content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def makeup(_x, n):
"""
Increase the length of _x to be n by duplicating some elements
:param _x: input length
:param n: output size
:return: list of length n with all original and additional duplicate elements from _x
"""
x = []
for i in range(n):
x.append(_x[i % len(_x)])
re... | 65aaa19d5c93c3430d10a16b1c4a38aa0459422b | 612,110 |
from pathlib import Path
def temp_paths_1(tmp_path_factory):
"""
Makes temporary directories, for testing bak_to_git_1, and populates them
with test files. Returns pathlib.Path objects for each.
"""
temp_path: Path = tmp_path_factory.mktemp("baktogit1")
bak_path = temp_path / "_0_bak"
bak_... | 3d8418a50258349dc2cac9671e57039bc193b901 | 612,115 |
def _adjugate(M, method="berkowitz"):
"""Returns the adjugate, or classical adjoint, of
a matrix. That is, the transpose of the matrix of cofactors.
https://en.wikipedia.org/wiki/Adjugate
Parameters
==========
method : string, optional
Method to use to find the cofactors, can be "bar... | c647a8ddd155de4164945ff44e6a7fcb1a23051c | 612,122 |
def boundary(graph, subgraph):
"""
Get the nodes in the subgraph that have neighbors in the graph but not in the subgraph.
This is useful for conditionally styling nodes at the boundary of a subgraph. For example:
::
boundary = nxv.boundary(graph, subgraph)
style = nxv.Style(node=lamb... | 011c30e355a208d73e0ccb5c3e1ccd91b41b4e74 | 612,126 |
def hh_mm(time_struct, twelve_hour=True):
""" Given a time.struct_time, return a string as H:MM or HH:MM, either
12- or 24-hour style depending on twelve_hour flag.
"""
postfix = ""
if twelve_hour:
if time_struct.tm_hour > 12:
hour_string = str(time_struct.tm_hour - 12) # 13-... | 070a22c7bfec95f69d1d6970d74ac020c71bd6ea | 612,132 |
from typing import Iterable
from typing import Callable
def indexOf(items: Iterable, match: Callable, *args):
"""Returns the index of the first item for which the `match` function returns
True."""
for idx, item in enumerate(items):
if match(item, *args):
return idx | b9f418a6e303bd8f83fb1be2a7cfad925fb6da0b | 612,133 |
def merge_two_dicts(x, y):
"""
Merges 2 dictionary.
Overrides values from x with values from y, if key is the same.
Needed for Python < 3.5
See: https://stackoverflow.com/a/26853961
:param x:
:param y:
:return:
"""
z = x.copy() # start with x's keys and values
z.update(y)... | 1d79c0d3a59778b347a6eed4602116ea031cbeb0 | 612,134 |
def count_lines(input_filepath):
"""Count number of non-empty lines in file."""
counter = 0
with open(input_filepath, 'r', encoding='utf-8') as input_str:
for line in input_str:
if line.strip():
counter += 1
return counter | 95e0f36210e78c99fb35831edd96ac6fd96f9e69 | 612,135 |
def get_metal_bonds(mol, metal_atoms):
"""
Return a list of bonds in molecule that contain metal atoms.
"""
metal_bonds = []
ids_to_metals = []
for bond in mol.get_bonds():
if bond.get_atom1() in metal_atoms:
metal_bonds.append(bond)
ids_to_metals.append(bond.ge... | e6bff1d5c225f4b59d75a9473a998e367c0ff4ad | 612,136 |
def speed_section_bot(speed_limit_bot, D_bot, D):
"""
Calculates the section speed of vapor at the bottom
Parameters
----------
speed_limit_bot: float
The limit speed of the vapor at the bottom of column, [m/s]
D_bot : float
The calculating bottom diameter of column, [m]
D :... | aca95adf8d304146951f3db05ca5f4872599f614 | 612,137 |
def minutes_to_seconds(minutes: str) -> int:
"""
Converts minutes to seconds
Arguments:
minutes: The number of minutes to be converted to seconds.
Returns:
The number of seconds.
"""
return int(minutes)*60 | fe2c6a8ba148c86dcee93ac26c9f21648b3fa204 | 612,139 |
def make_allowed_registries(registry_list):
""" turns a list of wildcard registries to allowedRegistriesForImport json setting """
return {
"allowedRegistriesForImport": [
{'domainName': reg} if isinstance(reg, str) else reg for reg in registry_list
]
} | 1e6335fc199fb60cdc0412e2274b02f085800611 | 612,141 |
def is_one_to_one(d):
"""
(dict of {str: int}) -> bool
Return True if and only if no two of d's keys
map to the same value.
>>> is_one_to_one({'a': 1, 'b': 2, 'c': 3})
True
>>> is_one_to_one({'a': 1, 'b': 2, 'c': 1})
False
>>> is_one_to_one({})
True
"""
values = []
... | 935e08f666bd0d8ba9de9b170a8dc9e04bed5db9 | 612,146 |
def crop_from_right(sequence_string, crop_length):
"""
return a sequence string without last crop_length characters
drops values at end ie chops off right side
if crop_length > length sequence_string --> returns ""
if crop_length <= 0 returns string
"""
if (crop_length <= 0):
return ... | c3830b6643f151441ffa32d00ff2023e10ca05ae | 612,149 |
from functools import reduce
from operator import mul
def _geom_mean(growth_list, weights):
"""Computes weighted geometric mean."""
weighted = [g**w for g, w in zip(growth_list, weights)]
gmean = reduce(mul, weighted)**(1 / sum(weights))
return gmean | e913c0a52f5c09381871d62591720d787e036fc9 | 612,150 |
def get_tensor_name(subgraph, tensor_idx):
"""Get the tensor name.
Parameters
----------
subgraph:
tflite.Subgraph.Subgraph
tensor:
tensor index in subgraph
Returns
-------
tensor name in UTF-8 encoding
"""
return subgraph.Tensors(tensor_idx).Name().decode(... | c880db3e75711d7acc49a5a0536c3e6219c4959b | 612,152 |
def firstEmail(m, d):
"""
Engage stores emails and phone numbers in the 'contacts' section
of a supporter record. This function finds the first email. If
there's not an email record, then we'll return a None.
Parameters:
m dict supporter record
d string default value ... | 43670cb42bc2f7864cb7414f519eff08b29cf443 | 612,154 |
def warc_datetime_str(date):
"""Amendedment to warctools' function to fix non-ISO8601 output."""
iso = date.isoformat()
if "." in iso:
iso = iso[:iso.find(".")]
if "+" in iso:
iso = iso[:iso.find("+")]
return iso + "Z" | f5932bedd398ecd5c6f3e346b1fc2ccfc024eaa5 | 612,158 |
def exists_key_in_dicts_list(dict_list, key):
"""From a list of dicts, checks if a certain key is in one of the dicts in the list.
See also https://stackoverflow.com/questions/14790980/how-can-i-check-if-key-exists-in-list-of-dicts-in-python
Parameters
----------
dict_list: list
A list of... | 27ff74ea0258d394685b28560232628be96a70a4 | 612,166 |
import hashlib
def numeric_hash(string, digest_size=4):
"""
Returns an integer hash of a string.
Args:
string: str -- String to hash
digest_size: int -- Size of the digest in bytes. Max is 16.
Returns:
int
"""
return int(hashlib.md5(string.encode("utf-8")).hexdigest()[... | 90de663c3035fb46215483a24c9490a81c1c0880 | 612,167 |
def generate_parameterized_path(
test_rate=0, random=False, n_negative=100, by_user=False
):
"""Generate parameterized path.
Encode parameters into path to differentiate different split parameters.
Args:
by_user (bool): split by user.
test_rate (float): percentage of the test data.
... | ee2a6cbd903d604c4d1081252a5a646e057d0333 | 612,168 |
def convert_to_list(value):
"""
Creates a list argument from command line.
Arguments:
value : The keyword argument from command line
Returns:
None if the string none is found
list if the string is space seperated values is found
"""
if value == 'None':
return No... | 5028740bac30d3069b1b6ab681070746949c4095 | 612,171 |
def instrument_to_insCode(instrument):
"""Given a pretty_midi.Instrument object, returns a concise string code representing its program number & its is_drum parameter.
Parameters
----------
instrument : pretty_midi.Instrument
object of pretty_midi.Instrument class.
Returns
-------
... | f958f5ca651580a330d3ca54b9d668827caffa08 | 612,172 |
def construct_package_url(base_url, dist, arch, sha256):
"""
Construct a package URL for a debian package using the 'by-hash' path.
See: https://wiki.debian.org/DebianRepository/Format#indices_acquisition_via_hashsums_.28by-hash.29
Example: http://us.archive.ubuntu.com/ubuntu/dists/bionic/by-hash/SHA25... | acee4d440414fd65cca9d895857750dd3a4bee55 | 612,174 |
import importlib
def get_trainer(name, **trainer_args):
"""
Factory function for retrieving a trainer.
"""
module = importlib.import_module('.' + name, 'mldas.trainers')
return module.get_trainer(**trainer_args) | 74542656c6f1f3a91c428aec77d575c8c6f57f7d | 612,176 |
import re
def is_docker() -> bool:
"""
Look into cgroup to detect if we are in container
"""
path = "/proc/self/cgroup"
try:
with open(path, encoding="utf-8") as file:
for line in file:
if re.match(r"\d+:[\w=]+:/docker(-[ce]e)?/\w+", line):
r... | 220af504f71fb406fcedd7c9e398214324a1719e | 612,178 |
def JD2epochJulian(JD):
#---------------------------------------------------------------------
"""
Convert a Julian date to a Julian epoch
:param JD:
Julian date
:type JD:
Floating point number
:Returns:
Julian epoch
:Reference:
Standards Of Fundamental Astronomy,
http://www.iau-sofa.rl.ac.u... | 3e9189ebb07bfb862844bf9f7e5ed5fb01ac7219 | 612,180 |
def is_midnight(dt):
"""
Determines if given datetime object is set to midnight.
"""
return dt.hour == 0 and dt.minute == 0 and dt.second == 0 | 4e8761ac27164987c57ef1cb335c9745bb65acd6 | 612,181 |
def set_outputs_key_for_list_recipient_and_sender(args):
"""
This function checks which argument used and returns it for the outputs prefix.
Args:
args: The recipient list or the sender list.
Returns:
The recipient list or the sender list, depending on what was used.
"""
return a... | f1dc7db1dbfa8061f34f9c6e0a1e6ab2496a4b3f | 612,182 |
def split_tokenize(text):
"""Splits tokens based on whitespace after adding whitespace around
punctuation.
"""
return (text.replace('.', ' . ').replace('. . .', '...')
.replace(',', ' , ').replace(';', ' ; ').replace(':', ' : ')
.replace('!', ' ! ').replace('?', ' ? ').replace('(... | e850dbad8b2c82c334a58eb1c9300936646dbf54 | 612,183 |
import re
def _remove_prefix_username(text: str) -> str:
"""removes twitter style usernames at the start of the tweet"""
p_text = text
while re.search(r'^@[a-zA-Z0-9_]{1,15}', p_text):
p_text = re.sub(r'^@[a-zA-Z0-9_]{1,15}\s*', '', p_text)
return p_text | 41055ed7c0ccf10901a124d6a07dab9b0112cf34 | 612,186 |
def title(fields, __):
"""
Assign a title to the document.
This is metadata only; nothing is added to the body text.
"""
return [], {'title': fields[0]} | 7ae470c9e7376a0e153cf927c953a1c04bbdb41e | 612,189 |
def _filter_files(adir, filenames, filecnt, file_type, ffilter):
"""
Filter files by file type(filter function) then returns matching
files and cumulated count.
"""
rfiles = ffilter(adir, filenames)
filecnt += len(rfiles)
return rfiles, filecnt | d8d672a66db67ae06c618dbeac660856a923db93 | 612,191 |
def get_datapoints(target_rps=500, rps_min=50, rps_max=20000, increment=50, exponent=0.5):
"""Get a distribution around target_rps from rps_min to rps_max with increasing distance between individual measurements."""
rps = [rps_min, target_rps, rps_max]
for inc in sorted(set([increment * round(2 ** (i * expo... | 53d6eedc117a88b5fa5e080285f01c043c8957a3 | 612,192 |
def get_query(string, pos=1):
"""Get query parameter of a URL."""
try:
return string.split("?")[pos]
except IndexError:
if pos == 1:
return ""
else:
return string | 2c463a597f899306f3bda9ed9b6d16c981cd16e2 | 612,193 |
def is_user(request):
"""Check if the incoming request is from the appropriate_user."""
return request.authenticated_userid == request.matchdict['username'] | 2ed218c70d712d6b03d470e7ebe228e872d20a0b | 612,195 |
import re
def remove_bars(string):
"""Return argument without square brackets ('[' and ']')."""
return re.sub(r"[\[\]]", "", string) | a8143b53ee462cef1d8a98c8408e2481651c2bec | 612,199 |
def delta_total_seconds(td):
"""Equivalent to timedelta.total_seconds() available in Python 2.7.
"""
microseconds, seconds, days = td.microseconds, td.seconds, td.days
return (microseconds + (seconds + days * 24 * 3600) * 10 ** 6) / 10 ** 6 | 0e21661f3e4a3d51401de139e4823565d0d835ed | 612,204 |
def is_ttt(soup):
"""Check if stage is team time trial."""
stage_info = soup.select("h2 span.blue")[0].text
return "TTT" in stage_info | 261ad958811ce1fad633b30ec679d711acb94b0e | 612,205 |
def get_trimmed_path(location, num_segments=2):
"""
Return a trimmed relative path given a location keeping only the
``num_segments`` trailing path segments.
For example::
>>> assert get_trimmed_path(None) == None
>>> assert get_trimmed_path('a/b/c') == 'b/c'
>>> assert get_trimmed_path('/b... | c60ae7d5be5316a34c5c3228353da61a036777e0 | 612,206 |
from pathlib import Path
def as_jupyter_path(path):
"""
Paths in Jupyter are delimited by / (even on Windows) and don't have
trailing leading slashes. This function takes a platform-dependent
path and converts it to a valid jupyter path
Notes
-----
https://jupyter-notebook.readthedocs.io/... | a9802a97fa8425afe51d6eb795dbe23d49ef4cde | 612,208 |
from datetime import datetime
def get_today() -> str:
"""
Get todays date.
"""
return str(datetime.today().date()) | af018a51932f3c74f572f46a9595f1d95326cd3b | 612,210 |
def format_response(response_collection):
"""Re-format responses to a dict"""
return {
"code": response_collection[0]['code'],
"message": "%s created" % response_collection[0]['resource'],
"status": response_collection[0]['status'],
"payload": response_collection
} | ff068b95103e5c6b20d6f95794ed9d8baad1ef09 | 612,213 |
def check_permutations(s_one, s_two):
"""
Question 2: Given two strings, write a method to decide if one is a permutation
of the other.
"""
if len(s_one) != len(s_two):
return False
h_table = {}
for index, char in enumerate(s_two):
h_table[char] = index
for char in set(... | 027eff8c87d3e4c898beb026eb46c1d6d5593cf4 | 612,214 |
from typing import IO
from typing import Tuple
import base64
import click
def read_public_key(f: IO[str]) -> Tuple[str, str, str, str]:
"""
Read a public SSH key.
This function does some basic verification to see if the content
looks like a public key.
"""
data = f.read()
try:
kin... | 6104d25f3ca32720ab680113fcc30622feec1796 | 612,218 |
def is_none(value):
""" is value None"""
return value is None | bf073d4cc1aac2e21f00d7f34311c16d21877236 | 612,220 |
from typing import OrderedDict
def digest_node_line(line):
"""Return OrderedDict of relevant line parts."""
line = line.strip()
d = OrderedDict()
d["num"], fields = line.split('[')
fields = fields.replace('rounded,dashed', 'rounded-dashed')
fields = fields.rstrip('];').split(',')
fields[-... | d68b88e57ea5d420f92f2da6600ee164856f4619 | 612,222 |
def read_full_superlinks(filename):
"""Read the full superlinks input file and create a dictionary with superlink number as the key and a list of Measures Estimation links that make it up as the value"""
superlinks = {}
with open(filename) as in_f:
for line in in_f:
row = line.split(','... | 0c0bd0f47052f82e066264d720b229c4f5c01410 | 612,228 |
def atomic_prop(entry, molTuple):
"""Return true if atom fits F5 (atomic property) entry, False otherwise"""
molecule, atomIndex = molTuple
#determine atom properties
propList = []
nonRing = True
for count, ring in enumerate(molecule.ringList):
if atomIndex in ring:
nonR... | 590a0b170081c4b345552804dc9bfdc52db90087 | 612,230 |
def enum_constraint(value, enum):
"""Test value in predefined set constraint."""
if str(value).lower() in enum:
return True
return False | b46bb36f462fed74b02a2399667f88d156ef1eec | 612,231 |
def required_padding(address, alignment):
""" Return how many padding bytes are needed to align address """
rest = address % alignment
if rest:
# We need padding bytes:
return alignment - rest
return 0 | b9fa01def41bf25661af877d71dbe24dff329671 | 612,235 |
import torch
def greedy_decoding(arc_f):
"""greedy_decoding
Arguments:
arc_f: a tensor in shape of (n, l+1, l+1)
length of the sentence is l and index 0 is <root>
Output:
arc_pred: a tensor in shape of (n, l), indicating the head words
"""
f_arc = arc_f[:, 1:, :] #... | 9a79643f4404511317d479ad0369bc234fcbd3fc | 612,239 |
def get_connection_info(file_name):
""" Get connection details from config file
Args:
file_name: name of file on disk including path (relative or absolute)
Returns:
a dictionary containing connection details
"""
# Initial empty dictionary to store connection details
connecti... | b4872235febce7a95f08516a41ba167f8f6f86a3 | 612,241 |
def lossAttack(model, images, labels, Loss):
""" Computes the loss value for a batch of samples.
model: instance of a nn.Module subclass
images: pytorch tensor with dimensions [batch,channels,width,height]
labels: pytorch tensor of shape [batch] containing the integer labels of the samples
loss: cal... | d6f99e3a9b9b44b966a9ced4991d4d045304400e | 612,242 |
def euclidean_distance(preference_space, person1, person2):
""" Return euclidean distance measure @ https://en.wikipedia.org/wiki/Euclidean_distance
Args
--------------
preference_space (dict) keys are users while values are dictionary of items and ratings
ie. preference_space={'userA:{'item1':'rati... | 516e75ce234931577223d663d90c3fd4e29e739a | 612,245 |
def get_feature_filename(
feature_extractor_name,
h_stride,
v_stride,
feature_height,
fov):
"""Returns a filename given feature map parameters."""
return "features_{}_h-{}_v-{}_height-{}_fov-{}.sstable@100".format(
feature_extractor_name, h_stride, v_stride, feature_height, fov) | 7a70e5f5e9f496fbb3bd0c47aa0e1824576c749b | 612,252 |
import re
def strip_punct( text ):
"""Remove punctuation and numbers.
Remove select punctuation marks and numbers from a text and replaces them with a space.
Non-permanent changes for evaluation purposes only.
Uses the :mod:`re` library.
Args:
text (str): Content to be evaluated... | 3b349b7cf7d3ddfd4aa3f96a792e38abcf354b2c | 612,253 |
def user_directory_path(instance, filename: str) -> str:
"""
Helper function to store images in `[...]/user_pk/filename`.
Parameters
----------
instance: :class:`models.Model`
The Model instance to get the PrimaryKey.
filename: :class:`str`
The filename to store.
"""
# ... | 50ae26292d42265c6724a79727e95197e369b186 | 612,254 |
def get_from_power_tuple(power_tuple, index):
"""
Extracts an exponent from an exponent tuple that may have been canonicalized
to be shorter than the expected length, by removing extra zeroes.
"""
if index >= len(power_tuple):
return 0
else:
return power_tuple[index] | 1c7afec1301b641448f12806f30d8411a0546d16 | 612,256 |
import json
import random
def get_substitutions(subs_json):
"""Randomly pull phrase variations from the substitutions file."""
with open(subs_json) as subs_file:
raw_subs = json.loads(subs_file.read())
return { k : random.choice(raw_subs[k]) for k in raw_subs } | 81ae67b35ad11b51eb029d758fc85149cf126e4d | 612,265 |
def is_mono(t):
""" Returns True if all values of _t_ are equal
and False otherwise.
"""
for i in t:
if i != t[0]:
return False
return True | 4b7322f64cb3e421e22319756f2ccf981ceb22ec | 612,266 |
def clamp(x: float, minval: float, maxval: float) -> float:
"""
Clamp value
"""
if x >= maxval:
return maxval
elif x <= minval:
return minval
return x | f65000bbd8ce2f92590f8a94db8ffc561c24fb5b | 612,268 |
import random
def roll_d66(num):
"""
D66 roller, which is a 36-result table where one D6 is the 1s digit and
the other is the 10s
"""
result = 0
rolled_die = 6
for _ in range(0, num):
result += random.randint(1, rolled_die)*10
result += random.randint(1, rolled_die)
re... | 154da0535571ce825805835f41fda5b7bae99526 | 612,270 |
import multiprocessing
def get_cores() -> int:
"""
Get numbers of available cores.
"""
return multiprocessing.cpu_count() | 0d5ac0a6ca3b1dc9f53894657bb6c0ef1962c15d | 612,274 |
from pathlib import Path
def format_output(output, runtype="prod", q1v4=False, bal=False,
exp_v_unexp=False):
"""
format_output(output)
Returns output path with subdirectory added based on the arguments.
Required args:
- output (Path): base output path
Optional args:
... | 22702273ee0ee99e793035620927ddf0efceaf4d | 612,278 |
from typing import Callable
from typing import Any
import inspect
def fn_ends_with_pass(fn: Callable[..., Any]):
"""
Check that function end with pass statement
(probably does nothing in any way).
Mainly used to filter callbacks with empty on_{event} methods.
Args:
fn (Callable[..., Any])... | e6c11e826c33f5e7b5ba7f6768f43a4048ba5c60 | 612,282 |
import json
def deduplicate_results(results):
"""
Removes duplicates from all SPARQL queries to various Virtuoso instances
Args:
results: List of results which may contain duplicates
Returns: Deduplicated list of results
"""
deduped = set()
for result in results:
deduped... | 0b5686fd4a7d526c816c08281f5722f5bfa9f46f | 612,284 |
def extract_species_strings(species, characteristics, species_string_dict):
"""
Extract the species strings from the species_string_dict based on the meta-species and characteristics given
Parameters:
species (meta-species object) = Instance of the meta-species to obtain the species str... | 2df6b3dfb1206a5797952ec035982eb4e92dd58f | 612,287 |
def convert_to_unix_line_endings(source):
"""Converts all line endings in source to be unix line endings."""
return source.replace('\r\n', '\n').replace('\r', '\n') | 0ae3742ed9a62da8ef3434eb852511548f50b8d2 | 612,291 |
import inspect
def get_python_function_arguments(f):
"""
Helper to get the parameter names and annotations of a Python function.
Examples:
"""
# Note that we only return non-optional arguments (we assume that any optional args are not specified).
# This allows to, e.g., accept max(a, b, *more,... | 3359b80824113c725335fd238cb93e43e18f0feb | 612,292 |
def get_attribute(attribute_list, name):
"""Finds name in attribute_list and returns a AttributeValue or None."""
attribute_value = None
for attr in attribute_list:
if attr.name.text == name and not attr.is_default:
assert attribute_value is None, 'Duplicate attribute "{}".'.format(name)
attribute... | 4bdfed766122eae2484c2b1dbe28f853caf0caec | 612,294 |
from typing import List
from typing import Pattern
import re
def combine_multiple_regexes(regexes: List[str]) -> Pattern[str]:
"""Combine multiple regular expressions in a single pattern.
Parameters
----------
regexes: List[str]
A list of regular expressions.
Returns
-------
Patt... | d561005c04ef1f664fec43c32c4fa8a9f87fc7e5 | 612,301 |
def _FindRuleForRegister(cfi_row, reg):
"""Returns the postfix expression as string for a given register.
Breakpad CFI row format specifies rules for unwinding each register in postfix
expression form separated by space. Each rule starts with register name and a
colon. Eg: "CFI R1: <rule> R2: <rule>".
"""
... | 1bfb1d2f70eee56956630814c5c28f900a00ba6a | 612,308 |
def gauss_fill(std):
"""Gaussian fill helper to reduce verbosity."""
return ('GaussianFill', {'std': std}) | afa06a76157cf287e669fbe3be4757dc3d823c17 | 612,309 |
from pathlib import Path
def _tdep(target, dep):
"""Make a target name into a '.wants/requires' dir as a Path type."""
return Path(target + "." + dep) | 49b963f00b5bfe851b640b5e3b2bbf1e9b4591be | 612,310 |
def is_real_number(obj):
"""Yield whether an object is a real number"""
return isinstance(obj, float) or isinstance(obj, int) | 87ea9dde0c87f2bf889b3b77039e4142af8420e8 | 612,311 |
import re
def tag_to_label(tag: str) -> str:
"""Return the spaced and lowercased label for the given camelCase tag."""
return re.sub(r'(?<!^)(?=[A-Z])', ' ', tag).lower() | 262d72d343c99f509e91da07fbd307ac6c30836b | 612,313 |
def copy_file(ctx, src_file, dest_path, sibling = None):
"""
Copy a file to a new path destination
Args:
ctx: the <ctx> object
src_file: the source file <File>
dest_path: the destination path of the file
sibling: a file to use as a sibling to declare_file <File>
Returns... | d746edb7ac74774ae6081678c3187f6cd9a9d913 | 612,321 |
from typing import Tuple
import torch
def prior(topics: int) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Prior for the model.
:param topics: number of topics
:return: mean and variance tensors
"""
a = torch.Tensor(1, topics).float().fill_(1.0)
mean = a.log().t() - a.log().mean(1)
var = ... | d4c127e7e64cb448c2e47fd9ca7db02f7962e3e5 | 612,322 |
def _get_pin_cw(pincount, loc):
"""Helper function to locate pin number for cw_dual.
Args:
pincount: Total number of pins
loc: Starting location
Returns:
pin_number: Starting pin number
"""
pins_per_side = pincount // 2
if loc == "top_left":
return 0
elif lo... | ead41f7590b0a431aa0dc96db3a4261e6a078859 | 612,325 |
def merge_lists(*args):
"""Merge an arbitrary number of lists into a single list and dedupe it
Args:
*args: Two or more lists
Returns:
A deduped merged list of all the provided lists as a single list
"""
out = {}
for contacts in filter(None, args):
for contact in conta... | 3d48bd0b1b36af5f12f730a8442991aa91797d64 | 612,326 |
def average(avg_list):
"""Averages all values in the list."""
if len(avg_list) == 0:
return 0
avg = sum(avg_list) / len(avg_list)
return avg | aa8822fe97ad2d7687306f347acdbae69114dccd | 612,327 |
from typing import Union
from typing import Dict
from typing import List
from typing import Any
def _func_minimum(
target_attr: Union[
Dict[Union[float, int], Union[float, int]], List[Union[float, int]]
],
*_: Any,
) -> Union[float, int]:
"""Function for returning the minimum element of a list... | 68d5b43772a4ad735a8250e4fa835b97cdb5bb27 | 612,332 |
def percent_nan(data_series):
"""
For data_series, calculate what proportion of rows are NaN.
@param data_series: data to check for NaNs
@type data_series: Series
@return: A number representing the proportion of data in data_series that is NaN
@rtype: Float
"""
nan_count = data_series.is... | f03998b0a7d98112566bc339ed118891d8d05a7e | 612,333 |
def builtin_2nip(a, b, c, d):
"""Modify the stack: ( a b c d -- c d )."""
return (c, d) | df7723ecd5dda70b8138c4c59d8f37adc101a645 | 612,334 |
import math
def calculateDistance(coordinate1, coordinate2) -> float:
"""Calculates the distance between two 2D coordinates.
Args:
coordinate1 (list): x, y coordinates.
coordinate2 (list): x, y coordinates.
Returns:
float: Distance between coordinates.
"""
deltaX = math.fabs(coordinate1[... | 57320f41fb9b66653fab83449a438043085a2887 | 612,341 |
from typing import OrderedDict
def get_questions_from_manifest_by_id(content_manifest):
"""Returns an OrderedDict of all questions in a content manifest, {question.id: question, ...}"""
questions = OrderedDict()
for section in content_manifest.sections:
for question in section.questions:
... | d6376d9960315baca3b354bf3d9377c29d4a7d79 | 612,342 |
def lists_overlap(l1, l2):
"""
This functions return whether two lists overlap
:param l1: list 1
:type l1: list
:param l2: list 2
:type l2: list
:return: whether the list overlap. If TRUE, then the list overlap
:rtype: bool
"""
intersection_set = set(l1).intersection(set(l2))
... | 24fd92b48bf40b8f7900b290667ed22c8c73ec86 | 612,348 |
import re
def remove_zero_padded_dates(date_string):
"""Mimic %-d on unsupported platforms by trimming zero-padding
For example:
January 01 2018
Becomes:
January 1 2018
The regex finds a space or a hyphen followed by a zero-padded
digit, and replaces with the symbol (space or hyp... | 100b06eee8c756f289be7e457be67d2334160a6c | 612,353 |
def FindMatch(matrix, seq1, x, seq2, y, options, max_advance=10, min_match=3):
"""advance on sequence2 from position y until you find a minimum match of
min_match residues.
returns the offset in y. If no match is found, an offset of 0 is returned.
"""
# for z in range(0,10):
# print seq1.asCha... | 0f5cbd5f7f2f556762a0c4e2289e3b8fdd9342a5 | 612,355 |
def xrd_from_atto(atto_amount: int) -> float:
""" Converts an amount of Atto to their XRD equivalent
Args:
atto_amount (int): The amount of atto to get in XRD.
Returns:
float: The equivalent amount of XRD.
"""
return atto_amount / (10**18) | 646cd7b2b85b00ee6ef62b5863444d9ef34b3874 | 612,356 |
import dataclasses
def field(pytree_node=True, serialize=True, cache=False, **kwargs):
"""Mark a field of a dataclass to be:
Args:
pytree_node: a leaf node in the pytree representation of this dataclass.
If False this must be hashable
serialize: If True the node is included in the... | 8c2170b742273dc89f4e4a4b7d035ca496971653 | 612,360 |
def flatten_list(l):
"""Flatten a multidimensinoal list to a 1 dimensional list.
Parameters:
l (list): The list that you want to flatten.
Returns:
list: ! dimensional list.
"""
try:
return flatten_list(l[0]) + (flatten_list(l[1:]) if len(l) > 1 else []) if type(l) is list else [l]
... | 49cd6329a8a821dd35420e76f3a7f043ff0241ed | 612,365 |
def split_type_line(type_line):
"""Splits the comment with the type annotation into parts for argument and return types.
For example, for an input of:
# type: (Tensor, torch.Tensor) -> Tuple[Tensor, Tensor]
This function will return:
("(Tensor, torch.Tensor)", "Tuple[Tensor, Tensor]")
... | 14d354a0881b5e07d0893fc37ee1e29a1a8bb40d | 612,367 |
def get_field_description(field, description_keyword='description'):
""" Gets field description if available, using the description_keyword"""
return getattr(field, description_keyword, '') | fdba387f541d4e1d29c1b95d9a8a751d16737806 | 612,374 |
def valid_chrom(arg):
"""Check if a string represents a valid chromosome"""
arg = arg.lower()
if arg[:3] == 'chr':
return True
if arg.isdigit() or arg in ('x', 'y', 'mt'):
return True
if arg[:8] == 'scaffold' or arg[:2] == 'gl' or arg[:3] == 'par':
return True
return Fals... | 7b1483cbff37bf222a9539719a288d0e6909dbc8 | 612,375 |
def read_predictions_from_file(filename):
"""
Reader for the gold file and the template output file.
Return values are four arrays with article ids, labels
(or ? in the case of a template file), begin of a fragment,
end of a fragment.
"""
articles_id, span_starts, span_ends, gold_labels ... | 1b7663d11fa341d72a3f2f8733f3625b1d096324 | 612,376 |
def any_match(record, patterns):
"""Check record for match with any of the patterns
:param record: record string to search for patterns
:param patterns: list of regexes
:return: True of record matched with any of the patterns; False otherwise
"""
return any(map(lambda x: x.search(record), patter... | 507658c3bd2ae3194e09c10b04f8ca1df017df25 | 612,379 |
def char2note(char):
"""Convert a char to a midi note number wih the followung syntax. First
the note ('a', 'b' , etc..) then the number of the note, and finally
it's accentuation ('-', '=', '+')."""
if char == 's': # Return a silence
return 0, 0, 0
notes = {'a': 69, 'b': 71, 'c': 60, 'd': ... | b4c4ef162083db837acfedb28e9d66724edb736b | 612,380 |
def _convert_terms_to_spin_blocks(terms, n_orbitals: int, n_spin_components: int):
"""
See explanation in from_openfermion in conversion between conventions of netket
and openfermion.
Args:
terms: the operator terms in tuple tree format
n_orbitals: number of orbitals
n_spin_comp... | 77ac3434b4bc8b3b1808e208b92f5fa20080def2 | 612,381 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.