content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def equal(param1, param2, ignore_case=False):
"""
Compare two parameters and return if they are equal.
This parameter doesn't run equal operation if first parameter is None.
With this approach we don't run equal operation in case user don't
specify parameter in their task.
:param param1: user i... | e25f4f63836790cae9c08ceaccc2d161be7b9921 | 675,329 |
import os
def get_default_sysroot_path(build_target_name=None):
"""Get the default sysroot location or '/' if |build_target_name| is None."""
if build_target_name is None:
return '/'
return os.path.join('/build', build_target_name) | 376659fc38d3153ccc6eff5b3ced5d9dda6e8c9e | 675,330 |
def do_use_container(**kwargs):
"""
Decide whether to use a container or not.
:param kwargs: dictionary of key-word arguments.
:return: True if function has decided that a container should be used, False otherwise (boolean).
"""
use_container = False
# return use_container
# to force... | bd270c72d2d5147d86444e7724305d6c9a997d7b | 675,331 |
import torch
def BCEFlat(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""Same as F.binary_cross_entropy but flattens the input and target.
Args:
x : logits
y: The corresponding targets.
Returns:
The computed Loss
"""
x = torch.sigmoid(x)
y = y.view(x.shape).type... | 81ae53a5af7dcb05561d0285f72b1bb668261c39 | 675,332 |
def determine_reads_conversion(read):
"""
Determine HISAT-3N read conversion level
Parameters
----------
read
Returns
-------
return conversion string GA or CT
"""
# For HISAT-3N, use YZ tag
# YZ:A:<A>: The value + or – indicate the read is mapped to REF-3N (+) or REF-RC-3... | 0c3d5ff05dbe2e55d1c66035709f8eec687026f5 | 675,333 |
def _compute_yield_pf(metrics):
"""
Compute the yield (number of bases passing filter) from a populated
metrics object generated by get_illumina_sequencing_metrics()
"""
if not metrics.get('num_clusters_pf'):
return None
total_length = 0
total_length += len(metrics.get('read1_q30_fr... | 05a64384ec0798427c624487a905dec990cfcd75 | 675,334 |
import os
import time
def file_avoid_overwrite(path):
"""if the path is exit, then revise the file to avoid overwritting"""
if os.path.exists(path):
t = time.localtime()
data_code = '{:04d}{:02d}{:02d}[{:02d}{:02d}]'.format(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min)
idx = pat... | 276676dc553e1c0059fe7b00a394f0ea623592f9 | 675,335 |
def _parse_message(exc):
"""Return a message for a notification from the given exception."""
return '%s: %s' % (exc.__class__.__name__, str(exc)) | 89cd5fafb6b79bd575bea2fb0c9de30b5157c130 | 675,336 |
def split_workload(workload):
""" Fork of CrazyMerlyn's solution from CodeWars """
diff = sum(workload)
minimum = abs(diff), 0
for i, work in enumerate(workload, 1):
diff -= 2 * work
current = abs(diff), i
if current < minimum:
minimum = current
return (None, None... | 68f07fb6723189cb9a197b7c7092c74f6ff87ec7 | 675,337 |
def build_error(qparams):
""""
Fills the `error` part in the response.
This error only applies to partial errors which do not prevent the Beacon from answering.
"""
if not qparams.requestedSchemasServiceInfo[1] and not qparams.requestedSchemasDataset[1]:
# Do nothing
return
m... | a4701df06bf7cbb18b1980475a8264b32fff1f34 | 675,338 |
import string
def printable_substring(the_str):
"""Returns the printable subset of the_str
:param str the_str: a putative string
:return str the_pr_str: the portion of the_str from index 0 that is printable
"""
i = 0
the_pr_str = ''
while i < len(the_str):
if the_str[i] in string.... | ba0251252e0878bfbc1f94bdef21376ed45c53d0 | 675,339 |
import re
def CompareNormalizedFiles(normalized_template, normalized_text):
"""
This function matches the normalized text with the normalized
template regex using the match function.
"""
if re.match(normalized_template, normalized_text):
return True
else:
return False | 0fbec188e0716cfd92cbd3cc447453d970435daa | 675,340 |
def make_read_only(tkWdg):
"""Makes a Tk widget (typically an Entry or Text) read-only,
in the sense that the user cannot modify the text (but it can
still be set programmatically). The user can still select and copy
text
and key bindings for <<Copy>> and <<Select-All>> still work properly.
Inp... | 57c8560b0c3979963397aaa635f7567644140012 | 675,341 |
import numpy
def from_standard(data):
""" Extract diffusion gradient direction and b-value from standard DICOM
elements (MR Diffusion Sequence).
"""
diffusion_data = data["MRDiffusionSequence"]
scheme = []
for entry in diffusion_data:
entry = entry[0]
if "Diffusio... | 69c05363f65c990237c11080edab4d5f3496b926 | 675,345 |
def is_array(value):
"""Check if value is an array."""
return isinstance(value, list) | 757c4f07d456a41d42fc98ed3a469695f7420201 | 675,346 |
import random
def expand_model_parameters(model_params, expansion_limit):
"""Expand a model template into random combinations of hyperparameters.
For example, if model_params is:
{name: regression, l2_strength: [0, 1], train_steps: [100, 50] }
Then the returned new_model_params will be the following:
[
... | c083abcaf5c09fbc365c5f3fa77095b24fd2f57f | 675,347 |
import json
def mock_hue_put_response(request, context):
"""Callback for mocking a Philips Hue API response using the requests-mock library,
specifically for a put request.
This mock response assumes that the system has a single light with light_id of '1',
and the expected request is to set the 'on' ... | cc54a09d9595ac6e0868f7143bd663d2da78c3e4 | 675,349 |
def get_matching_datasets(d1,d2,s1,s2):
"""
get_matching_datasets(d1,d2,s1,s2)
"""
joint_subs=set(s1).intersection(s2)
s1_idx=[i for i in range(len(s1)) if s1[i] in joint_subs]
s2_idx=[i for i in range(len(s2)) if s2[i] in joint_subs]
for i in range(len(s1_idx)):
assert s1[s1_id... | 8f71b6df47e3d0973e841df0a740573b8b845d1a | 675,350 |
def _dflt_unit_sizes(num_blocks):
""" Returns a default set of values for the unit sizes. """
ret = []
unit_size = 64
for _ in range(num_blocks):
ret.append(unit_size)
unit_size = min(unit_size*2, 512)
return ret | 2873bb497f826b84047514101745e124b0fff616 | 675,351 |
def _column_original_name(name):
""" Return original name of the metric """
if ':' in name:
return name.split(':')[-1]
else:
return name | 57dc38e79e997cfa2fb863023c36db62fbf32d4b | 675,353 |
import math
def translate_key(key):
""" Translate from MIDI coordinates to x/y coordinates. """
vertical = math.floor(key / 16)
horizontal = key - (vertical * 16)
return horizontal, vertical | 1916fb2abc97f421494c3ced21d9f8ec05936845 | 675,354 |
def is_definitely_composite(n, b):
"""
Let n = d*2^s + 1 for some odd d. If b^d != 1 (mod n) and b^{d*2^r} != n - 1
(mod n) for all r in [0, s), then n is definitely composite. Otherwise, n is
probably prime.
"""
s, d = 0, n - 1
while d % 2 == 0:
s += 1
d //= 2
m = pow(b,... | 0ab0100a10af93750862c0320961cf3f605c7d2b | 675,355 |
def join_arg(arg_name, arg_type, mode='i'):
"""make string with procedure arguments"""
if mode == 'o':
out_s = 'OUT '
else:
out_s = ''
return '%s%s %s' % (out_s, arg_name, arg_type) | 2b6b22ad91824089e647fdea53e1be8bce268078 | 675,356 |
def naniži(vrijednost):
"""Pretvaranje vrijednosti koja nije n-torka u 1-torku."""
return vrijednost if isinstance(vrijednost, tuple) else (vrijednost,) | 1a59e09b39c5f83ee210fd296691c949a6a62584 | 675,358 |
import os
def find_service(port_no):
"""
Retrieves information about the service running on the given port.
This information is read from services.csv
"""
if os.path.isfile("services.csv"):
f = open("services.csv")
line = f.readline()
while line != '':
if line.count(",") < 11:
line += f.readline()
... | b4062903832228aad0bbcbf2ba4dd036baa460ea | 675,359 |
import math
def calculate_fov(zoom, height=1.0):
"""Calculates the required FOV to set the
view frustrum to have a view with the specified height
at the specified distance.
:param float zoom: The distance to calculate the FOV for.
:param float height: The desired view height at the specified
... | 8868bf32e7d0d2240a0d2996b9444b82074eb024 | 675,360 |
def uds_clus_param():
"""
Define co-ordinates for the Papovich(2010) cluster.
Returns:
Centre RA, DEC, redshift, and the size of redshift bin
"""
BCG_RA = 2.30597 *15
BCG_DEC=-5.172194
z=1.62
dz=0.05
return BCG_RA, BCG_DEC, z, dz | d8dac970965fbe8169b9f6fae2c05f3ccee08abb | 675,361 |
from typing import Counter
def avg_dicts(*args):
"""
Average all the values in the given dictionaries.
Dictionaries must only have numerical values.
If a key is not present in one of the dictionary, the value is 0.
Parameters
----------
*args
Dictionaries to average, as positiona... | efe54e9263f5675263aba1bbc775ca38c7d694bb | 675,362 |
import random
def get_random_color():
"""Get a random color for bb color."""
r=random.randint(0,255)
g=random.randint(0,255)
b=random.randint(0,255)
return(r,g,b) | 953de084a795a788625c3c80d878f70177126386 | 675,363 |
def first_ok(results):
"""Get the first Ok or the last Err
Examples
--------
>>> orz.first_ok([orz.Err('wrong value'), orz.Ok(42), orz.Ok(3)])
Ok(42)
>>> @orz.first_ok.wrap
>>> def get_value_rz(key):
... yield l1cache_rz(key)
... yield l2cache_rz(key)
... yield get_... | 00ec3f8de716270142715a521cb27fbb3f5a6264 | 675,364 |
def add1(num):
"""Add one to a number"""
return num + 1 | ae7daac0e4f46d755fd24978b85a4103d93b0e93 | 675,365 |
def chomp(string):
"""
Simple callable method to remove additional newline characters at the end
of a given string.
"""
if string.endswith("\r\n"):
return string[:-2]
if string.endswith("\n"):
return string[:-1]
return string | 4ad36802075451d6800dda41417db42c919b4f21 | 675,366 |
def _patch_wrapper(old, new):
"""Helper function that forwards all the function details to the
decorated function."""
try:
new.__name__ = old.__name__
new.__module__ = old.__module__
new.__doc__ = old.__doc__
new.__dict__ = old.__dict__
except:
pass
return new | a1da5044adbcc7262bc7ec32aae66299318d6ce5 | 675,367 |
def decode(bytes_):
"""
Decode into one or multiple values
"""
result = []
decoded = ""
for value in bytes_:
print(bin(value))
binary = bin(value)
if len(binary[2:]) < 8:
decoded += "0" * (7 - len(binary[2:])) + binary[2:]
else:
decoded... | 697a4af6b6bd82cd987001791a82da2bc954c441 | 675,368 |
import math
def is_prime(n):
""" Checks if F(n) is prime. Returns True if F(n) is prime
It checks for all odd values of N in (3, sqrt(n))
"""
if n < 2:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
else:
for i in range(3, math.floor(n**... | 805b5e68ad940989a7d089938d3df152e71e3e51 | 675,369 |
def videoQuality():
""" Select different video qualities. """
quality = ['240p', '360p', '480p', '720p', '1080p']
return quality[4] | 6c7368627dc751c3a4b552e97d2d0d37fe635061 | 675,370 |
def syntax(command): # pylint: disable=W0621
"""Function to return the help content"""
cmd_and_aliases = " | ".join([str(command), *command.aliases])
params = []
for key, value in command.params.items():
if key not in ("self", "ctx"):
params.append(f"[{key}]" if "NoneType" in str(v... | 6b0cdc17b8e5dd12ccc3ded5124ceb5e858e9b92 | 675,371 |
def subtract(datae):
"""Subtracts two fields
Parameters
----------
datae : list
List of `np.ndarray` with the fields on which the function operates.
Returns
-------
numpy.ndarray
Subtracts the second field to the first field in `datae`. Thought to
process a list of ... | fa493877f1959c86c89e986dbac8d2807afafe05 | 675,372 |
def pairs_brute(k, arr):
"""
Runtime: O(n^2)
"""
if len(arr) < 2:
return []
pairs = []
for i, n1 in enumerate(arr):
for n2 in arr[i+1:]:
if n1 + n2 == k:
pairs.append([n1,n2])
return pairs | 4509bf55b2eecce92bb807cb3e240cd02bc43b05 | 675,374 |
def _to_op(tensor_or_op):
""" Convert to op """
if hasattr(tensor_or_op, "op"):
return tensor_or_op.op
return tensor_or_op | 1322dbab5bc5bcbd2a9db0b8278c8f05e937fe7a | 675,375 |
def _get_config_attrs(request):
"""Hack to get config attrs which are class variables
Cannot think of a situation where a caller should need to access this
directly so it is marked private"""
return {k: v for k, v in vars(request).items() if not k.startswith('__')} | 0ae0a5ddbbe17e90647ee2f728bc24e0377c825f | 675,376 |
def estimate_bg_noise(chrom, tx_st, tx_end, samfile, e_ranges):
"""
estimate background noise level for a particular transcript
"""
intron_sig = 0.0 # reads_num * reads_len
alignedReads = samfile.fetch(chrom, tx_st, tx_end)
for aligned_read in alignedReads:
if aligned_read.is_qcfail:
... | 52aeed26026da0106ca18d5739f6aa561f7afd4e | 675,377 |
import collections
import importlib
import platform
import sys
def _info():
"""Print information about the current machine, Python, and scientific
computing packages.
"""
pkgs = ['numpy', 'scipy', 'matplotlib', 'seaborn', 'sklearn']
def pkg_ver(name):
try:
module = importlib.... | fbb14f14127cf533e6e079352a2d079dec81b259 | 675,378 |
import itertools
def flatten(list_of_lists):
"""
Takes an iterable of iterables, returns a single iterable containing all items
"""
return itertools.chain(*list_of_lists) | 8c7a4b3d06e6e959eb20b0b57868a39d317daaf4 | 675,379 |
def parse_timezone(text):
"""Parse a timezone text fragment (e.g. '+0100').
Args:
text: Text to parse.
Returns: Tuple with timezone as seconds difference to UTC
and a boolean indicating whether this was a UTC timezone
prefixed with a negative sign (-0000).
"""
# cgit parses th... | 30c8232d4bfe072077a56ca06c94e72779bdff07 | 675,380 |
def normalize(
text: str, lang: str, whitespace: bool = True, lowercase: bool = False
) -> str:
"""
Perforn some normalization steps on a text string
"""
if whitespace:
text = " ".join(text.split())
if lowercase:
text = text.lower()
return text | 7296a9f517b0da6d488386609b85cf73d4c7cbec | 675,381 |
import random
def auditData(auditsamples = 1, data = {}, randseed = 12345213 ):
"""
Samples a DATA graph based on a probability of inclusion
which is the ratio auditsamples/len(data). So, one recieves
approximately the number of samples selected. From Data Crunching
pg 170. This function uses a fixed seed, so i... | 0d2104951e975fd747d67dc86f633becd32b3f92 | 675,382 |
import time
def timer(function):
"""Decorator for timer functions
Usage:
@timer
def function(a):
pass
"""
def wrapper(*args, **kwargs):
start = time.time()
result = function(*args, **kwargs)
end = time.time()
print(f"{function.__name__} took: {end -... | 09f29d87f25cb04a9cf9e82233f49be476830581 | 675,383 |
import os
def all_exists(*paths: str) -> bool:
"""Check whether all provided paths exist.
Args:
*paths: paths to files
Returns:
True if all files exist, False otherwise
"""
return all(os.path.exists(path) for path in paths) | 86717e7c02fdfbcae5605fce33808caf9c324039 | 675,384 |
def add_default_module_params(module_parameters):
"""
Adds default fields to the module_parameters dictionary.
Parameters
----------
module_parameters : dict
Examples
--------
>> module = add_default_module_params(module)
Returns
-------
module_parameters : dict
... | 4731c6fbe06232f8bedf1b586c5cf01a8b4de336 | 675,385 |
def add_options(options):
"""Wrap common parameters that all commands should implement."""
def _add_options(func):
for option in reversed(options):
func = option(func)
return func
return _add_options | f79ab97936ba06bf47a3391b20ac6621f256343b | 675,386 |
def yesno(value):
"""Converts logic value to 'yes' or 'no' string."""
return "yes" if value else "no" | 6b333a4f1bedd2a0f6c07af47fdba11cea8a060f | 675,387 |
def gen(block):
"""Variables that are written in the block.
"""
return {i['dest'] for i in block if 'dest' in i} | 160aa9d065ad7c3f85a45a97d964a3729f5aaee0 | 675,388 |
def mod_crop(tensor, SR_factor):
"""
:param tensor: B, C, H, W
:param SR_factor:
:return:
"""
B, C, H, W = tensor.shape
return tensor[:, :, :- H % SR_factor, :- W % SR_factor] | 7a32cc7eaa6d43402af36b38e7407849472178ea | 675,389 |
def clean_thirty_five_or_more(text):
""" Return True if the location can support more than 35 4th graders. """
text = text.lower().strip()
if text == 'yes' or text == 'y':
return True
else:
return False | 2530bc1f913388213ab9e179a616c4db3e606f24 | 675,390 |
def str2bool(val):
""" converts a string to a boolean value
if a non string value is passed
then following types will just be converted to Bool:
int, float, None
other types will raise an exception
inspired by
https://stackoverflow.com/questions/15008758/
... | 85d4ee26ccea660014fb9bd2891dcf7bc234e459 | 675,391 |
def _find_text_in_file(filename, start_prompt, end_prompt):
"""
Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty
lines.
"""
with open(filename, "r", encoding="utf-8", newline="\n") as f:
lines = f.readlines()
# Find the star... | a77b68257639e877e8a899ae63e97dce3a7f066f | 675,392 |
import math
def refraction_angle( theta1, index2, index1=1.0):
"""
Determine the exit angle (theta2) of a beam arriving at angle
theta1 at a boundary between two media of refractive indices
index1 and index2.
The angle of refraction is determined by Snell's law,
sin theta1 /... | 348c7add495448424018b964d9d964c9c416bdfe | 675,393 |
def writeRead(lineList, of, bc, bcLen, args, doTrim=True):
"""
Trim the read as specified and write to the appropriate file.
Return the modified read name (for read #2, if needed)
"""
rname = lineList[0]
if doTrim:
UMI = ""
if args.umiLength > 0:
UMI = lineList[1][:ar... | bc37fde1ea9512b22ac75b3db956eaec247940e3 | 675,394 |
import os
from six.moves import urllib
def download(path):
"""Use urllib to download a file.
Parameters
----------
path : str
Url to download
Returns
-------
path : str
Location of downloaded file.
"""
fname = path.split('/')[-1]
if os.path.exists(fname):
... | 3a18080b187b7a3a90189223ab63a33797423aad | 675,395 |
def conJac(function):
""" {a_i;i in (0, n)} """
def xx(x):
return function[:-1]
return xx | cddb4d6b7c003e24fa092d4c9c7480fbf01bd14e | 675,396 |
def region_key(r):
"""
Create writeable name for a region
:param r: region
:return: str
"""
return "{0}_{1}-{2}".format(r.chr, r.start, r.end) | 1f66b7e8b141b97728a6c5f12604bcd17d321df1 | 675,397 |
def multiply(a, b):
"""Multiplies two numbers.
Function to multiply two numbers.
Parameters
----------
a : numbers.Real
First operand.
b : numbers.Real
Second operand.
Returns
-------
numbers.Real
Product of a and b.
Examples
--------
>>> ... | c7573bc15d91dab96e7e531112eeb87fa1cd77df | 675,399 |
import math
def crop(image, cams, max_h,max_w):
""" resize images and cameras to fit the network (can be divided by base image size) """
# crop images and cameras
h, w = image.shape[0:2]
new_h = h
new_w = w
if new_h > max_h:
new_h = max_h
else:
new_h = int(math.ceil(h / 32) * 32)
if new_w > max_w:
new... | 60bf2c3529bd862ea3607a5234e64cdca60f2d9e | 675,400 |
def get_base_color_node(node_tree):
""" returns the last node of the diffuse block """
for node in node_tree.nodes:
if node.label == 'BASE COLOR':
return node
return None | 0e6737f23448f32c4a98d98db083612b1c31a4f7 | 675,401 |
def delDim(mat,num):
"""
Removes desired number of rows and columns from bottom right corner
"""
try:
if mat.matrix==[]:
return "Empty matrix"
assert isinstance(num,int) and num>0 and mat.dim[0]-num>=0 and mat.dim[1]-num>=0
goal1=mat.dim[0]-num
goal2=m... | b3151fe7e2a2e1d22b7a012416bbdad99dc4f180 | 675,402 |
from pathlib import Path
def _read_lark_file() -> str:
"""Reads the contents of the XIR Lark grammar file."""
path = Path(__file__).parent / "xir.lark"
with path.open("r") as file:
return file.read() | 16806475468f02d379bcb0750d1ca62e2c7f4a5f | 675,403 |
import json
def read_cluster_results(directory, cluster):
"""Try to read results for given cluster, where results are stored in specified directory."""
filename = f"{directory}/{cluster}.json"
with open(filename, "r") as fin:
raw_data = fin.read()
results = json.loads(raw_data)
retur... | c7c11fd84aa557594128fc75a61c5ee332782281 | 675,404 |
def outliers_detect_iqr(s, factor=1.5):
"""
Detects outliers in a pandas series using inter-quantile ranges
Parameters
----------
s : pandas.core.series.Series
Pandas Series for which the outliers need to be found
factor : int
iqr factor used for outliers
Returns
-----... | 681e0d9310e17cf73c7b61f56128a7bde30ad960 | 675,406 |
import bisect
def compute_previous_intervals(I):
"""
For every interval j, compute the rightmost mutually compatible interval
i, where i < j I is a sorted list of Interval objects (sorted by finish
time)
"""
# extract start and finish times
start = [i.left for i in I]
finish = [i.right... | cc8c935dc7e1bf5f308e125515d61d250e2d5bcf | 675,407 |
def read_bytes(filename, offset, number):
"""
Reads specific bytes of a binary file.
:param filename: path to file
:type filename: string
:param offset: start reading at offset
:type offset: integer
:param number: number of bytes
:type number: integer
... | c04c7659211f7bfee3d88b27cd014cea303b13c4 | 675,408 |
def combine_roi_and_cav_mask(roi_mask, cav_mask):
"""
Combine ROI mask and CAV mask
Parameters
----------
roi_mask : torch.Tensor
Mask for ROI region after considering the spatial transformation/correction.
cav_mask : torch.Tensor
Mask for CAV to remove padded 0.
Returns
... | 103021df9035c2ad87cb9735f81d78af700df645 | 675,409 |
import os
import json
def get_json_from_file(file_path):
"""
Parse JSON from file.
"""
if not os.path.isfile(file_path):
raise FileNotFoundError(f"The specified file path {file_path} does not exist")
with open(file_path) as f:
data = json.load(f)
return data | e7de95a924b1e992908c21b8e021cd2c23275ea2 | 675,410 |
import logging
def get_branches_map(branchitems):
"""
Get list of branches from configuration to be auto merged, only these branches
are going to be taken into account when auto merging.
Args:
branchitems: The list of branches to be analyzed.
"""
branchesmap = {}
logging.info('b... | 4947065f96b5ec477da3fff3b93fefc6a41a3a03 | 675,411 |
import argparse
def argument_parser():
""" Define the arguments and return the parser object"""
parser = argparse.ArgumentParser(
description="Create the Octtrees of each tile of the input data folder")
parser.add_argument('-i','--input',default='',help='Input folder with the tiles',type=str, required... | e793c23a730ef424dcb34570110a7f2b38702785 | 675,412 |
def no_absents(df):
"""Elimina alunos faltosos. No caso, considerou-se que faltaram os alunos
que estavam com todas as notas zeradas (coluna 2 em diante). Funciona pois
nenhum aluno presente zerou a prova. Caso isso algum dia aconteça, vai
falhar. Talvez adotar um sistema de coluna de flag para indicar ... | 09a0633eff5851a9c1826f36966f9eab9414fccf | 675,414 |
import re
def getDatefromName(fname):
"""
Returns the date of the form YYYY-MM-DD from fname, or an empty
string if there is no string that matches. If there are multiple
matches, this returns the first of them.
"""
dates = re.findall(r"\d{4}-\d{2}-\d{2}", fname)
if len(dates) == 0:
... | 24bd989c840483cb2f105f6c6f38794984534b9c | 675,415 |
def pname(name, levels=None):
"""
Return a prettified taxon name.
Parameters
----------
name : str
Taxon name.
Returns
-------
str
Prettified taxon name.
Examples
--------
.. code:: python3
import dokdo
dokdo.pname('d__Bacteria;p_... | 4ae357f82531f6a4b1aeee3007e65a304fa134cb | 675,416 |
def user_directory(ssh_fn, name=None):
"""Get the directory for the user.
The ssh_fn is a function that takes a command and runs it on the remote
system.
If :param:`name` is None, then the user for the ssh_fn is detected,
otherwise the home dir or specified user is detected.
:param ssh_fn: a ... | 1fbe280a777d193a5cb0448598d0ec0200531860 | 675,417 |
def create_parameter(model, parameter_id, value, constant=True, units="dimensionless"):
"""
Creates new parameter for libsbml.Model. It is not necessary to assign the
function to a value. The parameter is automatically added to the input model
outside of the function.
Parameters
----------
... | fa7206e53941aa8bfe81f5f1ee1cd764c3c12668 | 675,418 |
def calc_damp(frequency_wn, freq_cutoff):
"""A damping function to interpolate between RRHO and free rotor vibrational entropy values"""
alpha = 4
damp = [1 / (1 + (freq_cutoff / entry) ** alpha) for entry in frequency_wn]
return damp | 03029d6cb14f9e561202f707d5aa0677ee2723e7 | 675,419 |
def get_filter_set(taxonomy_filters_dict):
"""Create a set of all taxonomy filters from a dictionary.
:param taxonomy_filers: dict of taxonomy filters
Return a set.
"""
taxonomy_filters = set()
for key in taxonomy_filters_dict:
try:
for tax_filter in taxonomy_filters_dict[... | beda8c99bc2b2ffa0e41ea1e7a12d2b126bc84d4 | 675,420 |
import time
def inttime_to_strtime(t):
""" 时间戳转换为字符串时间
"""
struttime = time.localtime(t)
strtime = time.strftime("%Y-%m-%d %H:%M:%S", struttime)
return strtime | 49b7d2c802b88713291619b916fa953741783909 | 675,422 |
import requests
import json
import sys
def get_pypi_data(pkg_name):
"""Retrieve metadata from PyPI json endpoint"""
try:
pkg_url = "https://pypi.org/pypi/" + pkg_name + "/json"
response = requests.get(pkg_url)
metadata_dict = response.json()
except json.decoder.JSONDecodeError:
... | ddb19c7b2dcd8d5794204ec6116dcde241ade7ca | 675,423 |
def parse_impact_report(report, local_pkgs, hubble_format, impacted_pkgs=[]):
"""Parse into Hubble friendly format"""
for key, value in report.items():
pkg_desc = 'Vulnerable Package(s): '
for pkg in value['installed']:
pkg_desc += '{0}-{1}, '.format(pkg['name'], pkg['version'])
... | 73ed839294f9c50819ef6a77359a6442b3449152 | 675,424 |
def _polynomial_sim(x, y, p=2):
"""
polynomial/linear kernel
compute the similarity between the dicts x and y with terms + their counts
p: >1 for polynomial kernel (default = 2)
"""
# get the words that occur in both x and y (for all others the product is 0 anyways)
s = set(x.keys()) & set(y... | 226c514f111ed0bd140505005327cb21c5e163e0 | 675,425 |
def floatimg2uint8(image):
"""
Convert array with floats to 'uint8' and rescale from [0,1] to [0, 256].
Converts only if image.dtype != uint8.
>>> import numpy as np
>>> image = np.eye(10, 20, dtype=float)
>>> arr = floatimg2uint8(image)
>>> np.max(arr)
255
:param numpy.array imag... | 9ccf364931ee37679ab7e5871555bb80b7ad252a | 675,426 |
import os
def GetCWD():
"""Returns the current working directory."""
return os.getcwd() | f6ede7553f278a47de51155609625f3df6f26af9 | 675,427 |
import filecmp
import sys
def diff_q(first_file, second_file):
"""Simulate call to POSIX diff with -q argument"""
if not filecmp.cmp(first_file, second_file, shallow=False):
print("Files %s and %s differ" % (first_file, second_file),
file=sys.stderr)
return 1
return 0 | 340bf427983732ca8a8f75eaa40477e157124f59 | 675,428 |
import os
def find_expected_files(labels, cluster_name, annotation, scope, method):
""" Check that files were created for all expected annotation labels
"""
found = 0
for label in labels:
sanitized_label = label.replace(" ", "_")
expected_file = (
f"{cluster_name}--{annotat... | 69345668dbc9652dea70afc9766b4296f0240f32 | 675,429 |
import numpy
def indices_to_coords(indices, top, left, csx, csy):
"""
Convert a tuple of ([i...], [j...]) indices to coordinates
:param indices:
:param top:
:param left:
:param csx:
:param csy:
:return: Coordinates: ([y...], [x...])
"""
i, j = numpy.asarray(indices[0]), numpy.a... | 65198c5c74127d5077cf0ac883ea31a3555f98f1 | 675,430 |
from pathlib import Path
def safe_ipa_path(dst_dir, name_prefix, name_suffix=None):
"""
获取ipa文件路径,保证此路径不指向任何文件;
:param dst_dir: ipa文件存放的目录
:param name_prefix: 文件名前缀(不包含扩展名)
:param name_suffix: (可选)文件名后缀
:return: 路径对象
"""
if name_suffix:
pure_name = "{}-{}".format(name_prefix, n... | 62454f0d2b5ed7e98c768fb934ec867083443825 | 675,431 |
def datetime_to_string(datetime):
"""convert a datetime object to formatted string
Arguments:
datetime {datetime}
Returns:
[string] -- formatted datetime string
"""
return "/".join([str(datetime.day), str(datetime.month), str(datetime.year)]) | 984d49e0f263855b03e7191bbdb549258bd2ca64 | 675,433 |
def dict_element_of_list(my_dict_list, dict):
""" description:
Check if <dict> is part of dict list <my_dict_list>
usage:
ui_utils.dict_element_of_list(my_dict_list, dict)
tags:
ui, android, helper, dict, list
"""
for el in my_dict_list:
eq = Tru... | 04e038678b30b7070c5997a4aa4d09442ed5fa7f | 675,434 |
import os
def find_cost(path='.', cost_function_filename='cost_-5_0.8.h5'):
"""
Find all cost functions in folder structure.
We have multiple snapshots of a molecule, with corresponding cost functions.
This function explores the folderstructure, and returns all paths leading to cost functions.
Argume... | 964682af8b8f486a2188cc2f37d053a8e816f51c | 675,435 |
def helper1(X):
"""
this will remove whitespaces in the column names
"""
# Prevent SettingWithCopyWarning; read-in as csv
#X = pd.read_csv(X)
X = X.copy()
# removes all whitespace from column names
X.columns = X.columns.str.strip()
# add a line to remove whitespace from the row objects
... | 222725cc27be7fd6192b3cb076b5efb7cc842bc7 | 675,436 |
import glob
def CountFiles():
"""Counts all the existing SBOL files in the directory"""
list = glob.glob('**/*.xml', recursive=True)
return len(list) | ef031b0ea056af8848537aff556c103ff310e910 | 675,437 |
import re
def extract_options(text, key):
"""Parse a config option(s) from the given text.
Options are embedded in declarations like "KEY: value" that may
occur anywhere in the file. We take all the text after "KEY: " until
the end of the line. Return the value strings as a list.
"""
regex = ... | 43089bc40961b50751e008264d6960007747beee | 675,438 |
from typing import Union
def map_value(
x: Union[int, float], in_min: Union[int, float], in_max: Union[int, float],
out_min: Union[int, float], out_max: Union[int, float]
) -> float:
"""Maps a value from an input range to a target range.
Equivalent to Arduino's `map` function.
Args:
x: t... | 06941afe1d269ee622aa1c75564622897cdcde2e | 675,439 |
def _get_workflow_input_parameters(workflow):
"""Return workflow input parameters merged with live ones, if given."""
if workflow.input_parameters:
return dict(workflow.get_input_parameters(),
**workflow.input_parameters)
else:
return workflow.get_input_parameters() | 70de5e28c8b7b29258b134b7bd12df24d7cf4d46 | 675,440 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.