content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def evaluations(ty, pv): """ evaluations(ty, pv) -> ACC Calculate accuracy using the true values (ty) and predicted values (pv). """ if len(ty) != len(pv): raise ValueError("len(ty) must equal to len(pv)") total_correct = total_error = 0 for v, y in zip(pv, ty): if y == v: total_correct += 1 l = len(ty) ACC = 100.0 * total_correct / l return ACC
021c80dab1d4ed97876bebc882db3423af107ea5
8,327
import json def load_json(json_file, verbose=True): """ Simple utility function to load a json file as a dict. Args: json_file (str): path to json file to load verbose (bool): if True, pretty print the loaded json dictionary Returns: config (dict): json dictionary """ with open(json_file, 'r') as f: config = json.load(f) if verbose: print('loading external config: =================') print(json.dumps(config, indent=4)) print('==========================================') return config
9487e5f164b4f6e221ec1fd7f35d880f0ba894f7
147,410
def _temp_analyze_files(tmpdir): """Generate temporary analyze file pair.""" img_dir = tmpdir.mkdir("img") orig_img = img_dir.join("orig.img") orig_hdr = img_dir.join("orig.hdr") orig_img.open('w') orig_hdr.open('w') return orig_img.strpath, orig_hdr.strpath
bf14fd612757fe4751d3a276b9f6f4a617059d10
396,424
def primary_cat(catstr): """Return the primary category from a rider cat list.""" ret = u'' cv = catstr.split() if cv: ret = cv[0].upper() return ret
f5204e6c705bd683e6521030c6b608021de9ae5c
147,969
from typing import Any def build_where(**conditions: Any) -> str: """ Build WHERE statement with several `conditions` If no `conditions` passed return `WHERE 1 = 1` In case if a value has primitive type it will be an equal condition and in case if it is an iterable it will be an include condition """ if not conditions: return "WHERE 1 = 1" where_str = "WHERE " for i, (column, value) in enumerate(conditions.items()): if i > 0: where_str += " AND " if value is None: where_str += f"{column} IS NULL" else: if isinstance(value, (int, float)): where_str += f"{column} = {value}" elif isinstance(value, (list, tuple)): in_str = ", ".join([f"'{v}'" if isinstance(v, str) else str(v) for v in value]) where_str += f"{column} IN ({in_str})" else: where_str += f"{column} = '{value}'" return where_str
ec2d7c2aebe4798a7cb06b20f9d2c06259afdadd
648,289
def namedtuple_lower(t): """Lower cases a namedtuple""" return type(t)(*[s.lower() for s in t])
8ad93713ea12b0b9cfa48dce1629ab8da7ce7cfe
91,459
def template_function(message: str, show: bool = True) -> str: """Return a message if `show` is True. Args: message (str): The message to be returned. show (bool): Flag to return the message. Return: The message. Is show is True, empty string otherwise. """ return message if show else ""
bf84d876d133ff1a7ff2ab31d863ae5a527f8e0d
618,103
def get_tag(commands): """Generates a preprocessor tag from a set of grid commands.""" # Extra line break prevents unclosed paragraphs in markdown HTML output return "\n<!--grid:%s-->" % ';'.join([str(cmd) for cmd in commands])
2e5d3c099a10dd6175e94c609b88fa211b3cbe0d
629,621
def apply_permutation(cm, perm): """ Apply permutation to a matrix. Examples -------- >>> cm = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> perm = np.array([2, 0, 1]) >>> apply_permutation(cm, perm) array([[8, 6, 7], [2, 0, 1], [5, 3, 4]]) """ return cm[perm].transpose()[perm].transpose()
6dc35a54da4970e86506e2215411957ebfcd1d6f
634,584
import logging def get_bucket_name_from_s3_event(event): """ Purpose: Get the S3 Bucket name from an event triggered by the creation of an object in S3 Args: event (Dict): Dict with event details from the triggering event for the function. Return: bucket_name (String): Bucket name of the object creation triggering the call to the Lambda function """ bucket_name =\ event.get("Records", {})[0].get("s3", {}).get("bucket", {}).get("name", None) if not bucket_name: error_msg = "Event did not have a bucket name; cannot process event" logging.error(error_msg) raise Exception(error_msg) return event.get("Records", {})[0].get("s3", {}).get("bucket", {}).get("name", None)
ce73ed2a67495240c2de1c667976b1a26d205f7d
393,854
import math def efficiency_integrand(x): """ The integrand in the efficiency equation. """ return x**3 / (math.exp(x) - 1)
747bd05dda8bfd547b1f53e11df20a889341cf38
233,949
from typing import Counter def percent_repeated_blocks(text: str, block_length: int = 16) -> float: """ Checks how many repeating blocks there are in the text, which is a indication/vulnerability of ECB encryption. :param text The text in question we are checking for encryption. :param block_length The length of each block to compare for repeats, defaults to 16-bit blocks. :return: A float which is the percent of blocks which repeat, a indication of ECB encryption. """ # break the string down into block_length sized blocks blocks = [text[i:i + block_length] for i in range(0, len(text), block_length)] counts = list(Counter(blocks).values()) repeats = 0 for i in range(0, len(counts)): if counts[i] > 1: repeats += counts[i] return repeats / len(blocks)
4ff0bb16ae03509e2b1e1360a16f13a4b4e53666
583,101
from typing import OrderedDict def order_dict(content, order): """Converts a dict into an OrderedDict Args: content (dict): The content to convert. order (Seq[str]): The field order. Returns: OrderedDict: The ordered content. Examples: >>> order_dict({'a': 1, 'b': 2}, ['a', 'b']) == OrderedDict( ... [('a', 1), ('b', 2)]) True """ get_order = {field: pos for pos, field in enumerate(order)} keyfunc = lambda x: get_order[x[0]] return OrderedDict(sorted(content.items(), key=keyfunc))
28df3c879a942e223ce963b58b1b1af8ca3372f4
326,980
def mean(feature_vector): """ :param feature_vector: List of integer/float/double.. :return: Mean of the feature vector. """ return sum(f for f in feature_vector)/len(feature_vector)
5ed9dfa0d54cc6fa2a882c32e52ba41be67ff3d3
109,911
def vertical_velocity_from_pass_diagnostics(diagnostic): """Method for handling a chain_pass diagnostic and outputting it's vertical velocity Shouldn't be calculated for pass chains of 1 pass vertical velocity = vertical distance / cumulative time """ vertical_distance = diagnostic[5] elapsed_time = diagnostic[9] pass_count = diagnostic[7] if pass_count > 1: return float(vertical_distance) / elapsed_time else: return None
8d9c0d49d9efd97870ad188c0ca8ad144a2ceb40
31,390
import pickle def load_pickle(filepath): """Load a pickle at the given filepath and return the contents. Args: filepath (str): The filepath to load. Returns: The unpickled object. """ with open(filepath, 'rb') as f: return pickle.load(f)
7b0b250c776fb8699c540d815e3593dd3f3ba77c
331,614
from typing import BinaryIO from typing import cast import struct def read_short(stream: BinaryIO) -> int: """Read a short integer value in big-endian order.""" return cast(int, struct.unpack('>h', stream.read(2))[0])
20eb8c6c91b08841039f235a872ad8261fffd2bd
363,350
import six def dslice(value, *args): """Returns a 'slice' of the given dictionary value containing only the requested keys. The keys can be requested in a variety of ways, as an arg list of keys, as a list of keys, or as a dict whose key(s) represent the source keys and whose corresponding values represent the resulting key(s) (enabling key rename), or any combination of the above.""" result = {} for arg in args: if isinstance(arg, dict): for k, v in six.iteritems(arg): if k in value: result[v] = value[k] elif isinstance(arg, list): for k in arg: if k in value: result[k] = value[k] else: if arg in value: result[arg] = value[arg] return result
ae4c76bc75d48881609a7398806f1b688f6c1587
398,004
def compose(func_a, func_b): """ Return a new function that is the composition of the first one with the second. """ return lambda x : func_a(func_b(x))
a2fee8e0f7bb499c1839abc9cc66fe806f1fcdda
194,110
def fields_from(dataline, cols): """ Given a data line and a set of column definitions, strip the data and return it as a list """ fields = [] for start, fin in cols: fields.append(dataline[start:fin].strip()) return fields
9b733969ad066914dcf82caeea285f277e6fdbc2
251,707
def calc_PV_power(absorbed_radiation_Wperm2, T_cell_C, eff_nom, tot_module_area_m2, Bref_perC, misc_losses): """ To calculate the power production of PV panels. :param absorbed_radiation_Wperm2: absorbed radiation [W/m2] :type absorbed_radiation_Wperm2: float :param T_cell_C: cell temperature [degree] :param eff_nom: nominal efficiency of PV module [-] :type eff_nom: float :param tot_module_area_m2: total PV module area [m2] :type tot_module_area_m2: float :param Bref_perC: cell maximum power temperature coefficient [degree C^(-1)] :type Bref_perC: float :param misc_losses: expected system loss [-] :type misc_losses: float :return el_output_PV_kW: Power production [kW] :rtype el_output_PV_kW: float ..[Osterwald, C. R., 1986] Osterwald, C. R. (1986). Translation of device performance measurements to reference conditions. Solar Cells, 18, 269-279. """ T_standard_C = 25.0 # temperature at the standard testing condition el_output_PV_kW = eff_nom * tot_module_area_m2 * absorbed_radiation_Wperm2 * \ (1 - Bref_perC * (T_cell_C - T_standard_C)) * (1 - misc_losses) / 1000 return el_output_PV_kW
31673aaf6d693fba150975841b3ae2717f7d0d5c
629,298
def tuple_min(t1, t2): """Return the entry-wise minimum of the two tuples""" return tuple(min(a, b) for a, b in zip(t1, t2))
7a5df2634c8cc0f477ec62b53452b39c561cb356
555,788
def generate_wild_card_by_date(date: str) -> str: """ Method to build a wildcard_date from a date string :param date: :return: """ return f"{date}*"
4d5e5824468e3556f8c0e29f9342a50a35ab270f
524,372
def cycle(iterable): """ Returns iterator with values which are in iterable object. cycle(['A', 'B', 'C']) -> A, B, C, A, B, C, ... cycle(['ABCA']) -> A, B, C, A, A, B, ... cycle(('C')) -> C, C, C, ... """ lenght = len(iterable) if lenght == 0: return iterable else: while True: for item in iterable: yield item
caf86eef922ed28b8accac7b5a560ecbd0f3d534
272,904
def get_durations(raw_data, get_duration, is_successful): """Retrieve the benchmark duration data from a list of records. :parameter raw_data: list of records :parameter get_duration: function that retrieves the duration data from a given record :parameter is_successful: function that returns True if the record contains a successful benchmark result, False otherwise :returns: list of float values corresponding to benchmark durations """ data = [get_duration(run) for run in raw_data if is_successful(run)] return data
b50ab9c3e2b9b9cbf82c2f745314ee683db30dab
322,621
def EnumNameToChoice(name): """Converts the name of an Enum value into a typeable choice.""" return name.replace('_', '-').lower()
0ee5074f6a97e71e5ac17e5181f7cc3d6119c237
474,508
def any(it, func=bool): """ 对iter中的每个元素调用func,任意一个为真则返回True,否则为False :param it: 可迭代对象 :param func: callable :return: True if any func(i) is true ,otherwise false """ for i in it: if func(i): return True return False
3b79130c525133d387beb7d946190ac864182449
539,839
import re def filter_remove_device_sw_log_prefix(line): """ Remove the file/line information in log messages produced by device software LOG() macros. """ # See base_log_internal_core() in lib/base/log.c for the format description. pattern = r'^[IWEF?]\d{5} [a-zA-Z0-9\.-_]+:\d+\] ' if isinstance(line, bytes): return re.sub(bytes(pattern, encoding='utf-8'), b'', line) else: return re.sub(pattern, '', line)
c69ce2ecc96370dd1c55ce47cb38ce59aa759a11
52,060
from typing import Any def check_type(o: Any, target_type: str) -> bool: """ Check if `o`'s class path + name matches `target_type`. E.g. `check_type(o, "numpy.ndarray")` Checking types using this method instead of `isinstance` with the actual type is preferred here so that we don't have to import pytorch, PIL, and numpy (and complicate the code by handling import errors if any of these are missing, importing comet-ml before pytorch, etc.). """ return str(type(o)) == f"<class '{target_type}'>"
cf96d05d720d6e057a6eb3b46b96ce213d463d65
596,924
def _calc_overlap(geom1, geom2): """Return area overlap""" return geom1.intersection(geom2).area
13183e0f20dd441425b55793d667a0f7ff73ac59
615,995
import glob def get_roi_zip_list(path): """ Returns a list of files ending in *.zip in provided folder :param: path :return: list -- filenames """ path += '/*.zip' return glob.glob(path)
af5249d936709d11f57a72cac582ce3664764128
162,330
from typing import Dict from typing import Any def flatten(data: dict, prefix: str = "") -> Dict[str, Any]: """ Recursively flatten a dict into the representation used in Moodle/PHP. >>> flatten({"courseids": [1, 2, 3]}) {'courseids[0]': 1, 'courseids[1]': 2, 'courseids[2]': 3} >>> flatten({"grades": [{"userid": 1, "grade": 1}]}) {'grades[0][userid]': 1, 'grades[0][grade]': 1} >>> flatten({}) {} """ formatted_data = {} for key, value in data.items(): new_key = f"{prefix}[{key}]" if prefix else key if isinstance(value, dict): formatted_data.update(flatten(value, prefix=new_key)) elif isinstance(value, list): formatted_data.update(flatten(dict(enumerate(value)), prefix=new_key)) else: formatted_data[new_key] = value return formatted_data
a2b0439de0a2505d8940e1d8d55b750275023afa
121,275
def convert_c_to_f(temp_c): """Converts temp (C) to temp (F).""" try: temp_f = (temp_c * 1.8) + 32 temp_f = round(temp_f, 2) except TypeError: temp_f = False return temp_f
88b08f89c5d674a0220390aff91faa3db2e7e0be
83,183
import re def strip_wiki_comment(src): """ Strip wiki comment like [1], [편집] to get clean text Args: src: String to strip Return: Text that escaped wiki comment """ return re.sub(r"(\[.+\])", '', src)
d34f34f5e1cd182e9fd2f1c432e93f8328274787
409,919
from typing import Iterable import itertools def primed(iterable: Iterable): """Preprimes an iterator so the first value is calculated immediately but not returned until the first iteration """ itr = iter(iterable) try: first = next(itr) # itr.next() in Python 2 except StopIteration: return itr return itertools.chain([first], itr)
73123976f40cc7331be5988c9c71cadd8f031b65
461,997
from typing import Union def _calc_n_kwargs(args: list[str]) -> Union[str, int]: """ Here we try to calculate the nargs for **kwargs arguments. Basically we are starting from the end until not encountering the "=" sign in the provided argument. Example: <CLI> <feature> <command> [arguments: pos[bst labs] *args[lib1 lib2] **kwargs[name1=lib1 name2=lib2]] :param args: the list of arguments from the argparse :return: nargs for argparse add_argument() """ n_kwargs = 0 for n_kwargs in range(0, -len(args), -1): if "=" not in args[n_kwargs - 1]: break return -n_kwargs or "*"
60bd2c0ad1b43ea6818252ed82334a41aa06795f
429,622
def _get_top_values_categorical(series, num_x): """Get the most frequent values in a pandas Series. Will exclude null values. Args: column (pd.Series): data to use find most frequent values num_x (int): the number of top values to retrieve Returns: top_list (list(dict)): a list of dictionary with keys `value` and `count`. Output is sorted in descending order based on the value counts. """ frequencies = series.value_counts(dropna=True) df = frequencies.head(num_x).reset_index() df.columns = ["value", "count"] df = df.sort_values(["count", "value"], ascending=[False, True]) value_counts = list(df.to_dict(orient="index").values()) return value_counts
d3ea35ba6ee60536a56bbfc07cfae3633f26b138
43,810
from typing import Tuple def distance(point_a: Tuple[int, int], point_b: Tuple[int, int], m: int) -> float: """Generalized distance between two points Note: See more info here: https://xlinux.nist.gov/dads/HTML/lmdistance.html Args: - point_a (Tuple[int, int]): a coordinate pair - point_b (Tuple[int, int]): a coordinate pair - m (int): the type of distance to calculate between the points Can only take three values: 1 -> manhattan 2 -> euclidean More than 2 -> minkowski Result: float: the distance between the two points """ abs_diff_x_exp_m = abs(point_a[0] - point_b[0]) ** m abs_diff_y_exp_m = abs(point_a[1] - point_b[1]) ** m sum_dif = abs_diff_x_exp_m + abs_diff_y_exp_m distance = sum_dif ** (1 / m) return distance
f73fb9045a94dfe745f29bae7a30891f34221791
576,748
def overlap(range1, range2): """ Checks whether two ranges (f.e. character offsets overlap) This snippet by Steven D'Aprano is from the forum of www.thescripts.com. Keyword arguments: range1 -- a tuple where range1[0] <= range1[1] range1 -- a tuple where range2[0] <= range2[1] Returns: True (ranges overlap) or False (no overlap) """ assert(range1[0] <= range1[1]) assert(range2[0] <= range2[1]) # Fully overlapping cases: # x1 <= y1 <= y2 <= x2 # y1 <= x1 <= x2 <= y2 # Partially overlapping cases: # x1 <= y1 <= x2 <= y2 # y1 <= x1 <= y2 <= x2 # Non-overlapping cases: # x1 <= x2 < y1 <= y2 # y1 <= y2 < x1 <= x2 return not (range1[1] < range2[0] or range2[1] < range1[0])
c8871689127cc6944e84788179efe98bb454de28
367,215
def match_substrings(text, items, getstr=None, cmp=None, unmatched=False): """ Matches each item from the items sequence with sum substring of the text in a greedy fashion. An item is either already a string or getstr is used to retrieve a string from it. The text and substrings are normally compared with normal string equality but cmp can be replaced with a two-argument function that does the comparison instead. This function expects that all items are present in the text, in their order and without overlapping! If this is not the case, an exception is raised. Args: text: the text to use for matching items: items that are or contains substrings to match getstr: a function that retrieves the text from an item (Default value = None) cmp: a function that compares to strings and returns a boolean \ that indicates if they should be considered to be equal. (Default value = None) unmatched: if true returns two lists of tuples, where the second list\ contains the offsets of text not matched by the items (Default value = False) Returns: a list of tuples (start, end, item) where start and end are the\ start and end offsets of a substring in the text and item is the item for that substring. """ if getstr is None: getstr = lambda x: x if cmp is None: cmp = lambda x, y: x == y ltxt = len(text) ret = [] ret2 = [] item_idx = 0 start = 0 lastunmatched = 0 while start < ltxt: itemorig = items[item_idx] item = getstr(itemorig) end = start + len(item) if end > ltxt: raise Exception("Text too short to match next item: {}".format(item)) if cmp(text[start:end], item): if unmatched and start > lastunmatched: ret2.append((lastunmatched, start)) lastunmatched = start + len(item) ret.append((start, end, itemorig)) start += len(item) item_idx += 1 if item_idx == len(items): break else: start += 1 if item_idx != len(items): raise Exception( "Not all items matched but {} of {}".format(item_idx, len(items)) ) if unmatched and lastunmatched != ltxt: ret2.append((lastunmatched, ltxt)) if unmatched: return ret, ret2 else: return ret
9413ed626d87d796be001d75403f950073b63a4b
535,109
import base64 def gen_basic_auth(username, password): """ Generates a basic auth header. """ encoded_username = username.encode("utf-8") encoded_password = password.encode("utf-8") return "Basic " + base64.b64encode(b"%s:%s" % (encoded_username, encoded_password)).decode( "ascii" )
12471f7383546346b45ea46f19ae0e216ee7c521
131,100
from typing import Optional import torch def batch_eye( eye_dim: int, batch_size: int, device: Optional[torch.device] = None ) -> torch.Tensor: """Create a batch of identity matrices. Parameters ---------- eye_dim : int Desired eye dimension. batch_size : int Desired batch dimension. device : Optional[torch.device], default=None The device. Returns ------- torch.Tensor, shape=(batch_size, eye_dim, eye_dim) Batched eye. """ if device is None: eye = torch.eye(eye_dim).unsqueeze(0) # shape=(1, eye_dim, eye_dim) else: eye = torch.eye(eye_dim, device=device).unsqueeze(0) return eye.expand([batch_size, eye_dim, eye_dim])
d1542fcc9a24a5a0306552cf47019891a26634e8
574,914
def get_gamma_distribution_params(mean, std): """Turn mean and std of Gamma distribution into parameters k and theta.""" # mean = k * theta # var = std**2 = k * theta**2 theta = std**2 / mean k = mean / theta return k, theta
49b5ccdf7b83c949b81ad05e6d351cfb0b1f4d26
666,361
def hex_to_bin(txt: str) -> str: """Convert hexadecimal string to binary string.Useful for preprocessing the key and plaintext in different settings.""" return bin(int(txt,16))[2:]
beffae4a0eb8bda8a56e0a23fb9aefcdbd41dd37
683,643
from typing import Dict import aiohttp async def head(url: str) -> Dict: """Fetch headers returned http GET request. :param str url: The URL to perform the GET request for. :rtype: dict :returns: dictionary of lowercase headers """ async with aiohttp.request("HEAD", url) as res: response_headers = res.headers return {k.lower(): v for k, v in response_headers.items()}
b4decbfb4e92863c07c5202e2c884c02e590943f
2,629
import requests def extra_metadata_helper(json_content, repo_name, header): """ Build extra metadata dict to help with other integrations. Parameters ---------- json_content: dict Information about the GitHub repo repo_name: str The name of this GitHub repository header: dict GitHub Authorization header Returns ------- Extra metadata dictionary """ # Build up extra metadata name_helper = requests.get(json_content['owner']['url'], headers=header) first_name = None last_name = None if name_helper.status_code == 200: try: name = name_helper.json()['name'].partition(' ') first_name = name[0] last_name = name[2] except AttributeError: pass try: license = json_content['license']['name'] except TypeError: license = None extra_metadata = { "title": repo_name, "creators": [ { "first_name": first_name, "last_name": last_name, "ORCID": None } ], "publication_date": json_content['created_at'], "description": json_content['description'], "keywords": json_content['topics'], "license": license, "related_identifiers": [], "references": None, "notes": None } return extra_metadata
51fb0fa1035827f4d93ccbc461e1938a92569264
364,470
def parse_scripts(scp_path, value_processor=lambda x: x, num_tokens=2): """ Parse kaldi's script(.scp) file If num_tokens >= 2, function will check token number """ scp_dict = dict() line = 0 with open(scp_path, "r") as f: for raw_line in f: scp_tokens = raw_line.strip().split() line += 1 if num_tokens >= 2 and len(scp_tokens) != num_tokens or len(scp_tokens) < 2: raise RuntimeError( "For {}, format error in line[{:d}]: {}".format( scp_path, line, raw_line ) ) if num_tokens == 2: key, value = scp_tokens else: key, value = scp_tokens[0], scp_tokens[1:] if key in scp_dict: raise ValueError( "Duplicated key '{0}' exists in {1}".format(key, scp_path) ) scp_dict[key] = value_processor(value) return scp_dict
db22596c8639c2e7d81d3fe749fc235a6281d0c3
678,534
def clean_games_stats(game_details_ele, picture_link, url): """ This module contains functions for cleaning data, it is called by BGA_scraper when run. Keyword arguements: ------------------- game_details - game info to be cleaned, string picture_link - url to game image, passed on without cleaning url - url to game page, passed on without cleaning Returns: -------- players - number of players required playtime_cleaned - aproximate playtime in minutes complexity - game complexity ranked from 1 (lowest) to 5 (highest) picture_link - url for the game image, to be downloaded later url - url to game page, for reference """ game_details = game_details_ele.text game_details = game_details.split('\n') game_details = game_details[1] players = game_details[0:5] playtime = game_details[8:12] playtime_cleaned = playtime.split() playtime_cleaned = playtime_cleaned[0] complexity = game_details[-5:] # add to dictionary in BGA_scraper return [players, playtime_cleaned, complexity, picture_link, url]
86833c6bea183cb00d2d7c7815e28e7735aec766
480,659
def row_format_resource(*fields): """Transform a variable number of fields to a `table-row` format. ``` >>> row_format_resource(a,b,c,d) '| a | b | c | d |' ``` :param fields: fields to be converted to row. """ return ('| {} ' * len(fields)).format(*fields) + '|\n'
bab8eec97396ba8021ce85e9a57d766a6de630ef
624,250
def bmi_to_bodytype(bmi): """ desc : converts bmi to a category body type based on CDC guidelines https://www.cdc.gov/healthyweight/assessing/bmi/adult_bmi/index.html args: bmi (float) : the users bmi returns: bodytype (string) : The users bodytype """ if bmi < 18.5: return "Underweight" elif 18.5 <= bmi < 24.9: return "Normal" elif 24.9 <= bmi < 29.9: return "Overweight" else: return "Obese"
24ff38d0b010df0b0fb0ee5c89fa071e4db2e0d9
474,490
def get_split_ratio(df): """ This function returns a copy of a data frame with a new column for split ratios. :param dataframe df: contains split times for individual runners :return dataframe df_new: a copy of the passed data frame which contains one new column; the split ratio comparing the second half of each individual's marathon to the first half. """ df_new = df.copy() df_new["split_ratio"] = (df_new["official_time"] - df_new["half"]) / ( df_new["half"] ) return df_new
097464e980f19b85939360c90bf62fc88d6ba002
134,017
import pwd def uid_to_name(uid): """ Find the username associated with a user ID. :param uid: The user ID (an integer). :returns: The username (a string) or :data:`None` if :func:`pwd.getpwuid()` fails to locate a user for the given ID. """ try: return pwd.getpwuid(uid).pw_name except Exception: return None
f9054e4959a385d34c18d88704d376fb4b718e47
6,022
def _fingerprint(row): """Generate a string-based fingerprint to characterize row diversity.""" return ''.join(map(lambda x: str(type(x)), row))
0ea349cd89e2f08e908c06fadb4c9509481b7cc1
213,689
def create_filename(last_element): """ For a given file, returns its name without the extension. :param last_element: str, file name :return: str, file name without extension """ return last_element[:-4]
3faaf647ed6e3c765321efb396b2806e7ef9ddf9
8,050
def convert_to_d_h_m_s(days): """Return the tuple of days, hours, minutes and seconds from days (float)""" days, fraction = divmod(days, 1) hours, fraction = divmod(fraction * 24, 1) minutes, fraction = divmod(fraction * 60, 1) seconds = fraction * 60 return int(days), int(hours), int(minutes), int(seconds)
f7457043788559689100441cc0b2099ee04c8993
497,154
def extension(filename): """ returns the extension when given a filename will return None if there is no extension >>> extension('foo.bar') 'bar' >>> extension('foo') None """ s = filename.split('.') if len(s) > 1: return s[-1] else: return None
5634effc420299a66dd71985eb49cbbf98714622
586,575
def max_consecutive_sum(array): """ given an array of numbers (positive, negative, or 0) return the maximum sum of consecutive numbers """ max_value = max(array) running_sum = 0 for num in array: if running_sum < 0: running_sum = 0 running_sum += num if running_sum > max_value: max_value = running_sum return max_value
32e7322f8936f8399ec2ebe0702dbb10332cb529
699,640
def cauchy(x0, gx, x): """1-D Cauchy. See http://en.wikipedia.org/wiki/Cauchy_distribution""" #return INVPI * gx/((x-x0)**2+gx**2) gx2 = gx * gx return gx2 / ((x-x0)**2 + gx2)
ed76e0683c68642fc3c4a81754df2eb38344237b
121,353
def _correct_searchqa_score(x, dataset): """Method to correct for deleted datapoints in the sets. Args: x: number to correct dataset: string that identifies the correction to make Returns: The rescaled score x. Raises: ValueError: if dataset is none of train, dev, test. """ if dataset == 'train': return x * 90843 / (90843 + 8977) elif dataset == 'dev': return x * 12635 / (12635 + 1258) elif dataset == 'test': return x * 24660 / (24660 + 2588) else: raise ValueError('Unexepected value for dataset: {}'.format(dataset))
d92b992f98116d069456d7a9f34b2a95d93b5880
104,986
from typing import Tuple def get_two_first_items(t: Tuple) -> Tuple: """Return (first, second) item of tuple as tuple.""" return (t[0], t[1])
cdc3d474f9dbbf2271a0617977140f6f995e7f90
484,191
def match_relationships(package_archive, relationship_sets): """ Validate that `package_archive` DebArchive satisfies all the relationships of a `relationship_sets`. Return True if valid and False otherwise. """ archive_matches = None for relationships in relationship_sets: status = relationships.matches(package_archive.name, package_archive.version) if status is True and archive_matches is not False: archive_matches = True elif status is False: # This package archive specifically conflicts with (at least) one # of the given relationship sets. archive_matches = False # Short circuit the evaluation of further relationship sets because # we've already found our answer. break return archive_matches
f738fd9ce78f56f7f5931264dd32ada86f2aa442
589,475
from bs4 import BeautifulSoup def info_from_html(html, name_selector, author_selector): """Return a tuple with song's name and author from a page. name_selector -> css selector for song's name author_selector -> css selector for author's name """ soup = BeautifulSoup(html, 'html.parser') name = soup.select(name_selector)[0] author = soup.select(author_selector)[0] return (name.get_text().strip(), author.get_text().strip())
06eeafa40418730a98d25a28b65740b25e1f17e0
68,395
def _expand_global_features(B, T, g, bct=True): """Expand global conditioning features to all time steps Args: B (int): Batch size. T (int): Time length. g (Variable): Global features, (B x C) or (B x C x 1). bct (bool) : returns (B x C x T) if True, otherwise (B x T x C) Returns: Variable: B x C x T or B x T x C or None """ if g is None: return None g = g.unsqueeze(-1) if g.dim() == 2 else g if bct: g_bct = g.expand(B, -1, T) return g_bct.contiguous() else: g_btc = g.expand(B, -1, T).transpose(1, 2) return g_btc.contiguous()
868e7c652e2b4aebc9d0a55ee908068b49639ef7
189,795
def is_valid_matrix(mtx): """ >>> is_valid_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) True >>> is_valid_matrix([[1, 2, 3], [4, 5], [7, 8, 9]]) False """ if mtx == []: return False cols = len(mtx[0]) for col in mtx: if len(col) != cols: return False return True
2e57455155cca8f37f738ef5ca7444ec118f1f6a
663,151
def sum_payout(cost_matrix, confusion_matrix): """ Calculate the profit from cost and confusion matrices. """ return (confusion_matrix * cost_matrix).sum()
8b1b0fe44a283582625ad2cdee91411b59cfb105
645,854
def get_species_label(entry): """Get the species name of an assembly summary entry.""" parts = entry['organism_name'].split(' ') if len(parts) < 2: return 'sp.' return parts[1]
b4e059d2f40e89351b9749bacea95909e8524873
613,430
def choose_weapon(decision, weapons): """Chooses a weapon from a given list based on the decision.""" choice = [] for i in range(len(weapons)): if i < decision: choice = weapons[i] return choice
86e6272022a45603525e06a732748cf7275337b8
86,978
def extract_from_dictionary(ls_of_dictionaries, key_name): """ Iterates through a list of dictionaries and, based on the inserted key name, extracts that data. :param: ls_of_dictionaries: a list of dictionaries :param: key_name: a string with ('') that indexes which set of the dictionary you want to extract :returns: list with the specified (keyed) datatype """ #index = [] partic_name = [] data_element = [] for index, dictionary in enumerate(ls_of_dictionaries): data = dictionary[key_name] partic_name = dictionary['partic_number'] data_element.append(data) return(data_element)
1bdc41a61a21d2cc1903440be7720300ea12ed46
460,921
def validate_connections(nodes, connections): """Ensure all connections actually connect to a node that has been provided.""" # nodes may have multiple connections to the same node #(this is to allow for data centers/smaller servers) if not connections or not nodes: return if len(nodes) < len(connections) - 1: # There can't be no nodes then connections less 1 raise IndexError names = [node.address for node in nodes] for connection_obj in connections: if (connection_obj.start_node.address == connection_obj.end_node.address or connection_obj.start_node.address not in names or connection_obj.end_node.address not in names): raise AttributeError # addressError return True
91f15cbcc8ef87d2585f6c5951a23cef3a267e92
466,878
def get_stats(stat_int_list: list) -> list: """Return a list of stats in play. Argument(s): stat_int_list: list -- list of stat indices """ stat_list = [] for stat in stat_int_list: if stat == 0: stat_list.append("Hunger") elif stat == 1: stat_list.append("Thirst") elif stat == 2: stat_list.append("Energy") elif stat == 3: stat_list.append("Fitness") elif stat == 4: stat_list.append("Mental Health") return stat_list
22d36dcd5cb7736c1591e635ad49650c2e51fcc5
652,039
def _parse_requirements_file(filename): """Parses a requirements.txt file into a list of requirement strings.""" reqs = [] with open(filename, "r") as f: for line in f.read().splitlines(): line = line.strip() if line.startswith("#"): continue if not line: continue reqs.append(line) return reqs
040feefaaf087746a55ee2a531dcec992fa5f633
516,959
def flatten(lst): """Flattens a list of lists""" return [subelem for elem in lst for subelem in elem]
34b3c041a0d6bd6cb46bf15b218ac29be1fba566
112,190
import re def matchline(line): """ >>> matchline("{{teet}}") 'teet' >>> matchline("teet") """ rg = re.compile("{{(\S*)}}") m = rg.match(line.strip()) if m: return m.group(1) else: return
7db884f164197213497b27050dacd0ff90c1b29e
77,305
def heaviside(x, bias=0): """ Heaviside function Theta(x - bias) returns 1 if x >= bias else 0 :param x: :param bias: :return: """ indicator = 1 if x >= bias else 0 return indicator
b325a862cbc2cac97b8e4808c6d77b54a0f1d643
700,057
import base64 import gzip import json def uncompress_payload(cw_event: dict) -> dict: """Uncompresses a Cloudwatch log event and turns it into a dict. Args: cw_event: Dict containing base64 encoded and zipped logs entry delivered by Cloudwatch Logs subscription Returns: (dict): uncompressed logs data """ cw_data = cw_event["awslogs"]["data"] compressed_payload = base64.b64decode(cw_data) uncompressed_payload = gzip.decompress(compressed_payload) return json.loads(uncompressed_payload)
bc2b9a69cfce7bfa8e6630b001df53104440cd6e
603,964
import copy def deep_merge_dict(base, custom, dict_path=""): """Intended to merge dictionaries created from JSON.load(). We try to preserve the structure of base, while merging custom to base. The rule for merging is: - if custom[key] exists but base[key] doesn't, append to base[key] - if BOTH custom[key] and base[key] exist, but their type is different, raise TypeError - if BOTH custom[key] and base[key] exist, but their type is same ... - if both are dictionary, merge recursively - else use custom[key] """ for k in custom.keys(): if k not in base.keys(): # entry in custom but not base, append it base[k] = custom[k] else: dict_path += "[{}]".format(k) if type(base[k]) != type( custom[k] ): # noqa - intended, we check for same type raise TypeError( "Different type of data found on merging key{}".format(dict_path) ) else: # Have same key and same type of data # Do recursive merge for dictionary if isinstance(custom[k], dict): base[k] = deep_merge_dict(base[k], custom[k], dict_path) else: base[k] = custom[k] return copy.deepcopy(base)
2f6461e35ef48937500e7148ee2180865844914a
429,159
def _is_logging_required(example_index, number_of_examples): """Returns True only if logging is required. Logging is performed after 10%, 20%, ... 100% percents of examples is processed. """ return (example_index + 1) % max(1, number_of_examples // 10) == 0
de48fe770f79e3f4f5f92f9a87e2b65b907656a2
453,518
def write_manningsn(fid, node, value): """ Write out a formated node value line to fid :type fid: :class:`file` :param fid: the file object to be written to :type node: int :param node: the node number :type value: float :param value: the nodal value :rtype: string :return: formatted string for a line in a ``fort.13`` formatted file """ return fid.write('{:<8d} {:17.15g}\n'.format(int(node), value))
2bae14a7dbd5c906a830384527d12931609cdca0
160,430
def __make_renderer(env, variables): """Returns a function that takes some text and creates and renders a template from it using *env* and *variables* """ def renderer(text): template = env.from_string(text) return template.render(**variables) return renderer
2f8553d3c7a22583e36f88abdd528cb422bf6eb2
234,882
def agent(request): """ A context processor that sets the template context variable ``agent`` to the value of ``request.agent``. """ return {'agent': getattr(request, 'agent', None)}
fd2bf218db173101f63762f3c3fc862108073cbd
270,613
def get_number_of_unique_values_series(series): """ Return number of unique values of Pandas series Parameters ---------- series: (Numeric) Pandas series Returns ------- Number of unique values of series """ return series.unique().shape[0]
5de75f35d95b7212b51eb233145327f477c9852d
357,470
def hash_qlinef(line): """ a hash function for QLineF, Args: line (QLineF) the line Returns: hash of tuple formed from end point coordinates (x1, x2, y1, y2) """ coords = (line.x1(), line.x2(), line.y1(), line.y2()) return hash(coords)
050cc88335a15129e3f721b694a2001e154f8114
509,582
import jinja2 import yaml def parse(filename): """Parse a configuration file. Parameters ---------- filename : str The config file to parse. Should be YAML formatted. Returns ------- config: dict The raw config file as a dictionary. """ with open(filename, "r") as fp: config_str = jinja2.Template(fp.read()).render() config = yaml.load(config_str, Loader=yaml.Loader) return config
055bcca59e2c9d3adad2ca9bdc527fc849ef2290
16,822
import json def message_to_json(message): """ This function tranforms the string message to a json string, this is to make all REST responses to be in JSON format and easier to implement in a consistent way. """ #if message is alreay in json then do not do anything mesage_dict = {} try: message_dict = json.loads(message) except ValueError: message_dict = { "msg": message } return json.dumps(message_dict)
bf20d028068d2716c5b40807e6b17a6ffb8b1073
39,249
def _get_pad_size(in_size, dilated_kernel_size, stride_size): """Calculate the paddings size for Conv/Pool in SAME padding mode.""" if stride_size == 1 or in_size % stride_size == 0: pad = max(dilated_kernel_size - stride_size, 0) else: pad = max(dilated_kernel_size - (in_size % stride_size), 0) pad_before = pad // 2 pad_after = pad - pad_before return [pad_before, pad_after]
94681f94f653749ef6192491398545c11f0ba3b5
275,210
def compare_values(values0, values1): """Compares all the values of a single registry key.""" values0 = {v[0]: v[1:] for v in values0} values1 = {v[0]: v[1:] for v in values1} created = [(k, v[0], v[1]) for k, v in values1.items() if k not in values0] deleted = [(k, v[0], v[1]) for k, v in values0.items() if k not in values1] modified = [(k, v[0], v[1]) for k, v in values0.items() if v != values1.get(k, None)] return created, deleted, modified
f16a299ae3ac989bca6d2c6b0d93f9a526b4a74d
252,458
def _jax_type(dtype, weak_type): """Return the jax type for a dtype and weak type.""" return type(dtype.type(0).item()) if (weak_type and dtype != bool) else dtype
44efbfdf00aff48d5535aad79b207dde956f59f6
193,805
def rating_label(rating, cfg): """Convert a credibility rating into a label :param rating: a credibility rating. We assume it has `reviewAspect == credibility` and float `confidence` and `ratingValue`s :param cfg: configuration options :returns: a short string to summarise the credibility rating :rtype: str """ if 'reviewAspect' in rating: assert rating['reviewAspect'] == 'credibility', '%s' % (rating) conf_threshold = float(cfg.get('cred_conf_threshold', 0.7)) if 'confidence' in rating and rating['confidence'] < conf_threshold: return 'not verifiable' assert 'ratingValue' in rating, '%s' % (rating) val = rating['ratingValue'] assert val <= 1.0 and val >= -1.0, '%s' % (rating) if val >= 0.5: return 'credible' if val >= 0.25: return 'mostly credible' if val >= -0.25: return 'uncertain' if val >= -0.5: return 'mostly not credible' return 'not credible'
80fb93416e3be227153ba1db078178fddd99fb89
499,880
import re def clean_whitespace(text: str) -> str: """ Replace all contiguous whitespace with single space character, strip leading and trailing whitespace. """ text = str(text or '') stripped = text.strip() sub = re.sub(r'\s+', ' ', stripped, ) return sub
1744f4ea82dfc538b2e095e66a2260368c5c09ac
63,322
def moment_from_muad(mu, A, d): """moment = mu * A * d :param mu: shear modulus, in Pa :type mu: float :param A: area, in m^2 :type A: float :param d: slip, in m :type d: float :returns: moment, in Newton-meters :rtype: float """ return mu*A*d;
c2ff5a654165d5ede686d41b66e930751552e11d
178,158
from urllib.parse import urlparse def check_pdf(download_url: str) -> bool: """Check if the download_url is a PDF or not by reading the extension.""" result = urlparse(download_url) return result.path[-3:] == 'pdf'
9754d14f0c04edf05c4618a5934fa84dc006af71
158,913
def get_frequency(every): """Get frequency value from one every type value: >>> get_frequency('3.day') 3 :param every: One every type value. """ return int(every[:every.find('.')])
713916a264bd4172f02b0996121d50830f0f3ce4
181,858
def sig(nTermAnte, coef) : """Devolve '+' se coef não é negativo e existe termo anterior ao termo dele no polinômio. Devolve '' (string vazia) no caso contrário. Usado para determinar se o '+' deve aparecer antes de coef na string que representa o polinômio. nTermAnte -- expoente de x no termo anterior ao termo do coef coef -- coeficiente de um termo do polinômio """ if nTermAnte > 0 and coef >= 0 : return "+" else : return ""
640a0e9f1300f4eb4e4a5c11e2f9ee653846da54
165,331
import socket import struct def decode_hosts_ports(peers_raw): """Decode a compact byte string of hosts and ports into a list of tuples. Peers_raw's length must be a multiple of 6.""" if len(peers_raw) % 6 != 0: raise ValueError('size of byte_string host/port pairs must be' 'a multiple of 6') peers = (peers_raw[i:i+6] for i in range(0, len(peers_raw), 6)) hosts_ports = [(socket.inet_ntoa(peer[0:4]), struct.unpack('!H', peer[4:6])[0]) for peer in peers] return hosts_ports
2d8c1406fd0be8d2b43e206c4a4a421357b7f0dc
237,087
def _get_metadata_map_from_client_details(client_call_details): """Get metadata key->value map from client_call_details""" metadata = {metadatum[0]: metadatum[1] for metadatum in (client_call_details.metadata or [])} return metadata
1d0b843b41f2777685dad13b9269410033086b02
21,571
def _cliname_to_modname(parser_cli_name): """Return real module name (dashes converted to underscores)""" return parser_cli_name.replace('--', '').replace('-', '_')
91f5c750984b3a53bee51fe3752627ae3234b162
317,822
def clean(elems): """ This method takes a list of scraped selenium web elements and filters/ returns only the hrefs leading to publications. """ urls = [] for elem in elems: url = elem.get_attribute("href") if 'article' in url and 'pdf' not in url\ and 'search' not in url\ and 'show=' not in url: urls.append(url) return urls
8703797a615c8662def5cea40c7805c51694da75
542,126
def get_required_kwonly_args(argspecs): """Determines whether given argspecs implies required keywords-only args and returns them as a list. Returns empty list if no such args exist. """ try: kwonly = argspecs.kwonlyargs if argspecs.kwonlydefaults is None: return kwonly res = [] for name in kwonly: if not name in argspecs.kwonlydefaults: res.append(name) return res except AttributeError: return []
35f06e45e7f686e64db9ab39a66a025f5a4512c2
299,595
def DistanceFromMatrix(matrix): """Returns function(i,j) that looks up matrix[i][j]. Useful for maintaining flexibility about whether a function is computed or looked up. Matrix can be a 2D dict (arbitrary keys) or list (integer keys). """ def result(i, j): return matrix[i][j] return result
f3cb95aace0cfe70bfeef9d8778947df16cdd4b1
698,249
from typing import Counter def glass_catalog_stats(glass_list, do_print=False): """Decode all of the glass names in glass_cat_name. Print out the original glass names and the decoded version side by side. Args: glass_list: ((group, num), prefix, suffix), glass_name, glass_cat_name do_print (bool): if True, print the glass name and the decoded version Returns: groups (dict): all catalog groups group_num (dict): all glasses with multiple variants prefixes (dict): all the non-null prefixes used suffixes (dict): all the non-null suffixes used """ groups = Counter() group_nums = Counter() prefixes = Counter() suffixes = Counter() for g in glass_list: (group_num, prefix, suffix), gn, gc = g group, num = group_num if prefix != '': prefixes[prefix] += 1 if suffix != '': suffixes[suffix] += 1 groups[group] += 1 group_nums[group_num] += 1 if do_print: fmt_3 = "{:14s} {:>2s} {:8s} {:12s}" print(fmt_3.format(gn, prefix, group+num, suffix)) # filter group_nums to include only multi-use items group_nums = {k: v for k, v in group_nums.items() if v > 1} return groups, group_nums, prefixes, suffixes
7f139179eb8c531e41bd5d6a36ab6751be397a97
174,786