content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def unorderable_list_difference(expected, actual):
"""Same behavior as sorted_list_difference but
for lists of unorderable items (like dicts).
As it does a linear search per item (remove) it
has O(n*n) performance."""
missing = []
while expected:
item = expected.pop()
try:
... | 012bc28b91fdcb76b23b19ced1e81a0bd8609fab | 662,964 |
from pathlib import Path
import hashlib
def hash_file(fpath: Path, md5=None, hash_path=False, root=None):
""" Hash a file (and optionally, its path)
Adapted from https://stackoverflow.com/a/22058673/2700168"""
buf_size = 65536
md5 = hashlib.md5() if md5 is None else md5.copy()
root = root or fpa... | 8265bf18d216931fbf1939428a7029b887785284 | 662,966 |
import re
import argparse
def year_arg(value):
"""Validate the 'year' command-line argument."""
if not re.fullmatch(r'\d{4}', value, re.ASCII):
raise argparse.ArgumentTypeError("invalid year {!r}".format(value))
return value | 2abd2c2714d91ad5f7d2663c5b7fb1a16f733ed1 | 662,967 |
def string_bool(argument):
"""
Converts True, true, False, False in python boolean values
"""
if argument is None:
msg = 'argument required but none supplied; choose from "True" or "False"'
raise ValueError(msg)
elif argument.lower() == 'true':
return True
elif argument.... | 11ed032d3c757e0ea4a6afd681fcaab18daeaad8 | 662,968 |
def get_margin_value():
"""Return the margin pixel around a cell coordinate used to define its
bounding box.
Returns
-------
_ : int
Margin value (in pixels).
"""
# should be greater or equal to 2 (maybe 1 is enough)
return 5 | 688e36fa76ce667af359457684f552b721483cf4 | 662,969 |
import time
def start():
"""
Short-hand for starting a timing measurement.
"""
return(time.time()) | be54703df13b5966406c9bbb04c8e4dba16032b0 | 662,970 |
def CheckAddonStatus(modelClient, addOn = "stress_analysis_active"):
"""
Check if Add-on is reachable and active.
For some types of objects, specific Add-ons need to be ennabled.
Args:
modelClient (Model.clientModel)
method_or_type (string): method or type of SOAP client
Returns:
... | 53324de72892564852eda608444ccaf6b3508d5d | 662,971 |
def is_enabled(ext):
"""Check to see whether a plugin should be enabled. Assumes that the
plugin extends PluginBase.
:param ext: The extension instance to check.
:return: True if it should be enabled. Otherwise false.
"""
return ext.obj.enabled() | 87a8b495f90df70cefba7978a0d1730d8d35d480 | 662,972 |
import pickle
def load_model(model_filepath):
""" Loads the model from disk
INPUT
model (model object) -- model to be evaluated
OUTPUT
model_filepath (str) -- Path where the model will be loaded from
"""
# load the model from disk
model = pickle.load(open(model_... | 1f32d1b4c1cc6dbbb1d247788a219831c20353b3 | 662,973 |
def most_common_dict(a_dict: dict):
"""Returns the most common value from a dict. Used by consensus"""
val_list = list(a_dict.values())
return max(set(val_list), key=val_list.count) | 4651673d73e93d7a61fee222e976bfd3185487f9 | 662,974 |
import json
def custom_response(res):
""" De-Serializes the JSON response
"""
try:
return json.loads(res.text), res
except:
return "No JSON available", res | b029b1010a2b8f02cc92305f7d08b1f53630e3ce | 662,975 |
def rename_band(bandpath):
"""
Bring bandname from CAAPR convention to Williams convention.
"""
def _any_in(candidate_parts, string):
for part in candidate_parts:
if part in string:
return True
return False
# GALEX_NUV.fits -> GALEX_NUV
bandname = ba... | 886f33b58669e7954dc2252ac312634300bba1a5 | 662,977 |
def trihex_to_tris(a, b, c):
"""Given a trihex, returns the co-ordinates of the 6 triangles it contains, using co-ordinates as described in updown_tri"""
n = a + b + c
if n == 0:
return [
(a * 2 + 1, b * 2, c * 2),
(a * 2 + 1, b * 2 + 1, c * 2),
(a * 2, b * 2 + 1,... | 4256d92af37d27f63f984807e7936fb7e5d3003f | 662,978 |
import torch
def reference_orgqr_batch(v, tau, checks=True):
"""
Unoptimized differentiable implementation of batched ORGQR.
Memory consumption linear in matrix rank.
Intended for use only within the test suite.
"""
if checks:
assert torch.is_tensor(v) and torch.is_tensor(tau)
... | 76a63a4b9631efae97fd903ff16fcbbe5d45000a | 662,979 |
def count_characters(array: list):
"""given a list:array of strings return the character count"""
if len(array) == 1: # base case
return len(array[0])
elif len(array) == 0: # edge case of empty array
return 0
else:
return len(array[0]) + count_characters(array[1:]) | b0f4058ab38a6d221457ee1583000d71b5a4fa44 | 662,981 |
import json
import itertools
def parse_template_index():
"""Load json that defines template structure
"""
with open('devopstemplate/template.json', 'r', encoding='utf-8') as handle:
template_dict = json.load(handle)
template_index = list(itertools.chain(*template_dict.values()))
return... | 5fb57a97dd73cdee235c5cf6e3b20d90385592c6 | 662,982 |
def filter_type(data, titletype: str):
"""
Filters the data so that it only returns rows with the
defined value 'titletype' in the field titleType.
Parameters:
data = IMDb dataframe that contains the column 'titleType'.
titletype = String value used to filter the data.
Returns: A dat... | 5da3499d9fdf6331ddfd4b2287d5f2fc0d685350 | 662,983 |
def concatenate_matrices(matrices):
"""
This function creates a concatenated matrix from a list of matrices
Arguments:
matrices: A list of tranformation matrices
Returns:
_transform: Concatenated matrix
"""
_transform = matrices[0]
for i in range(1,len(matrices)):
... | 2beaa3b99b4cd6dca8a1d2db58b3c91458f4559c | 662,984 |
def is_overlapping(node2comm):
"""Determine whether a graph partition contains overlapping communities.
Parameters
----------
node2comm : list of set of nonnegative integers **or** ndarray
Community structure. A mapping from node IDs [0..NN-1] to community
IDs [0..NC-1].
Examples
... | c2a2b2c8b396dd8117a2ce354b43fdea20176ce1 | 662,985 |
import re
def remove_extra_quotation(text: str) -> str:
""" Removes extra quotation marks
:param text: Text to be cleaned
:return: Clean text
"""
text = re.sub(r'\"{2,}', '"', text)
return re.sub(r'\'{2,}', "'", text) | 57e59b88ebeae9d299e91306ef6b8f438f23ef91 | 662,986 |
def promote_closest(context, int_type, candidates):
"""
promote_closest(Py_ssize_t, [int_, long_, longlong]) -> longlong
"""
for candidate in candidates:
promoted = context.promote_types(int_type, candidate)
if promoted == candidate:
return candidate
return candidates[-1... | dc6b788e335fb9b1e1b64f19bc921e0927e6ae57 | 662,987 |
import threading
import tqdm
def provide_progress_bar(function, estimated_time, tstep=0.2, tqdm_kwargs={}, args=[], kwargs={}):
"""Tqdm wrapper for a long-running function
args:
function - function to run
estimated_time - how long you expect the function to take
tstep - time delta (sec... | 195525f01359ec99bb8c7e8ef195ed4fa4c56d93 | 662,988 |
def masked_topk(logits, vocab, k, dim, functional=False, var=True, op=True, nullable=False):
"""
assumes dimension of logits includes </s>, not includes <pad>, (, ), ","
only use </s> for empty child for special cases
"""
topk_p, topk_idx = logits.topk(logits.shape[dim], dim=dim)
new_top_p, new_... | 31f466e2d0f5597f42915c1dc76dac1ba54c1a7c | 662,989 |
def intToBits(val, b=8):
"""
Returns list of binary data representing integer value.
"""
bits = [] # bad
for bit in format(val, '0' + str(b) + 'b'): # bad (?)
bits.append(bit)
return [int(bit) for bit in bits] | b46370801b43882a20e108746a331d5d97525c1d | 662,990 |
import numpy
def initial_hessian_identity(param_diff, jacobian,
previous_jacobian):
"""Return identity matrix, regardless of arguments."""
return numpy.identity(jacobian.shape[0]) | 6279fef9324f5066cfbd876d135c5092e5065dc4 | 662,991 |
def TopologicalSortSimple(ideps):
"""Simple topological sort working on sequence of integer indices."""
# Returns permutation indices (list of integers).
# Using variable names `cons` for dependent, `prod` for dependency
# (consumer, producer) to increase readability.
# cons is implied by the index into ideps... | a884b07e4b75a867242c36337e3dccebe404cc68 | 662,992 |
import os
import errno
def makedirs(path, mode=0o777):
"""
Create a directory if it doesn't already exist (keeping concurrency in mind).
:param path: The pathname of the directory to create (a string).
:param mode: The mode to apply to newly created directories (an integer,
defaults ... | 23ba0932bdee473bd8782c78319ea67195cf5df6 | 662,993 |
def find_io_by_name(input_list: list, name: str):
"""Retrieve an item from a list by its name attribute
Arguments:
input_list {list} -- A list of IO Items
name {str} -- The name to filter for
Raises:
ValueError: No item with this name was found
Returns:
IOItem -- An IO... | 7ad962935a04b20f813d6a822c0f770adb973beb | 662,994 |
def get_tasks_args(parser):
"""Provide extra arguments required for tasks."""
group = parser.add_argument_group(title='tasks')
group.add_argument('--task', type=str, required=True,
help='Task name.')
group.add_argument('--epochs', type=int, default=None,
he... | 598be6d15a341e6ed05e37d59c7bc81b88df4498 | 662,995 |
import torch
def compute_fg_mask(gt_boxes2d, shape, downsample_factor=1, device=torch.device("cpu")):
"""
Compute foreground mask for images
Args:
gt_boxes2d: (B, N, 4), 2D box labels
shape: torch.Size or tuple, Foreground mask desired shape
downsample_factor: int, Downsample facto... | afc295bfd6fc9d2fa924474631dd0cc19bd301ae | 662,996 |
import torch
def accuracy(y: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
"""Computes multi-class classification accuracy"""
assert y.shape[:-1] == t.shape, f"y {y.shape}, t {t.shape} is inconsistent."
pred_label = torch.max(y.detach(), dim=-1)[1]
count = t.nelement()
correct = (pred_label == t... | 50be0cd55ac4a035c32d88c390eba1f7d5e07a44 | 662,998 |
def dict_to_tuple(dict):
"""Return RSA PyCrypto tuple from parsed rsa private dict.
Args:
dict: dict of {str: value} returned from `parse`
Returns:
tuple of (int) of RSA private key integers for PyCrypto key construction
"""
tuple = (
dict['modulus'],
dict['publicExponent'],
... | f404f17051e4eb0280be18543c96f1c07a3999b0 | 663,001 |
import os
def existe_archivo(archivo_csv):
""" Verifica que el archivo exista dentro del directorio actual o de la ruta fijada"""
if os.path.isfile(archivo_csv):
return True
else:
return False | 18fb25a84f4ac889d381a13977f5ae23f3bc71fe | 663,002 |
def get_word_freq(word_list, normalize=True):
"""Returns a sorted list of (word,word count) tuples in descending order.
The frequency is normalized to values between 0 and 1 by default."""
word_freq_dict = {}
for w in word_list:
if w in word_freq_dict:
word_freq_dict[w] += 1
... | 42084d118456eec3a29d667bcb248330a82dd413 | 663,003 |
def extract_stations(soup):
""" Extract station selector and station name
"""
station_list_html = soup.find_all(attrs={'id': 'station_name'})[0]
station_children = station_list_html.findChildren(
'option', recursive=False)
station_selector_list = []
station_name_list = []
for statio... | 4d04090fcde65179aac395050d54a971fcfb2612 | 663,004 |
def get_drop_dates_and_len(df, allow_missing_num=3):
"""
Find missing values and get records to drop
"""
missing_num = df.total.isnull().astype(int)\
.groupby(df.total.notnull().astype(int).cumsum()).sum()
drop_missing_num = missing_num[missing_num > allow_missing_num]
drop_datetimes = d... | 6c2863e7bc9336f6d524ac2af2c78121f828841b | 663,005 |
from operator import concat
def concat_list(wire_list):
"""
Concatenates a list of WireVectors into a single WireVector
:param wire_list: list of WireVectors to concat
:return: WireVector with length equal to the sum of the args' lengths
The concatenation order is LSB (UNLIKE Concat)
"""
... | 2938cae9ce26ba4e4507b42bea3c55d7a148ff21 | 663,006 |
def split_doc_num(doc_num, effective_date):
""" If we have a split notice, we construct a document number
based on the original document number and the effective date. """
effective_date = ''.join(effective_date.split('-'))
return '{0}_{1}'.format(doc_num, effective_date) | 57f3709955d5e5c49f40e1a9b2d0917304f6cab6 | 663,008 |
import os
def du(path):
"""Return the size of the file or directory."""
if not os.path.exists(path):
raise Exception("Path does not exist: " + path)
if os.path.isfile(path):
return os.path.getsize(path)
else:
total = 0
for root, dirs, files in os.walk(path):
... | 647a60266bb8e5e0c5e403d0fd3ffee3cf136754 | 663,009 |
from typing import IO
def isatty(fh: IO) -> bool:
"""Return True if fh has a controlling terminal.
Notes:
Use with e.g. :data:`sys.stdin`.
"""
try:
return fh.isatty()
except AttributeError:
return False | c4cefa8f544aac67fb0e80366bc62c974f2bd4a0 | 663,010 |
import re
from typing import Tuple
def parse_version_string(name: str) -> Tuple[str, str]:
"""Parse a version string (name ID 5) and return (major, minor) strings.
Example of the expected format: 'Version 01.003; Comments'. Version
strings like "Version 1.3" will be post-processed into ("1", "300").
The pars... | 0680cd64e28c7ddb5c0aeae5cb868387c8bd5a35 | 663,011 |
import shlex
def prepare_environment(variables):
"""Prepare a `env` shell command to set up the requested process environment.
NOTES:
- an environment variable value can't reference another environment variable (e.g. you can't set
FOO to "${USER}_foo".
- due to how we chain commands together i... | 496e6815f079378224f9b5a062eef5b2c616c509 | 663,012 |
def autocrop_array_shapes(input_shapes, cropping):
"""Computes the shapes of the given arrays after auto-cropping is applied.
For more information on cropping, see the :func:`autocrop` function
documentation.
# Arguments
input_shapes: the shapes of input arrays prior to cropping in
... | acf407935814ae9ffb77a8b7ff3dd747be04bb03 | 663,013 |
def degc_to_kelvin(x):
"""Degree Celsius to Kelvin
Parameters
----------
x : float or array of floats
Air temperature in deg C
Returns
-------
output : float or array of floats
Air temperature in Kelvin
"""
return x + 273.15 | 52a7c242f08a0e0cb849fc8433ec143f4e19d4fb | 663,014 |
def letter_count(word, letter):
"""
Returns the number of instances of "letter" in "word"
"""
return word.count(letter) | 17121bb6820db0ece553cc0021ad4daba70df945 | 663,016 |
def make_reducer(delimiter):
"""Create a reducer with a custom delimiter.
Parameters
----------
delimiter : str
Delimiter to use to join keys.
Returns
-------
f : Callable
Callable that can be passed to `flatten()`'s `reducer` argument.
"""
def f(k1, k2):
if ... | 7454e221e53abb915a0ba84badd618a6030e512c | 663,017 |
import time
def read2(reader, read_len=20):
"""Read one line from reader asynchronously."""
data = []
temp = " "
while "\n" not in temp and temp != "":
temp = reader.recv(read_len)
temp = temp.decode("utf-8")
data.append(temp)
time.sleep(0) # allows thread switching
... | 48f6800e901a5634a0d360f061698b59e19a95c6 | 663,018 |
import os
def delete_missing_pairs(input_data, pair_data):
"""Delete items from input data that does not have a corresponding item in pair data
Args:
input_data (list): list of file paths to check
pair_data (list): list of file paths to find a match
Returns:
list: list of files w... | 98a771faaeb22e0392ceba0277b08903ebb80ffb | 663,019 |
def resource_is_object(resource):
"""Check if the resource is a simple object."""
if resource:
return (
"metadata" in resource
and "kind" in resource
and "name" in resource["metadata"]
)
return False | b543e1595d1862b1702404bef4d90105fc9bc75b | 663,020 |
def cleanString(s,spaces_for_underscores=False):
"""cleans a string from special chars and spaces"""
if spaces_for_underscores: s= s.strip().replace(' ','_')
return "".join(x for x in s if x.isalnum() or x == '_') | 7938990547dbec3bed6e96b4360f2c41ff46a239 | 663,022 |
import random
def roll_die():
"""Simulate a single roll of a 10-sided die"""
roll = random.randint(1, 10)
return roll | 3e18839ec41c7c89514734fed9401a0751df2b62 | 663,023 |
import re
def getROS(fontPath):
"""
Check to see if font is a CID-keyed font by
looking for the keys Registry, Ordering, Supplement.
We are looking for the text:
/Registry (Adobe) def
/Ordering (Japan1) def
/Supplement 3 def
"""
Reg = Ord = Sup = None
with open(fontPath... | 18c4d5aaa1610a60ca597aafbed8599f7fbe3834 | 663,024 |
import warnings
def div(a, b):
"""Divides a number 'a' by another number 'b'
Parameters
----------
a: int or float
Number to be divided
b: int or float
Number to divide by
Returns
-------
d: int or float
Result of the division
""... | 76c43818c6336d1b6d321fad2150f9b85e3d6774 | 663,025 |
import os
def _get_source_infos(experiment_root, person_id, sources):
"""
Extract path of the features files and additional useful informations out of the selected feature name.
Parameters
----------
experiment_root: str
path to the experiments root folder
person_id: str
which... | 0bf3ab2b626c97de124b8ef701826e9eef4ec650 | 663,026 |
def test_abs(temp_x):
"""This function is used to \
calculate the absolute value of a numbere"""
if temp_x < 0:
return -temp_x
return temp_x | a1dcaafb4ed76489114fdebee387058250790929 | 663,027 |
def get_param_value(param_name, args, config):
"""Get value of a named command parameter either from args or from config.
"""
param_val = None
# If param_name is available in config use it
if config and config.get('default', None) and config['default'].get(param_name, None):
param_val = conf... | f3e2b3b3a769d5ac3ef5fdb0677cc4d21a916452 | 663,029 |
def CO2_to_fCO2(CO2, Ks):
"""
Calculate fCO2 from CO2
"""
return CO2 / Ks.K0 | eb08fdf824047536eb47c9927f434d1f8ca499c5 | 663,030 |
def chr_start_stop_to_sj_ind(chr_start_stop, sj):
"""Transform a 'chr1:100-200' string into index range of sj dataframe
Parameters
----------
chr_start_stop : str
Genome location string of the format chr:start-stop
sj : pandas.DataFrame
Dataframe of splice junctions as created by re... | 361a9a0c893059fbf5d51868826a7151b22fb59e | 663,031 |
import time
def to_timestamp(dtime):
"""Converts datetime to unix timestamp"""
return int(time.mktime(dtime.timetuple())) | ad9267879f268ccb97a82a350e0fb9e2cf56696a | 663,032 |
def selection_sort(a):
"""
Use selection sort algorithm to sort array/list
"""
i, n = 0, len(a)
while i < n - 1:
j, small = i + 1, i
while j < n:
if a[small] > a[j]:
small = j
j += 1
a[i], a[small] = a[small], a[i]
i += 1
re... | c483b07d17805172e348ecd671371e8499680304 | 663,033 |
def nmc_LGM50_thermal_conductivity_ORegan2021(T):
"""
Wet positive electrode thermal conductivity as a function of the temperature from
[1].
References
----------
.. [1] Kieran O’Regan, Ferran Brosa Planella, W. Dhammika Widanage, and Emma
Kendrick. "Thermal-electrochemical parametrisation ... | 3b7daa2e9a2be76a4b1ef7b92fb7f2800d77e542 | 663,034 |
def parse_isomer_spin(spin):
"""Parses nubase style spin information
returns dictionary {value, extrapolated} """
result = {}
result['extrapolated'] = True if spin.count('#') > 0 else False
if result['extrapolated']:
spin = spin.replace('#', ' ')
result['value'] = spin[0:8].strip()
... | b45154d71b2d32b4bf639e7b072c4ae17f1dc1eb | 663,035 |
from typing import Union
import os
def delete(file: str) -> Union[str, None]:
"""Deletes file"""
if os.path.exists(file):
os.remove(file)
else:
return f"{file} does not exists. Make sure the name is correct or you need to put the file path." | 59829ae7f57ad0e28dd448b75831ef23073ecd49 | 663,036 |
def in_exception_list(*exc_types):
"""Build a predicate function that checks if an exception is a subtype from a list"""
def matches_types(thrown_type, _):
return issubclass(thrown_type, exc_types)
return matches_types | 4fe3d85142ed866a07f4ece1c8ab7cc6f66d7280 | 663,037 |
def check_order(order: int) -> int:
"""Confirms the input is a valid parity order."""
if not isinstance(order, int):
raise TypeError("`order` must be an integer.")
if order <= 0:
raise ValueError("`order` must be greater than zero.")
return order | 884bd95adbbcfcd5f6544bf981db50e269389408 | 663,038 |
def wc(filename):
"""A function wc(filename) that returns the number of words in file filename.
The name wc stands for Word Count."""
f = open(filename, 'rt')
content = f.read()
f.close()
return len(content.split()) | 0ad9fc53992ee202a1a1c71add1b5fa5966503bd | 663,039 |
def get_h5_dataset_shape_from_descriptor_shape(
descriptor_shape, ep_data_key, ep_data_list
):
"""
Return the initial shape of the h5 dataset corresponding to the specified data_key.
Initially the dataset will have length 0. It will be resized when data is appended.
The descriptor shape will be eit... | b3f0f00d19bf56e82930c1f6ca705e853f8f0ad9 | 663,040 |
def uri_leaf(uri):
"""
Get the "leaf" - fragment id or last segment - of a URI. Useful e.g. for
getting a term from a "namespace like" URI. Examples:
>>> uri_leaf('http://example.org/ns/things#item')
'item'
>>> uri_leaf('http://example.org/ns/stuff/item')
'item'
>>> ... | 05d9e512c9cea837344a5a331488a9e7698815d4 | 663,041 |
def clean_tree(parseresults):
"""returns a set of nested lists/tuples from parsed file. Maintains the original folder structure but only containing foldernames and hyperlinks"""
try:
itemlist=parseresults.HyperLink.asList()
except:
itemlist=[] # an empty folder
for item in parseresults:
... | 48184bd427a6046ff2edf17baffbf548463db84b | 663,042 |
import asyncio
async def wait_for_event(evt, timeout): # pylint: disable=invalid-name
"""Wait for an event with a timeout"""
try:
await asyncio.wait_for(evt.wait(), timeout)
except asyncio.TimeoutError:
pass
return evt.is_set() | b8b2616f36f12db092c8f12a402115df863dff6f | 663,043 |
import sys
def get_chromedriver_url(version):
"""
Generates the download URL for current platform , architecture and the given version.
Supports Linux, MacOS and Windows.
:param version: chromedriver version string
:return: Download URL for chromedriver
"""
base_url = 'https://chromedriver... | c3c1914d725e56f0e13482c65f089509f848a19d | 663,044 |
def TRUE():
"""
Returns the logical value `True`. You may also use the value `True` directly. This
function is provided primarily for compatibility with other spreadsheet programs.
>>> TRUE()
True
"""
return True | b9cae99e4e7ecc1e5ec99b0f6a7ca7f871aae3e9 | 663,045 |
def _GenerateJsDoc(args, return_val=False):
"""Generate JSDoc for a function.
Args:
args: A list of names of the argument.
return_val: Whether the function has a return value.
Returns:
The JSDoc as a string.
"""
lines = []
lines.append('/**')
lines += [' * @param {} %s' % arg for arg in ar... | ec8fd41661dadc011bd76c2cc3e51e50b46ee019 | 663,046 |
def metric_count_active(result, base_key, count):
"""Counts the number of chain active ("o") for the specified keys."""
active = 0
base_keys = base_key.split(",")
for base_key in base_keys:
for i in range(1, count):
key = base_key.replace("[i]", str(i))
if key in result:
... | 78cc02c7ac185752dc7bd1a62ff2c519ad491de9 | 663,048 |
import os
def _fetch_parent_item(file_id, client, dest):
"""
Fetches the whole item that contains the given file ID into the given
destination directory. Returns the path to the specific file once the
download is complete.
"""
target_file = client.getResource('file', file_id)
item = client... | 0a763821a7e6d74c37adc224d176a9dcc3fdc1bd | 663,049 |
def undiag(*variables):
"""Resets the usual broadcasting strategy for the given ltn variables.
In practice, `ltn.diag` is designed to be used with quantifiers.
Every quantifier automatically calls `ltn.undiag` after the aggregation is performed,
so that the variables keep their normal behavior outsid... | ce9c818ab28d5c9ab5ab6812d7e0d4bdc756e9b9 | 663,050 |
import math
def loudness_level(sone: float) -> float:
"""
sone: in sones, >1
typically between 1 and 140
"""
return 40.0 + math.log2(sone) | d9f011ffde7bd7ece17ac3452ee817d36243fe35 | 663,051 |
def _testLengthBoundaryValidity(dataLength, tableDirectory):
"""
>>> test = [
... dict(tag="test", offset=44, length=1)
... ]
>>> bool(_testLengthBoundaryValidity(45, test))
False
>>> test = [
... dict(tag="test", offset=44, length=2)
... ]
>>> bool(_testLengthBoundaryVal... | e5876302e2fdeb2cb1b708f49777b73183d2a938 | 663,052 |
def get_neighbor(rows, ele):
"""
:param rows: lst, letters get from user
:param ele: lst, current letter position
:return neighbor: lst, the location tuple next to ele
"""
neighbor = []
# find valid location tuples that in 3x3 grid centered by ele
for x in range(-1, 2):
for y in range(-1, 2):
test_x = ele[... | 265b71ba5c5b3415bfd7de2746ed3e370e66c467 | 663,053 |
import os
def _env(env):
"""If ENV exist but with empty value, return empty string."""
return env if os.getenv(env) else '' | 60debd50f60cb720082a1cdcde11b857d9e98331 | 663,054 |
def get_unset_keys(dictionary, keys):
"""
This is a utility that takes a dictionary and a list of keys
and returns any keys with no value or missing from the dict.
"""
return [k for k in keys if k not in dictionary or not dictionary[k]] | 8f9ef6d753a7db6d7ee1426de141ec27459c510f | 663,055 |
from typing import List
from typing import Any
def get_search_result_path(search_response: List[Any]) -> str:
"""Extracts a search result path from a search job creation response
:type search_response: ``List[Any]``
:param search_response: A search job creation response
:return: A path to the search... | a973c31d9342e0e6da67e4ed265fc80560292581 | 663,056 |
def fichier2str(nom_fichier):
"""
Renvoie le contenu du fichier sous forme de chaîne de caractères.
"""
with open(nom_fichier, 'r') as f:
chaine = f.read()
return chaine | 7d7296a8e0d8df5d3d2841cb398dd4379d6cee46 | 663,057 |
def remove_optgroups(choices):
"""
Remove optgroups from a choice tuple.
Args:
choices (tuple): The choice tuple given in the model.
Returns:
The n by 2 choice tuple without optgroups.
"""
# Check whether the tuple contains extra optgroup
if isinstance(cho... | d02bf9d5da6717569c4a673b3d15d66f98a623f6 | 663,058 |
def underline_2_hump(text, big=True):
"""
下划线连接转为大小驼峰
:param text: 需要转换的字符串
:param big: 是否为大驼峰, 默认为True, 为False时表示要转换小驼峰
"""
arr = text.lower().split('_')
res = []
for i in arr:
res.append(i[0].upper() + i[1:])
if not big:
res[0] = res[0][0].lower() + res[0][1:]
r... | 5d178726f43913a9678c30f8e61fd4023a9d32d1 | 663,059 |
def is_valid_username(username):
"""Ensure username meets requirements. Returns True if successful."""
return bool(username and username.isalnum() and len(username) <= 30) | 0eca6ce5fe448e3056532404ab9fe415541fc130 | 663,060 |
def replace_linebr(value):
"""
Replaces all values of line break from the given string
with a line space.
Args:
value: string in template
"""
value = value.replace("\n", ' ')
while value.find(' ') >= 0:
value = value.replace(' ', ' ')
value = value.replace(' >', '>')
... | 9f926d7b2940f84193a33b2a739bc75d62ffd93d | 663,062 |
def remove_all(alist,k):
"""Removes all occurrences of k from alist."""
retval = []
for x in alist:
if x != k:
retval.append(x)
return retval | c19240519d5bd66eda8f735e3469ce96ed36b621 | 663,063 |
def intensity(c, i):
"""Return color c changed by intensity i
For 0 <= i <= 127 the color is a shade, with 0 being black, 127 being the
unaltered color.
For 128 <= i <= 255 the color is a tint, with 255 being white, 128 the
unaltered color.
"""
r, g, b = c[0:3]
if 0 <= i <= 127:
... | fbbb5582822b82e4e67fe6dc1e506e626bf39b37 | 663,064 |
def pixelfit(obs, i, times, series, timeslice=slice(None,None,None)) :
"""Fits a series object to the time series of data contained within
a single pixel, optionally extracting the specified time period.
Coefficients of the fit have been stored in the
series. The rsquared of the fit is returned."""
... | 489a93409bc99366cb840cbf44e1dfee4a566df5 | 663,065 |
from typing import Any
import hashlib
def compute_hash(val: Any) -> str:
"""compute a stable hash using a string representation of an object"""
hasher = hashlib.sha256()
hasher.update(str(val).encode("utf-8"))
return hasher.hexdigest() | 0b9f367cb6002405c222179d4babf6d1121433be | 663,066 |
def is_dict(obj):
"""
Check if an object is a dict.
"""
return isinstance(obj, dict) | 7424fa383aedacffaf0118efb5f55af6317d39bb | 663,067 |
def retry(func):
"""
Use of a decorator to retry a function execution (i.e polling a status)
"""
def wrapper(*args, **kwargs):
MAX_TRIES = 100
tried = 0
while True:
response = func(*args, **kwargs)
if response is False and tried < MAX_TRIES:
... | 22b9bd51f06b9c5fefc0e25234774aeba6201833 | 663,068 |
def selectObjsToRun(o):
"""
Choose objects that will be passed for DIF3D analysis.
We choose the reactor rather than the core because the globalflux code makes
some assumptions that it's using the reactor for geometry conversions (should
be changed in the framework!)
"""
return [o.r] | 6eed2d9195f48146fd68ceb946d6917732a054c5 | 663,069 |
def get_iteration(nb, batch_size):
"""
Given total sample size and batch size, return
number of batch.
"""
basic = nb//batch_size
total = basic + (0 if nb%batch_size==0 else 1)
return total | 509805c4b9f6f05142b3f758ac134ec8c82fd087 | 663,070 |
import torch
def hardmax(X):
"""
L2-smoothed max, a.k.a. sparsemax value.
Solves $max_{p \in \Delta^d} <x, p> along axis=2.
:param x: torch.Tensor, shape = (b, n, m)
Vector to project
:return: torch.Tensor, shape = (b, n)
Projected vector
"""
M, _ = torch.max(X, dim=2)
... | 8ada6d6647be4139154af054bd347d09bed30113 | 663,071 |
import re
def SplitComposition(compStr):
""" Takes a simple chemical composition and turns into a list of element,# pairs.
i.e. 'Fe3Al' -> [('Fe',3),('Al',1)]
**Arguments**
- compStr: the composition string to be processed
**Returns**
- the *composVect* corresponding to _compStr... | e3c67cbc7bccafdd3df83ca559b6989a1ea7e979 | 663,072 |
def test_is_true(v):
"""
Helper function tests for a value that evaluates to Boolean True
"""
return bool(v) | 21d84b0d4e93952921660b6afad9958d5fc78036 | 663,074 |
import argparse
def parse_args():
"""Parse arguments of command line"""
parser = argparse.ArgumentParser(
description='Convert CVAT annotation with instance segmentation ''to COCO representation'
)
parser.add_argument(
'--cvat-xml', required=True,
help='input file with CVAT ann... | 228d58efa35dc269b9eb379c5d36e083fcff0393 | 663,076 |
def circular_correlation_complex(vec1, vec2):
"""
Returns a vector from complex vectors by subtracting their respective phase angles
"""
return vec1 / vec2 | cff34073a3722f6ed4eb719db9597078e9d5190c | 663,077 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.