content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def broadcast_backward(input, shape): """Sum a tensor across dimensions that have been broadcasted. Parameters ---------- input : tensor Tensor with broadcasted shape. shape : tuple[int] Original shape. Returns ------- output : tensor with shape `shape` ...
f81140f7be710435ad1c65b848e0a5d1b7d56bb2
673,524
def style_attrs_to_sets(styles): """Convert the style attributes 'combination', 'exclude', 'include' and 'require' from string to a set. styles: Style dictionary returns: Style dictionary with modified attributes""" for style_name in styles.keys(): for attr in ['combination', 'exclude', 'inclu...
7af843c53c49ce35c8acdff2b2db31949d28fcd2
673,527
def _getrawimagelist(glance_client): """Helper function that returns objects as dictionary. We need this function because we use Pool to implement a timeout and the original results is not pickable. :param glance_client: the glance client :return: a list of images (every image is a dictionary) ...
86aff3f3508bf3da5fa9f97f9caa1a87b63c0e2c
673,528
def merge_dict_overwrite_first(dict1, dict2): """Desired result is a new dictionary with the values merged, and the second dict's values overwriting those from the first in pythonic syntax.""" return {**dict1, **dict2}
169ae4f957e8dab2e8e9bcdf9ac5770a3b9102f1
673,529
def parse_lines(lines): """Parse the lines in a chunk of coverage""" # groups of lines are separated by commas. # a group of lines is either a single line N or a range of lines N-M line_list = [] for line_range in lines.split(','): bounds = line_range.split('-') if len(bounds) == 1:...
5d4208510a65c520dd9efe140f998faac91bdde1
673,530
def is_int(num): """ is_int Confirms if an input is numeric. """ try: x = int(num) return True except: return False
6e8db1f774192ed448124f069acff8713c1e4b3d
673,531
def _normalize_lists(value_str): ############################################################################### """ >>> _normalize_lists("'one two' 'three four'") "'one two','three four'" >>> _normalize_lists("'one two' 'three four'") "'one two','three four'" >>> _normalize_lists("'one two' ,...
b1af63766e948d607e655f56eb751493cc1cf924
673,532
import uuid def prefixUUID(pre: str = "PREFIX", max_length: int = 30) -> str: """ Create a unique name with a prefix and a UUID string :param pre: prefix to use :param max_length: max length of the unique name :return: unique name with the given prefix """ if len(pre) > max_length: ...
3ff15b23f768cb138bce291defb288395c25609e
673,533
def unique_index(df): """ Assert that the index is unique Parameters ========== df : DataFrame Returns ======= df : DataFrame """ try: assert df.index.is_unique except AssertionError as e: e.args = df.index.get_duplicates() raise return df
4d3536c2f7f951f8512e8c867520f038aab2be3c
673,534
import re def _make_safe_id_component(idstring): """Make a string safe for including in an id attribute. The HTML spec says that id attributes 'must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), ...
81a4e7bec5a87d9588f303033c7960a8a24e9aba
673,535
import argparse def parse_arguments(): """Parses command-line flags. Returns: args: a named tuple containing three file objects args.labelmap, args.groundtruth, and args.detections. """ parser = argparse.ArgumentParser() parser.add_argument( "-l", "--labelmap", help="Filename of l...
6b654b5bc280e1863eedff0b3b0fcaa0cb61fa00
673,536
import math def exp_add(a: float, b: float): """ Add the exponents of two numbers :param a: input exponent :param b: input exponent :returns: Sum of exponents""" if b == 0: return a if a == 0: return b # Assume that for very large numbers the 1 is irrelevant if a > 30 ...
83e723ddd8a8c3aa72078eb275f35123f77ecf54
673,537
from typing import Iterable from typing import Any def _tqdm_progress_bar_fn(iterable: 'Iterable[Any]') -> 'Iterable[Any]': """The TQDM progress bar function.""" # pytype: disable=import-error import tqdm # pylint: disable=g-import-not-at-top # pytype: enable=import-error return tqdm.tqdm(iterable, leave=T...
66adca5a32ffe0061fa5823b02ea87b2ac1831b1
673,538
def is_pickup(df): """Return if vehicle is a pickup truck, per NHTSA convention.""" yr = df['YEAR'] body = df['BODY_TYP'] return ((yr.between(1975, 1981) & (body == 50)) | (yr.between(1982, 1990) & body.isin([50, 51])) | ((1991 <= yr) & body.between(30, 39)))
29925316fb1b744f36bf7506866bb036f4ccf2f6
673,539
def config(): """Create a configuration class which can be loaded by a Flask app.""" class Config: GCM_KEY = 'super secret' GCM_URL = 'http://foobar.com' return Config
fb7b90e8298bdf687b3be8ac5f76ced2279aa191
673,540
import logging def select_issuance_records_with_geolocation_data(connection) -> tuple: """ The database insert method is responsible for connecting to the database, adding records to one or more tables and closing the connection. """ # Connect to database logging.info('getting database rec...
5f360bee47fce539864e949de484d8e72bca699f
673,541
def _num_items_2_heatmap_one_day_figsize(n): """ uses linear regression model to infer adequate figsize from the number of items Data used for training: X = [2,4,6,10,15,20,30,40,50,60] y = [[10,1],[10,2],[10,3],[10,4],[10,6],[10,8],[10,10],[10,12],[10,15],[10,17]] Parameters --...
5fb398c753acb159ed3139588634825024d74acb
673,542
from pathlib import Path import os import shutil def extract_static_files(ctx, file_name, file_path, dest_dir): """ This function will look for static local files that were linked from inside ipynb file. The path is built dynamically according to the one provided in ipynb file. Eg: ('learning.mp4...
66b8fb7f45404d48345fb9f3534a32536335c2ce
673,543
import itertools def split_mosaic(image, tile_size): """ Returns image after splitting image to multiple tiles of of tile_size. Args: image: str an image array to split tile_size: tuple size each image in the split is resized to Returns: Returns list of images """ ...
b4c38c04f8473afe97179dd8968f59bc785b3f3e
673,544
def skolemize_one(bnode: str, url: str) -> str: """Skolemize a blank node. If the input value is not a Blank node, then do nothing. Args: * value: RDF Blank node to skolemize. * url: Prefix URL used for skolemization. Returns: The skolemized blank node, or the value itself if it was...
9d1ab0abff892f294e0b612d1f236c002fcb2d7e
673,545
def search_datastore_spec(client_factory, file_name): """Builds the datastore search spec.""" search_spec = client_factory.create('ns0:HostDatastoreBrowserSearchSpec') search_spec.matchPattern = [file_name] return search_spec
aead60178b4a595bb9ca6d1213c3934b2678f185
673,546
import torch def accuracy(test_loader, model): """ Evaluate on test set """ model.eval() correct = 0. total = 0. with torch.no_grad(): for i, (x, target) in enumerate(test_loader): target = target.cuda() input_var = x.cuda() target_var = target.c...
14618e366fde9cb86f6a3b971682d0d5dc8ff3f9
673,547
def unicorn_read(fn): """Decorator to apply scaling law upon read_policy, the decorated function will be the new read_policy (for physics field). Parameters ---------- fn : Scaling law from engineering to physics, UNICORN function name ends with '-P'. Examples -------- ...
f256b085614d0014c70ae563a44b6c1382c4eb3c
673,548
def artist_src_schema_to_dw_schema(df): """ Rename the event src columns to dimensional and fact tables format. dim_artist columns: artist_id, name, location, latitude, longitude """ df = df.withColumnRenamed("artist_name", "name") df = df.withColumnRenamed("artist_location", "location") df ...
11e69be3a535949af85a19fa6c255669953e81b2
673,549
def get_file_lines(filename): """ Inputs: filename - name of file to read Output: Returns a list of lines from the file named filename. Each line will be a single line string with no newline ('\n') or return ('\r') characters. If the file does not exist or is not readable, th...
7d5335838f1fd510705b86ec6716610654f43790
673,550
def get_lines(text_string, sub_string): """Get individual lines in a text file Arguments: text_string {string} -- The text string to test sub_string {string} -- The conditional string to perform splitting on Returns: {list} -- A list of split strings """ lines = [line for line in text_string.split("\...
69c7f05167b2a4423011a44ec5b7e40045463d4e
673,551
def tag(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: tag(tagkey) tag(tagkey, category) Only true if accessing_obj has the specified tag and optional category. If accessing_obj has the ".obj" property (such as is the case for a command), then accessing_obj.obj is use...
ac5db92d562e78fa98f114202dd0658cecb8823f
673,553
def selection_sort(array): """ Selection sort sorts an array by placing the minimum element element at the beginning of an unsorted array. :param array A given array :return the given array sorted """ length = len(array) for i in range(0, length): min_index = i ...
cd9cb6454807bcbdfc7db8d97a331bee728fb537
673,554
import re def get_filename_components(filename): """Decomposes a standard note filename A standard filename has the form of 2_03_04a_5_Some_Topic_fb134b00b Where 2_03_04a_5 define the order within the hierachy of notes (in this case 4 levels), Some_Topic is the base of the filename and fb...
a98abee89eb0644781e4187ba28d9896e74a7622
673,555
def ineq_from_qlr(r, k, a, b, c, d): """ Generates a monodromy polytope inequality from the position of a nonzero quantum Littlewood-Richardson coefficient for su_4. See (*) in Theorem 23 of /1904.10541 . NOTE: `r` is ignored, since `4 = r + k` makes it redundant with `k`. """ # $$d - \su...
1e30ff69ba77acc49c790cc34707f0d1057fcee8
673,556
def format_names_and_descriptions(objects, name_attr='name', description_attr='description'): """Format a table with names on the left and descriptions on the right.""" pairs = [] for o in objects: name = getattr(o, name_attr) description = getattr(o, description_attr) pairs.append((...
d34627893ffc72b66a5f4b74cf8e76294f498da0
673,557
def get_label_from_directory(directory): """ Function to set the label for each image. In our case, we'll use the file path of a label indicator. Based on your initial data Args: directory: string Returns: int - label Raises: NotImplementedError if unknow...
1e7a8c3066f813ad5f2aca1eb580de2673638fdb
673,558
def count_gold(pyramid): """ Return max possible sum in a path from top to bottom """ work = list(list(row) for row in pyramid) # из тупла туплов делаем список списков for i in range(len(work) - 2, -1, -1): # идем снизу вверх с предпоследней строчки for j in range(len(work[i])): ...
da764726f5100eeec51fe7cfa53b64b3e77dd9d0
673,559
import math def euclidean_distance(x0, y0, x1, y1): """ Regular Euclidean distance algorithm. :param x0: x value of the first coordinate :param y0: y value of the first coordinate :param x1: x value of the second coordinate :param y1: y value of the second coordinate :return: euclidean dis...
ae5e57b855a45d3353649cc50f098839642171ef
673,560
import math def sum(column): """ Funcion encargada de sumar todas las cantidades de una columna """ return math.fsum(column)
3230793ad537ada345425855f658a17e97aee793
673,562
def pluralize(count: int) -> str: """ Return 's' as long as count is not 1 :param count: as int :return: """ return '' if count == 1 else 's'
0fae4fbf8be227d201f2103ccace437185241a91
673,563
def GetExtent(ds): """ Return list of corner coordinates from a gdal Dataset """ xmin, xpixel, _, ymax, _, ypixel = ds.GetGeoTransform() width, height = ds.RasterXSize, ds.RasterYSize xmax = xmin + width * xpixel ymin = ymax + height * ypixel return (xmin, ymax), (xmax, ymax), (xmax, ymin), (xmi...
5dfcb2074b2fd5efb4019cf403bd026296079efc
673,564
def filter_request_parameters(field_name, msg, look_in_response=False): """ From an event, extract the field name from the message. Different API calls put this information in different places, so check a few places. """ val = msg['detail'].get(field_name, None) try: if not val: ...
a45f721fd4e2b344230d6b8f82403ba45a60fc60
673,565
from typing import List import random def randboolList(len: int) -> List[bool]: """Returns a list of booleans generated randomly with length `len`""" finalList: List[bool] = [] for _ in range(len): finalList.append(random.choice([True, False])) return finalList
1b3f8e3753ff3f61b5b292a91e2728ce889942e6
673,566
import os def is_circleci() -> bool: """True if executing under circleci""" twd = os.environ.get("TOX_WORK_DIR") if twd is not None: return twd == "/home/runner/work/cbers04aonaws/cbers04aonaws/.tox" return False
a4dcd454233965a06336c324f98c24584e1eb0c9
673,567
import numpy def h2uv(h,grd): """ SSH to U,V Args: h (2D array): SSH field. grd (Grid() object): check modgrid.py Returns: u (2D array): Zonal velocity v (2D array): Meridional velocity """ ny,nx,=numpy.shape(grd.mask) u=numpy.zeros((ny,nx)) v=numpy.zer...
8af4bf69c0393daf725b1d836a72a24ea95fb958
673,568
import mpmath def mean(p, b, loc=0, scale=1): """ Mean of the generalized inverse Gaussian distribution. The mean is: K_{p + 1}(b) loc + scale -------------- K_p(b) where K_n(x) is the modified Bessel function of the second kind (implemented ...
0e08c1f9275520b64a591b684ae0b369fe6fa3ba
673,569
import re def clean_number(number_string: str): """ Convert dirty string into number. Remove leading and trailing unrelated char and ignore ',' between number. """ if number_string is None or number_string == '': return None number_string = '{}'.format(number_string) pure_number = ...
7331dfe47ce84ba2eb5a2470784f5e4c77a9156b
673,570
def parse_pos_file(pos_free): """ parsing a position file input: a file containing positions of variants from freebayes output: a list of varinats positions """ # Parsing the file containing the positions of variants position_list = [] # initializing the list of variants posit...
4aacca99a4eabf91ddefeda2b2c54df0e0462e10
673,571
def scenario_inputs(scenarios): """Parse the scenarios and feed the data to the test function.""" return [test_input[0] for test_input in scenarios]
e81b76a2114690b9dd85c905c66c9ba7e2433816
673,572
from typing import Dict def with_type(d: Dict, kind) -> Dict: """ Add or overwrite the key "type", associating it with kind, while not mutating original dict. :param d: dictionary to add "type": kind to :param kind: the kind of object dict represents :return: d | {"type": kind} >>> with_t...
46d65c863eb0891727e9aa5f9901b924c434dae6
673,573
import os def repo_dir(): """Returns a string with the path to the root of the Metatlas git repo""" return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
27980928a7ec87a68e3c86449ca91e116e1c9a3b
673,574
def precondition(iterable=None, program=None): """Ensure that a condition/contract is fulfilled. The condition has to be fulfilled by the input stream given the specific program with the chosen parameters. Preconditions take in input all the input to the interface. Preconditions evaluate to True ...
f93671cf5a4879888968551a6497139589313b0e
673,575
def is_none(value): """ Checks if the value is a None """ return value.lower() == str(None).lower()
84eaeb3aa4d28e46be49d7dd67adbf40c1f3ec4e
673,576
def Dir(v): """Like dir(v), but only non __ names""" return [n for n in dir(v) if not n.startswith('__')]
eca5c032a5483778d1e56164967c60bd11b9a4bd
673,578
import re def splitFastaHeader(name): """ Split a FASTA/FASTQ header into its id and metadata components """ nameParts = re.split('\s', name, maxsplit=1) id_ = nameParts[0] if len(nameParts) > 1: metadata = nameParts[1].strip() else: metadata = None return (id_, metadat...
5fdb03606af766923969051c726d4b9cc42af95d
673,581
def build_some_features(df_, num_periods_ahead, num_periods_lagged=1, num_periods_diffed=0, monthday= False, weekday=False, month=False, rolling=[]): """ Builds some features by calculating differences between periods """ # make a copy df_ = df_.copy() target_dat...
954bd0be6ed760970982b613231bfbe283f2895d
673,582
def f(x): """ ((1-x**(ELEMENT_BOUND + 1)) / (1-x))**SIZE """ y = 1/(1-x) return y
e133d593fb33f3e75b7996b457600f2967844fd7
673,584
def selectGenes(df, selection): """ Remove all rows (gene_ids) from a data frame which can not be found in selection. Parameters --------- df : DataFrame The data frame to work with. selection : set All ids to keep. Return ------ df : DataFrame The clean...
f6d81fe7f9489f2ed0a9f8d597405319ea222151
673,585
def backend(manager): """Get the ``Backend`` instance of the currently loaded profile.""" return manager.get_backend()
2b67af37f1fb11f6dcebbc1a586eee3c4ad51cd1
673,586
import collections def Tree(): """Make me a tree""" return collections.defaultdict(Tree)
8146858ced8b45a63824df936a5bad34b0b9822f
673,587
def load_model(input_dir): """ This hook can be implemented to adjust logic in the scoring mode. load_model hook provides a way to implement model loading your self. This function should return an object that represents your model. This object will be passed to the predict hook for performing predi...
031f8fd77bf4d6dea7a08e8e0d923b1828b9a36f
673,589
def move_to_same_host_as(source, destin): """ Returns source or a copy of `source` such that `source.is_cuda == `destin.is_cuda`. """ return source.cuda(destin.get_device()) if destin.is_cuda else source.cpu()
7e6337be37d5e7ae54b60c86bb270e7d93c6f8f6
673,590
def subdict(d, keep=None, drop=None): """Compute the "subdictionary" of a dict, *d*. A subdict is to a dict what a subset is a to set. If *A* is a subdict of *B*, that means that all keys of *A* are present in *B*. Returns a new dict with any keys in *drop* removed, and any keys in *keep* stil...
4ff6e3d7470891eba190a5aca19f94f87724dc90
673,591
def create_data_model(): """Stores the data for the problem.""" data = {} data['distance_matrix'] = [ [ 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 ], [ 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594...
ed68f957056727f673bca385748148779d39dc2d
673,592
def is_image(path): """OpenCV supported image formats""" extensions = [ 'bmp', 'dib', 'jpeg', 'jpg', 'jpe', 'jp2', 'png', 'webp' 'pbm', 'pgm', 'ppm', 'pxm', 'pnm', 'pfm', 'sr', 'ras', 'tiff', 'tif', 'exr', 'hdr', 'pic', ...
7972a8fbfbd8404e61fa508f968d2948873a27c6
673,593
def any_heterozygous(genotypes): """Determine if any of the genotypes are heterozygous Parameters ---------- genoytypes : container Genotype for each sample of the variant being considered Returns ------- bool True if at least one sample is heterozygous at the varia...
1ed57835f84ebf8f609a6addba5b922003a5588e
673,594
import operator def get_operator_function(op_sign): """ Get operator function from sign Args: op_sign (str): operator sign Returns: operator function """ return { '>': operator.gt, '<': operator.lt, '>=': operator.ge, '<=': operator.le, ...
6b3a3f23335d499400e12071b421a4f34b1acffc
673,595
import unittest import operator def create_datecalctestcase(start, duration, expectation): """ Create a TestCase class for a specific test. This allows having a separate TestCase for each test tuple from the DATE_CALC_TEST_CASES list, so that a failed test won't stop other tests. """ class T...
3148c057992e13a64da9ca33340cd80ea68fb12f
673,596
def true_positives(truth, pred, axis=None): """ Computes number of true positive """ return ((pred==1) & (truth==1)).sum(axis=axis)
8112b2d719702e1aa0964555d9cd9327e0b295fb
673,597
import argparse def parse_args(): """Process input arguments""" parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('pdb', metavar='P', help="Input PDB file") parser.add_argument('--yam...
7acaf05a5f4e3be24b821d8b4cc3a65c874fb360
673,598
def merge_dicts(create_dict, iterable): """ Merges multiple dictionaries, which are created by the output of a function and an iterable. The function is applied to the values of the iterable, that creates dictionaries :param create_dict: function, that given a parameter, outputs a dictionary. :param...
c4d8165c07b268be8ee892bb64405d5ef1480ba2
673,600
def hs2_text_constraint(v): """Constraint function, used to only run HS2 against uncompressed text, because file format and the client protocol are orthogonal.""" return (v.get_value('protocol') == 'beeswax' or v.get_value('table_format').file_format == 'text' and v.get_value('table_format').c...
5fc055d6cd0f79a8f12fdfeff8d24399f3b74b9f
673,601
def split_length(wav, ov_r=0.5, seg_len=0.06, tot_length=0.48): """ Parameter ov_r: Overlay rate (겹치는 영역) default:0.5 seg_len: Sample Length(T) 길이별 샘플링되는 시간 default: 0.06sec tot_lenth: 데이터길이 default: 0.48 sec Output result: np.array 결과(list) """ result=[] l_wd = len(wav) ...
a38a8aa3535278f9b21677a938dd3e1b5f593f47
673,603
import random def recursive_back_tracker_maze(bm_edges, full_mesh=False): """trace a perfect maze through bm_edges input: bm_edges: list of BMEdges - needs to be pre-sorted on index full_mesh: does bm_edges include the whole mesh output: maze_path: list of BMEdges maze_vert...
21cb3e22c9a37d94d30a3ed41de358b5e536e284
673,604
def get_trunk(py): """helper function that returns name of df column name for particular percentile (py) of latency""" p_col_name = { "P50_latency(ms)": "P50ms", 'P90_latency(ms)': "P90ms", 'P95_latency(ms)': "P95ms", 'P99_latency(ms)': "P99ms" } return p_col_name[py]
e9ccd17ff734441c8b1bfa963265642746eee67f
673,605
import math def tscore(ab,a,b,N, h=1): """Calculates t-score.""" O = ab / float(N) E = (a / float(N)) * (b / float(N)) E = E * h T = (O-E) / (math.sqrt(ab)/float(N)) T = round(T,2) return T
92353cd2e22e532110d938844203dad547a7a898
673,606
def manachers(S): """Runs Manachers algorithm on string S. Returns an array P where P[i] is the length of the longest substring mirrored around i in S. Strictly, S[i - P[i] + 1:i] == S[i + 1:i + P[i]]. """ n = len(S) assert n > 0 P = [1] * n # Center of the "current" palindrome. This...
af5a6d97e46bd2ade261c5bacd48a240028e9314
673,607
def isBuildConfFake(conf): """ Return True if loaded buildconf is a fake module. """ return conf.__name__.endswith('fakeconf')
a27a2bb844cf928e75a073e8c731079aa940c281
673,609
def is_palindrome(n): """Checks if n is a palindrome""" n = str(n) return n == n[::-1]
4f1fab3178b1e0b35a08611298e8baaa00562bb7
673,610
import math def keldysh_parameter(i_p, u_p): """ i_p is the ionization potential and u_p is the pondermotive energy. Both i_p and u_p must be in the same unit. """ return math.sqrt(i_p /(2 * u_p))
aa6f33fd5591ee7dea44bca9b4cb03a9a41f964b
673,611
import torch def load_model(filename, model): """Load the model parameters in {filename}.""" model_params = torch.load(str(filename)) model.load_state_dict(model_params) return model
14cb058d61dedc1ad4b41b0aab09a4ce56db37a1
673,612
import re def mobile_valid(mobile): """ Mobile phone number validator :param mobile: [str] Mobile phone number :return: """ r = re.match(r"^1[345789]\d{9}$", mobile) if r: return True else: return False
edb991aa1568990f1c90a56ced3bb64d40e74774
673,613
def InitNewVars1(): """ Initializes variables Returns: new_vars (d): nMapped (int): Total # reads considered nSkipQBeg (int): Counts how many queries were skipped because the location barPosCount (d): pastEnd_d (d): (dict) A dictionary mapping barcode of...
357c1ba0addfe90e539a0f7f568b8e4c3b4f5116
673,614
def increment(param): """ Increment parameter by 1 unit (to run test) """ return param + 1
8bd66800dab52eb1b57ca5ecb04c154a1fc3ec24
673,615
def _to_version_info(version): """Convert a version string to a number and string tuple.""" parts = [] for part in version.split("."): try: part = int(part) except ValueError: pass parts.append(part) return tuple(parts)
07e63530cdc1ea663c5816ebd3adf9713d7fd3a6
673,617
def retry_login(value): """Return True if value is None""" return value == 'retry'
c528f8995132ef8bf25da97aa032b5f3c02ca984
673,618
def table(lst): """ Takes a list of iterables and returns them as a nicely formatted table. All values must be convertible to a str, or else a ValueError will be raised. N.B. I thought Python's standard library had a module that did this (or maybe it was Go's standard library), but I'm on an a...
b85fba6bd376810e4dfe206f7e7e053955ebec54
673,619
def push_variable_on_stack(assembler, stack_offset, value, value_array): """Push a value on a specified location on stack Args: assembler (Assembler): the assembler to use stack_offset (int): the offset relative to the current stack pointer value (bytearray): ...
5e62baf9410bd60a017929fae44f52e604a4dc1b
673,620
from typing import Mapping def signature(signages): """ Creates Signature HTTP header item from signages list RFC8941 Structured Field Values for HTTP Returns: header (dict): {'Signature': 'value'} where value is RFC8941 compliant (Structured Field Values for HTTP) formatted str of ...
8934f913d79a6f49fd1dd9bd5fa08eb1d01c4ed6
673,621
def get_file_content(fpath: str, **kwargs) -> str: """Get content from a file given a path Parameters ---------- fpath : str file path Returns ------- str file content """ with open(fpath, **kwargs) as f: txt = f.read() return txt
aaea3135d9f32df22d79ff4efb3decbffde06310
673,622
import os def data_colour(fname): """Colour nodes based on file extension""" colour = {'.csv': 'palegreen', '.tsv': 'palegreen', '.pdf': 'lightblue', '.pickle': 'yellow', '.pkl': 'yellow', '.gz': 'palegreen1', ...
1e3943853e697aac808a8fdf37597d12bef15af9
673,623
import json import requests import hashlib def handle(req: bytes): """handle a request to the function Args: req (str): request body """ args = json.loads(req) url = f'https://{args["host"]}/cdmi/cdmi_objectid/{args["fileId"]}' headers = {"X-Auth-Token": args["accessToken"]} resp ...
38c0cf478f25be47f2d7d8fd7faff73da700cce6
673,624
def summarize_all(req_info): """ Can be also used as matcher. """ return True
24bbb5d54993e07502342894c9c597f9e807e290
673,625
import random def generate_id(): """ Generate an ID suitable for use with Pubsubclub. """ return random.randrange(2**31)
49269de0252c1a49c0e8f4f62bd88dbe70c29151
673,627
def getElementDict(): """ Element name dictionary. Returns ------- dict Long name keys, short name values """ return({'Rubidium' : 'Rb', 'Caesium': 'Cs', 'Germanium' : 'Ge', 'Tin' : 'Sn', 'Iodine' : 'I', ...
9d70148d31a03769c1feda1a1b83f68e94c64116
673,628
import time def RecordStartTime(): """Records the time at which the request was started. Returns: A function that can be used in a Handler.request. """ def _RecordStartTime(request): """Records the start time of a request.""" del request # Unused. return {'start_time': time.time()} retur...
26b6734ab25701f4c89cfb296690c83c2a971dc3
673,629
def multiples(s1, s2, s3): """Show multiples of two numbers within a given range.""" result = [] for i in range(s3): if i % s1 == 0 and i % s2 == 0 and i: result.append(i) return result
cb6acc4eb372fff232190022e5a1d4b4938fc7f0
673,630
def get_z_2prop(p1, p2, n1, n2): """ """ sp_error = (((p1 * (1 - p1)) / n1) + ((p2 * (1 - p2)) / n2))**0.5 z = (p1 - p2) / sp_error return z
c8a4803469f4ab651f88af43028d29f94c796b84
673,631
def organizationString(organization): """ Print a nice organization string e.g ecotrends project#ecotrend@nmsu.edu#http://www.ecotrends.info#[23] """ organization_strings = [] for field in organization: organization_strings.append("%s:%s" % (field, organization[field])) return "#...
283e174d37978cdbbb3e81d62681d5dc74083041
673,632
def avg(array): """ Makes the average of an array without Nones. Args: array (list): a list of floats and Nones Returns: float: the average of the list without the Nones. """ array_wo_nones = list(filter(None, array)) return (sum(array_wo_nones, 0.0) / len(array_wo_nones)) i...
dea25aa24dbe53b0d3974d16f5b3ae3bf93ffcdc
673,633
import re def find_inline_equations(s): """Given a string, find all $...$ pairs and return matched strings. """ pattern = r'(?P<all><span class="math inline">\\\((?P<latex>.+?)\\\)</span>)' return re.findall(pattern, s)
c167d54d4339c81db76214e8b70af9c10c1d1b72
673,634
def pms_to_addrportsq(poolmembers): """ Converts PoolMembers into a list of address, port dictionaries """ return [{'address': p._node.name, 'port': p._port} for p in poolmembers]
fa24338856f383b1d8dcab3a499a6dddbb45adcb
673,635
def closer_probability(player_location, enemy_location, coins, dists_matrix): """Return the probability that the player will get a coin based only on the player distance to the coin and the enemy distance to the coin return a dictionary coin : probability """ probabilities = {} for coin in coins: ...
9676f1023121567b971ae922b64e2454027d0b2e
673,636
def get_mic(metadata_file, mic_column): """Reads metadata file (specifically strain-table-filtered.csv)""" mic = {} with open(metadata_file, "r") as infile: for line in infile: line = line.strip().split(',') mic[line[1]] = line[mic_column] return mic
4005eec3abb09c5e7f99304250c7d2013f08d1a9
673,637