content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def candidacy(request): """Generate a page to choose and request candidacy among the legal ones.""" # TODO Lots of unnecessary SQL queries; subgroups sorted by network should be queried all at once. user = request.user user_of_subgroups = m.Subgroup.objects.filter(users__in=[user]) candidacies = m.C...
b01c8fd57a814fe061f7398344a9d7f04dcfb044
3,623,400
def calc_f2_score(gt_bboxes_list, pred_bboxes_list, verbose=False): """ gt_bboxes_list: list of (N, 4) np.array in xywh format pred_bboxes_list: list of (N, 5) np.array in conf+xywh format """ #f2s = [] f2_dict = {'f2':0, "P":0, "R": 0} all_tps = [list([0] * 11) for _ in range(len(gt_bboxes...
fbc6e89bdd1555a3414c7ceb1d0653cb259256ee
3,623,401
def decode(serialized_example): """ Parses an image and label from the given `serialized_example` :param serialized_example: :return: """ features = tf.parse_single_example( serialized_example, # Defaults are not specified since both keys are required. features={ ...
8324094b768d849da16b82781b149ee827c9eae2
3,623,402
from datetime import datetime def dateformated(x): """ =========================================================== dateformated(x) =========================================================== this function converts the the date read from a list to a datetime format input: x is ...
ceee8998f5c381fcb4dc612e3f852f8c2a6862ab
3,623,403
from Orange.widgets.utils.itemmodels import VariableListModel def comboBox( widget, master, value, box=None, label=None, labelWidth=None, orientation=Qt.Vertical, items=(), callback=None, sendSelectedValue=False, valueType=str, emptyString=None, editable=False, ...
779a1f50e661fbf8ee5efe760bb34fec626658c2
3,623,404
def lowerbranch_subtract(X): """Function to subtract lower hysteresis branch from FORC magnetizations Inputs: H: Measurement applied field [float, SI units] Hr: Reversal field [float, SI units] M: Measured magnetization [float, SI units] Fk: Index of measured FORC (int) Fj: Index of giv...
47f62298feec88cc4ab9424994016aa0b69f3cda
3,623,405
def load_annotated_project(project_root_path): """ loads annotated symbols into a set of ModuleSymbols :param project_root_path: symbols we will use to write out new source code :return: set of ModuleSymbols objects """ return load_modules_into_module_symbol_objects(project_root_path, ...
9d4dbd7c4bce81fb8364400faa998417109c359d
3,623,406
def verify_annotation(ann_obj, projectconf): """ Verifies the correctness of a given AnnotationFile. Returns a list of AnnotationIssues. """ issues = [] issues += verify_annotation_types(ann_obj, projectconf) issues += verify_equivs(ann_obj, projectconf) issues += verify_entity_overla...
913658b75d64a161e17e256a72cb72458da9d8a6
3,623,407
def schedule_conv2d_nhwc_winograd_tensorcore_without_weight_transform(cfg, outs): """TOPI schedule callback""" s = te.create_schedule([x.op for x in outs]) def _callback(op): if "conv2d_nhwc_winograd" in op.tag: schedule_nhwc_winograd_cuda( cfg, s, op.output(0), use_tens...
1ac825c61eee950bdba43c80c393519fd7234831
3,623,408
def encode_dataset(dataset, vocabulary): """Encode from strings to token ids. Args: dataset: a tf.data.Dataset with string values. vocabulary: a mesh_tensorflow.transformer.Vocabulary Returns: a tf.data.Dataset with integer-vector values ending in EOS=1 """ def encode(features): return {k: vo...
1631f760be39c786fe8d2f7eb5eba0a3b78b5079
3,623,409
from datetime import datetime def now(): """ Get current time. :return: now as datetime with timezone """ return datetime.now(UTC)
1653538681a2bcdadbab6d8ea9e909a47a98ba32
3,623,410
import typing def CallGraphToFunctionCallCounts(g: nx.MultiDiGraph,) -> typing.Dict[str, int]: """Build a table of call counts for each function. Args: g: A call graph, such as produced by LLVM's -dot-callgraph pass. See CallGraphFromDotSource(). Returns: A dictionary where each function in the ...
61a5080e48574c7f4d13d58f3d58b8220d0ee2a4
3,623,411
def create_multi_stores(conf=CONF, reserved_stores=None): """ Registers all store modules and all schemes from the given configuration object. :param conf: A oslo_config (or compatible) object :param reserved_stores: A list of stores for the consuming service's internal ...
e002e2b37652c88c3a16a5a07dab7d095c965260
3,623,412
import logging def decompose(args): """ Make a decomposition of the energy into some if its residue components. """ if args.resList is None: msg = 'TERMINATED. List of residues not provided.' logging.info(msg) return None gmx = search_commands(['gmx', 'gmx_mpi'], args.gmxE...
c384d760e215f07e0251f028908f4790c371fdf8
3,623,413
def define_generator(image_shape, n_resnet): """ Creates the generator :param image_shape: shape of the input image :param n_resnet: Number of resnet blocks :return: generator model """ # Weight initialization init = RandomNormal(stddev=0.02) # Image input in_image = Input(shape...
2e24d70aff320cd282f3849e989f60adcc8ce950
3,623,414
def duplicates_allclose(dataframe, dcols, fcols): """Determine duplicates in dataframe based on tolerances Args: dataframe: the dataframe dcols: the columns that are tested for exact duplicates fcols: the columns that are checked for tolerance, dict with tolerances This is the si...
53b70eb37d2c7ee61e8e66828b5e598915ddcc79
3,623,415
import os def base_app(tmp_shared_volume_path): """Flask application fixture.""" config_mapping = { "SERVER_NAME": "localhost:5000", "SECRET_KEY": "SECRET_KEY", "TESTING": True, "SHARED_VOLUME_PATH": tmp_shared_volume_path, "SQLALCHEMY_DATABASE_URI": os.getenv("REANA_SQ...
b8200dc32b981dc17a0981c17b47675e4d02d30e
3,623,416
def get_topic_summary_by_id(topic_id, strict=True): """Returns a domain object representing a topic summary. Args: topic_id: str. ID of the topic summary. strict: bool. Whether to fail noisily if no topic summary with the given id exists in the datastore. Returns: Topic...
34ed9e5e0cbdf8b2e06f2bcedb43c361ad56f063
3,623,417
def smoothing_Negative_rx0(MSK, Hobs, rx0max): """ This program use an opposite methode to the direct iterative method from Martinho and Batteen (2006). This program optimizes the bathymetry for a given rx0 factor by decreasing it. Usage: RetBathy = smoothing_Negative_rx0(MSK, Hobs, rx0max) ...
ac93c4b983780dc8eae524efc4d7b7b7d1ff650c
3,623,418
def cgraphics_vec_to_RGBangle(source, w, h, cm, colorcorrect): """Pixelwise conversion of a 2D vectors to RGB angular image. This is especially useful for optic-flow visualization. Parameter --------- source : numpy array [2 * dim_x * dim_y] The 2D vector image of resolution dim_x x dim_y....
ea4437a1355bcb254fabff4a85b9e0bdc5fc54fd
3,623,419
def get_port(): """Returns a port number.""" return 0
97259c825bbe41f47bd5bec81fedf24c5b19a547
3,623,420
def return_car_dict(car: Car): """ Returns a Car Object as dictionary :param car: The car object being formatted :return: Returns the car object formatted to return as dictionary """ riders = [] for rider in car.riders: riders.append(rider.username) return { 'id': car.id,...
4bc9f15769db8564693b2396cef970c447a80729
3,623,421
def sort_unique(edges): """Make sure there are no duplicate edges and that for each ``coo_a < coo_b``. """ return tuple(sorted( tuple(sorted(edge)) for edge in set(map(frozenset, edges)) ))
d4f4425b78baed6d822d5559787ced1653986761
3,623,422
def ext_subtable23(cxt: DecoderContext, fmt: Format): """ EI | DI | SYSCALL | CLL | PUSHSP | POPSP | undef """ if fmt.lo5 == 0 and fmt.ext_hi5 == 0 and fmt.ext_lo5 == 0: ff_hi = fmt[15:14] ff_lo = fmt[13:11] mnem = [[MNEM.DI] + [MNEM.UNDEF_CODE] * 3, [MNEM.UNDEF_CODE] * 4...
6b53cf2f29df6fb2f62d307ec72e3558afbc65dc
3,623,423
def if_else(vector: np.ndarray) -> np.ndarray: """Copies vector but sets elements lower than 3 to 0 Parameters ---------- vector : np.ndarray shape = (n, ) Returns ------- np.ndarray shape = (n, ) Examples -------- >>> a = np.array([1, 2, 3, 4, 5, 6]) >>> i...
039d2c6ead74af0d1d6536f1ec7c1969bb77d1ba
3,623,424
import sys def daast_from_file(filename, args=None): """Generates DistAlgo AST from source file. 'filename' is the filename of source file. Optional argument 'args' is a Namespace object containing the command line parameters for the compiler. Returns the generated DistAlgo AST. """ try: ...
fde2f0fc6389786b919d5ac6802d84c88b8c6406
3,623,425
def plot_roc_auc_f1(y_test, y_proba, title=None): """Plot ROC curve and random comparison, along with f1 and AUC metrics""" std_f1 = f1_score(y_test, y_proba[:, 1] > 0.5) fpr, tpr, _ = roc_curve(y_test, y_proba[:, 1]) auc_score = auc(fpr, tpr) fig, axis = plt.subplots(figsize=(6, 6)) if title is...
867a84a45eeeb0b2451b84252e313714d08b9ea4
3,623,426
def get_var_names(var_name): """Defines replacement dictionary for the bare variable name and the names derived from it - the optimization flag and the identifier name. """ repl = dict() repl['opt_var_name'] = "Opt_%s"%var_name repl['id_var_name'] = "ID_%s"%var_name repl['var_name'] = var_name return...
37999ffed0a0df1dbf736ada0cc355080dd9997f
3,623,427
import sys def progressbar(it, prefix="", size=60, file=sys.stdout): """A super simple progressbar. Args: it ([type]): [description] prefix (str, optional): [description]. Defaults to "". size (int, optional): [description]. Defaults to 60. file ([type], optional): [descriptio...
cce6beee0d67e0d6be954f52709d0e9aa36c9a07
3,623,428
def hubble_parameter(z): """ It calculates the Hubble parameter at any redshift. """ part = np.sqrt(const.Omega0*(1.+z)**3+const.lam) return const.H0 * part
a026648e2a14630e8121d27d7a3435bae55a4d5e
3,623,429
import os def default_output_name(input_name): """Return the default output name for the specified input name. This function is invoked when no ``--output`` option is specified (see the documentation of this option for further details). """ tokens = os.path.split(input_name) basename = (token...
9ffbcd06f3cfba2dfcfc59d066b90ab43bd8af30
3,623,430
import logging def is_valid_snmp_v2_credential(credential): """check if credential is valid snmp v2 credential.""" if credential.keys() != SNMP_V2_CREDENTIALS.keys(): return False if credential['version'] != '2c': logging.error("The value of version in credential is not '2c'!") ret...
3adaf2eddc4c9afc9388e56f34c9d4d7afab171b
3,623,431
from typing import Dict from typing import Any from typing import List import json def test_remove_existing_last_key(mocker): """ Given: - a nonempty list with 1 value - a key that exists in the list (the only one that exists) When - trying to remove the last key of the list Th...
ccc1850aa17670d555308c0286dd8cdbdebb6a82
3,623,432
from emmaa.util import get_s3_client from emmaa.model import save_config_to_s3 from emmaa.model_tests import ModelManager, save_model_manager_to_s3, \ def setup_bucket( add_model=False, add_mm=False, add_tests=False, add_results=False, add_model_stats=False, add_test_stats=False): """ This fun...
3cf01e40dbcff44d1f91f324a4f81d7fe22f9427
3,623,433
def get_school_deadlines(college): """Get the admissions deadlines for the provided college.""" if college: college = college.lower() for deadline in DEADLINES: if college in deadline.lower(): return statement(deadline) return statement( 'Sorry, we are sti...
8a1034f3e1275d6243feefeef9b058ed9c2d6f8b
3,623,434
def function_grandkids_cell(): """Returns string see usage""" return "\n".join(["F1 is a function", "F1a is a function", "F1a1 is a function", "F1 is composed of F1a", "F1a is composed of F1a1", "a is a data", "F1a produces a", "b is a data", "F1a consumes b", "c is a...
07b862cd5c5e02a90cba744d7182dab25994be1b
3,623,435
def euclidean(matrix, vector, assure_consistency=False): """ Calculate inversed euclidean distance for all words in matrix against vector. """ if assure_consistency: vector = _assure_consistency(matrix, vector) inv_euc= 1/(1+matrix.subtract(vector).norm(axis=1)) return inv_euc.sort(ascen...
b31ec133957c555c8ce231f0ef0a99792ce0b502
3,623,436
def alfred_items_for_value(value): """ Given a Chinese language string, return a list of alfred items for each of the results """ index = 0 results = [] config_list = [ ('t2s.json', u'繁體到簡體', 'SimplifiedChinese.png'), ('s2t.json', u'簡體到繁體', 'TraditionalChinese.png'), ('s...
6f4437db0515e8464a235e59c5b4a3e26eaa5a44
3,623,437
import re def preprocess_caption(row, mode): """Applies the selected preprocessing steps to the text. Args: row: A UTF-8 string. mode: A string indicating the selected preprocessing strategy. Valid values include: 'no_preprocessing' (no preprocessing), 'rm_all...
68a3cad4e20ce5151cc7ed49b5de747b2a17cdcb
3,623,438
def encode(val, base, minlen=0): """Returns the encoded string""" code_string = get_code_string(base) result = "" while val > 0: result = code_string[val % base] + result val /= base if len(result) < minlen: result = code_string[0] * (minlen - len(result)) + result return...
772f787c915703cda7f7fb8f5942484ea6cbab6a
3,623,439
from typing import List from typing import Dict import re def parse_header_links(value: str) -> List[Dict[str, str]]: """ Returns a list of parsed link headers, for more info see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link The generic syntax of those is: :: Link: < u...
536d3f2b477666c076ac29312f3acfe63f40e324
3,623,440
import traceback def main(testsuite_list, project_repository, data_repository, auto_defects=False, ts_parallel=True): """Executes the list of testcases in parallel Computes and returns the testsuite status""" try: project_status = execute_parallel_testsuites(testsuite_list, project_reposi...
77542764fd46f57d420618fa747f3df8b09f0d4c
3,623,441
import ast from typing import List def find_function_def_nodes(node: ast.Module) -> List[ast.FunctionDef]: """Finds ast.FunctionDef nodes in the source code. ast.FunctionDef represents `def function_name(....):` statement in the code. Args: node: a root node of the AST tree, this node should be a...
1bed6da5705da11d614210de453bee6edae11941
3,623,442
def parseFloat(value, ret=0.0): """ Parses a value as float. This function works similar to its JavaScript-pendant, and performs checks to parse most of a string value as float. :param value: The value that should be parsed as float. :param ret: The default return value if no integer could be pa...
6828cc19882dcbfcf7b83781b1e79a6014034cad
3,623,443
import requests import json def metadataview(request, container, objectname=None): """ Return object/container/pseudofolder metadata. """ storage_url = get_endpoint(request, 'adminURL') headers = {'X-Storage-Token': get_token_id(request)} url = '{0}/{1}'.format(storage_url, container) if objectn...
82af25a85f89db5464bac5869dfa05480053c6b2
3,623,444
def count_call_alleles(ds: Dataset, merge: bool = True) -> Dataset: """Compute per sample allele counts from genotype calls. Parameters ---------- ds : Dataset Genotype call dataset such as from `sgkit.create_genotype_call_dataset`. merge : bool, optional If True (the defaul...
904235b56f0bc87c809e41c7f3fcaee85da5bf1f
3,623,445
from typing import Concatenate def dense_block(x, n_filters): """ Construct a Densely Connected Residual Block x : input to the block n_filters: number of filters in convolution layer in residual block """ # Remember input tensor into residual block shortcut = x # BN-R...
59d5d05b69756367f0ed4e24544ea58ff3afbae9
3,623,446
def get_fetcher(conf: MappingNode, build_dir: str, generator: ninja_syntax.Writer): """Construct and return RepoFetcher object""" return RepoFetcher(conf, build_dir, generator)
afc4efeb39a03a63e25b7eba840bd532db59b05d
3,623,447
def text_box_search_folder(path, tag, search_term): """applies the text_box_search() method to a full folder Arguments: path [string]: absolute of relative path to folder tag [string]: element type search_term[string]: search term to find element Returns: [named tuples]: ...
58835459faf37ddc5ec85e8cd0ef29604ef6c235
3,623,448
def discard_inserted_documents(error_documents, original_documents): """Discard any documents that have already been inserted which are violating index constraints such documents will have an error code of 11000 for a DuplicateKey error from https://github.com/mongodb/mongo/blob/master/src/mongo/base/...
9d7d47a0ade2300449a7f1a4a20c3a70f6dce583
3,623,449
def include_amp_css(path: str): """ Inserts CSS content into a Django template, stripping illegal CSS rules and keywords. """ actual_path = finders.find(path) with open(actual_path, 'r', encoding='UTF-8') as f: content = f.read() content = content.replace('!important', '') return mar...
45202a6dcfc894c72aabfa5c1b07ed9cd36a5c86
3,623,450
def get_target_no_match(mirna_sequence, length): """Given a miRNA sequence, return a random target sequence without 4 nt of contiguous pairing""" rc = rev_comp(mirna_sequence[1:8]) + 'A' off_limits = [rc[ix:ix + 4] for ix in range(5)] while True: target = generate_random_seq(length) keep...
2bd6e5fd226e21ff955f0f4f7ec30c8fbc54f887
3,623,451
def list_folder(drive, folder_id): """ Lists contents of a GoogleDriveFile that is a folder :param drive: Drive object to use for getting folders :param folder_id: The id of the GoogleDriveFile :return: The GoogleDriveList of folders """ _q = {'q': "'{}' in parents and trashed=false".format(...
1ea5837d6096f2f9c1f0485d5a02bd43a8b8c55e
3,623,452
def media_100_fixture(): """Load media payload for item 100 and return it.""" return load_fixture("plex/media_100.xml")
8b9f7a76b9a16cb15cc5d8c7ee48f28de45d8f5d
3,623,453
import matplotlib.pyplot as plt def plot_good_coils(raw, t_step=1., t_window=0.2, dist_limit=0.005, show=True, verbose=None): """Plot the good coil count as a function of time.""" if isinstance(raw, dict): # fit_data calculated and stored to disk t = raw['fit_t'] counts = ...
77c6bfd1e5a2b931398a43c6dabf36104e77d533
3,623,454
def ascii_encode_dict(data): """Encodes dict keywords to regular strings. Needed because of bug in Python 2.6 which causes fail when passing unicode keyword to _Substitute().""" ascii_encode = lambda x: x.encode('ascii') if isinstance(x, unicode) else x return dict(map(ascii_encode, pair) for pair in data.ite...
3c1f9b09f71fb61c59aa73465e0e67b4ca6398f9
3,623,455
import re def normalize_place_name(value): """Quick and dirty conversion of common verbiage around placenames""" query_value = value query_value = re.sub(r"^Place \w+:", "", query_value) query_value = re.sub(r"^Cultural Place:", "", query_value) query_value = query_value.strip() return query_...
790110ff9381cdce69caffc14362f61936c36cb4
3,623,456
def plot_calibration_curve(y_true, y_pred_prob, model_name, title, n_bins=5, normalize=False): """ Returns a matplotlib figure containing the plotted calibration plot. Args: y_true: array-like of shape (n_samples,) of true target y_pred_prob: array-like of shape (n_samples,) probabiliti...
3f1d5e20c61ea675e81372c1d3b9471c6e7d7979
3,623,457
from typing import List from typing import Optional from typing import Union from typing import Tuple from typing import Set from typing import Dict from typing import Callable from typing import Any def boxplot( df: DataFrame, groupby: List[str], metrics: List[str], whisker_type: PostProcessingBoxplo...
7bead51525f95f59a31de626976e232c387c31dd
3,623,458
def pow_mid(p, max_denom=1024): """ Return (x,1,t) power tuple t <= x^p 1^(1-p) user wants the epigraph variable t """ assert 0 < p < 1 p = Fraction(p).limit_denominator(max_denom) return p, (p, 1-p)
0393aed017a8d7a41388ee2b185f8f708b8a880c
3,623,459
def search_vulnerabilities_version(word_list, db_table): """ Search vulnerabilities for version number. :param word_list: the list of words searched by the user. :param db_table: the database table in which perform the search. :return: the list containing the results of the performed search. """...
e6995b9fa01e20cdd250c1784ce17aaa29db1168
3,623,460
import struct def htons(cpu_context, func_name, func_args): """ Convert the provided 16-bit number in host byte order (little-endian) to network byte order (big-endian) """ le_port = func_args[0] port_data = struct.pack("<H", le_port) return struct.unpack(">H", port_data)[0]
095be37630fbe0dc86ea5e731180249c29ccac85
3,623,461
import sys import torch def load_data(dataset): """Load data.""" names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph'] objects = [] for i in range(len(names)): with open("data/ind.{}.{}".format(dataset, names[i]), 'rb') as f: if sys.version_info > (3, 0): object...
b28400fb49f1ffc2cdf2639fcc14f3a08514e42f
3,623,462
def _split_columns(df, columns, delimiter, converter=identity): """Split column string values into tuples with the given delimiter.""" return df.update_columns( **{column: ignoring_exceptions(lambda s: tuple(converter(x) for x in s.split(delimiter)), (), (AttributeError)) for column in make_iterable(col...
fac76750bca4952c9ba8aff26b056c5554bbe076
3,623,463
def read_well_list(stream): """Read the well-list.""" retval = {} for line in stream: line = line.rstrip() if line.startswith("Row"): continue tokens = line.split("\t") wbc = tokens[5] retval[wbc] = { "row": tokens[0], "column": tok...
65b1782a76c5eddb88a6e6491a72fd2f93d56076
3,623,464
def bayes_compare_language(l1, l2, ngram_range=(1, 3), prior=.01, cv=None, counts_mat=None): """ Parameters ---------- l1, l2 : Iterable[str] list of strings from each language sample ngram_range : Tuple[int, int], default=(1,3) an integer describing up to what n-gram you want to co...
d3f47e41e48618f634dd60bc9606d5a127cd370c
3,623,465
import re def find_asn(string: str): """ Returns a autonomous system number or None :param str string: String :return: int or None """ match = re.search(PATTERN_ASN, string) if match: return int(match.group(1)) return None
1a5eade84a7960523197254160b2ce606ce4997d
3,623,466
import imp import uuid def load_solvers(path): """Load a suite of solvers.""" logger.info("loading solver suite from %s", path) return imp.load_source("borg.suite_{0}".format(uuid.uuid4().hex), path)
4e7a7f804e31fe6ea3d907d8f47b0940cfa43f35
3,623,467
def cross_derivative(expr, dims, fd_order, deriv_order, **kwargs): """ Arbitrary-order cross derivative of a given expression. Parameters ---------- expr : expr-like Expression for which the cross derivative is produced. dims : tuple of Dimension Dimensions w.r.t. which to diffe...
07574280f6ef0c8e1393db781506a008b90245db
3,623,468
def starting_node_random_walk(bipartite,weights_x, min_weight=100, max_dim=10 ): """ Sample random node in X (from bipartite graph X-Y) with the restriction that it does not connect to more than "max_dim" nodes in Y and that its weight is more than "min_weight" Parameters ---------- bipartite :...
7c8a54fa376823d6bb9b2d4c8c641f8e120fc247
3,623,469
def play_marbles(players, start_marble, limit_points): """Play marbles with number of players and limit_points.""" cur_marble = start_marble cur_points = 1 cur_player = 0 while cur_points <= limit_points: if cur_points % 23 == 0: for _ in range(7): cur_marble = cu...
06bae200c7b1763c68304442e592f1ef44d8618f
3,623,470
import json import re def get_extension_name(id: str, version: str) -> str: """Returns the 'name' of a Chrome extension by finding the correct source. Args: id: An extension identifier string. version: The extension version that is used to search file paths. Returns: A string for...
d953c5bcd7150a2f9e41dfab7c79e3ae940c4ca2
3,623,471
import time import sys def metered_stream(fn): """ Display a progress meter to standard out for a stream. """ def wrapped(*args, **kargs): meter = _use_and_del(kargs, 'meter', True) freq = _use_and_del(kargs, 'meter_freq', 10000) stream = fn(*args, **kargs) # Hijack the stream and keep cou...
3c3809a21570193c7e1a907754c56bcdd8b1ceb3
3,623,472
import json from datetime import datetime def filter_data(data): """ Setup the filter in use by the listen() function. It will take the rsvp event JSON string, and return a JSON string subset of that data. :param: json string :return: json string """ try: result = json.dumps({ ...
f32c6f7907fd6dd64fac443c459864cd62bb737f
3,623,473
from typing import OrderedDict def _to_distiller_modulelist(model): """Replaces all instances of torch.nn.ModuleList in a model with DistillerModuleList instances Args: model (torch.nn.Module): Model to convert """ def convert_container(container): # To maintain a similar order of reg...
6a37737dae923c418d3931994f5dd0467abe0b75
3,623,474
from typing import Any def noted_under(key: str) -> Any: """Gets a noted value from the director. Examples:: the_actor.should( See.the( Text.of_the(WELCOME_MESSAGE), ContainsTheText(noted_under("first name")) ), ) """ try: return Direct...
c598c33d8bd505a338d17ee90dbb8dd84fce35ab
3,623,475
def department_page(school_name): """ Renders the page where the user selects their department. """ school = School.query.filter(School.name == school_name).first() if school is None: return default_error, 400 return render_template('departments.html', departments=school.departments.all())
9871cf587f9310015be06305dd0cfd55d4ecb090
3,623,476
import os import subprocess def download_isolated_file(h, workdir, isolate_server, namespace): """Download the isolated file with the given hash and return its contents.""" dst = os.path.join(workdir, h) if not os.path.isfile(dst): subprocess.check_call([ 'python', 'isolateserver.py', 'download', '-...
6b286c0c50d06ead3f4a137030384737d49861b7
3,623,477
def add_feat_data_to_array(all_data, new_data, feat_pd_names, feat_name, params): """ Update all_data array by appending the new data. The new data contains the data from all freq bands Syntax: all_data = add_feat_data_to_array(all_data, new_data, feat_pd_names, feat_name, params) Inputs: all_...
bb7e20ff0e0468442adc0e5600dc165bbf18bade
3,623,478
def distance_matrix_dict_fixture(): """The expected distances between the example cities defined in tests/conftest.py""" return { 'euclidean': np.array([ [0, 1118, 2236], [1118, 0, 1118], [2236, 1118, 0] ]), 'manhattan': np.array([ [0, 1500...
165c2cbd25f8e6659fc25a76489c37e72b3bd14e
3,623,479
def get_global_config_definition(context, config, value): """Get config definitions included with Mycroft. Arguments: context: behave test context config: config value to fetch from the file value: predefined value to fetch Returns: Patch dictionary or None. """ con...
883bbc2cca021ac3bbed6f923c8b948ea83f4800
3,623,480
import numpy as np import xarray as xr def interp_sw_levels_xr(sw_xr_var): """takes swoosh data xarray Dataarray (one var) and interpolate it vertically to MERRA GCM pressure levels""" # *levels is other optional pressure levels MERRA_levels = np.array([3.00000000e+02, 2.50000000e+02, 2.00000000e...
255a93e69965fb24a7039cad57d919766a8d5a1e
3,623,481
def ordinal_number(n: int): """ Returns a string representation of the ordinal number for `n` e.g., >>> ordinal_number(1) '1st' >>> ordinal_number(4) '4th' >>> ordinal_number(21) '21st' """ # from https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1...
9cb2b333cfe7d4e7b115d21d9d3c1bbaec02cdd9
3,623,482
def rgamma(alpha, beta, size=None): """ Random gamma variates. """ return np.random.gamma(shape=alpha, scale=1. / beta, size=size)
c7985db1be3e979d793f90ff4eea6845853c4684
3,623,483
def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False, mesh_annotations=True): """Get metadata for an XML tree containing PubmedArticle elements. Documentation on the XML structure can be found at: ...
7375fbe805db7bf7fc243b143f5499212a6412af
3,623,484
def aodh_client(conf): """Get an instance of aodh client""" try: ao_client = driver_module('aodh') client = ao_client.Client( conf.aodh_version, session=keystone_client.get_session(conf)) LOG.info('Aodh client created') return client except Exception: ...
62bb9befd5ac99d8e7d210b655c3e31f8c85803f
3,623,485
def import_data(wave): """brings 2 dataframes with all the features and series with y (panelpat)""" # we predict particular wave attrition based on previous one, therefore we subtract 1 from wave number wave = str(int(wave) - 1) political = pd.read_csv(f'data/data_online_political_w{wave}.csv') pers...
1c3a72e608cb167c004eed76c38ef85b1d139ac6
3,623,486
from typing import Any from typing import Optional def _ensure_success(result: Any, attr: Optional[str], fail_msg: str) -> Any: """ Ensures that *status* is ``GattCommunicationStatus.SUCCESS``, otherwise raises ``BleakError``. Args: result: The result returned by a WinRT API method. a...
139b9053717e3ef2a2e8d45231f4b80fbfe306fa
3,623,487
def get_jaccard_sim(wordlist_a, wordlist_b): """Receive info for two documents and return jaccard similarity""" # Get info from documents cardinality_a = wordlist_a['cardinality'] cardinality_b = wordlist_b['cardinality'] # Bag of words bag_of_words_a = wordlist_a['bag_of_words'] bag_of_word...
2628d6a329062f391acf06c4f8a1eb483a84e3cd
3,623,488
def tree_depth(t): """What is the max depth of t?""" # n.b. car is always length 1 the way trees are currently parsed subdepth = 0 for subtree in tree_cdr(t): subdepth = max(subdepth, tree_depth(subtree)) return subdepth + 1
dad7ab3e4c0a245c4f5b4d1ab0794c344bc8923c
3,623,489
def vector_angle(pairs): """ Find the angles between pairs of unit vectors. Parameters ---------- pairs : (n, 2, 3) float Unit vector pairs Returns ---------- angles : (n,) float Angles between vectors in radians """ pairs = np.asanyarray(pairs, dtype=np.float64) ...
66f227180b6ff750ae7220fd4dbfd4736cf9416e
3,623,490
from typing import List async def get_contestants(token: str, event_id: str) -> List[dict]: """Get the contestants in the event.""" try: contestants = await EventsAdapter.get_contestants(token, event_id) except ContestantsNotFoundException as e: raise e from e if not contestants or len...
b42acfddb9e80d2d72a376b9fa4531170d867891
3,623,491
import sys def findVariantsInRange(vcfFname, chrom, start, end, strand, minFreq): """ find variants that overlap the position. varDb is a tuple of label, vcfFname return as a dict relative position -> (chrom, pos, refAllele, altAllele, list of info-dicts) special position is "label" which is the label...
8e09974a87a7edbb4a7c7ba6385705650130e88b
3,623,492
import re def limpieza_basica(texto, quitar_numeros=True): """Limpieza básica del texto. Esta función realiza una limpieza básica del texto de entrada, \ transforma todo el texto a letras minúsculas, quita signos de puntuación y caracteres \ especiales, remueve espacios múltiples dejando solo espacio senc...
e3f55d513b1f0326c14ef6c21b31227e66ced5c2
3,623,493
def texture(data): """ Compute the texture of data. Compute the texture of the data by comparing values with a 3x3 neighborhood (based on :cite:`Gourley2007`). NaN values in the original array have NaN textures. (Wradlib function) Parameters: ========== data : :class:`numpy:numpy.ndarra...
5f5d9d4251f907676eef6e1aa8451fc5672ee74d
3,623,494
def config_locator(): """ Returns the path to the file containing your LAtools configurations. """ return pkgrs.resource_filename('latools', 'latools.cfg')
86440567eeec92112a75d75473478d84b3f9b585
3,623,495
import os import torch def resnet50_fpn_backbone(pretrain_path="", norm_layer=FrozenBatchNorm2d, # FrozenBatchNorm2d的功能与BatchNorm2d类似,但参数无法更新 trainable_layers=3, returned_layers=None, extra_blocks=None): """ ...
93db72b0e10debffbe8e073482167d1ce85934b0
3,623,496
def hasroyalflush(hand: list): """ Check if hand has royal flush Royal Flush is a straight flush that consists of A, 10, J, Q, K Parameters: hand (list): The poker cards Returns: bool: True if hand is a Royal Flush """ if len(hand) == 5: isroyal = False cardval = [c...
05ce5fb92762c749052a06d05886bcb1f5ea5180
3,623,497
import json def get_lambda_config_property(context, property_name=None): """ Extract JSON properties from the JSON encoded description. Return the value for the property, None if not found, all properties if no name given. """ aws_lambda = boto3.client('lambda') function_arn = context.inv...
1f4f2e0f0ce684f07ba11e31bfa6666268cc9b53
3,623,498
def resolve_doi(doi): """ Takes as input a DOI and returns the internal HydroShare identifier (pid) for a resource. This method will be used to get the HydroShare pid for a resource identified by a doi for further operations using the web service API. REST URL: GET /resolveDOI/{doi} Parameter...
df198d9bb7324eecfd692dd1648b914180836313
3,623,499