content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _clean_roles(roles): """ Clean roles. Strips whitespace from roles, and removes empty items. Args: roles (str[]): List of role names. Returns: str[] """ roles = [role.strip() for role in roles] roles = [role for role in roles if role] return roles
d52b568f8a2d756f53f0b51307578f4d4afdcd08
667,334
from datetime import datetime def datetime_str_to_obj(datetime_str): """ :param datetime_str: a string representation of a datetime as formatted in DICOM (YYYYMMDDHHMMSS) :return: a datetime object :rtype: datetime """ year = int(datetime_str[0:4]) month = int(datetime_str[4:6]) day =...
bd1596dedfa692468b65a7ea327255936c14cef0
667,335
def lifecycle_hooks(request, testconfig): """List of objects with hooks into app/svc creation and deletion Hooks should implement methods defined and documented in testsuite.lifecycle_hook.LifecycleHook or should inherit from that class""" defaults = testconfig.get("fixtures", {}).get("lifecycle_hooks...
ab8da9a59b609f7c85df4561c1edd489611a1afd
667,336
def _int_to_indices(value, length, bits): """Converts an integer value to indices in big endian order.""" mask = (1 << bits) - 1 return ((value >> (i * bits)) & mask for i in reversed(range(length)))
b5f6f50d241744f00b9b385aef5eeef148e7f6e7
667,337
def formatdt(date, include_time=True): """Formats a date to ISO-8601 basic format, to minute accuracy with no timezone (or, if include_time is False, omit the time).""" if include_time: return date.strftime("%Y-%m-%dT%H:%M") else: return date.strftime("%Y-%m-%d")
91cb0acaf6a20a68c00557bacbd9327db624b927
667,338
import torch def calculate_wh_iou(box1, box2) -> float: """ calculate_wh_iou - Gets the Intersection over Union of the w,h values of the bboxes :param box1: :param box2: :return: IOU """ # RETURNS THE IOU OF WH1 TO WH2. WH1 IS 2, WH2 IS NX2 box2 = box2.t() # W, H = BOX...
0af45853c1e50157f587f9decea3834df862a314
667,339
import importlib def import_class(value): """Import the given class based on string. :param value: [path of the class] :type value: [str] :returns: [class object] :rtype: {[Object]} """ value, class_name = value.rsplit(".", 1) module = importlib.import_module(value) return getattr...
1da54577f5a772e3b8a230a2328c487b9ce504ed
667,340
def hardness(s: str) -> float: """Get the element hardness.""" d = { 'h': 6.4299, 'he': 12.5449, 'li': 2.3746, 'be': 3.4968, 'b': 4.619, 'c': 5.7410, 'n': 6.8624, 'o': 7.9854, 'f': 9.1065, 'ne': 10.2303, 'na': 2.4441, 'mg': 3.0146, 'al': 3.5849, 'si': 4.1551, 'p': 4.7258, 's': 5.2960, 'c...
232e341ecb341071fbdebe3059001a7cd72f0738
667,341
def remover_sp_add_sub(list_parameters): """ Remove "sp" of the elements of the list """ return [list_parameters[1]]
148f3c5d4c605213239b64649de9725aa237068c
667,342
import argparse def parse_args(): """Parse commandline arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--uses-library', dest='uses_libraries', action='append', help='specify uses-library entries known to the build system') parser.add_argument(...
64c9d1ddcb2260727e942e4659d8447eebe0b8b8
667,343
def database_connection_type(hostname, default_type): """ returns known DB types based on the hostname :param hostname: hostname from the URL :return: string type, or default type """ if 'rds.amazonaws' in hostname: return 'rds' if 'redshift.amazonaws' in hostname: return 're...
49b925811738bd838f754cf4e973b7d7440ac4e0
667,344
def from_positive_part(may_negative): """ >>> from_positive_part(numpy.array([1, -2, 3])) array([ 1., 0., 3.]) """ return (may_negative + abs(may_negative))/2.0
11b92ea4eef7ba4386cc93096b261f6cc0636ccc
667,345
import json def update_workspace(cursor, specification, workspace_id, update_at): """workspace情報更新 Args: cursor (mysql.connector.cursor): カーソル specification (Dict)): ワークスペース情報のJson形式 Returns: int: アップデート件数 """ sql = "UPDATE workspace" \ " SET specifi...
a93224dd0e69a3567b797359a4ef252124df9e70
667,346
def two_fer(name=None): """Return a string with a message when given a name.""" if name==None: return "One for you, one for me." else: return f"One for {name.title()}, one for me."
c07a91a48e02aa46430f4543a64a5433d763a1df
667,347
def hyphenate(path): """Replaces underscores with hyphens""" return path.replace('_', '-')
35f0b7baee9fada7385a9ffac66a45b32270f41a
667,348
def boolean(input): """Converter that takes a string and tries to divine if it means true or false""" if input.lower() in ("true", "on"): return True elif input.lower() in ("false", "off"): return False else: raise ValueError('"%s" not boolean' % input)
e544d0d5fe2d7658aa8f96fe0434370a54bdade5
667,349
import requests def post(url, headers, data): """ Post a request to a given url :param url: :param headers: :param data: :return: """ request = requests.post(url=url, headers=headers, json=data) return request
3b2cf139e8ceb11f2059d76b6238d4f1764d7919
667,350
def compute_score(parsed): """ If a node has no child node (len == 1), the score is the sum of the metadata, else the metadata are indexes of scores of child nodes. If an index does not exists, it is 0. """ score = 0 if len(parsed) == 1: # Only metadata score += sum(parsed['m...
dc1636fccce2406ea24e0313f9dff8124ec0e491
667,351
def _read_from(file): """Read all content of the file, and return it as a string.""" with open(file, 'r') as file_h: return file_h.read()
280860a0075a9b9e8b3f9c014d031147c1bb79ed
667,352
def askyesno(question, default=True): """Ask a yes/no question and return True or False. The default answer is yes if default is True and no if default is False. """ if default: # yes by default question += ' [Y/n] ' else: # no by default question += ' [y/N] ' ...
10635ea8eb9ff735921b0aeb98a3b0083703cf07
667,353
def genomic_dup2_rel_38(genomic_dup2_seq_loc): """Create test fixture relative copy number variation""" return { "type": "RelativeCopyNumber", "_id": "ga4gh:VRC.WLuxOcKidzwkLQ4Z5AyH7bfZiSg-srFw", "subject": genomic_dup2_seq_loc, "relative_copy_class": "partial loss" }
7b4076c58900fbacee758d23798c1c0cd800c69b
667,354
import torch def compute_iou(box1, box2): """Compute the intersection over union of two set of boxes, each box is [x1,y1,x2,y2]. Args: box1: (tensor) bounding boxes, sized [N,4]. box2: (tensor) bounding boxes, sized [M,4]. Return: (tensor) iou, sized [N,M]. """ lt = torch.max( ...
57c8770d828c793c5d34e3677a2ced8f5b755a9f
667,355
from pathlib import Path def path_to_example(dataset): """ Construct a file path to an example dataset, assuming the dataset is contained in the 'example-data' directory of the abc-classroom package. Adapted from the PySAL package. Parameters ---------- dataset: string Name of a d...
879e47e6108601fb5a79128172322f3505b65806
667,357
from typing import Iterable from typing import Any from functools import reduce def product(it: Iterable[Any]) -> Any: """ Convolution product of iterable object Args: it: Iterable object Examples: >>> fpsm.product(range(6)) 120 """ return reduce(lambda x, y: x * y, i...
e4ab027e9e672ac2ef8af17b3c9fa4ea6e61b216
667,358
def parse_range(arg,dtype=int): """Parse argument of type (0,10), [0,10]""" try: # Remove brackets and recombine x = ''.join(arg[1:-1]) # Get rid of the comma x = x.split(',') # Convert to given data type return dtype(x[0]), dtype(x[-1]) except ValueError: ...
b5138012ff6946eb39ba2ec437e46bb54de46064
667,360
def crnum2mjd(crnum): """ Converts a Carrington Rotation number to MJD Mathew Owens, 16/10/20 """ return (crnum - 1750)*27.2753 + 45871.41
53e9170e7f4226fda0996cde5fbc34992ba45f44
667,361
from typing import List def create_copy_sql(table_name: str, stage_name: str, upload_key: str, file_format_name: str, columns: List): """Generate a CSV compatible snowflake COPY INTO command""" p_columns = ', '.join([c['name'] for...
71a126c6e7274c7c3e6508ffec5502944b8f07c7
667,362
import json def QueryRowToJSON_JSON(var): """ Take the results of an SQL fetchone and returns a dictionary version of the string """ try: return json.loads(var[0]) except: return {}
dd037aeec40e7b5ae43a290247b2e2f3a33ddba9
667,367
import json def jsondump(data): """Return prettified JSON dump""" return json.dumps(data, sort_keys=True, indent=4)
3d4d76bc0c2f5c7e81c9a49d9f148a63b47127ec
667,368
def get_or_else(hashmap, key, default_value=None): """ Get value or default value Args: hashmap (dict): target key (Any): key default_value (Any): default value Returns: value of key or default_value """ value = hashmap.get(key) if value is None: return de...
6713541f8075636e92c2d2c2a2c444a9cf822375
667,369
import json def equal_list_of_dicts(obj1, obj2, exclude=[]): """Check whether two lists of dictionaries are equal, independent of the order within the list. Parameters ---------- obj1 : list of dict First object to compare obj2 : list of dict Second object to compare exclu...
dad55ea63e9da0f86c613acc39243c5ff8bbca58
667,370
from typing import List import random def generate_random_fill_holes(size: int) -> List[bool]: """ Generate a list of random bools of length size. :param size: length of list of random booleans to generate. """ return [bool(random.getrandbits(1)) for i in range(size)]
24880cbfe48f3230a198698c7ec3a90bb30f8995
667,371
def KtoM(k): """ (number) -> number Returns miles from kilometers. >>> KtoM(5) 3.106855 >>> KtoM(9) 5.592339 """ return k * 0.621371
ff684d5749aed8289828b80b44103e52702a26e4
667,372
def B2s(bs): """ Switch bytes and string. """ if type(bs) == type(b''): return "".join(map(chr, bs)) else : return bytes([ord(c) for c in bs])
435f42c3d167b4c141cc021216a997bf02a6a834
667,373
def get_store_dicts(): """ To store stats and metrics during training """ results_init = {"loss": {"dec": [], "rnk": [], "cls": []}, "ranking": {"trg": [], "prob": []}, "classification": {"trg": [], "prob": []}, "style": [], "lambdas": {"passage": [], "question": [], "vocabulary": []}} performance...
c5322e44f1927dea9c3bdb2d9fc9b816679792cf
667,374
def get_flights_sorted_price(flights, reverse=False): """Return a list of flights sorted by price. Args: flights (list): list of flights, each flight is represented by a dictionary. reverse (bool, optional): defines the sorting order, by default to False - ascending, if ...
2d21ff6ccee3e07b5ce4aaf7627c94be2570aeb7
667,375
def camera2world(R, t, p): """ R: 3x3 t: 3, p: 3, """ # matlab 先转置 R = R.T # R = np.linalg.inv(R) return (p - t).dot(R)
4ef10040a0490536142f361322ded558e887acde
667,376
from typing import List from typing import Dict def add_org_counts(label: str, sparql_results: List, org_counts: Dict) -> Dict: """Add counts for organization by entity type.""" for count in sparql_results: if org_counts.get(count["org"]): org_counts[count["org"]][label] = count["count"] ...
9c32ffa5dc767d0c0f114ef7380a3adc3a903720
667,377
import gzip import json def load_metadata_as_text(filepath): """ :param filepath: file to amazon item metadata file :return: dict of iid: metadata as one string """ metadata = {} with gzip.open(filepath, 'r') as f: for line in map(json.loads, f): iid = line["asin"] ...
a29df3ef99d674d91941129180cf782b0984a514
667,378
def isMemoryAccessValid(maccess): """ Verify if a memory access is valid. Args: maccess: memory access block. Returns: data: involved parts (registers or constants) in memory access. Raises: None """ data = [] maccess = maccess.replace(' ', '') if maccess....
052072cc2a61fdd3c003cc48580aa4c6358bf8a8
667,379
from pathlib import Path def create_profile_path(input_profile_path: Path, profile_name: str, output_dir: Path) -> Path: """Create the name of the output profile by grabbing the ID of the input profile.""" profile_name = profile_name + input_profile_path.stem[len("Color LCD"):] + ".icc" return output_dir ...
22c64f238f9122c3c0d2dccc04b9422d8ebf09db
667,380
def upnext_info(videoid, infos, art): """Create a data dict for upnext signal""" # Double check to 'rating' key, sometime can be an empty string, not accepted by UpNext Addon rating = infos.get('rating', None) return { 'episodeid': videoid.episodeid, 'tvshowid': videoid.tvshowid, ...
3e8667b166d1b200951781b669cbb0be9a0db51f
667,381
def filterit(s): """ A functoin to filter out unnecessary characters from a sentece, helper for nBOW Args: s = Sentence returns: filtered Sentence """ s=s.lower() S='' for c in s: if c in ' abcdefghijklmnopqrstuvwxyz0123456789': if c.isdigit(): ...
873e955a964470c8a795f3ca097cac2290dd5c67
667,382
def MaxPairwiseProduct_Better(array:list): """ Using 2 variables to store Top 2 Max Values in `array`. Single Pass O(n) """ if len(array) < 2: return 0 max1, max2 = array[0],array[1] for i in array[2:]: if i > max2: if i > max1: max1, max2 = i, max...
8c120f4b801a2855840f648fa61a534683b13c6c
667,383
import re def get_salary_section(string): """ e.g: 15k-25k -> (15, 25) 15k以上 -> (15, 20) 15k以下 -> (10, 15) :param string: 15k-25k :return: 15,25 """ pattern = r'K|k|以上|以下' replace_char = '' if string.find('-') != -1: string = re.sub(pattern=pattern, repl=repl...
d5df1a6755f5ed04e16b972bf55cd52c08bef081
667,384
def slash_sort(fn): """Used to sort dir names by the number of slashes in them""" return fn.count("/")
5850d4975c2107adaf356a18e5deae85fddbe9ae
667,385
import json def decode_workload_key(workload_key): """Decode the workload key from a string to the name and arguments. The wokrload key is expected to be a list of "[func_name/hash, args ...]" in a JSON string. If not, then simply return the workload key as the name without arguments. Parameters ...
4ee9e6a12673402149deda5b531d5fbeb57cd48f
667,386
def return_all_parameters_from_parameter_group(rds_client_obj, param_group): """ Returns all the parameters for a parameter group. """ parameters_to_return = [] pagination_token = None # Iterate through all parameters in parameter group and break out when appropriate. while(True): ...
7a16ac4c7aedddcb5d77a5813d2ec8a684bdfbbb
667,387
from typing import Optional from typing import Tuple def get_results(conn, query: str, values: Optional[Tuple] = None): """Returns the results from a provided query at a given connection""" cursor = conn.cursor() cursor.execute(query, values) results = list(cursor) return results
6673b5d64d82902877d0151e5e35eba5c210fb1a
667,388
def get_duplicates_from_cols(df, cols_to_use, what_to_keep='first'): """ Check duplicated rows by using the combination of multiple columns This is a workaround in the case where one doesn't have unique identifiers for a dataset :param pd.DataFrame df: :param list cols_to_use: columns to use to cre...
772c50c606a6e013b322c08be33356fd6bb70c36
667,389
def write_target_table_vector(var_name, target_table_names_in_order): """ // Lookup table of routers, Y int target to Y classifier Class name target. // Usage pattern "vec_target_table_Y[Y_int]" std::vector<std::string> vec_target_table_Y { "router_name_0", "router_name_1", "router_name_3" }; """...
3ff1173cb65ff04c8b109309f55d2ba1c75167c6
667,390
def get_time_to_run_pipeline(True_steps_suffix_map): """ This function calculates the total running time by adding the individual time per step. Args: True_steps_suffix_map: string, full path of where the text file will be written into Returns: total_time: string, total calculate the to...
fa84486323aab94ac7bf5e05da5cd745ed26f205
667,391
def frepr(var, ffmt="%.16e"): """Similar to Python's repr(), but return floats formated with `ffmt` if `var` is a float. If `var` is a string, e.g. 'lala', it returns 'lala' not "'lala'" as Python's repr() does. Parameters ---------- var : almost anything (str, None, int, float) ffmt :...
c7f37e53cc2cdc2c184fe233b3a27e3a3fed2b1c
667,392
def HA(df, ohlc=None): """ Function to compute Heiken Ashi Candles (HA) Args : df : Pandas DataFrame which contains ['date', 'open', 'high', 'low', 'close', 'volume'] columns ohlc: List defining OHLC Column names (default ['Open', 'High', 'Low', 'Close']) Returns : df : Pandas ...
b97a6018ad2ae39351e974f240c5961129b9c437
667,393
from typing import Tuple def RationalScalarBernoulliExp(*, gamma: Tuple[int, int] = (0, 1), rng) -> int: """ Draw an exact Bernoulli(exp(-gamma)) scalar. Inputs: gamma: Fraction >= 0, used to define Pr[X = 1] = exp(-gamma) rng: pseudo-random number generator (see pr...
1c59fa762b54279e3279d3143179388ff7e25cdc
667,395
import functools import gc def disable_gc(f): """ Decorator to disable garbage collection during the execution of the decorated function. This can speed-up code that creates a lot of objects in a short amount of time. """ @functools.wraps(f) def wrapper(*args, **kwargs): gc.di...
c49f7cce62f21bb3c32110044423741200a8c7a5
667,396
import numpy def best_reply_incentive(fitness): """Compute best reply to fitness landscape at state.""" def g(state): f = fitness(state) try: dim = state.size except AttributeError: state = numpy.array(state) dim = state.size replies = [] ...
17614d62ddc84c55497d3eac0578e6fdcd2cba0a
667,397
def filter(list, attribute, value, return_attribute=None): """Take a list and returns match objects (or list of attributes from those objects) where list object.attribute == value""" if return_attribute == None: matches = [match for match in list if match[attribute] == value ]; else: matches...
7d024ba138cb2ebb1f1b795567d1ce1402ededd8
667,398
def branch_text(branch): """ Takes and lxml tree element 'branch' and returns its text, joined to its children's tails (i.e. the content that follows childrens of 'branch'). """ texts = list(filter(lambda s: s != None, [branch.text] + [child.tail for child in branch])) if len(texts) == 0: ...
4b351d292e7c612d08296d5a968b80c0ac26267f
667,399
def prepare_query_domains(domain): """ prepare a domain or a list of domains for google query (adding site:*.) """ domain = domain.replace(" " , "").replace("," , " OR site:*.") domain = "site:*." + domain domain = domain.replace(".." , ".") return domain
affa22c9896a846112846165ee5ad59f26c15dae
667,400
import argparse import json def parse_input(): """ read the files given as parameters and load the newline-delimited json stings :return: a tuple with [0] a list of dicts with predicted classes, [1] a list of dicts with the true classes. """ parser = argparse.Argument...
fa3a7add7b0d485ae59838c279e9d07e88d70b39
667,401
def splitCommas(s): """Split a string s containing items separated by commas into a list of strings. Spaces before or after each string are removed.""" items = s.split(",") return [ i.strip(" ") for i in items ]
72b3bc8fbb512e139a8b1d6daa14e882b2f5b986
667,402
def divide(a, b): """ Divides two numbers. Automatically raises ZeroDivisionError. >>> divide(3.0, 2.0) 1.5 >>> divide(1.0, 0) Traceback (most recent call last): ... ZeroDivisionError: float division by zero :param a: first number :param b: second number :return: qu...
f232480b2f9cb86cda9676587fc8fad3e7c9aace
667,403
def get_imperatives(tokens): """Identify, color and count imparative forms""" imperatives = [t for t in tokens if t.full_pos.endswith('IMP')] for t in imperatives: t.mode_color.append('Imperatives') return len(imperatives)
9fd50604b631626850d43e9bcc3350e7ee4dee74
667,404
import os def get_credentials(): """ Returns the values stored in the AWS credential environment variables. Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and the value stored in the AWS_SECRET_ACCESS_KEY environment variable. Returns ------- out : tuple [string] ...
0ca2d44978e31168fae6b368c62e731536255f28
667,405
def stdin(sys_stdin): """ Imports standard input. :type sys_stdin: list :rtype: list """ return [int(x) for x in sys_stdin]
35e196c7063b8038313a12f4baa7bdd8675801ef
667,406
def get_target_rows(df): """Restrict data frame to rows for which a prediction needs to be made.""" df_target = df[ (df.action_type == "clickout item") & (df["reference"].isna()) ] return df_target
203f4a4dc5103b8d251e8063f4e76848efdb98b8
667,407
def _gen_val_counts_(df_in, col): """ """ df = df_in.copy()[col].value_counts().to_frame().reset_index() df.columns = [col, "n_files"] return df
e7dc50701b01a28bdad62ae9edc0660ee59d25ae
667,408
import os def generate_editor_command(): """generate a command for EDITOR is env var is set""" if "EDITOR" in os.environ: command = "%s {filename}" % os.environ.get("EDITOR") else: command = "vi +{line_number} {filename}" return command
c2fd17b32e82d0aab3aaa3980ff1c2dc32395724
667,409
def row_to_dict(row, field_names): """Convert a row from bigquery into a dictionary, and convert NaN to None """ dict_row = {} for value, field_name in zip(row, field_names): if value and str(value).lower() == "nan": value = None dict_row[field_name] = value return d...
10c903dda90524e6aacfb54a17d4839c8498a769
667,410
def parse_string_list_from_string(a_string): """ This just parses a comma separated string and returns either a float or an int. Will return a float if there is a decimal in any of the data entries Args: a_string (str): The string to be parsed Returns: A list of integers Auth...
5cd7801966b8e564faa00bb475bce06711441cb0
667,411
def convertToStepUpCDF(x, y): """Convert to a "stepped" data format by duplicating all but the last elt. Step goes up, rather than to the right. """ newx = [] newy = [] for i, d in enumerate(x): newx.append(d) newy.append(y[i]) if i != len(x) - 1: newx.append...
1ef12332b6931292a93801cc25459c06b647df5d
667,412
import string import math def str_count(s): """ Count the number of Chinese characters, a single English character and a single number equal to half the length of Chinese characters. args: s(string): the input of string return(int): the number of Chinese characters """ ...
5843de706cf19bb2ba087278c967c91011e24c55
667,413
def spritecollide(sprite, group, dokill, collided = None): """find Sprites in a Group that intersect another Sprite pygame.sprite.spritecollide(sprite, group, dokill, collided = None): return Sprite_list Return a list containing all Sprites in a Group that intersect with another Sprite. Intersection is...
ceb9728c3cbc41ad69b3425ebf8eac42e83233a6
667,414
def parse_domains_and_ips(file_loc): """Reads the file and returns a dict with every domain we want to redirect and the respective address we want to redirect it to. Parameters: file_loc (str): the location of the file. Returns: dict: a dictionary whose keys are the domain...
64a8ab2208c8189ddc21b41bc21440d709784eac
667,415
def _flatten_vertex(vertex_json): """Flatten the nested json structure returned by the Explorer.""" vertex = {'id': vertex_json['id'], 'properties': {}} for prop in vertex_json['properties']: if prop['cardinality'] == 'single': vals = prop['values'][0]['value'] elif prop['cardina...
c48e9afbc0d1504643d74ed0f5a1bd0ee65a816d
667,416
import os import contextlib def printmethod(func): """ Decorator function used to add kwargs common to all plotting functions. :param func: Function to be decorated. :return: Decorated function """ def wrapper(*args, print_fl=True, **kwargs): """ Wrapper for function ...
28a4bee84adec25b0a2f6269c75d1eacf4085c58
667,417
def large_validator_set(spec): """ Helper method to create a large series of default balances. Usage: `@with_custom_state(balances_fn=default_balances, ...)` """ num_validators = 2 * spec.SLOTS_PER_EPOCH * spec.MAX_COMMITTEES_PER_SLOT * spec.TARGET_COMMITTEE_SIZE return [spec.MAX_EFFECTIVE_BALAN...
b7437add1f30183f4ff6a41e0f02c78856867a61
667,418
import re def _clean_and_format_idf_string(st): """Cleans an idf string and reformats as a list. :rtype: str """ # removes the comments st=re.sub(r'!.*\n','',st) #print(st) # split by ';' a=st.split(';') # gives a list of object strings #print(a) # split by...
1f5444c7cdfb805d9d7a000d898e27d3ab367405
667,419
import os def ensure_ext(path, ext, infix=None): """ Compute target path with eventual infix and extension >>> ensure_ext("model.pt", "pt", infix="0.87") 'model-0.87.pt' >>> ensure_ext("model.test", "pt", infix="0.87") 'model-0.87.test.pt' >>> ensure_ext("model.test", "test", infix="pie") ...
05a2a948007294724316c830bf2bd18284ba9e24
667,420
def subsample(df, tightness=1, report=False): """Downsample larger topics to (roughly) size of smallest topic. Specify tightness < 1 to cap ratio of largest to smallest group produced.""" groups = df.groupby('topic') smallest = min([len(g[1]) for g in groups]) trim_to = int(smallest / tightness) ...
bee3946e38d3da35ef6ad0835a0f43532fa2dc58
667,421
def get_chunk(total, current, list): """ :param total: Total number of wanted chunks :param current: Current chunk position wanted :param list: List of data who will be chunked :return: The chunk """ length = len(list)//total start = current*length if current == total-1: ret...
11423312c1ed71bd5b04a3b05d8326d3887f8283
667,422
def get_element(array): """ Get an element from an array of any depth. Args ---- array (Type of the element): Array we want to get an element Returns ------- Type of the element: One of the element of the array """ element = array[0] for i in...
8a3cd667b9248a0451666469ed201512dbcae350
667,424
import os def getpolicypath(sysvolpath, dnsdomain, guid): """Return the physical path of policy given its guid. :param sysvolpath: Path to the sysvol folder :param dnsdomain: DNS name of the AD domain :param guid: The GUID of the policy :return: A string with the complete path to the policy folde...
a22be330ee72c94fad80329ae98d8c23e06f532f
667,425
import argparse def arg_load(): """ Lit les arguments et les assigne a gofile et aux options d'impression que sont notreemapr, notreemapcsv, noscatterr et noscattercsv """ parser = argparse.ArgumentParser() parser.add_argument("gofile", help="The GO\tp.value file.") parser.add_argu...
98539b3e50d95b51a67cb9f628f3e6ef9126c925
667,426
import six import re def is_valid_mac(address): """Verify the format of a MAC address. Check if a MAC address is valid and contains six octets. Accepts colon-separated format only. :param address: MAC address to be validated. :returns: True if valid. False if not. """ m = "[0-9a-f]{2}(:...
eba258e3c29fd50d2167d1f08493f1282bb6dbac
667,427
def does_flavor_exist(nova_client, flavor_name): """ Check if flavor exists """ for flavor in nova_client.flavors.list(): if flavor.name == flavor_name: return True return False
bdd853f606bcdb94c92c4417363bf9d0b8d2c36a
667,428
def alphabetical_value(name: str, alphabet: list): """ For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53 :param name: :param alphabet: :return: """ result = 0 for char in name: result += alphabet.index(char) + 1 ...
a3278126f4ff17c56e22f3cd68864457f0d79935
667,429
def namestr(obj, namespace): """This function extracts the name of the variable in a list Args: obj: variable whose name we want to extract namespace: namespace of interest """ return [name for name in namespace if namespace[name] is obj]
16756b7580dce4f9e0408cdc9431b307bbe141f7
667,430
def safe_value_fallback2(dict1: dict, dict2: dict, key1: str, key2: str, default_value=None): """ Search a value in dict1, return this if it's not None. Fall back to dict2 - return key2 from dict2 if it's not None. Else falls back to None. """ if key1 in dict1 and dict1[key1] is not None: ...
5a09b5dd5108957588e5eba7867dac69b7f09fc0
667,431
import os def isdirectory(path): """ Check if input path is a directory. """ try: os.chdir(path) os.chdir('..') except OSError: return False return True
1b694254544df200f9517fd5aa0ae9fcfc8c646a
667,432
import os import subprocess def optimal_moves(action_list): """ Parameters ---------- action_list: list Returns ------- int The value to the current player. Equals 1 if player can force a win, 0 if player can force a draw and -1 if player can only lose. list A...
70810025f0c47267be052385e4e41d83fb97a1ce
667,433
import math def Combinations(n, k): """Calculate the binomial coefficient, i.e., "n choose k" This calculates the number of ways that k items can be chosen from a set of size n. For example, if there are n blocks and k of them are bad, then this returns the number of ways that the bad blocks can be distrib...
b47be64681f0351eb63b910405f25c8aa8f0386d
667,434
def discard_ambiguous_seqs( content: list, ) -> list: """Discard any sequences with non DNA base letters. Args: content: list of sequences Returns: list of sequences which exclusively consist of DNA base letters """ unambiguous_seqs: list = list() seq_index: int = 0 ...
42568bdae223084aa9a71f33d32f2ca9ab27fb8e
667,435
from typing import Tuple def normalize_architecture(arch: str, variant: str) -> Tuple[str, str]: """ Normalize the passed architecture and variant. This is copying the same semantics used in https://github.com/moby/containerd/blob/ambiguous-manifest-moby-20.10/platforms/database.go """ arch, v...
fe1711fca17238fba1a840900d133013d5de7591
667,436
def get_postrate(dates, values, rate): """ rate: number of days input: rate: 2 -----------+-------- dates | values -----------+-------- 25-12-2019 | 5 26-12-2019 | 5 27-12-2019 | 5 28-12-2019 | 5 29-12-2019 | 8 30-12-2019 ...
2c1398dfa56ff5fcb6eb4eb0805d88b354892c1a
667,437
def force2bytes(s): """ Convert the given string to bytes by encoding it. If the given argument is not a string (already bytes?), then return it verbatim. :param s: Data to encode in bytes, or any other object. :return: Bytes-encoded variant of the string, or the given argument verbatim. """ ...
8a7fb86152d2d4086ca4dc20c2509c2e64653dc5
667,438
def is_chromosome_valid(chromosome: list) -> bool: """ :param chromosome: хромосома (или её шаблон) :return: True/False для верной/нарушенной топологии хромосомы """ for i, gen in enumerate(chromosome): for j in chromosome[:i:-1]: if gen and j and gen[1] in j: re...
de1767be8fe9b65631977ccb0a7f644c2cc8e607
667,439
def _get_build_data(build): """ Returns the given build model as formatted dict. Args: build (molior.model.build.Build): The build model. Returns: dict: The data dict. """ maintainer = "-" if build.maintainer: maintainer = "{} {}".format( build.maint...
27f11a267d08ee4fe9db6ccb013efc86f26709c2
667,440
def compute_title_bodyparagraph_sim_simple(t, p): """ A heuristic way of computing lexical similarity between two strings -- using BOW overlap. :param t: :param p: :return: """ # a very simple method used as a dummy until a more elaborate approach is implemented t_toks = t.split() p_...
ac3a904ca5bd14ab3d92036e2285d1a6f546b462
667,441