content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def first(id_): """The first service of the station.""" return jsonify( [ (n.removeprefix("_"), t) for n, t in r.zrange(f"Station:_{id_}:first", 0, -1, withscores=True) ] )
5de7ef49c1deb0edea3f3d4ddcc30da8c4ae2d3a
9,900
def sample(df, n, shape): """ randomly sample patch images from DataFrame Parameters ---------- df : pd.DataFrame DataFrame containing name of image files n : int number of patches to extract shape : list shape of patches to extract Returns ------- image...
a0f655ad71a7ef47c71ecc23f45365f721bc2085
9,901
def bitsizeof_varint32(value: int) -> int: """ Gets bit size of variable 32-bit signed integer value. :param value: Value to use for bit size calculation. :returns: Bit size of the value. :raises PythonRuntimeException: Throws if given value is out of range for varint32 type. """ return _b...
16fd942d23b6ec26a300119e56fbbad6f37a203d
9,902
import requests import json def slack(channel, message, subject=''): """ Sends a notification to meerkat slack server. Channel is '#deploy' only if in live deployment, otherwise sent privately to the developer via slackbot. Args: channel (str): Required. The channel or username to which the ...
274111901fd3b7545c8e2128ce3e98716eca8406
9,903
def compute_similarity(img_one,img_two): """Performs image resizing just to compute the cosine similarity faster Input: Two images Output: Cosine Similarity """ x = cv2.resize(img_one, dsize=(112, 112), interpolation=cv2.INTER_CUBIC) y = cv2.resize(img_two, dsize=(112, 112), int...
24d02db8c685480572fae2ab02f9648e3798fdf3
9,904
def get_results_from_firebase(firebase): """ The function to download all results from firebase Parameters ---------- firebase : pyrebase firebase object initialized firebase app with admin authentication Returns ------- results : dict The results in a dictionary with t...
ca06c24367d778d4b601eab6fa31009fe6ecb372
9,905
def mtci_vi(imgData, wave, mask=0, bands=[-1,-1,-1]): """ Function that calculates the MERIS Terrestrial Chlorophyll Index. This functions uses wavelengths 753.75, 708.75, and 681.25 nm. The closest bands to these values will be used. Citation: Dash, J. and Curran, P.J. 2004. The MERIS terrestrial chlo...
b1f88d2041d8cf9fa645316b47db472e3626f1f8
9,906
def GetSourceFile(file, sourcepath): """Return a relative file if it is embedded in a path.""" for root in sourcepath: if file.find(root) == 0: prefix_length = len(root) if not root.endswith('/'): prefix_length += 1 relative_file = file[prefix_length:] return relative_file retu...
b241497131c3595f78ebf9d1481c8d9d50887e5a
9,907
import os import subprocess def trace_cmd_installed(): """Return true if trace-cmd is installed, false otherwise""" with open(os.devnull) as devnull: try: subprocess.check_call(["trace-cmd", "options"], stdout=devnull) except OSError: return False return True
7135c0b2ebfa46b69df5b692178e6b569d3014dd
9,908
import configparser import sys def getmessage(msg_type) : """ Renvoie le message qui doit être affiché """ cfg = configparser.ConfigParser() cfg.read(clt_path) if not msg_type in cfg.options('Messages') : sys.stderr.write("{} is not a valide type message : {}".format(msg_type, cfg.options('Mes...
5e751d2f1a5df998f409f07f191f759e935a8b9d
9,909
def refine_gene_list(adata, layer, gene_list, threshold, return_corrs=False): """Refines a list of genes by removing those that don't correlate well with the average expression of those genes Parameters ---------- adata: an anndata object. layer: `str` or None (default: `None`) ...
0b26b5265bf62a6f771bb762cd3c497fa628c5c3
9,910
def shape_to_coords(value, precision=6, wkt=False, is_point=False): """ Convert a shape (a shapely object or well-known text) to x and y coordinates suitable for use in Bokeh's `MultiPolygons` glyph. """ if is_point: value = Point(*value).buffer(0.1 ** precision).envelope ...
1b585f6bb9831db63b2e0e8c52b6fb29ba0d9ab9
9,911
import argparse def get_args(): """ Supports the command-line arguments listed below. """ parser = argparse.ArgumentParser( description='Test Runner script') parser.add_argument('-c', '--controller', type=str, required=True, help='Controller host name') parser.add_argument('-s', '--se...
8bb488e026c13ddc008ea2877b1d0ae9f904f970
9,912
def max_union(map_list): """ Element-wise maximum of the union of a list of HealSparseMaps. Parameters ---------- map_list : `list` of `HealSparseMap` Input list of maps to compute the maximum of Returns ------- result : `HealSparseMap` Element-wise maximum of maps ...
169fef50486e22468f8942f6968630e8fdef6648
9,913
def getDtypes(attributes, forecastHorizon): """ Auxillary function to generate dictionary of datatypes for data queried from dynamo. Parameters ---------- attributes : list, Attributes queried from dynamo. forecastHorizon : integer, Number of forecast horizons which have been qu...
4974b7fe8107b36556da41173508c908785ddf5f
9,914
def cazy_synonym_dict(): """Create a dictionary of accepted synonms for CAZy classes.""" cazy_dict = { "Glycoside Hydrolases (GHs)": ["Glycoside-Hydrolases", "Glycoside-Hydrolases", "Glycoside_Hydrolases", "GlycosideHydrolases", "GLYCOSIDE-HYDROLASES", "GLYCOSIDE-HYDROLASES", "GLYCOSIDE_HYDROLASES", "GL...
0d635075901cc3e6ba7b432c68e5be3f7d2c34d6
9,915
def new_oauth2ProviderLimited(pyramid_request): """this is used to build a new auth""" validatorHooks = CustomValidator_Hooks(pyramid_request) provider = oauth2_provider.OAuth2Provider( pyramid_request, validator_api_hooks=validatorHooks, validator_class=CustomValidator, serv...
ef15f43dfa0549431931210d788fd8ccde611634
9,916
def rand_color(red=(92, 220), green=(92, 220), blue=(92, 220)): """ Random red, green, blue with the option to limit the ranges. The ranges are tuples 0..255. """ r = rand_byte(red) g = rand_byte(green) b = rand_byte(blue) return f"#{r:02x}{g:02x}{b:02x}"
43244b5912585a4496abbd6868f97a368fd785f0
9,917
import base64 def tile_to_html(tile, fig_size=None): """ Provide HTML string representation of Tile image.""" b64_img_html = '<img src="data:image/png;base64,{}" />' png_bits = tile_to_png(tile, fig_size=fig_size) b64_png = base64.b64encode(png_bits).decode('utf-8').replace('\n', '') return b64_im...
9e22304c9ee44a850e17930088b0fc81b390fded
9,918
def generate_buchwald_hartwig_rxns(df): """ Converts the entries in the excel files from Sandfort et al. to reaction SMILES. """ df = df.copy() fwd_template = '[F,Cl,Br,I]-[c;H0;D3;+0:1](:[c,n:2]):[c,n:3].[NH2;D1;+0:4]-[c:5]>>[c,n:2]:[c;H0;D3;+0:1](:[c,n:3])-[NH;D2;+0:4]-[c:5]' methylaniline = '...
80351743c2f651965735f38b514d7af017fc25ce
9,919
from niworkflows.engine.workflows import LiterateWorkflow as Workflow from niworkflows.interfaces.fixes import FixHeaderApplyTransforms as ApplyTransforms from niworkflows.interfaces.itk import MultiApplyTransforms from niworkflows.interfaces.utility import KeySelect from niworkflows.interfaces.nibabel import GenerateS...
5953ae62d40002283b41b4289fc45b96b50e319c
9,920
def _get_indent(node): """Determine the indentation level of ``node``.""" indent = None while node: indent = find_first(node, TOKEN.INDENT) if indent is not None: indent = indent.value break node = node.parent return indent
ed54eb8c1ea227534af0a3bd8eda9ab9089755d7
9,921
def distancesarr(image_centroid, object_centroids): """gets the distances between image and objects""" distances = [] j = 0 for row in object_centroids: distance = centroid_distance(image_centroid, object_centroids, j) distances.append(distance) j +=1 return distances
7abae0c58a2cc672b789d4c8620878b7e3b46375
9,922
def obs_agent_has_neighbour(agent_id: int, factory: Factory) -> np.ndarray: """Does this agent have a neighbouring node?""" agent: Table = factory.tables[agent_id] return np.asarray( [ agent.node.has_neighbour(Direction.up), agent.node.has_neighbour(Direction.right), ...
d91b4d7eabcac6ed71149ad9220c2594e5054e36
9,923
def P_split_prob(b): """Returns the probability of b according to the P_split() distribution. """ """n = b.length if n <= 2: p = 1.0 else: k = 1 # si el arbol es binario y n > 2 seguro que tiene que ser splittable. #while k < n and not b.splittable(k): while n...
94577a96e926686107a154aa82d55ceef6b9ab24
9,924
def t(): """Or time(). Returns the number of seconds elapsed since the cartridge was run.""" global begin return py_time.time() - begin
1b43767629c9585fcd29c1293ee043a189332ed7
9,925
import sys def data_provider(data_provider_function, verbose=True): """PHPUnit style data provider decorator""" def test_decorator(test_function): def new_test_function(self, *args): i = 0 if verbose: print("\nTest class : " + get_class_that_defined_method(te...
a291b715c18afd9af877dc8d7efa35a48a2c2365
9,926
import argparse def main(): """Console script for ceda_intake.""" parser = argparse.ArgumentParser() parser.add_argument('--test', dest='test_mode', action='store_true', help='Create small catalog in test mode') parser.add_argument('-p', '--project', type=str, required=True, ...
fe98c133afbdf75fce18e2d21e60d8b3a414ee0f
9,927
from typing import Any def convert_none( key: str, attr_type: bool, attr: dict[str, Any] = {}, cdata: bool = False ) -> str: """Converts a null value into an XML element""" key, attr = make_valid_xml_name(key, attr) if attr_type: attr["type"] = get_xml_type(None) attrstring = make_attrstr...
c04efd6ed52cb092d6987f627b7222668da32dfd
9,928
def is_title(ngram, factor = 2.0): """ Define the probability of a ngram to be a title. Factor is for the confidence coex max. """ confidence = 1 to_test = [n for n in ngram if n not in stop_words] for item in to_test: if item.istitle(): confidence += factor / len(to_test) # p...
678959cdafc966d05b5ef213b0727799f20a8e0f
9,929
import os import base64 def img_to_b64(img_path): """显示一副图片""" assert os.path.isfile(img_path) with open(img_path, 'rb') as f: img = f.read() b64 = base64.b64encode(img) return b64
6ab67dc503c7bf077fb8772b1c5708eb10efe7e7
9,930
def ul(microliters): """Unicode function name for creating microliter volumes""" if isinstance(microliters,str) and ':' in microliters: return Unit(microliters).to('microliter') return Unit(microliters,"microliter")
4d5d489191166a76e02cdc0211d52bec45cd65e1
9,931
def read_glh(filename): """ Read glitch parameters. Parameters ---------- filename : str Name of file to read Returns ------- glhParams : array Array of median glitch parameters glhCov : array Covariance matrix """ # Extract glitch parameters glh...
6948e0f5571c6d5f7a62dad1fb136cec48e476ae
9,932
def update_user_group(user_group_id, name, **options): """ Update a user group :param user_group_id: The id of the user group to update :type user_group_id: str :param name: Name of the user group :type name: str, optional :param options: ...
20784b935675c459b7dc258c210aedd86d7b4fb9
9,933
def longitudinal_kmeans(X, n_clusters=5, var_reg=1e-3, fixed_clusters=True, random_state=None): """Longitudinal K-Means Algorithm (Genolini and Falissard, 2010)""" n_time_steps, n_nodes, n_features = X.shape # vectorize latent positions across time X_vec = np.moveaxis(X, 0, -1)....
a76581a7784480fa90afa9ab9e080a09ce5662f4
9,934
import decimal def do_payment( checkout_data, # Dict[str, str] parsed_checkout, # Dict[str, str] enable_itn, # type: bool ): # type: (...) -> Dict[str, str] """ Common test helper: do a payment, and assert results. This takes a checkout's data and page parse (for session info ...
f69383f779ce68ef28ced79d794479a4e3a4dff9
9,935
from sphinx_astropy import __version__ as sphinx_astropy_version # noqa def ensure_sphinx_astropy_installed(): """ Make sure that sphinx-astropy is available. This returns the available version of sphinx-astropy as well as any paths that should be added to sys.path for sphinx-astropy to be available...
f20911b11beaf3483d1f2f829c63d654cb0557ef
9,936
def SPEED_OF_LIGHT(): """ The `SPEED_OF_LIGHT` function returns the speed of light in vacuum (unit is ms-1) according to the IERS numerical standards (2010). """ return 299792458.0
5f0b6e6fb81018983d541a6492eb2c5aac258ff6
9,937
from typing import Optional import abc import math from typing import Tuple def odd_factory(NATIVE_TYPE): # pylint: disable=invalid-name """ Produces a Factory for OddTensors with underlying tf.dtype NATIVE_TYPE. """ assert NATIVE_TYPE in (tf.int32, tf.int64) class Factory: """ Represents a nativ...
c8e55e3d5ad16568dbdadca9430d890bb4299e5e
9,938
def filter_by_is_awesome(resources): """The resources being that is_awesome Arguments: resources {[type]} -- A list of resources """ return [resource for resource in resources if resource.is_awesome]
46717a93e75dfed53bba03b5b7f8a5e8b8315876
9,939
def topograph_image(image, step): """ Takes in NxMxC numpy matrix and a step size and a delta returns NxMxC numpy matrix with contours in each C cell """ step_gen = _step_range_gen(step) new_img = np.array(image, copy=True) """step_gen ~ (255, 245, 235, 225,...) """ def myfunc(color):...
c3a340c422bb16de83b132506e975fecf21a335c
9,940
def _etag(cur): """Get current history ETag during request processing.""" h_from, h_until = web.ctx.ermrest_history_snaprange cur.execute(("SELECT _ermrest.tstzencode( GREATEST( %(h_until)s::timestamptz, (" + _RANGE_AMENDVER_SQL + ")) );") % { 'h_from': sql_literal(h_from), 'h_until': sql_li...
bd04dca4ef140003c0df867fa258beb5c60c77dd
9,941
import requests import time def send_request(url, method='GET', headers=None, param_get=None, data=None): """实际发送请求到目标服务器, 对于重定向, 原样返回给用户 被request_remote_site_and_parse()调用""" final_hostname = urlsplit(url).netloc dbgprint('FinalRequestUrl', url, 'FinalHostname', final_hostname) # Only external in...
b7ab08d5157964d03089c4db1a64b4f6461b3fe9
9,942
def MakeListOfPoints(charts, bot, test_name, buildername, buildnumber, supplemental_columns): """Constructs a list of point dictionaries to send. The format output by this function is the original format for sending data to the perf dashboard. Args: charts: A dictionary of chart names...
fe903667b0e3a4c381dbcbc3205ba87b2d0ef26b
9,943
import csv from io import StringIO def parse_csv(string): """ Rough port of wq/pandas.js to Python. Useful for validating CSV output generated by Django REST Pandas. """ if not string.startswith(','): data = [] for row in csv.DictReader(StringIO(string)): for key, val ...
bdf32e3ff1a2d63c568200e75d5f694ef5f49ce9
9,944
def list_system_configurations(): """ List all the system configuration parameters Returns: .. code-block:: python [ { "ParameterName": "ParameterValue" }, ... ] Raises: 500 - ChaliceViewError...
5989cc6f1bd79e5f7bd4889883dccb7fa9bf1bd4
9,945
def add_dbnsfp_to_vds(hail_context, vds, genome_version, root="va.dbnsfp", subset=None, verbose=True): """Add dbNSFP fields to the VDS""" if genome_version == "37": dbnsfp_schema = DBNSFP_SCHEMA_37 elif genome_version == "38": dbnsfp_schema = DBNSFP_SCHEMA_38 else: raise ValueEr...
f3c652c77858b9e859bd47e48002a1de3d865fa0
9,946
import bisect def look_for_time_position(target, source, begin_pos=0): """ Given a time stamp, find its position in time series. If target does NOT exist in source, then return the value of the smallest time point that is larger than the given target. Parameters ------------- target : Dat...
352e2e2aa0081926894867e0e6b67a5452685323
9,947
import torch def get_wav2vec_preds_for_wav( path_to_wav: str, model, processor, device: torch.device, bs: int = 8, loading_step: float = 10, extra_step: float = 1, ) -> str: """ Gets binary predictions for wav file with a wav2vec 2.0 model Args: path_to_wav (str): abso...
2f9abc97559d1853631dcdf79599190714f618c8
9,948
import jinja2 import sys def get_template(parsed_args): """Initialize jinja2 and return the right template""" env = jinja2.Environment( loader=jinja2.PackageLoader(__name__, TEMPLATES_PATH), trim_blocks=True, lstrip_blocks=True, ) # Make the missingvalue() function available in the tem...
2fb7c683cd660a92b542bdfdb973c91c0dafbb10
9,949
import logging def get_node_cmd(config): """ Get the node CLI call for Least Cost Xmission Parameters ---------- config : reVX.config.least_cost_xmission.LeastCostXmissionConfig Least Cost Xmission config object. Returns ------- cmd : str CLI call to submit to SLURM e...
b81fb7d6c06122122a8a4ec1cc2b5bc4724948a6
9,950
def header_lines(filename): """Read the first five lines of a file and return them as a list of strings.""" with open(filename, mode='rb') as f: return [f.readline().decode().rstrip() for _ in range(5)]
35056152c1566ea2d14452308f00d6903b6e4dff
9,951
import sys from meerschaum.utils.debug import dprint def deactivate_venv( venv: str = 'mrsm', color : bool = True, debug: bool = False ) -> bool: """ Remove a virtual environment from sys.path (if it's been activated). """ global active_venvs if venv is None: r...
6938497201d2e8f78b64b709a1e7b9191048e1c7
9,952
async def load_last_cotd(chat_id: int): """Load the time when the user has last received his card of the day. Args: chat_id (int): user chat_id """ QUERY = "SELECT last_cotd FROM users WHERE id = %(id)s" async with aconn.cursor() as cur: await cur.execute(QUERY, {"id": chat_id}) ...
2e2aabc18a014e9f96fee91f6e8d85b875edcf2a
9,953
from pathlib import Path import json import torch def load_model(targets, model_name='umxhq', device='cpu'): """ target model path can be either <target>.pth, or <target>-sha256.pth (as used on torchub) """ model_path = Path(model_name).expanduser() if not model_path.exists(): raise No...
8fdafa6ac28ed2277337dc1f3ded295668963c8a
9,954
from typing import Callable from typing import Optional from typing import Tuple from typing import List import scipy def model_gradient_descent( f: Callable[..., float], x0: np.ndarray, *, args=(), rate: float = 1e-1, sample_radius: float = 1e-1, n_sample_point...
d5bd32f21cdc871175c3f4c1601c1da240866e14
9,955
def index(): """Show the index.""" return render_template( "invenio_archivematica/index.html", module_name=_('Invenio-Archivematica'))
9c5e62bc29466bd4eae463d1dcd71c0d880fc5f8
9,956
from sys import path def get_functions_and_macros_from_doc(pmdk_path): """ Returns names of functions and macros in a list based on names of files from the doc directory. """ path_to_functions_and_macros = path.join(pmdk_path, 'doc') functions_and_macros_from_doc = [] for _, _, files in wa...
d234c7fb445574522b103ec39f8c478806588fbc
9,957
def kmv_tet_polyset(m, mf, mi): """Create the polynomial set for a KMV space on a tetrahedron.""" poly = polynomial_set(3, 1, m) # TODO: check this for axes in [(x[0], x[1]), (x[0], x[2]), (x[1], x[2]), (x[1] - x[0], x[2] - x[0])]: b = axes[0] * axes[1] * (1 - axes[0] - axes[1]) for i i...
cbf87063e6ae6523acf897d6e03fd288f48e04e6
9,958
import re def word_detokenize(tokens): """ A heuristic attempt to undo the Penn Treebank tokenization above. Pass the --pristine-output flag if no attempt at detokenizing is desired. """ regexes = [ # Newlines (re.compile(r'[ ]?\\n[ ]?'), r'\n'), # Contractions (re....
577c2ed235aaf889699efc291d2b206a922f1f4a
9,959
def googlenet_paper(pretrained=False, **kwargs): """ GoogLeNet Model as given in the official Paper. """ kwargs['aux'] = True if 'aux' not in kwargs else kwargs['aux'] kwargs['replace5x5with3x3'] = False if 'replace5x5with3x3' not in kwargs \ else kwargs['replace5x5with3x3'] ...
01eaf2cf89648b334f634e83ca2d774e58970999
9,960
import argparse def get_parser(): """ Parses the command line arguments .. todo:: Adapter services related to alerts/messaging, and local device/Edge management :returns: An object with attributes based on the arguments :rtype: argparse.ArgumentParser """ parser = argparse.Argumen...
1765c6021e4ad7175ccc54d27e9c5a71bda645e9
9,961
import os def get_prefix(path): """Generate a prefix for qresource in function of the passed path. Args: path (str): Relative path of a folder of resources from project dir. Returns; str: Prefix corresponding to `path` """ # Remove finishing separator from path if exist if p...
e412826cbc0ae631e5084a6619b73912cdd0ce40
9,962
def is_regex(obj): """Cannot do type check against SRE_Pattern, so we use duck typing.""" return hasattr(obj, 'match') and hasattr(obj, 'pattern')
cfd4fc702fb121735f49d4ba61395ce8f6508b1a
9,963
import functools def GetDefaultScopeLister(compute_client, project=None): """Constructs default zone/region lister.""" scope_func = { compute_scope.ScopeEnum.ZONE: functools.partial(zones_service.List, compute_client), compute_scope.ScopeEnum.REGION: functools.partial(regions_servi...
25069007b68a74b26e2767e146c25466b65e3377
9,964
def find_user(username): """ Function that will find a user by their username and return the user """ return User.find_by_username(username)
ef036f0df72bbdcb9aa8db519120209e20678e83
9,965
from typing import List def filter_by_author(resources: List[Resource], author: Author) -> List[Resource]: """The resources by the specified author Arguments: resources {List[Resource]} -- A list of resources """ return [resource for resource in resources if resource.author == author]
d03673ed8c45f09996e29eb996fc31fa3d073315
9,966
import time def cpu_bound_op(exec_time, *data): """ Simulation of a long-running CPU-bound operation :param exec_time: how long this operation will take :param data: data to "process" (sum it up) :return: the processed result """ logger.info("Running cpu-bound op on {} for {} seconds".form...
a52d3e25a75f9c7b0ab680a9ad1cb0e5d40de92a
9,967
def elastic_transform_approx( img, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, value=None, random_state=None, ): """Elastic deformation of images as described in [Simard2003]_ (with modifications for speed). Based on https://gis...
9684847e756e0299be6766b5bb8220e6a1b4fc8d
9,968
def uncompleted_task(request): """ Make the completed task incomplete if use uncheck the task.""" task_list = TaskList.objects.all() context = {'task_list': task_list} if request.POST: task_is_unchecked = request.POST['task_is_unchecked'] task_unchecked_id = request.POST['task_unchecked_...
1a12d3fc8cc7dc60b8b26d4c25041ed12abc0cd1
9,969
def jitter(t, X, amountS): """Return a random number (intended as a time offset, i.e. jitter) within the range +/-amountS The jitter is different (but constant) for any given day in t (epoch secs) and for any value X (which might be e.g. deviceID)""" dt = ISO8601.epoch_seconds_to_datetime(t) d...
db62c4365bf4cbf9d2ed0587c51846a274a691a4
9,970
import string def check_DNA(DNA_sequence): """Check that we have a DNA sequence without junk""" # # Remove all spaces DNA_sequence=string.replace(DNA_sequence,' ','') # Upper case DNA_sequence=string.upper(DNA_sequence) # Check that we only have DNA bases in the seq ok=1 garbage={}...
d73b8176938716b5c3710055750f05b24eab80a5
9,971
def read(): """ read() : Fetches documents from Firestore collection as JSON warehouse : Return document that matches query ID all_warehouses : Return all documents """ try: warehouse_id = request.args.get('id') if warehouse_id: warehouse = warehouse_ref.d...
17d3622f9f0770edb333907298112487432c7025
9,972
def transposeC(array, axes=None): """ Returns the (conjugate) transpose of the input `array`. Parameters ---------- array : array_like Input array that needs to be transposed. Optional -------- axes : 1D array_like of int or None. Default: None If *None*, reverse the di...
fecd60d72c4c38dc87d59f430365cefe72f40ef4
9,973
from typing import List def _partition_files(files: List[str], num_partitions: int) -> List[List[str]]: """Split files into num_partitions partitions of close to equal size""" id_to_file = defaultdict(list) for f in files: id_to_file[_sample_id_from_path(f)[0]].append(f) sample_ids = np.array(...
e9fac329f8e1c1c7682984216c34e7b259776c82
9,974
import json from pathlib import Path import time import requests def run_vscode_command( command: str, *args: str, wait_for_finish: bool = False, expect_response: bool = False, decode_json_arguments: bool = False, ): """Execute command via vscode command server.""" # NB: This is a hack to ...
4fa3626f1371c0c03923f37136616fb7055ef9cf
9,975
import threading def run_with_timeout(proc, timeout, input=None): """ Run Popen process with given timeout. Kills the process if it does not finish in time. You need to set stdout and/or stderr to subprocess.PIPE in Popen, otherwise the output will be None. The returncode is 999 if the proce...
414e18dae8f31b20c472f7da14475f8da5761781
9,976
def dot(x, y, alpha=0): """ Compute alpha = xy + alpha, storing the incremental sum in alpha x and y can be row and/or column vectors. If necessary, an implicit transposition happens. """ assert type(x) is matrix and len(x.shape) is 2, \ "laff.dot: vector x must be a 2D num...
2ef9fd4b02a586e9caff70b75bd598e925608171
9,977
def load_train_test_data( train_data_path, label_binarizer, test_data_path=None, test_size=None, data_format="list"): """ train_data_path: path. path to JSONL data that contains text and tags fields label_binarizer: MultiLabelBinarizer. multilabel binarizer instance used to transform tags ...
51aaf916f948b198e1f25c002655731008c173ed
9,978
import os def delete_courrier_affaire_view(request): """ Supprimer le fichier une fois téléchargé """ settings = request.registry.settings filename = request.params['filename'] temporary_directory = settings["temporary_directory"] file_path = os.path.join(temporary_directory, filename) ...
96b89ae5ed378b38af5a4426c6b1e9004d215bc9
9,979
def get_token() -> str: """Obtains the Access Token from the Authorization Header""" # Get the authorization header authorization_header = request.headers.get("Authorization", None) # Raise an error if no Authorization error is found if not authorization_header: payload = { "co...
5e1d05f705ad1c7505963e96c8637e5ab42aff79
9,980
def load_image(path, grayscale=False): """Summary Args: path (str): Path to image grayscale (bool): True loads image as grayscale, False loads image as color Returns: numpy.ndarray: Image loaded from path """ # TODO: Loa...
dd4ec76a2cd057f384b1894bc675c54abcff04a2
9,981
def convert_op_str(qubit_op_str, op_coeff): """ Convert qubit operator into openfermion format """ converted_Op=[f'{qOp_str}{qNo_index}' for qNo_index, qOp_str in enumerate(qubit_op_str) if qOp_str !='I'] seperator = ' ' #space Openfermion_qubit_op = QubitOperator(seperator.join(conver...
a6a512758a706b3a788f686331747ac9224c2f8b
9,982
def __state_resolving_additional_facts(conversation, message, just_acknowledged): """ Bot is asking the user questions to resolve additional facts :param conversation: The current conversation :param message: The user's message :param just_acknowledged: Whether or not an acknowledgement just happene...
d1e75e0d67aa2b1bcc899885c83132a47df015dc
9,983
import json def load_dataset(path): """Load json file and store fields separately.""" with open(path) as f: data = json.load(f)['data'] output = {'qids': [], 'questions': [], 'answers': [], 'contexts': [], 'qid2cid': []} for article in data: for paragraph in article['para...
4ba01f49d6a0aa3329b076fc0de9dd38fb99f2f8
9,984
def generate_rand_enex_by_prob_nb(shape: tp.Shape, entry_prob: tp.MaybeArray[float], exit_prob: tp.MaybeArray[float], entry_wait: int, exit_wait: int, ...
fbb7fc4bcf50139f455049edd4af62e9c0429dd3
9,985
def bresenham_3d_line_of_sight(observers, targets, raster, obs_height_field, tar_height_field, radius, raster_crs, fresnel=False): """Naive bresenham line of sight algorithm""" writePoints = [] lines_for_shp = [] start, end = 0, 0 raster_transform = raster.GetGeoTrans...
d11cfdf5c9d8f33b86a7dfc1026e6c668aebd3a4
9,986
import glob import os def delete(): """ Receives requests for deleting certain files at the back-end """ path = request.form['path'] files = glob.glob(path) for f in files: os.remove(f) return 'Successfull'
1ea2eb7dece5b3a1148b48b057a9e28780f52ce1
9,987
from datetime import datetime import html import requests from textwrap import dedent def retrieve(last_updated=datetime.now()): """ Crawls news and returns a list of tweets to publish. """ print('Retrieving {} alzheimer news since {}.'.format(SITE, last_updated)) to_ret = list() # Get all the conte...
ba194b84a50164ca8a238a77d0e80d5e80c93ae2
9,988
import binascii def check_seal(item): """ Given a message object, use the "seal" attribute - a cryptographic signature to prove the provenance of the message - to check it is valid. Returns a boolean indication of validity. """ try: item_dict = to_dict(item) raw_sig = item_dict...
86bb7b22d2efe4e7117b3c65fad2a7dc4853b428
9,989
def plot_win_prob(times, diff, end_lim, probs, team_abr, bools): """ This function plots the win probability and score differential for the game @param times (list): list containing actual_times and times. times contains all of the times at which win probability was calculated @param di...
139906b4a2db3cf3a7ffa531ec0701be0d395b13
9,990
def add_office(): """Given that i am an admin i should be able to add a political office When i visit ../api/v2/offices endpoint using POST method""" if is_admin() is not True: return is_admin() errors = [] try: if not request.get_json(): errors.append( make_response(j...
ee990cb55ca819a1b4fdd2eed4346f7fca21a7c3
9,991
from pathlib import Path import click def send_message( mg: mailgun.MailGun, templates: t.Tuple[str, str], contact_name: str, contact_email: str, sender: str, reply_to: str, sponsorship_package: t.Optional[Path], dry_run: bool, ) -> bool: """ Send an individual email and report...
62d03de5fa7a3c579ff2351e2c4623b3bf0e8a8e
9,992
def multi_class5_classification_dataset_sparse_labels() -> tf.data.Dataset: """ TensorFlow dataset instance with multi-class sparse labels (5 classes) :return: Multi-class sparse (labels) classification dataset """ # Create features X = tf.random.normal(shape=(100, 3)) # Create one multi-...
05bd5f809e08fde21270c286351ed32b9ed2cb97
9,993
def skipIfNAN(proteinPath): """ Test if there is a NAN (not a number) in the lists """ overlapArrayWhole = None overlapArrayInterface = None overlapTApproxWhole = None overlapTApproxInterface = None try: overlapArrayWhole = np.loadtxt(proteinPath+"overlapArrayWhole.txt") except IOErr...
0993fe55879e2c965b9856435e38f3a33d803e33
9,994
import json def alignment_view(request, project_uid, alignment_group_uid): """View of a single AlignmentGroup. """ project = get_object_or_404(Project, owner=request.user.get_profile(), uid=project_uid) alignment_group = get_object_or_404(AlignmentGroup, reference_genome__proj...
50f9420dca7c939524e1e243d667ddd76d7687d0
9,995
from typing import Optional async def get_latest_disclosure(compass_id: int, api: ci.CompassInterface = Depends(ci_user)) -> Optional[ci.MemberDisclosure]: """Gets the latest disclosure for the member given by `compass_id`.""" logger.debug(f"Getting /{{compass_id}}/latest-disclosure for {api.user.membership_n...
d5cce38ecce559b9bd9ac8306f88e32da1d2b4c6
9,996
def get_matching_string(matches, inputText, limit=0.99): """Return the matching string with all of the license IDs matched with the input license text if none matches then it returns empty string. Arguments: matches {dictionary} -- Contains the license IDs(which matched with the input text) with th...
be0fe152e530ec8244f892bfb4887b78bf89027b
9,997
def get_review(annotation): """ Get annotation's review (if exists). """ try: review = Comment.objects.get(annotation=annotation) return review except Comment.DoesNotExist: return None
89aeee2dc8811c57265ebbc30ede9cfafcd5e696
9,998
def load_grid(grdfiles, blocks, dimpart, nsigma, **kwargs): """Setup a `grid` by reading `grdfiles` on `blocks` """ ncgrid = nct.MDataset(grdfiles, blocks, dimpart, **kwargs) # dummy time, to be updated later time = ma.Marray(np.arange(10), dims=tdims) lat = nct.readmarray(ncgrid, "lat_rho", h...
08d102c4a1ef163e2af4801d7ffe2b572b747a58
9,999