content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def split(line, types=None, delimiter=None): """ Splite a line of text and optionally performs type conversion. By default, splitting is performed on whitespace, but a different delimiter can be selected with delimiter keyword argument. For example:接下来的才是最重要的! >>> split('GOO...
5c85fb8470882d93131dba2adc86b179d5e6000f
599,930
def get_count(input_str: str) -> int: """Count vowel from input string. Args: input_str: <str> inout string. Returns: <int> total amount of vowels. Examples: >>> assert get_count('abracadabra') == 5 """ return sum(map(lambda letter: letter in 'aeiou', input_str))
d925d652b8d394472d266f965950ab2d7cd23662
599,939
def create_upload_form_attributes(prefix, input_type, name): """Creates attribute dicts for the switchable upload form :type prefix: str :param prefix: prefix (environment, template) of field :type input_type: str :param input_type: field type (file, raw, url) :type name: str :param name: t...
bade2cdd07c89ebdab14fda9875fb2ccf5f5fb67
599,940
def is_value_name_applicable(buckets_names, value_name): """ Returns True if the given value name is AltFS applicable. Otherwise, returns False """ return value_name[:-5] in buckets_names and value_name[-5] == "." and \ all([char.isdigit() for char in value_name[-4:]])
bb36cccd77089af144164bf745ca580cf91e26c5
599,951
def params_and_context(context, arg): """Expected params_and_context __doc__""" return "params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)
4e909667c6b27d0ad24dff21e7f2dc98d8687af6
599,955
def token(get): """Wrapper to quickly retrieve a token.""" return get('/', query_string={'a': 'token'}).data.decode('UTF-8')
a6826d44fb46550119dcb9813d0393b1a5df78ab
599,959
import requests def get_url(url): """Downloads the content from a URL and gives us a string""" response = requests.get(url) content = response.content.decode("utf8") return content
45792daaf3a7c4e903d354e77055887229f34cca
599,960
def markov_forward(p0, A): """Calculate the forward predictive distribution in a discrete Markov chain Args: p0 (numpy vector): a discrete probability vector A (numpy matrix): the transition matrix, A[i,j] means the prob. to switch FROM i TO j Returns: p1 (numpy vector): the predictive probabili...
c4bb47422833055a9f6683917a17d868850e0b52
599,963
def _coalesce(*values): """ Return first non-none value. Return None if all values are None, or there are no values passed in. >>> _coalesce(1, 2) 1 >>> _coalesce(None, 2, 3) 2 >>> _coalesce(None, None, 3, None, 5) 3 """ for v in values: if v is not None: ...
9069cb40957afcd6a39edfb5a896d3d8da3e7a2a
599,966
def is_valid_int(num): """Check if input is valid integer""" try: int(num) return True except ValueError: return False
e8c0360e5973358ac788ee7cdcc60c9593cc765b
599,974
def make_bbh(hp,hc,fs,ra,dec,psi,det,ifos,event_time): """ Turns hplus and hcross into a detector output applies antenna response and and applies correct time delays to each detector Parameters ---------- hp: h-plus version of GW waveform hc: h-cross version of GW waveform ...
508542385a9084398b33e8b92436037f9d71a7e1
599,976
def unesc(line): """Uncomment once a commented line""" if line.startswith('# '): return line[2:] if line.startswith('#'): return line[1:] return line
e18977c215be645f294dce1297f2292a740c10f9
599,977
def weight_boundary(graph, src, dst, n): """ Handle merging of nodes of a region boundary region adjacency graph. This function computes the `"weight"` and the count `"count"` attributes of the edge between `n` and the node formed after merging `src` and `dst`. Parameters ---------- g...
1ccb1c6824eab1d2162f0f5992d7777852c1cb25
599,978
def start_form(i): """ Input: { (url) - url (name) - name (method) - 'POST' by default (enctype) - 'multipart/form-data' by default (charset) - 'utf-8' by default } Output: { return - return code = 0, if...
f95699c315e53f527bb5a7134e45befc6538d55f
599,979
import hashlib def get_md5_digest(arg): """Returns the MD5 digest of the specified argument. The digest is a string containing only hexadecimal digits. Args: arg (string): The string to hash. """ return hashlib.md5(arg).hexdigest()
6bacc5af3b9c59956fac33c27d03fd1598f8fff2
599,980
import glob def list_file_in_dir(path, file_ext): """ The function is used to return a list of files in a specific directory and its subdirectories. :param str path: the interested directory :param str file_ext: file extension. for exaple, 'tif', 'jpg' :return a list of files with full paths ...
3143e967eda4da5d5d18004ec2850e904004f752
599,982
from typing import OrderedDict def join_dicts(d, keys=None): """ Task: Concatenate list/directory of dictionaries: [d1, d2, ... ] or {"d1": d1, "d2": d2, ...} into a single dictionary. Note: This function returns a ordered dictionary, i.e, the order of the key insertions i...
0b90278a8359d2b5b1547a461a1aeaa8f3d514c7
599,990
def convert_coco_to_voc(label): """Converts COCO class name to VOC class name, if possible. COCO classes are a superset of VOC classes, but some classes have different names (e.g. airplane in COCO is aeroplane in VOC). This function gets COCO label and converts it to VOC label, if conversion is...
dc97c63b2888b086d3ff804a841838cb4db72583
599,999
def read_count(f, n): """Read n bytes from a file stream; return empty string on EOF""" buf = '' while len(buf) < n: nextchunk = f.read(n - len(buf)) if not nextchunk: return '' buf += nextchunk return buf
c7bbc0efb8e053b4eeb187a3a8bf88591468d48b
600,001
def urlencode(s): """urlencode(s) -> str URL-encodes a string. Example: >>> urlencode("test") '%74%65%73%74' """ return ''.join(['%%%02x' % ord(c) for c in s])
09905ba226368b23c081ccc7845a7deb3b4f69bc
600,003
def default_if_none(value, default=None): """Return default if a value is None.""" if value is None: return default return value
afa33dda51a074c18624da772719c333d05e787f
600,010
import json def notify_job_by_tweet(info): """ Create job json for tweet notification. Example: job = { 'type': 'notify_job_by_tweet', 'name': 'action-notify_job_by_tweet-CSKS4_RAW_B_HI_11_HH_RD_20131004020329_20131004020336', 'tag': 'tweet CSK ingest', ...
a728904e38803dd576f12f28b538deba376889c8
600,011
def simtk_vec_to_list(vec): """Convert SimTK::Vec_<T> to Python list. """ temp = [] for i in range(vec.size()): temp.append(vec[i]) return temp
dae089de940b7ac2d725e948342e121ff69a4046
600,012
def get_k(xy1, xy2, perpendicular = False): """ Establishes steepness of line, or its perpendicular - as if line were a Linear function graph, and we returned the k value from y = kx. Vertical line -> "Vertical" Input: 2 points (xy, xy), perpendicular (bool) Output: k of line OR k of perpendicular ...
7df13c8c6eed1961e87d4e71b7702c0a51d221cc
600,014
import requests import json def get_response(url, headers): """ Gets the report response from the API """ response = requests.request("GET", url, headers=headers) response_dict = json.loads(response.text) return response_dict
a6e8e965a33fd9f2a111d9a14b1b4f651d603423
600,015
def isGColRequired(config, num): """A quick helper function that checks whether we need to bother reading the g1,g2 columns. It checks the config dict for the output file names gg_file_name, ng_file_name (only if num == 1), etc. If the output files indicate that we don't need the g1/g2 columns, then w...
d4b59f62a13170470abb5fa064c1c9c74820eaae
600,021
def is_empty(val): """Returns True if val is Falsy, otherwise returns False""" return not bool(val)
d728754fcda8934e2ee994b76358a9b5be5b43ab
600,022
import re def normalize(name): """Returns a name suitable for a filename.""" name = re.sub(r'[^a-z0-9]', ' ', name.lower()) name = re.sub(r'\s+', '-', name.strip()) if not name: name = 'untitled' return name
8f26320b4a06edccb6e128c2452e6b0aff4eb51f
600,026
def return_dict_value(dictionary, keys, *, ignore_key_error=False): # pragma: no cover """ Return a value from a dictionary. Recursively iterate over a dictionary and return value for the key. Key must be a list. Each element of the list refers to the level of the dicionary It helps to reduce...
daa20af115ae4a6ee4615950be0bcb457aa99ad1
600,028
def swap_pairs(input_list): """Swaps pairs of elements in a list. The list can be of even or odd length""" return_list = [] return_list.extend(input_list) if len(input_list) % 2 == 0: return_list[::2], return_list[1::2] = input_list[1::2], input_list[::2] else: return_list[:len(input...
a14847fc10d5ee9fca49db46f816bdc2dad19315
600,029
def parse_filenames_and_sizes(list_file): """ Takes a file with tab-delimited filename/size pairs and returns a filename-->size dict. """ filename_to_size = {} with open(list_file,'r') as f: for line in f: if ('catalog.json' in line) or ('stac.json' in lin...
ca029d217a6b0b6ba65acea63255542179a413c2
600,032
def get_set_cookies(data): """returns set-cookies headers as a dict""" ret = {} cargs = data.split('||') for ck in cargs: ie = ck.find('=') sn = ck.find(';') if ie > -1 and sn > -1: name = ck[:ie] val = ck[ie+1:sn] ret[name] = val return re...
a4ca1f8ff5336905b05ed2a18911b3687b43ef11
600,034
def normaliseFileOrFd(fileOrFd): """Convert to a file descriptor. :Param fileOrFd: This can be a plain old integer FD or an object that provides a ``fileno`` method; such as a python ``file``. """ if hasattr(fileOrFd, "fileno"): try: return fileOrFd.fileno() ...
b1d81f74bdabbbc76f01226857778a1807bd627e
600,037
import re import click def validate_email_address(ctx, param, value): """Ensure that email addresses provided are valid email strings""" # Really just check to match /^[^@]+@[^@]+\.[^@]+$/ email_re = re.compile('^[^@ ]+@[^@ ]+\.[^@ ]+$') if not email_re.match(value): raise click.BadParameter( ...
4be5a86038b4f7be2fdf0f6f4c9f8d732d00454e
600,039
from typing import Sequence def __express_list_of_sections(sections: Sequence[str]) -> str: """Convert list of sections into natural language. >>> __express_list_of_sections(["one"]) 'Section one' >>> __express_list_of_sections(["one", "two"]) 'Sections one and two' >>> __express_list_of_sect...
3f70aeaebdc2f6ad84fbb78320d43b56b26e4f7d
600,041
import random def recombine(population): """Cross over two parent paths and return the resulting child path Arguments received: population -- an array of lists of coordinates representing paths Arguments returned: child -- list of coordinates representing a recombined child path """ # Ra...
151501f8f423f57dedf4af1303fb00116fbe38a1
600,045
def add_css_tag(token, modification): """Returns a token wrapped with the corresponding css tag.""" if modification == 'replace': token = '<span class=\"delta-replace\">' + token + '</span>' elif modification == 'delete': token = '<span class=\"delta-delete\">' + token + '</span>' elif ...
72ae2536122514eecadd3f7dd855911678279966
600,046
def is_python(view, ignore_comments=False, autocomplete_ignore_repl=False): """Determine if the given view location is python code """ if view is None: return False # disable in SublimeREPL if view.settings().get('repl', False): if not autocomplete_ignore_repl: return F...
d920ac88d87b4fc6a52d4d66a076fb816ab27f3f
600,048
def index_subs(ind, substitution): """ A simple subs function that works both on tuples and strings """ if ind is None: return ind else: return tuple([substitution.get(c, c) for c in ind])
304cb0952b2da9c70f7583ad5ca8b60fc1bcd5c4
600,049
def IsConvertibleTo( x, aType ): """Test if a value is convertible to a given type""" try: dummy = aType(x) return True except ValueError: return False
1ded65449ef96b13bb4994a277033fa6a11b9aa1
600,051
import unicodedata def strip_accents(unistr): """ Return the accent-stripped str for the given unistr (unicode is required). """ return unicodedata.normalize('NFKD', unistr).encode('ascii', 'ignore').decode('ascii')
dbbc539086d7e6e81e523da41e33459781178596
600,052
import torch def sample_pdf(bins, weights, N_importance, det=False, eps=1e-5): """ Sample @N_importance samples from @bins with distribution defined by @weights. Inputs: bins: (N_rays, N_samples_+1) where N_samples_ is "the number of coarse samples per ray - 2" weights: (N_rays, N_samples...
36f0aee56becb544f571561af6601353d4e5c211
600,054
def filter_word_counts(counts, min_length=1): """ Given a list of (word, count) tuples, create a new list with only those tuples whose word is >= min_length. """ stripped = [] for (word, count) in counts: if len(word) >= min_length: stripped.append((word, count)) return s...
dbc3b6cf319663d34f4bcccb5109d0a2d6bb4f99
600,058
def csv_safe(value): """Remove any beginning character '=-+@' from string value. Change None to empty string. See http://georgemauer.net/2017/10/07/csv-injection.html """ if isinstance(value, str): while len(value) and value[0] in '=-+@': value = value[1:] elif value is None:...
6cde7aedca288adc40fac194e2661aa690c6ff76
600,060
def drpver(versions): """Return DRP version.""" drpver, __ = versions return drpver
075666c0a2654948eff38f18ca567fd959005658
600,062
import configparser import functools def parse_benchmark_configuration(file): """Parse fields from INI-style configuration file section "Benchmark". Parsed fields: powers: whitespace separated string of float representations. module_name: name of module to import for benchmarking. pre...
dc094bd649d93d4745d7a8d1e68d9f01afd6e3fd
600,063
import json def bytes_to_json(line): """ Converts a sequence of bytes to a JSON object Parameters: line (bytes): sequence of bytes Returns: (JSON): Object converted """ # converts 'line' from bytes to string decoded = line.decode('utf-8') # deserializes 'decoded' string to ...
775c12b1038b32315074cc300ede2a33167a97b5
600,066
def PZapTable (inUV, tabType, tabVer, err): """ Destroy specified table Returns 0 on success inUV = Python UV object tabType = Table type, e.g. "AIPS AN" tabVer = table version, integer err = Python Obit Error/message stack """ ###########################################...
b927cabfac51353bc44ea693d4dc7b8687fa6d4e
600,071
def fizz_buzz_three( start, end ): """ Returns the fizzbuzz string for a given range using an inner function and a list comprehension. """ def int_to_fizzbuzz(i): """ Output the 'fizzbuzz' string for a single number. """ entry = '' if i%3 == 0: # if i divided by 3 has no rema...
60af6a08e7b838d06c089755b5fecb0df6c28f2a
600,076
def rpl_helper(_original, _replacement): """ Given a list `_original` that contains '0', '1', or 'X', replace the occurrences of 'X' in `_original` with chronological values from `_replacement`. :param _original: A list of '0', '1' or 'X'. :param _replacement: A list of '0', or ...
2817b66bab0d6cd7b8736379f58b13e969f9d41c
600,081
import importlib def try_import(module_name): """Try importing a module, with an informative error message on failure.""" install_name = module_name try: mod = importlib.import_module(module_name) return mod except ImportError: err_msg = ( "Failed importing {}. This...
6d09ad0c9722f7b5543536c2011bbe873624c9d2
600,082
import torch def reverse_cumprod(x, dim): """Perform cumprod in a reverse order along the dimension specified by dim. Args: x (Tensor): the tensor to compute the reverse cumprod on dim (int): the value indicating the dimension along which to calculate the reverse cumprod Retur...
2198bd8879f250661a37bb0730195dc38da5a05a
600,088
def build_slitw_format_dict(slitw_vals): """Build a dict mapping the slit width vals to matplotlib format statements""" idx = 0 odict = {} slit_fmt_list = ['r.', 'g.', 'b.', 'k.'] n_slit_fmt = len(slit_fmt_list) for slitw in slitw_vals: if slitw not in odict: odict[slitw] = s...
87fd6c91df450548367396dfaa0d225d86916866
600,090
def is_close(x, y, thresh=1e-8): """ Tests if x is close to y as measured by some threshold. """ diff = x - y return diff > (-thresh) and diff < thresh
6d4709f723bbc660b9d01091f4bcaf401c450af6
600,092
import secrets def rndstr(size=16): """ Returns a string of random url safe characters :param size: The length of the string :return: string """ return secrets.token_urlsafe(size)
f351de996cbfc88daa14baf8fce85e69017db006
600,093
import ast def has_node(code, node): """Given an AST or code string returns True if the code contains any particular node statement. Parameters ---------- code: A code string or the result of an ast.parse. node: A node type or tuple of node types to check for. If a tuple is passed it r...
9e1555a3393e3c91f35f6e3fc468eab14d5147b4
600,096
def is_valid_cord(x, y, w, h): """ Tell whether the 2D coordinate (x, y) is valid or not. If valid, it should be on an h x w image """ return x >=0 and x < w and y >= 0 and y < h
9dff108ffd3f6baf16eb729c9acb672ed1f93e9b
600,101
def filter_id(mention: str): """ Filters mention to get ID "<@!6969>" to "6969" Note that this function can error with ValueError on the int call, so the caller of this function must take care of this """ for char in ("<", ">", "@", "&", "#", "!", " "): mention = mention.replace(char, ""...
d8f8de89a1f3289cfd3a90b13dca418c54d64119
600,102
def mapRangeParam(u, min_u, max_u, min_v, max_v): """ Linearly map a floating point value u in the range [min_u, max_u] to a value v in the range defined by [min_v, max_v]. Args: See description. Return: Floating point value v """ assert type(u) is float assert type(min_u) is float assert t...
946c13f19e34b6f3007004b871b515652c96dd9e
600,104
import torch def em_by_begin_end_index(pred_begin, pred_end, begin, end): """ Calculate exact match score given the token index tensors of prediction boundary and true answer boundary. """ batch_num = pred_begin.size(0) exact_correct_num = torch.sum( (pred_begin == begin) * (pred_end =...
bbba638b87e5a4d668e701941dea37bf1315a09e
600,105
from pathlib import Path import tomllib import configparser def main() -> int: """Read version from pyproject.toml. Fallback to setup.cfg.""" version: str | None = None if (path_pyproject := Path("pyproject.toml")).is_file(): with open(path_pyproject, "rb") as fp: data = tomllib.load(...
4ec79b6ff90dee7f93afb1ab3b504316b58b6d72
600,110
import math def get_imprints_from_hashes(hashes): """The function return imprints of the given hashes @param hashes - list of hashes @return - list of each k element in hashes, where k equal log(len(hashes)) """ count_hashes = len(hashes) k = math.floor(math.log(count_hashes, 2)) r...
b611aa301bf06f1810f6c1301bf43b4655450838
600,113
def nodes_dict(G): """ It creates a dictionary where keys represent the node ID, and items the coordinate tuples. Parameters ---------- G: NetworkX Graph Returns ------- nodes_dict: dict a dictionary where each item consists of a node (key) and a tuple of coordinates (v...
230ffa11c88a11c57c7270cf77aee2e35cb120f4
600,115
def reverse_dict(adict): """Return the reverse mapping of a dictionary.""" return dict([(v, k) for k, v in adict.items()])
aff573b74e2e9c19359fb43cb3977dd5c59df1d7
600,116
from typing import Callable import time def timeit(func: Callable) -> Callable: """A decorator for functions, add execution time of a function as an additional return value. Use as @timeit just above your function definition. Args: func: A callable, could be any function. Returns: A...
713590223508111f7631103ac9d77b62cbabcf16
600,119
from typing import Type import typing from typing import Union def is_generic_union(type_: Type) -> bool: """Determines whether a type is a Union[...]. How to do this varies for different Python versions, due to the typing library not having a stable API. This functions smooths over the differences. ...
c2b7d5936db1ec2175af76026e67c9fc47d21efd
600,127
import torch def relu_network_gradient(relu_network, x: torch.Tensor, *, zero_tol: float = 0.) -> torch.Tensor: """ For a fully-connected neural network ϕ(x) with (leaky) relu units, compute the gradient ∂ϕ/∂x. Notice that s...
56be4ffcfa155ef2d2be9a8997a8638688805592
600,130
def get_results_count(api_response): """This function returns the number of results within a response from the Community API. :param api_response: The response to an API query in JSON format :type api_response: dict :returns: The number of results in the API response as an integer """ return ap...
024d5d8878d2bc0bad64ff310689ff3560eff7dd
600,131
from typing import List from typing import OrderedDict def surface_string(tokens: List[OrderedDict], trim=False) -> str: """Generates a surface string from a list of tokens/strings.""" s = ''.join([t['text'] + (' ' if t.get('misc', {}).get('SpaceAfter', 'No') == 'Yes' else '') for t in tokens...
2fc400eeb330b14a41d64c5b7caba3d6819ba8c3
600,132
from typing import Hashable def is_node(item: object) -> bool: """Returns whether 'item' is a node. Args: item (object): instance to test. Returns: bool: whether 'item' is a node. """ return isinstance(item, Hashable)
09df6e25fbd0f17f75a41ed9ce40d62e4830aaed
600,136
import csv def get_data_from_csv_file(filename): """Load data from csv file into a list.""" with open(filename, "r") as f_obj: reader = csv.DictReader(f_obj, delimiter=',') csv_data = list(reader) return csv_data
f2a689237b1c87577b7153842dc1a1ff2c504288
600,138
def sched_id_arr_size(cycle_id_list): """ Return total size for the scheduled ID array. """ id_list_size = 0 for l in cycle_id_list: s = len(l) if s == 0: id_list_size += 1 else: id_list_size += s return id_list_size
0cab78766b025ec39180602fad7449052a6f5803
600,139
def get_default_metadata( max_num_machines=1, max_wallclock_seconds=1800, with_mpi=False, num_mpiprocs_per_machine=1, ): """ Return an instance of the metadata dictionary with the minimally required parameters for a CalcJob and set to default values unless overridden :param max_num_mach...
d1eb80dc5acb2c111f88f54dd07aa36783dbf009
600,140
def cluster_ips(test_vars): """ Return a list of known cluster IPs. The cluster mgmt IP, at a minimum, must be known. Cluster node and vserver IPs are also added to the list of cluster IPs that is returned. """ c_ips = [test_vars["cluster_mgmt_ip"]] if "cluster_node_ips" in test_vars: ...
4c70b91f5c2a36d82a21b5e7d2684832bffc88e3
600,146
def identity_mapper(k, v): """ This is the identity mapper, just lets (k, v) pass to the next phase :param k: key :param v: value :return: (k,v) as a pair """ return k, v
c6e8204db0737d1b7b47e1695b3b0bb1217059a7
600,148
def unmap_trigger(library, session, trigger_source, trigger_destination): """Undo a previous map from the specified trigger source line to the specified destination line. Corresponds to viUnmapTrigger function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Uni...
2d20d3e8e2a2753afb68a88d0870888cff8ed547
600,150
def bget(jdb,s): """Better get. Check for nonetype""" try: return jdb.get(s) except: pass return None
3b1a1fee9a0b5b3331f8c8ee75bb6661ecd24a8b
600,152
def get_partition(string_): """ Return the partition portion of a device name (mount style, or udisksctl style). :param string_: :return: """ if "block_devices/" in string_: return string_[len("block_devices/"):] elif "/dev/" in string_: return string_[len("/dev/"):] els...
dedfb2547cfe58f2c85d56d63ebd17a294f0c53e
600,154
async def __fetch_user_names_and_icons(client, users): """ Get user display names and icon URLs for a list of users. Returns a dict structure: userid: {'display_name': display_name, 'icon_url': icon_url} client: the client from the context object. users: a list of userids. Uniqueness not requir...
060c2c3c17615052bfe35a6ee5a1ecb70de92aca
600,157
def _remove_inst(inst_map, remove_id_list): """Remove instances with id in remove_id_list. Args: inst_map: map of instances remove_id_list: list of ids to remove from inst_map """ for inst_id in remove_id_list: inst_map[inst_map == inst_id] = 0 return inst_map
c62781de0a996020dc47c41f3bd6c6eead03fc19
600,159
def simpleeq(data): """ You are given four positive integers: A, B, C, N. If 0 ≤ a ≤ A, 0 ≤ b ≤ B and 0 ≤ c ≤ C, using these integers you should try to calculate the number of possible solutions to the following equation: a + b + c ≤ N. """ numberofsols=0 for a in range(data[0]+1): ...
93d7d4ddc721d30ac9b64694e86fbff2e5ee01a5
600,167
def layout_to_text(layout: dict, text: str) -> str: """ Document AI identifies form fields by their offsets in the entirety of the document's text. This function converts offsets to a string. """ response = "" # If a text segment spans several lines, it will # be stored in different text seg...
f0b5333fc66c95b2e6ba46c6d03496c8174ef08b
600,168
def line_count(fname): """Count the number of lines in a file""" n = 0 for _ in open(fname): n += 1 return n
f5c66eb1ed45ae51973700ede6186d3becb9551c
600,177
def _merge_dicts(*args): """ Shallow copy and merge dicts together, giving precedence to last in. """ ret = dict() for arg in args: ret.update(arg) return ret
63b3ff5786b7be098e0e56eb8feee3e94627243a
600,178
def get_floorare_pp( floorarea, reg_pop_by, base_yr, sim_period, assump_diff_floorarea_pp ): """Calculate future floor area per person depending on assumptions on final change and base year data Arguments ---------- floorarea : dict Floor area bas...
ffa22d70a9d74f3ce9d9dd30f627409f48816319
600,182
import torch def reconstruction_loss(x, x_hat, *args, **kwargs): """ Returns the binary cross entropy loss Parameters ---------- x : Tensor the autoencoder input tensor x_hat : Tensor the autoencoder output tensor Returns ------- Tensor the (1,) loss tenso...
ca1bb562ed11262e4ebdb5a45d1ca5669c828b1d
600,183
def filter_unique(spisok): """Get unique values from list """ spisok_uniq = [] for x in range(0, len(spisok)): if spisok_uniq.count(spisok[x]) < 1: spisok_uniq.append(spisok[x]) return spisok_uniq
fd1f017a8de7f70de2173a2169f3f9f26999ea56
600,185
import logging def get_season(month): """ Detects to what season is the month :param month: int 1-12 :return: int 0-4 """ if month in [1, 2, 12]: return 1 elif month in [3, 4, 5]: return 2 elif month in [6, 7, 8]: return 3 elif month in [9, 10, 11]: ...
33fa4631ddd00469a107e5cf9564036bf7b49fe7
600,187
def captioned_button(req, symbol, text): """Return symbol and text or only symbol, according to user preferences.""" return symbol if req.session.get('ui.use_symbols') \ else u'%s %s' % (symbol, text)
b2f4be2fe0dac6b0d0b90ca91d00a625d674517c
600,190
def PyUnicode_Join(space, w_sep, w_seq): """Join a sequence of strings using the given separator and return the resulting Unicode string.""" return space.call_method(w_sep, 'join', w_seq)
f7cb8a460350475b5772c40730b89feefe4243d4
600,194
def property_value(row, prop): """Get the value of the row/object property specified by prop.""" return { 'TotalIngress': row.TotalIngress, 'TotalEgress': row.TotalEgress, 'TotalRequests': row.TotalRequests, 'TotalBillableRequests': row.TotalBillableRequests, 'Availability': r...
e325c3368a9582cca712e29ad588ef55abf761d5
600,195
import torch def amplitude_to_db(x, ref=1.0, amin=1e-7): """ Amplitude-to-decibel conversion (logarithmic mapping with base=10) By using `amin=1e-7`, it assumes 32-bit floating point input. If the data precision differs, use approproate `amin` accordingly. Args: x (Tensor): Input amplitud...
a1696b730368b464639a6ef78f9704621709f9c5
600,200
def test(data, beta): """ Output the quantities necessary to compute the accuracy, precision, and recall of the prediction of labels in a dataset under a given β. The accuracy (ACC), precision (PRE), and recall (REC) are defined in terms of the following sets: P = datapoints (x,y)...
84e4cdf8cb76c2cedd693a8bd879068f55305bc2
600,204
import json def read_data(path): """reads data from the path :param path: path to data :type path: str :returns: data :rtype: dict """ with open(path, 'r') as f: return json.load(f)
7125bda311f95348fa40999f29c57749e688818e
600,209
import re def _normalize_metadata(metadata): """Normalize metadata to improve match accuracy.""" metadata = str(metadata) metadata = metadata.lower() metadata = re.sub(r'\/\s*\d+', '', metadata) # Remove "/<totaltracks>" from track number. metadata = re.sub(r'^0+([0-9]+)', r'\1', metadata) # Remove leading z...
839777b708e871448ad133c0496331ce8b933585
600,210
def _constrain(value, lb=0, ub=1): """Helper for Color constructors. Constrains a value to a range.""" if value < lb: return lb elif value > ub: return ub else: return value
975fd371b004c5e40c21770aa55fbd59ab04a43f
600,211
def is_callable(value): """Returns whether the value is callable.""" return hasattr(value, '__call__')
33ebb2aad3b131f32eb74488783be39b20c86e24
600,212
def reverse_str(s): """Returns reverse of input str (s)""" return s[::-1]
825a7deedc37812f6efcd474f572df0ad6de6696
600,213
def find_sections_in_file(file_obj): """Find LAS sections in a file. Returns: a list of lists *(k, first_line_no, last_line_no, line]*. *file_pos* is the position in the *file_obj* in bytes, *first_line_no* is the first line number of the section (starting from zero), and *line* is the ...
9e000e56592959cdcf11267447f15f4ce44bbece
600,214
def LSTMCellWeightsShape(num_inputs, num_nodes): """Returns the shape of the weights for a single LSTM cell.""" # Dimension 0 accounts for combining x with the previous m state. # Dimension 1 accounts for the in value and the (in, forget, out) gates. return [num_inputs + num_nodes, 4 * num_nodes]
86b08db5539c9459ea49a198a5438c84887bc60c
600,217