content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def move_drift_to_zero(drift_nm, ref_average=10):
"""
moves to zero the start of the table
:param drift_nm: fxyz table
:param ref_average: how many frames to average to get zero
:return: shifted table
"""
assert drift_nm.shape[1] == 4
assert drift_nm.shape[0] > 0
drift_ref = drift_nm... | 34a42134377ec83ee3b86564f91d407360bab462 | 623,581 |
import re
def find_identity_in_list(elements, identities):
"""Matches a list of identities to a list of elements.
Args:
elements: iterable of strings, arbitrary strings to match on.
identities: iterable of (string, string), with first string
being a regular expression, the second string b... | 597b0e89547046a5ff7746344175ef6c0494b5ad | 623,582 |
import math
def polar_coordinates_to_cartesian(distance, relative_angle):
"""Computes relative x and y for give distance and angle.
Can be used to convert radar measurements to relative position."""
# Here +ve x is towards the left but the angle is +ve clockwise.
return [-1 * distance * math.sin(relat... | b526e7f0166e76cea2e3017dccd47489f7c75638 | 623,583 |
def diff_renorm(image):
"""Maps image back into [0,1]. Useful for visualising differences"""
scale = 0.5/image.abs().max()
image = image*scale
image += 0.5
return image | 18a2295f9a9497a25123195544296115cbdf5413 | 623,584 |
import math
def closed_form_solution(grid_size: int) -> int:
"""Closed form solution for number of routes through a `grid_size`x`grid_size`grid.
Using binomial coefficents in Pascal's triangle.
"""
return math.factorial(2 * grid_size) // math.factorial(grid_size)**2 | 5fe35ae95f20706891e563484808b0ea7fa45df5 | 623,589 |
def remove_inner_brackets(message: str) -> str:
"""Remove the inner brackets i.e., [ or ], from a string, outer brackets are kept.
Parameters
----------
message: str
The string to remove the inner brackets from.
Returns
-------
str:
A new message without any inner brackets.... | 40f8874aa1a621df71d4db6dbc125a25cba20096 | 623,590 |
def NSEW_2_bounds(cardinal, order=["minx", "miny", "maxx", "maxy"]):
"""
Translates cardinal points to xy points in the form of bounds.
Useful for converting to the format required for WFS from REST
style queries.
Parameters
----------
cardinal : :class:`dict`
Cardinally-indexed poi... | fc7710e0e17eaab5d50be21d47944921cad5f6ca | 623,594 |
def _isNumeric(n):
"""test if 'n' can be converted for use in numeric calculations"""
try:
b = float(n)
return True
except:
pass
return False | 902e2e8faf5c2dd804295faad3f00d9610f5e867 | 623,596 |
import re
def get_valid_filepath(s: str) -> str:
"""Convert a string to a safe-to-use string for naming file.
Parameters
----------
s : str
The given strings
Returns
-------
str
The safe string
Note
----
Adapated from django get_valid_filename function:
h... | d758db7136962c3107ce44b25a41d51bf213a7b8 | 623,598 |
def pyyaml_path_representer(dumper, instance):
"""Helper method to dump :class:`~pathlib.Path` in PyYAML."""
return dumper.represent_scalar('Path', f'{instance}') | 3755b6a581a498658ea3df2ad6420b3e506fd521 | 623,601 |
def eratosthenes_sieve(n):
"""Return primes <= n."""
def add_prime(k):
"""Add founded prime."""
primes.append(k)
pos = k + k
while pos <= n:
numbers[pos] = 1
pos += k
numbers = [0] * (n + 1)
primes = [2]
for i in range(3, n + 1, 2):
i... | 6b629554fddc786f6694ac0de769de1c40b7fb0e | 623,603 |
import torch
def jvp_diff(y, x, v):
"""Computes a jacobian-vector product J v, aka Rop (Right Operation)
This is what forward-mode automatic differentiation directly obtains.
The result of the operation can be differentiated.
Arguments:
y (torch.tensor): output of differentiated function
x (t... | 0917c3c9f2b9047838702fd25f99258535fd9d0f | 623,604 |
def chomp(x):
"""Remove any trailing line terminator from 'x' and return that."""
if x.endswith("\r\n"): return x[:-2]
if x.endswith("\n") or x.endswith("\r"): return x[:-1]
return x | 12a9d1053dbc1b556ee5f83407d34ee12cc521be | 623,605 |
def pad(values, width):
"""Format a list of values to a certain width"""
values = [ str(data) for data in values ]
return ''.join([ data + (' ' * (width - len(data))) for data in values ]) | de12a253d75e72451a2a8934144f1cba3a1471e5 | 623,606 |
def get_task_pairs(data_list, task):
"""Get a list of [input path, output dictionary] pairs where each
element of the list has at least `task` as a key in the output dictionary.
"""
task_pairs = []
for input_file, task_dict in data_list:
if task in task_dict.keys():
task_pairs.ap... | 69311ba82b5cba70ac3a624314ff8e7b1f6397e3 | 623,608 |
import inspect
def get_module_name(file_path):
"""Returns module name or '' for file at `file_path`"""
return inspect.getmodulename(file_path) if file_path else '' | 8a3d1e6f490efaec6a5d1256a0ef87d00fa7eeda | 623,613 |
import tempfile
def tmpfile (dir=None, prefix="temp", suffix=None):
"""Return a temporary file."""
return tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)[1] | 32a8e122142f6e4c60e449b7c4b9346e6888e355 | 623,617 |
def make_rep(req, body=None):
"""Utility which creates a reply object based on the headers in the request
object."""
rep = { 'head': { 'seq': req['head']['seq'] +1,
'cmd': req['head']['cmd'],
'rSeq': req['head']['seq'] }}
if body:
rep['body'] = body
... | d96c1c576943a3620af431303e115c59b01821d6 | 623,619 |
import ast
from typing import Optional
def get_context(node: ast.AST) -> Optional[ast.AST]:
"""Returns the context or ``None`` if node has no context."""
return getattr(node, 'wps_context', None) | 4d923b8395d3ce840eb92a194b0276f997620103 | 623,620 |
def format_list2(list1, sfmt = '%16s', nfmt = '%16.8e', delimiter = ','):
"""
format list of numbers or strings to a delimited string.
Parameters
----------
list1 : list of numbers and strings
List to convert to string
sfmt : str
string formatter, ie "%16s"
nfmt : str
... | cd2fb09fae195077e185391e9ef239d2bf795818 | 623,624 |
def guidance_UV(index):
"""Return Met Office guidance regarding UV exposure based on UV index"""
if 0 < index < 3:
guidance = "Low exposure. No protection required. You can safely stay outside"
elif 2 < index < 6:
guidance = "Moderate exposure. Seek shade during midday hours, cover up and we... | 07e1544a9f2683457d79ec9f0d9e84b7640d9d9c | 623,625 |
def tree_observation_probability(state, observation):
"""
Measurement model for a single Tree element for the LatticeForest.
Returns a probability of the combination (state, observation).
"""
measure_correct = 0.9
measure_wrong = 0.5*(1-measure_correct)
if state != observation:
retur... | 7edfd4d88e983f92cfeaa43509acde3664e261e7 | 623,628 |
def hex_to_dec(val):
"""Converts hexademical string to integer"""
return int(val, 16) | d8aa6a18f4c76b65feca1b3db38241e4a7b30bb9 | 623,629 |
import re
def get_valid_filename(s):
"""
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove anything that is not an alphanumeric, dash,
underscore, or dot.
>>> get_valid_filena... | 6561030d1e444e8fd5121636ec08d561433ce73c | 623,635 |
def is_json(fname):
"""
Returns True for string, enclosed with '[' ']', False else
"""
if str(fname) and (str(fname)[0] == "[") and (str(fname)[-1] == "]"):
return True
return False | f4ff9e4cb671d56c13ab0014d1b97bd41bba9d7c | 623,637 |
def ensure_all_mixing_vars_are_in_the_name_dict(mixing_vars,
name_dict,
ind_var_names):
"""
Ensures that all of the variables listed in `mixing_vars` are present in
`ind_var_names`. Raises a helpful ValueError if... | 377283d45fe51b3723fb84c176e4f54e3c60e9c4 | 623,639 |
def countwhile(predicate, iterable):
"""
return count of leading characters that satisfy the predicate
"""
count = 0
for character in iterable:
if predicate(character):
count += 1
else:
break
return count | c9f24a72ac3c6b878932bd98f09122f3c464bc55 | 623,641 |
def auth_str_equal(provided, known):
"""Constant-time string comparison.
:params provided: the first string
:params known: the second string
:returns: True if the strings are equal.
This function takes two strings and compares them. It is intended to be
used when doing a comparison for authe... | bc193ac7648fa5679c2bf33be10ef1dc2723c7f4 | 623,643 |
import re
def get_header(header):
"""
Extract key parts of image headers from the header of fabio-opened file and return them as a list. A list of wavelength, pixel size, detector distance, the x and y beam center, and exposure time are returned in that order.
"""
h = header['_array_data.header_contents']
wavele... | 5beae1c86a1e98bd91563fe2895d7b8d32a4e93a | 623,645 |
import json
def output_fn(predictions, content_type):
"""Post-process and serialize model output to API response"""
print('result:', predictions)
res = predictions.cpu().numpy().tolist()
return json.dumps(res) | f0c22dcd7e5a447b38afd141d6de7d16028fc670 | 623,646 |
def slice_at_axis(sl, axis):
"""
Construct tuple of slices to slice an array in the given dimension.
Parameters
----------
sl : slice
The slice for the given dimension.
axis : int
The axis to which `sl` is applied. All other dimensions are left
"unsliced".
Returns
... | 63ff4ca38924065567596285c36f5ad040c88970 | 623,648 |
def unit_range(arr, data_min=None, data_max=None, samples_in='row'):
"""
Normalize the data to have unit range. Return the normalized data, and
the min, and max used.
Data is assumed to be in row samples
If data is arranged in column samples, use samples_in='col'
Computes norm_arr = (arr - d... | 0e1aaa75f6343fdfcdbe2bcf1e164925de18dc83 | 623,659 |
from typing import Tuple
def get_file_type(image_path: str) -> Tuple[str, str]:
"""
Return the image file types.
Return
------------
[file_ext, file_type]
file_ext: .png, .jpeg, .jpg etc.
file_type: this is the MIME file type e.g. image/png
"""
file_ext = image_path.split(... | b1370f0b126842ec23224fd7cea33e8d3ed2a06a | 623,660 |
def hyphenate(value, arg):
"""Concatenate value and arg with hyphens as separator, if neither is empty"""
return "-".join(filter(None, [str(value), str(arg)])) | 484ef6e754a8c08fbd49533c50a4728a88b40c48 | 623,661 |
import inspect
def outer_args(skip_self=True) -> dict:
"""Get the arguments of the func within which this function is called.
Args:
skip_self (bool):
True: skip the argument named `self`
False: doesn't skip the argument named `self`
"""
currframe = inspect.currentframe... | cb4ccb6e1d4dc5f0f231e6b737cb7d4d1b097128 | 623,662 |
def numwrap(n, nmin, nmax):
"""最小値、最大値の範囲内でnの値を返す。
n: 範囲内で調整される値。
nmin: 最小値。
nmax: 最大値。
"""
if n < nmin:
n = nmin
elif n > nmax:
n = nmax
return n | f1ed3012ec34c917020edb419a575fa430d32520 | 623,667 |
def _GenerateMapperConstructor(transformer_class_name):
"""
Public constructor generation for the mapper.
"""
code = [
"\n\npublic Mapper({0} parent, DataViewSchema inputSchema) :".format(transformer_class_name),
"\nbase(parent.Host.Register(nameof(Mapper)), inputSchema, parent)",
... | 179de0599916ed3c0afc0ba67ed18d833e6e8b0c | 623,670 |
import math
def _non_finite(num):
"""Is this number not finite?"""
return math.isnan(num) or math.isinf(num) | a3075df3ea3276edd9798a975497ddd358c2f48e | 623,671 |
def _FormatProjectIdentifierForTransfers(project_reference, location):
"""Formats a project identifier for data transfers.
Data transfer API calls take in the format projects/(projectName), so because
by default project IDs take the format (projectName), add the beginning format
to perform data transfer comman... | c662a9bf5dda81be64c8fad00763f40b9d44241f | 623,672 |
import math
def offset_point_with_distance_and_bearing(lat, lon, distance, bearing):
"""
Get the new lat long (in degrees) given current point (lat/lon), distance and bearing
returns: new lat/long
"""
# Earth's radius in meters
radius = 6378137
# convert the lat long from degree to radia... | a2c61e9a0a8ffd1a0de6296b8d4ddc97171b6d14 | 623,675 |
def domain(x, y, s_w, s_h):
"""
The function estimates the rectangle that includes the given point.
Arguments:
x and y coordinates of the point and width and height of the screen
Return:
integer 0 <= n <= 5
"""
if x < s_w / 3:
return 0 if y < s_h / 2 else 3
if... | 0b505fce343b2ef49e96fd4857176692dcef70a8 | 623,680 |
def _merge(iterable):
"""Merge multiple items into a single one separating with a newline"""
return "\n".join(iterable) | 7e98de23500b449b50b4b55ae433b871f21a504e | 623,684 |
def _package_exists(module_name: str):
"""Check if a package exists"""
mod = __import__(module_name)
return mod is not None | 3ee3dcc147d988422d54adf4420b07dae24d3cb2 | 623,687 |
import re
def _parse_address(addr='XFD1048576') -> str:
"""
Parses the address given using a regexp and returns a cleaned string that can be split
Accepts any valid excel cell address definition, incl. absoulte adresses with $.
:param addr:
:return:
"""
patt = re.match(r'^(\$?[A-Z]{1,3}\$?... | e6559118345ee254901da2c0019dff3dcd140f33 | 623,694 |
import itertools
def generate_swapped_match(match, klass):
"""
Generate a new OpenFlow match with source and destination fields swapped
:param match: OpenFlow match
:param klass: Match class
:return: Swapped match
"""
def get_args(m):
args = {}
for key, arg in m.items():
... | 2e2c9988fe10a764c126cb6d146729ce3ab49f28 | 623,695 |
def get_relative5_positions(brc5):
"""Get relative positions of barcode nucleotides from 5'end."""
return list(range(0, len(brc5))) | cd983a9ac628622438375f28234cc964268338fd | 623,696 |
def averageListEntry(datalist):
"""
Return the average value of a Python List
:param datalist:
:return: average of list
"""
return sum(datalist)/len(datalist) | 300cfc7e73d28d9868d586e952637ed929129f72 | 623,697 |
def add_vecs(vec1, vec2):
""" Return the vector sum of vec1 and vec2 """
return [vec1[0] + vec2[0], vec1[1] + vec2[1]] | b623a2fdcea99ce2a497dc320c5479edb4d776b9 | 623,701 |
def ConvertAsci(L):
"""Converti les éléments d'une liste de lettres en entiers.
Cette fonction converti une liste de caractères en une liste d'entier correspondant à leur code ascii.
Parameters
----------
L : list
`L` est une liste de caractères.
Returns
-------
La : list
... | 9bc6d68badb1d25fa5f31abf0fc4430d1c3cd4bf | 623,702 |
def ipstr(barray):
"""Print a string of ip digits"""
return ".".join('{}'.format(x) for x in barray) | ebdc86d772e0879f7f1ef48cb3bc4eb18408290f | 623,703 |
def parse_zone_id(full_zone_id):
"""Parses the returned hosted zone id and returns only the ID itself."""
return full_zone_id.split("/")[2] | b4eebcc0bab022df77478b98d7c88a08e6adca1d | 623,705 |
def guess_num() -> str:
"""
049
Create a variable called comp_num and set the value to 50. Ask the user to enter a number. While their guess
is not the same as the comp_num value, tell them if their guess is too low or too high and ask them to have
another guess. If they enter the same value as comp... | 3467316d23498cca220987b3e0004973010f8901 | 623,708 |
def get_rank_function(rank_method):
"""
Gets the function to calculate the rank of a entity based on the
`rank_method`. The function receives two inputs: (1) the number of entities
whose rank is greater than the rank of the target entity; (2) the number
of entities whose rank is equal to the rank of... | 41fd973acccdeaa6b3e8e3af06cdf013a00c2319 | 623,711 |
def diff_between_angles(angle_a: float, angle_b: float) -> float:
"""Calculates the difference between two angles angle_a and angle_b
Args:
angle_a (float): angle in degree
angle_b (float): angle in degree
Returns:
float: difference between the two angles in degree.
"""
de... | 211da9702c651761a41a4de495cb379be14847d3 | 623,715 |
def c(units):
"""Speed of light
Parameters
----------
units : str
Units for c. Supported units
===== ===================== ===========
Unit Description Value
===== ===================== ===========
m/s Meter per second... | 705f4958510411fc6ec390da346d63f594bd7d36 | 623,720 |
def parse_line(line):
"""
Parse $VNYMR message:
Yaw float deg Calculated attitude heading angle in degrees.
Pitch float deg Calculated attitude pitch angle in degrees.
Roll float deg Calculated attitude roll angle in degrees.
MagX float Gauss Compensated magnetometer ... | 08662d3e91dbf2f9d527fc6c7f00214471c3b96f | 623,721 |
import random
def get_gif() -> str:
"""Returns a random GIF"""
gifs = [
'https://media.giphy.com/media/lZqlpPlT9llVm/giphy.gif',
'https://media.giphy.com/media/26FPzWoJlFvXyiZ6E/giphy.gif',
'https://media.giphy.com/media/9hqsyNVlf0DOU/giphy.gif',
'https://media.giphy.com/media/... | 7c7cbf1f19ac2c9db7d4c1f74c4e9110b0901d0d | 623,727 |
from pathlib import Path
def _fetch_dirs(bucket, prefix=None):
"""Return set of all directory paths within a GCS bucket blob names
Parameters
----------
bucket : google.cloud.storage.bucket.Bucket
Returns
-------
all_dirs : set
"""
all_dirs = set([])
for blob in bucket.list_bl... | 32183e449ed52c4fdb49b2992eb398e06bb63318 | 623,728 |
def find_key(dict_obj, key):
"""
Return a value for a key in a dictionary.
Function to loop over a dictionary and search for an specific key
It supports nested dictionary
Arguments:
dict_obj (obj): A list or a dictionary
key (str): dictionary key
Return:
(li... | ebe1a9dd68c045103c6e76969c77cba41cb0e683 | 623,734 |
def control_key_name(code):
"""Prefix the name of a control key with '^'"""
name = chr(code - 1 + ord("A"))
return f"^{name}" | 2f03c47fb1c0f2374ba892dbd2752a76abf28e75 | 623,736 |
import copy
from functools import reduce
def Gal_NLFSR(R, FF, ZF, N0):
"""Run Galois NLFSR
Parameters
----------
R : int
the number of output bits
FF : list
feedback functions of the Galois NLFSR
ZF : list
output function of the Galois NLFSR
N0 : list
initia... | 1e43c1ad53fe9375cbfc158bea5d7088d9cb7423 | 623,741 |
import time
def ago(past_timestamp):
"""
Returns a string, the number of days, hours, minutes, or seconds ago a timestamp is.
Example output:
5h30m ago
3d5h ago
2m30s ago
"""
time_diff = int(time.time() - past_timestamp)
time_diff_units = []
... | f457adc8b8ebe49ee8b433d2d76e6adff91a854a | 623,742 |
def hg_repo(repo):
"""
Tests if a repo URL is a hg repo, then returns the repo url.
"""
if repo.startswith('https://bitbucket.org/') and not repo.endswith('.git'):
return repo
if repo.startswith('http://hg.'):
return repo
# not hg
return None | e235b9daa2695a9922090fae4013519d44669e12 | 623,743 |
import re
def parse_component(comp):
"""Parse "10 ORE" -> (10, 'ORE')."""
m = re.match(r'(\d+) ([A-Z]+)$', comp)
assert m, comp
amt, what = m.groups()
return int(amt), what | df17c10c37ce0ed9e096d8954b1cef9b19730443 | 623,744 |
def enact_interventions(background_inmate_turnover, background_release_number, time, infected_list, release_number,
social_distance, social_distance_tau, stop_inflow_at_intervention, tau):
"""Enacts specified interventions."""
# Print intervention info
print(f'Release intervention co... | 2816a9670d25c281642461256d2e464c9d4274c1 | 623,745 |
def calc_RMM_phase(RMM1, RMM2, amp_thresh=0):
"""
Given RMM1 and RMM2 indices, calculate MJO phase.
Provided by Zane K. Martin (CSU).
Args:
RMM1: EOF for MJO phase space diagram.
RMM2: EOF for MJO phase space diagram.
amp_thresh (int): MJO amplitude threshold. Defaults to 0.... | a8aa9a860c1d3545b88d44e3433b6717df9a9760 | 623,747 |
def parse_bbox(bbox):
"""Given PDFMiner bbox info as a comma-delimited string, return it as a list of floats."""
return list(map(float, bbox.split(','))) | a3a6fb3ce6ce99000e0bdd06728558176d105086 | 623,748 |
def d_perspective_camera_d_shape_parameters(shape_pc_uv, warped_uv, camera):
"""
Calculates the derivative of the perspective projection with respect to the
shape parameters.
Parameters
----------
shape_pc_uv : ``(n_points, 3, n_parameters)`` `ndarray`
The (sampled) basis of the shape m... | 5d796388845cd87f6fb7625352c799a46ef6f354 | 623,750 |
import random
def v(N=50,min=-10,max=10):
"""Generates a random vector (in an array) of dimension N; the
values are integers in the range [min,max]."""
out = []
for k in range(N):
out.append(random.randint(min,max))
return out | b4457732e048b1c6cafdfd1b771f160d083a68d3 | 623,755 |
def remove_non_printable_characters(string):
"""
Eliminates from the input string all the characters that are not printable.
"""
return ''.join(char for char in string if char.isprintable()) | 88975b90e6d606eb504996db399cd41295fed210 | 623,763 |
import itertools
def has_fset_with_last(f, b, g):
"""Return True if g contains f-set of order b containing vertex n-1.
Arguments:
f -- predicate
Given a graph and a subset of its vertex set, returns bool.
g -- graph
b -- nonnegative int
We search for an order-b f-set.
See isograp... | 8731cc3c2138f1e87b6e67107b2f93ebdc927c00 | 623,764 |
def gen_targets(polynomial_fn, data):
"""Generate targets (ground truth) from polynomial"""
return [polynomial_fn(instance) for instance in data] | 5214d63d51921563c320441cfb1c4967b257006b | 623,765 |
def celsius_to_fahrenheit(celsius):
"""
Celsius to Fahrenheit
:param celsius: Degrees Celsius
:return: Fahrenheit
"""
return float(celsius) * 9.0/5.0 + 32 | 8ff05c95a1f8029a7fc73e5b834bcf9d614d7922 | 623,778 |
def is_valid_mask(mask):
"""
Validates a UNIX style permissions mask. Mask must be octal.
:type mask: str
:param mask: The octal mask to be validated. For example: '0755'.
:rtype: bool
:return: True or False depending on whether mask passes validation.
"""
if mask is None:
re... | a112efd59367c3b57c98df38429ef8bd933dc0fa | 623,779 |
def get_os_data_from_box_title(box_title: str) -> tuple:
"""
Gets OS name and version from a properly formatted box title.
Returns:
(str, str): OS name, OS version
"""
# Split box title into [os name, os version]
box_title_elements = box_title.split(" v")
return box_title_elements[... | a103a4c5690d8a7c544741671a8e6221618bda94 | 623,780 |
import json
def read_json(file):
"""
Loads JSON data from file
Arguments:
file: the path to the JSON file
Return:
the dictionary with parsed JSON
"""
with open(file) as f:
data = json.load(f)
return data | 9e2c7d215541e346747317fbef5ed8e0b37d99a4 | 623,785 |
def flatten(data):
""" Flatten list of tuples or tuple of tuples
Args:
data (list or tuple): list/tuple of data to flatten
Returns:
list: flattened list
"""
result = []
for var in data:
if isinstance(var, tuple):
result = flatten(var)
else:
... | 114dc37108f3e3c88860a17b3e8922f34ae1a4b6 | 623,786 |
def CFE_mu(theta, l_tilde, n):
"""
Marginal disutility of labor supply from the constant Frisch
elasticity utility function
Args:
theta (scalar): inverse of the Frisch elasticity of labor supply
l_tilde (scalar): maximum amount of labor supply
n (array_like): labor supply amoun... | 12c41be91ab9150e4e1b5330b6733b0cf4c59ac9 | 623,789 |
import re
def render(template, **params):
"""Replace placeholders in template with values from params."""
return re.sub(r'{{\s*([^}\s]+)\s*}}',
lambda match: str(params.get(match.group(1), match.group(0))),
template) | f8243284f13fd63ee82d65f2c1c30b0466d76947 | 623,791 |
import hashlib
def blake2b_hash(b: bytes) -> bytes:
"""
blake2b_hash hashes the given bytes with BLAKE2b (optimized for 64-bit platforms)
Args:
b (bytes): bytes to hash
Returns:
bytes: The hash result
"""
return hashlib.blake2b(b, digest_size=32).digest() | 6c41dcd2385440378c94e3f7b9694ccf19b9384e | 623,792 |
import math
def format_bytes(input_bytes, precision=2):
"""
Format an integer number of input_bytes to a human
readable string.
If input_bytes is negative, this method raises ArithmeticError
"""
if input_bytes < 0:
raise ArithmeticError("Only Positive Integers Allowed")
if input... | 29fd2c3577e830cb7ad8800ab32073eecd87b952 | 623,797 |
import logging
def setupLogging(logfileName, logFormat, logLevel, logToConsole=True):
"""
Setup simultaneous logging to file and console.
"""
# logFormat = "%(asctime)s %(levelname)s %(funcName)s:%(lineno)d
# %(message)s"
logging.basicConfig(filename=logfileName, level=logging.NOTSET,
... | b2f31e4f3916df792c0cae4bbdc95e7336918751 | 623,801 |
def col_filter_dict_with_vals(df, col, field, values):
"""Filter dictionaries with specific values from a column with lists of dictionaries
Args:
df(pd.Dataframe): dataframe
col(str): column name
field(str): field of the dictionary to extract
values(list)... | 7c41f96f8fd81168b3a05c2eae257554ee407047 | 623,802 |
def deserialize_grid(serialized):
"""Deserialize a serialized grid.
Arguments:
serialized (str): Serialized representation of a grid of integers.
Returns:
list of lists of ints
"""
return [list(map(int, row.split())) for row in serialized.split('\n') if row] | 0c93252823206feee4c464086fe159965662e730 | 623,804 |
def discard_console_entries() -> dict:
"""Discards collected exceptions and console API calls."""
return {"method": "Runtime.discardConsoleEntries", "params": {}} | c8e7d528fe47286334fb1d64bf99d2144415bc4e | 623,808 |
def user(request):
"""Return db user."""
return request.config.getoption("--user") | cf3e5662f23849c82277bebdb1f64599dea08127 | 623,810 |
def digitsToStr(digitNum, base=10):
"""
Convert list of digits (in specified base) to a string suitable for printing
"""
if base <= 10:
return ''.join(chr(d + 48) for d in digitNum)
elif base <= 36:
def _char(d):
if d < 10:
return chr(d + 48)
else:
return chr(d + 55)
re... | 883624a4ea3696d41fbbef9bced500d52d10d191 | 623,813 |
def byte(val, fmt="{:.2f}"):
"""Returns a byte representation of the input value
:param val: value to format, must be convertible into a float
:param fmt: optional output format string, defaults to {:.2f}
:return: byte representation (e.g. <X> KiB, GiB, etc.) of the input value
:rtype: string
... | 43ac7caa748d6902c4bf5bc2af12a379853a5a44 | 623,814 |
def set_bit(number, offset):
"""Set the `offset` bit in the binary representation of `number` to 1"""
return number | (1 << offset) | 9f7940777a9d38742995496590a0fc4b966557ee | 623,819 |
def map_palette(station):
"""
Function that returns the colour of a given station to use on the map, depending on the relationship between latest level and typical range.
Args:
station (MonitoringStation): The station.
Returns:
str: One of
* 'gray' - typical range not cons... | 6d53a47400edcecef113a3f1fcbdc0b6695886e5 | 623,824 |
def momentum_averager(momentum=0.9):
"""First order running averager with momentum.
y_n = momentum*y_{n-1} + (1-momentum)*x_n"""
def avg():
y = yield
while True:
x = yield y
y = momentum*y + (1-momentum)*x
return avg | db29baaf9280be6259178d1ac1c8a2b40d2516cb | 623,825 |
def unpack_bitmap(num):
"""
Unpact bitmap to indicate which cores are set.
For instance 11d = 1011b = [3,1,0]
"""
bit_length = num.bit_length()
return set(idx for idx in range(bit_length) if 2**idx & num) | 582fb8aa996bae2a7b0d7029934a6a5d7c19ddf3 | 623,828 |
def get_next_set_offset(context, matching_sets):
"""Get the set search offset for the next query."""
# Set the next offset. If we found all matching sets, set the offset to 'done'
if len(matching_sets) == 8:
return f"{context.inline_query_id}:{context.offset + 8}"
# We reached the end of the st... | 8033da435674ac90d7442a79744642e28b1a23ad | 623,831 |
def _check_git_access(req, dataset):
"""Validate HTTP token has access to the requested dataset."""
user = 'user' in req.context and req.context['user'] or None
# Check that this request includes the correct token
if user != None and 'dataset:git' in user['scopes'] and user['dataset'] == dataset:
... | 61c027d637f7040e33d64f0799c993c5c979827c | 623,836 |
def first_line(s):
"""Return first full line from string s (not including the '\n')
"""
i = s.find('\n')
if i > 0:
return s[:i]
else:
raise RuntimeError("can't find '\\n' in first_line") | d6b7a7e1315723b9b8965adcbd24bce2cc588715 | 623,839 |
def scrapeFloorplanSoups(soup):
"""Returns a list of soups, one per floorplan"""
obj = soup.find('table', class_='availabilityTable')
if obj is not None:
floorplans = obj.find_all('tr', class_='rentalGridRow')
if floorplans is not None:
return floorplans
return [] | a52bc5aeb28eb67da87cfc6d64fca5932af3a2e8 | 623,840 |
def get_filter(main_data, filtername='Month'):
"""Get filter params."""
filters = main_data[filtername].unique()
return filters | 912bb311ff05c9ccb327c329896855c1d9fc121c | 623,841 |
def dict_contain(dict_a, dict_b):
"""Test if all the key:value pairs of dict_b are in dict_a.
Arguments:
dict_a -- The dictionary
dict_b -- The sub-dictionary
Return:
True if all the key:value pairs of dict_b are in dict_a,
False otherwise
"""
if len(dict_b) > len(dict_a): return... | 6f44f1bb80c641362bca52fed3fe343a5d9bcdfc | 623,845 |
def get_mol_coordinate(conformer):
"""
Get the coordination vectors of the molecule.
:param conformer: Rdkit.Conformer.
:return:
np.array, The numpy array of the coordinates for the conformer.
"""
return conformer.GetPositions() | 301443dc724c94ba09ae44e4ab39a7a6fe0b6866 | 623,846 |
def _get_demographics_adjusted_to_contact_matrix_agebins(P_AGE, POPULATION_SIZE):
"""
Given that we are aggregating data from various sources, it is required that we adjust for the underlying assumptions.
One of these structural assumption is of age groups. Contact matrices available consider only 16 classe... | c91797a57c98ce21ae241d3f706c03763db37224 | 623,847 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.