content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def neurips2021_tex(*, family="serif"): """Fonts for Neurips 2021. LaTeX version.""" preamble = r"\renewcommand{\rmdefault}{ptm}\renewcommand{\sfdefault}{phv}" if family == "serif": return { "text.usetex": True, "font.family": "serif", "text.latex.preamble": pream...
fdcb284d548dea8cc9f030b9ed11edf6a9c63445
664,241
def calculate_IoU(geom, match): """Calculate intersection-over-union scores for a pair of boxes""" intersection = geom.intersection(match).area union = geom.union(match).area iou = intersection/float(union) return iou
92480c5cc7c1e3e99b6339a950256524a017ba3a
664,252
def powerset(lst): """returns the power set of the list - the set of all subsets of the list""" if lst == []: return [[]] #power set is a list of lists #this way is more efficent for getting the combinations of the characters in a list lose_it = powerset(lst[1:]) use_it = map(lambda subs...
04093ae60b1293edaea16ce9e278cfaff9f92251
664,253
import re def tokenize(text): """Parses a string into a list of semantic units (words) Args: text (str): The string that the function will tokenize. Returns: list: tokens parsed out by the mechanics of your choice """ tokens = re.sub('[^a-zA-Z 0-9]', '', text) tokens = t...
c5c993e05d9f7530359a44f321aa6d706cd27526
664,254
def iou_bbox(gt_box, pred_box): """ Method to calculate the Intersection over Union between two boxes """ inter_box_top_left = [max(gt_box[0], pred_box[0]), max(gt_box[1], pred_box[1])] inter_box_bottom_right = [min(gt_box[0] + gt_box[2], pred_box[0] + pred_box[2]), min...
5e1ef7e63713624eb6072b3b77d64b4579e618db
664,256
from typing import Tuple import math def get_graph_dimen(fields: dict, uniq_cnt_threshold: int) -> Tuple[int,int]: """ Helper function to first figure out how many graphs we'll be displaying, and then based on that determine the appropriate row and column count for display """ graph_cnt = 0 ...
4aa06d0ccf82fca15bd10f8470f666fad91caae5
664,258
def flatten(iterable): """Flatten a given nested iterable.""" return (x for e in iterable for x in e)
3f91d5f4b94ffdb484b53a18745e93d934b41c65
664,259
from datetime import datetime def date_from_string(indate): """ Returns a python datetime.date object from a string formatted as '2012-11-21' = 'yyyy-mm-dd' """ return datetime.strptime(indate, "%Y-%m-%d").date()
07abe82b0f6732a133485a223838e86872807329
664,260
import torch import gc def torch_pca( X, device='cpu', mean_sub=True, zscore=False, rank=None, return_cpu=True, return_numpy=False): """ Principal Components Analysis for PyTorch. If using GPU, then call...
8fbfa9c5cd55d9311913f496ece8cbc79f4d0cea
664,263
import pathlib import yaml def load_config_as_dict(path: pathlib.Path) -> dict: """ loads the ``yaml`` config file and returns a dictionary Args: path: path to json config file Returns: a nested object in which parameters are accessible using dot notations, for example ``config.model...
4ce42ced5cf95f926a992fd077847f41aff76f9e
664,264
def insertion_sort(lst: list) -> list: """Sort a list in ascending order. The original list is mutated and returned. The sort is stable. Design idea: Iterate over the list. After i iterations, the first i elements of the list should be sorted. Insert the i+1'th element in the appropriate spot in th...
56b33fda5f185381e522458718f8d0c05e9ab785
664,265
def create_ds_118(packer, filler1, filler2, filler3, brakectr, awdlckmax, awdlckmn, drvstate, drvtq, emergbrk, stoplmp, angle): """Creates a CAN message for the Ford 118 message.""" values = { "BrkCtrFnd_B_Stat": brakectr, "AwdLck_Tq_RqMx": awdlckmax, "AwdLck_Tq_RqMn": awdlckmn, "DrvSte_D_Stat": d...
6cf3bbf04307549bf3217a9ad0ce7ac06d81cdd1
664,269
def cipher(text, shift, encrypt=True): """ Encrypt and decrypt letter text by using the Caesar cipher. Parameters ---------- text : string A string only contains letters from alphabet shift : int A number that you wish to replace each original letter to the letter with that number o...
60cadd09a063af63cdd360ad62535161eab7d1bb
664,270
def load_image_mask_gt_eval(dataset, image_id): """Load and return ground truth data for an image, no processing. """ # Load image and mask image = dataset.load_image(image_id) point, class_ids, bbox, mask = dataset.load_mask(image_id) return image, class_ids, bbox, mask, point
8ab648ecaf0629e52d187ba019faaf40ce8534b3
664,271
def char_is_printable(char): """ Check if char is ascii number (<128) and printable """ if ord(char) >= 32 and ord(char) <= 126: return True else: return False
4a37f6453f5f1eb3297841960308f84c92468de8
664,272
def _url_joiner(*args): """Helper: construct an url by joining sections with /""" return '/'.join(s.strip('/') for s in args)
b94b25d0f3b5820993f4adc591e5ef257b4371da
664,273
import requests def query(uri): """ Fill in this method. Query the passed URI and return the text response. See https://2.python-requests.org/en/master/ """ response = requests.get(uri) return response.text
7cc2fee7a7cc256f59683ae2cf7832b57a63bfe9
664,275
def nonreturn(func): """ Decorator to simplying marking a function as nonreturning for the bridge """ func._bridge_nonreturn = True return func
52a8a9f1b270f105c01aeeb7b8d8c904df2ffba9
664,276
def to_int(value): """Returns the value as integer, or None if not integer.""" try: return int(value) except ValueError: return None
7345e928d0a583a87354b52a36c42ef92526fe3a
664,278
def calculateAverage(list): """ Calculate the average value from a list """ size = len(list) if size > 0: sum = 0 for i in range(0, size): sum += list[i] return sum / size return 0
cdcb8db816348ec3a2eae04ddc22719dc41a12a4
664,279
def exclude_variants(pages): """Checks if page is not a variant :param pages: List of pages to check :type pages: list :return: List of pages that aren't variants :rtype: list """ return [page for page in pages if (hasattr(page, 'personalisation_metadata') is False) ...
96246528732ae72e0b2eb900f36d0ca8a161a8c9
664,289
def check_input_expression_characters(expression): """Check whether characters of an expression are all valid. :type expression: str :rtype : bool :param expression: The expression. :return: True if all characters are valid. """ # Construct valid characters. valid_char = "0123456789AB...
4518aec25403e77c120a731013ec025359777bbe
664,291
def new_incremented_param_name(basename, currnames, start=1): """ Generate new integer incremented version of the parameter name defined by `basename` based on a list of current names in `currnames`. :param basename: base name to increment :type basename: :py:str :param currnames: curr...
bccbc76070cdd88432f5d1c9bf1ec401e3dac556
664,293
import logging def get_ugrid_mesh_description(nc_file): """ Collect UGRID mesh description from mesh file and return a list of UGRID variables; only one mesh description is allowed """ # Look for UGRID mesh description dummy variable mesh_names = [] for var_name, var in nc_file.variables....
47f6e782fe488b046abe7c3aef20f40fc85432f8
664,295
import socket def is_ipv6(addr): """Checks if a given address is an IPv6 address.""" try: socket.inet_pton(socket.AF_INET6, addr) return True except socket.error: return False
b877ff42e0077f05ea2af205a86b40822daa7fa7
664,296
def create_schema(base, engine): """ Create database schema. """ base.metadata.create_all(engine) return engine
d45a868edf0fce043dcee69b56cf721f7e5f7f0e
664,297
from typing import OrderedDict def sort_dict(d): """ Helper function; returns a recursively sorted OrderedDict (by key). :param d: A dictionary to sort. :return: An OrderedDict. """ res = OrderedDict() for k, v in sorted(d.items()): if isinstance(v, dict): res[k] = sort...
e6036ce4d1622744dd09144e00008edeaa6276d4
664,298
def get_names_from_wordlist(filepath): """Read wordlist line by line and store each line as a list entry.""" with open(filepath) as f: content = f.readlines() # Remove whitespace characters like '\n' at the end of each line return [x.strip() for x in content]
ff30553b9afeef59bc7fca8c05dc12f5d9a70686
664,299
def max_change_day(prices): """Returns the day (index) of the maximum single day change in price.""" diff_list = [] for x in range(len(prices)-1): diff_list += [prices[x+1] - prices[x]] maxindex = 0 maximum = diff_list[0] for x in range(len(diff_list)): if diff_list[x] ...
d49aec99c0fd7a29bbb382191c31835edd6b1ab9
664,301
import json def json_extract(json_path): """Converts JSON file to Python Dict Args: json_path (str): Path to JSON file Returns: data (dict): Dictionary containing JSON information """ with open(json_path) as f: data = json.load(f) return data
903c109ece195b05c40d312eab50b64538854c17
664,306
import re def sorted_alphanumeric(l, reverse=False): """ Sorts the given iterable alphanumerically. If values are numeric, sort numerically; if strings, alphanumerically. If string operations don't work we just sort normally; this works for numeric types. """ try: convert = lambda ...
34f382c7e34ee62a00bceebdeec0488d18c65e7e
664,310
import math def get_two_point_dis(point1, point2): """ Args: point1 (list): point1 point2 (list): point2 Returns: int: Euclidean distance between point1 and point2 """ # calculate the euclidean distance dist = math.sqrt((point1[0] - point2[0]) * ...
fbc80f35c6b824cf60e6cdc4a50c0ad015973304
664,313
import functools def product(iterable): """returns the product of the elements of the iterable""" return functools.reduce(lambda a, b: a * b, iterable, 1)
ac72acc233bd538bfc0322562acd44a6d16799a3
664,314
import collections def secs_to_text(cs): """Convert time in seconds to a human readable string. """ v = collections.OrderedDict() v['s'] = cs % 60 cs //= 60 v['m'] = cs % 60 cs //= 60 v['h'] = cs % 24 cs //= 24 v['d'] = cs parts = [] for k in v: if v[k] != 0: ...
f5d9cc66cbf6815fc765700309eb0f3124e58192
664,323
def connections(activities): """Enumerates the connections within a list of activities. Args: activities: The activities to process. Parents/children outside these are ignored. Returns: A list of two-tuples. Each tuple is a (parent, child) relationship. """ acts = frozenset(activitie...
2c68cc5628ad096e7bdfef426c75017bba407be9
664,325
import glob import re def GetTtyDevices(tty_pattern, vendor_ids): """Finds all devices connected to tty that match a pattern and device id. If a serial device is connected to the computer via USB, this function will check all tty devices that match tty_pattern, and return the ones that have vendor identifica...
e19851b5a54952ad03f5619e70b930e77ab264b5
664,326
import torch def cross_squared_distance_matrix(x, y): """Pairwise squared distance between two (batch) matrices' rows (2nd dim). Computes the pairwise distances between rows of x and rows of y Args: x: [batch_size, n, d] float `Tensor` y: [batch_size, m, d] float `Tensor` ...
cbe660db0458554619de62d25654991c9faf6b22
664,331
def cli_parse(parser): """Add method specific options to CLI parser. Parameters ---------- parser : argparse object Returns ---------- Updated argparse object """ parser.add_argument('-M', '--m-coef', type=int, required=False, default=4, help='M coefficient,...
d5c87c98b7641767a5dafa41219b1e30f1a88f9e
664,333
def _getSubtitleNumber(entry): """ Helper function that returns the subtitle number of a TTI block. Used to sort a list of TTI blocks by subtitle number. """ return entry['SN']
c72d4ee7df0007a316c33de5e35a14da62d77899
664,334
def extract_amount(accident, base_key): """ Get the amound of wounded/dead people from the accident data. """ if not base_key in accident.keys(): return 0 else: if len(accident[base_key].keys()) == 2: return int(accident[base_key][f"{base_key}_min"]) else: ...
96dcef363243e116115b58be70adfbca3d46d101
664,336
def write_bytes(fp, data): """ Write bytes to the file object and returns bytes written. :return: written byte size """ pos = fp.tell() fp.write(data) written = fp.tell() - pos assert written == len(data ), 'written=%d, expected=%d' % (written, len(data)) r...
4ffcfaa7005ce86d54382f273e2f801ba291dcba
664,339
def request_path(context): """Return request.path""" return context['request'].path
feebe8bb926632759ce98aeeebd7f1678005153d
664,340
import inspect def keyword(name=None, tags=(), types=()): """Decorator to set custom name, tags and argument types to keywords. This decorator creates ``robot_name``, ``robot_tags`` and ``robot_types`` attributes on the decorated keyword function or method based on the provided arguments. Robot Frame...
90bd90f4de9adafd657dba60c56cf4ffe74de097
664,344
import math def truncate_middle(content, max_length, middle="..."): """ Truncates the middle part of the string if the total length if too long. For example: truncate_middle('testabcdecho', 8) == 'tes...ho' :param content: The string that must be truncated. :type: str :param max_length: ...
16f9ec8e6210ab2820a78328e2f21ec6d636b787
664,347
def merge_jsons(jsons): """Merge JSONS returned from api.API.retrieve_pages. Args: jsons (list[dict]): Having the form: {"query": { "normalized": [ { "from": "", "to": "", }, ], "redirects": [ { "from": "", "to": "...
3fcf62b4c94b71972037727e7adbb39cc158186b
664,352
def truncate_description(desc: str) -> str: """Take the first line of a multiline description, truncated to 40 chars""" first_line = desc.strip().split("\n")[0] return first_line[:40]
387eebfcdbe1bbe1917226dd2a98763c8c8bad6e
664,355
import re def _check_separator(line, read_order): """Identify data separators, tabs or blanks """ temp = line.strip() lread = len(read_order) terms1 = re.split('\t', temp) # terms2 = re.split(' ', temp) if len(terms1) == lread: use_tabs = True print('Information: Reading ta...
62a5bf90d77a2a48cedce90ab9d7f4c8e421f0ba
664,356
def base_test_dir(tmp_path_factory): """Creates a temporary directory for the tests.""" return tmp_path_factory.mktemp("test_files")
ec8e1f123378f6d0fa4c938f664ccc665d3c4c3f
664,360
def _user_can_administer(user, org): """ Whether this user can administer the given org """ return user.is_superuser or org.administrators.filter(pk=user.pk).exists()
4664011e1cd28a149fedb5981f7d1f4595f0699b
664,365
def _get_element_type(tag): """This function extracts the type of tag specified in tag Args: tag (str or bytes): Full valid html tag from < to > Returns: str: type of HTML tag, e.g. div, p, meta, span, td, etc """ # decode tag parameter if its a bytes object tag = tag.decode() ...
42548a9f33ceeaa1126eafdc128b496b435eb2fb
664,366
import requests import json def query_vep(variants, search_distance): """Query VEP and return results in JSON format. Upstream/downstream genes are searched up to a given distance.""" ensembl_request_url = 'https://rest.ensembl.org/vep/human/region' headers = {'Content-Type': 'application/json', 'Accept':...
05558f329bf1f7deef3479937c1c54831492ee8a
664,372
def to_none(field): """ Returns the value of None for input empty strings and empty lists. """ if field == '' or field == []: return None else: return field
585e67f79ad779f0905828f4ea837f7e2e03f1d6
664,374
def ReadFile(file_path): """Returns the content of |file_path|.""" with open(file_path) as f: content = f.read() return content
4092e80a67c8495c0f71e0d4da358a9d1b98391d
664,375
from typing import Dict from typing import Hashable from typing import List def _switch_keys_and_values( key_value: Dict[Hashable, int] ) -> Dict[int, List[Hashable]]: """ Returns dictionary with switched key-value arguments where new values (old keys) stored in the list. """ value_key = {} ...
7c76cd2caea4f0a8215b026725d5896512517083
664,376
def should_assume_role(role_arn): """ Handles the case when AWS_IAM_ROLE_ARN Codefresh input parameter is omitted, which will cause the role ARN to contain the literal string "${{AWS_IAM_ROLE_ARN}}". In this case, we do not want to assume role. """ if role_arn == '${{AWS_IAM_ROLE_ARN}}': ...
3cc012977839a9edcf4bc533c29d0628ccd13d99
664,378
from typing import Union from pathlib import Path from typing import Any import pickle def read_pickle(path: Union[str, Path]) -> Any: """ Read a pickle file from path. Args: path: File path Returns: Unpickled object """ with open(path, "rb") as fp: return pickle.load...
53511f4b00bac4af6c2ed4150efc4b3dc575f59c
664,385
import torch from typing import OrderedDict def load_model(fname,model): """ Load saved model's parameter dictionary to initialized model. The function will remove any ``.module`` string from parameter's name. Parameters ---------- fname : :py:class:`str` Path to saved model model :...
561a0d2557aa92321cd8a3603cfc9d0f3cbb4b29
664,391
import socket def unused_port(hostname): """Return a port that is unused on the current host.""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((hostname, 0)) port = s.getsockname()[1] s.close() return port
c33be922d2663355b7df03c2a135535079186bac
664,395
def echo(request): """For testing purposes only.""" return request.POST
776f301cab18fc7215dabce30e27a2d147b245bd
664,396
def get_values_as_int(history, key): """Retrieve values from sequence of dictionaries, convert all values to int.""" return [int(i[key]) for i in history]
9c762fc25f33b41b1d24b54f0f27f1e1359a7aca
664,401
from pathlib import Path def empty_ref_tree(tmpdir): """Empty reference directory.""" tree = Path(tmpdir) / "ref" tree.mkdir() return tree
cc2adfd099f1adf3f95aa4ce7dd604db4a6364d9
664,402
import random def split_cases(cases, part=0.5): """Randomly split a list into two parts. part is a float between 0 and 1, indicating the relative size of the first part. """ cases = cases.copy() random.shuffle(cases) idx = int(len(cases) * part) return cases[:idx], cases[idx:]
34c726abc106e15f41edcaa84896b9e41d6decee
664,406
def _make_signal_unique(signal_name: str, db: dict) -> str: """ Preserve duplicated signal in WaveDrom format by adding extra space that will be removed later on. Add as many spaces it is required to make the identifier unique. """ new_name = signal_name while new_name in db: new_nam...
eab7a8ffe018799f4150aa8d13d34fdbd04464e3
664,407
def get_annot_reviewed_matching_aids(ibs, aid_list, eager=True, nInput=None): """ Returns a list of the aids that were reviewed as candidate matches to the input aid """ ANNOT_ROWID1 = 'annot_rowid1' ANNOT_ROWID2 = 'annot_rowid2' params_iter = [(aid,) for aid in aid_list] colnames = (ANNOT_R...
6181772fae00a13a25df9d3bea6513c394382e42
664,409
def never_swap(doors, past_selections): """ Strategy that never swaps when given a chance. """ return past_selections[-1]
77c318afdc6aea3d5d35a1ce97fe57878efc7383
664,411
from typing import List from typing import Dict from typing import Set def get_unique_affected_entity_ids(security_problems: List[Dict]) -> Set[str]: """Extract all unique affected entity IDs from a list of security problems. :param security_problems: the security problems, parsed from JSON to Dicts of Dicts ...
ffcfd9189e83ac7f0aa4c252216f47e2361713d7
664,413
import re def get_anchor_format(a): """Extract the resource file-type format from the anchor""" # (. or format=) then (file_extension) then (? or $) # e.g. "...format=txt" or "...download.mp4?..." file_format = re.search("(?:\.|format=)(\w+)(?:\?.*)?$", a) return file_format.group(1) if file_forma...
59ce6a76f82b84e8d20b2a10bd3c4130b1960656
664,415
import copy def convert_to_binary_cols(df, col, vals, targ_vals): """ convert_to_binary_cols(df, col, vals, targ_vals) Returns the input dataframe with the column values converted to categorical binary columns. The original column is dropped. Required args: - df (pd DataFrame): dataframe...
c70d46a41de933977538e1d10092fdd4380be8b6
664,417
def compute_avg_cosine(similarity_result, topn): """ Compute and return the average cosine similarities. Args ---- similarity_result (list): List of word:cosine similarity dict pairs. Return: avg_cosine (float): Computed average cosine similarity """ if len(similarity_result) >=...
fa107c66559342c7a66f5fee947cd3caeda40e9c
664,420
def default_preprocessing(df): """Replace Attrition Yes/No with 1/0""" status_map = {'No': 1, 'Yes': 0} df['Attrition'] = df['Attrition'].replace(status_map) return df
5bf0e0a87141cc4381d28edb4e40a343649083e0
664,421
def valid(board, val, pos): """Checks if value is valid to be entered in the cell or not params : val : int pos : tuple (cell cordinates) returns : boolean """ # Check row for i in range(len(board[0])): if board[pos[0]][i] == val and pos[1] != i: return False # C...
91b5aacc35f5ffe44388f678530cfc7f0e41a7d8
664,424
from typing import List def convert_records_to_dict(records: List[tuple]) -> dict: """Converts pyscopg2 records list to a dict.""" dict = {} for record in records: # Add record tuple data to dict. dict[record[0]] = record[1] return dict
523efb6c040779c3b885acdbf304177556e04c67
664,427
def is_key(obj): """Return True if object is most likely a key.""" if obj is not None and isinstance(obj, str): return "'" in obj
6eddb53f055dceac81db5056ec4b2dc8a246cc2b
664,432
def cmd( admin_only=False, acl="*", aliases=None, while_ignored=False, reply_in_thread=False, reply_broadcast=False, parse=None, strip_formatting=False, *args, **kwargs ): """ Decorator to mark plugin functions as commands in the form of !<cmd_name> * admin_only - in...
53d55b9246b0e2d0df01744ed82fe7843e896364
664,440
def until(n, filter_func, v): """Build a list: list( filter( filter_func, range(n) ) ) >>> list( filter( lambda x: x%3==0 or x%5==0, range(10) ) ) [0, 3, 5, 6, 9] >>> until(10, lambda x: x%3==0 or x%5==0, 0) [0, 3, 5, 6, 9] """ if v == n: return [] if filter_func(v): ret...
1996d5a27f964267122604937fa1163fa0da20cd
664,441
def matrix_to_text(mat): """ Convert matrix array to text using spaces/newlines as col/row delimiters """ rows = [] for row in mat: rows.append(" ".join([str(v) for v in row])) return "\n".join(rows)
ba1451374eae210ad37e227b4095c73b128c567d
664,443
def clean_data(df): """ Function to load the data sets and clean the data (so as to give column names corresponding to the different categories). Args: The merged dataframe containing the messages and the categories Returns: Dataframe that has the messages and one column for each...
9be4b0742be254ea061e6343292b71758b8269c7
664,445
def drelu(x): """ dReLu(x) = 1 if (x>0), 0 otherwise """ return (x > 0).float()
9b69826bd52f3f0875799bac571977ade6cf129b
664,446
import random def add_parameter_noise(cfg, noise_ratio): """ Add noise to the hyperparameters of the Dynamic DropConnect model. This changes the input dictionary in-place. Args: cfg: Dictionary containing the configuration with all hyperparameters noise_ratio: Ratio of noise relative ...
c46a96dbcd6f468c825f0a9fe0457ab7566541ed
664,447
import re def get_currents( content ): """ Gets the currents from an Igor file :param content: The content to search :returns: A numpy array of the currents """ j_search = 'WAVES\s*PhotoCurrent1\nBEGIN\n(.*)\nEND' match = re.search( j_search, content, flags = ( re.IGNORECASE | re.DOTALL )...
a2988fbdbe91262899fbd709b4d0d03729170b84
664,449
def _include_file_data(login, record): """Ensure that 'files' field is present in the input record""" if 'files' not in record: if 'files' in record.get('links', {}): url = record['links']['files'] elif 'id' in record: url = login.base_url + 'api/deposit/depositions/{0}/f...
578c75ed34460c408fe52f28ea5fdf38de57ef6b
664,457
def get_n_beads(n, i1 ,i2): """ given length of the ring polymer (n) and the starting-ending positions (i1, i2) returns the length of the segment of the smaller length :param n: number of elements :type n: int :param i1: starting position :type i1: int :param i2: ending position :ty...
5dee01efe31f9d98972dcdc997ad60ea1ba45b39
664,458
def variation_length(lastz_cig): """Determines how long the mapping is (sum of insertion/deletion/match), based on the lastz cig. Args: lastz_cig (string): a lastz cigar, e.g. "M50D3I5M30" Returns: int: sum of I+D+M in cigar. """ # Parsing cigars: # indices 0, 2, 4,... are ...
f353f7f9aced4c7d36f5058aa35eb2e27a8601f4
664,459
def next_indentation(line, tab_length): """Given a code line, return the indentation of the next line.""" line = line.expandtabs(tab_length) indentation = (len(line) - len(line.lstrip(" "))) // tab_length if line.rstrip().endswith(":"): indentation += 1 elif indentation >= 1: if line...
3791da54243c067a56bf21df23fbcb4d22516e70
664,460
from datetime import datetime def normalize_entity(in_dict): """Converts BlitzDB Document to standard dictionary Parameters ---------- in_dict : dict BlitzDB Document-compatible dictionary of values Returns ------- dict normal dictionary of values, output of to_dictionary...
bee7f9667c24e4296b6d4e5ceaeed29f839df123
664,461
def formatDuration(context, totminutes): """ Format a time period in a usable manner: eg. 3h24m """ mins = totminutes % 60 hours = (totminutes - mins) / 60 if mins: mins_str = '%sm' % mins else: mins_str = '' if hours: hours_str = '%sh' % hours else: hou...
f4a7ee4f8e6b4eb6ed37b005f0d2cb2b9925169b
664,465
def findpop(value, lst): """ Return whether `value` is in `lst` and remove all its occurrences """ if value in lst: while True: # remove all instances `value` from lst try: lst.pop(lst.index(value)) except ValueError: break return True # ...
eae11883a50d585fa7e319902b77e1f5e4143c52
664,467
from typing import Any def health() -> Any: """Returns an ok status for uptime monitoring purposes""" return {"status": "ok"}
496104e7d051fb7e50a6a9e9ec75c38f0dcf14bf
664,469
def replace_full_stop(string: str) -> str: """ Replace full width full stop character with Japanese dot character. :param string: String to be processed :type string: str :return: Result string :rtype: str **Example:** .. code-block:: python string = "Hello.World" res...
8b8cad94015076834827acb7a48e6840ebc0914d
664,470
import math def haversine(coord1, coord2): """use the Haversine function to determine the distance between two points in the WGS84 coordinate system. Returns the distance between the two points in meters. Source: https://janakiev.com/blog/gps-points-distance-python/ coord1: (lat, lon) coord...
611f242ead6ee90fba2c564f64d0869e77f7cdb2
664,473
from pathlib import Path def paths(base, network): """ Get the paths for the network directory, the wallet database file, and the blockchain database file. """ netDir = Path(base) / network dbPath = netDir / "wallet.db" dcrPath = netDir / "dcr.db" return netDir, dbPath, dcrPath
e97ac57993cde197ecd9f40145993d6bd3d0f4ab
664,476
def _detect_cycles(node, graph, visited, ps_stack): """ Perform DFS on PricingServices dependecy graph looking for cycles Params: node: PricingService graph: dict with adjacency list of PricingServices visited: set of already visited PricingServices during graph traversal ps...
d262533f1970c5fd674f0edf390e467444f3a34a
664,481
from typing import Any def u(x: Any) -> str: """Convert x to string.""" if isinstance(x, str): return x return str(x)
b7ae9c8d29b367d8b4f670b35b91acbda80182da
664,485
from typing import List from typing import Optional def task_list(items: List[str], items_to_check: Optional[List[int]] = None) -> str: """Creates a task list in GitHub Flavored Markdown where each item can be checked off. This task list cannot be used inside a table. :param items: The items in the task ...
92120e73ac5421479f28621e01b78a54ec3d647a
664,490
import hashlib def _get_data_and_md5_bulk(container, obj_hashkeys): """Get the MD5 of the data stored under the given container as a single bulk operation. :param container: a Container :param obj_hashkeys: a list of object hash keys :return: a dictionary where the keys are the object hash keys and t...
e0ae17ba3b4c64cdefbe0bc494afa35c2c05e287
664,491
def events_event_id_delete(event_id: str): """Deletes an event.""" return '', 204
616c11087c55f81ea072eb03d083963e28e62076
664,494
def is_palindrome(n): """ Fill in the blanks '_____' to check if a number is a palindrome. >>> is_palindrome(12321) True >>> is_palindrome(42) False >>> is_palindrome(2015) False >>> is_palindrome(55) True """ x, y = n, 0 f = lambda: y * 10 + x % 10 while x >...
a20e69502c7609131e2fe27d1b92fe1563558c38
664,496
def perm_to_string(p): """ Convert p to string, slightly more compact than listprinting. """ s = "(" for x in p: s = s + "%2d "%x s += ")" return s
3d2f99e0c5822a8f831147981d6b35c5061727a4
664,499
import re def xisabs(filename): """ Cross-platform version of `os.path.isabs()` Returns True if `filename` is absolute on Linux, OS X or Windows. """ if filename.startswith('/'): # Linux/Unix return True elif filename.startswith('\\'): # Windows return True elif re.match(r'\w:[\\/]'...
5aa82aa621dea7fb81316ea7c9d0bb9f0a9c2df7
664,500
def hot_cold_process( curr_yr, p_cold_rolling_steel, assumptions ): """Calculate factor based on the fraction of hot and cold rolling processes in steel manufacturing. The fraction of either process is calculated based on the scenario input of the future share of cold rolllin...
3fd125c0ab3a3ba26bb4eb0fcd33781de0ea08db
664,502