content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def find_bands(bands, target_avg, target_range, min_shows): """ Searches dictionary of bands with band name as keys and competition scores as values for bands that are within the range of the target average and have performed the minimum number of shows. Returns a list of bands that meet the search ...
1b2b93f0a1d4236ad62102205606eff8afb3802a
704,428
import torch def ones(shape, dtype=None): """Wrapper of `torch.ones`. Parameters ---------- shape : tuple of ints Shape of output tensor. dtype : data-type, optional Data type of output tensor, by default None """ return torch.ones(shape, dtype=dtype)
a234936baa16c8efdc63e903d8455895ab7f2f0c
704,440
import asyncio def mock_coro(return_value=None, exception=None): """Return a coro that returns a value or raise an exception.""" fut = asyncio.Future() if exception is not None: fut.set_exception(exception) else: fut.set_result(return_value) return fut
d06d037bab143e288534e3e7e98da259f7c1cefc
704,448
import requests import json def request_records(request_params): """ Download utility rate records from USURDB given a set of request parameters. :param request_params: dictionary with request parameter names as keys and the parameter values :return: """ records = requests.get( ...
7323657186cc87a291e47c3a71cd2e81b4ec8a73
704,449
def calc_glass_constants(nd, nF, nC, *partials): """Given central, blue and red refractive indices, calculate Vd and PFd. Args: nd, nF, nC: refractive indices at central, short and long wavelengths partials (tuple): if present, 2 ref indxs, n4 and n5, wl4 < wl5 Returns: ...
f347b6caf167c19451bb2f03e88b5846c6873250
704,451
def in_range(x, a1, a2): """Check if (modulo 360) x is in the range a1...a2. a1 must be < a2.""" a1 %= 360. a2 %= 360. if a1 <= a2: # "normal" range (not including 0) return a1 <= x <= a2 # "jumping" range (around 0) return a1 <= x or x <= a2
8855ea29e44c546d55122c7c6e4878b44a3bc272
704,455
def add_common_arguments(parser): """Populate the given argparse.ArgumentParser with arguments. This function can be used to make the definition these argparse arguments reusable in other modules and avoid the duplication of these definitions among the executable scripts. The following arguments a...
c8e3eba16c33f0fcf12caf3a31b281dcee858648
704,457
def attr_names(obj): """ Determine the names of user-defined attributes of the given SimpleNamespace object. Source: https://stackoverflow.com/a/27532110 :return: A list of strings. """ return sorted(obj.__dict__)
ecbc0321d0796925341731df303c48ea911fcf57
704,459
import random def weighted_choice(choices): """ Pick a weighted value off :param list choices: Each item is a tuple of choice and weight :return: """ total = sum(weight for choice, weight in choices) selection = random.uniform(0, total) counter = 0 for choice, weight in choices: ...
c32ff27b9892bb88db2928ec22c4ede644f6792c
704,461
def get_layout(data, width_limit): """A row of a chart can be dissected as four components below: 1. Label region ('label1'): fixed length (set to max label length + 1) 2. Intermediate region (' | '): 3 characters 3. Bar region ('▇ or '): variable length This function first calculates the width of...
dbb8bfa2c537f3b05713bf3abdc106ec74bc7ac9
704,466
def get_number_of_classes(model_config): """Returns the number of classes for a detection model. Args: model_config: A model_pb2.DetectionModel. Returns: Number of classes. Raises: ValueError: If the model type is not recognized. """ meta_architecture = model_config.WhichOneof("model") meta...
d87605b6025e1bc78c7436affe740f7591a99f68
704,467
def shorten_build_target(build_target: str) -> str: """Returns a shortened version of the build target.""" if build_target == '//chrome/android:chrome_java': return 'chrome_java' return build_target.replace('//chrome/browser/', '//c/b/')
03af53f1fcacae9a4e0309053075806d65275ce9
704,468
from typing import Tuple import random def draw_two(max_n: int) -> Tuple[int, int]: """Draw two different ints given max (mod max).""" i = random.randint(0, max_n) j = (i + random.randint(1, max_n - 1)) % max_n return i, j
9ebb09158c296998c39a2c4e8fc7a18456428fc6
704,471
def versionPropertiesDictionary(sql_row_list): """ versionPropertiesDictionary(sql_row_list) transforms a row gotten via SQL request (list), to a dictionary """ properties_dictionary = \ { "id": sql_row_list[0], "model_id": sql_row_list[1], "version": sql_row_list[2]...
ab8cdd166bf8a187945c44fd416c3a4cf4634d02
704,472
def ms2str(v): """ Convert a time in milliseconds to a time string. Arguments: v: a time in milliseconds. Returns: A string in the format HH:MM:SS,mmm. """ v, ms = divmod(v, 1000) v, s = divmod(v, 60) h, m = divmod(v, 60) return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
5d50aa072584e5ad17d8bd3d08b0b0813aced819
704,475
def is_index(file_name: str) -> bool: """Determines if a filename is a proper index name.""" return file_name == "index"
7beb5779b61e25b4467eb7964478c78d44f28931
704,480
def search_tag(resource_info, tag_key): """Search tag in tag list by given tag key.""" return next( (tag["Value"] for tag in resource_info.get("Tags", []) if tag["Key"] == tag_key), None, )
5945631a3de7032c62c493369e82dd330ef2bc47
704,483
import six def _expand_expected_codes(codes): """Expand the expected code string in set of codes. 200-204 -> 200, 201, 202, 204 200, 203 -> 200, 203 """ retval = set() for code in codes.replace(',', ' ').split(' '): code = code.strip() if not code: continue ...
52056db88bf14352d4cda2411f25855457defbd7
704,485
import torch def make_complex_matrix(x, y): """A function that takes two tensors (a REAL (x) and IMAGINARY part (y)) and returns the combine complex tensor. :param x: The real part of your matrix. :type x: torch.doubleTensor :param y: The imaginary part of your matrix. :type y: torch.doubleTe...
faae031b3aa6f4972c8f558f6b66e33d416dec71
704,489
from typing import SupportsAbs import math def is_unit(v: SupportsAbs[float]) -> bool: # <2> """'True' if the magnitude of 'v' is close to 1.""" return math.isclose(abs(v), 1.0)
0b31da2e5a3bb6ce49705d5b2a36d3270cc5d802
704,491
async def async_unload_entry(hass, config_entry): """Handle removal of an entry.""" return True
28005ececbf0c43c562cbaf7a2b8aceb12ce3e41
704,496
import json def is_valid_json(text: str) -> bool: """Is this text valid JSON? """ try: json.loads(text) return True except json.JSONDecodeError: return False
3013210bafd5c26cacb13e9d3f4b1b708185848b
704,497
from pathlib import Path def get_config_path(root: str, idiom: str) -> Path: """Get path to idiom config Arguments: root {str} -- root directory of idiom config idiom {str} -- basename of idiom config Returns: Tuple[Path, Path] -- pathlib.Path to file """ root_path = Path...
86d65f11fbd1dfb8aca13a98e129b085158d2aff
704,498
def minor_min_width(G): """Computes a lower bound for the treewidth of graph G. Parameters ---------- G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewidth. Examples -------- Thi...
649ea7fe0a55ec5289b04b761ea1633c2a258000
704,499
def normalize_email(email): """Normalizes the given email address. In the current implementation it is converted to lower case. If the given email is None, an empty string is returned. """ email = email or '' return email.lower()
6ee68f9125eef522498c7299a6e793ba11602ced
704,500
def parse_read_options(form, prefix=''): """Extract read options from form data. Arguments: form (obj): Form object Keyword Arguments: prefix (str): prefix for the form fields (default: {''}) Returns: (dict): Read options key - value dictionary. """ read_options = { ...
660e836172015999fe74610dffc331d2b37991c3
704,501
import operator import math def unit_vector(vec1, vec2): """ Return a unit vector pointing from vec1 to vec2 """ diff_vector = map(operator.sub, vec2, vec1) scale_factor = math.sqrt( sum( map( lambda x: x**2, diff_vector ) ) ) if scale_factor == 0: scale_factor = 1 # We don't have an actu...
79e2cff8970c97d6e5db5259801c58f82075b1a2
704,506
import re def get_info(prefix, string): """ :param prefix: the regex to match the info you are trying to obtain :param string: the string where the info is contained (can have new line character) :return: the matches within the line """ info = None # find and return the matches based on ...
ed41100910df8ec3e0060ecd1196fb8cc1060329
704,516
def is_nonnegative_length(G, l): """ Checks whether a length function, defined on the arcs, satisfies the non-negative condition. Args: G: An instance of Graph class. l: A dictionary that defines a length function on the edge set. Returns: A boolean, True if the length function sat...
c99aaf07b65f9a192b6421b4b3ccf73c98917500
704,521
def bytes_to_int(b: bytes) -> int: """ Convert bytes to a big-endian unsigned int. :param b: The bytes to be converted. :return: The int. """ return int.from_bytes(bytes=b, byteorder='big', signed=False)
eb08ae0b2663047557b8f102c6c6ed565aae8044
704,526
def pyav_decode_stream( container, start_pts, end_pts, stream, stream_name, buffer_size=0 ): """ Decode the video with PyAV decoder. Args: container (container): PyAV container. start_pts (int): the starting Presentation TimeStamp to fetch the video frames. end_pts (i...
5b012899c047dcd3ee90d793c68ebdd1d2f413c1
704,530
def crop_images(x, y, w, h, *args): """ Crops all the images passed as parameter using the box coordinates passed """ assert len(args) > 0, "At least 1 image needed." cropped = [] for img in args: cropped.append(img[x : x + h, y : y + w]) return cropped
e8f78246c0bfeb3d370b8fe01e264b2f7e0e1c49
704,537
import time import json def WriteResultToJSONFile(test_suites, results, json_path): """Aggregate a list of unittest result object and write to a file as a JSON. This takes a list of result object from one or more runs (for retry purpose) of Python unittest tests; aggregates the list by appending each test resu...
cb53b65bf5c8ceb1d0695e38c4ebeedd4916fe14
704,538
def split_person_name(name): """ A helper function. Split a person name into a first name and a last name. Example. >>> split_person_name("Filip Oliver Klimoszek") ("Filip Oliver", "Klimoszek") >>> split_person_name("Klimoszek") ("", "Klimoszek") """ parts = name.split(" ") return " ".join(parts[:-1...
86b7c7cec1e7772437f41f11437834cfa34051c7
704,539
def format_price(raw_price): """Formats the price to account for bestbuy's raw price format Args: raw_price(string): Bestbuy's price format (ex: $5999 is $59.99) Returns: string: The formatted price """ formatted_price = raw_price[:len(raw_price) - 2] + "." + raw_price[len(raw_pric...
a3b0adc94421334c3f1c4fe947329d329e68990e
704,541
def replicated_data(index): """Whether data[index] is a replicated data item""" return index % 2 == 0
26223e305d94be6e092980c0eb578e138cfa2840
704,543
def get_user_roles_common(user): """Return the users role as saved in the db.""" return user.role
cf25f029325e545f5d7685e6ac19e0e09105d65a
704,544
def partial_es(Y_idx, X_idx, pred, data_in, epsilon=0.0001): """ The analysis on the single-variable dependency in the neural network. The exact partial-related calculation may be highly time consuming, and so the estimated calculation can be used in the bad case. Args: Y_idx: index of Y to acce...
12186469b27bebea4735372e2b45f463bbfbaff1
704,545
def isfloat(s): """ Checks whether the string ``s`` represents a float. :param s: the candidate string to test :type s: ``str`` :return: True if s is the string representation of a number :rtype: ``bool`` """ try: x = float(s) return True except: r...
2233d0a06b9ff0be74f76ef2fce31c816f68584c
704,547
def percentage_to_float(x): """Convert a string representation of a percentage to float. >>> percentage_to_float('55%') 0.55 Args: x: String representation of a percentage Returns: float: Percentage in decimal form """ return float(x.strip('%')) / 100
6c1aeac99278963d3dd207d515e72b6e1e79f09f
704,548
from typing import OrderedDict import inspect def build_paramDict(cur_func): """ This function iterates through all inputs of a function, and saves the default argument names and values into a dictionary. If any of the default arguments are functions themselves, then recursively (depth-first) ad...
b62daf5ffe7b9211d898d26dc754875459dbe1ba
704,551
def get_channel_members_names(channel): """Returns a list of all members of a channel. If the member has a nickname, the nickname is used instead of their name, otherwise their name is used""" names = [] for member in channel.members: if member.nick is None: names.append(member.name) ...
955ea4013841fe8aac52f0474a65e221795db571
704,553
def compress_vertex_list(individual_vertex: list) -> list: """ Given a list of vertices that should not be fillet'd, search for a range and make them one compressed list. If the vertex is a point and not a line segment, the returned tuple's start and end are the same index. Args: indivi...
a98f8b101219215f719b598ed8c47074a42ecb13
704,555
def week_of_year(datetime_col): """Returns the week from a datetime column.""" return datetime_col.dt.week
c1bf4e0cd5d4aeddf2cff9a1142fcb45b17d1425
704,557
def normalize(df, df_ref=None): """ Normalize all numerical values in dataframe :param df: dataframe :param df_ref: reference dataframe """ if df_ref is None: df_ref = df df_norm = (df - df_ref.mean()) / df_ref.std() return df_norm
56c96f43c98593a5cf21425f23cfd92a7f6d6fe3
704,558
def _validate_positive_int(value): """Validate value is a natural number.""" try: value = int(value) except ValueError as err: raise ValueError("Could not convert to int") from err if value > 0: return value else: raise ValueError("Only positive values are valid")
ddc2087d69c96fa72594da62192df58555b25029
704,560
def transpose(table): """ Returns a copy of table with rows and columns swapped Example: 1 2 1 3 5 3 4 => 2 4 6 5 6 Parameter table: the table to transpose Precondition: table is a rectangular 2d List of numbers """ result = []...
fe84714d3e09deb22058fd75ac3333c2206f77c3
704,561
def max_rl(din): """ A MAX function should "go high" only when all of its inputs have arrived. Thus, AND gates are used for its implementation. Input: a list of 1-bit WireVectors Output: a 1-bit WireVector """ if len(din) == 1: dout = din[0] else: ...
b65710967a8a785e1ca0679252ac69c140b4c560
704,562
import requests def process_request(url, auth): """Perform an http request. :param url: full url to query :type url: ``str`` :param auth: username, password credentials :type auth: ``tuple`` || ``None`` :returns: ``dict`` """ content = requests.get(url, auth=auth) if content.statu...
051c60e03458e3c38d93dfd65d15f355ec284c12
704,563
import random def genpass(pwds_amount=1, paswd_length=8): """ Returns a list of 'pwds_amount' random passwords, having length of 'paswd_length' """ return [ ''.join([chr(random.randint(32, 126)) for _ in range(paswd_length)]) for _ in range(pwds_amount)]
d5d4e38cc334f44e837c72f265a391bf72f5bd5f
704,565
def vect3_scale(v, f): """ Scales a vector by factor f. v (3-tuple): 3d vector f (float): scale factor return (3-tuple): 3d vector """ return (v[0]*f, v[1]*f, v[2]*f)
94902cad0a7743f8e3ed1582bf6402229b8a028d
704,566
import math def RadialToTortoise(r, M): """ Convert the radial coordinate to the tortoise coordinate r = radial coordinate M = ADMMass used to convert coordinate return = tortoise coordinate value """ return r + 2. * M * math.log( r / (2. * M) - 1.)
1bbfad661d360c99683b3c8fbe7a9c0cabf19686
704,570
def MediumOverLong(lengths): """ A measure of how needle or how plate-like a molecules is. 0 means perfect needle shape 1 means perfect plate-like shape ShortOverLong = Medium / Longest """ return lengths[1]/lengths[2]
48a053b55b39a50d7b0f618f843d370a55220765
704,575
def rename_category_for_flattening(category, category_parent=""): """ Tidy name of passed category by removing extraneous characters such as '_' and '-'. :param category: string to be renamed (namely, a category of crime) :param category_parent: optional string to insert at the beginning of the str...
360e87da0a8a778f32c47adc58f33a2b92fea801
704,580
import math def billing_bucket(t): """ Returns billing bucket for AWS Lambda. :param t: An elapsed time in ms. :return: Nearest 100ms, rounding up, as int. """ return int(math.ceil(t / 100.0)) * 100
87b9963c1a2ef5ad7ce1b2fac67e563dcd763f73
704,581
def adjust_lr_on_plateau(optimizer): """Decrease learning rate by factor 10 if validation loss reaches a plateau""" for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr']/10 return optimizer
615631fd4853e7f0c0eae59a3336eb4c4794d3a3
704,583
import re def replace_php_define(text, define, value): """ Replaces a named constaint (define) in PHP code. Args: text (str) : The PHP code to process. define (str) : Name of the named constant to modify. value (int,str) : Value to set the 'define' to. Returns: ...
02e3194d6fb83958d525651cdca6e3cec1cf3bb7
704,590
def _only_one_selected(*args): """Test if only one item is True.""" return sum(args) == 1
9966cc7c2cde16c689f29ba2add80b2cddce56e7
704,592
import random import string def generate_random_id(start: str = ""): """ Generates a random alphabetic id. """ result = "".join(random.SystemRandom().choices(string.ascii_lowercase, k=16)) if start: result = "-".join([start, result]) return result
f818ecf7ba4296a3ad010ef20bc5e286036bb56d
704,593
def get_client_names(worksheet) -> list: """Get list of client names from Excel worksheet.""" num_rows = worksheet.max_row names = [] for i in range(2, num_rows+1): cell_obj = worksheet.cell(row=i, column=1) if cell_obj.value not in names: names.append(cell_obj.value) r...
6da6e52ed10e84ae79119c511e063114bb61b334
704,594
def upper(value: str): # Only one argument. """Converts a string into all uppercase""" return value.upper()
8ec4c4ed284bc8d823e356db7749a4c98a00b194
704,596
def xor(a,b): """ XOR two strings of same length""" assert len(a) == len(b) x = [] for i in range(len(a)): x.append( chr(ord(a[i])^ord(b[i]))) return ''.join(x)
cbe3d32883dc5516821711181c7f5d52194d89de
704,597
def hello_world(text: str) -> str: """Print and return input.""" print(text) return text
7bfcb8e9cfccdf5fad8c702f97f6b7c4e56c7682
704,601
import functools def polygon_wrapper(func): """ Wrapper function to perform the setup and teardown of polygon attributes before and after creating the polygon. Keyword arguments: func (function) -- the function to draw the polygon. """ @functools.wraps(func) def draw_polygon(self...
76056e41c36a2c15dcb8a2e05cc4ec4c1beb68dc
704,605
def compose_base_find_query(user_id: str, administrator: bool, groups: list): """ Compose a query for filtering reference search results based on user read rights. :param user_id: the id of the user requesting the search :param administrator: the administrator flag of the user requesting the search ...
2f398930603093ddc59e0c6ba4956e7d46a7758d
704,606
def filter_df_on_ncases(df, case_id_glue="case:concept:name", max_no_cases=1000): """ Filter a dataframe keeping only the specified maximum number of cases Parameters ----------- df Dataframe case_id_glue Case ID column in the CSV max_no_cases Maximum number of cases...
5f8532ebe465d7b80934b35ef8d3925217f4e355
704,608
def get_first_group (match): """ Retrieves the first group from the match object. """ return match.group(1)
d4103989a7fbd55e40600d391b51dfb93053ed8f
704,612
def _uint_to_le(val, length): """Returns a byte array that represents an unsigned integer in little-endian format. Args: val: Unsigned integer to convert. length: Number of bytes. Returns: A byte array of ``length`` bytes that represents ``val`` in little-endian format. """ retur...
54e765e7b3772c6e2e6dc4c7e6de48d034b9d4b5
704,616
def get_type_path(type, type_hierarchy): """Gets the type's path in the hierarchy (excluding the root type, like owl:Thing). The path for each type is computed only once then cached in type_hierarchy, to save computation. """ if 'path' not in type_hierarchy[type]: type_path = [] ...
29344b63197f4ea6650d059767100401c693990a
704,618
def expand_parameters_from_remanence_array(magnet_parameters, params, prefix): """ Return a new parameters dict with the magnet parameters in the form '<prefix>_<magnet>_<segment>', with the values from 'magnet_parameters' and other parameters from 'params'. The length of the array 'magnet_paramete...
e087f5b1e8ea264f074f921a5283d7806178664b
704,620
def tag_group(tag_group, tag): """Select a tag group and a tag.""" payload = {"group": tag_group, "tag": tag} return payload
f22ccd817145282729876b0234c8309c24450140
704,622
def read_seq_file(filename): """Reads data from sequence alignment test file. Args: filename (str): The file containing the edge list. Returns: str: The first sequence of characters. str: The second sequence of characters. int: The cost per gap in a sequence. ...
9160bb0b2643deae669818cea1bc1ebeb51506b8
704,624
def _seasonal_prediction_with_confidence(arima_res, start, end, exog, alpha, **kwargs): """Compute the prediction for a SARIMAX and get a conf interval Unfortunately, SARIMAX does not really provide a nice way to get the confidence intervals out of the box, so we ha...
9520bf1a60eeb39c25e9a369b0b337905df9afb8
704,626
def top_height(sz): """Returns the height of the top part of size `sz' AS-Waksman network.""" return sz // 2
1e4a43a8935cc5c3ccf104e93f87919205baf4a4
704,627
def reverse_complement(dna): """ Reverse-complement a DNA sequence :param dna: string, DNA sequence :type dna: str :return: reverse-complement of a DNA sequence """ complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} return ''.join([complement[base] for base in dna[::-1]])
efcb38e06fc494adabeb304934ebef9bd932a11f
704,631
import torch def threshold(tensor, density): """ Computes a magnitude-based threshold for given tensor. :param tensor: PyTorch tensor :type tensor: `torch.Tensor` :param density: Desired ratio of nonzeros to total elements :type density: `float` :return: Magnitude threshold :rtype: `f...
d0c5a2726a2df195b0588af8af95dac187f50e1b
704,635
def _succ(p, l): """ retrieve the successor of p in list l """ pos = l.index(p) if pos + 1 >= len(l): return l[0] else: return l[pos + 1]
0eea63bd24da4079b9718af437c6d7e38ef25444
704,638
def reorder_cols_df(df, cols): """Reorder the columns of a DataFrame to start with the provided list of columns""" cols2 = [c for c in cols if c in df.columns.tolist()] cols_without = df.columns.tolist() for col in cols2: cols_without.remove(col) return df[cols2 + cols_without]
917b0084ba34f8e1b1fc697c4838ff8404a2fc90
704,641
def add_923_heat_rate(df): """ Small function to calculate the heat rate of records with fuel consumption and net generation. Parameters ---------- df : dataframe Must contain the columns net_generation_mwh and fuel_consumed_for_electricity_mmbtu Returns ------- dat...
907ac6ba469a65dfe25a84f7498e66b1e0535d19
704,642
from datetime import datetime def datefix(datestr): """ transform string into a python datetime object handle mm/dd/yy or mm/dd/yyyy or dashes instead of slashes """ fix = datestr.replace('-','/') if len(fix) > 4: try: return datetime.strptime(fix, "%m/%d/%y") except V...
2cb728dfcec24b350d63a79fc3964d3325780b6a
704,644
import re def cleanHtml(sentence): """ remove all Html canvas from the sentence :param sentence {str} sentence :return: {str}: sentence without html canvas """ cleanr = re.compile('<.*?>') cleantext = re.sub(cleanr, ' ', str(sentence)) return cleantext
1a3edcd7227468f8f3102525538a728a9bc93fc0
704,645
def fit_index(dataset, list_variables): """ Mapping between index and category, for categorical variables For each (categorical) variable, create 2 dictionaries: - index_to_categorical: from the index to the category - categorical_to_index: from the category to the index Parameters ---...
7b8c73a5d23de2e537c1f28078d2e032095d6b1c
704,648
def convert_bin_to_text(bin_str: str) -> str: """Convert a string of binary to text. Parameters: ----------- bin_str: string: A string of binary, terminating with 00000000. Returns: -------- text: string: A plaintext representation of the binary string. """ # get nu...
8890ff192ae4b6e01401dd7f018bf8906c3c37ce
704,650
def scale_on_x_list(x_list, scaler): """Scale list of ndarray. """ return [scaler.transform(e) for e in x_list]
2fbe36cb23e99ca6eaf277fb5509e2e997ec4a52
704,651
import hashlib def md5(ori_str): """ MD5加密算法 :param ori_str: 原始字符串 :return: 加密后的字符串 """ md5_obj = hashlib.md5() md5_obj.update(ori_str.encode("utf8")) return md5_obj.hexdigest()
75efc3226c2f0355ce4b988acd6dcd1a95ea8294
704,652
import getpass def getuser() -> str: """ Get the username of the current user. Will leverage the ``getpass`` package. Returns: str: The username of the current user """ return getpass.getuser()
3f6053e9aba37f7eafcd7735d7509af290fd3940
704,653
def cal_pipe_equivalent_length(tot_bui_height_m, panel_prop, total_area_module): """ To calculate the equivalent length of pipings in buildings :param tot_bui_height_m: total heights of buildings :type tot_bui_height_m: float :param panel_prop: properties of the solar panels :type panel_prop: di...
60c95cc1c5a38876095a77f4e68ab3b0df6280a3
704,654
def format_parameters(section): """Format the "Parameters" section.""" def format_item(item): item = map(lambda x: x.strip(), item) return ' - **{0}**: *{1}*\n {2}'.format(*item) return '**Parameters**\n\n{0}'.format('\n\n'.join( map(format_item, section)))
8f1393b843b6ea46d69d5644f932f7f0e62160ab
704,655
def normalize_trinucleotide(trinucleotide): """Return the normalized representation of the input trinucleotide sequence Notes ----- Each trinucleotide sequence has two possible representations (the sequence and its reverse complement). For example, 5'-ACG-3' and 5'-CGT-3' are two representation...
fe04ba6fad28285eac9becbbd6e5324ec7734850
704,660
import math def format_float(number, decimal_places): """ Accurately round a floating-point number to the specified decimal places (useful for formatting results). """ divisor = math.pow(10, decimal_places) value = number * divisor + .5 value = str(int(value) / divisor) frac = value.sp...
e7aaa92025284489075ce053319c27310bb96a00
704,662
def decode_transaction_filter(metadata_bytes): """Decodes transaction filter from metadata bytes Args: metadata_bytes (str): Encoded list of transaction filters Returns: decoded transaction_filter list """ transaction_filter = [] if not metadata_bytes: return None for i in...
c76638f6592fb098e2878471746152aa9df9a694
704,663
def merge_schema(original: dict, other: dict) -> dict: """Merge two schema dictionaries into single dict Args: original (dict): Source schema dictionary other (dict): Schema dictionary to append to the source Returns: dict: Dictionary value of new merged schema """ source =...
6425b64e6ab166ac14afc2e47392745903b8fd12
704,667
import hashlib def hash160(s: bytes) -> bytes: """ sha256 followed by ripemd160 :param s: data :return: hashed data """ return hashlib.new('ripemd160', hashlib.sha256(s).digest()).digest()
7b18fcdf51db707a17d5408c7b364818a6c5ee0c
704,668
import re def valid_email(email): """Check for a valid email address. Args: email (str): Email. Returns: bool: Return True if in valid email format and False if not. """ return bool(re.match('^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$', email))
01c343008229fb2fdf2af3a9a74f3059930696eb
704,669
def PeerDownHasBgpNotification(reason): """Determine whether or not a BMP Peer Down message as a BGP notification. Args: reason: the Peer Down reason code (from the draft) Returns: True if there will be a BGP Notification, False if not """ return reason == 1 or reason == 3
8ee214798f6766916e8784dd907eeb45ff6620db
704,670
def set_purpose(slack_client, channel, purpose): """ Set the purpose of a given channel. """ response = slack_client.api_call("channels.setPurpose", purpose=purpose, channel=channel) return response
786a495b55300b955e2f7ec525117be75b251a07
704,671
def get_validate_result_form(tel_num, validate_code): """ Assemble form for get_validate_result :param tel_num: Tel number :param validate_code: Validate code from capcha image :return: Param in dict """ post_data_dict = dict() post_data_dict['source'] = 'wsyyt' post_data_dict['telno...
6340c97522a097c0cf96170e08466fb795e16dc3
704,674
def metric_max_over_ground_truths(metric_fn, predictions, ground_truths): """Take the average best score against all ground truth answers. This is a bit different than SQuAD in that there are multiple answers **and** predictions that we average over. For some situations (e.g., *top k* beams or multiple human r...
7c78fc1cca29bc9784a4e4687d794c1f2b6872c9
704,678
def not_contains(a, b): """Evaluates a does not contain b""" result = False if b in a else True return result
a0dc087049c8e93c1acdf0e59e3530a6ff8b54e5
704,684
import csv def import_town(data_file): """ Reads town raster data from a CSV file. Parameters ---------- data_file : str Name of CSV raster data file to use for the town. Returns ------- town : list List (cols) of lists (rows) representing raster data of the town. ...
b7749dfd4d698fddfe610c6a51c8ccc43c375cc2
704,686