content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def svn_diff_fns2_invoke_token_discard(*args):
"""svn_diff_fns2_invoke_token_discard(svn_diff_fns2_t _obj, void diff_baton, void token)"""
return _diff.svn_diff_fns2_invoke_token_discard(*args) | cdfd25973cf87190a6f82b07c82e741233c65fcd | 3,647,700 |
import torch
def process_bb(model, I, bounding_boxes, image_size=(412, 412)):
"""
:param model: A binary model to create the bounding boxes
:param I: PIL image
:param bounding_boxes: Bounding boxes containing regions of interest
:param image_size: Choose the size of the patches
:return: Patche... | 2029fa67fb85ce3e15913ce9c1684cbe762ea3b7 | 3,647,701 |
def roc(
observations,
forecasts,
bin_edges="continuous",
dim=None,
drop_intermediate=False,
return_results="area",
):
"""Computes the relative operating characteristic for a range of thresholds.
Parameters
----------
observations : xarray.Dataset or xarray.DataArray
Lab... | 328e00060c758ddf3c12cecdec1961561bb2d3f3 | 3,647,702 |
from typing import Literal
def make_grammar():
"""Creates the grammar to be used by a spec matcher."""
# This is apparently how pyparsing recommends to be used,
# as http://pyparsing.wikispaces.com/share/view/644825 states that
# it is not thread-safe to use a parser across threads.
unary_ops = (... | aef2a3fc897c42e61ebd81c9d43cb42f342b1fb6 | 3,647,703 |
def _pull(keys):
"""helper method for implementing `client.pull` via `client.apply`"""
if isinstance(keys, (list,tuple, set)):
return [eval(key, globals()) for key in keys]
else:
return eval(keys, globals()) | 779fcec45c3693bdd8316c14138a88c57f0c318c | 3,647,704 |
def position(df):
"""
根据交易信号, 计算每天的仓位
:param df:
:return:
"""
# 由 signal 计算出实际每天持有的股票仓位
df['pos'] = df['signal'].shift(1)
df['pos'].fillna(method='ffill', inplace=True)
# 将涨跌停时不得买卖股票考虑进来
# 找出开盘涨停的日期
cond_cannot_buy = df['开盘价'] > df['收盘价'].shift(1) * 1.097 # 今天的开盘价相对于昨天的收盘价上... | 15666e26cf8a9d6ae98ff1746aecab759de9139b | 3,647,705 |
def prepare_data(data, preprocessed_data, args):
"""Prepare Data"""
data = data.to_numpy()
train_size = int(len(data) * args.train_split)
test_size = len(data) - train_size
train_X = preprocessed_data[0:train_size]
train_Y = data[0:train_size]
test_X = preprocessed_data[train_size:len(pre... | b5e120eebd6060656d71f8f76755afd0d8eccce5 | 3,647,706 |
def svn_client_conflict_tree_get_victim_node_kind(conflict):
"""svn_client_conflict_tree_get_victim_node_kind(svn_client_conflict_t * conflict) -> svn_node_kind_t"""
return _client.svn_client_conflict_tree_get_victim_node_kind(conflict) | 6258c011eb947ddedb1e060cd036ddcf9cbc1758 | 3,647,707 |
import importlib
def load_module(script_path: str, module_name: str):
"""
return a module
spec.loader.exec_module(foo)
foo.A()
"""
spec = importlib.util.spec_from_file_location(module_name, script_path)
module = importlib.util.module_from_spec(spec)
return spec, module | 61ebc105d0c7a168b37210452445e8e24e16f87a | 3,647,708 |
import os
def readfile(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read() | fde9a2866b189cea40ecc3e48695d8b3e98f6228 | 3,647,709 |
def memory_func(func):
"""
декоратор для замера памяти занимаемой функцией в оперативной памяти.
"""
def wrapper(*args, **kwargs):
proc = Process(getpid()) # получение идентификатора текущего процесса и объявление класса
start_memory = proc.memory_info().rss # сохранение начального зна... | a8c634b3415925b65fe35df584328705eb0d171e | 3,647,710 |
def read_data(datafile='sampling_data_2015.txt'):
"""Imports data from an ordered txt file and creates a list of samples."""
sample_list = []
with open(datafile, 'r') as file:
for line in file:
method, date, block, site, orders = line.split('|')
new_sample = sample(method, da... | 4aee4b2ef0cd9d31eefbd9f394714f0ea789b49d | 3,647,711 |
async def get_https(method: str = "all"):
"""Get https proxies from get_proxies_func() function."""
return await get_proxies_func("https", method) | 575eccf2149724c29062d866fcc420fe3b34be78 | 3,647,712 |
import logging
import tqdm
def iam_analysis(obs_spec, model1_pars, model2_pars, rvs=None, gammas=None,
verbose=False, norm=False, save_only=True, chip=None,
prefix=None, errors=None, area_scale=False, wav_scale=True, norm_method="scalar", fudge=None):
"""Run two component model o... | 28a5291fe5dd62c2a3a988d994cc98a81beeaac8 | 3,647,713 |
import os
def _parse_archive_name(pathname):
"""Return the name of the project given the pathname of a project
archive file.
"""
return os.path.basename(pathname).split('.')[0] | 90e6bcf019ac48b73c16f4db605e1d92c3d32595 | 3,647,714 |
import imaplib
def is_authenticated(user, password):
"""Check if ``user``/``password`` couple is valid."""
global IMAP_WARNED_UNENCRYPTED
if not user or not password:
return False
log.LOGGER.debug(
"Connecting to IMAP server %s:%s." % (IMAP_SERVER, IMAP_SERVER_PORT,))
connection... | af7518aec858b2c1e1c6e4e71120f95af5787ce6 | 3,647,715 |
def apply_mask(input, mask):
"""Filter out an area of an image using a binary mask.
Args:
input: A three channel numpy.ndarray.
mask: A black and white numpy.ndarray.
Returns:
A three channel numpy.ndarray.
"""
return cv2.bitwise_and(input, input, mask=mask) | 34451c71b9f18a64f5b27e3ff9269a9c4e3b803d | 3,647,716 |
import sys
import time
def runUrllib2(urls, num):
"""Running benchmark for urllib2.
Args:
urls: List of URLs.
num: Number of requests.
"""
results = []
for i in range(num):
sys.stderr.write('.')
start = time.time()
for url in urls:
urlopen(url)
... | ecd883c44d68eb88b711dd9cbf22bc58fa93cd7b | 3,647,717 |
import requests
import json
def fetch_track_lyrics(artist, title):
""" Returns lyrics when found, None when not found """
MUSIXMATCH_KEY = get_musixmatch_key()
api_query = 'https://api.musixmatch.com/ws/1.1/matcher.lyrics.get?'
api_query += 'q_track=%s&' % title
api_query += 'q_artist=%s&' % arti... | f8e049578bb8c6b52636fd1e1789a81af30b28e6 | 3,647,718 |
def string_avg(strings, binary=True):
"""
Takes a list of strings of equal length and returns a string containing
the most common value from each index in the string.
Optional argument: binary - a boolean indicating whether or not to treat
strings as binary numbers (fill in leading zeros if lengths... | 3d515cbeedc93b95c5f38de62000629002e41166 | 3,647,719 |
def refresh():
"""Pull fresh data from Open AQ and replace existing data."""
DB.drop_all()
DB.create_all()
api = openaq.OpenAQ()
status, body = api.measurements(city='Los Angeles', parameter='pm25')
reading_list = []
for reading in body['results']:
object = Record(datetime = reading[... | 9fcf71ffe0e5a46119e98f17c12aae29721285c8 | 3,647,720 |
import json
def update_organization(current_user):
""" Обновление информации об организации. """
try:
if CmsUsers.can(current_user.id, "put", "contacts"):
organization = CmsOrganization.query.first()
update_data = request.get_json()
for key in list(update_data.k... | ff7826b1b4537eb0b793b426a6b6aa097936bfa9 | 3,647,721 |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_sep]
sep_base_path=/sepm/api/v1
sep_auth_path=/sepm/api/v1/identity/authenticate
sep_host=<SEPM server dns name or ip address>
sep_port=... | fcad9aa412d66b4a48dfb753d64e0f84979df617 | 3,647,722 |
def read_eieio_command_message(data, offset):
""" Reads the content of an EIEIO command message and returns an object\
identifying the command which was contained in the packet, including\
any parameter, if required by the command
:param data: data received from the network
:type data: byte... | 05abce201acf3b706e4b476c15eb2af5a0102cc8 | 3,647,723 |
def quote():
"""Get stock quote."""
if request.method == "POST":
# Get values
get_symbol = request.form.get("symbol")
stock = lookup(get_symbol)
# Ensure symbol was submitted
if not get_symbol:
return apology("must provide symbol")
# Ensure symbol ... | b26c04c01e5ddb26c19e555a45e3fac6f58c0fef | 3,647,724 |
def counts_to_df(value_counts, colnames, n_points):
"""DO NOT USE IT!
"""
pdf = pd.DataFrame(value_counts
.to_frame('count')
.reset_index()
.apply(lambda row: dict({'count': row['count']},
**d... | 85d5283f2d53dcf3ec33d7a1f3f52d9acc0affde | 3,647,725 |
import math
def make_pair_plot(samples, param_names=None,
pair_plot_params=PairPlotParams()):
"""
Make a pair plot for the parameters from posterior destribution.
Parameters
-----------
samples : Panda's DataFrame
Each column contains samples from posterior distributi... | 73f5d8fc7dee8b3179cb8c1513eb2989c788e7cf | 3,647,726 |
def read_meta_soe(metafile):
"""read soe metadata.csv to get filename to meta mapping"""
wavfiles = csv2dict(metafile)
return {f['fid']:{k:v for (k,v) in f.items() if k!='fid'} for f in wavfiles} | 51f82a45d12b332d9edbe7b027dc7ee2582af35b | 3,647,727 |
def send_message(message, string, dm=False, user=None, format_content=True):
"""send_message
Sends a message with string supplied by [lang]_STRING.txt files.
:param message: MessageWrapper object with data for formatting.
:param string: Name of the string to read.
:param dm: Whether the message shou... | c8396108126fcaea735a94be3dcd4ed954f43d70 | 3,647,728 |
def calc_torque(beam, fforb, index=False):
""" Calculates torque from a neutral beam (or beam component)
torque = F * r_tan = (P/v) * r_tan = (P/sqrt(2E/m)) * r_tan = P * sqrt(m/(2E)) * r_tan
:param fforb:
:param index:
:param beam: beam object with attributes z, m, a, en, pwr, rtan
:return: t... | 55cb8172f874a1d25c6dcf36c693f818d11d59c4 | 3,647,729 |
def cli(ctx, user_id):
"""Create a new API key for a given user.
Output:
the API key for the user
"""
return ctx.gi.users.create_user_apikey(user_id) | d7dafd77ef983286184b6f5aa2362bb734389696 | 3,647,730 |
import re
def whitespace_tokenizer(text):
"""Tokenize on whitespace, keeping whitespace.
Args:
text: The text to tokenize.
Returns:
list: A list of pseudo-word tokens.
"""
return re.findall(r"\S+\s*", text) | e79234b15912fdc225e2571788844732296f93d7 | 3,647,731 |
def _u2i(number):
"""
Converts a 32 bit unsigned number to signed. If the number
is negative it indicates an error. On error a pigpio
exception will be raised if exceptions is True.
"""
v = u2i(number)
if v < 0:
if exceptions:
raise error(error_text(v))
return v | 920a2dcbf68df34141c482c2318917ccff248501 | 3,647,732 |
def apply_once(func, arr, axes, keepdims=True):
"""
Similar to `numpy.apply_over_axes`, except this performs the operation over
a flattened version of all the axes, meaning that the function will only be
called once. This only makes a difference for non-linear functions.
Parameters
----------
... | 939eea81d4443a4ef144105b1cc9335000b20f49 | 3,647,733 |
from io import BytesIO
def bytes_to_bytesio(bytestream):
"""Convert a bytestring to a BytesIO ready to be decoded."""
fp = BytesIO()
fp.write(bytestream)
fp.seek(0)
return fp | d59e4f5ccc581898da20bf5d3f6e70f8e8712aa6 | 3,647,734 |
from typing import List
def image_scatter_channels(im: Image, subimages=None) -> List[Image]:
"""Scatter an image into a list of subimages using the channels
:param im: Image
:param subimages: Number of channels
:return: list of subimages
"""
image_list = list()
if subimages is None:... | f87cb88ef060a6d093dacabdaab0ebc94861b734 | 3,647,735 |
def unauthorized_handler():
"""
If unauthorized requests are arrived then redirect sign-in URL.
:return: Redirect sign-in in page
"""
current_app.logger.info("Unauthorized user need to sign-in")
return redirect(url_for('userView.signin')) | 72b505ae13023aea23e0353b6571da64d9f647b8 | 3,647,736 |
import posixpath
def pre_order_next(path, children):
"""Returns the next dir for pre-order traversal."""
assert path.startswith('/'), path
# First subdir is next
for subdir in children(path):
return posixpath.join(path, subdir)
while path != '/':
# Next sibling is next
name = posixpath.basenam... | fcbe2b17b29396ac978f4a931a454c988e6fe05b | 3,647,737 |
def gettiming(process_list, typetiming):
"""
Used to get a sort set for different duration needed to conver to
morse code.
"""
timing = []
for x in process_list:
if(x[0] == typetiming):
timing.append(x[3])
timing = set(timing)
return sorted(timing) | 8e71449eacaee086f9f9147e1c3b8602ce8e553f | 3,647,738 |
import click
def init():
"""Top level command handler."""
@click.command()
@click.option('--approot', type=click.Path(exists=True),
envvar='TREADMILL_APPROOT', required=True)
@click.argument('eventfile', type=click.Path(exists=True))
def configure(approot, eventfile):
""... | 2c24fe8dc2225b7f2f848ac3d2ef09275829c754 | 3,647,739 |
import subprocess
def launch_subprocess(command):
"""
Process launch helper
:param command Command to execute
:type command list[str]|str
:return Popen object
"""
is_shell = not isinstance(command, (list, tuple))
return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=i... | f5ab217ffdec69147bc79061b0ba029225c7b8a0 | 3,647,740 |
def tobooks(f: '(toks, int) -> DataFrame', bks=bktksall) -> DataFrame:
"""Apply a function `f` to all the tokens in each book,
putting the results into a DataFrame column, and adding
a column to indicate each book.
"""
return pd.concat([f(v, i) for i, v in bks.items()]) | e081e1c01d68b7b84cb6395f32f217360657636f | 3,647,741 |
def _identity_error_message(msg_type, message, status_code, request):
"""
Set the response code on the request, and return a JSON blob representing
a Identity error body, in the format Identity returns error messages.
:param str msg_type: What type of error this is - something like
"badRequest"... | d73e182fc794f01c3415069ffeb37e76a01df7af | 3,647,742 |
def _string_to_list(s, dtype='str'):
""" converts string to list
Args:
s: input
dtype: specifies the type of elements in the list
can be one of `str` or `int`
"""
if ' <SENT/> ' in s:
return s.split(' <SENT/> ')
elif dtype == 'int':
return [int(e) for e in s.split(L... | 9d2950afcd9f47e1fef7856af117953dbf99410a | 3,647,743 |
import warnings
def internal_solve_pounders(
criterion,
x0,
lower_bounds,
upper_bounds,
gtol_abs,
gtol_rel,
gtol_scaled,
maxinterp,
maxiter,
delta,
delta_min,
delta_max,
gamma0,
gamma1,
theta1,
theta2,
eta0,
eta1,
c1,
c2,
solver_sub,
... | c3f602af6f78a1cb57c15a6488e4aeadcd081951 | 3,647,744 |
import torch
def get_overlap_info(bbox):
"""
input:
box_priors: [batch_size, number_obj, 4]
output: [number_object, 6]
number of overlapped obj (self not included)
sum of all intersection area (self not included)
sum of IoU (Intersection over Union)
average of all i... | 451507a49fca589bc1102b085eab551ebe32bcc7 | 3,647,745 |
def get_current_language(request, set_default=True, default_id=1):
"""
Description:
Returns the current active language. Will set a default language if none is found.
Args:
request (HttpRequest): HttpRequest from Django
set_default (Boolean): Indicates if a default language must be a... | 98bc2a25201dc87afcee24d8ff5d10fcab7849bb | 3,647,746 |
def is_leap_year(year):
"""
returns True for leap year and False otherwise
:param int year: calendar year
:return bool:
"""
# return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
return year % 100 != 0 or year % 400 == 0 if year % 4 == 0 else False | 5bd0bb7a44dc7004b9198cb3d8ed244dc02417c2 | 3,647,747 |
def update_search_params(context, **kwargs):
"""Update the set parameters of the current request"""
params = context["request"].GET.copy()
for k, v in kwargs.items():
params[k] = v
return params.urlencode() | e3ce5a5a1dadc90bb544a761e154214d7a538f30 | 3,647,748 |
def dynamic2message(dynamic_dict: dict) -> Message:
"""
将从api获取到的原始动态转换为消息
"""
author_name = dynamic_dict['desc']['user_profile']['info']['uname']
dynamic_id = dynamic_dict['desc']['dynamic_id']
if dynamic_dict['desc']['type'] == 1: # 转发或投票
text = f"用户[{author_name}]转发了动态:\n" + dynamic_... | b5330876cb58bf71c73ef9f4d3cbcdd0e583aba6 | 3,647,749 |
def dem_to_roughness(src_raster, band=0):
"""Calculate the roughness for the DEM.
Parameters
----------
src_raster : Raster
The dem used to calculate the roughness.
band : int, optional, default: 0
source band number to use.
Returns
-------
dst_raster: Raster
ro... | f8ba073560aaf18ab9101befc5a3d1727a7cb93e | 3,647,750 |
import importlib
import sys
def import_file(path, name=None):
"""Import modules from file."""
spec = importlib.util.spec_from_file_location(name or '', path)
module = importlib.util.module_from_spec(spec)
if name:
sys.modules[name] = module
spec.loader.exec_module(module)
return module | 3a2fc184c3bca4e48d0c725b9370e2a9e8bcadf3 | 3,647,751 |
from typing import Any
from typing import List
def batch_matmul_checker(
attrs: Any, args: List[relay.expr.Expr], op_name: str
) -> bool: # pylint: disable=unused-variable
"""Check if dense is supported by TensorRT."""
if get_tensorrt_use_implicit_batch_mode() and len(args[0].checked_type.shape) != len(
... | 6c83ce1116a88e864bd577ee2dd7d669d43c43a3 | 3,647,752 |
def func_run_dynamic(input_file, dynamic_dic, exclude, pprint):
"""
Execute one dynamic template
:param input_file: (string) The template file name
:param dynamic_dic: (dict) The dictionary of the dynamic variables
:return:
"""
new_template_filename = create_dynamic_template(input_file, dyn... | 9432eadb4e3735a06f35aedd8fd9bb175ab2ba55 | 3,647,753 |
import os
def find(store_config, shardid): # FIXME require config instead
"""Find the path of a shard.
Args:
store_config: Dict of storage paths to optional attributes.
limit: The dir size limit in bytes, 0 for no limit.
use_folder_tree: Files organized in... | eddfc0f15deb833337f6312cb96b460b66ca16d7 | 3,647,754 |
import ctypes
def xclGetDeviceInfo2 (handle, info):
"""
xclGetDeviceInfo2() - Obtain various bits of information from the device
:param handle: (xclDeviceHandle) device handle
:param info: (xclDeviceInfo pointer) Information record
:return: 0 on success or appropriate error number
"""
li... | 794b6208c19a4f982a9fffb9270a3485299b62eb | 3,647,755 |
def template_failure(request, status=403, **kwargs):
""" Renders a SAML-specific template with general authentication error description. """
return render(request, 'djangosaml2/login_error.html', status=status) | fbcc8ad756213b4ba7f44d799c67b67beaad18f8 | 3,647,756 |
def zflatten2xyz(z, x=None, y=None):
""" flatten an nxm 2D array to [x, y, z] of shape=(n*m, 3)"""
if x is None:
x = np.arrange(0, z.shape[0], step=1)
if y is None:
y = np.arrange(0, z.shape[1], step=1)
xlen = len(x)
ylen = len(y)
assert z.shape[0] == xlen and z.shape[1] == ylen,... | 96fcc9755660a85f5501958cf3f7d8c7a0e35b69 | 3,647,757 |
def penalized_log_likelihood(curve,t,pairwise_contact_matrix,a,b,term_weights,square_root_speed=None,pairwise_distance_matrix=None):
"""
penalized log likelihood
"""
if pairwise_distance_matrix is None: #if the do not already have the pairwise distance matrix computed, then compute it
pairwise_d... | f26b5148b5f56be958d99714e5207417fd40a15d | 3,647,758 |
import os
def listening_ports():
""" Reads listening ports from /proc/net/tcp """
ports = []
if not os.path.exists(PROC_TCP):
return ports
with open(PROC_TCP) as fh:
for line in fh:
if '00000000:0000' not in line:
continue
parts = line.lstrip('... | 1d92f9acf0330882048594b7a12976286f12ecc4 | 3,647,759 |
def dict2array(X):
"""
Returns a Numpy array from dictionary
Parameters
----------
X: dict
"""
all_var = []
for k in X.keys():
all_var.append(X[k])
return np.array(all_var) | e3d1ecabe9897af7c60a8e4be1e92603619d130a | 3,647,760 |
import subprocess
def preprocess_field_data(subdelimiter, field_value, path_to_script):
"""Executes a field preprocessor script and returns its output and exit status code. The script
is passed the field subdelimiter as defined in the config YAML and the field's value, and
prints a modified vesion o... | 9cf0261c98652d0811868c91fbb3ab15e6c07af3 | 3,647,761 |
import requests
def dfs_level_details():
"""This function traverses all levels in a DFS style. It gets the child directories and
recursively calls the same function on child directories to extract its level details
Returns:
Dictionary: Key is the level name, value is a list with first element as ... | 31cf9fdf49620798e9411dda1eda99b95411858b | 3,647,762 |
import copy
def makeNonParameterized(p):
"""Return a new Pointset stripped of its parameterization.
"""
if isinstance(p, Pointset) and p._isparameterized:
return Pointset({'coordarray': copy(p.coordarray),
'coordnames': copy(p.coordnames),
'norm': ... | 778eed55d3da10dcfb4681484cb31d6469009ae8 | 3,647,763 |
def interface_getattr(*v):
"""Behaves like `getattr` but for zope Interface objects which
hide the attributes.
.. note:: Originally I simply tried to
override :meth:`InterfaceDocumenter.special_attrgetter` to deal with the
special access needs of :class:`Interface` objects, but found that thi... | f981d9cdea352f206b087455f1d8b33846a4d5df | 3,647,764 |
def round_time(t, to=timedelta(seconds=1)):
""" cftime will introduces noise when decoding values into date objects.
This rounds time in the date object to the nearest second, assuming the init time
is at most 1 sec away from a round minute. This is used when merging datasets so
their time dims match up... | dcc7d0caa4e4787f710a386968d8967661e662ca | 3,647,765 |
def decide_end(match_list, return_whole_match_object = False):
"""
Among all the match objects, return the march string the closest to the end of the text
Return : a string. If return_whole_match_object is True, return a match object
"""
if len(match_list) == 0:
return pd.NA
ends = ... | 72e9a4f63c9c7b95e5728b798bc1cd508d1911e6 | 3,647,766 |
def get_level_refactorings_count(level: int, dataset: str = "") -> str:
"""
Get the count of all refactorings for the given level
Parameter:
level (int): get the refactoring instances for this level
dataset (str) (optional): filter for these specific projects
"""
retu... | 8150537a35161541d7eb4b483d06ef8096611d37 | 3,647,767 |
def repeat_batch(t, K, dim=0):
"""Repeat a tensor while keeping the concept of a batch.
:param t: `torch.Tensor`: The tensor to repeat.
:param K: `int`: The number of times to repeat the tensor.
:param dim: `int`: The dimension to repeat in. This should be the
batch dimension.
:returns: `t... | 31ae6e02bd23c56049a4f8e5ea9f36e5b6186678 | 3,647,768 |
def ifte(s, g_cond, g_true, g_false):
"""goal that succeeds if g_cond and g_true succeed or g_cond fails and g_false succeeds"""
def loop(s_inf=g_cond(s)):
try:
first_cond = next(s_inf)
except StopIteration:
yield from g_false(s)
return
except Suspend... | 899ed78b53e056804e9515e2f01125831ae0dfba | 3,647,769 |
def filter_by_continue_threshold_variance_threshold(peak_info, acc, cont_win_size=3, cont_thres=4, var_thres=0.001):
"""
Calculate the continuity by a given window length, then calculate the variance and filter the data by
a given threshold
:param peak_info: a 5D matrix
:param cont_win_size: continu... | 7cdbe81b8c0931d315a9d928b6a32105e6da56fb | 3,647,770 |
from datetime import datetime
def send_update(*args: str) -> bool:
""" Updates the path endpoint to contain the current UTC timestamp """
assert args, "Firebase path cannot be empty"
endpoint = args[-1]
value = {endpoint: datetime.utcnow().isoformat()}
return send_message(value, *args[:-1]) | b9b9b7a277bc2a0ffd9ae0c4d658eb5f3d017d20 | 3,647,771 |
def execute_custom(datatype, runtype, driver, data_repository, step_list):
"""
Execute a custom testcase
"""
print_info("{0} {1}".format(datatype, runtype))
tc_status = False
if data_repository.has_key("suite_exectype") and \
data_repository["suite_exectype"].upper() == "ITERATIVE":
... | 884ab4ff7f66f1ad969b03ec406513b301739169 | 3,647,772 |
def parseSolFile(filename):
"""Parses SOL file and extract soil profiles."""
data = {}
profile = None
lat = None
lon = None
with open(filename) as fin:
for line in fin:
if line.startswith("*"):
if profile is not None:
data[(lat, lon)] = "{0... | 7c3876f1e4899eff5b0036045df4348903a11306 | 3,647,773 |
import collections
def get_deps_info(projects, configs):
"""Calculates dependency information (forward and backwards) given configs."""
deps = {p: configs[p].get('deps', {}) for p in projects}
# Figure out the backwards version of the deps graph. This allows us to figure
# out which projects we need to test ... | 10215dfb623b8ebaaabdb2d1bcffd876d37f9f66 | 3,647,774 |
def write_cflags():
"""Adds C-Flags. C++ version is defined at the beginning of this file"""
text = f"""CFLAGS = ${{TF_CFLAGS}} ${{OMP_CFLAGS}} -fPIC -O2 -std={CPPVERSION}
LDFLAGS = -shared ${{TF_LFLAGS}}
"""
text += write_cflags_cuda()
return text | 1348c70b5bdbe168760dba677f9bcc4507957510 | 3,647,775 |
def ins_to_sem_compatibility(sem_labels_for_instances, num_sem_labels, stuff_sem_cls_ids, stuff_penalisation=1.0):
"""
Returns the compatibility matrix for the instance_labels -> semantic_labels bipartite potentials in BCRF.
Args:
sem_labels_for_instances: Semantic labels of the instances. 0th in... | 3c96d3746a7e419848f9b2ddef4c636cf8a822d1 | 3,647,776 |
def get_coverage(inputs):
"""Get edge coverage.
Returns:
A dictionary of inputs and corresponding coverage
"""
cov_dict = dict()
for test_input in inputs:
"Get coverage by running the program"
cov = coverage(input)
"Update coverage dictionary of test input"
cov_dict[test_input] = cov
ret... | 5a80399b7877d968654e8c6fc069ff0f70d10a62 | 3,647,777 |
import os
import zipfile
import shutil
def compress_as(filename, fmt, target=None, keep=True):
"""Compress an existing file.
Supported compression formats are: gzip, bzip2, zip, and lzma (Python
3.3 or newer only).
Args:
filename: The path and name of the uncompressed file.
fmt: Deci... | 4f4c4862e314945ff7360d48cdb3cc10448b14e9 | 3,647,778 |
from operator import add
def average(arr, mode = "mixed"):
"""
average(arr, mode) takes the average of a given array
Once again, the modes of add() can be used here to denote what the type of the array is
The function below, determine_mode(arr) can be used to determine the correct mode for your array
... | 74d0b836e6877d1f7d23b69a191e653bcffd6f00 | 3,647,779 |
def non_halting(p):
"""Return a non-halting part of parser `p` or `None`."""
return left_recursive(p) or non_halting_many(p) | d9d8b87cad15c5416041c40396bd3e51b0c28051 | 3,647,780 |
def _isValidWord(word):
"""Determine whether a word is valid. A valid word is a valid english
non-stop word."""
if word in _englishStopWords:
return False
elif word in _englishWords:
return True
elif wordnet.synsets(word):
return True
else:
return False | aa0dd1ceecc807b3aa6ecf740d5ec547bf748e7c | 3,647,781 |
def compare_floats(value1: float, value2: float):
"""Função que compara 2 floats"""
return True if abs(value1 - value2) <= 10**-6 else False | 225a8fd4d472fe630efe32c506cb1ac3f7ff4b5f | 3,647,782 |
from typing import Tuple
import os
def carrega_dataset(caminho_diretorio: str, divisao: Tuple[int, int], embaralhar=True) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Especifique o caminho do diretório em que os arquivos `noisy.npy`e `original.npy` estão.
Args:
caminho_diretorio (str... | 30eb94954f012eb444f7cbcad24a5c943bafd4f4 | 3,647,783 |
from cuml.utils.import_utils import has_treelite, has_xgboost
import treelite
import treelite.runtime
import xgboost as xgb
def _build_treelite_classifier(m, data, arg={}):
"""Setup function for treelite classification benchmarking"""
if has_treelite():
else:
raise ImportError("No treelite package... | 095d9748988d55d2b578c0cb74fc4a662aa660c3 | 3,647,784 |
def _pkq(pk):
"""
Returns a query based on pk.
Note that these are designed to integrate with cells and how they are saved in the database
:Parameters:
----------------
pk : list
list of primary keys
:Returns:
-------
dict
mongo query filtering fo... | d17527132c26c7e3504471f8456baccea295c71e | 3,647,785 |
import torch
def inspect_decode_labels(pred, num_images=1, num_classes=NUM_CLASSES,
inspect_split=[0.9, 0.8, 0.7, 0.5, 0.0], inspect_ratio=[1.0, 0.8, 0.6, 0.3]):
"""Decode batch of segmentation masks accroding to the prediction probability.
Args:
pred: result of inference.
num_images... | d8ee386e2088428b7bfe5579cc5558cf4d6890f1 | 3,647,786 |
from typing import Dict
from typing import Union
def set_default_values(
**attributes: Dict[str, Union[float, int, str]],
) -> Dict[str, Union[float, int, str]]:
"""Set the default value of various parameters.
:param attributes: the attribute dict for the electronic filter being calculated.
:return: ... | 3c8871706446b2bd0aec1879b06e443a57898a96 | 3,647,787 |
import inspect
def validate_function(fn: FunctionType, config: Configuration, module_type: ModuleType) -> FunctionValidationResult:
"""Validates the docstring of a function against its signature.
Args:
fn (FunctionType): The function to validate.
config (Configuration): The configuration to u... | cc9c858f8ade844b89d944dc149c0233ed5741e7 | 3,647,788 |
import registry
import os
def find_existing_installation(package_name: str, display_name: str, test=True):
"""
Finds an existing installation of a package in the windows registry given the package name and display name
#### Arguments
package_name (str): Name of the package
display_name (st... | 70f6b8536693be2541c0365a743231eea95cc542 | 3,647,789 |
def say(l, b, i):
"""
!d Repeat a word or phrase
!a <message...>
!r moderator
"""
try:
print 'Saying the phrase:', ' '.join(i.args)
b.l_say(' '.join(i.args), i, 1)
return True
except TypeError:
return False | 260867612cd468babd42654c6d823649cbc73d41 | 3,647,790 |
import re
def rSanderSelect(dbItem,index=0,interactive=False):
"""
rSanderSelect(dbItem,index=0,interactive=False)
select which rSander henry data to use in dbItem
Parameters:
dbItem, db[key] dictionary object with keys = ['hbpSIP','hbpSIPL',
'hbpSI_index']
... | 54e6a79a2095810e10032c2da59972e89ca186eb | 3,647,791 |
def dataset_w_pedigree_field():
"""
:return: Return model Dataset example with `pedigree_field` defined.
"""
search_pattern = SearchPattern(left="*/*/*_R1.fastq.gz", right="*/*/*_R2.fastq.gz")
dataset = DataSet(
sheet_file="sheet.tsv",
sheet_type="germline_variants",
search_p... | 2fce0d1391e234a7bb4f2a0bcab5ba24fc27abe0 | 3,647,792 |
import requests
def get_new_access_token(client_id, client_secret, refresh_token):
"""Use long-lived refresh token to get short-lived access token."""
response = requests.post(
'https://www.googleapis.com/oauth2/v4/token',
data={
'client_id': client_id,
'client_secret'... | a8f79511f8f0078121cf291752c2b315023df6de | 3,647,793 |
def prettify_seconds(seconds):
"""
Prettifies seconds.
Takes number of seconds (int) as input and returns a prettified string.
Example:
>>> prettify_seconds(342543)
'3 days, 23 hours, 9 minutes and 3 seconds'
"""
if seconds < 0:
raise ValueError("negative input not allowed")
... | 4b77f9ed3d2085895ef15c6be30b7bfe83d1f49d | 3,647,794 |
import re
def get_regions_prodigal(fn):
"""Parse prodigal output"""
regions = {}
with open(fn, 'r') as f:
for line in f:
if line[:12] == '# Model Data':
continue
if line[:15] == '# Sequence Data':
m = re.search('seqhdr="(\S+)"', line)
... | d69f7b6d9dfc6802ad4dab3472f90a2d68b95bdd | 3,647,795 |
from typing import Optional
def get_transform(account_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
transform_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTransformResult:
"""
Use this dat... | 533ff2c95303c25b0a9741c36b34a755e18948e5 | 3,647,796 |
def default_preprocessing(df):
"""Perform the same preprocessing as the original analysis:
https://github.com/propublica/compas-analysis/blob/master/Compas%20Analysis.ipynb
"""
return df[(df.days_b_screening_arrest <= 30)
& (df.days_b_screening_arrest >= -30)
& (df.is_recid != -1... | e6f4d8ceaa09fe71657e7936db886c3eabfb7aa0 | 3,647,797 |
def get_step_type_udfs(
step_type: str,
workflow: str,
adapter: ArnoldAdapter = Depends(get_arnold_adapter),
):
"""Get available artifact udfs for a step type"""
artifact_udfs = find_step_type_artifact_udfs(
adapter=adapter, step_type=step_type, workflow=workflow
)
process_udfs = fi... | f3ad3ad96d3f33e343afbb2ffcfa176fd4c6e654 | 3,647,798 |
def decode_base58(s: str) -> bytes:
"""
Decode base58.
:param s: base58 encoded string
:return: decoded data
"""
num = 0
for c in s:
if c not in BASE58_ALPHABET:
raise ValueError(
"character {} is not valid base58 character".format(c)
)
... | ee56c73e4fd22f25cd0caf63651abc13a4ba147d | 3,647,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.