content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _sort_circle(the_dict):
"""
Each item in the dictionary has a list. Return a new dict with each of
those lists sorted by key.
"""
new_dict = {}
for k, v in the_dict.items():
new_dict[k] = sorted(v)
return new_dict | 0491dad0ff05e03b9775ccb5b9774e53b5960761 | 665,887 |
def make_anchor(type):
"""Takes a type name in CamelCase and returns the label (anchor) equivalent which is
all lower case, as the labels Sphinx generates for headers.
"""
return type.lower() | b88d615a904ca9cecc64287f48fae7072deb7965 | 665,888 |
import argparse
import shlex
import os
def GetOutputDirectory():
"""Returns the output directory that GYP will use."""
# Handle command line generator flags.
parser = argparse.ArgumentParser()
parser.add_argument('-G', dest='genflags', default=[], action='append')
genflags = parser.parse_known_args()[0].ge... | b9aefd8dd29696b39ad958db0c09198a8acdbbc1 | 665,889 |
def order_status_mapping(show_type):
""" 订单类型映射 """
status_dict = {
'0': [101, 102, 103, 201, 202, 203, 300, 301, 302, 303, 401],
# 代付款
'1': [101, 801],
# 代发货
'2': [300],
# 代收获
'3': [301],
# 代评价
'4': [30... | 67099148094b8eed1ff473d35460b81cdb3e71be | 665,890 |
import hashlib
def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
"""https://stackoverflow.com/a/4213255"""
h = hash_factory()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(chunk_num_blocks * h.block_size), b""):
h.update(chunk)
return h.hexd... | 4e4a039e576e2f3c4128bf434cd53d0e98a67122 | 665,891 |
import glob
def file_path_checker(name, suffix):
"""
Checks file paths for every sample to ensure that ratios of removed reads can be accessed.
Args:
name: Name of sample.
suffix: Version of meRanCall output
Return:
None
"""
print(name + " " + suffix)
try:
... | 59dd3bc68cec0fcfb05ed19ed75e587aecb10673 | 665,893 |
def changeInteraction(G, i, j):
"""
change statistic for Interaction
"""
return G.binattr[i] * G.binattr[j] | e9a54b7441373ef0ba8902cd75cf8c4c45cd78ef | 665,894 |
import os
import shutil
def asset_dir(tmpdir):
"""Copy the sample assets to a temporary directory and return path.
"""
test_dir = str(tmpdir.join('source'))
assets = os.path.join(os.path.dirname(__file__), 'pdfs')
shutil.copytree(assets, test_dir)
return test_dir | 6ece87a4020f705b077a1e79d8d1710273c700b3 | 665,895 |
import pickle
def read_data(infile):
"""Read data array.
Args:
infile (str): path to file
Returns:
np.ndarray: numpy arrays for features and labels
"""
print(f'Reading data from {infile}')
with open(infile, 'rb') as f_read:
obj = pickle.load(f_read)
array_ordered ... | 89b3ef2b081701789e3cfe6f33559078b5cadfee | 665,896 |
def vsize(min, max):
"""Keep reads with at least one variant falling within given v_range
Returns False for pure reference reads
:param min:
:param max:
:return:
"""
return lambda mate: any(min <= v <= max for v in mate['read_info'].v_list) | 5bb333d36d9f6ed039f8453ee58ee5d6260df338 | 665,897 |
def construct_processor_name(type_robot, type_processor):
"""
Construct the name of a single Post Processor.
:param type_robot: Type of robot.
:param type_processor: Type of processor.
:return:
"""
return '{} {}'.format(type_robot, type_processor) | da23435cdd4fdeb5c4ec1f550fbbef0fb655c6ec | 665,898 |
def load_input_data(input_path, do_lowercase):
"""Load input data."""
examples = []
lc = 0
with open(input_path, "r") as f:
for line in f:
lc += 1
line_split = line.strip().split("\t")
print(line_split)
if len(line_split) != 2:
raise Exception("Each line is expect to only hav... | 32ba298b930db730634c7853db06e9dddbfc122f | 665,899 |
def get_controller_index_by_typename(net, typename, idx=[], case_sensitive=False):
"""
Returns controller indices of a given name of type as list.
"""
idx = idx if len(idx) else net.controller.index
if case_sensitive:
return [i for i in idx if str(net.controller.object.at[i]).split(" ")[0] =... | 0ec63ed37114be6b764dc2de880a98c313ad0df5 | 665,900 |
def cap(v, l):
"""Shortens string is above certain length."""
s = str(v)
return s if len(s) <= l else s[-l:] | 8683d647f12aaf82880df8fe2f373a19ad24c674 | 665,902 |
import sqlite3
def openDatabase(file,inMemory=False):
"""Open SQLite db and return tuple (connection,cursor)"""
if inMemory==True:
conn=sqlite3.connect(':memory:')
else:
conn=sqlite3.connect(file)
conn.row_factory = sqlite3.Row
cursor=conn.cursor()
return (conn,cursor) | 5982508d8240c276a91d6118180b869d9e90de52 | 665,904 |
from typing import Any
def __wrap_boolean_value(value: Any) -> str:
"""
If `value` is Python's native True, returns 'true'.
If `value` is Python's native False, returns 'false'.
Otherwise returns 'null'.
"""
if value is True:
return 'true'
if value is False:
return 'false'
... | ef21b91d533e7d0d47cd2d1acb5a170d10a99779 | 665,906 |
def at_line_head(f):
"""judge if f's reading pointer is at the head of a line
Authors: xuruiqi
"""
if f.tell() == 0:
return True
else:
f.seek(f.tell() - 1)
return f.read(1) == "\n" | 862f57d29ca5b00238b04638d09d894e7a64ba65 | 665,907 |
from datetime import datetime
def datetime_helper(
datetime_str
):
"""try to convert datetime for comparison
Args:
datetime_str (str): datetime str (%Y-%m-%d) or (%Y-%m-%dT%H:%M:S)
Returns:
datetime.datetime
"""
try:
return_datetime = datetime.strptime(datetime_s... | b38988e5d64289197ecfe98537340ad91ef45874 | 665,908 |
def merge_lists(*lists):
"""Merges the given lists, ignoring duplicate entries.
Args:
*lists: lists of strings to merge
Returns:
A list of strings
"""
result = {}
for x in lists:
for elem in x:
result[elem] = 1
return result.keys() | 9d10de0f9ed07a6afd593979e4756ead017ae54b | 665,909 |
import os
from typing import List
def count_files_recursively(dir_path: str) -> int:
"""
Count the existing files number in a specified directory
recursively.
Parameters
----------
dir_path : str
Target directory path.
Returns
-------
count : int
Existing files co... | ac466dd485c991855bc56b5aa9955f7574e50c2d | 665,911 |
def sqr(x):
"""Return the square of x.
"""
return x*x | de543fbf626b2837781d7606c02147ddc8924af9 | 665,912 |
import argparse
def parse_args():
"""Parses user arguments"""
parser = argparse.ArgumentParser(
description="volafile downloader",
epilog="Pretty meh"
)
parser.add_argument('--room', '-r', dest='room', type=str, required=True,
help='Room name, as in https://vola... | a1ca46a308c58939b7a11f28b997233632cbf463 | 665,913 |
import asyncio
async def gather_with_concurrency(n, *tasks):
"""
Execute tasks concurrently with a max amount of tasks running at the same time.
Retrieved from https://stackoverflow.com/a/61478547/7868972.
"""
semaphore = asyncio.Semaphore(n)
async def sem_task(task):
async with semap... | c3241909b37d965391ad4a3e5809368a50544dd2 | 665,914 |
import functools
import warnings
def deprecated(msg=""):
"""Decorator factory to mark functions as deprecated with given message.
>>> @deprecated("Enough!")
... def some_function():
... "I just print 'hello world'."
... print("hello world")
>>> some_function()
hello world
>>> so... | 9617d6a8e5448f324b9f557e902c6e51c3f66a57 | 665,915 |
import torch
def l1norm(X, dim, eps=1e-8):
"""L1-normalize columns of X"""
norm = torch.abs(X).sum(dim=dim, keepdim=True) + eps
X = torch.div(X, norm)
return X | 6e3e9796f97403a4bf1513c8738ad343a2481392 | 665,916 |
def get_job_by_id(job_id): # noqa: E501
"""Get job by ID
# noqa: E501
:param job_id: ID of job that needs to be fetched
:type job_id: int
:rtype: Job
"""
return 'do some magic!' | 55595fa9428e1343029b3d039c9794880092f952 | 665,919 |
import json
def read_json(json_file):
"""
Updated to account for the scrapy output files
"""
try:
with open(json_file) as f:
products = json.load(f)
except:
# Scrapy output json is a bit different
products = []
with open(json_file, 'r') as f:
... | cef04acca06875a1b7b161d2bf5f4f23e6cbeec6 | 665,920 |
def fake_simple_login_algo_with_bu_dv_ac(mocker):
"""Mock with base_url, data_view and api_client attributes."""
return mocker.Mock(
base_url="basic instinct",
data_view="a point of view",
api_client="in a meeting with a client",
) | 0d434c1f1df0b9b3d277dcec960b70d18530ad98 | 665,921 |
import sys
def parse_bool(inpar):
"""
convert CLI True or False string into boolean
:param inpar: input True or False string (True/False or T/F)
:return: outpar (bool)
"""
msg = 'ERROR [parse_cli] CLI must be either True/False. ' \
'Exiting script...'
try:
if inpar.lowe... | 321726ddfe5b36fe22bf4cbb4d02c10d0a9da8ae | 665,922 |
def bin_hr(sl, pt, freq, t_sr):
"""
Given a training rule characterized by the parameters (sl, pt, freq), what is the min precision p required to achieve a Sharpe ratio t_sr?
:param sl: stop loss
:param pt: profit taking
:param freq: frequency = bets/per year
:param t_sr: target sharpe ratio
... | 759f9868d743c20127b8e7bac6dcf62acccbf52d | 665,923 |
import subprocess
def test_target_modules(triple, is_release, env, modules, parallel):
"""Does a cargo test on given modules for the triple and configuration.
Args:
triple: Target triple. Example: 'x86_64-unknown-linux-gnu'.
is_release: True to build a release version.
env: Enviroment variables to ru... | d5eccfca471d506fa5b008842e79d0dfefc0dbf2 | 665,924 |
def get_ods_by_race_3renfuku(xml):
"""
3連複 のページを読み込み、オッズを得る
"""
ods_3renfuku = []
tag_tables = xml.find_all('table', \
attrs={'class': 'ozSanrenUmaINTable'})
for tag_table in tag_tables:
tag_th_title = tag_table.find('th',
attrs={'class': 'title'})
title = ta... | 7f6158d986ef1d5938e7741da1d09111ec9323a4 | 665,925 |
import re
def floatAsReadable(f):
"""
source https://stackoverflow.com/questions/8345795/force-python-to-not-output-a-float-in-standard-form-scientific-notation-expo
"""
_ftod_r = re.compile(br'^(-?)([0-9]*)(?:\.([0-9]*))?(?:[eE]([+-][0-9]+))?$')
"""Print a floating-point number in the format ... | a17218c268ecf1aca17e67e1e520f17e454c19cf | 665,927 |
def s2_index_to_band_id(band_index):
"""s2_index_toBand_id returns the band_id from the band index
:param band_index: band index (0-12 inclusive) referencing sensors in ESA's metadata
:return: band_id for the band_index
"""
return {
0: '1', 1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7',
... | 8e79e3f6c162656f7884feb0eeb8aa5e8d5055dd | 665,928 |
def ppm_to_dalton(mass:float, prec_tol:int)->float:
"""Function to convert ppm tolerances to Dalton.
Args:
mass (float): Base mass.
prec_tol (int): Tolerance.
Returns:
float: Tolerance in Dalton.
"""
return mass / 1e6 * prec_tol | 384eee4cf267dcd1ada8011bba70191ee2715c8e | 665,929 |
def abbreviated_record(A: list):
""" Результат тот же, что и в первом варианте, только более сокращённая запись
и при этом она быстрее работает плюс обёрнут в функцию.
Здесь добавлено условие если x < 0, то в массив заходит ноль и т.д.
:param A:
:return: list
"""
return [0 if x < 0 else x **... | 8188a7bea18810f89ce767112365e78cf0f861ec | 665,930 |
import os
def abspath_dict(cond_filenames):
"""
Dictionary of filename's absolute path
"""
cond_filenames_dict = {}
for f in cond_filenames:
_, fname = os.path.split(f)
fname, _ = os.path.splitext(fname)
cond_filenames_dict[fname] = f
return cond_filenames_dict | 18f99189588455585957f319fdc521948e4198c8 | 665,931 |
def listsplit(liststr=u''):
"""Return a split and stripped list."""
ret = []
for e in liststr.split(u','):
ret.append(e.strip())
return ret | 1619917aeb57b1245e321dd48d2d32db5e2a3824 | 665,932 |
import multiprocessing
def timeout(seconds, return_value=None):
"""
Function dectorator that times-out after a number of seconds
Arguments:
seconds (float):
Keyword Arguments:
return_value (Any): Value returned if the function times out
Returns:
(Any): Result of the func... | 230105d56e76c6aa048868238275d5c2dd33b793 | 665,933 |
import os
import json
def check_bgdinfofile(bgdinfofile):
"""
Check that the background info file has the required items.
Parameters
----------
bgdinfofile : str
Path to a JSON file containing information related to the background
model. It must contain the following:
.. ... | 85636ca3b233851c935e999cab154c5f7f167f16 | 665,934 |
def canPublish_func(val):
"""
:Description:
Example callback function used to populate a jinja2 variable. Note that
this function must be reentrant for threaded applications.
Args:
val (object): generic object for the example
Returns:
example content (True)
"""
... | 235ef26b55019b75e22e12695f9d5a4ab571e3e8 | 665,935 |
def matrix_matrix_product(A, B):
"""Compute the matrix-matrix product AB as a list of lists."""
m, n, p = len(A), len(B), len(B[0])
return [[sum([A[i][k] * B[k][j] for k in range(n)])
for j in range(p) ]
for i in range(m) ] | ac4657df9efaf3bf903e818dfdef118590349300 | 665,936 |
def raw_input_default(prompt, default=None):
"""prompts the user for a string, proposing a default value in brackets."""
if default:
prompt = "%s [%s]: " % (prompt, default)
res = input(prompt)
if not res and default:
return default
return res | 801dc3b3e8a5d54cb9a500461d9296650f2c4e22 | 665,937 |
def lls_predict(A, X):
"""Given X and A, compute predicted value Y = A.T@X
"""
if X.ndim == 1:
return A * X
else:
return A.T @ X | d70dfba5bb5c911382efc373ac0a4b405c1490ea | 665,938 |
def ilog(n):
"""returns the smallest a, b s.t. a**b = n for integer a, b"""
a = n.bit_length()
for b in range(a, 0, -1):
lo, hi = 1, 1 << (a // b + 1)
while lo < hi:
mi = (lo + hi) // 2
a_b = mi**b
if a_b == n:
return mi, b
if a... | a7006f613679742a83c529100320e8a517946a95 | 665,939 |
def md_headline(title, level):
"""
Format a markdown header line based on the level argument
"""
level_char_list = ['=', '-']
try:
level_char = level_char_list[level]
except IndexError:
level_char = '='
return '\n%s\n%s\n' % (title, (level_char * len(title))) | 25ae97fbee0d356dbffca268b4a7f5fec67631f2 | 665,940 |
import os
def getSize(filename):
"""Returns size of file
"""
try:
return os.path.getsize(filename)
except:
return 0 | 6f0c21986f70aaead6601a8443ef092ade6e2fc4 | 665,941 |
def get_issue_info(payload):
"""Extract all information we need when handling webhooks for issues."""
# Extract the title and the body
title = payload.get('issue')['title']
# Create the issue dictionary
return {'action': payload.get('action'),
'number': payload.get('issue')['number'],
... | fd3836a94dbd93a387cd9d38b81c37c2a73be4ba | 665,942 |
import timeit
def time_fit(n=10):
"""Time actually generating the data."""
code = r"""fit = MODEL.sampling(
data={'n': %s},
seed=42,
iter=1,
chains=1,
algorithm="Fixed_param"
)
""" % n
t = timeit.timeit(
code,
number=1,
globals=global... | d078d11894c3135d68f7b16a235f047f0827909c | 665,943 |
def say_hello(name):
"""Very simple example of passing variables to func's docstring."""
print(f'Hello, my friend, {name}!')
return 42 | 49941b1dbdcfc690c55bef8624f9ef8c11c4a82b | 665,944 |
def validObject(object_):
"""Check if the data passed in POST is of valid format or not."""
if "@type" in object_:
return True
return False | efe5a1c94f0291ccc304ecea6759f004dc83801a | 665,945 |
def update_config_resgrp(config):
"""load resource group related config info"""
cnf_az_cluster = config["azure_cluster"]
cnf_az_cluster["resource_group"] = cnf_az_cluster.get(
"resource_group", config["cluster_name"] + "ResGrp")
cnf_az_cluster["vnet_name"] = config["cluster_name"] + "-VNet"
... | 93da176d82aaca5d3158faf5f1c6bf037de36a00 | 665,946 |
def decrypt(ciphertext, private_key):
"""function used for decryption"""
try:
key, n = private_key
text = [chr(pow(char, key, n)) for char in ciphertext]
return "".join(text)
except TypeError as e:
print(e) | ea4a48b2e994b861d6e7aab09d741ae37a03b068 | 665,947 |
def is_overlapping(bbox1, bbox2):
"""
:param bbox1:
:param bbox2:
:return:
"""
overlap = (max(bbox1[0], bbox2[0]), min(bbox1[1], bbox2[1]),
max(bbox1[2], bbox2[2]), min(bbox1[3], bbox2[3]))
return overlap[0] < overlap[1] and overlap[2] < overlap[3] | c665c9876d5c5143bdd78fec5ba6f4d3baae1b97 | 665,948 |
import copy
def copy_token(tok,attr):
"""make a new token by addding attributes 'attr' to tok"""
tcopy = copy.copy(tok)
for v in attr:
tcopy.__setattr__(v,attr[v])
return tcopy | cf2b671383b021d8c33d45e4b34f8235bc791b17 | 665,949 |
import collections
def graph_traversal(outputs):
"""helper function to traverse the computing graph and reeturn enough useful information
:param outputs: model outputs
:type outputs: :class:`.Symbolvar`
:return: tuple (map_oprs, map_vars, var2oprs, opr2receivers, indegree2opr, opr2indegree)
... | ab347a253bee9c7625e5bf19a61e60a39abf87fa | 665,950 |
from typing import Type
from enum import Enum
from typing import List
def enum_values(enum_cls: Type[Enum]) -> List:
"""List enum values."""
return [v.value for v in enum_cls] | 6ca7856af9abfbeae8bbdf7dec10db0b238f8e63 | 665,951 |
import uuid
def generate_appkey():
"""生成开发者的appkey"""
appkey = str(uuid.uuid1())
return appkey.replace('-', '') | 880f57dd68fb76fe28482481950a8c98941d730b | 665,953 |
def get_txtfilename(ID, era):
""" Return the txtfilename given by station ID and era in correct format."""
return era+'_'+ID+'.txt' | 54497cf696b543a3d1b4da66c2adaea2cc23e078 | 665,954 |
def Euler005(n):
"""Solution of fifth Euler problem."""
found = True
number = 0
while found:
i = 1
number += n
while number % i == 0 and i <= n:
if i == n:
found = False
i += 1
return number | ea2f22c9201d006f8ee99cdae36992f39b2ede60 | 665,955 |
def popcount(n=0):
"""
Computes the popcount (binary Hamming weight) of integer `n`.
Arguments
---------
n : a base-10 integer
Returns
-------
int
Popcount (binary Hamming weight) of `n`
"""
return bin(n).count('1') | fb44bbae77e0223196e2eb1352f3126605510bfb | 665,956 |
def GetGapSequenceConsensus_old(origTopoMSASeqList, indexIDTTopo):#{{{
"""Get a sequence of gap fractions of the consensus topology """
gapSeqCons =[];
apd=gapSeqCons.append
lengthAlignment = len(origTopoMSASeqList[0]);
numIDTTopo = len(indexIDTTopo)
for i in range(0, lengthAlignment):
... | 672d3071ef5643688efbd093034be4a8db33f39d | 665,957 |
def travel_time_filter(data):
"""
Filters for the employment prediction task
"""
df = data
df = df[df['AGEP'] > 16]
df = df[df['PWGTP'] >= 1]
df = df[df['ESR'] == 1]
return df | 3a94d85c27089f8dcbbdd1ec956a635df20acec6 | 665,959 |
from typing import Tuple
def get_neighbors(
cell: Tuple[int, int],
shape: Tuple[int, int, int],
with_start_position: bool = False,
):
"""
:param cell:
:param shape:
:param with_start_position
:return: The neighbor cells of the given cell, respecting the map shape
"""
p, q = sha... | 613638d13d0a3dd9b4b2e2dd8f03b232fb47f85c | 665,960 |
import xmltodict
def gen_query(search_ligand, search_protein=None, querymode=None):
"""
Args:
search_ligand: the Chem_ID of the FDA-approved inhibitor of interest
search_protein: UniProt Accession ID for the approved target for the inhibitor
querymode: string indicating whether searchi... | 4a70162f61bed0818cea7029aed71e178d55e1d1 | 665,961 |
def hamming_distance(str1, str2):
"""
Computes the number of different characters in the same position for two given strings. Typically the inputs are binary, but it needs not be the case.
Parameters:
----------
str1: str
str2: str
Returns:
-------
int: hamming distance
Exampl... | 6c487d875c0a6a9ca87e45a6f9b7d944af2b1d4a | 665,962 |
def get_node_ip(boot_conf, hostname):
"""
Returns the IPs of the configured nodes
:param boot_conf: the snaps-boot config to parse
:param hostname: the hostname in boot_conf that contains the IP returned
:return: a list if IPs for the given nodes
"""
if ('PROVISION' in boot_conf and 'STATIC'... | 577dde67f48d9e7b6e4ccdb0290ffe92fe25e8f2 | 665,963 |
import torch
def regulate_len(durations, enc_out, pace=1.0, mel_max_len=None):
"""A function that takes predicted durations per encoded token, and repeats enc_out according to the duration.
NOTE: durations.shape[1] == enc_out.shape[1]
Args:
durations (torch.tensor): A tensor of shape (batch x enc... | cfe975c3f9e2580421584421c0667e153833df54 | 665,964 |
def komogorov(r, r0):
"""Calculate the phase structure function D_phi in the komogorov approximation
Parameters
----------
r : `numpy.ndarray`
r, radial frequency parameter (object space)
r0 : `float`
Fried parameter
Returns
-------
`numpy.ndarray`
"""
return 6... | 38b42d967263e2ae1cb1fab9fccc7282bb92a4e2 | 665,965 |
def mix_targets(preds, targets, target_name1, target_name2, weight1=0.5,
weight2=0.5, skip_missing=False, new_name=None):
"""
Linearly combines two targets into one, optionally with custom weights,
storing it under the name of the first one, unless `new_name` is given.
`weight1` and `wei... | 048341c365cc7166027e3aa46f805c14d233c227 | 665,966 |
def calculate(expression, decimal=None, data_type='str'):
"""
数据计算,返回结果
// 为整除;/ 为自然除法,如4/2=2.0;% 为求余数;其他参考python
:param data_type:
:param expression: 计算表达式,python表达式均可用,但建议只用于数据计算, 比如1+1
:param decimal: 保存小数点位数,默认为None, 对结构是浮点数才有效,否则无效
:data_type: 返回数据的类型,默认是str, 可选:int, str; 如果是浮点数据,则以str返... | b7a2a86d81918c429c6049b716679dd0b12cab6f | 665,967 |
def ext2str(ext, compact=False, default_extver=1):
"""
Return a string representation of an extension specification.
Parameters
----------
ext : tuple, int, str
Extension specification can be a tuple of the form (str,int), e.g.,
('sci',1), an integer (extension number), or a string ... | 845a20832765f4c82357e7555c44f37cc0659393 | 665,968 |
import math
def cos(angle):
"""Retorna el coseno de un angulo"""
return math.cos(math.radians(angle)) | 995c9a4ad31de4f812eef143379d0b4e3b0380dd | 665,969 |
def way(routing, start, end):
"""Return the route from the start to the end as a list"""
route = []
current_node = end
while current_node != start:
route.insert(0, current_node)
current_node = routing[current_node]
return route | 924d5546db62aa799eb7bcf62acb6452d49f1caa | 665,970 |
def isclose(a, b, rel_tol=1e-02, abs_tol=0.0):
"""
Parameters
----------
a : int/float
first value
b : int/float
second value
rel_tol : float, (optional)
relative tolerance
abs_tol : float, (optional)
the absolute tolerance
Returns
-------
"""
... | ac6bf537c3abc3597373330dab4af4b0679e1d48 | 665,971 |
def check_rosetta_access(user):
"""Need this to check access to translation app (rosetta)"""
return user.is_staff | cc028b2948cf51dd46ccdce9377afa2bf082cf12 | 665,972 |
import os
def _check_path_exist(path):
""" Returns true if the given path exists"""
return os.path.exists(path) | 7af09f6a60e50c5aae520c8447acd1266c5494fe | 665,973 |
def parse_info_cfg(filename):
"""
Extracts information contained in the Info.cfg file given as input.
:param filename: path/to/patient/folder/Info.cfg
:return: values for: ed, es, group, h, nf, w
"""
ed, es, group, h, nf, w = None, None, None, None, None, None
with open(filename, 'r') as f:
... | 92769fc607c925c86a1d52802de31227c17123c9 | 665,974 |
import sympy
def isprime(candidate: int) -> bool:
"""
checks if an integer is prime
"""
return sympy.isprime(candidate) | 71c64cffc4e340a6cffd8007c647b270ed2080a2 | 665,975 |
def escape_shell(s):
"""
Escape a string so that it is a shell string.
:type s: str
:rtype: str
"""
'\'' + s.replace('\'', "'\"'\"'") + "'"
return s | 79585f072d9eae27d083b27491b980cc8689cfd0 | 665,976 |
import math
def safe_is_nan(x):
"""Is the value NaN (not a number).
Returns True for np.nan and nan python float. Returns False for anything
else, including None and non-numeric types.
Called safe because it won't raise a TypeError for non-numerics.
Args:
x: Object to check for NaN.
... | 2371352b9975c22130ecba83ea738b0e35ee07ac | 665,977 |
import time
def formatTime(when, localtime=0):
"""Given a time in seconds since the epoch, returns a time value in the
format used by server descriptors (YYYY/MM/DD HH:MM:SS) in GMT"""
if localtime:
gmt = time.localtime(when)
else:
gmt = time.gmtime(when)
return ("%04d-%02d-%02d... | 13194972e4f4c4a0cfba061550390ee59e3acdc6 | 665,978 |
def GetSymmPerChannelQuantParams(extraParams):
"""Get the dictionary that corresponds to test_helper::TestSymmPerChannelQuantParams."""
if extraParams is None or extraParams.hide:
return {}
else:
return {"scales": extraParams.scales, "channelDim": extraParams.channelDim} | cb63e3319536e0472ce82fe29572682c94e99b6a | 665,979 |
def format_trail_helper_id(trail, D):
"""Formats a given CoMetGeNe trail using internal KGML reaction IDs.
Skipped reactions are equally accounted for.
:param trail: CoMetGeNe trail
:param D: directed graph that served as input to the HNet algorithm,
representing the reaction network in which ... | 5bfed8426d165c84799a9bffd1d726f1eea6b107 | 665,980 |
def c_to_k(temp):
"""
Converts Celsius to Kelvin.
"""
return temp + 273.15 | 1d52f9989fd4ea0eec59041e98993018c54ec31d | 665,981 |
def __pydonicli_declare_args__(var_dict):
"""
Limit a dictionary, usually `locals()` to exclude modules and functions and thus contain
only key:value pairs of variables.
"""
vars_only = {}
for k, v in var_dict.items():
dtype = v.__class__.__name__
if dtype not in ['module', 'fun... | 0b38f0df8eb72993ee895a9a85c8abdc92e426cb | 665,982 |
def always_hold(state):
"""Always hold strategy."""
return 'hold' | 892d418d6a0eb729780b3b9412dbdd5903035d28 | 665,984 |
def normalize(X):
""" Normalizes the input between -0.5 and 0.5 """
return X / 255. - 0.5 | acff24b3548cfb5a7219e0620d3bb7e04010c4f2 | 665,985 |
def has_publish_permission(request, queryset):
"""
Returns `True` if the given request has permission to change the publication
status of all given language resources, `False` otherwise.
"""
# if not request.user.is_superuser:
# for obj in queryset:
# res_groups = obj.editor_grou... | 4eba416192687e3a91cd46b921e004bbc4c7cbb0 | 665,986 |
from datetime import datetime
def assemble_config_file(config_info, total_steps):
"""Add timestamp into benchmark id."""
target_info = config_info.copy()
_bm = config_info["benchmark"]
target_info["benchmark"].update({"id": "+".join([
_bm["id"], datetime.now().strftime("%Y%m%d%H%M%S")])})
... | 78b61d1378e588658ada418df79185427996c09c | 665,987 |
def list_diff(listEE1, listEE2):
""" Difference between two earth engine lists
:param listEE1: one list
:param listEE2: the other list
:return: list with the values of the difference
:rtype: ee.List
"""
return listEE1.removeAll(listEE2).add(listEE2.removeAll(listEE1)).flatten() | 24ca014f66163c02c47f8bd67cf0e09f4ed6534e | 665,988 |
def sentinel_linear_search(sequence, target):
"""
:param sequence : 탐색을 진행할 배열
:param target : 탐색할 키(key) 값
;return : 키 값이 있는 위치(index), 없을 경우 None
"""
sequence.append(target)
index = 0
while sequence[index] != target:
index += 1
sequence.pop()
if index == len(seq... | e01411d95affa65473c4f01f2429dabe70045388 | 665,989 |
import tempfile
import os
def tempdir(suffix="", prefix="tmp", dir=None, mode=0o755):
"""Create a temporary folder and set the permissions."""
try:
path = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
os.chmod(path, mode)
return path
except Exception as e:
raise e | bd9d473ba1c3aff92caddbdee57a5de89b237aea | 665,990 |
def percentage_and_total_marks_pipe(data, config):
"""
Pipe to calculate maximum marks possible, total marks and percentage obtained by the student.
1. Total marks obtained are available in the 'TotalMarksObtained' key.
2. Maximum marks possible for the student are available in the 'MaxMarks' key.
... | 47a1a1949997b5bf0e0fff926e714371854142c6 | 665,991 |
def iteration(printer, ast):
"""Prints "for (name : type) {body}"."""
name_str = ast["name"]
type_str = printer.ast_to_string(ast["type"])
body_str = printer.ast_to_string(ast["body"])
return f'for ({name_str} : {type_str}) {body_str}' | 27390871e7b39424b1fd763ded31b12578352c07 | 665,993 |
from pathlib import Path
def yaml_path_to_html_path(yaml_path):
"""Converts a yaml filepath to the corresponding html filepath.
For instance: converts 'newsletters/yaml/week_032.yml' to:
'newsletters/html/week_032.html'.
Args:
yaml_path (pathlib.Path): the yaml path to ... | 1c32811b363effa339c5f5a443972bca74db8bec | 665,994 |
import string
import os
import random
def password_gen(length, chars=['letters', 'digits', 'special'], extra_chars=None):
"""
Generates random password of given length. The password consists
of symbols drawn from the set of specified character groups (@prm{chars})
and (optionally) of extra characters ... | 8d74e6201ef3a264779553202ebac6ce48fe1b01 | 665,995 |
import time
import math
def run_time(t1, name="", is_print=True):
"""Performance test function, test run time.
:param t1: Set the time of the breakpoint
:param name: Set the name of the print
:param is_print: True, Whether to print
:return: Printed string content
>>> t1 = time.time()
# t... | 5a25cfb969a09ca66273f960e8dae8583ef29da2 | 665,996 |
import subprocess
def get_commit_log(prevRelLabel, relBranch):
"""Return the output of 'git log --pretty=online --merges prevRelLabel..relBranch' """
print("Running git log --pretty=oneline --merges " + prevRelLabel + ".." +
relBranch)
return subprocess.check_output([
"git", "log", "--p... | ea917bac3485e3c86d347fcbbd55b2df4bf3c742 | 665,997 |
import numpy
def uint8_float(inarray):
"""Converts arrays, lists, tuples and UINTs ranging 0:255
into an array of floats ranging -1:1
>>> uint8_float(0)
-1.0
>>> uint8_float(128)
0.0
"""
return numpy.asarray(inarray, 'f')/127.5 - 1 | 214f424326a268b4e60334789979ab7894a730ef | 665,998 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.