content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def parse_and_import_eri_2g(parent_dag_name, child_dag_name, start_date, schedule_interval): """Parse and import Ericsson GSM CM data""" dag = DAG( '%s.%s' % (parent_dag_name, child_dag_name), schedule_interval=schedule_interval, start_date=start_date, ) t22 = BashOperator( ...
b07f078463e29767ca0d9f28725c1ba58b38521a
54,977
def np_uncertainty(obs_name, wc_obj, *args, N=100, threads=1, **kwargs): """Get the uncertainty of the prediction of an observable in the presence of new physics. Parameters ---------- - `obs_name`: name of the observable as a string - `wc_obj`: an instance of `flavio.WilsonCoefficients` -...
d8c339a9899506178732f688e7bf6cc19cb99d42
54,978
def setup(app): """ Sets up the Sphinx extension for the `problog` directive. """ # register two Sphinx config values used for the extension app.add_config_value('sphinx_problog_code_directory', None, 'env') app.add_config_value('sphinx_problog_execution_server_url', '', 'env') # register t...
c890431df4d7b66b38106696b855d00772bdc2e0
54,980
import numpy def calculate_weighted_statistics(values, weights, statistics): """ Calculates weighted statistics :param values: pixel values :params weights: weight of each pixel, where 0 > weight >= 1 (areas of 0 weight should be masked out first). Weights can be thought of as the proportion of...
502869b5719aa0db59f16f61ab0eaa1c21a7128a
54,981
def check_sup_x(supp, row_num, z, c): """ delete unusable numbers from rows """ for x in range(3): for y in range(3): for k in row_num: supp[x+z*3][y+c*3][k] = 0 return supp
f776dd426a11ac806a7c025dd6e88c244f988208
54,983
def _get_session_id(config, url): """Retrieve session id associated with url. :param url: HTTP endpoint (including protocol, port and optional user). """ try: return config.parser.get('session_id', url) except NoSectionError: config.parser.add_section('session_id') except NoOptionError: pass
fc787c0ae95a3554991a825ba73bfad46de4db6d
54,984
def average_precision_recall_fscore(results, micro=True): """Return average precision, recall and f-score for list of BinaryClassificationMetrics. """ if micro: total = BinaryClassificationMetrics(*tuple(np.sum(results, axis=0))) return precision_recall_fscore(total.tp, total.fp, total.f...
a18cd518d6cbb71b1716d1c03c2c0a4d0f2e9f46
54,985
def unstratified_pooled_hessian(X, delta, beta): """unstratified_pooled's hessian.""" score_numer, score_denom = collect(unstratified_pooled_score, ["xebx", "ebx"])(X, delta, beta) score_numer_cs = cumsum(score_numer, name="xebx_cs") score_denom_cs = cumsum(score_denom, nam...
869a1bc8a9f96498d89be2fc79d594a237aa57fa
54,986
def get_name_from_key(key) -> str: """Given a dask collection's key, extract the collection name. Parameters ---------- key: string or tuple Dask collection's key, which must be either a single string or a tuple whose first element is a string (commonly referred to as a collection's 'na...
8a5b46a85000325932c043eb4a94864fef2d6dd4
54,987
def cornersphere(x): """Sphere (squared norm) test objective function constraint to the corner""" nconstr = len(x) - 0 if any(x[:nconstr] < 1): return np.NaN return sum(x**2) - nconstr
39e18fdbf69573d19a47537d4faa8a08f3504d79
54,988
from typing import Union def convert_cells_to_percentages(dimensions: Union[CoordinateType, ExtentType], cell_resolution: CellResolutionType) -> Union[ CoordinateType, ExtentType]: """Converts dimensions from cell units to percentage units""" if isinstance(dimensions, CoordinateType): if dimensions.x.units ...
7b9830d392d04f102999154e3364c245e6760cea
54,989
from typing import List def get_gene(entrez_gene_id: str, gene_list: List[GeneInfo], genes: dict): """ Find GeneInfo with a given entrez gene id or create a new GeneInfo """ gene_id = 'NCBIGene:'+str(entrez_gene_id) if gene_id in genes: return genes[gene_id] gene = GeneInfo(gene_id...
eb307f5c36a69ee3e2df600eedc99e6c14a4cec0
54,990
def get_auto_flow(novaclient, process_what): """Constructs and returns the engine entrypoint flow. This flow will do the following: 1. Disable compute service on source host 2. Get all HA_Enabled instances. 3. Evacuate all the HA_Enabled instances. 4. Confirm evacuation of instances. """ ...
3c3813cc56d598e79f91a70a211bbd43e7d1fe10
54,991
def get_percentiles(latency_list, percentages): """ Get the percentiles of the given latency list Arguments: latency_list: The list with latencies as elements p: List of percentiles to plot """ latency_np = np.array(latency_list) # Convert to numpy array sorted_np = np.sort(late...
a229b09bb0fba697ce3da6e3e60409f9c8c28399
54,992
from typing import Optional def make_identifier( signature: InstrSignature, dockerfile: Optional[Dockerfile] = None ) -> str: """ Create an URL friendly identifier string from a signature. This notion of identifier string does not exist in Docker per se, since we do factor in the definituon's mod...
c394e46d6a01e6d7622742efc4529666e308c030
54,993
def configure_mafdf(mafdf, keep_samples): """Configures a maf dataframe Args: mafdf: Chunk of maf dataframe keep_samples: Samples to keep in the maf file Returns: Configured maf dataframe """ keep_mafdf = mafdf[ mafdf['Tumor_Sample_Barcode'].isin(keep_samples.toli...
73a8be59eed431185ddcfaa1ea655ff554f61072
54,994
def yices_function_type2(tau1, tau2, ran): """For convenience: returns the function type tau1, tau2 -> ran, tau1, tau2, ran must be a valid types.""" return libyices.yices_function_type2(tau1, tau2, ran)
8b4e260a97d36c986e5fbabc20c896202255d7aa
54,995
def search(connection, preferred_hosts, ignore_hosts, facets): """Search for files on ESGF. Parameters ---------- connection : pyesgf.search.SearchConnection Search connection preferred_hosts : :obj:`list` of :obj:`str` List of preferred hosts. ignore_hosts : :obj:`list` of :obj...
3baef2b9cd8949b86d48c2a28d5ddf85c27f24a9
54,996
def _gaussian(x,mu,sig,height): """ helper function which computes a guassian """ return height*np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
9fa89b56dfd80ef0365194970415a57e36b0dc8b
54,997
def powers_and_coefs(order): """For a `order`-way FM returns the powers and their coefficients needed to compute model equation efficiently """ decompositions, _ = get_shorter_decompositions(np.ones(order)) graph = defaultdict(lambda: list()) graph_reversed = defaultdict(lambda: list()) for ...
cef362a32422844a919835ee8365d977b05ea95b
54,998
import sqlite3 from typing import Optional def get_account_id_for_api_key(db: sqlite3.Connection, api_key: str) \ -> tuple[Optional[int], AccountFlag]: """ This is not indicative of whether there is an account or not as disabled accounts will not be matched. If the account is valid, then and only ...
9cfaf458da4c132894e9faad041265e9ea648c74
54,999
def convert_init_dict(init_dict): """Convert an init_dict from an old version of pyleecan to the current one""" # V 1.0.4 => 1.1.0: New definition for LamSlotMag + SlotMag if init_dict["__class__"] == "MachineSIPMSM" and "magnet" not in init_dict["rotor"]: print("Old machine version detected, Updat...
d73718c77b1909b150e254aa1ef4eed7fbf33c35
55,000
def plot_2D_comparison( field_direction, diagnostic, observable, experimental_data, simulation_data, fig_width=7.5, fig_height_per_row=1.5, title_height=1.0, common_colorbar: bool = True, experiment_sets_colorbar: bool = False, diverging: bool = False, **kwargs, ): ""...
99132938fd8b962e8fb0b7d17347aad2a1a7d8d2
55,001
def f_solpos(times, latitude, longitude): """ Calculate solar position for lat/long at times. :param times: Python :class:`datetime.datetime` object. :type times: list :param latitude: latitude [degrees] :type latitude: float :param longitude: longitude [degrees] :type longitude: float ...
0499a8aec045ba27f20de2d0768f95b1c1f3a1bd
55,002
def linear_comb_layer(weights, vectors, size=None, name=None, layer_attr=None): """ A layer for weighted sum of vectors takes two inputs. - Input: size of weights is M size of vectors is M*N - Output: a vector of size=N .. math:: z(i) = \sum_{j=0}^{M-1} x(j) y(i+Nj) ...
e03344d23e3a68344dca214940ca9b489effec50
55,003
import json def get_default_conf(device_type: str) -> json.Data: """Get default configuration associated with provided device type""" if device_type == 'orchestrator': return hat.manager.devices.orchestrator.default_conf if device_type == 'monitor': return hat.manager.devices.monitor.def...
47172d9631a797cafc70c696fa6361822c4bf761
55,004
def plot_cartmap(lvc_healpix_file, levels=[0.5, 0.9], angsize=3., tile_ra=None, tile_dec=None, targ_ra=None, targ_dec=None): """Plot the GW map with the DESI footprint in a Cartesian projection. Parameters ---------- lvc_healpix_file : str Relative or absolute path to LIGO/Virgo HEALPix ang...
ede5746a3fca4d7d341f1cfe957bda3af65ac7c9
55,006
import fnmatch def check_result_ignore(result, ignore_ranges): """ Determines if the result has to be ignored. Any result will be ignored if its origin matches any bear names and its SourceRange overlaps with the ignore range. Note that everything after a space in the origin will be cut away, so...
d7ae057d76c77b6c8e2582e9e929a6aa7ce9f4dc
55,008
def ckan_collect_packages(url, memcached_client=None, cache=0): """ collect CKAN packages :param url: the CKAN url, e.g., .../api/3/action/package_list :param memcached_client: pymemcache client for caching http response :param cache: cache results :return: a list of CKAN packages """ p...
3f1ff946a63ce7f775b28ea7381155e5634235d1
55,010
def process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (Dictionary) raw structured data to process Returns: Dictionary. Structured data with the following schema: { "uid": { "id": integer, "name...
b97d35b93ea08d6adcd69e0fa84c9b59be8d4419
55,011
def datasource(name='Alpha', location='https://asource.foo/', id_prefix='A'): """ Create a DataSource object """ return DataSource(id=name, name=name, id_prefix=id_prefix, location=location)
bf1a3a49bdb70d28f4864961ef8cd4c4483f788d
55,012
def all_protoform(d, var_names, Q = "wiekszosc", desc = 'most', classtoprint="class"): """ Funkcja wyznaczajoca stopnie prawdy dla wszystkich podumowań lingwistycznych (prostych i zlozonych) """ pp = [var_names[0] + "_low", var_names[0] + "_medium", var_names[0] + "_high"] qq = [var_na...
3611b8a37c2856bccf2fc9402caac2466801d783
55,013
def get_indexes_async(**kwargs): """Asynchronously retrieves the application indexes and their states. Identical to get_indexes() except returns an asynchronous object. Call get_result() on the return value to block on the call and get the results. """ def extra_hook(indexes): return [(_index_converter(i...
f9c7f9af1263139c0efe69f2b0d0ff8e9d1b9339
55,014
def compute_stats(a, cfg, lgth_corr_function): """ Computes and returns basic positional, length, coverage and GC info. This function MUST be run in order to obtain cov, GC & length statistics! (i.e. mean and SD over all contigs and genes) Args: a: lgth_corr_function: Returns: ...
cbf274800b2ac32eab4c7b5d3ad756c303ec46a1
55,015
def unf_deadoilviscosity_Beggs_cP(gamma_oil, t_K): """ Correlation for dead oil viscosity ref1 Beggs, H.D. and Robinson, J.R. “Estimating the Viscosity of Crude Oil Systems.” Journal of Petroleum Technology. Vol. 27, No. 9 (1975) return dead oil viscosity,cP gamma_oil, specific oil de...
02271d26bfe72d2fc70ec02d17723010c9135e25
55,016
async def get_active_user(current_user: User = Security(get_current_user)): """Проверка активный юзер или нет""" if not current_user.is_active: raise HTTPException(status_code=400, detail="Inactive user") return current_user
36ece075acfcc77516223add7d80aa847f3828d0
55,017
def get_tag_type(tagtype, pairs): """ Given a list of (word,tag) pairs, return a list of words which are tagged as nouns/verbs/etc The tagtype could be 'NN', 'JJ', 'VB', etc """ return [w for (w, tag) in pairs if tag.startswith(tagtype)]
383515704788e0fd6bcfd7d7f21e77be18397163
55,018
from typing import AnyStr import re def regexp(pattern: AnyStr, string: AnyStr) -> bool: """SQLite REGEXP implementation.""" if pattern is None or string is None: return False try: return re.search(pattern, string) is not None except re.error: return False
ed5cc3eca07e153cfd5610e237afb62a0cadcb0a
55,019
def sortable_header(parser, token): """ Parses a tag that's supposed to be in this format: {% sortable_header field title %} """ bits = [b.strip('"\'') for b in token.split_contents()] if len(bits) < 2: raise TemplateSyntaxError, "anchor tag takes at least 1 argument" try: ti...
ffe8c76541b638248a0a33069a432da1ae461dae
55,021
def Sqrt(a): """ Square root op. """ return np.sqrt(a),
58bad6cfa02f0da5fe6546a581d58fc201b0194c
55,023
def SinC(x, c): """A unified sine and inverse sine function for different signs of curvatures. This function is used in k-Stereographic model, a unification of constant curvature manifolds. Please refer to https://arxiv.org/abs/2007.07698 for more details. First-order expansion is used in order to cal...
b029973a3b71b3de0daababbd8439cac3616c969
55,024
from functools import reduce def create_slug(title): """ Generates an alias url for the article by its title. """ only_latin = translit_text(title.replace(' ', '-')) is_allowed = lambda ch: ch.isalpha() or ch.isdigit() or ch == '-' if not only_latin: return '' leave_allowed = redu...
889ae39fbc5a72457dbd4701b44da28928b97238
55,025
def plotOrbitsMissed(allObjects, orbits, testOrbits=None, columnMapping=Config.COLUMN_MAPPING): """ Plots orbits that have been missed (but were findable) in semi-major axis, inclination and eccentrity space. Parameters --------...
4f8d546a4281e2cf6f6ce7dbea0cfdb7f6aa4b09
55,026
def sample_parameters(samplers): """Samples params [key, val, ...] list based on the samplers.""" params = [] for param, sampler in samplers.items(): val = sampler_types[sampler.TYPE](sampler) is_composite = is_composite_sampler(sampler.TYPE) params.extend(val if is_composite else [p...
a6fed6cfd9eef57c9b96e6ced90d7770d69ea051
55,027
def findCmd(keyword): # type: (str) -> Optional[Type['Cmd']] """ Find and return a Cmd subclass for a given keyword. """ command_list = getCmdList() matching_cmds = [cmd for cmd in command_list if keyword in cmd.keywords] if len(matching_cmds) == 0: return None if len(matching_cmds) ...
7d75f71975745bf6b7a1d3f54c50e125c12e8eea
55,028
def asin(var): """ Returns variable representing asin applied to the input variable var """ result = Var(np.arcsin(var.val)) result.parents[var] = var.children[result] = 1 / np.sqrt(1 - var.val ** 2) return result
8d62c6ff9b7342cae40ecbad870f68616acd1619
55,029
def accounts_list(svc_rec=None, hostfilter=None, compromised=False): """Returns a list of accounts for a service or host Accepts: Service id, hostfilter, compromised Returns: [ service_id, ipv4, ipv6, hostname, account info... ] """ query = (db.t_accounts.f_services_id==db.t_services.id) if svc_rec is no...
ad3a2a0191c5a0a5117bdadb2ede37b5c727c440
55,030
def read_data_from(file_: str) -> list: """Read boarding pass data from file.""" with open(file_, "r") as f: return f.read().splitlines()
7315c4c284cdd2e9e1b66776c26eccabe13acdb4
55,031
def warm_t(t, t_ust, Tn): """ Уравнение ПП при нагревании, когда температура двигателя равна температуре окружающей среды. t - время t_ust - установившееся значение температуры Tn - постоянная времени нагревания """ return t_ust * (1 - np.exp(-1 * t / Tn))
212c3bd5fd60c8a41568ca936e690ee4a078774b
55,032
import torch def Pocm_Matmul(x, gammas, betas): """ :param x: an output feature map of a CNN layer [*, ch, T, F] :param gamma: [*, ch, ch] :param beta: [*, ch] :return: gamma * x + beta """ x = x.transpose(-1, -3) # [*, F, T, ch] gammas = gammas.unsqueeze(-3) # [*, 1, ch, ch] po...
325e0318254b008b84c505d1de4c7f5ab61d7099
55,034
def convert_heads_to_classy_model( state_dict, out_prefix, num_fc_layers, use_bn_head=False, use_bias_head_fc=True ): """ Convert an MLP head of 2 kinds: Type 1: FC only Type 2: FC -> RELU -> FC """ logger.info("Converting head...") converted_dict = {"block3-2": {"default_head": {}}} ...
0b8a542dc3395d1983b65599141f45d273d908a9
55,036
def sigmoid(Z): """Applies sigmoid function to an array/value Arguments --------- Z: float/int/array_like Original Value Returns ------- A: same shape as input Value after applying sigmoid function """ # return 1/(1+np.power(np.e, -Z)) return 1/(1 + np.exp(-Z) )
34d1aa9358397c069619f4fe868222a1bc37b98b
55,037
import urllib def _unicode_urlencode(params): """ A unicode aware version of urllib.urlencode. Borrowed from pyfacebook :: http://github.com/sciyoshi/pyfacebook/ """ if isinstance(params, dict): params = params.items() return urllib.urlencode([(k, isinstance(v, unicode) and v.encode('u...
537d969e55aba91390d75f1fb4e59a82b08f8de2
55,038
import ast def get_auxiliary_name(node: ast.AST, aux_symbol_id: str) -> str: """ Generates a name for auxiliary variables. :param node: the ast node that originates the auxiliary symbol :param aux_symbol_id: the id name of the auxiliary symbol :return: the unique name to the symbol. """ r...
d67fc8d70553265a7d5345e97877e07caf36e19a
55,039
import typing async def patch( url: URLTypes, *, data: RequestData = None, files: RequestFiles = None, json: typing.Any = None, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, stream: bool = False, auth: AuthTypes = None, allow_redi...
9c65d3b8deba8496dc4412210ebb7191d4157aa1
55,040
def blob(x): """Given an Nx3 matrix of blob positions and size, create N img_size x img_size images, each with a blob drawn on them given by the value in each row of x One row of x = [x,y,radius].""" y = np.zeros((x.shape[0], img_size, img_size)) for i, particle in enumerate(x): r...
8371c49c0e0ad50988925e12575ade4845abf40d
55,041
import zipfile def fetch_uci_words(): """ Returns UCI vocabulary text. """ data_path = check_fetch_uci_words() all_data = [] with zipfile.ZipFile(data_path, "r") as f: for name in f.namelist(): if ".txt" not in name: # Skip README continue ...
8c09098aeb950eceac42ce416a60e3a411265d42
55,042
def search_for_pod_name(details: dict, operator_id: str): """Get operator pod name. Args: details (dict): workflow manifest from pipeline runtime operator_id (str): operator id Returns: dict: id and status of pod """ try: if 'nodes' in details['status']: ...
cc5bc532a1875145452fbe71cca54f840257c90d
55,043
def edit_dict_from_dict( old_embed_dict: dict, update_embed_dict: dict, add_attributes: bool = True, inner_fields: bool = False, ): """ Edits the changed attributes of an embed dictionary using another dictionary """ if inner_fields: if "fields" in old_embed_dict: ...
12d1314b2dfdbf01809fabf729a1f48732bd57e6
55,044
def humanize_demarche_names(name: str) -> str: """ >>> humanize_demarche_names('argent') "ARGENT: Crédit immobilier, Impôts, Consommation, Livret A, Assurance, " "Surendettement…" :param machine_names: :return: list of human names and description """ demarches = settings.DEMARCHE...
16b2d163adebc7f1dd6dfb50089c3bf831765a6b
55,045
def get_product_yield(product: reaction_pb2.ProductCompound, as_measurement: bool = False): """Returns the value of a product's yield if it is defined. If multiple measurements of type YIELD exist, only the first is returned. Args: product: ProductCompound message. as_...
01c6c7243d8ccd9b2ec25672ed06727d0324ef5f
55,046
def test_for_short_cell(raw_python_source: str) -> bool: """ Returns True if the text "# Long" is in the first line of `raw_python_source`. False otherwise. """ first_element = raw_python_source.split("\n")[0] if "#" in first_element and "short" in first_element.lower(): return True ...
f76c19750afda8851dfe328851662fa3276f3529
55,047
def generate_paths(G, od_pairs, k=10, weight=None): """ Generates k shortest paths from origin 'o' to destination 'd' for all origin destination pairs Args: G - graph of network od_pairs - list of origin-destination pairs k - max number of paths returned weight - par...
c7f4ca676bbb068b74cc1ece13b71429ac567a5a
55,050
import math def area_circle(radius): """ Calculate the area of a circle >> area_circle(20) 1256.6370614359173 """ return math.pi * radius * radius
978dc9252c48fd288d348316604910712c5b8b2b
55,051
def sum_missing_formula(base): """Define a biomass reaction whose components lack a formula.""" met_a = cobra.Metabolite("lipid_c", "H744") met_b = cobra.Metabolite("protein_c", "H119") met_c = cobra.Metabolite("rna_c") met_d = cobra.Metabolite("dna_c") met_e = cobra.Metabolite("ash_c", None) ...
a4167ef86be03cf449bb3f4fe902bac5a1f57412
55,052
import inspect def _get_warnings(warnings_instance): """ returns a list of the returned value of all private functions of warnings_instance """ # all functions of this class warning_functions = inspect.getmembers( warnings_instance.__class__, predicate=inspect.isfunction ) # al...
3152273a7eb2c78b612b1e35506163bce6a42f24
55,054
def make_embed_b(m, msg_type="banned"): """Create an embed for bans.""" title = "%s User __%s__ %s" % (msg_icon(msg_type), m.name, msg_type) embed = discord.Embed(title=title, description="", color=msg_color(msg_type)) return embed.set_footer(text="ID...
ca6fa9845fcad617be3f42b9f2042066f99747a2
55,055
def _get_year_month(file_name): """ Extract year and month from file name and concatenate to year-month string """ ym = file_name.replace('.csv', '') year, ita_month = ym.split("_")[-2:] month = [k for k, v in ITA_MONTHS.items() if v == ita_month][0] return year + "-" + month
f698529dd72d2455808aa4966f8e50a1c0b04f4a
55,056
import collections def windowed_slope_sum_function(fitered_bp_vector, window_length): """see the mathematical description of this algorithm in: An Open-source Algorithm to Detect Onset of Arterial Blood Pressure Pulses """ # this could be replaced with simple pointer manipulation, but this is easi...
730431f665589cecf32655e6f4d14a0f9cbb2290
55,057
import re def color(string: str) -> Color: """ Parse color string like a "#007fff" >>> color('#007fff') (0, 127, 255) >>> color('#000000') (0, 0, 0) >>> color('#fFfFfF') (255, 255, 255) >>> color('#1234567') Traceback (most recent call last): ... TypeError: "#1234567" i...
9fa59b23cc5b1375d549eab046a0ba1a350a00a2
55,058
def api_upload(request): """POST - Upload API.""" upload = Upload(request) resp, code = upload.upload_api() return make_api_response(resp, code)
baade870b77f6aa401b0fd6d3d654f90f3b4735e
55,059
def filter_count_df(count_df, min_read_mean, outdir_path): """ :return: filtered count dataframe """ check_sparse = stats.Density(count_df) filtering = MeanFiltering(count_df, threshold=min_read_mean) count_df = filtering.filtered_df filtered_stats = stats.Descriptive(count_df, outdir_path) ...
0130046812c8746e8cd75d031ecf77edb46860bc
55,060
import codecs def load_dataset(dataset_file): """ Loads a dataset file :param dataset_file: the file path :return: a list of dataset instances, (x, y, relation) """ with codecs.open(dataset_file, 'r', 'utf-8') as f_in: dataset = [tuple(line.strip().split('\t')) for line in f_in] ...
3f19a367b27c6dd123498e8cf73dee5d54454a2b
55,061
def get_vm_identifiers(wireserver_connection): """Get the ContainerId and InstanceId from the Wireserver.""" wireserver_connection.request( 'GET', '/machine?comp=goalstate', headers={'x-ms-version': '2012-11-30'} ) resp = wireserver_connection.getresponse() wireserver_goal...
e1629b4e87c106e71437273ef742cb43f5e275f8
55,062
import string import random def generate_random_name(seed_name: str): """ Function responsible for generating random names using Markov chain Args: seed_name (str): name of the seed file contained in name_generator directory Returns: random_name (str): string generated procedurally ba...
1f3ada644a9bea27a3b908a6fb857f43b3d2349b
55,063
def check_updates(version: str, user: str, repository: str) -> (bool, str): """ Checks if a newer version exists for a program at the given version, on github :param version: current program version :param user: the user who owns the repository :param repository: the repository where the code is hos...
f4c669b7050e66b877371480ca01786535c72a68
55,064
def readxmol(ifile,elem,xyz): """ read xmol file """ lines = ifile.readlines() nat = int(lines[0]) title = lines[1] for l in lines[2:]: type, x, y, z = l.split() xyz.append([float(x),float(y),float(z)]) elem.append(type) # xyz.append(l) return nat
62be4300fcf30f3b2dee329418352230639ef7a1
55,065
def euro_implied_vol_76(option_type, fs, x, t, r, cp): """Implied volatility calculator for European commodity options. Args: option_type (str): Type of the option. "p" for put and "c" for call options. fs (float): Price of underlying asset. x (float): Strike price. t (float): T...
fc1ab11f41d08cacedde466d9e1775488b48eb11
55,067
def delete(book_id): """ Delete A Blogpost """ post = BookModel.get_one_book(book_id) if not post: return custom_response({'error': 'post not found'}, 404) data = book_schema.dump(post).data post.delete() return custom_response({'message': 'deleted'}, 204)
427d2ca79c4155572d7916f426278fafed9085f3
55,068
def points_in_polygon(outline,qx,qy): """ Get points that are within the given polygon. Returns the index list. poly: list of (x,y) points that define the polygon qx,qy: list of the x and y coordinats of the points that are to be checked. ===RETURNS=== ix,iy: indices of x and y for ...
f644786a0448d937368681ed83185a96de014c0c
55,069
from datetime import datetime def json_dump_default(value): """ Default JSON serializer. """ if isinstance(value, Decimal): return float(value) elif isinstance(value, (date, datetime)): return value.isoformat() elif hasattr(value, 'serialize') and callable(value.serialize): r...
ae11f85db2d1e4e1954e70015cddec4dc9425822
55,070
import torch def get_model(args): """Build the model.""" print_rank_0('building GPT2 model ...') model = GPT2Model(num_layers=args.num_layers, vocab_size=args.vocab_size, hidden_size=args.hidden_size, num_attention_heads=args.num_attention...
477a5c2523633fda1e5c991c1fea3b37629f191e
55,072
def dicts_to_matched_tuples(dict1, dict2): """ Converts pair of dicts to pair of matched tuples so that their elements can be compared. Throws an exception if the set of keys in both dicts are not the same. """ try: return [(dict1[k], dict2[k]) for k in set(dict1.keys() + dict2.keys())] ...
496dba21da3766db49934761fd8ec142aed0f1ab
55,073
def transcriptsKnownSpliceSites(refs_1exon_by_chr, refs_exons_by_chr, start_ends_by_gene, trec, genome_dict, nPolyA): """ :param refs_1exon_by_chr: dict of single exon references (chr -> IntervalTree) :param refs_exons_by_chr: dict of multi exon references (chr -> IntervalTree) :param trec: id record (g...
56f602eae34c7b756fa7a0eeb9899000cee50744
55,074
def translate(rna): """ Translate RNA sequence into Protein sequence Starting from the first nucleotides """ codons = read_codons(join(MODULE_DIR, "codon.txt")) protein = "" for i in range(0, len(rna), 3): base = rna[i : i + 3] if len(base) != 3 or codons[base] == "Stop": ...
466dc7b0edc60900110429b860fe8d0d2f2bae07
55,075
def int_parameter(level, maxval): """Scale 'val' between 0 and maxval. :param level: Level of the operation that will be between [0, 'PARAMETER_MAX']. :type level: int :param maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. :type maxval: int :return...
f69595c999e8fa0b2d4b3854e43bd88ccb646e81
55,076
def key(profile): """Get the last name in lower case""" return profile["name"].split(' ')[-1].lower()
dd778619f601213f3cbae3504277fe6ee21ba3cd
55,077
from typing import Tuple from typing import List def _rewrite_jaxpr(jaxpr: core.Jaxpr, has_input_token: bool, has_output_token: bool) -> Tuple[core.Jaxpr, bool]: """Rewrite a Jaxpr to thread the token, if needed.""" assert has_input_token or not has_output_token if not has...
7a4a4fbe1441c961df622e364bd7824a05730881
55,078
def create(data, row_ticks, col_ticks, ax=None, cbar_kw={}, cbarlabel="", cbarpos=(0.95, 0.9), row_label=None, row_label_pos=(-0.083, 1.02), col_label=None, col_label_pos=None, reverse=True, **kwargs): """ Create a heatmap from a numpy array and two lists of labels. Follows: https://matplotlib.o...
8b74e54601f51fb8f9821aa47ae81160395533df
55,079
def LF_consistency_in_report(x): """ The words 'clear', 'no', 'normal', 'free', 'midline' in findings section of the report """ findings = x.text[x.text.find("FINDINGS:") :] findings = findings[: findings.find("IMPRESSION:")] sents = findings.split(".") normalcy_words = ["clear", "no", ...
423843f214e3805820a230cf7a82e666e42b3bbc
55,080
def split_by_hw(mdl: Model, x_attack: np.array, y_attack: np.array): """ Split traces in two classes. Class A: the hamming weight label is below 4, and class B: above 4. Returns traces for classes A and B """ hws = np.argmax(y_attack, axis=1) l4 = predict(mdl, x_attack[np.where(hws < 4)], ...
1a60b8f5c7ebaa205e0c946263855361b888b7a0
55,081
def remove_anthrophony(ale, time_delta, freq_delta, cutoffs=(1000, 11000)): """ Removes anthrophony from a PSD spectrogram Parameters ---------- ale: numpy float64 array a 3d array (channels, frequency bands, time steps) representing the spectrogram of a wave signal (with ale ap...
e247449e89f91fe9f78134110493e73287870469
55,082
def collect_data(data_file): """ Sets up Data Object using data :return: Pandas DataFrame created from data_file data """ dat = Table.read(data_file, format='fits') df_bytes = dat.to_pandas() # Convert to pandas dataframe df = pd.DataFrame() # Init empty dataframe for converted types...
bc3d2b2157e520338530a98471da57daa595ddfe
55,083
def objectToTypes(object,world=None): """Returns a string defining the type of the given Python Klamp't object. If multiple types could be associated with it, then it returns a list of all possible valid types.""" if hasattr(object,'type'): return object.type if isinstance(object,ContactPoin...
2c76334ecd1351df521aed4ec717f803dbea3e86
55,084
def setup_file_explorer(qtbot): """Set up FileExplorerTest.""" widget = FileExplorerTest() qtbot.addWidget(widget) return widget
76637bfd13513091c0d66c0780b8cb32ab9122ba
55,085
def solution(a: list, k: int) -> list: """ >>> solution([], 0) [] >>> solution([], 100) [] >>> solution([1] * 100, 100) == [1] * 100 True >>> solution([1, 3], 1) [3, 1] >>> solution([1, 3], 2) [1, 3] :param a: An array of integers :param k: Number of rotations :r...
f1ff42df2ec1181357732ea7910b8994099dfa65
55,086
def compute_radius(X, max_x, max_y): """Compute the radius of a chip coordinate. """ center = [max_x / 2.0, max_y / 2.0] return np.sqrt((X.ix[:,0] - center[0])**2 + (X.ix[:,1] - center[1])**2)
aa4771f5e0b4bfc4393f6cb00a5cd497d28026da
55,087
def tx_or_block_from_bytes(data: bytes) -> BaseTransaction: """ Creates the correct tx subclass from a sequence of bytes """ # version field takes up the first 2 bytes version = int.from_bytes(data[0:2], 'big') try: tx_version = TxVersion(version) cls = tx_version.get_cls() r...
b863dcfc5980d3cda0c910175900d3fc4141b30c
55,088
from typing import Tuple def new_tile( *, # Enforce the use of keywords, so that parameter order doesn't matter. walkable: int, transparent: int, dark: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]], light: Tuple[int, Tuple[int, int, int], Tuple[int, int, int]], ) -> np.ndarray: """He...
1f138058d8f005674ec766ab35e2de4c473c8739
55,089
def density(x): """ Standard set of parameters for density remap. Parameters ---------- x : numpy.ndarray Returns ------- numpy.ndarray """ return _clip_cast(amplitude_to_density(x))
cc1f3a37010ceefb74106c7f7ec5e6bfffd44661
55,090