content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _filter_out_disabled(d):
"""
Helper to remove Nones (actually any false-like type) from the scrubbers.
This is needed so we can disable global scrubbers in a per-model basis.
"""
return {k: v for k, v in d.items() if v} | 64a4577d6e5998e647ef82f126c50360388aba9a | 704,219 |
def points(start, end):
"""
Bresenham's Line Drawing Algorithm in 2D
"""
l = []
x0, y0 = start
x1, y1 = end
dx = abs(x1 - x0)
dy = abs(y1 - y0)
if x0 < x1:
sx = 1
else:
sx = -1
if y0 < y1:
sy = 1
else:
sy = -1
err = dx - dy
whil... | ffa8be5eb09e2b454242e4095883bfee239e5319 | 704,222 |
def ab_from_mv(m, v):
"""
estimate beta parameters (a,b) from given mean and variance;
return (a,b).
Note, for uniform distribution on [0,1], (m,v)=(0.5,1/12)
"""
phi = m*(1-m)/v - 1 # z = 2 for uniform distribution
return (phi*m, phi*(1-m)) | 0326c165e44c1ab9df091e0344f12b9fab8c0e19 | 704,223 |
def fds_remove_crc_gaps(rom):
"""Remove each block's CRC padding so it can be played by FDS
https://wiki.nesdev.org/w/index.php/FDS_disk_format
"""
offset = 0x0
def get_block(size, crc_gap=2):
nonlocal offset
block = rom[offset : offset + size]
offset += size + crc_gap
... | 935ecb4ac01c1256ec074f6888704fdd1db63ea4 | 704,224 |
def truncatewords(base, length, ellipsis="..."):
"""Truncate a string by words"""
# do we need to preserve the whitespaces?
baselist = base.split()
lenbase = len(baselist)
if length >= lenbase:
return base
# instead of collapsing them into just a single space?
return " ".join(baseli... | f6472c7511e7e9abf03d4da3ed10c94ef070f78a | 704,225 |
import random
def random_permutation(iterable, r=None):
"""Random selection from itertools.permutations(iterable, r)"""
pool = tuple(iterable)
if r is None:
r = len(pool)
return list(random.sample(pool, r)) | 09e9f22def2c1125bf0ffc50db73659eaac65105 | 704,226 |
def get_hms(t_sec):
"""Converts time in seconds to hours, minutes, and seconds.
:param t_sec: time in seconds
:return: time in hours, minutes, and seconds
:rtype: list
"""
h = t_sec//3600
m = (t_sec - h*3600)//60
s = t_sec%60
return h,m,s | f873ea04905ebcc5b41a394a4dd880a566623c83 | 704,227 |
def current_velocity(x_new, x_prev, h):
""" returns current velocity of a particle from next
position at timestep. """
"""
parameters
----------
x_new : array
new x-position of particle
x_prev : array
previous x-position of particle
h : float
simulation timestep
... | 33d47f901be44fed20613957459aca1eecd5ea2c | 704,229 |
import csv
def csvReadCallback(inputFile, **kw):
"""Read callback for CSV data"""
inputFile.readline() # skip header
reader = csv.reader(inputFile, lineterminator='\n', **kw)
return [row for row in reader] | e36c92e5792e905da22438a58c8ce810c2a22e2a | 704,230 |
def load_word():
""" return the sql and values of the insert queuery."""
sql = """
INSERT INTO Spanglish_Test.Word
(
`word`, `language_id`, `category_id`
)
VALUES (%s, %s, %s)
"""
values = [
(
'Ir', 2, 1
),
... | f0d836f5ca912865f9d75a5e6c10c13cf554674b | 704,231 |
import torch
def reconstruct_from_patches_2d(patches, img_shape, step=[1.0,1.0], batch_first=False):
"""Given patches generated from extract_patches_2d function, creates the original unpatched image. We keep track of the
overlapped regions and average them in the end.
Parameters:
patches ... | 35b03ee61dd5a2749601e839d7ade75d1b686383 | 704,232 |
def _LJ_rminepsilon_to_ab(coeffs):
"""
Convert rmin/epsilon representation to AB representation of the LJ
potential
"""
A = coeffs['epsilon'] * coeffs['Rmin']**12.0
B = 2 * coeffs['epsilon'] * coeffs['Rmin']**6.0
return {"A": A, "B": B} | 0963c0e8b949d35842660a499ce80a388485773f | 704,233 |
def calculate_SI(aggregated_df):
""" calculates suspicion of infection as per Sepsis-3 on aggregated hourly dataframe and saves it under the column `suspicion_of_infection`.
Note:
aggregated_df must contain `antibiotics` and `microbio-sample` columns.
"""
df = aggregated_df[['hadm_id', 'hour', ... | 88f0fb6285c3fc2826168f01416e1e825b2ed4cc | 704,235 |
def _get_reduce_batch_axis(axis, x_dim, x_ndim):
"""get batch_axis for reduce* operation."""
if not isinstance(axis, tuple):
axis = (axis,)
batch_axis = ()
if axis:
for index in axis:
if index < x_dim:
batch_axis = batch_axis + (index,)
else:
... | b2a41f5e03c0388c70d2690793329d922f2d3248 | 704,236 |
def evalrawexp(context, mapping, arg):
"""Evaluate given argument as a bare template object which may require
further processing (such as folding generator of strings)"""
func, data = arg
return func(context, mapping, data) | dc443da540bef0fe1198b12c0205921f0de66b2e | 704,237 |
import os
def get_file_list(path):
"""
获取文件夹下的所有文件,返回list
:param path:
:return:
"""
file_paths = []
get_dir = os.listdir(path)
for dir in get_dir:
tmp_path = os.path.join(path,dir)
if os.path.isdir(tmp_path):
file_paths.append({str(dir):get_file_list(tmp_pat... | 47f183479fb9304d33677fc811509f1801fa0130 | 704,238 |
def find_stab(state, xs, zs):
"""
Find a stabilizer in the stabilizer group.
Args:
state:
logical_circuit:
delogical_circuit:
Returns:
"""
stabs = state.stabs
destabs = state.destabs
# Find the destabilizer generators that anticommute with the stabilizer indi... | 07987377192cb4a4fa8cc35bd13d7566a838778c | 704,239 |
def CycleTarget_to_c(self):
"""Syntax for a target of a cycle."""
return f"cycle_{self.targetID}: continue;" | 12cc7a57e5a24a62aba43ac99879d5a5d364ee29 | 704,240 |
def disable_layer_logging():
"""
Disable the shape logging for all layers from this moment on. Can be
useful when creating multiple towers.
"""
class ContainEverything:
def __contains__(self, x):
return True
# can use nonlocal in python3, but how
globals()['_LAYER_LOGGED'... | e05785f1ade46903c2e66efc35d4fc5f0e9d4fbd | 704,241 |
def _remap_keypoints(keypoints, padded_w, padded_h, expand, data_shape, ratio):
"""
Remap bboxes in (x0, y0, x1, y1) format into the input image space
Parameters
----------
bboxes
padded_w
padded_h
expand
Returns
-------
"""
keypoints[:, 0::2] *= padded_w / (data_shape ... | 1b8d2520f0df1847967e8db9c565598d6b5ee2b6 | 704,242 |
def get_pipeline_lines(input_pipeline):
"""Returns a list with the lines in the .cppipe file"""
with open(input_pipeline) as f:
lines = f.readlines()
return lines | 403e7531b1cadfe25f519d2b176b97ac344cde6b | 704,243 |
def maxmin(*args):
"""
Returns timed ((t,max),(t,min)) values from a (t,v) dataset
When used to filter an array the winndow will have to be doubled to
allocate both values (or just keep the one with max absdiff from previous).
"""
data = args[0]
t = sorted((v,t) for t,v in data)
mn,mx... | 8f76ee029d04a4a35688054512d0a0212adbfede | 704,244 |
def from_none(exc):
"""raise from_none(ValueError('a')) == raise ValueError('a') from None"""
exc.__cause__ = None
exc.__suppress_context__ = True
return exc | 86e45ba2df0020c85f13b85d8a98ee693422e922 | 704,245 |
def get_interface_type(interface):
"""Gets the type of interface
"""
if interface.upper().startswith("ET"):
return "ethernet"
elif interface.upper().startswith("VL"):
return "svi"
elif interface.upper().startswith("LO"):
return "loopback"
elif interface.upper().startswith... | f770a3ef1c43574d22630a5c4fff2f25d4975279 | 704,246 |
def rgb2gray(image):
"""Convert 3-channel RGB image into grayscale"""
if image.ndim == 3:
return (0.299 * image[:, :, 0] + 0.587 * image[:, :, 1] +
0.114 * image[:, :, 2])
elif image.ndim == 4:
return (0.299 * image[:, :, :, 0] + 0.587 * image[:, :, :, 1] +
0.... | f87ed301dfd9c13ebfbabf99ad4b56c959a91e46 | 704,247 |
def create_variable(workflow_stat):
"""
Generates the javascript variables used to generate the chart.
@param workflow_stat the WorkflowInfo object reference
"""
number_of_jobs = workflow_stat.total_job_instances
# Adding variables
var_str = "<script type='text/javascript'>\nvar initMaxX = " + str(workflow_sta... | d0b55b00952f28242775a297fedab6cf1a69169e | 704,248 |
def aten_le(mapper, graph, node):
""" 构造对比大小的PaddleLayer。
TorchScript示例:
%80 : bool = aten::le(%78, %79)
参数含义:
%80 (bool): 输出,第一个元素是否小于等于第二个元素。
%78 (-): 需对比的输入1。
%79 (-): 需对比的输入2。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_ou... | 45797abf1ec5a97619578dd734c1d9d7fb448aec | 704,249 |
from pathlib import Path
def filter_files(names: list[Path]) -> list[Path]:
"""只要文件,不要文件夹"""
return [x for x in names if x.is_file()] | 25c1258891e2df7c35f700a26cadf01013329337 | 704,250 |
def move_ship_waypoint(instructions: list) -> list:
"""Move the ship using the waypoint movement rules
:param instructions: List of movement instructions
:return: Final position of the ship
"""
waypoint = [10, 1]
ship = [0, 0]
for instruction in instructions:
cmd, val = instruction
... | 7202392e4826d522287455d94f7b06c0e2f931ee | 704,251 |
import itertools
def get_hyperparams_combinations(hyperparams):
"""Get list of hyperparmeter (dict) combinations."""
# transforms tuning hyperparams to a list of dict params for each option
return [
{k:v for k,v in zip(hyperparams.keys(), hypms)}
for hypms
in itertools.product(*[... | e5f52a8eddb8a2a476e0daa47f63161d440263f2 | 704,252 |
from datetime import datetime
import json
import logging
def convert_from_poolfile_to_sequence_set_and_back(inp_fp_path,
op_path, conversion_type, description="", run_id=None):
"""
In this function we take either pool file or Sequence Set
and convert from one to the other. Sequence Set is out... | ad46eb491840aa75764b013495a113ae746144ba | 704,253 |
from typing import List
def read_basis_format(basis_format: str) -> List[int]:
"""Read the basis set using the specified format."""
s = basis_format.replace('[', '').split(']')[0]
fss = list(map(int, s.split(',')))
fss = fss[4:] # cp2k coefficient formats start in column 5
return fss | 9701309ab43eb7a0227aa141653688dbdce40811 | 704,254 |
def p_to_stars(p, thres=(0.1, 0.05, 0.01)):
"""Return stars for significance values."""
stars = []
for t in thres:
if p < t:
stars.append("*")
return "".join(stars) | d88c2fd6c1b4e2d75a9cb664dfc10fab308bc6ee | 704,255 |
def correct_dcm(dcm):
""" Correct DCM image which were actually signed data, but were treated as unsigned """
x = dcm.pixel_array + 1000
px_mode = 4096
x[x>=px_mode] = x[x>=px_mode] - px_mode
dcm.PixelData = x.tobytes()
dcm.RescaleIntercept = -1000
return dcm.pixel_array, dcm.RescaleIntercep... | 0186ab3fc4b606902da3a50a5835eb227a1b7733 | 704,256 |
def factorial_r(number):
"""
Calculates the factorial of a number, using a recursive process.
:param number: The number.
:return: n!
"""
# Check to make sure the argument is valid.
if number < 0:
raise ValueError
# This is the recursive part of the function.
if number == 0... | e5c28edac93b965f438bd61c5bb1c0a935c96700 | 704,257 |
def make_perturbed_cmtsolution(py, src_frechet_directory, cmtsolution_directory, output_directory):
"""
make the pertured cmtsolution based on src_frechet.
"""
script = f"ibrun -n 1 {py} -m seisflow.scripts.source_inversion.make_perturbed_cmtsolution --src_frechet_directory {src_frechet_directory} --cmt... | 07bb69751ddaee9d7aa6389c6cab9bc6021758ed | 704,258 |
def weight_correct_incorrect(rslt):
"""Return a pair of floating-point numbers denoting the weight of
(correct, incorrect) instances in EvaluationResult rslt.
>>> listInstCorrect = [Instance([],True,0.25)]
>>> listInstIncorrect = [Instance([],False,0.50)]
>>> rslt = EvaluationResult(listInstCorrect, listInstIncor... | 5a7ef1d338821f10b58ba06224059e532180c50d | 704,259 |
import pathlib
import csv
def get_data_info(path):
"""
Get metadata of the iamges.
"""
samples = []
# the data is in subfolders
parent = pathlib.Path(path)
for csv_file in parent.glob('**/*.csv'):
with open(str(csv_file), 'r') as f:
reader = csv.reader(f)
f... | 53f3dd1b6ff18d43a656f4a3f6da26ab1e60a6c2 | 704,260 |
import random
def shuffle(x, y):
""" Shuffle the datasets. """
for n in range(len(x) - 1):
rnd = random.randint(0, (len(x) - 1))
x1 = x[rnd]
x2 = x[rnd - 1]
y1 = y[rnd]
y2 = y[rnd - 1]
x[rnd - 1] = x1
x[rnd] = x2
y[rnd - 1] = y1
y[rnd... | c9f198d3796c5d64eba818753701957ea1a0e924 | 704,261 |
def get_data_names(data, data_names):
"""
Get default names for data fields if none are given based on the data.
Examples
--------
>>> import numpy as np
>>> east, north, up = [np.arange(10)]*3
>>> get_data_names((east,), data_names=None)
('scalars',)
>>> get_data_names((east, nort... | e2097d6dbf2c8cc52fd4a60124727cad5fe9fbc4 | 704,262 |
import pandas
def get_labels_from_file(filename):
"""Get labels on the last column from file.
Args:
filename: file name
Returns:
List[str]: label list
"""
data_frame = pandas.read_csv(filename)
labels = data_frame['summary'].tolist()
return labels | 605e9a464eb9fc007d2421fadcab362b7c22ebf5 | 704,263 |
from typing import Any
def create_result_scalar(name: str, item_type: str, value: Any) -> dict:
"""
Create a scalar result for posting to EMPAIA App API.
:param name: Name of the result
:param item_type: Type of result
:param value: Value of the result
"""
result = {"name": name, "type": ... | 3fb16c540cc8c76cfc42e4a906e4be280346b802 | 704,264 |
import sympy
def replace_heaviside(formula):
"""Set Heaviside(0) = 0
Differentiating sympy Min and Max is giving Heaviside:
Heaviside(x) = 0 if x < 0 and 1 if x > 0, but
Heaviside(0) needs to be defined by user.
We set Heaviside(0) to 0 because in general there is no sensitivity. This
done ... | d1aff5e4a2dd68ba53ced487b665e485dab4b54d | 704,265 |
import os
def is_dicom(filename):
"""Returns True if the file in question is a DICOM file, else False. """
# Per the DICOM specs, a DICOM file starts with 128 reserved bytes
# followed by "DICM".
# ref: DICOM spec, Part 10: Media Storage and File Format for Media
# Interchange, 7.1 DICOM FILE MET... | 014c15481224413d6757c950a0888fb60e0f94d5 | 704,266 |
def exact_change_recursive(amount,coins):
""" Return the number of different ways a change of 'amount' can be
given using denominations given in the list of 'coins'
>>> exact_change_recursive(10,[50,20,10,5,2,1])
11
>>> exact_change_recursive(100,[100,50,20,10,5,2,1])
4563
... | f18cd10802ba8e384315d43814fcb1dcd6472d78 | 704,267 |
def knapsack(val,wt,W,n):
"""
Consider W=5,n=4
wt = [5, 3, 4, 2]
val = [60, 50, 70, 30]
So, for any value we'll consider between maximum of taking wt[i] and not taking it at all.
taking 0 to W in column 'line 1' taking wt in rows 'line 2'
two cases ->
* cur_wt<=total wt in that c... | d030a57e8c7040cbd1f7a3556f21d599ac049428 | 704,268 |
def filter_graph(graph, n_epochs):
"""
Filters graph, so that no entry is too low to yield at least one sample during optimization.
:param graph: sparse matrix holding the high-dimensional similarities
:param n_epochs: int Number of optimization epochs
:return:
"""
graph = graph.copy()
g... | 04af2804e208b8ce582440b2d0306fe651a583b0 | 704,269 |
def rev_find(revs, attr, val):
"""Search from a list of TestedRev"""
for i, rev in enumerate(revs):
if getattr(rev, attr) == val:
return i
raise ValueError("Unable to find '{}' value '{}'".format(attr, val)) | 6b9488023d38df208013f51ed3311a28dd77d9b8 | 704,270 |
def untempering(p):
"""
see https://occasionallycogent.com/inverting_the_mersenne_temper/index.html
>>> mt = MersenneTwister(0)
>>> mt.tempering(42)
168040107
>>> untempering(168040107)
42
"""
e = p ^ (p >> 18)
e ^= (e << 15) & 0xEFC6_0000
e ^= (e << 7) & 0x0000_1680
e ^... | 4118b55fd24008f9e96a74db937f6b41375484c3 | 704,271 |
def multiplicar(a, b):
"""
MULTIPLICAR realiza la multiplicacion de dos numeros
Parameters
----------
a : float
Valor numerico `a`.
b : float
Segundo valor numerico `b`.
Returns
-------
float
Retorna la suma de `a` + `b`
"""
return a*b | 2d1a56924e02f05dcf20d3e070b17e4e602aecf6 | 704,272 |
def pascal_row(n):
"""returns the pascal triangle row of the given integer n"""
def triangle(n, lst):
if lst ==[]:
lst = [[1]]
if n == 1:
return lst
else:
oldRow = lst[-1]
def helpRows(lst1, lst2):
if lst1 == [] or lst2 == [... | 030fe3e574f4261c862a882e7fdeee836a1dffb7 | 704,273 |
def can_comment(request, entry):
"""Check if current user is allowed to comment on that entry."""
return entry.allow_comments and \
(entry.allow_anonymous_comments or
request.user.is_authenticated()) | 04bcd019af083cff0367e236e720f4f7b00f7a65 | 704,274 |
def single(mjd, hist=[], **kwargs):
"""cadence requirements for single-epoch
Request: single epoch
mjd: float or int should be ok
hist: list, list of previous MJDs
"""
# return len(hist) == 0
sn = kwargs.get("sn", 0)
return sn <= 1600 | 8734916221f0976d73386ac662f6551c25accfc3 | 704,276 |
def accuracies(diffs, FN, FP, TN, TP):
"""INPUT:
- np.array (diffs), label - fault probability
- int (FN, FP, TN, TP) foor keeping track of false positives, false negatives, true positives and true negatives"""
for value in diffs:
if value < 0:
if value < -0.5:
FP+=1
... | 001cebd169589f9f1494d9833c1fc49d8ba9964b | 704,277 |
def data_scaling(Y):
"""Scaling of the data to have pourcent of baseline change columnwise
Parameters
----------
Y: array of shape(n_time_points, n_voxels)
the input data
Returns
-------
Y: array of shape(n_time_points, n_voxels),
the data after mean-scaling, de-meaning a... | 94b550386b8411a96b9ccd3f5e93098560c327e1 | 704,278 |
import json
def load_json(path: str):
"""Load json file from given path and return data"""
with open(path) as f:
data = json.load(f)
return data | d165d087c78a0ba88d318a6dbe8b2ac8f9a8c4b5 | 704,279 |
def _get_int_val(val, parser):
"""Get a possibly `None` single element list as an `int` by using
the given parser on the element of the list.
"""
if val is None:
return 0
return parser.parse(val[0]) | d2e029657b3424027e83ee8e1e2be76e3abf8fda | 704,280 |
def gcd(a, b):
"""Compute greatest common divisor of a and b.
This function is used in some of the functions in PyComb module.
"""
r = a % b
while r != 0:
a = b
b = r
r = a % b
return b | 10f09e979b525dffe480ca870726459ad0420c0d | 704,281 |
def get_n_p(A_A, n_p_in='指定しない'):
"""付録 C 仮想居住人数
Args:
A_A(float): 床面積
n_p_in(str): 居住人数の入力(「1人」「2人」「3人」「4人以上」「指定しない」)
Returns:
float: 仮想居住人数
"""
if n_p_in is not None and n_p_in != '指定しない':
return {
'1人': 1.0,
'2人': 2.0,
'3人': 3.0,
'4人以上':... | db257abdb76ee35f16b07e5baccec82211737971 | 704,282 |
def make_mmvt_boundary_definitions(cv, milestone):
"""
Take a Collective_variable object and a particular milestone and
return an OpenMM Force() object that the plugin can use to monitor
crossings.
Parameters
----------
cv : Collective_variable()
A Collective_variable object whi... | 45baaaa70ea24cb564c529cd885597415561a25d | 704,283 |
def is_leaf_module(module):
"""Utility function to determine if the given module is a leaf module - that is, does not have children modules
:return:
True if the module is a leaf, False otherwise
"""
module_list = list(module.modules())
return bool(len(module_list) == 1) | f34cbd4e961a467117a980ab0b7829f4a8245d2f | 704,284 |
def _is_fix_comment(line, isstrict):
""" Check if line is a comment line in fixed format Fortran source.
References
----------
:f2008:`3.3.3`
"""
if line:
if line[0] in '*cC!':
return True
if not isstrict:
i = line.find('!')
if i!=-1:
... | 8ac7f74f2b4e57b9fb65183a46ed3dbfc0f7ef79 | 704,285 |
def parseConfigFile(configFilePath):
"""
:param configFilePath:
:return: a hash map of the parameters defined in the given file.
Each entry is organized as <parameter name, parameter value>
"""
# parse valid lines
lines = []
with open(configFilePath) as f:
for line in f:
... | aee6a1da052f4c2ef907bf41b2cfaa4b93612a5e | 704,286 |
def has_annotations(doc):
""" Check if document has any mutation mention saved. """
for part in doc.values():
if len(part['annotations']) > 0:
return True
return False | 6b57893bc35af45950ec2eeb5008b663028d48bf | 704,287 |
def DEFAULT_APPLICANT_SCRUBBER(raw):
"""Remove all personal data."""
return {k: v for k, v in raw.items() if k in ("id", "href", "created_at")} | 16fa853551cd03bcf1124639e23b0c72ec9db75d | 704,288 |
def partition(my_list: list, part: int) -> list:
""" Function which performs Partition """
begin = 0
end = len(my_list) - 1
while begin < end:
check_lower = my_list[begin] < part
check_higher = my_list[end] >= part
if not check_lower and not check_higher:
# Swap
... | 754a039eede5e143400b0fd58b622d57e083a671 | 704,289 |
def _sparse_elm_mul(spmat_csr, col):
"""
spmat (n, m)
col (n,)
"""
for i in range(spmat_csr.shape[0]):
i0, i1 = spmat_csr.indptr[i], spmat_csr.indptr[i+1]
if i1 == i0:
continue
spmat_csr.data[i0:i1] *= col[i]
return spmat_csr | 55c7ca7f848989eaa95a5917cfa40edf2d7e1372 | 704,290 |
import os
def make_file_path(file, args):
"""Create any directories and subdirectories needed to store data in the specified file,
based on inputs_dir and inputs_subdir arguments. Return a pathname to the file."""
# extract extra path information from args (if available)
# and build a path to the spec... | 58ac390734f60daf67adcd6e05b3bf721f4b2383 | 704,292 |
import hashlib
def calc_checksum(filename):
"""
Calculates a checksum of the contents of the given file.
:param filename:
:return:
"""
try:
f = open(filename, "rb")
contents = f.read()
m = hashlib.md5()
m.update(contents)
checksum = m.hexdigest()
... | 080e3686279ae126951cd1b66efdb9a0d2448011 | 704,295 |
def __filter_card_id(cards: list[str]):
"""Filters an list with card ids to remove
repeating ones and non-ids"""
ids = list()
for c in cards:
try:
int(c)
except ValueError:
continue
else:
if c not in ids:
ids.append(c)
ret... | 53f7cfa979ac8c7bc5357216eb903f5fe5abc02b | 704,296 |
import time
def get_elapsed_time(start_time) -> str:
""" Gets nicely formatted timespan from start_time to now """
end = time.time()
hours, rem = divmod(end-start_time, 3600)
minutes, seconds = divmod(rem, 60)
return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds) | d75a1873254e1b1cc9ffc714e65d3a9ed95e5803 | 704,297 |
import time
def gmt_time():
"""
Return the time in the GMT timezone
@rtype: string
@return: Time in GMT timezone
"""
return time.strftime('%Y-%m-%d %H:%M:%S GMT', time.gmtime()) | 6009f0c3bc185bca9209827f2c89e39917c1e418 | 704,298 |
import os
def is_subdirectory(path_a, path_b):
"""Returns True if `path_a` is a subdirectory of `path_b`."""
path_a = os.path.realpath(path_a)
path_b = os.path.realpath(path_b)
try:
relative = os.path.relpath(path_a, path_b)
except ValueError:
# Different mounts on Windows:
... | 935a5897ff447cc3c6e757d6528f795732bed56f | 704,300 |
def clean_string_columns(df):
"""Clean string columns in a dataframe."""
try:
df.email = df.email.str.lower()
df.website = df.website.str.lower()
except AttributeError:
pass
str_columns = ["name", "trade_name", "city", "county"]
for column in str_columns:
try:
... | eb9aaa474fe517b346eaa8cd93e669b3fcc3459d | 704,302 |
def ordinal(n: int) -> str:
"""
from: https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd#answer-4712
"""
result = "%d%s" % (n, "tsnrhtdd"[((n / 10 % 10 != 1) * (n % 10 < 4) * n % 10)::4])
return result.replace('11st', '11th').replace('12nd', '12th').replace('13r... | 97eecb539ae37c89ea3e4e76c5c913877fbf2365 | 704,304 |
def part_2():
"""Function which calculates the solution to part 2
Arguments
---------
Returns
-------
"""
return None | 7b454841494c9f717868eda727b6273fabbf8222 | 704,305 |
import glob
def expand_files(files):
"""Expands a wildcard to a list of paths for Windows compatibility"""
# Split at whitespace
files = files.split()
# Handle wildcard expansion
if len(files) == 1 and '*' in files[0]:
files = glob.glob(files[0])
# Convert to Path objects
return ... | 46e2d6e7ee1609c144d04a2d429dc07ff1786cf1 | 704,306 |
def split_exon(exon, cds):
"""Takes an exon and a CDS, and returns a map of regions for each
feature (UTR5/3, CDS) that may be inferred from the arguments.
Note that the CDS is simply returned as is, to simplify
downstream handling of these features."""
results = [cds]
if exon["start"] < cds["s... | e2bb12a688bbe3e5c79039c2a9cce4e5aa9e9a1b | 704,307 |
def state_dict_to_cpu(state_dict):
"""Make a copy of the state dict onto the cpu."""
# .state_dict() references tensors, so we detach and copy to cpu
return {key: par.detach().cpu() for key, par in state_dict.items()} | 2d1fcc07ab8eac192a846cbcdb8d7363ffd8e9e8 | 704,308 |
import unicodedata
def normalize_str(text):
"""
Normalizes unicode input text (for example remove national characters)
:param text: text to normalize
:type text: unicode
"""
# unicodedata NFKD doesn't convert properly polish ł
trans_dict = {
u'ł': u'l',
u'Ł': u'L'
}
... | 40c8f77cdbf08b12a3867cd4a9d9bb91b323b50b | 704,309 |
def get_context_data(data) -> dict:
"""Look for 'context' item in 'queries' item."""
if "queries" in data:
if "context" in data["queries"]:
if isinstance(data["queries"], list):
return data["queries"][0]["context"]
else:
return data["queries"]["con... | 4e05d3d9041a8199f32b4201dcfc69d3adef1034 | 704,310 |
import copy
def merge(src: list, dst: list) -> list:
"""Merge `src` into `dst` and return a copy of `dst`."""
# Avoid side effects.
dst = copy.deepcopy(dst)
def find_dict(data: list, key: str) -> dict:
"""Find and return the dictionary in `data` that has the `key`."""
tmp = [_ for _ i... | 84976322fda7306d6bc15507750314b6b4fcad44 | 704,311 |
def grab_receivers(apk) :
"""
@param apk : an APK instance
@rtype : the android:name attribute of all receivers
"""
return apk.get_elements("receiver", "android:name") | 632d6903b63ca9d815a9f9d81ff19b8d6dc12a84 | 704,312 |
def itos(x):
"""Converts intergers to strings"""
if type(x) != int:
raise ValueError("Input value not an integer!")
return '{}'.format(x) | 96efe311cade41b37c4f671ed0b7e5e2a74f3d0b | 704,313 |
import json
import re
def translate_reference_entities(ref_entities, mappings=None):
"""Transform MaaS reference data for comparison with test deployment.
Positional arguments:
ref_entities -- the reference entity data
Keyword arguments:
mappings -- describe the relationship between the referenc... | 8e7a6144b5d51fb25908a70100e0d1e03b10b3d5 | 704,314 |
import os
def file_size_feed(filename):
"""file_size_feed(filename) -> function that returns given file's size"""
def sizefn(filename=filename,os=os):
try:
return os.stat(filename)[6]
except:
return 0
return sizefn | da6c5d15df0f3d99022f3d42c95bb33a82065e32 | 704,315 |
import logging
def getLogger(name='root') -> logging.Logger:
"""Method to get logger for tests.
Should be used to get correctly initialized logger. """
return logging.getLogger(name) | dde177b07f9d8528d216fbc4c719e5bff9c67939 | 704,316 |
def public_dict(obj):
"""Same as obj.__dict__, but without private fields."""
return {k: v for k, v in obj.__dict__.items() if not k.startswith('_')} | 2edee1a17d0dad6ab4268f80eb565406656a77b4 | 704,317 |
def wilight_to_opp_position(value):
"""Convert wilight position 1..255 to opp.format 0..100."""
return min(100, round((value * 100) / 255)) | 4f6e4298a77c29ff0375d0ce5e5fd23e77e30622 | 704,319 |
def get_task_link(task_id, task_df):
"""Get the link from the PYBOSSA task."""
try:
task = task_df.loc[int(task_id)]
except KeyError:
return None
return task['info']['link'] | d90e994d2f0a4718bbedf8fd5fd534f6d5d32549 | 704,320 |
from typing import List
from typing import Tuple
def partwise_function(function: str, parts: List[Tuple[str, str]], add_zero_otherwise: bool = True) -> str:
"""
Returns a string representing the definition a part-wise mathematical function.
**Parameters**
- `function`: str
The name of the f... | b2954a9c947add4cf4b4740ac62f4ca16d3e1d70 | 704,321 |
def read_restrictions_file(file):
"""
<Purpose>
Reads in the contents of a restrictions file.
<Arguments>
file: name/path of the file to open
<Returns>
A list, where each element is a line in the file
"""
# Get the file object, read mode with universal newlines
fileo = open(file,"rU"... | df7207ea3bab49af47fcfbdaa9cc51f54692bb85 | 704,322 |
import re
def uniescape(text: str) -> str:
"""
Escapes all non-ASCII printable characters with JavaScript Unicode escapes.
"""
def escape(match):
character = match.group(0)
assert len(character) == 1
code_point = ord(character)
assert code_point <= 0xFFFF
retur... | 0ce57acb1dc8dc88ad366844f323e6527eb655af | 704,323 |
from typing import Dict
from typing import List
from typing import Union
def aggregate_collate_fn(insts) -> Dict[str, List[List[Union[int, str, List[int]]]]]:
"""aggregate the instance to the max seq length in batch
Args:
insts: list of sample
Returns:
"""
subtree_spans, children_spans, s... | 5b3cbb71876b9814a9664f0d99396308a218c3aa | 704,324 |
import re
def clean(s):
"""
remove symbols and lowercase
"""
regex = re.compile('\W+')
s = regex.sub(' ', s).strip()
return s.lower() | f0f71dacac0d792c10480f9eec605bc85bf58be0 | 704,325 |
def trueifset(xeval, typematch=False):
"""return True if @xeval is set, otherwise False"""
if typematch:
if not (xeval is False or xeval is None): return True
else: return False
else:
if xeval: return True
else: return False | ff9ab55f869edc0fc784d9a34f55fe46652f22b5 | 704,326 |
def get_file_content(file: str) -> str:
"""
Get file content.
"""
try:
with open(file, 'r') as f:
content = f.read()
return content
except IOError as e:
print(e)
print('Exiting...')
exit(1) | c10407d73ba2cd2d84eb99c0f131d3895ede460d | 704,327 |
def Any(x):
"""The Any type; can also be used to cast a value to type Any."""
return x | 88abecb27317e5bf16c5bd27c306ce800c7ac760 | 704,328 |
def resource_name_for_resource_type(resource_type, row):
"""Return the resource name for the resource type.
Each returned row contains all possible changed fields. This function
returns the resource name of the changed field based on the
resource type. The changed field's parent is also populated but is not us... | 500bc32be1765f1e516f4f7cd386b24c3c4f373f | 704,329 |
import re
def to_yw7(text):
"""Convert html tags to yWriter 6/7 raw markup.
Return a yw6/7 markup string.
"""
# Clean up polluted HTML code.
text = re.sub('</*font.*?>', '', text)
text = re.sub('</*span.*?>', '', text)
text = re.sub('</*FONT.*?>', '', text)
text = re.sub('</*SPAN.*?... | 59b9b961f7a94d23e2829b9d940f63c32207600b | 704,330 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.