content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _get_state(self): """Get dictionary of dataclass fiels.""" return _dc.asdict(self)
f4c26ea75ba19988d649b62a12fbde29d7c7361e
45,952
def twilightFunc(xdata, *args, amCut=1.0): """ xdata: numpy array with columns 'alt', 'az', 'sunAlt' all in radians. az should be relative to the sun (i.e., sun is at az zero. based on what I've seen, here's my guess for how to fit the twilight: args[0] = ratio of (zenith twilight flux at sunAlt = ...
6a0b8f738cc6e21f0da0c88b40e2d6af4788518b
45,953
def matrix_constant_mult(m, c): """ Multiply components of matrix m by constant c """ return [mult(row_m, c) for row_m in m]
e6beb4400e1d99edb1193a3fe53fc17891182e51
45,954
def rasterize_geom(geom, affine, shape): """ Rasterize geometry to a matching affine and shape. """ geoms = [(geom, 1)] rv_array = features.rasterize( geoms, out_shape=shape, transform=affine, fill=0, dtype='uint8' ) return rv_array.astype(bool)
3032955cda29ff1801abbe5ff28be951460334c3
45,955
def top_usernames_used(): """ Get top usernames used according to module Returns: JSON/Dict of top usernames used """ module_name = get_value_from_request("module_name") module_query = [ group_by_ip_dest_and_username, { "$skip": fix_skip( get_...
8405def2c6875e282094d4270bf4c7503f6ffcc1
45,956
def robust_match_fundamental(p1, p2, matches, config): """Filter matches by estimating the Fundamental matrix via RANSAC.""" if len(matches) < 8: return np.array([]) p1 = p1[matches[:, 0]][:, :2].copy() p2 = p2[matches[:, 1]][:, :2].copy() FM_RANSAC = cv2.FM_RANSAC if context.OPENCV3 else ...
2f1a267b2b845415d18b8944ccc23c8286533e28
45,957
from numpy import array,arange def beam_position(images): """Returns first moment of beam position (X1,Y1) in units of pixels relative to the center pixel in images. The mask is assumed to be 7x7.""" height,width = images[0].shape N_bkg = background_mask().sum() X0 = int((width-1)/2) Y0 = int(...
469784d8091563acc1039408e7770530a412ca5d
45,958
import tqdm def median_freq_balancing(dataloader, num_classes): """Computes class weights using median frequency balancing as described in https://arxiv.org/abs/1411.4734: w_class = median_freq / freq_class, where freq_class is the number of pixels of a given class divided by the total number of pixel...
c2a5a6625d78893cb1357aa0e364936f4c77c791
45,959
def filter(params: LDS, x_hist: chex.Array, jump_size: chex.Array, dt: chex.Array): """ Compute the online version of the Kalman-Filter, i.e, the one-step-ahead prediction for the hidden state or the time update step Parameters ---------- x_hist: array(times...
097f34894c7b35f86893556940e26482b4baf868
45,960
def poly_trace(m, a): """Compute the coefficients of the trace polynomial of (a*x) mod m.""" out = [0, a] for i in range(FIELD_BITS - 1): out = poly_sqr(out) while len(out) < 2: out += [0] out[1] = a poly_divmod(m, out) return out
37f9410a25baefe2cdc45c2b0854e126170509b9
45,961
def totalStatistics(totalData, saveLoc): """Plots the error in a combined box plot Input arguments: totalData = error data which is to be analysed saveLoc = where to save the image """ mean = np.zeros([10,36]) std = np.zeros([10,36]) index = 0 for _, dataSet in enumerate(totalDat...
08dfa2aa4aab4070176ce3c02b9e76fe5b7f07f9
45,962
def convert_examples_to_features(examples, tokenizer, max_seq_length, is_training): """Loads a data file into a list of `InputBatch`s.""" # RACE is a multiple choice task. To perform this task using Bert, # we will use the formatting proposed in "Improving Language # Un...
83ed688237cfdea776ba6d1898345900eb04b876
45,963
def binRV(time, rv, err=None, stat='wmean', tstat='wmean', estat='addquad', binning_indices=False, n_consecutive=None, consecutive_step=None, seed=None): """ Bin a dataset of radial-velocity observations. Parameters ---------- time : array The array of times where the radial...
de3fd853de5709dafd065ab1de3cb85933ce47ec
45,964
def get_secret(secret_id): """ Get a Secret from Secrets Manager. """ return secrets_client.get_secret_value(SecretId=secret_id)["SecretString"]
80a18b37e7e8245e17c583728fd0df815e581db6
45,965
def generate_mutation_tracker(old_attributes, new_attributes): """ Given old attributes of an entity and the new attributes in a Properties object, this method creates a new dictionary based on the whole old attributes dictionary, with: - the attributes in old_attributes updated with the attributes in ...
f9a7545c9c55ef0afcfbc99df139a3679548c7e5
45,966
from typing import Tuple import transformers import torch def build_model(model_name: str) -> Tuple[transformers.FeatureExtractionMixin, torch.nn.Module]: """ Builds the model given its name Args: model_name (str): The name of the ViT Returns: Tuple[transformers.FeatureExtractionMixi...
f9d17b614c5b8c24e5cb7f99bea15d214fc162f4
45,967
def verify_chassis_pic_exists_under_mic(device, mic, fpc, invert=False, max_time=60, check_interval=10): """ Verif...
574d75a58fffa1517d7d6067b73e0906038292b9
45,968
def selection_sort(lst): """This function will do a sort on a string of input.""" for i in range(len(lst)): if len(lst) == 0: return False min_position = i for j in range(i+1, len(lst)): if lst[min_position] > lst[j]: min_position = j temp...
7e963a4b6a1e04c07ecf8af34ca9c425e831629b
45,969
def transform(transformation_matrix, points): """ Does homographic transformation to points using given transformation matrix. See http://www.corrmap.com/features/homography_transformation.php https://wp.optics.arizona.edu/visualopticslab/wp-content/uploads/sites/52/2016/08/Lectures6_7.pdf """...
69c72c1a1df893274236221e3bfcc25ff63fda91
45,970
def TextureAddMemoryHints(builder, memoryHints): """This method is deprecated. Please switch to AddMemoryHints.""" return AddMemoryHints(builder, memoryHints)
71903073b3be48ca64158d0f2aa1c0ffb55dd049
45,972
def S_outlier_filter(_data_list, _factor=4): """ Returns data samples where data samples significantly greater than median are discarded. """ n_data = [] ds = len(_data_list) p_d = S_translate_to_positive_axis_values(_data_list) m_d = mining.S_median_sample_values(p_d) b_v = m_d[1] ...
5804f72e901007f2dd8fbe90a5a01066c7d37995
45,973
def get_default_palette(): """ Return the default color palette, which slightly tweaks the Digital Standards for better flexibility on light/dark backgrounds. """ palette = {} # the standard set of colors palette["blue"] = "#2176d2" palette["green"] = "#58c04d" palette["yellow...
2eb1239ad9fde6185b47732f3f2540a19ae54770
45,974
from pydft.poisson import _Bj_dag_operator, _O_operator, _Bj_operator, _generate_r, _find_dr def _Vdual(s,R,V = None): """Finds the dual of the potential matrix. Args: s (list of int): The number of samples points along each basis vector. R (numpy.ndarray): The basis vectors fo...
42add3b413672d9019c7b68bcf864d5b4bfa7fa8
45,976
def iv(): """ The initialization vector to use for encryption or decryption. It is ignored for MODE_ECB and MODE_CTR. """ return chr(0) * 16
f38999b898427f5c6df124acd727744652d5db75
45,977
def build_inputs(data_params, input_context=None): """Returns tf.data.Dataset for sentence_prediction task.""" return data_loader_factory.get_data_loader(data_params).load(input_context)
5f7fee282dbee8ba5abb8bcee1de209793e9c468
45,978
def support_index(): """ Renders a page with the details on how to get support for the Wikimetrics project. """ return render_template('support.html')
c5a79dc6079056fa6613e56b1f049b735baac754
45,979
import functools def peak_count_hist(dat, bins=20, lim=None, neighborhood_size=5, threshold=0, log=True, mean=True): """Make the histogram of the peak count of data. Arguments --------- dat : input data (numpy array, first dimension for the sample) bins : number of bins for the histogram (defaul...
e45b33a41975d4abe99829e6db9c09865552e762
45,980
def url(value, allow_empty = False, allow_special_ips = False, **kwargs): """Validate that ``value`` is a valid URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/ht...
9f7f0d7f828a393a3e5254ba023de0a6eb9f0d14
45,981
def get_indent(text): """Get text indentation. Args: text: Text to analyze. Returns: Number of leftmost spaces. Notes: Input text must be tab expanded, otherwise indent will be incorrect. """ return len(text) - len(text.lstrip())
5d5d53417f35f84bf48aa66fa8f35cf1930e77b7
45,982
from typing import Any import ray def ray_get_if_needed(obj: Any) -> Any: """If obj is an ObjectRef, do ray.get, otherwise return obj""" if isinstance(obj, ray.ObjectRef): return ray.get(obj) return obj
8f96360a46cf4269218ff52ab686b47915b092d4
45,983
def get_mark(name, task): """Getting marks of students for certain student and task""" return int(input('Mark for {}, task {} > '.format(name, task)))
00d8a0bf1ab97f600a3e6d2c8f488563419a95e1
45,984
def svn_opt_args_to_target_array3(*args): """ svn_opt_args_to_target_array3(apr_array_header_t targets_p, apr_getopt_t os, apr_array_header_t known_targets, apr_pool_t pool) -> svn_error_t """ return apply(_core.svn_opt_args_to_target_array3, args)
4cc49952b047e03bfd381cc2e0a79f7aa193b31f
45,985
def is_unary(s: str) -> bool: """Checks if the given string is a unary operator. Parameters: s: string to check. Returns: ``True`` if the given string is a unary operator, ``False`` otherwise. """ return s == '~'
1e04439c9b94032fe1291bccd41c4a845c0c18c8
45,986
def prior_current_next(iterable, pad=None): """" s -> (pad, s0, s1), (s0,s1,s2), ..., (sN-1, sN, pad). Aka 'prior, current, and next' elements in an iteration all at once. Lets you visit each element in an iterable while also being presented with the prior and next element...
e3d74ff4661802e5fe6804df12085ec43fd47b72
45,987
import unittest def test_suite(): """Test suite including all test suites""" testSuite = unittest.TestSuite() testSuite.addTest(test_listtools("test_unique")) testSuite.addTest(test_listtools("test_sort")) return testSuite
e75092af531885eb550b7fcc4fb07b25562c3878
45,988
def create_db_session(*, engine: Engine) -> scoped_session: """Broadly speaking, the Session establishes all conversations with the database. It represents a “holding zone” for all the objects which you’ve loaded or associated with it during its lifespan. """ return scoped_session( sessio...
004c896a2b75740e74f391c536cae0c839295cde
45,989
def select_locale(): """ Selects the locale. Babel uses this to determine which language to go with. """ try: if opt['VERBOSE']: print(session['LANG']) return session['LANG'] except Exception, ex: return opt['LANG']
0547d690acefb7b401e8deb94619645c39031875
45,991
def _format_line(k, v): """ Format a readable line. """ return "0x%08x: %20s --> %s\n" % (v.start, str(k), str(v))
46f77e43a695933b89987e854cd6c6d91d05c1db
45,992
import pymf # noqa def pick_device_id() -> int: """Tries to use a library to list video devices""" try: except ImportError: return 0 device_list = pymf.get_MF_devices() if not device_list: raise RuntimeError('No video devices found...') elif len(device_list) == 1: ret...
1b04259f94da00ae9d80bf203264d87f953c70f5
45,993
from datetime import datetime def feature_extraction(activity, location, word2vec_file): """feature extraction function giving word embedding, demographics, case no., weather and social dist. levels""" # initiate placeholder and progress bar bar = st.progress(0) placeholder = st.empty() # get...
7ac749fb0335b14a58cc9b1e1ca38d4fda66be35
45,994
def get_sample_sheet_text(p7_index_length, p5_index_length): """ Gets the sample sheet text that will demux cells into one set of files """ sample_sheet_template = """[DATA] Lane,Sample_ID,Sample_Name,index,index2 %s""" line = ',fake,fake,%s,%s' % ('N' * p7_index_length, 'N' * p5_index_length) ...
6b9c04b7d353bfdf2067213ce197152fdf92f90b
45,996
def truncate_money(money: Money) -> Money: """Truncates money amount to the number of decimals corresponding to the currency""" amount = truncate_to(money.amount, money.currency) return Money(amount, money.currency)
dcbb4b239e491d84796f781d52335a476bc2ebab
45,997
def elephantblog_patterns(list_kwargs={}, detail_kwargs={}): """ Returns an instance of ready-to-use URL patterns for the blog. In the future, we will have a few configuration parameters here: - A parameter to specify a custom mixin for all view classes (or for list / detail view classes?) -...
e989871b7696096bd80118619da5a129fb18040e
45,998
def get_average_precisions(gt: list, predictions: list, class_names: list, iou_thresholds: list) -> np.array: """Returns an array with an average precision per class. Args: gt: list of dictionaries in the format described below. predictions: list of dictionaries in the format described below. ...
e04e04cb5214219a5fdb341a4577036241b8b241
46,000
import random def make_stan_person(num1, num2): """字段列表 "busi_reg_no":"客户号", "ctnm":"客户名称", "cten":"拼音/英文名称", "client_tp":"客户类别",1客户,2商户 "account_tp":"账户分类",1/2/3代表1、2、3类账号 "busi_type":"业务类型", "smid":"主体特约商户编号", "citp":"证件类型", "citp_ori":"证件类型原值", "citp_nt":"证件类型说明", "c...
c8d30542b75de2f499cf664319eb5fc0fb0d2fec
46,001
def zeros(shape, dtype=None, name=None): """ The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0. Args: shape(tuple|list|Tensor): Shape of the Tensor to be created, the data type of ``shape`` is int32 or int64. dtype(np.dtype|str, optional): Data type o...
d76ee2f286054459438b75136ab5404dbb26becb
46,002
import numpy def scroll_array(array: numpy.ndarray, dx: int=0, dy: int=0) -> numpy.ndarray: """ Scroll pixels inside a 3d array (RGB values) Use dy to scroll up or down (move the image of dy pixels) :param dx: int, Use dx for scrolling right or left (move the image of dx pixels) :param dy: int, ...
ac05c552af73a2a655938c7bfadbb5f6225b88f4
46,003
import pathlib def available_datasets(dataset_path=None, keys_only=True): """Get a list of available datasets. Parameters ---------- dataset_path: path location of saved dataset files """ if dataset_path is None: dataset_path = processed_data_path else: dataset_pat...
2aaf4b578ea992e1d43113c67f5f097d0f62abba
46,004
def get_user_by_username(username): """ Get user by username helper :param username: :return: user query object """ user = User.query.filter_by(username=username).first() return user
50816187b85bde183fdf6d3dfe4cb28d5fafebf3
46,005
def pproc_Kirchhoff_2d(size, shape: nparray, points: nparray, solution: nparray, D: nparray, S: nparray, loads: nparray): """ JIT-compiled function that calculates post-processing quantities at selected ponts for multiple left- and right-hand sides. ...
b5e40e229b9cefaad7f0fc9ca166946acde164b2
46,006
def make_interrupt(name, irq, description): """make an interrupt""" i = interrupt() i.name = name i.irq = irq i.description = description return i
b81580f4426da5b68ee69a532cddfa18fd2d99b5
46,007
def stacked_bar(tag, title, datalist): """ data list should be a list of dictionary formatted as follows {"name": "A" "data": { "R1_mapped": 50, "R2_mapped": 50, "R1_unmapped": 50, "R2_unmapped": 50, } } """ dataitems = "" for item in datalist: ...
2d19d8b15e10d54690f69940aa5cdedff317af00
46,008
async def restart(hub, ctx, name, resource_group, **kwargs): """ .. versionadded:: 1.0.0 Restart a virtual machine. :param name: The name of the virtual machine to restart. :param resource_group: The resource group name assigned to the virtual machine. CLI Example: .. code-block...
4296e109471c2d376b9a571f1dc9749a9f4b8699
46,010
def mk_models_NO1(activation, mid_units, dropout_rate,dropout_rate_2,X_train,LEARNING_RATE): """ RGB画像を対象に分類を行います 入力サイズは基本(image_num,64,64,3) 畳み込みは2回 """ filter_num=get_filter_num() labels=get_labels() model = Sequential() model.add(Conv2D(32, (3, 3), padding='same',input_shap...
c7d958de69a74319d820495cdd25065cf00c6fd3
46,011
def cli(ctx, workflow_id, label): """Get a list of workflow input IDs that match the given label. If no input matches the given label, an empty list is returned. Output: list of workflow inputs matching the label query """ return ctx.gi.workflows.get_workflow_inputs(workflow_id, label)
266434ed4cf55c822cb231114d20f0388f70b879
46,012
def cvCalcAffineFlowPyrLK(*args): """ cvCalcAffineFlowPyrLK(CvArr prev, CvArr curr, CvArr prev_pyr, CvArr curr_pyr, CvPoint2D32f prev_features, CvPoint2D32f curr_features, float matrices, int count, CvSize win_size, int level, char status, float track_error, CvTermCriteria crit...
c3ea0716a12e993fee2a63219989f3abf9b2197e
46,013
from typing import Optional def build_sgpr( data: Dataset, search_space: SearchSpace, kernel_priors: bool = True, likelihood_variance: Optional[float] = None, trainable_likelihood: bool = False, num_inducing_points: Optional[int] = None, trainable_inducing_points: bool = False, ) -> SGPR: ...
709abf48da0bf2c4df8e6f7d3db76912477f06bf
46,015
def cb_config(data, option, value): """Script option changed, update our copy.""" option_name = option.split(".")[-1] if option_name in vimode_settings: vimode_settings[option_name] = value if option_name == 'user_mappings': load_user_mappings() if "_color" in option_name: lo...
64cee35e2dbe8cab3017e658ed21ac77bd078d98
46,016
def phasedivergent(repo, subset, x): """Mutable changesets marked as successors of public changesets. Only non-public and non-obsolete changesets can be `phasedivergent`. (EXPERIMENTAL) """ # i18n: "phasedivergent" is a keyword getargs(x, 0, 0, _(b"phasedivergent takes no arguments")) phase...
b7d9c00160bfe06d50d5e46903f6d0af46d0768e
46,017
def find_on_screen(file): """ :param file: image :return: the x and y coordinate and width and height dimensions of the image on the screen """ return gui.locateOnScreen(file)
9111e66abd4986ed7540dd9e6541c4220db81393
46,018
from pyNastran.op2.dev.op4 import OP4 def proccess_drm1_drm2(op2file, op4file=None, dosort=True): """ Process op2/op4 file2 output from DRM1/DRM2 DMAPs to form data recovery matrices. Parameters ---------- op2file : string Either the basename of the .op2 and .op4 files, or the full ...
03721bfb60ec1893071e1bc8530ed033eb0d6d59
46,020
def ugrnn_transform(state: tf.Tensor, inputs: tf.Tensor, W_gates: tf.Tensor, b_gates: tf.Tensor): """ Performs a standard UGRNN transformation. """ # Compute the linear transformation for the gates stacked = tf.concat([inputs, state], axis=...
a0957ea7f183143d9f80c6043e892fe6157df835
46,021
def f(xx, uu, uref, t, p): """ Right hand side of the vectorfield defining the system dynamics :param xx: state :param uu: input :param uuref: reference input (not used) :param t: time (not used) :param pp: additionial free parameters (not used) :return: ...
e348be5a4f687e3aae1502b94d7810956b818747
46,022
def overview_data(vv, state = None,p = 0.25): """ Fetches, filters, and cleans Voteview NOMINATE data and returns as JSON string Args - p: sample proportion """ if state != None: p = 1.0 vv = filter_state(vv, state) vv = filter_cols(vv,COLS) vv = add_part...
3ff21acbdfe87fb013c303238dbfbea34f52c2d8
46,023
def return_prediction(model, sample): """Return a prediction for heart classification Arguments: model {model.h5} -- Pre-trained model to predict the heart classification sample {array} -- Sample of the ECG reading of dimension (1,186,1) Returns: string -- Returns the predictions ...
6e0e5885a32781fff3917f7cd1b1eb6a0e228cf5
46,024
import importlib import pkgutil def import_submodules(package, recursive=True): """ Import all submodules of a module, recursively, including subpackages :param package: package (name or actual module) :type package: str | module :rtype: dict[str, types.ModuleType] """ if isinstance(packa...
edd0ccfc16f1c3b73da765d2e530607e6f08ef19
46,025
def shownamespaces(context, mapping): """Dict of lists. Names attached to this changeset per namespace.""" repo = context.resource(mapping, b'repo') ctx = context.resource(mapping, b'ctx') namespaces = util.sortdict() def makensmapfn(ns): # 'name' for iterating over namespaces, templat...
e1364824d80acd4a1e4efeaa0ceabd7bac4c2525
46,027
def GetFlagValue(index): """Returns the flag value for the given index value (0...n-1).""" return bundle_firmware.gbb_flag_properties.values()[index]
60819cb01ebd03009052ec322515cc6010c6e62e
46,028
def get_translation(nmt_outputs, sent_id, tgt_eos, subword_option): """Given batch decoding outputs, select a sentence and turn to text.""" if tgt_eos: tgt_eos = tgt_eos.encode("utf-8") # Select a sentence output = nmt_outputs[sent_id, :].tolist() # If there is an eos symbol in outputs, cut them at that poin...
355a7f52489154a59d89aec50a8f61118d478797
46,029
def lstmcell_grad_h(input, hx, cx, w_ih, w_hh, b_ih, b_hh, dh, dc, target="cce"): """ Computes dh w.r.t. dw, db, dcx, dhx, dx. Args: input: akg.tvm.Tensor of type float16, float32. hx: akg.tvm.Tensor for hidden variable from previous cell. cx: akg.tvm.Tensor for state variable...
b45d0c57961db28e7de41d9c1830b3306e860fc3
46,030
def get_mod_whitelist(): """Return dict of modifications that are relevant for the data.""" mod_whitelist = {} for members in antibody_map.values(): for gene_name, phos_sites in members.items(): for residue, position in phos_sites: if gene_name not in mod_whitelist: ...
ae0ca3d7b04d3c5c5de07eed4b185556a92e1763
46,031
def urldecode(str): """ >>> print(urldecode("%E4%BD%A0%E5%A5%BD")) 你好 """ return unquote(str)
57d37690f4f12c2ca6ffd390de5e91b72d269897
46,032
def distance_uv(uv1, uv2): """ [cmds] UV 2 点間の距離を返す Args: p1 (list[float, float]): cmds の UV コンポーネント文字列 p2 (list[float, float]): cmds の UV コンポーネント文字列 Returns: float: 二次元座標の距離 """ uvCoord1 = cmds.polyEditUV(uv1, query=True) uvCoord2 = cmds.polyEditUV(uv2, query=True) ...
84c48ca8af1137b749bb9d224a8ab928afa4705f
46,033
from typing import Union from typing import Optional from typing import Dict from typing import Any from typing import List from typing import Tuple def apply(log: Union[EventLog, pd.DataFrame], parameters: Optional[Dict[Any, Any]] = None) -> List[ Tuple[Tuple[str, str], int, Dict[str, Any]]]: """ Provide...
91c4297bb07f0bdd40a3f998746d625d8ef1a5d3
46,034
def check_trading_day(df_indices, date): """ The function return the next trading day. Parameters: df_indices: List of trading days in the whole dataset date: The prediction day Returns: date: The next trading day """ while (True): if (date in df_indices): ...
d411bad3540c2a5501ee4f7028b2afc6969c69e0
46,035
import random import fractions def coPrime(x): """ Finds a random co-prime of given number """ n = x * 2 + 100000 # Upper limit for range of random integers y = random.randint(x * 2, n) if (fractions.gcd(x, y) != 1): return coPrime(x) else: return y
336a49b7fcb4d9659b404d09618fae783f14212c
46,036
def create_task_id(prefix): """ Create random task-id """ return "{prefix}-{id}".format(prefix=prefix, id=random_hex(6))
6dae23e5056351ba38f2b3c90b3f38329b05e6f7
46,037
def feh_calc(theta, V, EW, power): """Calculate the metallicity for a given magnitude and EW.""" a, b, c, d, e = theta # Wdash = reduced_ew(theta, V, EW) FeH = a + b*V + c*EW + d*EW**power + e*V*EW # FeH = d + f*np.power(Wdash, 1) + g*np.power(Wdash, 2) return FeH
9591aa54d077579c3d7c625615c2beb7758b4402
46,038
def metadata_parser(f): """ Parses a metadata file into dictionary. The metadata file is expected to have the following format: id;name;dtype where: - id denotes packet id (unsigned char or 1 byte uint) - name is the data channel name (str) - dtype is expected datatype (str) :param f: A file object with th...
91ccec2a0231f35e0693173e67bfda5498f941f5
46,039
import logging def _GetValueAndSource(sim, control, name, sources): """Returns value of specified telemetry 'name' and 'source'. Arguments: sim: Simulator telemetry dictionary. control: Controller telemetry dictionary. name: [string] Telemetry variable e.g. 'airspeed' or 'alpha'. sources: [list o...
6f7beb63bdd45d937584dc07e02452a53af94750
46,040
def _clean_sub_graphs(G_, min_length=80, max_nodes_to_skip=100, weight='length', verbose=True, super_verbose=False): """ Remove subgraphs with a max path length less than min_length, if the subgraph has more than max_noxes_to_skip, don't check length (this ...
6915596934cf20598cf424a49f400be974ce5e0d
46,041
def transform(*args): """ Transform XML document(s) using XSLT. `*args` contain string commands and/or options in the following format: [<options>] <xsl-file> {-p|-s <name>=<value>} [<xml-file>...] where <xsl-file> - main XSLT stylesheet for transformation <xml-file> - input...
c438746302fab6c7f997624fec0656c3605fe521
46,042
from typing import Union from typing import Mapping import hmac import hashlib def decode(secret: Union[str, bytes], token: Union[str, bytes]) -> Mapping: """Decode JWT.""" if isinstance(secret, str): secret = secret.encode() if isinstance(token, str): token = token.encode() try: ...
e8e1da5f797855b95b3ed3ed1d8cd3de376b134a
46,043
def bencode(data, f=None): """ Writes a serializable data piece to f The order of tests is nonarbitrary, as strings and mappings are iterable. If f is None, it writes to a byte buffer and returns a bytestring """ if f is None: f = BytesIO() _bencode_to_file(data, f) return f.getvalue() else: _bencode...
42edad06af3aba85752a1b2edd569f1349fd3ac0
46,044
def Mean0(a): """ Replacing np.mean(a, axis = 0) for 2D arrays Parameters ---------- a : 2D numpy array, floats Returns ------- average : 1D numpy array, floats Averages over the columns of a. """ average = np.zeros(a.shape[1]) for col in range(a.shape[1]): ...
7a3b1620a8dc481613d655a5716e11fac5954c69
46,045
import zipfile import time def download_burst(): """Returns an html table with the burst retrieved from the DB. """ images_path = "server/data/bursts" burst_id = int(request.args.get('burstId')) burst_format = request.args.get('format') burst = DB.get_burst(burst_id) files = int(burst['dur...
9a9c41c08083f725d5c80efff2a2a304248f806e
46,046
async def delete_order(request: web.Request, order_id) -> web.Response: """Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors :param order_id: ID of the order that needs to be deleted :type order_id: str ...
e77b8197feb05094665c54501f5824d284c7612b
46,047
def fio_json_output_with_error(fio_json_output): """ Example of fio --output-format=json output, with io_u error. Based on actual test run. """ err_line = ( "fio: io_u error on file /mnt/target/simple-write.0.0: " "No space left on device: write offset=90280222720, buflen=4096" )...
babfcd242a47091dc9b8acd29f24b6ebb398c679
46,048
def supprimeExtension(str): """ Fonction qui supprime l'extension de notre str param : str : string -> chaine de caractere qu'on souhaite supprimer l'extension. return string : chaine de caractere sans extenstion """ #appliquer cette fonction avant supprimePonctuation return "".join(str.spl...
63dda5c2987121f537501bddb4076aa432fbf51e
46,049
def has_equal_properties(obj, property_dict): """ Returns True if the given object has the properties indicated by the keys of the given dict, and the values of those properties match the values of the dict """ for field, value in property_dict.items(): try: if getattr(obj, field...
d96b17124121af5db31c9db096b5010aff01b233
46,050
def outerproduct(tensor1: BlockSparseTensor, tensor2: BlockSparseTensor) -> BlockSparseTensor: """ Compute the outer product of two `BlockSparseTensor`. The first `tensor1.ndim` indices of the resulting tensor are the indices of `tensor1`, the last `tensor2.ndim` indices are those of `tensor...
d19ef9a5d6fbb3d5c9f03a481ca02c48717833e9
46,051
def niriss_header(ra=53.1592277508136, dec=-27.782056346146, pa_aper=128.589, filter='F150W', grism='GR150R'): """Make JWST/NIRISS image header Parameters ---------- ra, dec : float, float Coordinates of the center of the image pa_aper : float Position angle of th...
09630a85ce3c1ec7cd437b3fd35d8daa0b7110ed
46,052
def validate_twilio_request(f): """Validates that incoming requests genuinely originated from Twilio""" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&c...
fa1d309e7e3b224e36a5a356d68ae0b2720475d4
46,053
def is_api(auth_entry): """Returns whether the auth entry point is via an API call.""" return (auth_entry == AUTH_ENTRY_LOGIN_API) or (auth_entry == AUTH_ENTRY_REGISTER_API)
27c4cec6294cc3d4fda4c7b801d2fc5b99724ae5
46,055
import numpy def calcROC(output, LTE): """Uses shogun functions to calculate the area under the ROC curve""" pm = PerformanceMeasures(Labels(numpy.array(LTE)), Labels(numpy.array(output))) auROC = pm.get_auROC() return auROC
6485ab7654e1f65eebae4d9b0043630d356966b2
46,056
def _GetCoveredBuilders(trybot_config): """Returns a dict mapping masters to lists of builders covered in config.""" covered_builders = {} for master, builders in trybot_config.iteritems(): covered_builders[master] = builders.keys() return covered_builders
e759be62c1c57045dca98e40f83beda6a7ddf7e5
46,057
import collections def _load_vocabulary(filename): """Loads a vocabulary file. Args: filename: Path to text file containing newline-separated words. Returns: vocab: A dictionary mapping word to word id. """ tf.logging.info("Reading vocabulary from %s", filename) vocab = collections.OrderedDict()...
bd4bca7cede67e43bcbfea39deb7392b85701ed0
46,058
def get_all_names(): """ Return a dictionary of all names, indexed by index. """ keys = get_singleton(create=False) if keys is None: return {} entries = keys.attr('entries') result = {} for entry in entries: idx = entry.index() result[idx] = entry.attr('name...
495c8dfcf2b7416be4a0f8dcf5bc28f62ecfd873
46,059
def format_power(power): """ Converts a value for a power (which may be floating point or a `fractions.Fraction` object), into a string either looking like an integer or a fraction. """ if not isinstance(power, Fraction): if power % 1.0 != 0.0: frac = Fraction.from_float(powe...
9bc7c914d979a9d2f38b7de65de773699ff4497e
46,060
def _aggregate_neighbors(estimator, neigh_Y, neigh_weights): """Aggregate the nearest neighbors rankings according to the weights.""" aggregate = estimator._rank_algorithm.aggregate neigh_data = zip(neigh_Y, neigh_weights) Y = [aggregate(Y, sample_weight) for Y, sample_weight in neigh_data] return...
763168c7d78a2d918109b017781b44cca6c6e78e
46,061