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: ...
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 """ ...
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...
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 ...
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[...
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_nam...
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 ...
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}...
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[...
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 va...
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 [degr...
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: ...
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: fu...
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 isi...
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 impo...
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({"grad...
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 StopIteratio...
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[bs...
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 ...
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 ...
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] ...
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 compare...
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 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 re...
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: d...
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()....
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 c...
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...
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: ...
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 se...
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)....
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(seco...
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 ru...
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 == ...
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 = rela...
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') nam...
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) R...
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 r...
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 ex...
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) < le...
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.appen...
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....
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)...
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 cu...
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: form...
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") a...
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 = {...
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...
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....
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 r...
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 n...
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' ...
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\ an...
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 ...
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] retu...
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_pri...
7f139179eb8c531e41bd5d6a36ab6751be397a97
174,786