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, Nsample, Ndim) torch.Tensor
"""
m = torch.distributions.exponential.Exponential(1.0)
a = m.sample(torch.Size([n_batch, n_sample]))
a = a / a.sum(dim=1)[:, None]
m = torch.distributions.uniform.Uniform(0.0, 1.0)
x = m.sample(torch.Size([n_batch, n_sample, n_dim]))
return a, x
|
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
return 3 : has both
"""
rv = 0
for lind in range(len(mdata)):
line = mdata[lind]
if len(line) > 0:
ttok = line[0]
if len(ttok[1]) > 0: rv |= 1 # has amp mods
if ttok[2] > 0: rv |= 2 # has dur mods
break
return rv
|
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: str,
organization_display_name: Optional[str],
) -> Dict[str, str]:
"""
Returns a dictionary of all environmental variables
handled by the web service.
"""
return {
"EDGEDB_HOST": edgedb_host or "127.0.0.1",
"EDGEDB_USER": "edgedb",
"EDGEDB_PASSWORD": edgedb_password,
"EDGEDB_TLS_CA": edgedb_tls_ca,
"GITHUB_RSA_PRIVATE_KEY": "private-key.pem",
"GITHUB_APPLICATION_ID": github_application_id,
"GITHUB_OAUTH_APPLICATION_ID": oauth_application_id,
"GITHUB_OAUTH_APPLICATION_SECRET": oauth_application_secret,
"SERVER_URL": server_url,
"SECRET": application_secret,
"ORGANIZATION_NAME": organization_name,
"ORGANIZATION_DISPLAY_NAME": organization_display_name or "edgedb",
}
|
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
p = 1.0 * num_same / len(pred_list)
r = 1.0 * num_same / len(ref_list)
f1 = (2 * p * r) / (p + r)
return p, r, f1
|
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 lists of actions
"""
split = {}
for action in actions:
for behavior in action.behaviors:
if behavior.name not in split:
split[behavior.name] = []
split[behavior.name].append(action)
return split
|
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],
[s, s, s, r]]
|
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', 'paleo_lon', 'paleo_lon_sigma',
'azimuth', 'azimuth_dec_correction', 'dir_dec',
'geographic_precision', 'bed_dip_direction']
relevant_cols = list(set(vals).intersection(df.columns))
return relevant_cols
|
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:
if item == 'title' or item == 'any':
if rgx.search(issue['title']):
return True
if item == 'text' or item == 'any':
if rgx.search(issue['body']):
return True
if item == 'label' or item == 'any':
for label in issue['labels']:
if rgx.search(label['name']):
return True
return False
|
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
``from_plugin_config`` function, given the appropriate plugin-getter method.
TL;DR: This wraps the instance's ``get_config`` return in a certain way
that's compatible with ``from_plugin_config``.
:param cp_inst: Instance of a Configurable-subclass.
:type cp_inst: Configurable
:return: Plugin-format configuration dictionary.
:rtype: dict
"""
name = cp_inst.__class__.__name__
return {
"type": name,
name: cp_inst.get_config()
}
|
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
publication_urls = set()
for a in analyses:
surface = a.related_surface
if surface.is_published:
pub = surface.publication
pub_url = request.build_absolute_uri(pub.get_absolute_url())
publication_urls.add(pub_url)
return publication_urls
|
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
}
### add author of modif
if by != None :
modif["modif_by"] = by
if val != None :
modif["modif_val"] = val
doc["modif_log"].insert(0, modif)
return doc
|
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()
while result == original:
random.shuffle(result)
return result
|
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.
:param ind1: The first individual participating in the crossover.
:param ind2: The second individual participating in the crossover.
:returns: A tuple of two individuals.
Moreover, this crossover generates two children by matching
pairs of values in a certain range of the two parents and swapping the values
of those indexes. For more details see [Goldberg1985]_.
This function uses the :func:`~random.randint` function from the python base
:mod:`random` module.
.. [Goldberg1985] Goldberg and Lingel, "Alleles, loci, and the traveling
salesman problem", 1985.
"""
size = min(len(ind1), len(ind2))
p1, p2 = [0] * size, [0] * size
# Initialize the position of each indices in the individuals
for i in range(size):
p1[ind1[i]] = i
p2[ind2[i]] = i
# Choose crossover points
cxpoint1 = random.randint(0, size)
cxpoint2 = random.randint(0, size - 1)
if cxpoint2 >= cxpoint1:
cxpoint2 += 1
else: # Swap the two cx points
cxpoint1, cxpoint2 = cxpoint2, cxpoint1
# Apply crossover between cx points
for i in range(cxpoint1, cxpoint2):
# Keep track of the selected values
temp1 = ind1[i]
temp2 = ind2[i]
# Swap the matched value
ind1[i], ind1[p1[temp2]] = temp2, temp1
ind2[i], ind2[p2[temp1]] = temp1, temp2
# Position bookkeeping
p1[temp1], p1[temp2] = p1[temp2], p1[temp1]
p2[temp1], p2[temp2] = p2[temp2], p2[temp1]
return ind1, ind2
|
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 cc in ccs_payload)
ccs_tracker = set(cc.strip() for cc in ccs_issuetracker)
return list(ccs_system.union(ccs_tracker))
|
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 = features.view(n, l, 1, c)
x = x.expand(n, l, l, c)
y = features.view(n, 1, l, c).contiguous()
y = y.expand(n, l, l, c)
return x * y
|
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
correct class.
"""
one_hot = torch.eye(num_classes)
return one_hot[labels.long()]
|
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_version": "1.0.0",
"software": {
"name" : "SLiM",
"version": "3.3.2"
},
"parameters": {
"command": ['pyslim'],
"model_type": model_type,
"stage": stage,
"spatial_dimensionality": spatial_dimensionality,
"spatial_periodicity": spatial_periodicity,
"separate_sexes": separate_sexes,
"nucleotide_based": nucleotide_based,
},
"environment": {},
"metadata": {
"individuals": {
"flags": {
"16": {
"name" : "SLIM_TSK_INDIVIDUAL_ALIVE",
"description" : "the individual was alive "
+ "at the time the file was written",
},
"17": {
"name" : "SLIM_TSK_INDIVIDUAL_REMEMBERED",
"description" : "the individual was requested "
+ "by the user to be permanently remembered",
},
"18": {
"name" : "SLIM_TSK_INDIVIDUAL_RETAINED",
"description" : "the individual was requested "
+ "by the user to be retained only if its "
+ "nodes continue to exist in the tree sequence",
},
}
}
},
"slim": {
"file_version": "0.4",
"generation": slim_generation,
"model": ""
}
}
return document
|
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 token in the sentence...
for token_i in range(len(tokenized_text)):
# Holds 12 layers of hidden states for each token
hidden_layers = []
# For each of the 12 layers...
for layer_i in range(len(encoded_layers)):
# Lookup the vector for `token_i` in `layer_i`
vec = encoded_layers[layer_i][batch_i][token_i]
hidden_layers.append(vec)
token_embeddings.append(hidden_layers)
return token_embeddings
|
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("{", end=" ")
[__print_sent__(t, attr) for t in token.lefts]
print(u"%s->%s(%s)" % (token,token.dep_,token.tag_ if not attr else getattr(token, attr)), end="")
[__print_sent__(t, attr) for t in token.rights]
print("}", end=" ")
return __print_sent__(sent.root, token_attr)
|
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)
return obj_str
|
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 c == "*" else re.escape(c) for c in pattern)
return bool(re.match("^" + pattern + "$", target))
|
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,
"km": 1000.0,
"inch": 0.0254,
"foot": 0.3048,
"mile": 1609.34,
}
return val * SI[unit_in] / SI[unit_out]
|
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)
for i, x in enumerate(src):
found = False
j = 0
while j < len_ and not found:
found = val_list[j] in x
j += 1
if found:
val_idx.append(i)
else:
train_idx.append(i)
return train_idx, val_idx
|
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")
return f"{hostname}:{http_port}"
|
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 little endian
:return:
"""
val = int(val) #ensure it is an int
if six.PY3:
order = 'little'
if big_endian:
order = 'big'
return val.to_bytes(length=bit//8, byteorder=order, signed=signed)
if bit == 8:
code = 'B'
elif bit == 16:
code = 'H'
elif bit == 32:
code = 'I'
elif bit == 64:
code = 'Q'
else:
raise Exception("int_to_bytes : size parameter value should be 8, 16, 32, or 64")
if big_endian:
code = '>'+code
else:
code = '<'+code
if signed or val < 0:
code = code.lower()
return struct.pack(code, val)
|
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
containing the measurement configs (1-indexed)
potentials_raw: list with N entries
corresponding to each measurement, containing the node potentials of
each injection dipole.
"""
# we operate on 0-indexed arrays, config holds 1-indexed values
# configs = configs_raw - 1
voltages = []
for config, potentials in zip(configs_raw, potentials_raw):
print('config', config)
e3_node = grid.get_electrode_node(config[2])
e4_node = grid.get_electrode_node(config[3])
print(e3_node, e4_node)
print('pot1', potentials[e3_node])
print('pot2', potentials[e4_node])
voltage = potentials[e3_node] - potentials[e4_node]
voltages.append(voltage)
return voltages
|
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 with a random proxy which uses the http protocol.
"""
random_proxy = "http://" + str(random.choice(list_of_proxies))
proxy_dict = {"http" : random_proxy}
return proxy_dict
|
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}", field['type'])
.replace("{value}", field['value']))
return final_template
|
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.
Solution #2: no additional stack but using recursion, first recurse on the
substack without the last element to bring the max to top, then compare
top two elements. This is bubble-sort.
"""
def move_last(stack):
""" Finds the max element in stack and moves it to to the top. """
if len(stack) <= 1:
return stack
last = stack.pop()
stack = move_last(stack)
previous = stack.peek()
if previous > last:
previous = stack.pop()
stack.push(last)
stack.push(previous)
else:
stack.push(last)
return stack
def stack_sort(stack):
if stack.is_empty():
return stack
stack = move_last(stack)
last = stack.pop()
stack = stack_sort(stack)
stack.push(last)
return stack
return stack_sort(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 several case, lower case of them are used as key of mapping.
"""
mapping = {}
with open(data_file_list_path) as f_in:
for line in f_in.readlines():
if line.strip() == '':
continue
video_name_prefix, files_txt = line.strip().split('\t')
mapping[video_name_prefix.lower()] = (
video_name_prefix, files_txt.split(','))
return mapping
|
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]
"""
li[a], li[b] = li[b], li[a]
return li
|
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 border_mode is 'half',
this function will return None.
Parameters
----------
image_shape: int or None. Corresponds to the input image shape on a
given axis. None if undefined.
top_shape: int or None. Corresponds to the top shape on a given axis.
None if undefined.
border_mode: string, int or tuple of 2 ints. If it is a string, it must be
'valid', 'half' or 'full'. If it is an integer, it must correspond to
the padding on the considered axis. If it is a tuple, its two elements
must correspond to the asymmetric padding (e.g., left and right) on
the considered axis.
subsample: int. It must correspond to the subsampling on the
considered axis.
dilation: int. It must correspond to the dilation on the
considered axis.
Returns
-------
kernel_shape: int or None. Corresponds to the kernel shape on a given
axis. None if undefined.
"""
if None in [image_shape, top_shape, border_mode, subsample, dilation]:
return None
if subsample != 1 or border_mode == "half":
return None
if border_mode == "full":
kernel_shape = top_shape - image_shape
elif border_mode == "valid":
kernel_shape = image_shape - top_shape
else:
if isinstance(border_mode, tuple):
pad_l, pad_r = border_mode
else:
pad_l = pad_r = border_mode
if pad_l < 0 or pad_r < 0:
raise ValueError("border_mode must be >= 0")
kernel_shape = image_shape + pad_l + pad_r - top_shape
if dilation > 1:
kernel_shape = kernel_shape / dilation
return kernel_shape + 1
|
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=permission.content_type.model,
codename=permission.codename,
)
|
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 = const.squeeze(dim=0)
return const
|
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 corresponding to x**r is the number of r-length
combinations of sum(n) elements with multiplicities given in n.
The coefficients are given as a default dictionary (so if a query is made
for a key that is not present, 0 will be returned).
Examples
========
>>> from sympy.functions.combinatorial.numbers import _AOP_product
>>> from sympy.abc import x
>>> n = (2, 2, 3) # e.g. aabbccc
>>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand()
>>> c = _AOP_product(n); dict(c)
{0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1}
>>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)]
True
The generating poly used here is the same as that listed in
http://tinyurl.com/cep849r, but in a refactored form.
"""
n = list(n)
ord = sum(n)
need = (ord + 2)//2
rv = [1]*(n.pop() + 1)
rv.extend([0]*(need - len(rv)))
rv = rv[:need]
while n:
ni = n.pop()
N = ni + 1
was = rv[:]
for i in range(1, min(N, len(rv))):
rv[i] += rv[i - 1]
for i in range(N, need):
rv[i] += rv[i - 1] - was[i - N]
rev = list(reversed(rv))
if ord % 2:
rv = rv + rev
else:
rv[-1:] = rev
d = defaultdict(int)
for i in range(len(rv)):
d[i] = rv[i]
return d
|
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, str]:
consumed = []
start_ix = 0
should_continue = True
while should_continue:
should_continue = False
for chars in charset:
if text[start_ix:].startswith(chars):
start_ix += len(chars)
consumed.append(chars)
should_continue = True
token = "".join(consumed)
return token, text[len(token) :]
return consumer
|
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). This means some searches may never make it all the way
up the hierarchy to the desktop level.
@param acc: Starting accessible object
@type acc: Accessibility.Accessible
@param pred: Search predicate returning True if accessible matches the
search criteria or False otherwise
@type pred: callable
@return: Node matching the criteria or None if not found
@rtype: Accessibility.Accessible
"""
if acc is None:
# guard against bad start condition
return None
while 1:
if acc.parent is None:
# stop if there is no parent and we haven't returned yet
return None
try:
if pred(acc.parent): return acc.parent
except Exception:
pass
# move to the parent
acc = acc.parent
|
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 initializer function
Returns:
[bytes]: Return the encoded bytes.
"""
if not len(args):
args = b""
if initializer:
return initializer.encode_input(*args)
return b""
|
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.
"""
if not support.get("webwallet"):
return False
return any(".trezor.io" in url for url in coin["blockbook"] + coin["bitcore"])
|
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.set_session_settings(**params)
return 'OK'
|
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.
Returns
-------
imAxis: matplotlib.axis
Axis in which the image is placed on the plot.
"""
figAxis.set_title(title, fontsize=15)
figAxis.set_xlabel('x')
figAxis.set_ylabel('y')
figAxis.set_xticks([])
figAxis.set_yticks([])
return figAxis.imshow(kernel.real, cmap='hot', interpolation='bicubic')
|
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.parsed_version.base_version
|
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"
elif attr == "rightMargin":
attr = "angledRightMargin"
return attr
|
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 the same guild where the message
was delivared.
Returns
-------
member : discord.Member
First discord member that matches the nickname.
If no member was found that matches the nickname
None will be returned.
"""
for member in message.guild.members:
if nickname in member.display_name:
return member
|
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),
]
Returns:
coalesced = [(4100, 10), (4200, 130), (4400, 10)]
"""
# nothing to do
if not blocks:
return []
elif len(blocks) == 1:
return blocks
# before we can operate on the blocks, we must ensure they are sorted
blocks = sorted(blocks)
#
# coalesce the list of given blocks
#
coalesced = [blocks.pop(0)]
while blocks:
block_start, block_size = blocks.pop(0)
#
# compute the end address of the current coalescing block. if the
# blocks do not overlap, create a new block to start coalescing from
#
if sum(coalesced[-1]) < block_start:
coalesced.append((block_start, block_size))
continue
#
# the blocks overlap, so update the current coalescing block
#
coalesced[-1] = (coalesced[-1][0], (block_start+block_size) - coalesced[-1][0])
# return the list of coalesced blocks
return coalesced
|
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
----------
shape : (int, int)
The (y,x) shape of the 2D array the arc-second centre is computed for.
pixel_scales : (float, float)
The (y,x) arc-second to pixel scales of the 2D array.
centre : (float, flloat)
The (y,x) centre of the 2D mask.
Returns
--------
tuple (float, float)
The (y,x) arc-second central coordinates of the input array.
Examples
--------
centres_arcsec = centres_from_shape_pixel_scales_and_centre(shape=(5,5), pixel_scales=(0.5, 0.5), centre=(0.0, 0.0))
"""
y_centre_arcsec = (float(shape[0] - 1) / 2) - (centre[0] / pixel_scales[0])
x_centre_arcsec = (float(shape[1] - 1) / 2) + (centre[1] / pixel_scales[1])
return (y_centre_arcsec, x_centre_arcsec)
|
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 item in split_line:
if item:
cleaned_item = item.strip()
execution_list.append(cleaned_item)
return execution_list
|
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_density : float
The current population density requiring the lookup.
"""
highest_popd, highest_geotype = clutter_lookup[2]
middle_popd, middle_geotype = clutter_lookup[1]
lowest_popd, lowest_geotype = clutter_lookup[0]
if population_density < middle_popd:
return lowest_geotype
elif population_density > highest_popd:
return highest_geotype
else:
return middle_geotype
|
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_bytes)
|
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 not None:
return attr.ib(default, **kwargs)
return attr.ib(factory=factory, **kwargs)
|
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(" ", "T") + ".000"
|
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 = [
[0, 1, 1],
[0.5, -0.5, 0.5],
[0, 0, 0],
[0.5, 0.5, 0.5],
[0, -0.5, 1],
[0, 0, 1],
[0, 0.5, 1],
[0, 1, -0.5],
[0, 1, 0],
[0, 1, 0.5],
[0, 0, 0.5],
[0, 0, -0.5],
[1, -0.5, 1],
[1, 0.5, 1],
[0.5, -0.5, -0.5],
[0.5, 0.5, -0.5],
[0.5, -0.5, 1],
[1, -0.5, -0.5],
[0, 0.5, -0.5],
[-0.5, -0.5, 1],
[1, 0.5, -0.5],
[0.5, 0.5, 1],
[0, -0.5, -0.5],
[-0.5, 0.5, 1]]
return DiAC_table[cliffNum]
|
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
Gas detector intensity.
bin_low : int
The bin number of the lower bound of the intensity integration.
bin_high : int
The bin number of the upper bound of the intensity integration.
Returns
-------
intensity : float
Sum of 5 qbins above and below the center, normalized by gas detector.
"""
intensity = sum(azav[bin_low:bin_high]) / gas_det
return intensity
|
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: unemployment rate of the player has this round
"""
# based on okuns law
delta_unemployment = ((earning - earning_new) / earning) / 1.8
new_unemployment = max(0, unemployment + delta_unemployment)
return new_unemployment
|
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 values modified to match their type. String is the default return value. If the values are
ints or floats, returns the list formatted as a list of ints or floats. Empty values will be replaced with none.
"""
if new_type == str:
coerced_values = [str(x) for x in values]
elif new_type == int or new_type == float:
float_values = [float(x) for x in values]
if new_type == int:
coerced_values = [int(round(x)) for x in float_values]
else:
coerced_values = float_values
else:
raise ValueError("{} not supported for coercing types".format(new_type.__name__))
return coerced_values
|
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_scale_trans.inverted()
)
return bbox.width, bbox.height
|
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]
for i in range(len(xyz)):
if xyz[i] > 0.008856:
xyz[i] = pow(xyz[i], (1.0 / 3.0))
else:
xyz[i] = (7.787 * xyz[i]) + (16.0 / 116.0)
CL = (116.0 * xyz[1]) - 16.0
Ca = 500.0 * (xyz[0] - xyz[1])
Cb = 200.0 * (xyz[1] - xyz[2])
return CL, Ca, Cb
|
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
"""
return n if n < 3 else fib_r(n - 1) + fib_r(n - 2)
|
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] == sub:
results += 1
return results
|
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 the ILOGIC
connected to the IOB.
ologic_site is the relevant prjxray.tile.Site object for the OLOGIC
connected to the IOB.
iologic_tile is the tile containing the ilogic_site and ologic_site.
"""
gridinfo = grid.gridinfo_at_tilename(tile)
tile_type = db.get_tile_type(gridinfo.tile_type)
sites = sorted(tile_type.get_instance_sites(gridinfo), key=lambda x: x.y)
if len(sites) == 1:
iob_site = sites[0]
else:
iob_site = sites[1 - int(site[-1])]
loc = grid.loc_of_tilename(tile)
if gridinfo.tile_type.startswith('LIOB33'):
dx = 1
elif gridinfo.tile_type.startswith('RIOB33'):
dx = -1
else:
assert False, gridinfo.tile_type
iologic_tile = grid.tilename_at_loc((loc.grid_x + dx, loc.grid_y))
ioi3_gridinfo = grid.gridinfo_at_loc((loc.grid_x + dx, loc.grid_y))
ioi3_tile_type = db.get_tile_type(ioi3_gridinfo.tile_type)
ioi3_sites = ioi3_tile_type.get_instance_sites(ioi3_gridinfo)
ilogic_site = None
ologic_site = None
target_ilogic_site = iob_site.name.replace('IOB', 'ILOGIC')
target_ologic_site = iob_site.name.replace('IOB', 'OLOGIC')
for site in ioi3_sites:
if site.name == target_ilogic_site:
assert ilogic_site is None
ilogic_site = site
if site.name == target_ologic_site:
assert ologic_site is None
ologic_site = site
assert ilogic_site is not None
assert ologic_site is not None
return iob_site, iologic_tile, ilogic_site, ologic_site
|
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_spec.executor.LoadAndRun(ycsb_vms)
return samples
|
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)
return h.hexdigest()
|
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 = (
import_marker.split(" ")[2]
.replace('"', "")
.replace("./", "")
.replace(".py", "")
.replace("\n", "")
.replace("/", ".")
)
import_definition = f"from .{module_path} import *"
return import_definition
|
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:
"""
return {
'detections': detections,
'classes': classes
}
|
019d3b74699af20a9f3cbc43b575e8bae5e15946
| 3,743 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.