content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _wrap_class_factory(methods_wrap_func_list,
*args,
allow_exceptions=False,
**kwargs):
"""Factory function for metaclasses that produce methods via a functor.
Applies the functor to each method given in methods. This occurs before
c... | 936a6395e77322cffe0a08c0b82379983fae9815 | 609,492 |
def determine_format(format_string: str):
"""
Determines file format from a string. Could be header/ext.
Args:
format_string: Header or file extension.
Returns:
str: Type of the image.
"""
formats = ["PNG",
"TIF", "TIFF",
"JPG", "JPEG"]
for form... | 9a2ea8316da8f7bb08143d49a457de6c33d12566 | 609,493 |
def wrap_text(inText, maxlen=70, subsequent_indent='=\n'):
"""
Text wrapper without need for textwrap package.
>>> wrap_text('SADI 0.02 C1A C2A C2A C3A C3A C4A C4A C5A C5A C6A', maxlen=30)
'SADI 0.02 C1A C2A C2A C3A C3A =\\n C4A C4A C5A C5A C6A'
"""
line_list = []
wrapped = []
inText_lis... | b51c7f60a771ddeb9b227755db688526c43f5b2f | 609,496 |
def is_scalar(arg) -> bool:
"""
Return True if the arg is a scalar.
"""
return isinstance(arg, int) or isinstance(arg, float) | e17772e0216879b55310073f2a7869fe44e7544e | 609,501 |
from typing import List
from typing import Dict
from typing import Any
def default_text_pipeline() -> List[Dict[str, Any]]:
"""
Return a list of dictionaries representing the functions in the default pipeline.
Use as a template for creating a custom pipeline.
Read more in the :ref:`User Guide <clean_... | 9d7e22b1c0a34e3b76888176375324d8ed606d6c | 609,506 |
def matching_error(error_list, reason, processor):
"""
There's a matching error if any error in the list has the same processor and reason associated with it.
:param error_list: list, of Error objects
:param reason: str, reason for the error
:param processor: str, in ['voc', 'methane', 'picarro']
... | 769588b77c23ea2a3705218a17db9d033417b24f | 609,508 |
import torch
def loc2bbox(loc, priors, center_var=0.1, size_var=0.2):
"""
Compute SSD predicted locations to boxes(cx, cy, h, w).
:param loc: predicted location, dim: (N, num_priors, 4)
:param priors: default prior boxes, dim: (1, num_prior, 4)
:param center_var: scale variance of the bounding box... | ea6180ddb032115e3c0980a1f584ac1c0acf1192 | 609,510 |
def get_label(filename:str) -> str:
"""
Assign label from directory name.
"""
label = filename.split("/")[-2]
return label | 8742dc160a439ac559816d8660d1c36a2d0a686e | 609,512 |
def _CreateActionsText(text, igm_field, action_types):
"""Creates text presented at each wait operation for given IGM field.
Args:
text: the text associated with the field.
igm_field: reference to a field in the Instance Group Manager.
action_types: array with field values to be counted.
Returns:
... | 2eb42dd58efccbc18dc827bb6582204eb7808144 | 609,513 |
def _protect_password_sqlcipher(password: str) -> str:
"""A double quote in the password would close the string. To escape it double it
source: https://stackoverflow.com/a/603579/110395
"""
return password.replace(r'"', r'""') | 6b0ac79ff3be06d9d08913b6c8b58b19ac39b0e4 | 609,515 |
import pathlib
def sample_svs(remote_sample) -> pathlib.Path:
"""Sample pytest fixture for svs images.
Download svs image for pytest.
"""
return remote_sample("svs-1-small") | 0b502e7d064bcf264f05e5f09277e2832685a060 | 609,516 |
def pixelscale_nyquist(wave, f_number):
"""Compute the output plane sampling which is Nyquist sampled for
intensity.
Parameters
----------
wave : float
Wavelength in meters
f_number : float
Optical system F/#
Returns
-------
float
Sampling in meters
""... | 54f703517f55a83ae196547e2e9d67a12db807f4 | 609,520 |
def attach_ordinal(num):
"""Convert an integer to an ordinal string, e.g. 2 -> '2nd'."""
suffixes = {str(i): v
for i, v in enumerate(['th', 'st', 'nd', 'rd', 'th',
'th', 'th', 'th', 'th', 'th'])}
v = str(num)
# special case early teens
if v in {... | dc54c9919af1b64e217ca552ffacd01becec989b | 609,526 |
def top_sentences(query, sentences, idfs, n):
"""
Given a `query` (a set of words), `sentences` (a dictionary mapping
sentences to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the `n` top sentences that match
the query, ranked according to idf... | aaeff62650f992f099e2bc8d892b1ebf83ba2004 | 609,528 |
from typing import Optional
from typing import Dict
from typing import Iterable
def dict_values_in(
dict_: dict,
key_values: Optional[Dict[str, Optional[Iterable]]] = None,
) -> bool:
"""
Returns True if ``dict_[key]`` is in ``values`` for all items in
``key_values``.
Also returns True if ``k... | 5e0e3716f268ebd070c601fa1a7a3b9242fca498 | 609,531 |
def fastas_for_features_vs_masked_genomic(afasta, bfasta):
"""
>>> fastas_for_features_vs_masked_genomic("a.fasta", "b.fasta")
('a.features.fasta', 'b.genomic.masked.fasta')
"""
a = afasta.replace(".fa", ".features.fa")
b = bfasta.replace(".fa", ".genomic.masked.fa")
return a, b | 26011e6ba54bbd7e53a38d443dd92ad277a791ff | 609,533 |
def _convert_lon_to_0to360(ds, coord="lon"):
"""Convert from -180 to 180 (W-E) to 0 to 360 (degrees E) grid.
.. note::
Longitudes are not sorted after conversion (i.e., spanning -180 to 180 or
0 to 360 from index 0, ..., N), as it is expected that the user will plot
via ``cartopy``, ``b... | 72d32ffa1227dcd4a93bc9625c8c3bacdbea1dc0 | 609,534 |
def to_native_str(str_or_bstr):
"""
Returns a native string, regardless of the input string type (binary or
UTF-8), and the Python version (2 or 3).
Note that the native string type is actually not the same in Python 2 and
3: In the former, it's a binary string, in the latter, it's Unicode.
>>> ... | 1a5fa2a1e892502673c80044b7f28d6ea397985e | 609,539 |
import math
def _generalised_sum(data, func):
"""_generalised_sum(data, func) -> len(data), sum(func(items of data))
Return a two-tuple of the length of data and the sum of func() of the
items of data. If func is None, use just the sum of items of data.
"""
count = len(data)
if func is None:
... | ee79aac172024b335e10bbb3176560778a872c9b | 609,540 |
def calculate_TB(salt, ver="Uppstrom"):
""" Calculate Total Borate """
if "upp" in ver.lower():
return 0.0004157 * salt / 35 # in mol/kg-SW
else:
# Lee, Kim, Byrne, Millero, Feely, Yong-Ming Liu. 2010.
# Geochimica Et Cosmochimica Acta 74 (6): 1801?1811.
return 0.0004326 * salt / ... | 1a3371e99d24987d936cbf83b29c044d5cff7552 | 609,542 |
import requests
import time
def fetch_from_url_or_retry(url, json=True, header=None, post=False, data=None,
retry_in=None, wait=1, n_retries=10, stream=False, **params):
"""
Fetch an url using Requests or retry fetching it if the server is
complaining with retry_in error. There... | 693ce7a5b62741a6c5e2431c7619c679f2e6a497 | 609,544 |
def binStringToInt(binString):
"""Converts a string of binary digits to an integer of base 10"""
return int(binString,2) | 88d0afa30f7ae7d28d542b73ff2d20874341e73c | 609,545 |
import torch
def gather(values, index, name="segmented_gather"):
"""
Gathers from `values` using the index map. For each element in the domain of the index map this operation looks up
a value for that index in `values`. Two elements from the same segment always get assigned the same value.
Args:
... | e8a69ba49c3aeb52de2595865dd9a6703ab648e3 | 609,547 |
def cast_to_int(string):
"""
Cast string value to int or return None if the string is not convertible to int.
:param string: string
:return: int or None if string is not convertable to int
"""
try:
return int(string)
except (ValueError, TypeError) as e:
return None | 21bad651f3bc7faf4a5232860d5aa67bee38d82e | 609,548 |
def _process_keyword(obj, target, source, keyargs, default=None):
""" Set obj.target from:
- keyargs[source]
- default
- obj.source
in that order."""
arg = keyargs.get(source)
if arg is not None:
setattr(obj, target, arg)
elif default is not None:
setattr(obj, target, def... | bd5d7cc44d91e3e12e88b1d499a5e13cd4120804 | 609,550 |
import csv
def load_angle_offsets(csv_path):
"""Load additive euler angles from CSV file.
header: joint, i, j, k
Order of x,y,z values must match order of rotation channels in BVH file. If the order is zxy then i=z, j=x, k=y.
:param csv_path: Path to CSV file containing values.
:type csv_path... | aed976ebf2801364b9d770895e943d0864c46d5c | 609,553 |
def get_best_opportunity(opportunities, min_profit):
""" Find the best opportunity for trading
"""
best = None
for opportunity in opportunities:
if opportunity['profit'] >= min_profit and \
(best is None or opportunity['profit'] > best['profit']):
best = opportunity
... | 8c13909be0c8771c3f56ed660de0bb6d0b68d08a | 609,555 |
def html_table(headers, table):
"""
Format a table into an html table.
Parameters
----------
headers : list
List of header titles
table : list
List of rows with data formatted
[ [row1_entry1, row1_entry2, ..., row1_entry<len(headers)>],
[row2_...],
... | 7a6f648c861c594a8f058e2f6011efdac88d391f | 609,558 |
def min_shape(args):
"""Returns the minimum shape that encompasses the shape of all *args*."""
args = tuple(args)
if len(args) <= 0:
raise ValueError("args must not be empty.")
elif not all(len(a) == len(args[0]) for a in args):
raise ValueError("All shapes must have the same number of d... | d1494a6a8f00f8dab84c57fea44bb91dac7df805 | 609,560 |
def get_filename_from_path(path):
"""
:param path
:return: file name without type
"""
return ".".join(path.replace('\\', '/').split('/')[-1].split('.')[:-1]) | 4f69a97378a382ff3c115bf247808c819aac6bde | 609,562 |
import base64
import binascii
def decode_b64(value):
"""Decode base64 values or return raw value."""
try:
decoded = base64.b64decode(value, validate=True)
return decoded.decode("utf-8")
except binascii.Error:
return value | fecf98e26ccd3f9a10fd6968d86bf8a6cb7625b8 | 609,565 |
def bounding_box(points):
"""
Computes the bounding box of a list of 2D points.
:param points: list of (x, y) tuples, representing the points
:return: list of four (x, y) tuples, representing the vertices of the bounding box
"""
xs, ys = zip(*points)
x_min = min(xs)
x_max = max(xs)
... | 8bbe5ea57b93ef5deb74233d14657d5b0739e407 | 609,566 |
def compute_crow_spatial_weight(X, a=2, b=2):
"""
Given a tensor of features, compute spatial weights as normalized total activation.
Normalization parameters default to values determined experimentally to be most effective.
:param ndarray X:
3d tensor of activations with dimensions (channels, ... | 259b9b3ed8da4886e234d3cb50ffa9a244639735 | 609,567 |
def combine_convergence_data(data_A, data_B):
""" Combine dictionaries with potentially overlapping keys. """
data = {}
for key in data_A:
data[key] = data_A[key]
if key in data_B:
data[key].update(data_B[key])
for key in data_B:
if key not in data:
data[k... | 5117c498ff1b27356de096b5d15768e2005e3e47 | 609,568 |
import re
def update_file_data(data, replace_list):
"""
The replace list is a list of two strings, the first is a regex
defining what is to be replaced, the second the text to replace the
matches with
:data: the source data on which to run the replace on
:replace_list: list of a regex string a... | 410771f58d480fb865aa12fb0e40b3167792f529 | 609,571 |
from pathlib import Path
from typing import Optional
def get_latest_json_file(output_dir: Path) -> Optional[Path]:
"""Get the name of the last data-*.json file."""
files = list(output_dir.glob("data-*.json"))
return sorted(files)[-1] if files else None | 9bd907d78917c8e8db450a2c5a099c6f871c2c8e | 609,573 |
def py_type_name(type_name):
"""Get the Python type name for a given model type.
>>> py_type_name('list')
'list'
>>> py_type_name('structure')
'dict'
:rtype: string
"""
return {
'blob': 'bytes',
'character': 'string',
'double': 'float',
'... | e8944a740a94be92dc38f3aedcb26a0beffde367 | 609,574 |
from boto.s3.connection import S3Connection
from boto.exception import NoAuthHandlerFound
def S3ConnectionWithAnon(access, secret, anon=True):
"""
Connect to S3 with automatic handling for anonymous access
Parameters
----------
access : str
AWS access key
secret : str
AWS sec... | 3e640cfae9d580fe58d7f44588e2ffe7de9eb269 | 609,576 |
def space_indentation(s):
"""The number of leading spaces in a string
:param str s: input string
:rtype: int
:return: number of leading spaces
"""
return len(s) - len(s.lstrip(' ')) | 1b93211b50c7501a22cd509484b9c6a4e92d00c9 | 609,577 |
import click
def command_line_progressbar_option(f):
"""
Decorator for specifying a progress bar option.
"""
f = click.option(
"--hide-progress",
is_flag=True,
default=False,
help="Hide the Progress bar. Default: show progress, unless using pipes.",
)(f)
return ... | b8e558d54f3aa1cc3af4e51129ec9a8830be3fe7 | 609,581 |
def create_event_names_for_offsets(event_name, offset):
"""
Create names for offsets of every event
Args:
event_name (string): Name of the event
offset (int): Offset of the event
Returns:
offset_name (string): A name created for the offset of the event
"""
offset_name = ... | 9f65e9e8b9dfb3368f43e41401045a1ab8fdcfc1 | 609,583 |
import re
def intcomma(value):
"""
Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
value = str(value)
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', value)
if value == new:
return new
else:
... | fca5cbbff83cf23e052308cec0d88a2a49d85387 | 609,584 |
def notenum_to_freq(notenum):
"""Converts MIDI note number to frequency."""
f0 = 440.0
a = 2 ** (1.0 / 12.0)
return f0 * (a ** (notenum - 69)) | d39e2164a942d3ca090e5016b05375586cafb012 | 609,586 |
def is_pip_compile_noise(line_of_requirements_file):
"""Check if line in requirements file is not a dependency declaration.
Args:
line_of_requirements_file: line from requirements*.txt file
Returns:
Boolean indicating if line is suspected noise from pip-compile comments.
"""
return... | 6c1810ff907849441e27fcc629b76f01ad4e2461 | 609,587 |
from typing import Sequence
def duplicated(sequence: Sequence) -> bool:
"""
Determine if a sequence contains duplicate elements
"""
try:
return len(set(sequence)) < len(sequence)
except TypeError:
# If elements are unhashable
seen = []
for elem in sequence:
... | 48d7ea3ba4cc1beb44c03b5708967091fae12582 | 609,594 |
def ipv4_int(ipv4_str):
"""Returns an integer corresponding to the given ipV4 address."""
parts = ipv4_str.split('.')
if len(parts) != 4:
raise Exception('Incorrect IPv4 address format: %s' % ipv4_str)
addr_int = 0
for part in parts:
part_int = 0
try:
part_int = ... | b7b540b6fb7687e711dcdcc57923c58a13ea9ba3 | 609,597 |
def lift(lst):
"""Lift from 2D to 3D, with z=0."""
return [(x, y, 0) for (x,y) in lst] | 1c6ee616be59156515901f84d4c2ef691d4a8608 | 609,604 |
def build_gragh(graph_string):
"""
A quick parser from string into a dict that represent the graph.
Keys in the root level are the start of the path, keys in the result
are the desinations, values are the distance of the path
sample format:
AB5, BC4
returns {"A": {"B": 5}, "B": {"C": 4}}
... | 83a44c0f407c0df0b90e8bcb80e4cddce8c583d3 | 609,608 |
def getDiaphantineSums(n, degree=2):
"""
Checks if n satisfies n^2 = a^2 + b^2 (a "Diophantine" equation)
for any two other positive integers a and b (a, b are not necessarily
distinct). Note: although a different degree than 2 can be passed
in, this will result in an empty collection returned (as a result
of Fer... | 14c856762479949bf129cc13d2adca3496ddbf2a | 609,612 |
def _check_for_too_many_exclusions(exclude_instances, available_instances,
delta, groups_members):
"""
Check whether the amount of exluded instances will make it possible to
scale down by the given delta.
:param exclude_instances: A list of node instance I... | dca3588e02c8eaf60c6511dfedb3a3b281d64992 | 609,614 |
def Deserialize(serializationFormat, data): # real signature unknown; restored from __doc__
"""
Deserialize(serializationFormat: str, data: str) -> object
Deserializes the result of a Serialize call. This can be used to perform serialization
for .NET types which are s... | 7099292cdba94c0e876bf6c00fc33a03b7dcae99 | 609,615 |
def _get_prefix_and_full_hash(repo_data, kernel_partial_hash):
"""Find the prefix and full hash in the repo_data based on the partial."""
kernel_partial_hash_lookup = 'u\'%s' % kernel_partial_hash
for line in repo_data.splitlines():
if kernel_partial_hash_lookup in line:
prefix, full_hash = line.split('... | 277a857153adb3db63ce433db5b0506877eae5dd | 609,618 |
def appears_bnd(content):
"""Checks if the magic bytes at the start of content indicate that it
is a BND3-packed file.
"""
return content[0:4] == "BND3" | 89ca1fd281e0b8bc2e965b2105e4e2f502c341c9 | 609,623 |
import json
def load_json(fname: str) -> object:
"""Loads a json file and returns the encoded object.
Args:
fname (str): Path to json file.
Returns:
Any: Object encoded in json file.
"""
with open(fname, 'r') as fobj:
return json.loads(fobj.read()) | 6ad58ad66dfbe1178bef175223caeecb41d1f30f | 609,624 |
import re
def _parse_gpus(s: str) -> str:
"""
Accept either a comma separated list of numbers 'a,b,c' or a range 'a-c' and return as a string of list of ints.
"""
# Perhaps unnecessary sanity check?
s = s.replace(' ', '')
range_re = re.compile(r'^(\d+)-(\d+)$')
m = range_re.match(s)
if... | edeae4dfacf5e133f588fd09a61afc61d86746d9 | 609,625 |
def _cleanup(parts):
"""
Normalize up the parts matched by :obj:`parser.parser_re` to
degrees, minutes, and seconds.
>>> _cleanup({'latdir': 'south', 'longdir': 'west',
... 'latdeg':'60','latmin':'30',
... 'longdeg':'50','longmin':'40'})
['S', '60', '30', '00', 'W', '50', ... | 91b3eb57898834c7d5444c4b65caabb1d920353b | 609,627 |
def _sorted_arrangement(arrangement: list, items: list | str) -> list:
"""Elements of arrangement ordered as they appear in items."""
return sorted(
arrangement,
key=lambda item: items.index(item),
) | 649af33c2c750033742dad4d5655a89df58f5c0e | 609,629 |
import configparser
def read_headless_config(file_path: str, dummy_sec_name: str='root') -> configparser.ConfigParser:
"""read a meta file
It is in the worst possible form: a pseudo 'ini' file without headers
Here, I add a dummy section name ['root'] and read it using configparser
Arguments:
f... | f07fd1c91dfb3eab9d404f5025f36baabaaac904 | 609,631 |
def coding_problem_09(numbers):
"""
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers.
The "largest sum of non-adjacent numbers" is the sum of any subset of non-contiguous elements.
Solution courtesy of Kye Jiang (https://github.com/Jedshady).
Examples:
... | cc971c450afa0cd9d384711a0bea98452e09e856 | 609,634 |
def scoreIteration(jsonDump):
"""Helper function to evaluate the overall performance of a single evaluation.
Currently, we evaluate the performance of an iteration based on the harmonic
mean of MI and SC accurcy.
Args:
jsonDump: The jsonDump that is written to the json output file, containing
all ... | 475c262a6fb01330f04512cf4ec42fbd7721eaee | 609,635 |
def split_fn_by_number(fn):
"""split file name by numbers
'[KTXP][Vivy-Fluorite_Eye's_Song-][03][GB_CN][1080p][HEVC_opus]'
->
[
'[KTXP][Vivy-Fluorite_Eye's_Song-][',
'03',
'][GB_CN][',
'1080',
'p][HEVC_opus]'
]
"""
builder = [] # temporate string bui... | a35534fe24a6b4c4eb35f040e9c7a9b3937b569b | 609,636 |
def protobuf_namespace_alias() -> str:
"""Get the protobuf namespace alias."""
return "pb" | b6735cdeaec11f4e6b14cf40929efddf106ce3c1 | 609,637 |
import torch
def depth_to_world(projection, depth):
""" backprojects depth maps to point clouds
Args:
projection: 3x4 projection matrix
depth: hxw depth map
Returns:
tensor of 3d points 3x(h*w)
"""
# add row to projection 3x4 -> 4x4
eye_row = torch.tensor([[0,0,0,1]])... | bd4938732ac679a32b41a7b28e42b16312835170 | 609,639 |
def addChildIfNotPresent(node, childTag, childNode):
"""Add childNode with childTag to node, if no child with that tag is present.
Returns the childNode of node with tag childTag.
"""
for child in node:
if child.tag == childTag:
return child
# No match. Add a child.
node.append(childNode)
... | 28d3cb4c501f5eee9ce7a024d499726e17c0864f | 609,640 |
import json
import yaml
def json_or_yaml_to_dict(string: str) -> dict:
"""Parse JSON/YAML string to dict.
Parameters
----------
string : str
String containing a valid JSON or YAML document.
Returns
-------
dict
Dictionary of the parsed string.
Raises
------
V... | 812654b7f7d56df25b7aa1435a8971d027b054b3 | 609,641 |
def perc_difference(x, y):
"""Calculate percent difference of two values."""
if x == y == 0:
return 0
else:
if x + y == 0:
return 1
else:
return abs(x - y) / ((x + y) / 2) | 1aaa206d1bf951ca48a988cf770a754c185537b8 | 609,647 |
def make_string(n, attname):
"""look for an attribute of a node and returns the attribute, or --"""
if hasattr(n, attname):
val = getattr(n, attname, None)
if val is None:
return '--'
else:
return str(val) | 4e39450b81eac558c92148cc04401b3b67d2b230 | 609,648 |
def indent_lines(
text: str
) -> str:
"""Indent the lines in the specified text."""
lines = text.splitlines()
indented_lines = [f' {line}' for line in lines]
return '\n'.join(indented_lines) | 93a6a9feacbde14d54408fa14783df8bdc2a9178 | 609,649 |
def format_data(account):
"""Format account into printable format: name, description and country"""
name = account["name"]
description = account["description"]
country = account["country"]
return f"{name}, a {description}, from {country}" | 51e6ef001b72877327b78f408e5e3a17270710a4 | 609,650 |
def none_to_zero(x):
"""Return 0 if value is None"""
if x is None:
return 0
return x | 31c4b5382af320ff13d9b54f354c5a1a44476544 | 609,651 |
def get_parameter_for_dev_mode(dev_mode_setting):
"""Return parameter for whether the test should be running on dev_mode.
Args:
dev_mode_setting: bool. Whether the test is running on dev_mode.
Returns:
str: A string for the testing mode command line parameter.
"""
return '--params.... | ded2a4add9ec3ad0dd151dab254b9d3adae50ca0 | 609,653 |
def sqlite_adapt_decimal(decimal):
"""
Adapts ``decimal.Decimal`` types to FLOAT.
"""
return float(decimal) | 21e17536b90ab5d6c32a2522d656a9584f9a3784 | 609,654 |
import threading
def communicateWithTimeout(subProc, timeout=0, input=None):
"""Communicates with subProc until its completion or timeout seconds,
whichever comes first."""
if timeout > 0:
to = threading.Timer(timeout, subProc.kill)
try:
to.start()
return subProc.co... | a4f807fc4d6bdd03a5a1d23e1481a9070693f3c7 | 609,655 |
def data() -> str:
"""
Test data for day_01.
Returns
-------
data: str
"""
data = (
'35\n20\n15\n25\n47\n40\n62\n55\n65\n95\n102\n117\n150\n182\n127\n'
'219\n299\n277\n309\n576'
)
return data | 34211f2e53f9fc6fd604407d1c487b02487cd1a2 | 609,656 |
def ingest_dataset(info):
"""
Create job json for dataset ingest.
Example:
job = {
'type': 'ingest_dataset',
'name': 'ingest_dataset-AIRS.2010.01.01.222',
'params': {
'dataset': 'AIRS.2010.01.01.222'
},
'localize_urls': [
... | c04ec43077fa6bf93f9fd28f932fe38abec55906 | 609,657 |
import hashlib
def sha512_checksum(filename, block_size=65536):
"""
Calculates a SHA512 checksum from a file.
"""
sha512 = hashlib.sha512()
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
sha512.update(block)
return sha512.hexdigest() | 5af6ce896dcef81d86844365ad343fe73210b2e4 | 609,658 |
import functools
def compose_left(*functions):
"""
Compuse functions from left.
Returns
-------
Function
Composed function.
Examples
--------
>>> def a(v_a):
... return v_a+1
...
>>> def b(v_b):
... return v_b*2
...
>>> def c(v_c):
... ... | 49b8d033325c00d9c24347c9119aa823a93d55a5 | 609,659 |
def future_value(interest, period, cash):
"""(float, int, int_or_float) => float
Return the future value obtained from an amount of cash
growing with a fix interest over a period of time.
>>> future_value(0.5,1,1)
1.5
>>> future_value(0.1,10,100)
259.37424601
"""
if not 0 <= interest... | a2a69434c78f29ee15e6c4e00b65746c0327dac5 | 609,660 |
def get_region(reg_str):
"""Transform a string of the form X-Y into a region"""
spl = reg_str.split('-')
if spl[0] == '' and spl[1] == '':
# Fully open region
reg = [0, float('inf')]
elif spl[0] == '':
# Open beginning
reg = [0, int(spl[1])]
elif spl[1] == '':
... | 8425de6c6da10043d386efc5ff417f5f9618a378 | 609,661 |
def path_to_list(path):
"""
Converts a path into a two-dimensional list of coordinates
:param path: A path generated by the functions above, in the form of an iterator over a set of rows,
in which each row is an iterator over a set of (x, y) coordinates
:return: A list of rows, each row a list of (x... | 1f8e0fe24dfc4a02444e8187f2c7a47f27265184 | 609,662 |
def extract_dates(qd):
"""Extract a date range from a query dict, return as a (start,end) tuple of strings"""
start = end = None
# attempt to extract "start", or
# fall back to the None
try:
start = "%4d-%02d-%02d" % (
int(qd["start-year"]),
int(qd["start-month"]),
int(qd["start-day"]))
except: pass
... | 582036b6893b0b441159ffada27d70417275400c | 609,663 |
def get_auto_step_size(max_squared_sum, alpha_scaled, loss, fit_intercept):
"""Compute automatic step size for SAG solver
The step size is set to 1 / (alpha_scaled + L + fit_intercept) where L is
the max sum of squares for over all samples.
Parameters
----------
max_squared_sum : float
... | ecbad7182faa7007ee8e3897b9ac82fd2f29157c | 609,665 |
def not_contains(x, y):
"""
Python's operator module does not have a function for the ``not in`` operator. That's a shame.
"""
return y not in x | a8ffb54de957d385503eeb3863aa656ecefd5a51 | 609,668 |
def get_data_hundred_people(data, population):
"""Get the vaccination data per hundred people."""
# Filter the numerical data to avoid errors
data = data.select_dtypes("number")
return data * 100 / population | f3dcf9f951fee60e4b73a81c6551fb12210f948e | 609,669 |
def dfs(g, s):
"""Depth-first search. Returns list of vertices in order traversed."""
if s not in g.graph:
return []
visited = {s: 1}
out = [s]
stack = []
stack.extend(g.graph[s])
while stack:
n = stack.pop()
if n in visited:
continue
visited[n] = 1
out.append(n)
stac... | 688f85b79e4769b45e48d6b29285a05cb843c103 | 609,673 |
def dtt(f, f_1, f_2, dt):
"""
Second order central difference differentiation in time.
Parameters
----------
f: ndarray
Variable at current timestep t.
f_1: ndarray
Variable at timestep t-dt.
f_2: ndarray
Variable at timestep t-2*dt.
dt: scalar
Timestep.
... | b1a440c654b566a340eb6cb482f03afdda77151e | 609,676 |
def getFileInfo(filename: str):
"""Get file information from filename.
Parameters
----------
filename : str
Filename of CSV file
Returns
-------
date : str
Date of the file
time : str
Time of the file
folder : str
Measurement folder of the file
f... | da81360d7425e27c67465cacbaaf096d6fae7d55 | 609,677 |
def is_deriv_in(coll: list):
"""Check to see if there are any derivatives acting on fields in `coll`."""
for f in coll:
if str(f)[0] == "D":
return True
return False | 867a72b078df6f5830c28c8979186cb700f18ae6 | 609,682 |
from typing import List
def normalize_words(words: List[str], acronyms: List[str]) -> List[str]:
"""Normalize case of each word to PascalCase.
Arguments:
words (list of str): Words to normalize
acronyms (list of str): Acronymes to upper
Returns:
list of str: Normalized words
... | 790846d86cf961d59d1fb3304b3ee4b40a3b1d26 | 609,683 |
import re
def tokenize( string ):
""" Returns a string formatted in snake case. """
token = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', string)
token = re.sub('([a-z0-9])([A-Z])', r'\1-\2', token).lower()
token = re.sub(r"[_\s]+-?", '-', token)
return token | 71c1c30b4fe07ae5fe7e644a6272eceb15f8ff55 | 609,686 |
def get_ngrams(s, ngmin, ngmax, separator="",
bos="<", eos=">", suffix="", flatten=True):
""" For the given sequence s. Return all ngrams in range ngmin-ngmax.
spearator is useful for readability
bos/eos symbols are added to indicate beginning and end of seqence
suffix is an a... | 2d2578b914c7f67f3624b23a8a5c3f7ba26ecc4e | 609,688 |
import torch
def phi(A: torch.Tensor) -> torch.Tensor:
"""Phi operator.
See here for more details https://homepages.inf.ed.ac.uk/imurray2/pub/16choldiff/choldiff.pdf
Parameters
----------
A: torch.Tensor, shape=(B, X, X)
A batched matrix.
Returns
-------
B: torch.Tensor, sha... | faf908c5a66abb7522b2d1eb230ef916ed0d7e2d | 609,689 |
def update_nested_dict(old_dict, new_dict, extend_list_values=False):
"""Update recursively old_dict items with new_dict ones
>>> update_nested_dict(
... {"a": {"a.a": 1, "a.b": 2}, "b": 3},
... {"a": {"a.a": 10}}
... ) == {'a': {'a.a': 10, 'a.b': 2}, 'b': 3}
True
>>> update_nested_... | dbb948d1eb959f75bca1c3d49b7836bae1128483 | 609,691 |
def get_test_methods(testcase):
""" Retrieve a list of test method names from a TestCase instance. """
return [s for s in dir(testcase) if s.startswith('test_')] | 5f6faa48273f5268b1f3cfe5c307c970a5fbd2fa | 609,693 |
from typing import Union
from typing import List
def parse_to_float_list(values: Union[None, float, List[float]]) -> List[float]:
"""Parse to float list."""
if isinstance(values, float):
return [values]
if isinstance(values, list):
return values
return [] | 9f230018d51f1646c52cfeede0a6be1a105bae4a | 609,696 |
def find_folder(folder_list, folder_name):
"""
Check whether there is already a folder named 'folder_name' within the list 'folder_list'. Return its id.
"""
# Check whether a folder with the same name already exists
for folder in folder_list:
if folder['title'] == folder_name:
#... | 1acb4b83ee5773314a37386d4b637a7ccfec17dc | 609,698 |
from typing import Callable
from typing import AnyStr
def combine_formatters(*formatters: Callable):
"""
Combines all formatters into one function that checks if
all formatters return True.
:param formatters: A list of validators
:return: A function that combines all the formatters
"""
d... | c881efad67b05167e639054dc8bb1b0b7e410dcc | 609,699 |
from typing import Any
def identity(x: Any) -> Any:
"""
Returns the same values passed as arguments
>>> x = (10, 20)
>>> identity(x)
(10, 20)
"""
return x | 681581faea47dd613a4e4584954e2dd616b481ff | 609,700 |
def grubler_f(m, n, j, *f_i):
"""
Formular (2.4). Grubler's formula for calculation of Degrees of Freedom (DoF) of a mechanism.
:param m: DoF of a link. For planar mechanisms, m = 3; for spatial mechanisms, m = 6.
:param n: Number of links.
:param j: Number of joints.
:param f_i: DoF brought by ... | c5ed4996b22f3702f45b8b25a0aaea4b0b1cd61f | 609,702 |
def on_events(*events):
"""
Register a method for callback when any of the given events are emitted,
by adding an entry in the class' events dict.
The class the method belongs to must inherit from PluginBase.
:param events: string or iterable containing names of events to listen to
"""
... | b26a8332ebe1e7809e83862ccfbf2b0aa7fd7292 | 609,704 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.