content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def convert_to_dict(data): """Returns a dictionary of US state and the total number of COVID-19 cases as key-value pairs. Parameters: data (list): a list of lists that contain states and total number of cases Returns: dict: a dictionary that contains state and the total number of cases as ...
55ce00b08a6f4b1e21d08df101ccb7cb639fbd1d
629,242
def SUBTRACT(x, y): """ Subtracts two numbers to return the difference, or two dates to return the difference in milliseconds, or a date and a number in milliseconds to return the resulting date. See https://docs.mongodb.com/manual/reference/operator/aggregation/subtract/ for more details :p...
096f22edbde4a330c486dca51299d76d4ed173f0
629,245
def cc(key): """ Changes python key into Camel case equivalent. For example, 'compute_environment_name' becomes 'computeEnvironmentName'. :param key: :return: """ components = key.split('_') return components[0] + "".join([token.capitalize() for token in components[1:]])
311d253842638f581dd1dd051270f3d6098e2955
629,247
import re def parse_remote_states(tf_content): """ Parse remote states configurations from the provided file content. Returns a list of tuples. Ex.: ('foundation', 'gc://tf-bootstrap-vdf/terraform/foundation') Sample configuration: data "terraform_remote_state" "foundation" { backend = "gcs" config ...
b395108991ab11ec18b2737c63abf7ecf2a3ac78
629,249
def clamp(n, smallest, largest): """Ensure 'n' is no smaller or larger then a certain range. If the number is smaller than the range it will be returned as the smallest. If the number is larger than largest it will be returned as the largest. Args: n (int): integer to inspect ...
51fb99ddc7c1f468232c077a9f75542203b63514
629,250
def run_verbose(message, fn, args=[]): """ Calls the function provided by 'fn' with the parameters provided in 'args'. Prints '[message] ... done', with '[message] ...' printed at the start of the function call and 'done' printed at the end of the function call. """ print('{} ...'.format(message...
c6916cf5d99973f764b10ad2c61c34516417e3c5
629,251
def xtick_formatter(x, pos): """ A formatter used in main_paper function to divide ticks by specific amount. From Stackoverflow #27575257 """ s = '%d' % int(x / 1000) return s
e34e5ad57d58275c5bb79d72536084a80129a980
629,256
def sum_htcl_branches(nested_dict, adj_frac, sum_val): """Sum all leaf node values under a given nested dict level. Args: nested_dict (dict): The nested dict with values to sum. adj_frac (dict): Adjustment fraction to apply to values. sum_val (dict): Summed values. Returns: ...
9543150451c192c9953577af44032c8b6530f0fa
629,257
def remove_undefined(payload: dict) -> dict: """Takes a dictionary and removes keys without value""" return {name: value for name, value in payload.items() if value is not None}
5253a2340afdf0d8d431cd85d5a99b74ee8552cd
629,264
import socket def send_all(s, text, stutdown_after_sending=True): """send_all(socket, text, stutdown_after_sending=True) Send all text to the socket. Used during handshaking and in the clientserver module. If stutdown_after_sending, the socket is shut down. Some protocols rely on this. It i...
5f24df23db227f021746d3cf37b84f361259294a
629,266
def adjust_repeat_data(li, suffix='+'): """ 分析序列li里的值,对出现重复的值进行特殊标记去重 :param li: list,每个元素值一般是str :param suffix: 通过增加什么后缀来去重 :return: 新的无重复数值的li >>> adjust_repeat_data(['a', 'b', 'a', 'c']) ['a', 'b', 'a+', 'c'] """ res = [] values = set() for x in li: while x in values:...
6b5f01bf2a39840d5e9ff0f28420c34aeddba4e6
629,268
from typing import Any def update( dct: dict[str, Any], dct_merge: dict[str, Any], ) -> dict[str, Any]: """Recursively merge dicts.""" if not isinstance(dct, dict): return dct for key, value in dct_merge.items(): if key in dct and isinstance(dct[key], dict): dct[key] = ...
ac7ecc086b668da2122220c7ad4309257e678110
629,269
import json def to_json(response): """Convert raw response into json output.""" return json.dumps(response, indent=2)
a6bcbe8765c9eaeeb335e2b95c151af13527c204
629,272
def mock_pack_data(name='SomePack'): """ Creates mock data to create a pack. """ data = { 'name': name, 'submit': '' } return data
e56fa55a0989a1d8e6d2c6b123597bec7125e110
629,273
import calendar def millis(input_dt): """Convert datetime to milliseconds since epoch""" # Python 3 (or 2 with future module) return 1000 * int(calendar.timegm(input_dt.timetuple())) # Python 2 # return 1000 * long(calendar.timegm(input_dt.timetuple())) # return 1000 * long(time.mktime(input_d...
e337830774554a1e382dc4fdc74806703f33d98b
629,280
import pickle def load_data(filename): """Return a Data object loaded from the given pickle file.""" with open(filename, "rb") as f: return pickle.load(f)
91c9d3b9a66a5603992b32be3eb758c88e21dd1c
629,282
def get_fields(db, fields_sql): """ Calls the database and gets fields information. Input: database connection object, SQL query Returns: dictionary of student information, key=field name """ fields = {} with db.cursor() as cursor: cursor.execute(fields_sql) for id, name, fu...
6f0345af4be9eca3214bf5b66e972aaea138778b
629,283
def first(predicate, iterable): """return first element in iterable that satisfies given predicate. Args: predicate: a function that takes one parameter and return a truth value. iterable: any iterable, the items to check. Return: first element in iterable that satisfies predicate,...
c090bb223cb7b83d5f471fdeb6f6b3dc871484c1
629,285
import string import random def random_string(count=10): """ Return a random string with the length of given count. Args: count: the count of random charactors to return. (default: 10) Returns: string, with random charactors, with the length of count. """ charactors = string....
37768b1565c5d8f577e5c88b4df5cef269392a66
629,290
def unflatten(data, dims): """ Given a batch of flattened 1-D tensors, reshapes them into specified N-Dims. """ B = data.size(0) return data.view(B, *dims)
d9ac2fbaa695213d42e785027a6d36899f2da2ac
629,292
from typing import Tuple def complete_index(index: Tuple, n_dims: int) -> Tuple: """ Complete the index with empty slices. This will expand ellipses if present, or pad at the end if not. Args: index: The index in which to replace ellipses n_dims: The number of dim...
d268c7abf9680842dab38f407fed0498c6164b18
629,295
def calc_PV_power(absorbed_radiation_Wperm2, T_cell_C, eff_nom, tot_module_area_m2, Bref_perC, misc_losses): """ To calculate the power production of PV panels. :param absorbed_radiation_Wperm2: absorbed radiation [W/m2] :type absorbed_radiation_Wperm2: float :param T_cell_C: cell temperature [degr...
31673aaf6d693fba150975841b3ae2717f7d0d5c
629,298
def power_law_vband_norm(x, slope): """Power law normalised at 0.55 microns (V band).""" return (x / 0.55) ** slope
93569ef42998e324a3beda3ec4693b62328c713f
629,300
def get_chrom_sizes(fai_file, exclude_scaffolds=True): """ Get the names and sizes of all the chromosomes in a reference by iterating over the index. """ chroms = {} with fai_file.open('r') as fin: for line in fin: # get the chrom name and size contig, size, _, _, _ ...
a04bf433cf51fd9732e4528e7e861cbb161c40ab
629,302
import pprint def pformat_truncate(o, width=50): """Convert the object to printable representation and truncate it if too long Note: If the object is a multiline string or pformat returns a multiline string, only the first line of the string will be returned Args: o (object): Object to...
9119054d8c473f8906fc223b727b41785e4ca12f
629,306
def create_schema_name(account): """Create a database schema name.""" return f"acct{account}"
ab90ec89f353f41ac9643f1aca44ab3d52bd2fa5
629,310
def specific_match(versions, position=0): """Matches a specific position in a trie dict ordered by its keys Recurse on the trie until it finds an end node (i.e. a non dict node) Position = 0 indicates it will follow the first element Position = -1 indicates it will follow the last element """ if...
bfccc9f3a6fcd4cfeab3c0cbd0d27ec5a32256f9
629,312
def divide_by_four(a): """Return a / 4. """ return a / 4.0
ff64759a439a95626ee60eb18614d9ab18636f82
629,313
def int_tuple(arg): """Convert a string of comma separated numbers to a tuple of integers""" args = arg.split(',') try: return tuple([int(e) for e in args]) except ValueError: raise ValueError('Expected a comma separated list of integers, ' + 'found %s' % arg)
dc6c94f8efbeee3352570d8a32b85dc3c9a7a908
629,314
def find(word, letter, start): """Modify find so that it has a third parameter, the index in word where it should start looking.""" if start > len(word): return -1 index = start while index < len(word): if word[index] == letter: return index index = index + 1 ret...
bad8ff0af68b10b002279d13d0ceb021622c001b
629,315
def format_perc(x, dec_places=1): """ format_perc x: a number to format as a percentage dec_places: an integer for the number of digits past the decimal """ format_str = '{{:,.{}f}}%'.format(dec_places) return format_str.format(float(100*x))
1a57d0bda0dd1c7a5734d29fd77db8edc09328a7
629,316
def find_service_roles(roles, type): """ Look for roles like spark_worker, spark_master, namenode, ... We will have duplicate roles depending on how many host are running the same role :param roles: list of service roles :param type: the type of role we are looking for, ie "SPARK_MASTER" :retur...
07353d2c2328ef805309794adf5b63516f7c50c1
629,318
def check_puppet_class(rec): """ Checks if the given file is a puppet class :param rec: file path :return: check result """ return rec.lower().endswith(".pp")
93e0f57c44c6b942488c0281e7a6fe6c735bc6fc
629,320
import math def surface_disque(rayon): """ fonction qui calcule et renvoie la surface du disque :param rayon: le rayon du disque :type rayon: int ou float :return: la surface du disque (unité (au carré) de celle du rayon) :rtype: float """ return math.pi*rayon**2
424b81b84c21a8e1f848497124bcff971b7f0e15
629,322
def get_datetime_str(record): """ Get the datetime string for a record. Args: record: the record to get data for. Returns: datetime string. """ return str(record.getDataTime())[0:19].replace(" ", "_") + ".0"
93bab7ed0457d372e9cd556e280eb4fa963e9fcd
629,325
def find_average_score(generation): """ Generation is a dictionary with the subjects and score. Returns the average score of that generation """ sum = 0 for score in generation.values(): sum += score return sum/len(generation.values())
8fb830914824fda08d1e925e2dbe37fb20d1b4bd
629,326
import inspect def method_name(caller_depth=0): """ Returns the name of the caller method. """ # Note: inspect.stack()[0][3] would return the name of this method. return inspect.stack()[caller_depth+1][3]
f90997a9e31a1de16edc7c87adf643a013965ee1
629,329
def _is_earlier(t1, t2): """Compares two timestamps.""" if t1['secs'] > t2['secs']: return False elif t1['secs'] < t2['secs']: return True elif t1['nsecs'] < t2['nsecs']: return True return False
d726384c72dd8e702a4251346b3e6b8a339d597c
629,333
def eq_tokens(token_sequence1: str, token_sequence2: str) -> bool: """Returns True if bothe token sequences contain the same tokens, no matter in what order:: >>> eq_tokens('red thin stroked', 'stroked red thin') True >>> eq_tokens('red thin', 'thin blue') False """ retu...
06e51bf34e063ae8d3b9724f054764b61a043d01
629,334
from typing import List from typing import Tuple from typing import Any def simple_producer(key, value) -> List[Tuple[Any, Any]]: """simple_producer A function that returns the key,value passed in for production via "KafkaProducerOperator" :param key: the key for the message :type key: Any :param val...
1c04821f7db789c73be4533f60206e5196ab98d4
629,335
import torch def process_data(file_name, tokenizer, max_size=None): """Reads the line of a file and segments the lines using the tokenizer Args: file_name (str): Full file path tokenizer (:obj:`WMT16Tokenizer`): The tokenizer to use max_size (Optional[int]): The maximum size of result...
19244f25bec78786badea778f149e8991e9a318a
629,337
def get_out_dir(request): """ Get the temporary output directory for writing files to """ return request.fspath.join("..") + "/tmp"
e178e91434c04bd97d7c0fbdc0d0ea379d525059
629,339
def string_to_bytes(string): """ Convert a string to NULL-terminated ASCII string. """ return bytearray(string, encoding='ascii') + b'\x00'
0c66ba9f9364cc02e74473450e785b887a6f5cec
629,340
def isheader(string): """ Check if a string looks like a star header line. Args: string (str): line of a star file Returns: true if the line looks like a star file header lines false if the line is expected to be a star file data line. """ try: string = string.de...
1f8a9ff2ec7ee24818c0f7bbfcd90ed5bf74fbf8
629,349
def tuple_setter(tensor, idx_tuple, val): """ Sets a tensor element while indexing by a tuple""" tensor_ = tensor for el in idx_tuple[:-1]: tensor_ = tensor_[el] tensor_[idx_tuple[-1]] = val return tensor
269826fe5757b63214d4cca7e37a25a1eb2ba454
629,351
def is_ask_help(text: str) -> bool: """ A utility method to tell if the input text is asking for help. """ sample_phrases = [ "help", "help me", "i need help", "i'm lost", "i am lost" ] text = text.strip() return any(text == phrase for phrase in sample_phrases)
994ac984c69b77c869f0f28c5ee77a082e76c909
629,353
def minus(first, second): """The difference of two numbers""" return first - second
3ef4b455558a91a5831ac8cc9067055ab09942c3
629,359
import math def _find_poles(damping, freq): """Find roots of equation s^2+2hws+w^2=0 Parameters ---------- damping: float Damping constant. freq: float Angular frequency. """ real = -damping*freq imaginary = freq * math.sqrt(1 - damping*damping) return real, imag...
53be0f5e645163395f2ab9ec167e500adab6f8da
629,360
def pot_harmonic(x, x0, k): """ pot_harmonic(x, x0, k) Returns harmonic potential from displacememt of x away from x0 """ return k * (x - x0)**2
9b2ad50b848baf2b4354d8820f5e7f0ae9cee39f
629,366
def int_to_mac(integer): """ Converts a an integer into a mac address, with `:` notation. Arguments --------- integer: int Returns ------- str """ first = "{:012x}".format(integer)[::2] second = "{:012x}".format(integer)[1::2] return ':'.join(a + b for a, b in ...
d4374e56a20ce444070679ff4830630302a8ccdd
629,367
def coord_2_id(x, y): """Give the pinID from the x,y coordinate.""" return (34 - y) * 34 + x
e02c03f0761ea7adfb6d50332ded3b0a82c2b016
629,372
from typing import Dict from typing import Any from typing import Mapping import itertools def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool: """Check that nothing will be overwritten when dictionaries are merged using `deep_merge`. Examples: >>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3...
1f666a79952c4a667ff3d27c92b1dae816c33ed6
629,373
def emission_probability(symbol, word, emission_probabilities, symbol_counts): """ Takes a symbol, a word, a nested dictionary of emission probabilities, and a dictionary of symbol counts and returns the emission probability for that symbol and word If the word has not been encountered in the traini...
df41ef4bbb01e993416c8e5e581e44b2a5292fa3
629,375
def _make_qa_class(type_class, mode_class, p_name, p_description, p_software): """Create and return a new class to represent a QA metric""" class QA(type_class, mode_class): name = p_name __doc__ = p_description software = p_software QA.__name__ = p_name return QA
e37f36a5bce075e9572e34437bc13525886219bf
629,378
import re def __highlight_fuzzy_string(target: str, search_value: str) -> str: """ Highlight every existence of target in the search_value with the <em> tag. This <em> tag can be replaces with any other tag. :param target: the haystack to search in :param search_value: the needle to search for ta...
46b1d6d8d02a920faa4338be62311d3b62af960f
629,379
def url_file_name(url: str) -> str: """ Extract file name from url (last part of the url). :param url: URL to extract file name from. :return: File name. """ return url.split('/')[-1] if len(url) > 0 else ''
38ea970f26f439119ad8bb8312ff9e393bf7e431
629,384
def _add_box_and_whiskers(canvas, quantiles, limits): """Add a box and whiskers to the canvas""" for jj in range(5): canvas[quantiles[jj], limits[0] + 1 : limits[2]] = 20 canvas[quantiles[0] + 1 : quantiles[1], limits[1]] = 22 canvas[quantiles[3] + 1 : quantiles[4], limits[1]] = 22 canvas[...
5032a40edad1d99c4818e9c1e020375312c6797c
629,389
def convert_kicad_coor(edif_pt): """ KiCAD schematic coordinates are 10 times EDIF Y axis is flipped """ scale = 10 return [edif_pt[0] * scale, -edif_pt[1] * scale]
ee4b5e5d2aa5a50fac73cd1d4a5e4ce604ea5711
629,390
def fake_request(*responses): """ Creates a request function that returns the supplied responses, one at a time. Making a new request after the last response has been returned results in a StopIteration error. """ iterator = (response for response in responses) def request(method, url, **kwargs...
e5a9a190129587f0c76fcabddfaca487fab3bd0c
629,393
def rovarspraket(english): """Translates input to rovarspraket""" for low, upper in zip("bcdfghjklmnpqrstvwxyz", "BCDFGHJKLMNPQRSTVWXYZ"): english = f"{upper}o{low}".join(f"{low}o{low}".join(english.split(low)).split(upper)) return english
7d234968c1edd1461b64359697d8d4fef592fcec
629,394
import re def iscrcard(value): """ Return whether or not given value is a credit card. If the value is a credit card, this function returns ``True``, otherwise ``False``. Examples:: >>> iscrcard('375556917985515') True >>> iscrcard('5398228707871528') False :par...
d77e6f15255f57e83a295f875c02ea6a7643d37c
629,396
def compute_scale_factor(height, size): """ Compute gallery conversion scale factor as a percentage. """ landscape = True source_width = size[0] source_height = size[1] if source_width < source_height: landscape = False if landscape: return height/source_height * 100 ...
18fb5f160c893d685248d88059814da50064e369
629,397
def utc_time(source): """Convert source bytes to UTC time as (H, M, S) triple HHMMSS.000 >>> utc_time(b'123456.000') (12, 34, 56.0) """ if source: return int(source[:2]), int(source[2:4]), float(source[4:]) return None, None, None
97d651d615262d19df84eda71085e54d0b39cb19
629,400
import re def quoted_split(string_to_split, preserve_quotations=False): """ Function to split string into list of words but preserves quoted sub strings. found here: https://stackoverflow.com/a/51560564 Parameters ---------- string_to_split : string the string to split preser...
c57eeb0c4118955baf8a3233c5e3c295063535b4
629,403
def segment_length(curve, start, end, start_point, end_point, error, min_depth, depth): """Recursively approximates the length by straight lines""" mid = (start + end) / 2 mid_point = curve.point(mid) length = abs(end_point - start_point) first_half = abs(mid_point - start_point) second_half = a...
521391bd0d818c33f927a687913d9812350b8168
629,405
def get_highest_priority_reachable(Sr): """ Sr: The remaining unconsidered part of the original solution Return: the highest priority rule which is also reachable, i.e. that is to say it is in table 1. Or None if no rules are reachable. """ reachable = [r for r in Sr if r.tab...
0db461c71b79f10f0e239fd6c48658c0d1fdfc2e
629,411
import re def parse_line(line): """ This function is needed to parse one-liner from the controller and extract the information we need :param line: a one line of output from "show ap database long" command :return: object, representing AP and it's key values, like MAC-address or given name """ ...
d0193154d2306c305a4a5f058ec388c16b84dced
629,412
def emc(values: list) -> float: """ Fraction of empty cells """ if len(values) == 0: return 0.0 empty_cells_count = sum([ 1 for v in values if len(v.strip()) == 0 ]) return empty_cells_count / len(values)
5cd78f65ba1b536ad6efdddf29be0981ad3a8b45
629,413
def create_search_group(recordset = None, field = None, values = None, criteria_operator = "EqualTo"): """ Create a Coalesce search group/filter object (the value of "group" in a `Coalesce search request object <https://github.com/InCadence/coalesce/wiki/REST-API#search-query-dat...
b55e37f2df255b19e8e12566031cf7f784ff094b
629,414
def __is_org(string: str) -> bool: """ Return if a given string is an org directive :param string: String to check for org. :return: True if org. """ return string.startswith("org ")
7d6300a7e582c1d9cdacb648cfc1f4ff969c3be1
629,419
def empty_fld_dict(names): """creates a dictionary with expected field names initialized to none """ return {_f:None for _f in names}
996fbb41cb792b2a2fc2e8dded3420a841600431
629,420
def optlist_to_dict(optlist, opt_sep=',', kv_sep='=', strip_quotes=False): """Parse an option list into a dictionary. Takes a list of options separated by ``opt_sep`` and places them into a dictionary with the default value of ``True``. If ``kv_sep`` option is specified then key/value options ``key=va...
ad554763610d1f4cc95faefabb9218477a5f80ce
629,424
def unwrap_string(s): """A utility function that converts a "'string'" to a "string" """ s = s.replace("'", "") return s
62fd829604123cb53a40f8d496fe8082f406b9d1
629,425
def is_even(n: int) -> bool: # suggested solution """ Check if a given number is even Using modulo 2, and checking if the remainder is zero """ return n % 2 == 0
e49e3a5bfbf565071d363f6eadcd8604bc0cdfe3
629,426
import torch def calc_total_loss(flow, data): """ Compute total loss of model on data. Parameters ---------- flow : nflows.flows.Flow Normalising flow, instance of Flow object from nflows.flows, generated from e.g. load_flow() or setup_MAF(). data : torch.Tensor, shape (N, n_d...
38b21d43c7fdf023a8f1e2f8382c575219c3f4f7
629,427
def titlecase(string: str): """Safely recast a string to title case""" try: return string.title() except AttributeError: return string
eb13947c6f59069a6a3ab4b42d77931e3f5bc740
629,432
import json def dumps_tree(tree, duplicate_action = 'list', **kwargs): """ Dumps a Tree as json.dumps. First converts to_python using duplicate_action. Additional kwargs are sent to json.dumps. """ obj = tree.to_python(duplicate_action = duplicate_action) return json.dumps(obj, **kwargs)
3419ef28cce2c77605ec9fedca173dcbc7ed6b8b
629,433
def _get_indices(topology, residue_name): """ Get the indices of a unique residue in an OpenMM Topology Parameters ---------- topology : openmm.app.Topology Topology to search from. residue_name : str Name of the residue to get the indices for. """ residues = [] for ...
396a888c92a1b002bdaf7fd757577cda13824ea5
629,435
def construct_select_original_bericht_query(bericht_uri): """ Construct a SPARQL query for selecting the first message in a conversation :param bericht_uri: URI of a bericht in a conversation :returns: string containing SPARQL query """ q = """ PREFIX schema: <http://schema.org/> ...
66be0a019b4bb64c7a3d4a96866a2a695981d9b6
629,438
def is_fq_local_branch(ref): """Return True if a Git reference is a fully qualified local branch. Return False otherwise. Usage example: >>> is_fq_local_branch("refs/heads/master") True >>> is_fq_local_branch("refs/remotes/origin/master") False >>> is_fq_local_bra...
455e8bc4897155292bb36f359db46952d8d74f95
629,442
import csv from typing import OrderedDict def load_tab_delimited_csv(filepath): """ loads a tab delimted csv as a list of ordered dictionaries """ data = [] with open(filepath) as file: reader = csv.reader(file, delimiter="\t") header = [] for csv_row in reader: ...
7a04ebc88b4f661af2bc64404ceab0ee311078d1
629,444
def move_consonant_left(letters: list, positions: list) -> list: """Given a list of letters, and a list of consonant positions, move the consonant positions to the left, merging strings as necessary. >>> move_consonant_left(['a', 'b', '', '', 'bra'], [1]) ['ab', '', '', '', 'bra']""" for pos in p...
3a1faae1c1ab9bec1fb077d8264cdd0474eba82a
629,445
import glob from pathlib import Path def get_mas_variables(path): """ Return a list of variables present in a given directory. Parameters ---------- path : Path to the folder containing the MAS data files. Returns ------- var_names : list List of variable names presen...
ec0c218d850d93034ce2008f7f0d12a7267a04c5
629,451
def bundle(*addable): """ Getting addable objects (such as Matching) and composing them to one. When nothing is provided, this will raise a ValueError """ if len(addable) <= 0: raise ValueError('Provide at least one Matching object') return sum(addable[1:], addable[0])
37ded01839005e954c8ae7f8491a870b30b58e86
629,455
def find_fomoists(events_attendees, rsvp_statuses=['attending']): """ "events" is a list of lists of attendees: [ [ { "name": "Brittany Miller", "rsvp_status": "attending", "id": "1442173849420454" }, ... ] ... ] ...
80a43ebc531456315157d14c932629c8e496c5d3
629,459
def get_id(record): """ Returns the Amazon DynamoDB key. """ return record['dynamodb']['Keys']['id']['S']
4211d847a382a8220bf842176266f7b7b9ece6fd
629,463
def join_string(phrase: str, join_s: str): """ Take the 'phrase' and intersperse it whit 'join_s' string :param phrase: string to be interspersed :param join_s: string :return: interspersed string """ return join_s.join(phrase)
380fa1b7ee9ea6cb4ee5b1e75b4dc32b0daecead
629,465
from typing import Counter def list_duplicates(iterable): """Return a set of duplicates in given iterator.""" return {key for key, count in Counter(iterable).items() if count > 1}
5d11aa77f774ff4e700c2a5ffce9bb189d38bbea
629,469
def makeFullName(parScope, parName): """ Create the fully-qualified name (inclues scope if used) """ # Skip scope (and leading dot) if no scope, even in cases where scope # IS used for other pars in the same task. if parScope: return parScope+'.'+parName else: return parName
0dda72bb1ed8a6f82eaa34362834d2329bae9630
629,471
def selectPivotIndex (ar, left, right, comparator): """Select pivot index for ar[left,right] inclusive using comparator.""" midIndex = (left + right)//2 lowIndex = left if comparator(ar[lowIndex], ar[midIndex]) >= 0: lowIndex = midIndex midIndex = left # when we get here, ar[lowInd...
6d57c1931777fdd4335a674f8a8374c1243e1dc6
629,473
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths): """ Calculate the maximum metric value when we have multiple ground truths. i.e., for each question, we have multiple answers. :param metric_fn: the function to calculate metric :param prediction: our model predicted answer str...
869d0cbc4c8f813c2ef5a789bf75ffa8bf987560
629,478
def flatten_forward(x_input): """Perform the reshaping of the tensor of size `(K, L, M, N)` to the tensor of size `(K, L*M*N)` # Arguments x_input: np.array of size `(K, L, M, N)` # Output output: np.array of size `(K, L*M*N)` """ K, L, M, N = x_input.shape output = x_in...
0767220baa652e5f4c6efbca7b3ffdb03f71902b
629,482
def is_inside(center_point, corner_point): """ Find if center_point inside the bbox(corner_point) or not. :param center_point: center point (x, y) :param corner_point: corner point ((x1,y1),(x2,y2)) :return: """ x_flag = False y_flag = False if (center_point[0] >= corner_point[0][0])...
1254990b9a775a56a09448f44965aeba7bc59a4d
629,483
def contains_embedded_molfile(field_value): """Returns True if the RD file $DATUM field value contains an embedded molfile, otherwise returns False.""" return field_value == '$MFMT'
ee800e23710d73f54ef4792f0b49e27caa98c5bc
629,484
def flatten(d, sep='.', flat_type=dict): """Flatten a nested dict using a specific separator. :param sep: When None, return dict with tuple keys (guaranties inversion of flatten) else join the keys with sep :param flat_type: Allow other mappings instead of flat_type to be fl...
e9e1f6efc2fb677e1f5661797deb5398a469c5ec
629,485
import torch def reverse_letter_box(h, w, input_size, boxes, xywh=True): """ :param h: 输入网络的图片的原始高度 :param w: 输入网络的图片的原始宽度 :param input_size: 网络的固定输入图片大小 :param boxes: Tensor, shape: (..., 4(cx, cy, w, h)) :param xywh: Bool, True:boxes是(cx, cy, w, h)格式, False: boxes是(xmin, ymin, xmax, ymax)格式...
2d7f37ef4328d2848bade47d7808455d46012863
629,488
import json def save_json(data, path_target: str): """ Saves json data to file at given path. :param data: Json to save. :param path_target: Path where to store the json data. String. """ with open(path_target, 'w') as outfile: json.dump(data, outfile) print('Json saved to:', path_...
d8ce4bd067f20dcfaf0c99c7d3a869587b631ab2
629,494
from pathlib import Path import string def alphabet_file(tmpdir): """Fill a temporary file with the alphabet, one letter per line.""" filename = Path(tmpdir) / "data" open(filename, "w").write("\n".join(string.ascii_lowercase)) return filename
7591f0bf1a1b54e16a6fd5cb06846a7ff231bf2d
629,495
import json def parse_json_string(json_string): """Parse json string to object, if it fails then return none :param json_string: json in string format :type json_string: str :return: object or none :rtype: dict/None """ json_object = None if not isinstance(json_string, str): ...
71552552022cc82c425780fe8713e17d91ebc8b7
629,501
def chunk_into_passages(doc_offsets, doc_stride, passage_len_t, doc_text): """ Returns a list of dictionaries which each describe the start, end and id of a passage that is formed when chunking a document using a sliding window approach. ""...
af76dd6f994c3eeb26175c0cf7fa05761b85749d
629,505