content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import torch
def generate_measure(n_batch, n_sample, n_dim):
"""
Generate a batch of probability measures in R^d sampled over
the unit square
:param n_batch: Number of batches
:param n_sample: Number of sampling points in R^d
:param n_dim: Dimension of the feature space
:return: A (Nbatch,... | 86edea6ac97052a928c854d803a80910beab2881 | 192,069 |
def married_type(mdata):
"""return whether there are modulators or durations
(need only check first non-empty element, as consistency is required)
return a bit mask:
return 0 : simple times
return 1 : has amplitude modulators
return 2 : has duration modulators
... | 6d128e13797f934527fe070c3832f5f4ddba066d | 449,449 |
from typing import Optional
from typing import Dict
def get_env_variables(
edgedb_host: str,
edgedb_password: str,
edgedb_tls_ca: str,
github_application_id: str,
oauth_application_id: str,
oauth_application_secret: str,
server_url: str,
application_secret: str,
organization_name: ... | 2e985d32005982a36ead32938b63511d85b004d8 | 361,493 |
from typing import Counter
def local_prf(pred_list, ref_list):
"""
Compute local precision recall and f1-score,
given only one prediction list and one reference list
"""
common = Counter(pred_list) & Counter(ref_list)
num_same = sum(common.values())
if num_same == 0:
return 0, 0, 0... | 0f7eb5ff0df4288765ffc16cddf798eb96e68951 | 358,781 |
def actions_by_behavior(actions):
"""
Gather a dictionary grouping the actions by behavior (not SubBehaviors). The actions in each
list are still sorted by order of their execution in the script.
@param actions (list) of Action objects
@return (dict) where the keys are behaviors and the values are... | ebf97a5837a8d7de735207c5df5e19af2438510a | 697,839 |
import hashlib
def get16ByteUUID(uuid):
"""
Return a 16 byte has of the UUID, used when smaller unique
ID is required.
"""
return hashlib.md5(uuid).hexdigest()[:16] | 1e27479b2ac7c3c7aaaf5b30916265753e86b780 | 569,628 |
import math
def make_jc_matrix(t, a=1.):
"""
Returns Juke Cantor transition matrix
t -- time span
a -- mutation rate (sub/site/time)
"""
eat = math.exp(-4*a/3.*t)
r = .25 * (1 + 3*eat)
s = .25 * (1 - eat)
return [[r, s, s, s],
[s, r, s, s],
[s, s, r, s],... | 12f0c30732db909930201ba7ff26c78c38ea4f4a | 672,772 |
def _capture_callback(x):
"""Validate the passed options for capturing output."""
if x in [None, "None", "none"]:
x = None
elif x in ["fd", "no", "sys", "tee-sys"]:
pass
else:
raise ValueError("'capture' can only be one of ['fd', 'no', 'sys', 'tee-sys'].")
return x | 79a905c5793fabe43475ecc8a46c162f01060250 | 683,372 |
def get_degree_cols(df):
"""
Take in a pandas DataFrame, and return a list of columns
that are in that DataFrame AND should be between 0 - 360 degrees.
"""
vals = ['lon_w', 'lon_e', 'lat_lon_precision', 'pole_lon',
'paleolon', 'paleolon_sigma',
'lon', 'lon_sigma', 'vgp_lon', ... | 17dce72df59b186f3f864aefdc2eedf88d381127 | 66,934 |
def formToDict(form, exclude=()):
""" Returns a dictionary from the given form/ProtoRPC Message """
return {field.name: getattr(form, field.name) for field in form.all_fields() if field.name not in exclude} | 87a1957d6259e1adc427e4fcd05032c74819b039 | 461,889 |
def check_match(issue, patterns):
"""Check if any pattern matches the given issue
:param issue: issue to match against
:type issue: dict
:param patterns: patterns to try to match
:type patterns: list
:return: True if any pattern matches
:rtype: bool
"""
for item, rgx in patterns... | 31e00395344134df47a8d5613eb32a374eea378b | 360,591 |
def checkTestCaseSuccess(output):
""" Searches the output of the GDB script for incentives of failure """
incentives = ["error", "fail", "unexpected", "cannot"]
for word in incentives:
if output.lower().find(word) != -1:
return False
return True | f3fce44219999030f6f01cc77a0b084dbdde09c0 | 505,406 |
def shader_source_with_tex_offset(offset):
"""Returns a vertex shader using a texture access with the given offset."""
return """#version 150
uniform sampler1D tex;
void main() { vec4 x = textureOffset(tex, 1.0, """ + str(offset) + "); }" | 3a8764e74f588afbfb983db7ab5dd86a4e61b5c9 | 125,745 |
def total_ret(x):
"""
Calculates Total cumalative Return
"""
return (x.add(1).prod() - 1) * 100 | 5bddf551fa2293749f576fc06028a3fc5d177543 | 607,019 |
def to_plugin_config(cp_inst):
"""
Helper method that transforms the configuration dictionary gotten from the
passed Configurable-subclass instance into the standard multi-plugin
configuration dictionary format (see above).
This result of this function would be compatible with being passed to the
... | 41993c9af895bf147c99afee5adca7540f2f5e75 | 531,424 |
def _publications_urls(request, analyses):
"""Return set of publication URLS for given analyses.
Parameters
----------
request
HTTPRequest
analyses
seq of Analysis instances
Returns
-------
Set of absolute URLs (strings)
"""
# Collect publication links, if any
... | f60efb37c9603d614f8cf0fa9c53657235d0a156 | 666,609 |
from datetime import datetime
def create_modif_log( doc,
action,
dt = datetime.utcnow(),
by = None,
val = None,
) :
"""
Create a simple dict for modif_log
and insert it into document
"""
### store modification
modif = {
"modif_at" : dt,
"modif_for" : action ... | 7a2625fce27b561437692741acdca7d1a32f2c52 | 472,143 |
def get_file_contents(file):
"""
Utility function to read contents of a file.
Will only read files in current path
:param file: Specifies the file to read
:return: File contents
"""
return open(file).read() | e05584bfff223acd6536a08519eda68d59d9fe9f | 315,027 |
import random
def distinct_permutation(sequence):
"""
Returns a permutation of the given sequence that is guaranteed to not be the same
order as the given input.
"""
assert len(sequence) > 1, "there is no distinct permutation for this input"
original = list(sequence)
result = original.copy... | 00fc54ea0a2b3f1f5a775be70a3075d6dc576f99 | 124,322 |
def str2boolean(string):
"""
Converts the parameter to a boolean value by recognising different
truth literals.
"""
return (string.lower() in ('yes', 'true', '1')) | 489521a4af89b061674e69de483b6f51b87cea34 | 588,767 |
import random
def mpda_cxPartialyMatched(ind1, ind2):
"""Executes a partially matched crossover (PMX) on the input individuals.
The two individuals are modified in place. This crossover expects
:term:`sequence` individuals of indices, the result for any other type of
individuals is unpredictable.
... | 8a20c7778e690205ffd5b85000400d1b648f32f5 | 559,723 |
def wrap_angle(x):
"""Wraps an angle between 0 and 360 degrees
Args:
x: the angle to wrap
Returns:
a new angle on the interval [0, 360]
"""
if x < 0:
x = 360 - x
elif x > 360:
x = x - 360
return x | 011c21fb4354ce9462196da6a0c971d9c5f83dc7 | 601,899 |
def _group_ccs_with_issuetracker(ccs_payload, ccs_issuetracker):
"""Group ccs from ggrc system and issuetracker.
Args:
- ccs_system: CCs on Issue Tracker Payload
- ccs_tracker: CCs from Issue Tracker
Returns:
list of grouped ccs from ggrc and issuetracker.
"""
ccs_system = set(cc.strip() for c... | e43265bca4eb7047aa9ab2f2ed0c49fabb0b5ed2 | 619,000 |
def outer_product(features):
"""InterProduct: Get inter sequence product of features
Arguments:
features: feature vectors of sequence in the shape of (n, l, h)
Return:
f: product result in (n, l, l, h) shape
"""
n, l, c = features.shape
features = features.contiguous()
x = fe... | d8bce915a7b935f5de0861b52508e6c2b72052cb | 172,736 |
import torch
def label_to_onehot(labels, num_classes=10):
""" Converts label into a vector.
Args:
labels (int): Class label to convert to tensor.
num_classes (int): Number of classes for the model.
Returns:
(torch.tensor): Torch tensor with 0's everywhere except for 1 in
... | e6cfd53cf460970dcc85254a175359a14dbf9bed | 621,709 |
def swap_empty_string_for_none(array):
""" replace empty string fields with None """
def swap(value):
""" change empty string to None """
if value == "":
return None
else:
return value
return [swap(x) for x in array] | aa6a9189057fe72d28ed938e65240c5bd90ddbcc | 526,963 |
def mirc_format(s):
"""
Replaces mIRC-Codes (for example ^K for Strg+K for colors) with the corresponding chars
"""
s = s.replace("^B", chr(0x02))
s = s.replace("^K", chr(0x03))
s = s.replace("^R", chr(0x0f))
return s; | 379c4f3bf9a7003ff2a459ba79c98bfe3d832929 | 124,088 |
def make_slim_provenance_dict(model_type, slim_generation,
stage='late', spatial_dimensionality='', spatial_periodicity='',
separate_sexes=False, nucleotide_based=False):
"""
Returns a dictionary encoding provenance information for a SLiM tree sequence.
"""
document = {
"schema_v... | a1e1788dcb22ed2c593d8df7c604e165236a32f6 | 634,433 |
def _convert_to_float_if_possible(s):
"""
A small helper function to convert a string to a numeric value
if appropriate
:param s: the string to be converted
:type s: str
"""
try:
ret = float(s)
except (ValueError, TypeError):
ret = s
return ret | d8e736ee3072f1368a991b3b2cc974f3d04894d1 | 570,490 |
def get_token_embeddings(tokenized_text, encoded_layers):
"""
Convert the hidden state embeddings into single token vectors.
"""
# Holds the list of 12 layer embeddings for each token
# Will have the shape: [# tokens, # layers, # features]
token_embeddings = []
batch_i = 0
# For each ... | 6011a359388fd0cbabba81bb2efd14adf1d52502 | 229,437 |
def print_tree(sent, token_attr):
"""Prints sentences tree as string using token_attr from token(like pos_, tag_ etc.)
:param sent: sentence to print
:param token_attr: choosen attr to present for tokens(e.g. dep_, pos_, tag_, ...)
"""
def __print_sent__(token, attr):
print("{", en... | 84d97efb8f6f95a73efb7b214c2f77d88ebe77f3 | 517,239 |
def json(path, _pod):
"""Retrieves a json file from the pod."""
return _pod.read_json(path) | d5d62b698fee0ed62400c6a40cbe76cd7319ec96 | 671,589 |
import hashlib
def _sha256(string):
"""Returns a hash for the given string."""
sha256 = hashlib.sha256()
sha256.update(string)
return sha256.hexdigest() | fd28388976ef845f0efbc9c99014e4555b525449 | 288,372 |
import base64
import dill
def deserialize_obj(obj: str) -> str:
"""Deserialize given object with the following steps:
1. Decode it using base64 to obtain bytes representation.
2. Load it into an object using dill.
"""
obj_dill = base64.b64decode(obj)
obj_str = dill.loads(obj_dill)
... | 6e27eb25e2840a632eb92c32b69c9bb9e9092b14 | 118,385 |
import re
def match(pattern, target):
"""Match a string exactly against a pattern, where the pattern is a regex
with '*' as the only active character.
Args:
pattern (str): Pattern.
target (str): Target.
bool: `True` if `pattern` matches `target`.
"""
pattern = "".join(".*" if... | 6c481a32664f1bd383772df2286016f13732435c | 307,465 |
def _ev_charge_level_value(data, unit_system):
"""Get the charge level value."""
return round(data["evStatus"]["chargeInfo"]["batteryLevelPercentage"]) | b8ce457fd18fe91f27e8e06a597121854f673f9b | 468,109 |
def convert_SI(val, unit_in, unit_out):
"""Unit converter.
Args:
val (float): The value to convert.
unit_in (str): The input unit.
unit_out (str): The output unit.
Returns:
float: The value after unit conversion.
"""
SI = {
"cm": 0.01,
"m": 1.0,
... | 78ddc342a194a6f2841b01c2d1d949dc3c12c10d | 225,547 |
def get_train_val_split_from_names(src, val_list):
"""
Get indices split for train and validation entity names subset
src -- list of all entities in dataset
val_list -- contains entities that belong to the validation subset
"""
train_idx = []
val_idx = []
len_ = len(val_list)
... | 931c9ed22997bdfdbbaf89454ada2f02439e0208 | 587,503 |
def get_http_addr(config):
"""
Get the address of the Proteus server
Args:
config (Config): Pytest config object containing the options
Returns:
str: Address of the Proteus server
"""
hostname = config.getoption("hostname")
http_port = config.getoption("http_port")
retu... | 46352e1c65186fac5c08e5320e70cdd08b6786f3 | 119,741 |
import six
import struct
def int_to_bytes(val, bit=32, signed=False, big_endian=True):
"""
Converts an int to a byte array (bytes).
:param val: value to encode
:param bit: bit length of the integer to encode
:param signed: encode as unsigned int if false
:param big_endian: encode with big or l... | 1737dd18714afe4faf71bfd6cb86914d4b8a965f | 438,565 |
def compute_voltages(grid, configs_raw, potentials_raw):
"""Given a list of potential distribution and corresponding four-point
spreads, compute the voltages
Parameters
----------
grid:
crt_grid object the grid is used to infer electrode positions
configs_raw: Nx4 array
containi... | d060cf55e0439872a48c2e969eff128ced142923 | 362,352 |
import random
def get_random_proxy(list_of_proxies):
"""
Returns a dictionary with a random proxy chosen from the given list.
Parameters
----------------
list_of_proxies : list
A list containing various proxies.
Returns
----------------
dictionary
Returns a dictionary... | 376d3274229a3d796045a705bd02847548da388d | 339,060 |
from typing import Dict
def bounds(stac: Dict) -> Dict:
"""
Return STAC bounds.
Attributes
----------
stac : dict
STAC item.
Returns
-------
out : dict
dictionary with image bounds.
"""
return dict(id=stac["id"], bounds=stac["bbox"]) | 6a7d6d3845d001a8e9975f3d64e41ca45e403479 | 316,652 |
def fill_fields_template(fields, templates):
"""
Substitute the name, type and value for all the fields
"""
final_template = ""
for field in fields:
final_template += (templates[3]
.replace("{name}", field['name'])
.replace("{type}",... | aa3aaa570769e722fb7f84f28756ab628e1abda2 | 217,280 |
def get_successors(graph):
"""Returns a dict of all successors of each node."""
d = {}
for e in graph.get_edge_list():
src = e.get_source()
dst = e.get_destination()
if src in d.keys():
d[src].add(dst)
else:
d[src] = set([dst])
return d | 1ec7b0ab8772dc738758bb14fe4abd5dd4b9074e | 709,606 |
def csv_escape(text):
"""Escape functional characters in text for embedding in CSV."""
if text is None:
return ''
return '~' + text.strip('\n -') + '~' | 3715565582f00e927ec490399d277abe4cbae413 | 247,333 |
def problem_3_6(stack):
""" Write a program to sort a stack in ascending order. You should not make
any assumptions about how the stack is implemented. The following are the
only functions that should be used to write this program:
push | pop | peek | isEmpty.
Solution #1: use one more stack.
... | d8c95fb053a4190a1628c48fe4014ca45e962890 | 585,632 |
def get_data_file_path_list(data_file_list_path):
"""Get mappting of video id to sensor data files.
video id to (original video id, [file 1, ..., file n])
where file 1, ..., file n are one series data.
Note.
- Original video id in input files sometimes mixed lower and upper case.
- To treat se... | 7655c27105b1ce051bf1942655daabc2dfce9bd0 | 21,851 |
import socket
async def async_discover_unifi(hass):
"""Discover UniFi address."""
try:
return await hass.async_add_executor_job(socket.gethostbyname, "unifi")
except socket.gaierror:
return None | a59b928937582813f4210e91d03b739ecc1a77e8 | 332,534 |
def reorder(li: list, a: int, b: int):
"""Reorder li[a] with li[b].
Args:
li (list): List to process.
a (int): Index of first item.
b (int): Index of second item.
Returns:
list: List of reordered items.
Example:
>>> reorder([a, b, c], 0, 1)
<<< [b, a, c... | 6629e47d3e172d2f9c2fb1c2feceb4efb4c0b14b | 417,251 |
def get_conv_gradweights_shape_1axis(
image_shape, top_shape, border_mode, subsample, dilation
):
"""
This function tries to compute the image shape of convolution gradWeights.
The weights shape can only be computed exactly when subsample is 1 and
border_mode is not 'half'. If subsample is not 1 or... | d9a0221d09b24d1c0dd18f3848f11e6b185c5ce4 | 368,906 |
def get_permission_code(permission):
"""
Get unique code for identify permission
:param permission: Permission object
:return: unique_code: unique code of Permission object
"""
return '{app_label}.{codename}'.format(
app_label=permission.content_type.app_label,
# model=permissio... | 7f753347b757530be5892232e94672ac0ccace8a | 122,172 |
import torch
def squeeze_left(const: torch.Tensor):
"""
Squeeze the size-1 dimensions on the left side of the shape tuple.
PyTorch's `squeeze()` doesn't support passing multiple `dim`s at once, so
we do it iteratively.
"""
while len(const.shape) > 0 and const.shape[0] == 1:
const = con... | 1f2390a17e06258757b8890fa8e0df38edb79a67 | 120,363 |
from collections import defaultdict
def _AOP_product(n):
"""for n = (m1, m2, .., mk) return the coefficients of the polynomial,
prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients
of the product of AOPs (all-one polynomials) or order given in n. The
resulting coefficient corresp... | 612cf61c6bf07fdc44df906e2cb5d3ad28aab72c | 564,650 |
from typing import List
from typing import Callable
from typing import Tuple
def build_consumer(charset: List[str]) -> Callable[[str], Tuple[str, str]]:
"""Return a callable that consume anything in *charset*
and returns a tuple of the consumed and unconsumed text"""
def consumer(text: str) -> Tuple[str,... | 3f7d24f32fb667786012af7bf247be997ee4c806 | 361,692 |
from typing import Iterable
def digit_range(num_digits: int) -> Iterable[int]:
""" Range over all numbers with a given number of digits """
minimum = 10 ** (num_digits - 1)
maximum = 10 ** num_digits
return range(minimum, maximum) | d357cd747e1000124b542e269afed78b1b936a8e | 374,766 |
def round_list(input, ndigits=3):
""" Takes in a list of numbers and rounds them to a particular number of digits """
return [round(i, ndigits) for i in input] | 27ad731e626afce3d928aca2093ef022c78f95d2 | 310,429 |
def findAncestor(acc, pred):
"""
Searches for an ancestor satisfying the given predicate. Note that the
AT-SPI hierarchy is not always doubly linked. Node A may consider node B its
child, but B is not guaranteed to have node A as its parent (i.e. its parent
may be set to None). T... | 643a3265c2c5d0dd38fadcee82fc37678df8b32e | 391,024 |
def encode_function_data(initializer=None, *args):
"""Encodes the function call so we can work with an initializer.
Args:
initializer ([brownie.network.contract.ContractTx], optional):
The initializer function we want to call.
args (Any, optional):
The arguments to pass to the i... | 303c297d8ea2b62d3ecb6ccc1e208fc54dd84e49 | 700,798 |
def _webwallet_support(coin, support):
"""Check the "webwallet" support property.
If set, check that at least one of the backends run on trezor.io.
If yes, assume we support the coin in our wallet.
Otherwise it's probably working with a custom backend, which means don't
link to our wallet.
"""
... | b9ed226a8cff055910c3e5883a17aff54ab09843 | 62,612 |
def set_session_settings(torrent_client, params):
"""
Set speed limits
params - session settings key=value pairs.
More info can be found in
<a href="http://www.rasterbar.com/products/libtorrent/manual.html#session-customization">libtorrent API docs</a>.
:return: 'OK'
"""
torrent_client.... | 3174240f919514646af0d9abf08667a8b670db8e | 272,003 |
def format_dict_str(record):
"""
Transform all dict values into strings
"""
for key, value in record.items():
record[key] = str(value)
return record | 8602f708e6e8bbd56d636ceb9023f58e80b114c6 | 92,440 |
import re
def _clean_cassandra_log(string):
"""Strip the text formatting from Cassandra output"""
string = re.sub(r"\^\[\[0m", "", string)
string = re.sub(r"\^\[\[1m", "", string)
return string | e56d6b44d20bdd7b67ae035860fe513e9548defc | 232,367 |
def plotKernel2D(kernel, figAxis, title):
"""
Creates a 2D representation of a kernel.
Parameters
----------
kernel: numpy.array
Kernel to display in 2D.
figAxis: matplotlib.figure.axis
Figure axis where to plot the graphic.
title: str
Title of the graphic built.
... | 7d1d54b9802ecfbf397f02e2304cb0d037fc43e3 | 452,128 |
import pkg_resources
def get_installed_version(base_version_only: bool = False):
"""Get the version of the installed aws-parallelcluster package."""
pkg_distribution = pkg_resources.get_distribution("aws-parallelcluster")
return pkg_distribution.version if not base_version_only else pkg_distribution.parse... | 0ad3875465867daf897e6d9404bb5e309778998c | 145,652 |
def getAngledAttrIfNecessary(font, attr):
"""
Coerce "leftMargin" or "rightMargin" to
"angledLeftMargin" or "angledRightMargin"
if the font is italic.
"""
useAngledMargins = font.info.italicAngle != 0
if useAngledMargins:
if attr == "leftMargin":
attr = "angledLeftMargin"... | 7476b4e8e2bffdd323e2c290143e3e1f910b1b65 | 529,089 |
def find_member(message, nickname):
"""
Finds the first memeber that matches the nickname
on the guild where the message was sent.
Parameters
----------
message : discord.Message
Message that triggered the event.
nickname : str
nickname of the user that might be
on t... | 036ec983a34522f15293ab25246f7b89fc83dade | 83,808 |
def _parse_qsub_job_id(qsub_out):
"""Parse job id from qsub output string.
Assume format:
"Your job <job_id> ("<job_name>") has been submitted"
"""
return int(qsub_out.split()[2]) | 6af319f93cc5ab06fb81597196675e87e3719f5f | 610,839 |
def format_none_and_zero(value):
"""Return empty string if the value is None, zero or Not Applicable
"""
return "" if (not value) or (value == 0) or (value == "0") or (value == 'Not Applicable') else value | a9bcff49098ca6ced92f38e07e922845d87f8fd9 | 130,227 |
def to_float(val):
"""Convert string to float, but also handles None and 'null'."""
if val is None:
return None
if str(val) == "null":
return None
return float(val) | 3a4fe68fa215b414a36e009d56aeb16c7a38573a | 622,846 |
def coalesce_blocks(blocks):
"""
Coalesce a list of (address, size) blocks.
----------------------------------------------------------------------
Example:
blocks = [
(4100, 10),
(4200, 100),
(4300, 10),
(4310, 20),
(4400, 10),
... | 43aebd989dc548fb41eb95555422fd544dcac19f | 466,392 |
def mask_2d_centres_from_shape_pixel_scale_and_centre(shape, pixel_scales, centre):
"""Determine the (y,x) arc-second central coordinates of a mask from its shape, pixel-scales and centre.
The coordinate system is defined such that the positive y axis is up and positive x axis is right.
Parameters
-... | a95972dda4ef22db8ee7b044a2782fc484f11da6 | 456,102 |
def parse_execution_line_for_python_program(execution_line):
"""
Take a line ex. 'python -m service_framework -s service.py' and parse
it so it can be used by the subprocess module.
execution_line::str
return::[str]
"""
split_line = execution_line.split(' ')
execution_list = []
for ... | 699787f343a1f8690db8a4d9890556619795d203 | 214,082 |
def lookup_clutter_geotype(clutter_lookup, population_density):
"""
Return geotype based on population density
Parameters
----------
clutter_lookup : list
A list of tuples sorted by population_density_upper_bound ascending
(population_density_upper_bound, geotype).
population_de... | e778a079ee30e5130f50566bf5b8af1f21d49166 | 145,080 |
import struct
import socket
def long_to_ipv4(ip_long):
"""Convert a long representation to a human readable IPv4 string
>>> long_to_ipv4(2130706433L)
'127.0.0.1'
>>> long_to_ipv4(16909060L)
'1.2.3.4'
"""
ip_bytes = struct.pack("!I", ip_long)
return socket.inet_ntop(socket.AF_INET, ip_... | a4fd91227d5625865113cac06abbb5895f6c6e67 | 319,893 |
import attr
def DictParameter(default=None, factory=dict, **kwargs):
"""Adds a dict parameter:
Args:
default (optional, dict): Default value. Default: None.
base (optional, callabe): Factory function, e.g. dict
or collections.OrderedDict. Default: dict.
"""
if default is n... | 023b58244cd7152bdd25d35211afd189f3eaf136 | 260,497 |
def words(string, sep=','):
"""Split string into stripped words."""
return [x.strip() for x in string.split(sep)] | 538beeed79212a3ee160e7f9dc17e07e3ea93f85 | 135,982 |
import time
def get_time(timestamp):
"""
Get a string representing the timestamp
Parameters
------------
timestamp
Numeric timestamp
Returns
------------
stru
String timestamp
"""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp)).replace(" "... | 0ca53e4a61d3b234f2890e99bff359338d1aed45 | 315,250 |
def identity_nd(*args):
"""Identity functions
Args:
args: variable arguments
Returns:
args: same arguments
"""
return args | c19aca21442e99b2e00306afd9c25f679103ffad | 588,106 |
def rotate(deg, x, y):
"""
Generate an SVG transform statement representing rotation around a given
point.
"""
return "rotate(%i %i %i)" % (deg, x, y) | 27f963dc7bff21b3047495c2ea255d8a2a6325e1 | 304,654 |
def normalize_input(answer):
"""Take a string and normalize it to a standard format."""
return answer.strip() | b7ed9600ae230a07b90b3feabc6ac509f4d0a5a2 | 226,679 |
def normalize_string(s: str) -> str:
"""
function to normalize strings by removing extra quotes and trailing spaces
"""
if s.startswith("'") and s.endswith("'"):
return s.replace("'", "", 2).rstrip("'").strip()
return s.rstrip() | 5c822446f54718c9891d51c09ba820216efb23bb | 268,952 |
def get_DiAC_phases(cliffNum):
"""
Returns the phases (in multiples of pi) of the three Z gates dressing the two X90
pulses comprising the DiAC pulse correspoding to cliffNum
e.g., get_DiAC_phases(1) returns a=0, b=1, c=1, in
Ztheta(a) + X90 + Ztheta(b) + X90 + Ztheta(c) = Id
"""
DiAC_table... | e8c9f7e4aabc1840968663a19557ed7cc4fcf939 | 184,387 |
def get_cspad(azav, gas_det, bin_low, bin_high):
"""
Get the intensity of the diffraction ring on the CSPAD.
The returned value is normalized to the intensity from the gas detector.
Parameters
----------
azav : ndarray
Azimuthal average calculated from CSPAD.
gas_det : float
... | 309b4799b602038b7a9be0060c57e1285397c3d9 | 310,544 |
def unemployment_rate(earning, earning_new, unemployment):
"""
Args:
earning: how much money the player earned last round
earning_new: how much money the player earned this round
unemployment: unemployment rate of the player had last round
Returns: unemplo... | 25f671212bc9b428a8c52f88a575ea36e1fc0178 | 669,897 |
def set_type(values, new_type):
"""Convert string values to integers or floats if applicable. Otherwise, return strings.
If the string value has zero length, none is returned
Args:
values: A list of values
new_type: The type to coerce values to
Returns:
The input list of value... | a1aa1cc74800a1add464e8ac124e0873a455f59a | 34,866 |
def _axes_get_size_inches(ax):
"""
Size of axes in inches
Parameters
----------
ax : axes
Axes
Returns
-------
out : tuple[float, float]
(width, height) of ax in inches
"""
fig = ax.get_figure()
bbox = ax.get_window_extent().transformed(
fig.dpi_scal... | 02dcd5a8b5f099dc136007c0c74dc067042b7538 | 227,421 |
import re
def parse_params(path):
"""Parse a path fragment and convert to a list of tuples.
Slashes separate alternating keys and values.
For example /a/3/b/5 -> [ ['a', '3'], ['b', '5'] ]."""
parts = re.split('/',path)
keys = parts[:-1:2]
values= parts[1::2]
return zip(keys,values) | c79bc783374f314c00c559fb61879e7671eb8f5a | 693,130 |
def XYZtoCIELab(X, Y, Z, obs): # XYZ - Lab
""" convert XYZ to CIE-L*ab color
:param X: X value
:param Y: Y value (luminance)
:param Z: Z value
:param obs: Observer (CIEObs class or class inheriting from it)
:return: CIE-L*ab tuple """
xyz = [X / obs.ref_X, Y / obs.ref_Y, Z / obs.ref_Z]
... | 759063a1f6a5cd4f63854b88c581fc773d32ea02 | 376,292 |
def fib_r(n: int) -> int:
"""Recursively the nth fibonacci number
:param n: nth fibonacci sequence number
:type n: int
:returns: the nth fibonacci number
:rtype: int
.. doctest:: python
>>> fib_r(1)
1
>>> fib_r(2)
2
>>> fib_r(6)
13
"""
... | 82952279aba9bfd1946f9b32f57943b4dcf2d643 | 496,879 |
def NumSearch(big, sub):
"""
Helper function for ModelML. Returns the number of times the string sub appears in the string big.
sub: string of shorter or equal length to big
big: string to search in
"""
results = 0
subLen = len(sub)
for i in range(len(big)):
if big[i:i + subLen]... | 12a284e3ca35a61ef7efa845d781c243957f9e17 | 431,233 |
from pathlib import Path
import tempfile
import venv
def create_new_venv() -> Path:
"""Create a new venv.
Returns:
path to created venv
"""
# Create venv
venv_dir = Path(tempfile.mkdtemp())
venv.main([str(venv_dir)])
return venv_dir | 077dd1318d579ccdb3333849b092555c54297903 | 676,018 |
def get_iob_site(db, grid, tile, site):
""" Return the prjxray.tile.Site objects and tiles for the given IOB site.
Returns tuple of (iob_site, iologic_tile, ilogic_site, ologic_site)
iob_site is the relevant prjxray.tile.Site object for the IOB.
ilogic_site is the relevant prjxray.tile.Site object for... | 627f7f4d6d3a0d5eb67115ed7a55b36723d0f375 | 291,617 |
def first_10_digits_of_sum(filename):
"""Calculates first 10 digits of sum of numbers in file."""
summ = 0
with open(filename) as f:
for line in f.readlines():
summ += int(line[:12])
return str(summ)[:10] | a8d38a84535b31a5d8816e035961c331d6bbf1bf | 299,259 |
def _get_minimal_smoothing(N):
"""An heuristic function for the "most optimal"
(in some sense) smoothing parameter for inverting
an integral operator of quadrature dimension *N*."""
return 9.5e-11*N**1.71 | 04281dc5cab3bac6bdfd49f2400a0c8c415ab8b2 | 363,132 |
def Run(benchmark_spec):
"""Doc will be updated when implemented.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
Returns:
A list of sample.Sample instances.
"""
ycsb_vms = benchmark_spec.vm_groups['clients']
samples = benchmark_s... | 6dc058ad3d5a50dba27a1a7c6df58f870328f1b8 | 170,990 |
from typing import IO
import hashlib
def _hash_fileobj(fileobj: IO[bytes]) -> str:
""" Compute sha256 hash of a file. File pointer will be reset to 0 on return. """
fileobj.seek(0)
h = hashlib.sha256()
for block in iter(lambda: fileobj.read(2 ** 20), b""):
h.update(block)
fileobj.seek(0)
... | d7bab1e68dca88af9df0a22bb0ba05abc8093ff9 | 584,649 |
def get_import_definition_from_import_marker(import_marker: str) -> str:
"""
Restores a Python import definition from a given import marker.
:param import_marker: The import marker String containing the path to be imported.
:returns: The restored Python import definition.
"""
module_path = (
... | 3faabd2a1ad350f24de7722157b9c77bdd02392d | 355,307 |
from datetime import datetime
def parse_date(datestr):
""" Given a date in xport format, return Python date. """
return datetime.strptime(datestr, "%d%b%y:%H:%M:%S") | b802a528418a24300aeba3e33e9df8a268f0a27b | 2,235 |
def make_sequence_output(detections, classes):
"""
Create the output object for an entire sequence
:param detections: A list of lists of detections. Must contain an entry for each image in the sequence
:param classes: The list of classes in the order they appear in the label probabilities
:return:
... | 019d3b74699af20a9f3cbc43b575e8bae5e15946 | 3,743 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.