content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_quest_stat(cards): # pylint: disable=R0912,R0915 """ Get quest statistics. """ res = {} encounter_sets = set() keywords = set() card_types = {} for card in cards: if card.get(lotr.CARD_KEYWORDS): keywords = keywords.union( lotr.extract_keywords(c...
33de1c65288a82c91dd3ee6f4e31c2ea54f938d8
221
def bind_type(python_value): """Return a Gibica type derived from a Python type.""" binding_table = {'bool': Bool, 'int': Int, 'float': Float} if python_value is None: return NoneType() python_type = type(python_value) gibica_type = binding_table.get(python_type.__name__) if gibica_t...
ff1ac8d907a90584694408b8e60996fb7be25eab
222
import traceback import requests def delete_server(hostname, instance_id): """ Deletes a server by hostname and instance_id. """ host = get_host_by_hostname(hostname) if not host or not instance_id: return None try: r = requests.delete("%s/servers/%i" % (host['uri'], instance_...
9456e45d49be61672b89427c93542374ff0359e2
223
def quote_ident(val): """ This method returns a new string replacing " with "", and adding a " at the start and end of the string. """ return '"' + val.replace('"', '""') + '"'
452058861fb5be138db3599755fbf3c6d715c0a8
224
def TFC_TDF(in_channels, num_layers, gr, kt, kf, f, bn_factor=16, bias=False): """ Wrapper Function: -> TDC_TIF in_channels: number of input channels num_layers: number of densely connected conv layers gr: growth rate kt: kernel size of the temporal axis. kf: kernel size of the freq. axis ...
b1d4aa007b40c920f4c985d102a4094821fbf228
225
import json def barplot_data(gene_values, gene_names, cluster_name, x_label, title=None): """ Converts data for top genes into a json for building the bar plot. Output should be formatted in a way that can be plugged into Plotly. Args: gene_values (list): list of tuples (gene_id, ...
67879df5d4918dddc8f46fd6fa975f3bf53de2b4
226
def logic_not(operand: ValueOrExpression) -> Expression: """ Constructs a logical negation expression. """ return Not(operators.NotOperator.NOT, ensure_expr(operand))
9b3755e00afc9aa8a843358ef83442614bda0feb
227
def webpage_attribute_getter(attr): """ Helper function for defining getters for web_page attributes, e.g. ``get_foo_enabled = webpage_attribute_getter("foo")`` returns a value of ``webpage.foo`` attribute. """ def _getter(self): return getattr(self.web_page, attr) return _getter
3626f8e2d8c6fb7fbb490dc72f796599cdbc874e
228
def diff_with_step(a:np.ndarray, step:int=1, **kwargs) -> np.ndarray: """ finished, checked, compute a[n+step] - a[n] for all valid n Parameters ---------- a: ndarray, the input data step: int, default 1, the step to compute the difference kwargs: dict, Returns ---...
8475ec66a983f32d4ed7c06348a8607d335dbdca
229
def rmse(y_true: np.ndarray, y_pred: np.ndarray): """ Returns the root mean squared error between y_true and y_pred. :param y_true: NumPy.ndarray with the ground truth values. :param y_pred: NumPy.ndarray with the ground predicted values. :return: root mean squared error (float). """ return...
42d08e8bfd218d1a9dc9702ca45417b6c502d4c5
230
def party_name_from_key(party_key): """returns the relevant party name""" relevant_parties = {0: 'Alternativet', 1: 'Dansk Folkeparti', 2: 'Det Konservative Folkeparti', 3: 'Enhedslisten - De Rød-Grønne', 4: 'Liberal...
86041235738017ae3dbd2a5042c5038c0a3ae786
231
def __imul__(self,n) : """Concatenate the bitstring to itself |n| times, bitreversed if n < 0""" if not isint(n) : raise TypeError("Can't multiply bitstring by non int"); if n <= 0 : if n : n = -n; l = self._l; for i in xrange(l//2) : self[i],self[l-1-i] = self[l-1-i],self[i]; ...
3305fd98899d0444aea91056712bae1fd4a6db2f
233
from pyrado.environments.pysim.quanser_qube import QQubeSim def create_uniform_masses_lengths_randomizer_qq(frac_halfspan: float): """ Get a uniform randomizer that applies to all masses and lengths of the Quanser Qube according to a fraction of their nominal parameter values :param frac_halfspan: fr...
87fc94d17b3fab77b175139d2329c0d67611d402
235
def compress_table(tbl, condition, blen=None, storage=None, create='table', **kwargs): """Return selected rows of a table.""" # setup storage = _util.get_storage(storage) names, columns = _util.check_table_like(tbl) blen = _util.get_blen_table(tbl, blen) _util.check_equal_len...
eb675913da51b48fc6a663ddb858e70abee3f1ce
236
def validate_schedule(): """Helper routine to report issues with the schedule""" all_items = prefetch_schedule_items() errors = [] for validator, _type, msg in SCHEDULE_ITEM_VALIDATORS: for item in validator(all_items): errors.append('%s: %s' % (msg, item)) all_slots = prefetch_...
8f6d0f9670b25c22e4518b53327dffc4fa897a6e
237
from typing import Any from typing import Dict from typing import Union from typing import Callable from typing import Tuple def train_gridsearchcv_model(base_model: Any, X: np.array, y: np.array, cv_splitter, ...
7fe8677f985db7d3518c7b68e5005fde1dee91c6
238
def set_resolmatrix(nspec,nwave): """ Generate a Resolution Matrix Args: nspec: int nwave: int Returns: Rdata: np.array """ sigma = np.linspace(2,10,nwave*nspec) ndiag = 21 xx = np.linspace(-ndiag/2.0, +ndiag/2.0, ndiag) Rdata = np.zeros( (nspec, len(xx), nwave)...
49aac12441c1ef793fa2ded4c5ac031df7ce8049
239
def assembleR(X, W, fct): """ """ M = W * fct(X) return M
c792da453b981cc3974e32aa353124f5a5e9c46d
240
import logging def generate_dictionary_variable_types( dict_name, key_name, search_dict, indent_level=0 ): """Generate a dictionary from config with values from either function, variable, or static""" out_str = [] # Don't escape these: types_used = ["None", "True", "False", None, True, False] ...
82a7282bc999dcf049ff6fbe6329271577908775
241
import uuid def make_uuid(value): """Converts a value into a python uuid object.""" if isinstance(value, uuid.UUID): return value return uuid.UUID(value)
b65b5739151d84bedd39bc994441d1daa33d1b51
242
def create_config(config_data, aliases=False, prefix=False, multiple_displays=False, look_info=None, custom_output_info=None, custom_lut_dir=None): """ Create the *OCIO* config based on the configuration ...
c036094b3a8a3debc80d2e66141f8b95e51a41d0
243
import re from pathlib import Path import json def parse_json_with_comments(pathlike): """ Parse a JSON file after removing any comments. Comments can use either ``//`` for single-line comments or or ``/* ... */`` for multi-line comments. The input filepath can be a string or ``pathlib.Path``. ...
e79a461c210879d66b699fe49e84d0d2c58a964b
244
def _unpack_available_edges(avail, weight=None, G=None): """Helper to separate avail into edges and corresponding weights""" if weight is None: weight = "weight" if isinstance(avail, dict): avail_uv = list(avail.keys()) avail_w = list(avail.values()) else: def _try_getit...
0c4ac0afc209544e385f9214f141cde6f75daa4a
245
import json def reddit_data(subreddit, time_request = -9999): """ @brief function to retrieve the metadata of a gutenberg book given its ID :param subreddit: the name of the subreddit :param time_request: unix timestamp of when requested subreddit was generated :return: a list of reddit objects wi...
78d79e2e917aaa892b4122d657c30a7cd13dfc4b
247
def write_velocity_files(U_25_RHS_str, U_50_RHS_str, U_100_RHS_str, U_125_RHS_str, U_150_RHS_str, U_25_LHS_str, U_50_LHS_str, U_100_LHS_str, U_125_LHS_str, U_150_LHS_str, path_0_100, path_0_125, path_0_150, path_0_25, path_0_50): """Create the details file for the surrounding cases, and write the velocities in line...
6c4af67ea659c09669f7294ec453db5e4e9fb9df
248
def datetime_to_bytes(value): """Return bytes representing UTC time in microseconds.""" return pack('>Q', int(value.timestamp() * 1e6))
e8b1d78615a84fb4279563d948ca807b0f0f7310
249
from typing import Sequence from typing import List def _f7(seq: Sequence) -> List: """order preserving de-duplicate sequence""" seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
f4dde886503754a09ac4ff545638750bf8fc6d94
250
def get_config(cfg): """ Sets the hypermeters for the optimizer and experiment using the config file Args: cfg: A YACS config object. """ config_params = { "train_params": { "adapt_lambda": cfg.SOLVER.AD_LAMBDA, "adapt_lr": cfg.SOLVER.AD_LR, "lamb...
a88bc3c8057d969998ab286aaa15ee5e8768c838
251
def get_nas_transforms(): """ Returns trajectory transformations for NAS. """ return [ PadActions(), AsArray(), RewardsAsValueTargets(), TileValueTargets() ]
f323ef2cd40af81fdd230e4bbb53cfa2ba6e4450
252
from datetime import datetime def epoch_to_datetime(epoch): """ :param epoch: str of epoch time :return: converted datetime type """ return datetime.datetime.fromtimestamp(float(epoch) / 1000)
59d9b85489320f5b1db93e6513fc375b9b58b151
253
def qe_m4(px,mlmax,Talm=None,fTalm=None): """ px is a pixelization object, initialized like this: px = pixelization(shape=shape,wcs=wcs) # for CAR px = pixelization(nside=nside) # for healpix output: curved sky multipole=4 estimator """ ells = np.arange(mlmax) #prepare temperature map ...
f2b6c7fe03a5dae34aaa58738684e37cf30efc01
254
def seasonality_plot_df(m, ds): """Prepare dataframe for plotting seasonal components. Parameters ---------- m: Prophet model. ds: List of dates for column ds. Returns ------- A dataframe with seasonal components on ds. """ df_dict = {'ds': ds, 'cap': 1., 'floor': 0.} for n...
ae362631659ec1652eb1798a73dce786cd269ee5
255
async def response(request: DiscoveryRequest, xds_type: DiscoveryTypes, host: str = 'none'): """ A Discovery **Request** typically looks something like: .. code-block:: json { "version_info": "0", "node": { "cluster": "T1", "build_version": "...
3ffa2ec8c64dd479ea6ecf3494a2db23b95f2ef2
256
def count_inner_bags(content, start_color): """Count inner bags""" rules = process_content(content) bags = rules[start_color] count = len(bags) while len(bags) != 0: new_bags = [] for bag in bags: count += len(rules[bag]) new_bags += rules[bag] bags =...
f6e188d548beaa5f1b24d96e6394c2bdbfaefd0b
257
def build_generation_data( egrid_facilities_to_include=None, generation_years=None ): """ Build a dataset of facility-level generation using EIA923. This function will apply filters for positive generation, generation efficiency within a given range, and a minimum percent of generation from the ...
32a2f1757419e52b7d8ea5b198a70bfd36f7dd4c
258
def get_nessus_scans(): """Return a paginated list of Nessus scan reports. **Example request**: .. sourcecode:: http GET /api/1.0/analysis/nessus?page=1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0...
1828d42baff7e16c8dac6b1e5ab6c66c14834c3c
259
from doctest import TestResults from _doctest26 import TestResults def count_failures(runner): """Count number of failures in a doctest runner. Code modeled after the summarize() method in doctest. """ try: except: return [TestResults(f, t) for f, t in runner._name2ft.values() if f > 0 ]
0e755114f5c23be0bdac11876f32bd2ac4ad9625
260
def fnv1_64(data, hval_init=FNV1_64_INIT): """ Returns the 64 bit FNV-1 hash value for the given data. """ return fnv(data, hval_init, FNV_64_PRIME, 2**64)
3981677c02317f63ae62cab75ee0d5db2fec7dc2
261
from pathlib import Path import tqdm def parse_data_sp(source_root, parallel_roots, glob_str="**/*.wav", add_source=False): """ assert that parallel_root wil contain folders of following structure: PARALLEL_ROOT/record_17/IPhone 12 Pro Max/JBL CLIP3/distance=60-loudness=15-recording_mode=default/RELATIVE_...
d23613c63d904ca5adb23c10c670ddab2d4148e7
263
def heat_diffusion(A, t, L, k, eps=0.0001): """ Computes the heat diffusion equation Parameters ---------- A : Tensor or SparseTensor the (N,N,) density matrix t : float the diffusion time L : Tensor or SparseTensor the (N,N,) Laplacian matrix k : Tensor ...
56ee07ed473463116b045700e4923218d72b5aca
264
def unpack_ad_info(ad_info: dict, param_name: str) -> bytes: """Проверяет наличие ожидаемой структуры и возвращает значение.""" # Красиво не сработает, потому что применение условий должно быть последовательным if ( isinstance(ad_info, dict) and ad_info.get(param_name) # noqa: W503 ...
85a6c95bac7e35bed4f478b352b2a56203818139
265
def _read_file(file, sheet_name=0): """ Helper function used to read the file and return a pandas dataframe. Checks if file type is a .csv or excel. If not, returns a ValueError. Parameters ---------- file : str the name of the file, including the filetype extension sheet_name : ...
fbe9212084062233ca2073af57b401afc9532701
266
def get_school_total_students(school_id, aug_school_info): """ Gets total number of students associated with a school. Args: district_id (str): NCES ID of target district (e.g. '0100005'). aug_school_info (pandas.DataFrame): Target augmented school information (as formatted by...
d0d2ea36a2e3f4b47992aea9cc0c18c5ba7e0ff3
267
def loci_adjust(ds, *, group, thresh, interp): """LOCI: Adjust on one block. Dataset variables: hist_thresh : Hist's equivalent thresh from ref sim : Data to adjust """ sth = u.broadcast(ds.hist_thresh, ds.sim, group=group, interp=interp) factor = u.broadcast(ds.af, ds.sim, group=group,...
2bb833a33bf32ed308137342007f7c62acfabe82
268
def _ClientThread(client_ip, client_user, client_pass, mvip, username, password, purge): """delete the volumes for a client, run as a thread""" log = GetLogger() SetThreadLogPrefix(client_ip) log.info("Connecting to client") client = SFClient(client_ip, client_user, client_pass) account_name = ...
258531ac383271c1a637b38ed3ff4f7a358c1dbc
269
import json def objective(args: Namespace, trial: optuna.trial._trial.Trial) -> float: """Objective function for optimization trials. Args: args (Namespace): Input arguments for each trial (see `config/args.json`) for argument names. trial (optuna.trial._trial.Trial): Optuna optimization trial...
629711996034664654430fba8af541fc934e143a
270
def read_gdwarfs(file=_GDWARFALLFILE,logg=False,ug=False,ri=False,sn=True, ebv=True,nocoords=False): """ NAME: read_gdwarfs PURPOSE: read the spectroscopic G dwarf sample INPUT: logg= if True, cut on logg, if number, cut on logg > the number (>4.2) ug= if Tru...
da073917d825dac283d8157dec771036588b0cec
271
def add_item(category_slug=None): """ Add a new Item Form. :param category_slug: The category slug """ # Get the current category using the slug current_category = Category.where('slug', category_slug).first() return render_template( 'items/add.html', categories=Category.a...
6bbaabdab6da6290c1de17ecbc36e849b7fd4c5e
272
def track_type(time, lat, tmax=1): """ Determines ascending and descending tracks. Defines unique tracks as segments with time breaks > tmax, and tests whether lat increases or decreases w/time. """ # Generate track segment tracks = np.zeros(lat.shape) # Set values ...
5872deaf6ff5d5e651705f40b8ad3df192ec98de
273
def get_installed_procnames(): """Get a list of procs currently on the file system.""" return set(get_procs())
6f3f83d579033ef407c72ccbd8d973f39d41ae22
274
def pam_bw_as_matrix(buff, border): """\ Returns the QR code as list of [0, 1] lists. :param io.BytesIO buff: Buffer to read the matrix from. :param int border: The QR code border """ res = [] data, size = _image_data(buff) for i, offset in enumerate(range(0, len(data), size)): ...
0360ee9d9e22fd667bc80063bd799fbaa2cb3a44
275
def delete_task(task_id: int): """Remove task with associated ID from the database.""" send_to_login = ensure_login() if send_to_login: return send_to_login else: old_task = Task.delete(task_id) flash(f'You deleted "{old_task.title}"', "info") return redirect(url_for("ta...
976c8aedc47ca342809d82904c4a1eab31e8886f
276
def get_version(): # noqa: E501 """API version The API version # noqa: E501 :rtype: str """ return '1.0.0'
75df6627bb2aaec205a0679d86c190d7b861baf5
278
import tqdm import torch def bert_evaluate(model, eval_dataloader, device): """Evaluation of trained checkpoint.""" model.to(device) model.eval() predictions = [] true_labels = [] data_iterator = tqdm(eval_dataloader, desc="Iteration") for step, batch in enumerate(data_iterator): i...
3534796f06a89378dec9c23788cb52f75d088423
279
def get_cached_scts(hex_ee_hash): """ get_cached_scts returns previously fetched valid SCT from this certificate. The key to perform this search is the hex-encoded hash of the end-entity certificate :param hex_ee_hash: the hex-encoded hash of the end-entity certificate :return: a dictionary of SCTs whe...
5f86f1ccd7488f9712b16d1c71077ceb73098ea3
280
import torch def all_gather_multigpu( output_tensor_lists, input_tensor_list, group=None, async_op=False ): """ Gathers tensors from the whole group in a list. Each tensor in ``tensor_list`` should reside on a separate GPU Only nccl backend is currently supported tensors should only be GPU te...
e948709a209877c0d994699106e06bd13ddb46a7
281
import uuid def get_uuid_from_str(input_id: str) -> str: """ Returns an uuid3 string representation generated from an input string. :param input_id: :return: uuid3 string representation """ return str(uuid.uuid3(uuid.NAMESPACE_DNS, input_id))
51ce9ceab7c4f9d63d45fbee93286711bcba3093
282
import requests def extend_request(request_id=None, workload_id=None, lifetime=30): """ extend an request's lifetime. :param request_id: The id of the request. :param workload_id: The workload_id of the request. :param lifetime: The life time as umber of days. """ return requests.extend_r...
4b5c523f1af2b1c7c6f55bf522bb2c32e0f14995
283
def from_bytes(buf: bytes) -> str: """Return MIME type from content in form of bytes-like type. Example: >>> import defity >>> defity.from_bytes(b'some-binary-content') 'image/png' """ _guard_buf_arg(buf) # We accept many input data types just for user's convenience. We still c...
5b997bc8d9b6d5e3fc7e38c5956bcefe3f0244cc
284
def pl__5__create_train_frame_sequences(ctvusts_by_tcp__lte_1, frame_sequences__by__tcpctvustsfs, train_tcpctvustsfs__gt__1): """ returns: train_tcpctvustsfs__all ( <TokenID>, <CameraPerspective>, <ASLConsultantID>, <TargetVideo...
1824b26a449a24ae02e72c1fe1fc6931c9658875
285
def createList(value, n): """ @param value: value to initialize the list @param n: list size to be created @return: size n list initialized to value """ return [value for i in range (n)]
ff419e6c816f9b916a156e21c68fd66b36de9cfb
286
def label_class_num(label): """ 标签的种类 :param label: :return: """ return label.shape[1]
d3b9f6e7b84c10af289878587d7f36bf18147b9e
287
def heur(puzzle, item_total_calc, total_calc): """ Heuristic template that provides the current and target position for each number and the total function. Parameters: puzzle - the puzzle item_total_calc - takes 4 parameters: current row, target row, current col, target col. Returns i...
bed67110858733a20b89bc1aacd6c5dc3ea04e13
288
def make_argparse_help_safe(s): """Make strings safe for argparse's help. Argparse supports %{} - templates. This is sometimes not needed. Make user supplied strings safe for this. """ return s.replace('%', '%%').replace('%%%', '%%')
3a1e6e072a8307df884e39b5b3a0218678d08462
289
def create_pysm_commands( mapfile, nside, bandcenter_ghz, bandwidth_ghz, beam_arcmin, coord, mpi_launch, mpi_procs, mpi_nodes, ): """ Return lines of shell code to generate the precomputed input sky map. """ mpistr = "{}".format(mpi_launch) if mpi_procs != "": ...
f0528968096f41a291a369477d8e2071f4b52339
292
def edits1(word): """ All edits that are one edit away from `word`. """ letters = 'abcdefghijklmnopqrstuvwxyz' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in spli...
ec78ba3648e04c59b380cd37760b7865e5f364ea
293
def process_text_cn(text: str): """中文文本处理""" text = del_white_chars(text) text = sub_punctuation(text) return text
18fd44ee2c5929fd6fe3c4aef9fde332773b016c
294
import math def total_elastic_cross_section_browning1994_cm2(atomic_number, energy_keV): """ From browning1994 Valid in the range 100 eV to 30 keV for elements 1 to 92. """ Z = atomic_number E = energy_keV factor = 3.0e-18 power_z = math.pow(Z, 1.7) power_e = math.pow(E, 0.5) n...
bf12a49e3aba07a44e44bfb6df87212745fd5ed3
295
def plot_fancy(nodes, elems, phi=None, charge=None, u=None, charge_max=None, show=False, save=None, num_intp=100, title=None, clabel=None, animation_mode=True, latex=False): """ Plots fancily. """ if animation_mode: fig = Figure(colorbar=False, tight_layout=True, show=show,...
a334c581b9601c73a1b003aec14f4f179dab5202
296
def buildModelGPT(modelType='gpt2-medium'): """ This function builds the model of the function und returns it based on GPT """ ## Create Model # Load pre-trained model tokenizer (vocabulary) tokenizer = GPT2Tokenizer.from_pretrained(modelType) # Load pre-trained model (weights) model = GPT2LMHeadMo...
51b2dca333a06ed9168d3056b681b1ed192c5761
297
def vid_to_list(filepath): """ Converts a video file to a list of 3d arrays of dim (h, w, c) Input: filepath: (str) full filepath of video Output: vid: (ndarray) list of 3d numpy arrays, of shape (height, width, color) """ cap = cv.VideoCapture(filepath) list_of_frames = ...
062423bcf10749705e767edf6721dd20903653ef
298
import pickle def from_pickle(fname=interpolator_path): """Loads grid inperpolator from pickle located at `fname`. """ with open(fname, "rb") as f: grid = pickle.load(f) return grid
5b4f2a94ba3024ea63a5859284f1b6877bac1623
299
import torch def get_prob_and_custom_prob_per_crops( logits_for_patches, img_size_work_px_space, n_pixels_in_crop, descendent_specifier, target_list, rf, DEVICE, ): """Determine the probability and the custom probability (i.e. the non-Deep-Learning "logit", cf. Appendix C.2) for crops ...
18a4c166334c6e5c3fa3300ddd255992677d412b
300
def xywh_to_xyxy(boxes): """Convert [x y w h] box format to [x1 y1 x2 y2] format.""" if boxes is None or len(boxes) == 0: return boxes boxes = np.array(boxes) return np.hstack((boxes[:, 0:2], boxes[:, 0:2] + boxes[:, 2:4] - 1))
391c55ddd2e84cf60073cbd02d0e5d595f3ea3b1
301
def vscat(a,fig=None,ls=None,marker='o',nmin=2,mhmin=-3,density=False,out=None) : """ Make histograms of VSCATTER for different bins of Teff H], given min NVISITS, and min [M/H] """ if fig == None : fig,ax=plots.multi(4,6,hspace=0.001,wspace=0.4,figsize=(12,8)) else : fig,ax=fig tbins=[3000,3500,400...
b302883263ef79682e697d4c82b0fc352eb597ec
302
def parse_unique_count_for_column(column_df, column): """ returns column specific distribution details. sample output, ``` "<column_df>": { "<>": 30 } ``` """ return {column: get_unique_counts_of_column(column_df)}
275375c012d8ffc2bd8f209bf57e1c1aa1d183f6
303
def transaction(): """ Get database transaction object :return: _TransactionContext object usage: with transaction(): # transactions operation pass >>> def update_profile(t_id, name, rollback): ... u = dict(id=t_id, name=name, email='%s@test.org' % name, password=name, ...
d0b941dd9c2ce3e07079280edc74324a28d60509
304
from typing import Union from typing import Dict from typing import Any import typing def _BoundedIntRange( description: str = "", description_tooltip: str = None, layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {}, max: int = 100, min: int = 0, style: Union[D...
0f54f750da5000df2952298b0f6bec987a7b02b4
305
def get_benchmark_snapshot(benchmark_df, threshold=_MIN_FRACTION_OF_ALIVE_TRIALS_AT_SNAPSHOT): """Finds the latest time where |threshold| fraction of the trials were still running. In most cases, this is the end of the experiment. However, if less than |threshold| fraction of the ...
6e7f887f3f720612013dfe06b5decbf2e092a2e2
307
import tqdm import timeit import warnings def get_results_seq_len(given_true_eig, hidden_dim, input_dim, min_seq_len, max_seq_len, num_sampled_seq_len, num_repeat, ...
6d7439b4b9c5bca6010eaffc4c924ef8f09fbb4f
310
import functools def episode_to_timestep_batch( episode: rlds.BatchedStep, return_horizon: int = 0, drop_return_horizon: bool = False, flatten_observations: bool = False, calculate_episode_return: bool = False) -> tf.data.Dataset: """Converts an episode into multi-timestep batches. Args: ...
105c528772257b990897d35e8f8b82663e26e57c
311
def parse(authz_file, modules): """Parse a Subversion authorization file. Return a dict of modules, each containing a dict of paths, each containing a dict mapping users to permissions. Only modules contained in `modules` are retained. """ parser = UnicodeConfigParser(ignorecase_option=False) ...
9102d77ed5db05c582a0ecbc3eb26a63fd579ce6
312
def send_expiry_note(invite, request, user_name): """ Send a notification email to the issuer of an invitation when a user attempts to accept an expired invitation. :param invite: ProjectInvite object :param request: HTTP request :param user_name: User name of invited user :return: Amount o...
62602f670724630ff5aeb99ab28b7dfb18fc5233
313
def level_is_between(level, min_level_value, max_level_value): """Returns True if level is between the specified min or max, inclusive.""" level_value = get_level_value(level) if level_value is None: # unknown level value return False return level_value >= min_level_value and level_value...
b0bc1c4ea749d51af147bc1237aac5a5d1e5ba1b
314
def voronoiMatrix(sz=512,percent=0.1,num_classes=27): """ Create voronoi polygons. Parameters ---------- sz : int row and column size of the space in which the circle is placed percent : float Percent of the space to place down centers of the voronoi polygons. Smaller percent makes the polygons larger ...
c4dfb74ae5b9e26494cb8642eb96dca565d6497d
315
from typing import Counter def genVBOF2(virus_record, model, model_name=None): """New version of the genVBOF function by Hadrien. Builds a Virus Biomass Objective Function (basically a virus biomass production reaction, from aminoacids and nucleotides) from a genbank file. Params: - virus...
98f0aafae9efa65d18b65e23eb9d7c0457641bb0
316
import time def get_current_ms_time() -> int: """ :return: the current time in milliseconds """ return int(time.time() * 1000)
3c037bffb486ebae3ffcfba5fe431bd9b69b3bda
318
def get_service_info(): # noqa: E501 """Get information about Workflow Execution Service. May include information related (but not limited to) the workflow descriptor formats, versions supported, the WES API versions supported, and information about general service availability. # noqa: E501 :rtype: Ser...
693d7c47a235dc96f9c44d993fba25607994f2e3
319
def str_of_tuple(d, str_format): """Convert tuple to str. It's just str_format.format(*d). Why even write such a function? (1) To have a consistent interface for key conversions (2) We want a KeyValidationError to occur here Args: d: tuple if params to str_format str_format: Auto fie...
b5612efb3b189754cb278f40c7f471284dfc1daa
320
def _intersect(bboxes1, bboxes2): """ bboxes: t x n x 4 """ assert bboxes1.shape[0] == bboxes2.shape[0] t = bboxes1.shape[0] inters = np.zeros((bboxes1.shape[1], bboxes2.shape[1]), dtype=np.float32) _min = np.empty((bboxes1.shape[1], bboxes2.shape[1]), dtype=np.float32) _max = np.empty((...
91056250d3adf829d1815a016a75423f93adb6c1
321
def convert_x_to_bbox(x,score=None): """ Takes a bounding box in the centre form [x,y,s,r] and returns it in the form [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right """ w = np.sqrt(np.abs(x[2] * x[3])) if(w<=0): w=1 h = x[2] / w if(score==None): return np.array([...
f49a6b7c306087d92e99acb5bd679c59308f81b3
322
from typing import Tuple def decimal_to_boolean_list(num: int, padding: int = 0) -> Tuple[bool, ...]: """ Convert a decimal number into a tuple of booleans, representing its binary value. """ # Convert the decimal into binary binary = bin(num).replace('0b', '').zfill(padding) # Return a tuple...
c13831214faece847960089f781cc1c6442205ec
323
def get_credentials(fn, url, username, allowed): """Call fn and return the credentials object""" url_str = maybe_string(url) username_str = maybe_string(username) creds = fn(url_str, username_str, allowed) credential_type = getattr(creds, 'credential_type', None) credential_tuple = getattr(cr...
931d01d2c8ea44e1f8522f5dedb14a66367f3d4f
324
def tpack(text, width=100): """Pack a list of words into lines, so long as each line (including intervening spaces) is no longer than _width_""" lines = [text[0]] for word in text[1:]: if len(lines[-1]) + 1 + len(word) <= width: lines[-1] += (' ' + word) else: lin...
e1b1b54a528c8dc2142a750156d3db1f754b4268
325
import torch def _log_evidence_func(arr): """Returns an estimate of the log evidence from a set of log importance wegiths in arr. arr has shape TxN where T is the number of trials and N is the number of samples for estimation. Args: arr (torch.FloatTensor of shape TxN): log importance weights...
6fd0f7a3e6ad677300a1c2d342082417d6c1a2c8
326
import struct def parse_bgp_attr(atype, aval_buf): """Given a type and value buffer, parses a BGP attribute and returns the value parsed""" if atype == BGP_ATYPE_ORIGIN: attr = 'ORIGIN' if len(aval_buf) != 1: return None, None, -1 aval = struct.unpack('B', aval_buf)[0] ...
337ee8d0178759afead4ef1c55653639ed901fac
328
def getUsage(): """ Get usage information about running APBS via Python Returns (usage) usage: Text about running APBS via Python """ usage = "\n\n\ ----------------------------------------------------------------------\n\ This driver program calculates electrostatic potentials,...
c21950b52106400cb20dd9d30a5cf742e98f9da9
330
def run_length_div_decode(x, n, divisor): """Decodes a run length encoded array and scales/converts integer values to float Parameters ---------- x : encoded array of integers (value, repeat pairs) n : number of element in decoded array """ y = np.empty(n, dtype=np.float32) start = 0 ...
434edfb44d1225277526233989ece2c91be14b0c
331
def modelFnBuilder(config): """Returns 'model_fn' closure for Estimator.""" def model_fn(features, labels, mode, params): print('*** Features ***') for name in sorted(features.keys()): tf.logging.info(' name = {}, shape = {}'.format(name, features[name].shape)) is_training = (mode == tf.estimator....
ea39f0ed099ec9455667ec79df0f91fdda425783
333
from notifications.utils import notify_people, unotify_people def accreds_validate(request, pk): """Validate an accred""" accreds = [get_object_or_404(Accreditation, pk=pk_, end_date=None) for pk_ in filter(lambda x: x, pk.split(','))] multi_obj = len(accreds) > 1 for accred in accreds: if ...
9f539b4dacfc8bc4e824af9bff2acc4aad552c6c
334