content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from os.path import dirname, join
def get_version(relpath):
"""read version info from file without importing it"""
for line in open(join(dirname(__file__), relpath)):
if '__version__' in line:
if '"' in line:
# __version__ = "0.9"
return line.split('"')[1]
... | d49969bc2c778d800597dcf025eebe61b256e8ee | 672,153 |
def effort_required_to_make_a_sale():
"""
Real Name: Effort Required to Make a Sale
Original Eqn: 4
Units: Hours/Person
Limits: (0.0, 50.0)
Type: constant
Subs: None
This is the amount of time the agent must spend (on average) with a lead
(high or low value, for now) to make a s... | 11c9747d41dcf04da84d5e047b02690b29dffa34 | 672,154 |
def get_admin_url(page, lang=None):
"""Return the admin URL for a specific language."""
return page.get_admin_url() | 7d10fa259c6baecbdf733ed99ab7ec09585814c7 | 672,155 |
import zlib
import struct
def createGZStream(buffer):
"""
Manually create a GZ stream using the zlib library - the built in python
one seems to create incompatable GZ streams thankfully, the file format
is quite simple. See: http://www.gzip.org/zlib/rfc-gzip.html
"""
compressedBuffer = zlib.compress(buffer, 6);... | 652e3b5d4d95f7858bccffaa0c71f96fc73b5089 | 672,156 |
def RemoveAllJetPtCuts(proc):
"""
Remove default pt cuts for all jets set in jets_cff.py
"""
proc.finalJets.cut = "" # 15 -> 10
proc.finalJetsAK8.cut = "" # 170 -> 170
proc.genJetTable.cut = "" # 10 -> 8
proc.genJetFlavourTable.cut = "" # 10 -> 8
proc.genJetAK8Table.c... | 1f73ccfc1d81c6af449fe45990bc9097dbc91252 | 672,157 |
import importlib
def validate_external_function(possible_function):
"""
Validate string representing external function is a callable
Args:
possible_function: string "pointing" to external function
Returns:
None/Callable: None or callable function
Raises:
N/A # noqa
... | 47b1584fbca601a67ff495b45d8f634a3bd412cd | 672,158 |
def flatten(obj, keys):
"""
flattens the dictionary object specified in the argument
:param obj: object to be flattened
:param keys: list of keys which are not flattened by default
:return: reference of flattened object
"""
for key in keys:
values = obj[key]
if values:
... | ed65bf736d596747b055f4e8a98c0afaafe66f20 | 672,159 |
def std_problem_3(x):
"""Standard start point x0 = (0.5, 0.5, ...)"""
n = len(x)
f = [0.0] * n
for i in range(n - 1):
f[i] = x[i] * x[i + 1] - 1
f[n - 1] = x[n - 1] * x[0] - 1
return f | 3af6448f75662956b007c4840166445f683851a8 | 672,160 |
from pathlib import Path
def get_mirror_path(path_from: Path, path_to: Path) -> Path:
"""Return the mirror path from a path to another one.
The mirrored path is determined from the current working directory (cwd)
and the path_from. The path_from shall be under the cwd. The mirrored
relative path is t... | e617e58c426f91499ba6ec85e842513b19b98ce2 | 672,161 |
def load_requirements():
"""
Load requirements.txt file into a list.
"""
with open('requirements.txt') as f:
required = f.read().split('\n')
if len(required) == 1 and required[0] == '':
required = []
return required | 019f6720d37781660f938eba3fdb32da0f434815 | 672,162 |
def _translate_keys(inst):
""" Coerces into dictionary format, excluding all model attributes
save for id and name """
return dict(server=dict(id=inst['id'], name=inst['display_name'])) | 12cec4f95f8e012dc4d35846b951b32763be35b9 | 672,164 |
def L001_fix(segment, raw_stack, **kwargs):
""" We only care about the segment the preceeding segments """
# We only trigger on newlines
if segment.raw == '\n' and raw_stack[-1].name == 'whitespace':
# If we find a newline, which is preceeded by whitespace, then bad
deletions = []
id... | 1e55f780e47217a5000dd7baa96829265e0f9e66 | 672,167 |
def find_Align(name, all_files_list, img_suffix = '.png'):
"""Find a .Align file matching (same except for file type) an image file.
Parameters
----------
name : str
Image file name (relative; without full path).
all_files_list : list[str]
A list of all files in a directory where .A... | faef38335388d15b49cce62f8e2b4d43cad4015e | 672,169 |
def htk_int_to_float(value):
""" Converts an integer value (time in 100ns units) to floating
point value (time in seconds)...
"""
return float(value) / 10000000.0 | 54546e9d980ad0bcc488d086daa50a8bfb51821d | 672,170 |
from typing import Counter
def count_polymer_pairs(counts: Counter, rules: dict) -> Counter:
"""Count the number of element pairs in the next step for the polymer."""
new_step_counts: Counter = Counter()
for pair, pair_count in counts.items():
if pair_count > 0:
for new_pair in rul... | 5647b11e171507ad97747d49094f6d11587a8aef | 672,171 |
def parse_name(name):
""" Parse name of the form 'namespace_name.unit_name' into tuple ('namespace_name', 'unit_name'). """
if '.' not in name:
raise ValueError('`func` parameter must be provided or name must be "namespace_name.unit_name"')
name_components = name.split('.')
if len(name_component... | 97a81e27e9b9c5eaea1a13b1c9a28cddf549c7f6 | 672,172 |
def loglinear_rule_weight(feature_dict, feature_weights_dict):
"""
Compute log linear feature weight of a rule by summing the products of feature values and feature weights.
:param feature_dict: Dictionary of features and their values
:param feature_weights_dict: Dictionary of features and their weights... | 5db1edec2a3218144972434f6a7512484a3b71cc | 672,173 |
import os
def convert_affine(unwarped_brain, mean_func, out_fsl_file):
"""Converts fsl-style Affine registration into ANTS compatible itk format
Parameters
----------
unwarped_brain : structural reference image
mean_func : image that was coregistered
out_fsl_file : fsl-style coregistration ma... | af5cd2978ca200f1b1c11f9ca9e949ea80843d99 | 672,174 |
def get_view(name): # noqa: E501
"""get_view
Retrieve view details # noqa: E501
:param name: Name of the view
:type name: str
:rtype: ListView
"""
return 'do some magic!' | 0ef20df0ec0419949f2f0cb49d6cbdfa6e926cb3 | 672,176 |
import time
def elapsedTreeTimeExtractor(elapsedTimesDict, stepsDict):
"""elapsedTreeTimeExtractor() takes a newickTree, a list of all the present cycle
directories, and the parentNode and returns the total amount of machine time
spent on the tree including all branches.
"""
prgTimesDict = {}
... | b6c05a5fb948b96bc1b733aa4efc8eb3b86b147e | 672,177 |
def folder_from_egtb_name(name: str) -> str:
"""
Determine EGTB folder (Xvy_pawn(less|ful)) from EGTB name
:param name: EGTB name
"""
l, r = name.split('v')
prefix = f'{len(l)}v{len(r)}'
suffix = '_pawnful' if ('P' in l or 'P' in r) else '_pawnless'
return prefix + suffix | 4c4838bcbaa20ac422102526162d44bf1422fcf2 | 672,178 |
import inspect
def parental_funct_name():
"""
Return the current functions' name. Used to allow better snippets generation.
Source: https://www.stefaanlippens.net/python_inspect/
:return:
"""
return inspect.stack()[2][3] | 4dc7fdd7a52873e054a8468df0a68464af0cf38e | 672,179 |
from typing import Dict
def get_noise_cost_coeff(noises: Dict[int, float], db_costs: Dict[int, float]) -> float:
"""Returns noise cost coefficient."""
if not noises:
return 0.0
db_distance_cost = sum([db_costs[db] * length for db, length in noises.items()])
total_length = sum(noises.values())
... | 7892a0e3dad5d96baaf98109d565e063df28558d | 672,180 |
def is_among(value, *possibilities):
"""
Ensure that the method that has been used for the request is one
of the expected ones (e.g., GET or POST).
"""
for possibility in possibilities:
if value == possibility:
return True
raise Exception('A different request value was encoun... | ba6fd5a3a4ffae8e6d9db57b18d7e8a9b1cdf448 | 672,181 |
def butterfly_mul_np(ABCDs, input_):
"""Product of block 2x2 diagonal matrices, implemented in Numpy.
Parameters:
ABCDs: list of the ABCDs factors as used in Block2x2DiagProduct, in numpy array.
we accept real and complex.
input_: input_ vector as numpy array, (batch_size, n)
... | a261fff29b1e072f58ecd11ee9e6499c2290ec65 | 672,182 |
import time
import requests
def make_page_request(url, sol, camera, api_key, page):
"""Make one page request from NASA API."""
time.sleep(0.4)
params = {
'sol': sol,
'camera': camera,
'api_key': api_key,
'page': page,
}
response = requests.get(url, params=params)
... | e313f93f5acb2b5760d28ec95d357075396da69b | 672,183 |
import ast
def tryeval(val):
"""
Convert to the proper type, e.g. '87' -> 87
:param val: string
:return: mixed
"""
try:
val = ast.literal_eval(val)
except (SyntaxError, ValueError) as ex:
pass
return val | 408a049a63767b5e437956c048046c8b7d38e836 | 672,184 |
import torch
def householder_matrix(v, size=None):
"""
householder_matrix(Tensor, size=None) -> Tensor
Arguments
v: Tensor of size [Any,]
size: `int` or `None`. The size of the resulting matrix.
size >= v.size(0)
Output
I - 2 v^T * v / v*v^T: Tensor of size [size, ... | 8b00a552bed7f22b671a4e4fa0a6b6df67b3aadc | 672,185 |
def multiply(numbers):
"""
Write a Python function to multiply all the numbers in a list.
multiply([1,2,3,-4]) -> -24
"""
cummulator = 1
for i in numbers:
cummulator *= i
return cummulator | 875366fba178ffd9a3dab1df293d434b7e485f9e | 672,186 |
def balanced_error(refrxn, refeq, rrat, m=0.03, p=10.0):
"""
:param refrxn:
:param refeq:
:param rrat:
:param m: minimum permitted weight for a point
:param p: multiples of abs(refeq) above refeq to which zero-line in head is displaced
:return:
"""
one = float(1)
q = one if rrat... | ecaadb8ada0a283b0e6d9433bf7634f21272362a | 672,187 |
def count_first_word(str_list):
"""Count the first word of each string in the list.
Args:
str_list: List of strings
Returns:
{"word": count, ...}
"""
ret_count = dict()
for phrase in str_list:
words = phrase.split("-")
ret_count[words[0]] = ret_count.get(words[... | 3350441d38daec4bb9f659d780886efd4af7dd4f | 672,188 |
def kw_pop(*args, **kwargs):
"""
Treatment of kwargs. Eliminate from kwargs the tuple in args.
"""
arg = kwargs.copy()
key, default = args
if key in arg:
return arg, arg.pop(key)
else:
return arg, default | 8410e3313943286100643a2251d2190ed0903a4b | 672,189 |
import os
def readAtLeast(fd, bytecount):
"""Read 'bytecount' bytes from file descriptor fd. raise if we can't."""
inputData = os.read(fd, bytecount)
while len(inputData) < bytecount:
newData = os.read(fd, bytecount - len(inputData))
assert len(newData) != 0
inputData += newData
... | eb3fc72381807f7119d29e87354cf80e56bf5c5f | 672,190 |
def add_article(str_):
"""Appends the article 'the' to a string if necessary.
"""
if str_.istitle() or str_.find('the ') > -1:
str_ = str_
else:
str_ = 'the ' + str_
return str_ | 5bdcaeb0c9d0732bd32c3e0dfea808373b1fd186 | 672,191 |
def merge_cards_based_on_label(cards):
"""Merge cards with common label."""
cards_dict = {}
for card in cards:
label = card.get('label')
if label in cards_dict:
links = cards_dict[label].links + card.links
cards_dict[label].update(dict(links=links))
cards_dict[label] = cards_dict.pop(label)
else:
c... | 3d7a3ea3db8d24baffb8e1c0f040e6397b88ebec | 672,192 |
def extract_ipi(ipi_number):
"""IPI NUMBER must have 11 characters otherwise paddle left 0 till len == 11
or empty if not ipi number is supplied"""
return ipi_number if ipi_number == '' else f"{int(ipi_number):011}" | b931319fafe4a6a24c4fe70556d355bf58b6f055 | 672,193 |
import shlex
import subprocess
def check_dput_host(dput_host):
"""
Check spcified host is defined in dput.cf
:rtype: bool
:return: ``True`` is dput_host is defined
:param str dput_host: dput host
"""
command = '/usr/bin/dput -H'
args = shlex.split(command)
response = subprocess.c... | eb428338c5709fd53d82bb759698d2b8775daf81 | 672,194 |
def quantify(iterable, pred=bool):
"""Count the number of items in iterable for which pred is true."""
return sum(1 for item in iterable if pred(item)) | f43fbd0459db90615bd019e3afd9417abf7d8e88 | 672,195 |
def windows_low_high_to_int(windows_int_low, windows_int_high):
"""Returns an int given the low and high integers"""
return (windows_int_high << 32) + windows_int_low | ead6e4d19022f49e9bde7600f13399d3e236d10a | 672,197 |
import time
def filename_stamped(filename, number):
"""Create a time-stamped filename"""
time_str = time.strftime("%Y%m%d-%H%M%S")
return '{}_{}_{}'.format(filename, number, time_str) | cf97aad13edbc1657f328725f2351d2ca1481ce6 | 672,198 |
def say_hello() -> str:
"""Say hello function."""
return "Hello" | 42c2de62056246c01f4e0072e073d1fa944c406c | 672,199 |
def parse_hash_id(seq):
"""Return a list of protein numbers within the given string.
Example
-------
"#10,41,43,150#" -> ["10", "41", "43", "150"]
"""
ans = seq.strip("#").split(",")
return ans | 26e196be40c741dca9c09c79ec6e4352c48952e9 | 672,200 |
def shorten_dfs(dfs, plot_start=None, plot_end=None):
"""Shorten all incidence DataFrames.
All DataFrames are shortened to the shortest. In addition, if plot_start is given
all DataFrames start at or after plot_start.
Args:
dfs (dict): keys are the names of the scenarios, values are the incide... | a059d0a27ec521d816679aeba1e5bf355cb5dc16 | 672,201 |
def nt2over_gn_groupings(nt):
"""Return the number of grouping ``over'' a note.
For beamings trees this is the number of beams over each note.
Args:
nt (NotationTree): A notation tree, either beaming tree or tuplet tree.
Returns:
list: A list of length [number_of_leaves], with integer... | 7f2c2a281a55d8dd3b837b7510be4dcc93f74779 | 672,202 |
import os
def get_current_folder_file(file_type):
"""
通过文件类型,获取到当前目录下的文件 filename = get_current_folder_file('apk')
:param file_type:
:return:
"""
# 当前目录下所有的文件
all_files = os.listdir('.')
# 满足要求的文件列表
target_files = []
for file in all_files:
if file.split('.')[-1] == fi... | d4702c96307a6757035c1ea6a52fe6316f7c8a49 | 672,203 |
def valid_2(password, lower, upper, letter):
"""
Takes in a password and checks if it is valid
"""
if password[lower] == letter and password[upper] != letter:
return 1
elif password[lower] != letter and password[upper] == letter:
return 1
else:
return 0 | 38631bf389b351a2f8a427430bdc2fe6a3e07188 | 672,204 |
def center_crop(data, shape):
"""
Apply a center crop to the input real image or batch of real images.
Args:
data (torch.Tensor): The input tensor to be center cropped. It should
have at least 2 dimensions and the cropping is applied along the
last two dimensions.
sh... | c1f220e555333d38a83271d5e9254c4b1178d3c1 | 672,205 |
import copy
import random
def select_random_genes(parent_genes):
"""there are supposed to be 2 parents"""
child_genes = []
for i in range(len(parent_genes[0])):
child_genes.append(copy.deepcopy(random.choice([parent_genes[0][i], parent_genes[1][i]])))
for i in range(0, len(parent_genes[1]) - len(parent_genes[0]... | d72e69d70ab5ae1deab40530adedfb2e04fc96f9 | 672,206 |
def apply_concept_similarity_one(logits, *_, **__):
"""
Return
logits * 1
"""
return logits | afebc8ccf2c57dd933e30bb3da8bfc5d187e0e3c | 672,207 |
def fetch_method(obj, method):
"""
fetch object attributes by name
Args:
obj: class object
method: name of the method
Returns:
function
"""
try:
return getattr(obj, method)
except AttributeError:
raise NotImplementedError(f"{obj.__class__} has not impl... | 49f823c4f8fd2296f6fd17dcfd5fc72b8835b42a | 672,208 |
import uuid
def q_name(string: str) -> str:
"""
Return string representation of uuid5 of *string*.
Creates unique identifiers.
"""
if not isinstance(string, str):
raise TypeError(f"Parameter string: Expected type str, got type {type(string)}.")
return str(uuid.uuid5(uuid.NAMESPACE_DN... | e8e45bab96f55dab2516339fe8055f5f026623e0 | 672,209 |
def job_spec():
"""Job spec dict."""
job_spec = {
"experiment": "experiment",
"docker_img": "image",
"cmd": "cmd",
"prettified_cmd": "prettified_cmd",
"env_vars": {},
"workflow_workspace": "workflow_workspace",
"job_name": "job_name",
"cvmfs_mounts... | a6ce92e5a13af8012014dbb418c6b30e79ffebe8 | 672,210 |
def extend_dict(dict_1: dict, dict_2: dict) -> dict:
"""Assumes that dic_1 and dic_2 are both dictionaries. Returns the merged/combined dictionary of the two
dictionaries."""
return {**dict_1, **dict_2} | 88e2f1c613181046b388092677b8ee627c432d4d | 672,211 |
import requests
def download_zip(url:str, dest_path:str, chunk_size:int = 128)->bool:
"""Download zip file
Downloads zip from the specified URL and saves it to the specified file path.
see https://stackoverflow.com/questions/9419162/download-returned-zip-file-from-url
Args:
url (str): sl... | a4f6024695976f422bc6dc3979c8438cfff9c70e | 672,212 |
import os
import argparse
def vid_valid(vid):
"""
Validate the input video file.
"""
if (not os.path.isfile(vid) or
not vid.lower().endswith(('.mp4','.avi'))):
raise argparse.ArgumentTypeError(
'Cannot read video file. If the video type cannot be read, ' \
'ch... | 912141c4c6af2f88e55a47cef1fe748ea0870d6d | 672,213 |
def trash_file(drive_service, file_id):
"""
Move file to bin on google drive
"""
body = {"trashed": True}
try:
updated_file = drive_service.files().update(fileId=file_id, body=body).execute()
print(f"Moved old backup file to bin.")
return updated_file
except Exception:
... | f9a2a331a74cdb4050dc6bb788fc398d7db90ec1 | 672,214 |
import inspect
def extract_kwargs(docstring):
"""Extract keyword argument documentation from a function's docstring.
Parameters
----------
docstring: str
The docstring to extract keyword arguments from.
Returns
-------
list of (str, str, list str)
str
The name of the... | 3ec2442fbe3ec3984d6c5462f1c0006c4b723f2f | 672,215 |
def get_total_interconnector_violation(model):
"""Total interconnector violation"""
# Total forward and reverse interconnector violation
forward = sum(v.value for v in model.V_CV_INTERCONNECTOR_FORWARD.values())
reverse = sum(v.value for v in model.V_CV_INTERCONNECTOR_REVERSE.values())
return forw... | cbe6c1e3e1424623064e9d906d143e1ae728a141 | 672,216 |
def absorption_spectrum(spectrum_data):
"""Takes spectral data of energy eigenvalues and returns the absorption spectrum relative to a state
of given index. Calculated by subtracting from eigenenergies the energy of the select state. Resulting negative
frequencies, if the reference state is not the ground s... | 7cf5b6a9bba9e030a64cfb9a09bfc8e408ebba7d | 672,217 |
import hashlib
def Many_Hash(filename):
""" calculate hashes for given filename """
with open(filename, "rb") as f:
data = f.read()
md5 = hashlib.md5(data).hexdigest()
sha1 = hashlib.sha1(data).hexdigest()
sha256 = hashlib.sha256(data).hexdigest()
sha512 = hashlib.sha512(data).hexdiges... | 7805ab4e72726026a4fb21f754964d02fba857a0 | 672,218 |
def grad_likelihood(*X, Y=0, W=1):
"""Gradient of the log-likelihood of NMF assuming Gaussian error model.
Args:
X: tuple of (A,S) matrix factors
Y: target matrix
W: (optional weight matrix MxN)
Returns:
grad_A f, grad_S f
"""
A, S = X
D = W * (A.dot(S) - Y)
... | 4a52389764b9d52cc5dd4dae9f72fbdd46dba174 | 672,219 |
from typing import Sequence
from typing import List
def chain(items: Sequence, cycle: bool = False) -> List:
"""Creates a chain between items
Parameters
----------
items : Sequence
items to join to chain
cycle : bool, optional
cycle to the start of the chain if True, default: Fals... | d47e834b152c061011ec6278220777a5c3d04146 | 672,220 |
def _ensure_list_of_lists(entries):
"""Transform input to being a list of lists."""
if not isinstance(entries, list):
# user passed in single object
# wrap in a list
# (next transformation will make this a list of lists)
entries = [entries]
if not any(isinstance(element, list... | a1866fdd62861f40e7f5aa9ce491ba14fc5a6cc9 | 672,222 |
import os
import fnmatch
def find_packages(path):
"""
Recursively find RPM packages in a `path` and return their list
"""
packages = []
for root, _, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, "*.rpm"):
if filename.endswith(".src.rpm"):
... | a668c08de76636429e20cb38099579f1814ca554 | 672,223 |
import platform
import os
import stat
def which(exe):
"""locate the given executable via the environment, if necessary"""
# platform-specific executable checks
is_windows = platform.system() == "Windows"
if is_windows:
exe_check = lambda p: (os.stat(p)[0] & (stat.S_IXUSR | stat.S_IXGRP | stat.... | ea98675511a25abee6af6c0083353cc9de9c41ab | 672,224 |
def get_daily_returns(df):
"""Compute and return the daily return values."""
daily_returns = df.copy()
daily_returns[1:] = (df[1:] / df[:-1].values) - 1
daily_returns.iloc[0] = 0 # set daily returns for row 0 to 0
return daily_returns | 8b72e3bb446f77d0ccdd63d664da4f9a48f45cf0 | 672,225 |
def bitarray2dec(in_bitarray):
"""
Converts an input NumPy array of bits (0 and 1) to a decimal integer.
Parameters
----------
in_bitarray : 1D ndarray of ints
Input NumPy array of bits.
Returns
-------
number : int
Integer representation of input bit array.
"""
... | ae4cbb907c13d92a5dde734e7bb9d11ab4aa6225 | 672,226 |
import unicodedata
def _is_punctuation(ch):
"""标点符号类字符判断(全/半角均在此内)
提醒:unicodedata.category这个函数在py2和py3下的
表现可能不一样,比如u'§'字符,在py2下的结果为'So',
在py3下的结果是'Po'。
"""
code = ord(ch)
return 33 <= code <= 47 or \
58 <= code <= 64 or \
91 <= code <= 96 or \
123 <= code <= 126 or ... | 7da573f1fdd3eebd6c40b7652fc54226c152cd42 | 672,227 |
def set_state_dict(model, state_dict):
"""Load state dictionary whether or not distributed training was used"""
if hasattr(model, "module"):
return model.module.load_state_dict(state_dict)
return model.load_state_dict(state_dict) | fab8c5e73d0efa3df480e692697c865977066804 | 672,229 |
import re
def _parse_line(cpuid, match):
"""Search a line with the content <match>: <value> in the given
StringIO instance and return <value>
"""
cpuid.seek(0)
for l in cpuid.readlines():
m = re.match('^(%s.*):\s+(.+)' % match, l)
if m:
return (m.group(1), m.group(2).r... | d83fcc1e79b13e5ed11e79e3dad47eb99d0e2371 | 672,230 |
def other_options(options):
"""
Replaces None with an empty dict for plotting options.
"""
return dict() if options is None else options.copy() | b2f22bc681ed633445a7a984e3c9f3da9dc975ab | 672,231 |
from typing import Optional
import os
def get_logfile() -> Optional[str]:
"""Find a Genshin Impact logfile
:returns: A logfile path or None if no genshin installation exists
"""
mihoyo_dir = os.path.expanduser("~/AppData/LocalLow/miHoYo/")
for name in ["Genshin Impact", "原神", "YuanShen"]:
... | f69d0ea2e33501a90418d955f46fdd018245edb2 | 672,232 |
def tap(fun, value):
"""
A function that takes a function and a value, applies the function
to the value and returns the value.
Complexity: O(k) where k is the complexity of the given function
params:
fun: the function
value: the value
returns: the value
"""
fun(value)
... | 23883f7cfc8b8a5f7711726bc50fb3f9588da560 | 672,233 |
def getMax(data):
""" Find the maximum number of steps in the data and the date it was achieved.
Parameters:
data: Pandas DataFrame containing Apple Health data imported from a
.csv file.
Return:
The row of values for when the maximum number of steps were ac... | 3725bfb83d6a5c98259f2e38b8206f6bc87a446e | 672,234 |
from typing import Any
def make_safe(element: Any) -> str:
"""
Helper function to make an element a string
Parameters
----------
element: Any
Element to recursively turn into a string
Returns
-------
str
All elements combined into a string
"""
if isinstance(el... | ea104f847323c8b56ec20df57f28c98fce784cd7 | 672,235 |
import re
def demo_id(filename):
"""Get the demo_number from a test macro"""
b1 = re.match('.*/test_demo\d{2}\.py', filename)
found = re.findall('.*/test_demo(\d{2})\.py', filename)
b2 = len(found) == 1
is_test_file = b1 and b2
assert is_test_file, 'Not a test file: "%s"' % filename
return... | 9402586f92ea9d95eee10c9047efc6b43c25abac | 672,236 |
import token
import requests
def get_repos():
"""Finds all public GitLab repositories of authenticated user.
Returns:
- List of public GitLab repositories.
"""
url = f'https://gitlab.com/api/v4/projects?visibility=public&owned=true&archived=false'
headers = {'Authorization': f'Bearer {token... | 42161800a8f3d68ade2a68fc1ed732198a4d6d7f | 672,237 |
import numpy as np
def count_b0s(in_bval, low_bval=5.0):
"""
Count the number of volumes where b<=low_bval.
Args:
in_bval (str): bval file.
low_bval (Optional[int]): Define the b0 volumes as all volume
bval <= lowbval. (Default=5.0)
Returns:
num_b0s: Number of b0s... | 79eb9b5ef709d4ae4ff26f859698343e8ddd084e | 672,238 |
def read_classification_from_file(filename):
""" Return { <filename> : <classification> } dict """
with open(filename, "rt") as f:
classification = {}
for line in f:
key, value = line.split()
classification[key] = value
return classification | 8e3d30e55efd289fa98d0d28acf0d8d857ace835 | 672,239 |
def all_items(searchqueryset):
"""Return all items of SearchQuerySet.
Args:
searchqueryset (SearchQuerySet): QuerySet of search items.
Returns:
All items in index.
"""
return searchqueryset.all() | d19af2a2c9c5516ed9590e9ef32795b1eae5cd92 | 672,240 |
def truncate(message, limit=500):
"""
Truncates the message to the given limit length. The beginning and the
end of the message are left untouched.
"""
if len(message) > limit:
trc_msg = ''.join([message[:limit // 2 - 2],
' .. ',
message[... | 93d117c475e4a198b60a387f6911c9cbbc246e64 | 672,241 |
def get_slack_user(user, slack_users):
"""Return user profile from Slack."""
if hasattr(user, "profile"):
if user.profile.slack_api_id:
for slack_user in slack_users:
if slack_user["id"] == user.profile.slack_api_id:
return slack_user
return None
... | 9753fb1f929389b58b95a91193bda1e494c8fa30 | 672,242 |
import torch
def batchmv_cosine_similarity(m, v):
"""
Computes a cosine similarity between batches of matrices and vectors.
计算批量矩阵和向量之间的余弦相似度
参数:m:一个包含一批矩阵的#维张量
:param m: a #D tensor that contains a batch of matrices
参数:v:一个包含一批矩阵的2维张量
:param v: a 2D tensor that contains a batch of vectors... | e2a3d6806e2678f50a6c23895bf525114dc32ab9 | 672,243 |
import numpy
def simulate_Noise(frequency, times, power=50e3, bchan = None, echan = None, timevariable=False, frequency_variable=False):
""" Calculate Noise sqrt(power) as a function of time and frequency
:param frequency: (sample frequencies)
:param times: sample times (s)
:param power: DTV emitted ... | cdd1e1e6300b3c523fc27227f7e168f9b4037e17 | 672,244 |
def findDataStart(lines, delin = ' '):
"""
Finds the line where the data starts
input:
lines = list of strings (probably from a data file)
delin = optional string, tells how the data would be separated, default is a space (' ')
output:
i = integer where the data stops being... | b9e2aa79d9eae1616412491763cfdde3e6e37672 | 672,247 |
import os
def list_files(path):
"""Returns a list of all non-hidden files in a directory"""
return [file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file)) and file[0] != "."] | a04e02b056c1b641a36c55ee64459c98c61096ec | 672,248 |
import linecache
import random
def get_verse(filepath, min_len):
"""
:param filepath: Path to txt-file (e.g. /home/Documents/file.txt or file.txt)
:param min_len: Minimum line length
:return: A random text line (exclude ones with ':', '=' etc. last character)
"""
if filepath == '':
ret... | ff9283a2efcd4a5cbabbf603b0ff70830dce2716 | 672,249 |
def pa_bbm_hash_mock(url, request):
"""
Mock for Android autoloader lookup, new site.
"""
thebody = "http://54.247.87.13/softwareupgrade/BBM/bbry_qc8953_autoloader_user-common-AAL093.sha512sum"
return {'status_code': 200, 'content': thebody} | 4d1909fef728aa2adec2b418796747a7b789add1 | 672,250 |
def _range_check(datarange):
"""
Utility to check if data range is outside of precision for 3 digit base 256
"""
maxrange = 256 ** 3
return datarange > maxrange | d385c0137f71d8f029a6c5d7b0e38951486e96b8 | 672,252 |
def rotate(wcsprm, rot):
"""Help method for offset_with_orientation. Set the different rotations in the header."""
#hdr["PC1_1"] =rot[0][0]
#hdr["PC1_2"] =rot[1][0]
#hdr["PC2_1"]=rot[0][1]
#hdr["PC2_2"] =rot[1][1]
pc = wcsprm.get_pc()
pc_rotated =rot@ pc
wcsprm.pc = pc_rotated
return... | 747b47de0b8feae94e1ca87ce61e25e76e4d1b7f | 672,253 |
import itertools
import random
def generate_comparison_pairs(condition_datas):
"""
Generate all stimulus comparison pairs for a condition and return in a random order for a paired comparison test.
Parameters
----------
condition_datas: list of dict
List of dictionary of condition data as ... | f850da7cfd9edbecf22bdabe7dff1e1a325cc1fb | 672,255 |
def alltrue(seq):
"""
Return *True* if all elements of *seq* evaluate to *True*. If
*seq* is empty, return *False*.
"""
if not len(seq):
return False
for val in seq:
if not val:
return False
return True | ecfc0a2a88d4bac16144e676e9c141624ec15c9e | 672,256 |
import locale
def _to_str(s, enc=locale.getpreferredencoding()):
"""Method to convert a bytes into a string based on a local preferred encoding
_to_str
=======
This method is used to decode a bytes stream into a string based on the location/regional
preference. It returns the converted string.... | bae340921cd263f183f19a9ec63a1cad6dbc07f8 | 672,257 |
def test(classifier, data, labels):
"""
Test a classifier.
Parameters
----------
classifier : sklearn classifier
The classifier to test.
data : numpy array
The data with which to test the
classifier.
labels : numpy array
The labels with which to test the
the classifier.
Returns
... | ab26442225b9a97fea27ad7d86cd2c4251dd4a3f | 672,258 |
def process_form_data(dict_form_data, *args):
"""
After casting form data to dict, the values
become lists. Transform the lists to non-iterables
"""
new_dict = {}
try:
for key in dict_form_data.keys():
new_dict[key] = dict_form_data[key][0]
except AttributeError:
... | 8327fc414eed40a6c014a6b271ba0ef227d98d26 | 672,260 |
import os
def is_workspace_file(sample_file_path):
"""
Return if input file is a vivisect workspace, based on file extension
:param sample_file_path:
:return: True if file extension is .viv, False otherwise
"""
if os.path.splitext(sample_file_path)[1] == ".viv":
return True
return ... | fd4cd18c9c18010e7450b90459538eb840f15cbc | 672,261 |
def reverse_complement(s):
"""Return reverse complement sequence"""
ret = ''
complement = {"A": "T", "T": "A", "C": "G", "G": "C", "N": "N", "a": "t", "t": "a", "c": "g", "g": "c", "n": "n"}
for base in s[::-1]:
ret += complement[base]
return ret | dff5b4597596be93973c143a0e3fc110d23f132f | 672,262 |
def _tuples(key, values):
"""list of key-value tuples"""
return [(key, value) for value in values] | eae11652514b0991b5a96f6955770117ae9cd6aa | 672,263 |
import random
def get_ephemeral_host():
"""
Returns a random IP in the 127.0.0.0/24. This decreases the likelihood of
races for ports by 255^3.
"""
res = '127.{}.{}.{}'.format(random.randrange(1, 255),
random.randrange(1, 255),
rando... | 82d4e1690171eb148a25ca2e5132641bd9ce602a | 672,264 |
def _flatten_nodes_betweenness_weights(weighted_nodes):
"""
Betweenness metrics weights the nodes betweenness.
Example result is :
[(('systems', 'linear'), 0.30303030303030337), (('systems', 'systems'), 0.257575757575758), ...]
The method is to flatten edge betweenness and maximum edge between... | 0d2bb2898daec27e1dcc2fa95129f3d662241f64 | 672,265 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.