content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import requests def scrapejson(jsonurl): """This function scrapes a URL to get the JSON file at the URL.""" api_output = requests.get(jsonurl) data = api_output.json() return data
178cf1c2225736340e82c8975eca923e257d42d4
606,701
def header_dict_from_list(array): """Given a list of strings in http header format, return a dict. If array is None, return None""" if array is None: return array header_dict = {} for item in array: (key, sep, value) = item.partition(':') if sep and value: header_...
706119757b4daf3a3aea83e7689fe6ebe2faed4f
606,702
def bboxes_overlap(bbox_1, bbox_2): """Determines if two bounding boxes overlap or coincide Parameters ---------- bbox_1 : array-like (or 4-tuple) 1st bounding box convention: (x_min, y_min, x_max, y_max) bbox_2 : array-like (or 4-tuple) 2nd bounding box convention: ...
8253d416049e1747639d70484c47d13d667afdcc
606,704
from typing import List import re def _extract_author_names(authors_list: List[str]) -> str: """ Parse out only names from 'name <email>' list. Args: authors_list: List of authors in 'name <email>' format. Returns: author_names_csv: String with only the 'name' part ex...
09bfca97d2e5143e7fd550ca4705cadabf5207c7
606,705
import itertools def get_pairs(data: dict) -> dict: """Gets list of pairs of splits to run. E.g. Given splits ['train', 'val', 'id_test', 'od_test'], produces list: [ ['train', 'id_test'], ['train', 'od_test'], ['id_test', 'od_test'] ] Args: data...
25a9d25e08b2b5db6afdc232ce1de8875c3f9f10
606,707
def inhg_to_mb(val): """ Converts inches of mercury to millibars; accepts numeric or string """ try: return float(val) * 33.8639 except (TypeError, ValueError): return val * 33.8639
d1f4b7187697ab84e0b2e4ff0ccaec24693cc4c4
606,709
def _alpha(n): """Excel-style column numbering A..Z, AA..AZ..BA..ZZ.., AAA""" if n < 1: raise ValueError(f"Can't represent {n} in alphabetic numbering") p = [] while n > 0: n, r = divmod(n - 1, 26) p.append(r) base = ord('A') ords = [(base + v) for v in reversed(p)] r...
e604f50e6886e444c91ff4b2483a0e9ce240c83b
606,710
def create_route_long_name(relation, short_name): """Create a meaningful route name.""" if relation.tags.get('from') and relation.tags.get('to'): return "{0}-to-{1}".format(relation.tags.get('from'), relation.tags.get('to')) name = relation.tags.get('name') or\ ...
c975ee4776b820492f2912e1543d01ae98e61872
606,711
def _consolidate_terms(dterms): """ Combine like derivative terms. Arguments ----------- dterms: A list of DerivativeTerms. Returns ------------ A new list of derivative terms that evaluate equivalently where terms with the same derivative signature have been combined. ...
62ce5df6e2fb69e5b799319df3caec07c5542667
606,716
def split_network_line(line): """Parses line of /proc/virtual/<xid>/cacct for network usage. The cacct file has a header followed by usage counts for multiple protocols. Header (provided for context): Type recv #/bytes send #/bytes fail #/bytes Each protocol's usage counts are formatte...
9f8899595da8aba6d4cd29ea2ada67cfeb6b5a14
606,721
def _convert_color_component(float): """Convert color component between 0 and 1 to integer value in [0, 255].""" return max(0, min(255, int(float * 255)))
b8b8320737d7507e17eb521f6c3530e029458d15
606,723
def parse_test_files_option(opt): """ Parse option passed to --test-files into a key-value pair. >>> parse_test_files_option('generators.py:10,13,19') ('generators.py', [10, 13, 19]) """ opt = str(opt) if ':' in opt: (f_name, rest) = opt.split(':', 1) return f_name, list(map...
71f3d6a962b826984c975828a8ecc7de8061e62c
606,724
def downsample_ds(normlogSAR, downsample_factor=5): """Spatially downsample an xarray DataArray or Dataset. """ downsampled = normlogSAR.groupby_bins('x',len(normlogSAR.x)/downsample_factor).mean(dim='x').groupby_bins('y',len(normlogSAR.y)/downsample_factor).mean(dim='y') downsampled = downsampled.renam...
f6e17c9c22ce7eb3a95700d4915636c93cca2fb3
606,725
import json import requests def check_aws(admin_api_key, env, cc_account_id): """ Checks if an account is an AWS Account with get_account API call """ api_url = env + "/api/account.json/get_account" get_account_info = json.dumps({"account_id": cc_account_id}) r7 = requests.post(api_url, hea...
fc69b72870dadb54b796e4206319f2181d252686
606,726
import re def get_method_versions(obj, method_name): """Useful function for initializing versioned senders/receivers. Returns a dictionary of different internal versions of the given method. Assumes that the object has the particular versioned method and this method is public. Thus versions are priv...
08c21fcc376fca330271317e6f18257e6bd6f175
606,727
import torch def bbox_transform_inv(boxes, delta): """ Inverse Bounding Box Transform from deltas and proposal boxes to predicted boxes Args: boxes: [N, 4] torch.Tensor (xywh) delta: [N, 4] torch.Tensor (xywh) Return: pred: [N, 4] torch.Tensor (xyxy) """ pred_boxes = to...
bd060c64fecd68167152f28fca2ab076e138256d
606,729
def is_data(value): """Return whether the value is a wrapped data descriptor.""" return value is not None and value.is_data
fe34a563e16b9e11aec8e751c930441bdd856a99
606,730
import unicodedata def char_is_punct(char): """True if char is a punctuation character.""" return unicodedata.category(char).startswith("P")
d1b8b0887e028a8366f0c290cc870ee5224a4389
606,731
def get_polygon_area(verts): """ Calculate the area of a closed polygon Parameters ---------- verts : numpy.ndarray polygon vertices Returns ------- area : float area of polygon centroid """ nverts = verts.shape[0] a = 0. for iv in range(nverts - 1): ...
86165171c8f75b079ae554759db47bce9841b1fa
606,735
def compute_f1_score(precision, recall): """ Computes the F1-score between the precision and recall :param precision: float number :param recall: float number :return: The float corresponding to F1-score """ if precision == 0 and recall == 0: return 0 else: return 2 * pre...
59875e6ca489d69f4490b8c24c29f6f29237e234
606,736
def is_non_empty_string(input_string): """ Validate if non empty string :param input_string: Input is a *str*. :return: True if input is string and non empty. Raise :exc:`Exception` otherwise. """ try: if not input_string.strip(): raise ValueError() except Attribu...
1c8cf35c5b0aea1b5e12c085d59f9b2dc110ae83
606,737
def normalized_name(player): """Normalizes the player name.""" player_name = str(player) # for char1, char2 in [('/', '-'), ('\\', ''), ('$', '')]: # player_name = player_name.replace(char1, char2) return player_name
c9724eb4f7227fe9a245bb5d4ceae1cb130bbed3
606,741
import torch def restore_model(model_class, load_path): """ Restores a model from the given path. `model_class` must be the class for which the saved model was created from. This will create a model of this class, using the loaded creation arguments. It will then restore the learned parameters to ...
993b1ee4070db41bf39c6f45d21660d507668b73
606,743
def _flatten_results(result, default_value=None): """ Formats results to map to a single value or default value if empty. """ flattened = {} for k, v in result.items(): if len(v) > 1: raise ValueError( 'Expected one, but more returned for "{}": {}'.format(k, v)) i...
51fce4eb317cfd4185857bcd4c36546bea406d9d
606,744
def subclasses(cls, leaves=False): """ List all subclasses of the given class, including itself. If `leaves=True`, only returns classes which have no subclasses themselves. :type cls: type :param leaves: Only return leaf classes :type leaves: bool :rtype: list[type] """ stack = [cls] ...
71b13fe786956786c0330c62318a09208a71d70a
606,746
def middle(t): """Takes a list, returns a new list with first and last elements removed""" return t[1:-1]
51da0fbefa9ee7c23c431dea9cfb0ff22139b778
606,753
def get_secondary_connections(network, user): """Get the 2nd level of connections of a given user. Keyword arguments: network -- a dictionary containing users' connections and games user -- the name of a person in the network """ try: return list(set([secondary for primary in network[us...
56050eb1a437fd4d4b6ab0b1c3815dae7f89426d
606,760
def _clutter_to_dict(clutter_array): """ Function that takes the clutter array and turn it into a dictionary to be used and added to the pyart radar object. """ clutter_dict = {} clutter_dict['units'] = 'unitless' clutter_dict['data'] = clutter_array clutter_dict['standard_name'] = 'xsapr_cl...
ff87226e7d332cdb900f6e687ab7722fb5cbec65
606,765
def percentage(reviewed, voted): """ Returns the percentage of voted contributions. """ try: return 100.0 * voted / reviewed except ZeroDivisionError: return 100.0
b3f207700ce2691d5dc5b4c77e4e89db605fee66
606,766
def c_to_f(tempe): """Receives a temperature in Celsius and returns in Fahrenheit""" return 1.8 * tempe + 32
5121c9e33fcabd4d63aece794dcd3bd9d9cbd48c
606,768
def check_existing_filtered_location(timeseries, entry): """ Returns true if there is an existing filtered_location. We check for this by querying the database for an existing entry with the same timestamp. Note that we cannot check for the write_ts because in case the stream is filtered on the client, ...
7b0d938e4cb415bcefaa59dd81937ac35e8c9484
606,769
def _service_account_id(project): """Return service account ID for project.""" # From # cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/create: # # The account id that is used to generate the service account email address # and a stable unique id. It is unique within a project, must be 6-30 ...
bf24e62e620e2ffa5e59aa6c5c7e0b55b54a962f
606,770
def is_printable_as_block_string(value: str) -> bool: """Check whether the given string is printable as a block string.""" if not isinstance(value, str): value = str(value) # resolve lazy string proxy object if not value: return True # empty string is printable is_empty_line = True ...
ad4120ab4d60eacf713f83806c07c4f72e7d9008
606,772
def precision(ct): """Computes precision based on a contingency table. :param ct: a contingency table :type ct: ContingencyTable """ if ct.TP + ct.FP == 0: return 0.0 return float(ct.TP) / (ct.TP + ct.FP)
2c99c7c9c855a06c27eb310d8dde050acc42c64d
606,775
def streamplot(ax, x, y, z, **kwargs): """ Wrapper around Matplotlib's streamplot plot. """ default_args = {"color": "w"} default_args.update(kwargs) return ax.streamplot(x, y, z[..., 0], z[..., 1], **default_args)
69e6f5d3857e2d39777e57f9f48b557101534bee
606,776
def browser_eligible_for_reuse(current_browser, future_browser): """ type current_browser: ManagedAdhocBrowser type future_browser: AdhocBrowser.msg Compares two browsers and returns bool telling whether one browser can be updated to the other. It can't be updated if there's a difference in: ...
9d093536800f80df75f87ae4873dd1c004765202
606,777
from typing import List def split(x: str, sep: str, maxsplit: int) -> List[str]: """Same as x.split but always returns a list of length `maxsplit+1`, padded with empty strings.""" parts = x.split(sep, maxsplit) extra = [""] * (maxsplit + 1 - len(parts)) return [*parts, *extra]
625efefef007faa903bde41f34a06ef194e9df58
606,780
from typing import List def binomial_list(n: int, k: int) -> List[List[int]]: """ Produce a list of all possible combinations of picking k elements out of n. All elements are different. Args: n: Total number of elements. k: Number of elements to pick. Returns: blist: List of ...
c44d7ba77655b60193a99b7f60858582f9831b8c
606,783
from typing import Dict import json def json_to_dict(input: str) -> Dict[str, str]: """A wrapper around `json.loads` that returns an empty dictionary rather than raising an exception.""" try: return json.loads(input.replace("'", '"')) except json.decoder.JSONDecodeError: return {}
3fdac68f26fda0c6872b7d4745ce28aa543c76e0
606,784
def get_np_rows(matrix, start_entry, x=512): """ Returns the next x rows of a numpy array. """ arrays = [] matrix_len = len(matrix) end_entry = start_entry + x if matrix_len < start_entry + x: end_entry = matrix_len for i in range(start_entry, end_entry): arrays.appe...
b0a70b66481b033d268b81aa5b96388282fc747e
606,790
import struct def upstream_forward(sock, data): """ Forward a DNS request to a upstream server using TLS. Params: sock - socket object connected to upstream server data - wireformat DNS request packet to forward Returns: A wireformat DNS response packet Notes: Using DNS over TLS format as described he...
7447786ae51833ff486b2924f5a85639eb760fbf
606,791
def allow_coef0_specification(value): """Dash callback for enabling/disabling the 0th coefficient input widget for support vector classification. Given a kernel from the dropdown menu, allow the user to specify a 0th coefficient if the selected kernel is polynomial ("poly") or sigmoid. Otherwise, d...
333ebef833d5e01bd2243def9779ebe017ca9ef8
606,793
import logging def validate_csv(package, version, csv): """ Checks csv to make sure there are no clusterPermissions, it does not support multi-namespace install mode, and it does not require security context constraints """ tests = {} # Cluster Permissions aren't allowed cpKey = "CSV ...
80a4ac55d877949088e322138397a8dc7938da36
606,797
def sentence_to_bigrams(sentence): """ Add start '<s>' and stop '</s>' tags to the sentence and tokenize it into a list of lower-case words (sentence_tokens) and bigrams (sentence_bigrams) :param sentence: string :return: list, list sentence_tokens: ordered list of words found in the sentenc...
8fd3425517a31114c9b6560001fba21d5b62ef19
606,798
def same_array_size(array1, array2): """Crop the input arrays such that they are the same size in both dimensions Parameters ---------- array1 : numpy.ndarray 2D array array2 : numpy.ndarray 2D array Returns ------- array1 : numpy.ndarray Potentially croppe...
d3b4594016bc4e247e6d13edb10b51feb7aa2104
606,803
def dftd3_coeff_formatter(dashlvl, dashcoeff): """Return strings for DFTD3 program parameter file. s6 rs6 s18 rs8 alpha6 version ------------------------------------------------------ d2: s6 sr6 s8=0.0 a2=None alpha6 version=2 d3zero: s...
756a04901d9188824abdec0c4d0b60ab947ddbb2
606,805
def find_crf(crfs, sample_date): """ Returns the carbon response factor object for a sample at the given sample_date crfs: list, of crf objects sample_date: datetime, the date_start attribute of a sample """ return next((crf for crf in crfs if crf.date_start <= sample_date < crf.date_end), Non...
96ffb20654eaf2a8dfd98927a13d648ac6e616d9
606,806
def subread_dictionary(bash5_reader): """Return a dictionary of dictionaries. First level keys are (movie_name, hole_number). They point to a second dictionary with keys (rStart, rEnd) where rStart and rEnd are from the bax.h5, not the cmp.h5. """ subread_dict = {} for zmw in bash5_reader: ...
914fdade4b3203d5d175373f87aadb699bf3c42f
606,807
def getEltonNuclearRadius(A, natUnits=False): """Return nuclear charge radius in fm according to Elton formula :param A: mass number :param natUnits: return result in units where m_e=hbar=c=1 (Default value = False) """ R = 1.121 * A ** (1. / 3.) + 2.426 * A ** (-1. / 3.) - 6.614 / A if natUn...
3dc10c02d4b0cc892aa72ba34514e5fcdc2a1533
606,812
def validate_boolean(value, label): """Validates that the given value is a boolean.""" if not isinstance(value, bool): raise ValueError('Invalid type for {0}: {1}.'.format(label, value)) return value
716cf553ae8c957a33424dcbb699ec493c742fe0
606,813
def get_page_display_string(current, per, total): """ Get the format string x - x of xx :param current: current page :param per: count per page :param total: total count :return: str """ return '{start} - {end} of {total}'.format( start=((current - 1) * per + 1) if current else 0...
93b13acebb3a9fb7ff878752bbc83f3818011864
606,817
def create_default_config(schema): """Create a configuration dictionary from a schema dictionary. The schema defines the valid configuration keys and their default values. Each element of ``schema`` should be a tuple/list containing (default value,docstring,type) or a dict containing a nested schem...
06f51a864cf25c9c4028d8355095173a27732da2
606,818
def cohensutherland(left, top, right, bottom, x1, y1, x2, y2): """Clips a line to a rectangular area. This implements the Cohen-Sutherland line clipping algorithm. left, top, right and bottom denote the clipping area, into which the line defined by x1, y1 (start point) and x2, y2 (end point) will be ...
df9bf82a7ebacb36d5c0a6d18ef4210b321456a9
606,823
def removePtclsByLst(rejectlst, params): """ Removes particles by reading a list of particle numbers generated externally. Requirements: the input file has one particle per line the first piece of data is the particle number from the db """ f=open(params['rejectlst'],'r') lines=f.readlines() f.close() for ...
d7af17548f00c066d1464bf40f5d70b0135b5b90
606,824
def friendly_boolean(boolean): """ Returns 'Yes' if boolean is True, 'No' if boolean is False and None otherwise """ if boolean is None or boolean == "": return None elif boolean is True or str(boolean).lower() == "true": return "Yes" else: return "No"
09443a26e236269c79be85f123e0a3f3b1784b55
606,825
def get_last_ter_line(model_lines): """Gets the index of the last TER record in a list of records. 0 will be returned if there are none. :param list model_lines: the lines to search. :rtype: ``int``""" last_ter = 0 for index, line in enumerate(model_lines[::-1]): if line[:3] == "TER": ...
b8fbbbb87d9f530a30244fa085d12b8850527d08
606,827
def str_xor(a, b): """ (string, string) -> string xor two strings(a and b) of different lengths >>> str_xor("string", "integer") '\x1a\x1a\x06\x0c\t\x02' >>> str_xor("hello", "world") '\x1f\n\x1e\x00\x0b' >>> str_xor("foo", "bar!") '\x04\x0e\x1d' >>> str_xor("AI", " ") 'ai...
1fcef738dfe37be4dc9141acf0913d5a589505dc
606,828
def fixture_mktmpfile(tmp_path_factory): """Fixture to create a temporary file with 'data' as content""" def _mktmpfile(data): """Fixture to create a temporary file with 'data' as content""" fn = tmp_path_factory.mktemp("mktmpfile") fn_file = str(fn) + "/file" with open(fn_file,...
e94038e76c140604643702aaa04c6eb7bd70ff75
606,829
def t_and_beta_to_varcope(t, beta): """Convert t-statistic to sampling variance using parameter estimate. Parameters ---------- t : array_like T-statistics of the parameter beta : array_like Parameter estimates Returns ------- varcope : array_like Sampling varia...
3b353cea543f0ac5487d12653c45618195803302
606,831
import ast def is_literal_eval(node_or_string) -> tuple: """ Check if an expresion can be literal_eval. ---------- node_or_string : Input Returns ------- tuple (bool,python object) If it can be literal_eval the python object is returned. Otherwise None ...
a46810bf2c6e3106da0fc9985ee350c9397161ce
606,832
import json def send_files(ws, filepaths): """send_files will format a messages to import files and send the message through websocket""" file_import_message = { 'data': { 'command': 'DEFAULT_ACTION', 'action': 'IMPORT_CURRENT', 'data': { 'paths': fi...
24edbeef984db9edb41f339d38c2d43460922168
606,834
def skip_14(labels): """Customised label skipping for 14 quantiles.""" return ( labels[0], labels[2], labels[4], labels[6], labels[8], labels[10], labels[13], )
4c784d7625486d8e4a56006d22af9455f90238f9
606,841
import base64 def embedded(pem: str, name: str, app: str) -> str: """Returns data formatted for embedded configuration.""" b64 = base64.b64encode(pem.encode("ascii")).decode('ascii') data = [ f"data:application/{app}", f"name={name}", f"base64,{b64}" ] return ";".join(data)
4f1c0087f6a2fa0bdbd8c3074ed27076d26724c9
606,844
def matchPattern(string, pattern): """Verifica se uma string contém um padrão.""" return bool(pattern.match(string.lower()))
73db7d1ba11cefb0c3b13891d90ba6d525b9a171
606,845
def _default_alias_is_added(fn_aliases, default_alias_name): """ Checks if the `default alias` is part of a list of aliases """ for alias in fn_aliases: if alias["Name"] == default_alias_name: return True return False
b5fb3f92d508515d660acc3dd78f1b22a33322f0
606,847
import re import fnmatch def _match_files(universe, pattern): """From a universe of files, get just those files that match the pattern.""" # Implicit recursive iff no / in pattern and starts with * if "/" not in pattern and pattern.startswith("*"): pattern = f"**/{pattern}" pattern = re.compil...
d32d722cf3e0d36de08c1ad5b694a19b116eb979
606,851
def patched(obj, attr, fun): """Context manager to locally patch a method. Within the managed context, the `attr` method of `obj` will be replaced by a method which calls `fun` passing in the original `attr` attribute of `obj` as well as any positional and keyword arguments. At the end of the cont...
7d048039a6fcfc13a4343d8af02b8f66f501ac4c
606,852
def brute_force_flops(D, N): """ Given the data dimension and the number of results to rank, compute the number of flops for brute force exact distance computation. """ return N * (3 * D)
2f487a9fa2212021c8202936e8df9f4072e6035b
606,853
from functools import reduce from operator import mul def _product(l): """Return the product (i.e. all entrys multiplied together) of a list or iterator. """ return reduce(mul, l, 1)
e2970b20b32f2c60c1af5b3b6b9bbe973fface3a
606,854
def invert_map(dic): """ Inverts map. Raises ValueError if map is not invertible. """ inv = {v: k for k, v in dic.items()} if len(inv) != len(dic): raise ValueError("map not invertible!") return inv
de1b5d85ee57488ee531a5e9c54c334cf5ee13f4
606,855
def count_divisible_digits(n, m): """ This function takes two integer numbers n and m as an arguments and returns the number of digits in n that are divisible by m. """ if n < 0: n = n * -1 if m == 0: return 0 count = 0 while n != 0: digit = n % 10 remaind...
d0b2f78f6e3f153d410eead163fffc095a3bf184
606,857
import re def nsort(fnames): """Sort a file list, automatically detecting embedded numbers""" def path2parts(fname): parts = re.split(r"([0-9][0-9.]*e[-+][0-9]+|[0-9]+\.[0-9]+|[0-9]+)", fname) parts[1::2] = map(float, parts[1::2]) return parts return sorted(fnames, key=path2parts...
0f57dee998a9665d0aea533f1f31313e2eb6580e
606,859
import re def convert(k: str) -> str: """Convert a key name. BigQuery specification for field names: Fields must contain only letters, numbers, and underscores, start with a letter or underscore, and be at most 128 characters long. :param k: Key. :return: Converted key. """ # Trim special ...
819394cf7bd0ada07f2992f6a41b1368220cea16
606,861
def provided(samplelist, condition): """ Determines if optional rules should run. If an empty list is provided to rule all, snakemake will not try to generate that set of target files. If a given condition is not met (i.e. False) then it will not try to run that rule. """ if not condition: ...
e1b802ca82e1d585e7238536a05a246fcf0c525b
606,864
import struct def pack_integer(value): """ Pack an integer value into 32-bits, little endian form. """ return struct.pack('<I', value)
6bd83ce74ddc914cfcb3564ca84bcb4855c2a95d
606,865
def index_to_label(index: int) -> str: """ Map an column index to a label :param index: the index :return: the resulting label """ letter = chr(65 + (index % 26)) return letter * ((index // 26) + 1)
b90f18e3dd12888d834d41171505b12500509baa
606,866
def mod_min(a, b): """ return r such that r = a (mod b), with minimum |r| """ # like divmod_min, just skipping a single add r = (a % b) diff = b - r if abs(r) > abs(diff): r = -diff return r
0cf2fb88b34992a2ede6c4a53f4f621625703fab
606,867
def get_segment_length(fs, resolution_shift=0): """ Calculates a segment length such that the frequency resolution of the resulting analysis is in the region of ~1Hz subject to a lower limit of the number of samples in the signal. For example, if we have a 10s signal with an fs is 500 then we convert fs...
06f5c36d48b2bda8e06f42a2785f16ee2fb60f73
606,872
def pairs_generator(rng): """ Creates Generator of ordered pairs :param rng : Range of the interval, e.g. 3 means pairs (0,1),(0,2),(1,2) :return: """ return ((i, j) for i in range(rng) for j in range(rng) if i < j)
1d3eb5f1a0a06aeae6df32c222c5321539620da4
606,876
def is_finite(builder, val): """ Return a condition testing whether *val* is a finite. """ # is_finite(x) <=> x - x != NaN val_minus_val = builder.fsub(val, val) return builder.fcmp_ordered('ord', val_minus_val, val_minus_val)
6899f64d171eed820f18970baeb5c899e7149248
606,878
def _accuracy(input, target): """Accuracy, i.e. mean(input == target)""" return input.eq(target.view_as(input)).float().mean()
249053246f0f4752345e0b87016bcf792458740d
606,879
def coerce_tuple(item): """Return item converted to tuple if not already tuple. :param Union[str, IKey, Iterable] item: item to coerce to tuple. :returns: coerced value of item as tuple. :rtype: Tuple[Any]. .. Usage:: >>> coerce_tuple('test') ('test',) >>> coerce_tuple(('...
b6b0ed565562f37f596cf0aa148bb59d9416d9bb
606,881
def _b3_id_to_dd_id(b3_id): # type: (str) -> int """Helper to convert B3 trace/span hex ids into Datadog compatible ints If the id is > 64 bit then truncate the trailing 64 bit. "463ac35c9f6413ad48485a3953bb6124" -> "48485a3953bb6124" -> 5208512171318403364 """ return int(b3_id[-16:], 16)
6de4991e36fcdbcb8b75c02b4e4c1cb90c221fa2
606,882
def unique_id(ID, IDList): """ Assigns a unique ID to each spectral target. A spectral target may appear in multiple files so unique_id assigns IDs by appending _<New number> to the spectral target ID. Parameters ---------- ID : String Spectral target ID. IDList : Dictionary...
1b0b4097eeb493414b33aa55e4409d63f90af3eb
606,883
def BuildPairs(rows, cols): """Build closeness pairs for consecutive numbers. Build set of allowed pairs such that two consecutive numbers touch each other in the grid. Returns: A list of pairs for allowed consecutive position of numbers. Args: rows: the number of rows in the grid cols: the num...
2af7454dc07ecfc2ce4db1bf067661bb715bd4f3
606,884
def strike_through(text): """Replace ~~foo~~ with <s>foo</s> to support strike-through in output""" text = text.split('\n') for line_i, line in enumerate(text): if '~~' not in line: continue line = line.split('~~') parts = [] for part_i, part in enumerate(line): ...
3b0128035c183db9f6e273fb394456f91c9e0192
606,887
def get_builtin_code_from_operator_code(opcode): """Return the builtin code of the given operator code. The following method is introduced to resolve op builtin code shortage problem. The new builtin operator will be assigned to the extended builtin code field in the flatbuffer schema. Those methods helps to h...
b260c9c811f07ef12db3791ac3b9d1d3c44953ac
606,891
import time import calendar def mktime_tz(data): """Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.""" if data[9] is None: # No zone info, so localtime is better assumption than GMT return time.mktime(data[:8] + (-1,)) else: t = calendar.timegm(data) r...
d04d758642467b82df8fc5a42d323f9044129489
606,893
def celsius_to_fahrenheit(temperature): """Convert from Celsius to Fahrenheit :param temperature: degree understood to be in Celsius NOTE: Celsius to Fahrenheit formula: °F = (°C × 9/5) + 32 Multiply by 9, then divide by 5, then add 32. """ return 9.0 / 5.0 * temperature + 32
e3db99189f3a26b925a25f3a4164ac4a7bc34d3a
606,894
def read_color(input_func): """ Reads input color and lower cases it """ user_supplied_color = input_func() return user_supplied_color.casefold()
f29a5429c99e71b8578965645ae4909b868ec6ed
606,895
from typing import Tuple def get_bucket_and_key(s3_path: str) -> Tuple[str, str]: """ Get the S3 bucket and key given the full path. For example get_bucket_and_key("s3://foo/bar/test.file") returns ("foo", "bar/test.file") If the s3_path doesn't start with "s3://", it throws ValueError. """ ...
6ffb2e6cf2e8e786b163c80b440c12163b984032
606,896
import mpmath def interval_prob(x1, x2, a, b): """ Compute the probability of x in [x1, x2] for the beta distribution. Mathematically, this is the same as beta.cdf(x2, a, b) - beta.cdf(x1, a, b) but when the two CDF values are nearly equal, this function will give a more accurate result...
6bd34f64828165e3e48a810ac32a958300a38a33
606,903
def unravel_lm(el, m): """Get index from (el, em).""" return el * (el + 1) + m
dbbab7434b568aa11266ca66b9c42e2fb231b083
606,905
def max2(x,y): """ Returns: max of x, y This function shows the flow of if-else. Parameter x: first value Precondition: x is a number Parameter y: second value Precondition: y is a number """ # Put max of x, y in z print('before if') # trace if x > y: prin...
fb9ea81c100d4705ec250cf96cea6eba90f06a80
606,910
def insert_in_front(val, seq): """ >>> insert_in_front(5, [1, 3, 4, 6]) [5, 1, 3, 4, 6] >>> insert_in_front(5, (1, 3, 4, 6)) (5, 1, 3, 4, 6) >>> insert_in_front('x', 'abc') 'xabc' """ if type(seq) == list: seq = [val] + seq return seq elif type(seq) =...
fe46d787cd7373a9e7d735e2bae2e3eb816d52b8
606,912
import torch def merge_lists(input_list): """ input_list = list:time[ list:level[4D tensor] ] output_list = list:level[ 4D tensor (batch*time, channel, height, width)] """ len_tt = len(input_list) len_ll = len(input_list[0]) output_list = [] for ll in range(len_ll): list_ll = ...
3de262e4cd6da6a79988b329d33f82831d65d494
606,915
from typing import Dict from typing import Tuple from typing import List def filter_eyes_landmarks( landmarks: Dict[int, Tuple[int, int]] ) -> List[Tuple[int, int]]: """Collect eyes landmarks""" eyes_indexes = list(range(37, 48)) out_arr = [] for (k, v) in landmarks.items(): if k in eyes_i...
bbbb46b89cecfdefad532d3cd9852b4c39817b99
606,919
def _ensure_width(inp: str, width: int): """ Ensure that string `inp` is exactly `width` characters long. """ return inp[:width].ljust(width)
ed8ef2e184d2ea00027ed2648adc33927580e694
606,920
def get_homogeneous_attack_rate(df, R0_star): """ Get the attack rate for an SIR model with the homogeneous mixing assumption for a given basic reproduction, R0_star, value. Args: df (pd.DataFrame) : a dataframe of attack rates by the basic reproduction number R0_star (float) : the basic ...
d3998347032ec2a36dd99a17df9b7dcdd4b8b213
606,921
def addHtmlBreaks(inStr, nChars): """Adds an html line-break every nth character, and returns the resulting string.""" strWithBreaks = "" strIdx = 0 while (strIdx < len(inStr)): if (((strIdx + 1) % nChars) == 0): strWithBreaks = strWithBreaks + "</br>" strWithBreaks = str...
3b42e85d50324814579fd62080fbb29c962c4308
606,928