content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import copy def get_social_config(env): """ Arguments: env: Arena-Blowblow-Sparse-2T2P-Discrete Returns: [[0,1],[2,3]] """ xTxP = env.split("-")[-2] T = int(xTxP.split("T")[0]) P = int(xTxP.split("T")[1].split("P")[0]) policy_i = 0 all_list = [] for t in ran...
09781e93b2339ab0df262fdd6968aa94626f9ef2
677,092
def delete_at(my_list=[], idx=0): """ deletes an element from a list at a given index """ l_len = len(my_list) if idx >= l_len or idx < 0: return (my_list) del my_list[idx] return (my_list)
63c1897eb87a2feed7c013c0b277bacd7d3f61d5
677,093
import random def _get_pin(length=5): """ Return a numeric PIN with length digits """ return random.sample(range(10**(length-1), 10**length), 1)[0]
f24ce227d88a63a429475b07df761babb3d35c97
677,095
def swap_byte_order(arr_in): """Swap the byte order of a numpy array to the native one. Parameters ---------- arr_in : `~numpy.ndarray` Input array. Returns ------- arr_out : `~numpy.ndarray` Array with native byte order. """ if arr_in.dtype.byteorder not in ("=", "...
ac583be80cdc417e990dd883ea5e7efd0dedcc4c
677,097
def determineTranslation(translation,reference_orientation): """ Convert a translation in the world reference frame to a translation in the steroid reference frame. """ return translation*reference_orientation.I
315905b96818f6474f6f27f3db9f91da1b8bf14a
677,107
def is_empty(value: object) -> bool: """ Check if value is None or not empty in case if not None. """ return (value is None) or (not value)
88b848e6a25da134a3408def4db83d258a031919
677,108
def count_attached(mol): """ Counts the number of atoms labelled 'attached'. Parameters ---------- mol : :class:`rdkit.Chem.rdchem.Mol` A molecule to have 'attached' atoms counted. Returns ------- :class:`int` The number of atoms with the property 'attached' in `mol`. ...
4fee5a3aa650609e1365fbb2e6b73dedffcf5e24
677,110
def remove_method_from_itemname(itemname): """Return an itemname without any method name in it""" return itemname.split(':')[0]
3b55116dfd88d4348e968ffdbcae0f2f3a9398d4
677,111
def num(s): """Function will try to convert the variable to a float. If not possible it will return the original variable.""" try: return float(s) except: return s
d867980a3663a13af12f25e750cc03f638e4cabd
677,112
import inspect def is_class(obj): """ Returns True if obj is a class, else False. """ return inspect.isclass(obj)
5a49139a19ca9b2d0108e1db10a1d558b81ed5de
677,113
def sum_even_values(d: dict) -> int: """Returns the sum of all even values in d, using recursion if d contains nested dictionaries.""" total = 0 for value in d.values(): if type(value) == int: if not value % 2: total += value elif type(value) == dict: ...
3de76e3ac86ce7958f9f07584103229f70950da4
677,114
import re def string_builder(string): """ To match DaCe variable naming conventions, replaces all undesired characters with "_". """ newstring = string if string[0].isdigit(): newstring = "_" + string out = re.sub("[^a-zA-Z0-9_]", "_", newstring) return out
cbb1ec2270c6fab997dd2dfd69a26339abf05728
677,115
def translate_service_orm_to_json(orm): """Translate ORM to JSON for response payload.""" ret = {"service_id": orm.service_id, "schema": orm.schema, "config": {}} for config in orm.configs: if config.hostname not in ret["config"]: ret["config"][config.hostname] = {} ret["config"]...
2f0c26dfbf00d9d703200512c1874d49494658dd
677,124
import inspect def _is_non_defaulted_positional_args(param: inspect.Parameter) -> bool: """Returns True if `param` is a positional argument with no default.""" return ((param.kind == param.POSITIONAL_OR_KEYWORD or param.kind == param.POSITIONAL_ONLY) and param.default is param.empty)
a001f9130f3e5be1acad61959faf5e9ef66c19f1
677,127
def idems(dit): """Convenience function for iterating dict-likes. If dit.items is defined, call it and return the result. Otherwise return dit itself. """ return dit.items() if hasattr(dit, 'items') else dit
e9fa755e7187bee24a1682380c62d38bd9d8a50d
677,128
def parse_data_url(data_url): """ Parse a data url into a tuple of params and the encoded data. E.g. >>> data_url = "data:image/png;base64,ABC123xxx" >>> params, encoded_data = parse_data_url(data_url) >>> params ('image/png', 'base64') >>> data 'ABC123xxx' """ # e....
b06819b02d4453ec60b9875251484f01b19aa09f
677,136
def are_strings(*args): """Tells wheter all the argument passed are of type string""" return all(map(lambda _: type(_) is str, args))
88277b7be08d6cc1a0fdbc1300f955797000c53b
677,137
def get_host(environ): """ Return the real host for the given environment. """ if 'HTTP_X_FORWARDED_HOST' in environ: return environ['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in environ: return environ['HTTP_HOST'] result = environ['SERVER_NAME'] if (environ['wsgi.url_scheme'...
5d8bedd1d4bdfe80ff135042929649d1e0d5e826
677,140
def any_difference_of_one(stem, bulge): """ See if there's any difference of one between the two ends of the stem [(a,b),(c,d)] and a bulge (e,f) :param stem: A couple of couples (2 x 2-tuple) indicating the start and end nucleotides of the stem in the form ((s1, e1), (s2, e2)) :pa...
8fbd986943286443f9a177a5b3336fa920fbd649
677,142
def fuzzy_not(mfx): """ Fuzzy NOT operator, a.k.a. complement of a fuzzy set. Parameters ---------- mfx : 1d array Fuzzy membership function. Returns ------- mfz : 1d array Fuzzy NOT (complement) of `mfx`. Notes ----- This operation does not require a unive...
f96d1c90838789daa204f1d61db62cb9736d9ab1
677,145
def get_group_cv_splits(groups, cv): """ Presplit the groups using the given cross-validation scheme. Normally, the train/test split is done right before training and testing, but this function will presplit the data for all cross folds before any training/testing is done. This is us...
1eeea2193d836b48a03dac56b3ae94af2b31839c
677,147
def power_pump(flate_pump_feed, rho_F, g, head_pump, ECE_motor, ECE_trans): """ Calculates the power of pump. Parameters ---------- flate_pump_feed : float The flow rate pump for Feed [m**3 / h] rho_F : float The density of feed, [kg / m**3] head_pump : float The hy...
9571fe2c80c2da9d69b51ec52ac2b8942b267261
677,149
def bin2hex(strbin): """ Convert a string representing a binary number into a string representing the same value in hexadecimal format. """ dic = { "0000":"0", "0001":"1", "0010":"2", "0011":"3", "0100":"4", "0101":"5", "0110":"...
7069dba59e699acbeb53cf9ea78c8e169ce60de9
677,150
def walk_derivation(derivation, combiner, leaf): """ Traverse a derivation as returned by parser.item.Chart.kbest. Apply combiner to a chart Item and a dictionary mapping nonterminals (and indices) to the result of all child items. """ if type(derivation) is not tuple: if derivation =...
ab4b9b1c3d5cf9ae2b053f8de8b832892c77634e
677,152
import re def get_skipped_reason(data): """Return test case skip reason from report string. Args: data(str): test case report Returns: str: skip reason or None """ try: reason_rules = re.compile("Skipped:(.*?)..$") return ('\n'.join(reason_rules.findall(data))).s...
fc20f07b80477ca3252adaee2f5e8269ffda74ca
677,157
import binascii import logging def checkHeader(filename, headers, size): """ The checkHeader function reads a supplied size of the file and checks against known signatures to determine the file type. :param filename: The name of the file. :param headers: A list of known file signatures for the fil...
052b5d037dbda64a4556e19e007033e9fedaeeaa
677,158
def replace_tup(tupl, old, new, count=-1): """ Creates a copy of ``tupl`` with all occurrences of value ``old`` replaced by ``new``. Objects are replaced by value equality, not id equality (i.e. ``==`` not ``is``). If the optional argument ``count`` is given, only the first count occurrences are ...
ab6ab25b3620b9d0c8729b77658bb33d5702c47c
677,159
def identifier_to_flag(identifier): """ Turn an identifier back into its flag format (e.g., "Flag" -> --flag). """ if identifier.startswith('-'): raise ValueError('expected identifier, not flag name: %r' % identifier) ret = identifier.lower().replace('_', '-') return '--' + ret
e5af739656ef7c18a17d7a2427202c2366cf47ae
677,162
import csv def write_csv(csv_list, filename): """ writes a single csv file to the current directory :param csv_list: 2d list containing the csv contents :param filename: name of the newly created csv file :return: True if write successful, False if not """ try: with open(filename,...
281adbad93d791538d276b1a4edd884592e5c108
677,165
def ptsort(tu): """Return first element of input.""" return tu[0]
b5ec4c5111850b4730600c2c2844a120b62b97ad
677,170
def probe(value): """ Factorization of n by probing. :param n: value to factorize. :returns: all proper divisors of n. >>> probe(10) [1, 2, 5, 10] >>> probe(12) [1, 2, 3, 4, 6, 12] """ value = abs(value) limit = value // 2 divisors = [1] divisor = 2 while divis...
c4bcc3c0d6fb859258710ddea833fe497a731b38
677,171
def find_ancilla_values(counts, ancilla_qubits, ancilla_location = 0): """Returns a dictionary with a count of each possible ancilla bit string. Parameters ---------- counts : dictionary counts for each possible output bit string ancilla_qubits : int number of ancilla qubits anc...
5af09ee5e7cb6565aa7db8c7485ca59d04fc3e4f
677,173
def destroy_lvol_store(client, uuid=None, lvs_name=None): """Destroy a logical volume store. Args: uuid: UUID of logical volume store to destroy (optional) lvs_name: name of logical volume store to destroy (optional) Either uuid or lvs_name must be specified, but not both. """ if (...
221fd9f589c7ad56955c609db91ab4ef9ab3c6fc
677,174
def url_normalize(url: str): """ Convert a URL into the standard format """ if url.startswith('//'): return 'http:' + url if url.startswith('www'): return 'http://' + url if not url.startswith('http'): return 'http://' + url return url
bfdcbd8006176a65b102fee96f4f80a3fde13f55
677,175
def gaze_duration(interest_area, fixation_sequence): """ Given an interest area and fixation sequence, return the gaze duration on that interest area. Gaze duration is the sum duration of all fixations inside an interest area until the area is exited for the first time. """ duration = 0 fo...
9df438a342d61114ed6d2fc61ca5c47397e64791
677,177
def decrypt(ciphertext, cipher, shift): """ Caesar decryption of a ciphertext using a shifted cipher. :param ciphertext: the encrypted plaintext to decrypt. :param cipher: set of characters, shifted in a directed to used for character substitution. :param shift: offset to rotate cipher. :return...
af487c893837356ee8ba1eed22818561d984f519
677,179
import glob def make_fileslist(path_list): """Get lists of files from paths which may contains wildcards and symbols.""" ret = [] for p in path_list: ret += glob.glob(p) return ret
30a4c2eedd9c953601448281ec19221b97156732
677,181
def T1_sequence(length, target): """ Generate a gate sequence to measure relaxation time in a two-qubit chip. Parameters ---------- length : int Number of Identity gates. target : int Which qubit is measured. Returns ------- list Relaxation sequence. ""...
110a06a96423f0a4d87018c9dfba6a5505bcad32
677,184
def create_element(doc, parent, tag, value=None, attributes=None): """ Creates an XML element """ ele = doc.createElement(tag) parent.appendChild(ele) if value: text = doc.createTextNode(u"%s" % value) ele.appendChild(text) if attributes: [ele.setAttribute(k, str(v)) ...
e324e8f5d8395de1d35975457fd3a1692c0e9a35
677,186
def get_min_max_values(data, col1, col2): """ extracts min and max value of two columns :param data: ptcf data frame :param col1: column 1 :param col1: column 2 :return: dict of min and max values of two columns """ return { 'ds1_min' : data[col1].min(), 'ds1_max' : data[col1].max(), 'ds2_...
e28e31d29bcb530404e2e51358cff98e47159f41
677,187
def create_dict_node_enode(set_proj_nodes, neighbors_dict, H, node, dict_node_enode, dict_enode_node): """ A function to create useful dictionaries to represent connections between nodes that are in the embedding and nodes that are not in the embedding. :param set_proj_nodes: Set of the nodes that are i...
da2b05648dd200f98e03d3483fd3e80b225a1ee9
677,191
def upper(value): """Uppercase the string passed as argument""" return value.upper() if value else value
a5e109e0174040e06d2784c391d414c753154d5b
677,192
def pwr2modp(k, p): """Return 2**k mod p for any integer k""" if k < 0: assert p & 1 return pow((p + 1) >> 1, -k, p) return pow(2, k, p)
deeda4c153ae9d6b2409cd8047a98289f7bcd47e
677,193
def QuadraticLimbDarkening(Impact, limb1, limb2): """Quadratic limb darkening. Kopal 1950, Harvard Col. Obs. Circ., 454, 1""" return 1 - limb1 * (1 - Impact) - limb2 * (1 - Impact) ** 2
1b271c7afec301331b978e015c085ffaaa335240
677,194
import re def parse_bucket_url(url): """ Parse s3 url to get bucket name and object name. input: s3://test/templates/3.0/post_install.sh output: {"bucket_name": "test", "object_key": "templates/3.0/post_install.sh", "object_name": "post_install.sh"} """ match = re.match(r"s3://(.*?)/(.*)", ur...
eedf1ced909053c4533982e1a37f0f6decc90acb
677,195
def scan_reverse(f, arr): """Scan over a list in reverse, using a function""" r=list(arr) for i in reversed(range(len(r))[1:]): r[i-1] = f(r[i-1],r[i]) return r
db5d8461ec0c3eb9930d77104d7f055fc74b8f44
677,196
import itertools def juxtapose_text(text_a, text_b, buffer_len=15): """Places text_a to the left of text_b with a buffer of spaces in between""" lines_a = text_a.splitlines() lines_b = text_b.splitlines() longest_line_length_a = max(map(len, lines_a)) paired_lines = itertools.zip_longest(lines_a, ...
20cfb54c0e9d5978ecc00312c7a0465294684921
677,197
def color2gray(x): """Convert an RGB or RGBA (Red Green Blue Alpha) color tuple to a grayscale value.""" if len(x) == 3: r, g, b = x a = 1 elif len(x) == 4: r, g, b, a = x else: raise ValueError("Incorrect tuple length") return (r * 0.299 + 0.587*g + 0.114*b) *...
d598a2fa415170ab9242a2d52f2a3b0e0942b600
677,204
from csv import reader def parse_csv(filep): """Parse csv file and return dict containing site code to bandwidth mappings Keyword Arguments: filep -- file path to csv file """ bw_map = dict() with open(filep, 'r') as csvfile: bw_reader = reader(csvfile, delimiter=',', dialect='ex...
cc3ca8a74d08f5aff2dd1fe89a8dc013fbad55dd
677,207
def pax_to_human_time(num): """Converts a pax time to a human-readable representation""" for x in ['ns', 'us', 'ms', 's', 'ks', 'Ms', 'G', 'T']: if num < 1000.0: return "%3.3f %s" % (num, x) num /= 1000.0 return "%3.1f %s" % (num, 's')
c0cf037a6a170e9fda15cc68361c38b8e1e7761c
677,209
def check_answer(guess, a_followers, b_followers): """Take the user guess and follower counts and returns if they got it right.""" if a_followers > b_followers: return guess == "a" else: return guess == "b"
16ec16e7c045f5837a31e062c2d100f300cfad32
677,210
def to_yellow(string): """ Converts a string to yellow color (8bit) Returns: str: the string in yellow color """ return f"\u001b[33m{string}\u001b[0m"
6ae585485464f3ac6ab1c6862cc9063bb8e672a5
677,212
def parse_json(request): """ Default content parser for JSON """ return request.json
cc45af02c1ac9b3838fbf8434661321af6337f27
677,218
def getUrl(sIpAddress): """Returns the full cgi URL of the target""" return 'http://' + sIpAddress + '/cgi-bin/xml-cgi'
d51499ef9828ead13f7a17a6a7ba0484cc3d3b91
677,220
def _initial_gaussian_params(xm, ym, z, width=5): """ Guesses the initial 2D Gaussian parameters given a spatial filter. Parameters ---------- xm : array_like The x-points for the filter. ym : array_like The y-points for the filter. z : array_like The actual data t...
d36522c30d937672c4bfddcb698b0029ddd6bb18
677,221
import re def requires(prefix=''): """Retrieve requirements from requirements.txt """ try: reqs = map(str.strip, open(prefix + 'requirements.txt').readlines()) return [req for req in reqs if not re.match(r'\W', req)] except Exception: pass return []
85c53c21bd8aaccd58ee8e37f7f83cf1b0d5abe3
677,223
def get_ray_num(file_path): """ extract the ray's number from it's file name Parameters: file_path : string: full path to ray file Returns: num :string : the number corresponding to the ray """ filename = file_path.split('/')[-1] num = filename[3:-3] return num
3e7367097ea6f57aae083dc1e1463bcdff9fe32d
677,226
def stats_file_keys(gene_number): """Return fiels in stats file, ordered, as a list of string""" return [ 'popsize', 'genenumber', 'generationnumber', 'diversity', ] + ['viabilityratio' + str(i) for i in range(gene_number) ] + ['viabilityratioDB'...
05a8b6837cc3b68d3e0f8c0ec4ca5e27cfe4e533
677,228
def knight_amount(board_state, player): """ Returns amount of knights the player has """ board = board_state knight_amt = 0 for row in board: for column in row: if player == 1 and column == "k": knight_amt += 1 elif player == 0 and column == "K": ...
4a2cad597ec0751fb6d4d751a177509576cba87d
677,229
def enum(**named_values): """Creates an enum type.""" return type('Enum', (), named_values)
fa8390972f4ef343b3cbcc05bca064fe853aa876
677,231
def assign_pre_id_to_inner_nodes(phylo_tree): """ Replace the name of the inner nodes of a given phylogenetic tree with its preorder number in the tree. """ idx = 0 for node in phylo_tree.find_clades(terminal=False, order='preorder'): node.name = '%d' % (idx) idx += 1 ...
d114fe5c19b749c499cd8a1167ba6bf957c71c35
677,232
def get_column_names(path_to_test, key_to_infer): """ Get a list containing the names of the columns in your table minus the column that you want to infer. =Parameters= path_to_test: Path where your test.csv is saved. key_to_infer: The name of the column that you want to infer. """ with ...
f16a7269c2f9c913ec3c8dd86ed7137bb3ec900b
677,234
def list_of_lists_to_md_table(rows): """Convert a list (rows) of lists (columns) to a Markdown table. The last (right-most) column will not have any trailing whitespace so that it wraps as cleanly as possible. Based on solution provided by antak in http://stackoverflow.com/a/12065663 CC-BY-SA 4.0 ...
12cb19028a05c921c9c57c7af93827a4bdcb53fc
677,237
def read_lines(file_path): """ Read lines from the file and return then as a list. """ lines = [] with open(file_path, 'r', encoding='utf8') as asm_file: lines = asm_file.readlines() return lines
a6f97f60edefac2207369624c4421829b8637fbe
677,239
import random def between(min_wait, max_wait): """ Returns a function that will return a random number between min_wait and max_wait. Example:: class MyUser(User): # wait between 3.0 and 10.5 seconds after each task wait_time = between(3.0, 10.5) """ return lambda...
54ca9ec56c8848c6672817d8bbd48357faedda6c
677,240
def _recolumn(tmy3_dataframe): """ Rename the columns of the TMY3 DataFrame. Parameters ---------- tmy3_dataframe : DataFrame inplace : bool passed to DataFrame.rename() Returns ------- Recolumned DataFrame. """ # paste in the header as one long line raw_columns...
facc1a29ff277546d5458d179b51003f0d0674db
677,242
def get_insertion_excess(cigar): """Return excess insertions over deletions. Using pysam cigartuples sum all insertions and softclips (operation 1 and 4) minus sum of all deletions (operation 2) """ return sum([l for o, l in cigar if o in [1, 4]]) - sum([l for o, l in cigar if o == 2])
2ed458cfd4a46c163a7e19a18da14941e1ad5a28
677,249
def merge_pred_gt_boxes(pred_dict, gt_dict=None): """ Merge data from precomputed and ground-truth boxes dictionaries. Args: pred_dict (dict): a dict which maps from `frame_idx` to a list of `boxes` and `labels`. Each `box` is a list of 4 box coordinates. `labels[i]` is a lis...
03b2c9800850a7f6ebe34e3d18c4353b32113930
677,252
def _bop_and(obj1, obj2): """Boolean and.""" return bool(obj1) and bool(obj2)
96b285545f4d8d3b04ff68630c38592b192a815d
677,253
import re def find_match(regex, text, stripchars='^$'): """ Finds a match from given text and return match else None. :param regex: Regular expression :param text: Target text :param stripchars: Characters to be removed from left and right :returns: boolean match object if match found else Fa...
38439c5dab26d5b6f4a04315a21f013d770fe715
677,256
def b2h(num, suffix='B'): """Format file sizes as human readable. https://stackoverflow.com/a/1094933 Parameters ---------- num : int The number of bytes. suffix : str, optional (default: 'B') Returns ------- str The human readable file size string. Ex...
6394c4ecc2bdf06f5f7b8f429e6b308030163c57
677,257
def indent(string_in: str, tabs: int = 0): """Returns the str intended using spaces""" return str(" " * tabs) + string_in
5311de4ab33e0020f95bc126c4db06fdf452212f
677,260
def no_error_check(func_name, result, func, args): """Nothing special""" return args
d2e6bf201d648812a0a2b7e1bf316aa851508374
677,262
import re def br_with_n(text): """ Replace br with \n """ return re.sub(r'<br.*?>','\n', text, flags=re.IGNORECASE)
105fdc3b83e40b7d0e6e35e4785e11da59772576
677,265
def S_M_to_mS_cm(CTM_S_M): """ Seabird eq: ctm [mS/cm] = ctm [S/m] * 10.0 """ ctm_mS_cm = CTM_S_M * 10.0 return ctm_mS_cm
38a679d5c39627aaa3e919f199aac826298f03f9
677,271
import _ast def Dict(keys=(), values=()): """Creates an _ast.Dict node. This represents a dict literal. Args: keys: A list of keys as nodes. Must be the same length as values. values: A list of values as nodes. Must be the same length as values. Raises: ValueError: If len(keys) != len(values). ...
60cd4508f47a0160c97d9030ef2560023a08a20c
677,272
from datetime import datetime def format_iso_date(d): """ If the parameter is datetime format as iso, otherwise returns the same value """ if type(d) is datetime: return d.isoformat() return d
19fceb51f32f92c8ed078da5498c1e46317c8cad
677,277
def local_scheme(version: str) -> str: # pylint: disable=unused-argument """Skip the local version (eg. +xyz) to upload to Test PyPI""" return ""
50448c7ecc8457229ca5a752b2157987b80d104e
677,278
def cmp_dicts(dict1, dict2): """ Returns True if dict2 has all the keys and matching values as dict1. List values are converted to tuples before comparing. """ result = True for key, v1 in dict1.items(): result, v2 = key in dict2, dict2.get(key) if result: v1, v2 = (t...
8a0bba46b8257d3d82ee21a99d3472e2ebb09c41
677,280
def breaklines(s, maxcol=80, after='', before='', strip=True): """ Break lines in a string. Parameters ---------- s : str The string. maxcol : int The maximum number of columns per line. It is not enforced when it is not possible to break the line. Default 80. af...
4d35d8da06de1d96b3af3c9de997dc58bf85cbba
677,282
def sum_digits(n): """Recursively calculate the sum of the digits of 'n' >>> sum_digits(7) 7 >>> sum_digits(30) 3 >>> sum_digits(228) 12 """ """BEGIN PROBLEM 2.4""" return n % 10 + (0 if n < 10 else sum_digits(n // 10)) """END PROBLEM 2.4"""
18aaf2714970dadf5c6c7a5d009b2e2c9d210502
677,284
import re def escape(pathname: str) -> str: """Escape all special characters.""" return re.sub(r"([*?[\\])", r"[\1]", pathname)
33a357c49acfe44dd25fa897b629b812e07cfdd0
677,285
import requests from bs4 import BeautifulSoup import re def get_apps_ids(play_store_url): """Scrape play store to gather App IDs. Returns a list of App IDs Keyword arguments: play_store_url -- URL from a Play Store Search :rtype: list """ page = requests.get(play_store_url) soup = Bea...
18f8304827bf8f269d63ff1a0b342ac5cee9eb8a
677,291
import yaml def read_config(path): """ Load the yaml file into a dictionary. """ with open(path) as f: return yaml.load(f, Loader=yaml.FullLoader)
24e9ef759141ce11f7e090c76768e77d29018181
677,295
import re def normalizeName(name): """Transforms a name to deal with common misspellings.""" # Only use the first of several names. oneName = name.split(' ', 1)[0].lower() REPLACEMENTS = [ ['y$', 'a'], # Szczęsny = Szczęsna ['i$', 'a'], # Nowicki = Nowicka ['ę', 'e'], ['ą', 'a'], ['ó', '...
cc97be3255ea902f34d63ca459dc3b968c73bf0e
677,309
def join_query_keys(keys): """Helper to join keys to query.""" return ",".join(["\"{}\"".format(key) for key in keys])
aae572da696641c548a26acde8e2d94237ca3c19
677,310
def defaultparse(wordstags, rightbranching=False): """A default parse to generate when parsing fails. :param rightbranching: when True, return a right branching tree with NPs, otherwise return all words under a single constituent 'NOPARSE'. >>> print(defaultparse([('like','X'), ('this','X'), ('example', 'NN'),...
4770088bdabc2b2036a60402be243a7e072f23de
677,312
def string_to_int(string): """ Problem 7.1 convert a string to an integer, without using `int` """ negative = string[0] == '-' if negative: string = string[1:] idx = 0 output = 0 while idx < len(string): low = ord(string[idx]) - ord('0') output = (output * 1...
583a87eb8aea4347f9d04378308ef6a901ffa6a0
677,316
def apply_LLD(spectrum, LLD=10): """ Applies a low level discriminator (LLD) to a channel. Parameters: ----------- spectrum : vector The spectrum LLD : int The channel where the low level discriminator is applied Returns: -------- spectrum : vecto...
c3dfe53fdbc22aa6c2b3ac1dc054f2a1a0fc40dd
677,320
def wants_json_resp(request): """ Decide whether the response should be in json format based on the request's accept header. Code taken from: http://flask.pocoo.org/snippets/45/ """ best = request.accept_mimetypes.best_match(['application/json', '...
591b66c1a37012e344642d2130cc8e5b06f69f31
677,321
def route_business_logic(logicFn): """ Decorates a function to indicate the business logic that should be executed after security checks pass. :param logicFn: The business logic function to assign. :return: The decorated function. """ def decorator(fn): fn.route_business_logic = logicFn...
b1c50db9ae54ca86755a43ae4cecef6887061b5b
677,323
def _schema_sql_to_bq_compatibility( schema_dict: dict ) -> dict: """ Convert sql schema to be compatible with the bq ui. Args: schema_dict: column name-sql column type as key-value pairs e.g. {'uid': 'STRING', 'clicks': 'INTEGER'} Returns: schema_dict: column name-sql ...
bf07abe26aad00f9d052fffced0563f4efae5551
677,324
def nodes_within_bounds(indices, bounds): """ nodes_within_bounds filters a set of indices to those that are within the bounding box :param indices: a set of indices :param bounds: upper bounds for each axis, implicit minimum at 0 :return: filtered indices within bounds """ filtered = set() ...
18000d24efaade8200ca67010d1b6d52e7276f61
677,327
def _GetRegionalGetRequest(client, health_check_ref): """Returns a request for fetching the existing health check.""" return (client.apitools_client.regionHealthChecks, 'Get', client.messages.ComputeRegionHealthChecksGetRequest( healthCheck=health_check_ref.Name(), project=heal...
8abc4d639f81739fcd943658c7a6707775d5cf87
677,335
import logging def get_logger(name=None): """Return a logger to use""" return logging.getLogger("dandi" + (".%s" % name if name else ""))
ca9cf40d4edd9e5368241ff6d53e991d360601d7
677,336
def _divide_if_possible(x, y): """ EXAMPLES:: sage: from sage.combinat.free_module import _divide_if_possible sage: _divide_if_possible(4, 2) 2 sage: _.parent() Integer Ring :: sage: _divide_if_possible(4, 3) Traceback (most recent call last): ...
73f88957e16c4562071152662249b1f83f1103b4
677,340
def make_progress_bar_text(percentage: float, bar_length: int = 2) -> str: """ Get the progress bar used by seasonal challenges and catalysts and more Translations: "A" -> Empty Emoji "B" -> Empty Emoji with edge "C" -> 1 Quarter Full Emoji "D" -> 2 Quarter Full Emoji ...
6422dfbb7f4bb9b875491398fab57e9f8af5a380
677,345
import copy def offset_bonds(bonds, offset): """ Offset all of the numbers in the bonds array by value offset; useful for adding molecules to a system that's already established because the bond arrays start at 0. For a system with N atoms, all indices in the new molecule to be added's bonds ...
601493fb728a80a5c5ed1226fb22e41005cd9576
677,346
def get_primitive_matrix_by_centring(centring): """Return primitive matrix corresponding to centring.""" if centring == "P": return [[1, 0, 0], [0, 1, 0], [0, 0, 1]] elif centring == "F": return [[0, 1.0 / 2, 1.0 / 2], [1.0 / 2, 0, 1.0 / 2], [1.0 / 2, 1.0 / 2, 0]] elif centring == "I": ...
e24a670cf426ce8942f49631eb41c31c3b6fa468
677,347
def _get_children(heap, idx): """Get the children index-value of the input index.""" length = len(heap) idx_left = 2 * idx + 1 val_left = heap._idx2val(idx_left) if idx_left < length else None idx_right = idx_left + 1 val_right = heap._idx2val(idx_right) if idx_right < length else None retur...
2d073915ca595a9235caf9dab195199aba4280b5
677,349