content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import sys
def configOpt():
"""Init for option
"""
usage = 'Usage: %prog [-f] [other option] [-h]'
p = OptionParser(usage)
# basic options
p.add_option('-t', '--totalsj', dest='totalsj',
action='store', type='string', help='totalsj file')
p.add_option('-b', '--bed', dest='... | 04e7269da18f0e8d6aeb98ff94d73776c5ca1e00 | 43,300 |
def meta_track_name(txt):
"""
Creates a track name meta message.
Parameters
----------
txt : string
The track name for the message.
"""
return text_meta_message(kTrackName, txt) | bf969e023107b8517bd6df9cf7d9040e52b7b00d | 43,301 |
from pathlib import Path
def model_path(base_path: Path, training_run):
"""Returns the path of the model of a given training run.
Arguments:
base_path: A Path object pointing to the base directory where the training run is located.
training_run: The name of the directory of the training run.
... | cea149172aa12a2e35fb558fa867dcbfe17eda3e | 43,302 |
import tqdm
import random
import copy
def process_images():
"""
新增实现:
1. 记录每个图像样本包含的caption出现的concept词,按照dict_concept_to_index编码记录
2. 如果是origin模式,则直接将karpathy的划分方案继承下来,不做改动
3. 如果是fewshot模式,则按照我们希望的,按照BaseTrain、BaseVal、BaseTest、Support、Test的方式进行划分
4. 划分的修改结果返回到下一步处理
"""
... | c9f9bd5e768792877cc50ed0cdebe580d3108e48 | 43,303 |
import threading
def countLinkCheckThreads():
"""
Count LinkCheckThread threads.
@return: number of LinkCheckThread threads
@rtype: int
"""
i = 0
for thread in threading.enumerate():
if isinstance(thread, LinkCheckThread):
i += 1
return i | 077c9a6b00f9ba438981fa0769b4244d931c5db1 | 43,304 |
def predict_class_name_and_confidence(img, model, input_size):
"""predict image class and confidence according to trained model
Args:
img: image to predict
model: pytorch model
Returns:
class_name: class index
confidence: class confidence
"""
class_idx, confidence = ... | 58d2e8b9b4f05e259e6612c4f1342c01e91cf12f | 43,305 |
import os
def get_overview_of_data(subject_data, layout, b0_threshold):
"""
Gather data from dwi and fmaps into a dictionary
"""
data = {}
data['dwi'] = []
data['fmap'] = []
data['sbref'] = []
# dwi data
data_types = ['dwi','fmap','sbref']
for data_type in data_types:
... | c5f851301aae7ed91ba874100f0a23a6bc824884 | 43,306 |
def laplace(arr):
"""Laplace filtered signal as features.
Parameters
----------
arr : ndarray, shape (n_channels, n_times)
Returns
-------
output : (n_channels * n_times,)
"""
c4 = 4 * arr[8] - (arr[2] + arr[7] + arr[14] + arr[9])
c3 = 4 * arr[4] - (arr[0] + arr[3] + arr[10] + ... | 021f65a6e1bf58892929168f05c664b6191e8988 | 43,307 |
def plot_block_diffs(
blocks,
truths,
title=None,
active_label=1,
fig_fname=None):
"""
Show percent of datapoints in each block where truth value is equal
to active_label
:param blocks: array of block or meta-values
:type blocks: np.array with shape (num_samples,)
:param tru... | d5357e0b81e262caf20a5d4157b9fea30348fb69 | 43,308 |
def assign_road_name(x):
"""Assign road conditions as paved or unpaved to Province roads
Parameters
x - Pandas DataFrame of values
- code - Numeric code for type of asset
- level - Numeric code for level of asset
Returns
String value as paved or unpaved
"""
... | 01bf8bccca43aa833e3d9edfcbfe0213e30d9ac0 | 43,309 |
import os
def create_icon_node(node, params):
"""
Alters the params dict with the values suitable for creation of the nodes with icons and
creates additional parameters dict storing the information about the icon node
:params:
:param node: dict containing the node data
:param params: dict cont... | 860a221a5c24eca0b095df56e064e14143dfcf24 | 43,310 |
def _check_fm(fm):
"""Check Field Index map value types"""
if not isinstance(fm, dict): return False
for f in fm:
if not isinstance(f, basestring): return False
if not isinstance(fm[f], set): return False
for m in fm[f]:
if not isinstance(m, fm[f]): return False
retur... | a7f3e7cd68232c6e6e0f83bed88b3e51db187ef0 | 43,311 |
from typing import Union
from typing import Dict
from typing import List
def fixed_param_names_from_stragegy(config: model.ModelConfig,
params: Union[Dict, mx.gluon.ParameterDict],
strategy: str) -> List[str]:
"""
Generate a fixed paramet... | 415a56e6a5161634e9732596cb85f7e2d50f9c27 | 43,312 |
from typing import Any
def valid_publish_topic(value: Any) -> str:
"""Validate that we can publish using this MQTT topic."""
value = valid_topic(value)
if "+" in value or "#" in value:
raise vol.Invalid("Wildcards can not be used in topic names")
return value | f3d04117779bfdc01f78c21fdef7954752e2933b | 43,313 |
def get_ownership_filter(filter_str: str) -> Filter:
"""Get an OwnershipFilter from its id string."""
filter_dict = {
UNOWNED_FILTER: UnownedFilter(),
OWNED_FILTER: OwnedFilter(),
ALL_FILTER: None,
}
return _get_filter(filter_dict=filter_dict, filter_str=filter_str) | 6bd8544a83687e12c0aa3b22c2901f0af4be29d8 | 43,314 |
def forgot_password_request():
"""Respond to existing user's request to reset their password."""
if not current_user.is_anonymous:
return redirect(url_for('main.index'))
form = RequestResetPasswordForm()
if form.validate_on_submit():
user = User.objects(email=form.email.data).first()
... | 5b2fbbff95701aaaa5ec6a489e20456ac27e4579 | 43,315 |
from pathlib import Path
def get_cached_bc_file_path(
project: Project,
binary: ProjectBinaryWrapper,
required_bc_file_extensions: tp.Optional[tp.List[BCFileExtensions]] = None,
) -> Path:
"""
Look up the path to a BC file from the BC cache.
Args:
project: the project
binary: ... | 5b40d32bb985bdea80ce2ecd4dd8877ae45dad7b | 43,316 |
import logging
def get_data(parts_of_interest):
"""
Given a dictionary of classes with sub-dicts of required properties, returns a dictionary keyed
first by class and then by instance_id of those extracted properties.
"""
component_dict = defaultdict(dict)
## verbose log entry detailing what ... | acd672f7ff1c7a12902437dfa192b7d288011086 | 43,317 |
def buildClassifier(input_shape=(100, 100, 3)):
"""
This creates the CNN algorithm.
Args:
input_shape(tuple): This is the image shape of (100,100,3)
Returns:
classifier(sequential): This is the sequential model.
"""
# Initialising the CNN
classifier = Sequential()
classif... | bbad10918aec4d1b42c30d8dac58237287023e98 | 43,318 |
def exp_categorical_crossentropy_Im_mc(exp=1.0, class_weights=[],nclass=2,ncluster=[]):
"""
:param exp: exponent. 1.0 for no exponential effect.
"""
def inner(y_true, y_pred):
# sz=y_pred.shape
mv=tf.reduce_max(y_true)
I_weight = tf.cond(tf.greater(mv,50), lambda: tf.add(1.0,0.0... | b6ff25cec0d276700d9e09cd272f6854a0c5c93c | 43,319 |
import math
def cubic_approx_quadratic(cubic, tolerance, _2_3=2/3):
"""Approximate a cubic Bezier with a single quadratic within a given tolerance.
Args:
cubic (sequence): Four complex numbers representing control points of
the cubic Bezier curve.
tolerance (double): Permitted dev... | 28e5f23f4d9aa5179f72f7361a834db9353654ee | 43,320 |
import json
import os
def get_labeled_filelist(json_file_list_path):
"""
Get a list of raw image files and mask files.
Parameters
----------
json_file_list_path : str
Path to a json file which contains a list of dictionaries with the
keys 'raw' and 'mask'
Returns
-------
... | 0aa6aa1d9773a984cf301c6bc5b815d7fe483b8e | 43,321 |
def __substituteGamma(expr, *args, gamma=IndexedBase('\gamma', integer=True, shape=1)):
"""
Substitute gamma[i] by args[i] in expression.
:param Expr expr: expression
:param args: entries of the gamma vector
:param Expr gamma: optional symbol to use for gamma
:return: expr with gamma[i] substit... | 3398775dd0fbb39d73178ef4f866d187fd0d9678 | 43,322 |
def generate_password():
"""Funtion that generates random password for the user"""
gen_password = Credentials.generate_password()
return gen_password | f982e8dc3f825cd855921d67eb5a2c9e0d7a5a0e | 43,323 |
def hyphenation(word):
"""
Split word in syllables
:param word: input string
:return: a list containing syllables of the word
"""
if not word or word == '':
return []
# elif len(word) == 3 and (is_vowel(word[1]) and is_vowel(word[2]) and not is_toned_vowel(word[2]) and (
# no... | 1d202c285195730ba9b4b3d7fe6616fc71895808 | 43,324 |
def create_dictionary(generator):
"""
Creates dictionary
(key=CVE id, value=list of links)
<class 'generator'> -> dict
"""
cves = dict()
for item in generator:
if item.startswith('CVE'):
header = item
links = list()
else:
links.append(item... | 271c3bdb5f1062ebc8a7f4eb69afbf54af5743eb | 43,325 |
def GetBusNumberToDeviceTreeMap(fast=True):
"""Gets devices currently attached.
Args:
fast [bool]: whether to do it fast (only get description, not
the whole dictionary, from lsusb)
Returns:
map of {bus number: bus object}
where the bus object has all the devices attached to it in a tree.
"""
... | b871c3bb2503b28ea78e2dc7b8183cb3d7ceae04 | 43,326 |
def logprob_angle(xa, ya, xb, yb,ha,measured_angle, std):
"""logprob that a, b and c are in (xa,ya),(xb,yb),(xc,yc) under the measured angle.
Args:
xa: abscissa of point a
ya: ordinate of point a
xb: abscissa of point b
yb: ordinate of point b
measured_dist: measured... | a16294f05cfe837a759ef3403b6ef281c7541ba0 | 43,327 |
def get_partype(cdragon_bin, ddragon_language):
"""
Gets partype in the requested language.
This is a backup to relying on ddragon, still not pretty, could use improvement
"""
if 'arType' not in cdragon_bin['primaryAbilityResource']:
return translate.t(ddragon_language, "game_ability_resourc... | 8edbf97ca54266e22b09b4f1edaf4ca5bec230f6 | 43,328 |
def GetGap ( classes, gap_list ):
"""
Input
classes: {课号:{教师姓名:[完成课时,完成课时比例,完成业绩]}} (dict)
Output
availableT: available teacher list,在职教师名及其完成业绩(tuple)
unavailableT: unavailable teacher list,离职 & 管理岗教师名及其完成业绩(tuple)
gap:由离职 & 管理岗教师产生的业绩缺口(float)
"""
gap = 0
availableT = []
... | 4c9bba825d4763e8c98c3f01f623b331d97a5cd4 | 43,329 |
def filter_exists(name):
"""
Check whether a filter named "name" exists.
"""
hdata = weechat.hdata_get("filter")
filters = weechat.hdata_get_list(hdata, "gui_filters")
filter = weechat.hdata_search(hdata, filters, "${filter.name} == %s" % name, 1)
return bool(filter) | 826c985b6c6c2a4b56788fb0c181a7b51c585197 | 43,330 |
def normalize_image(image,
mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225)):
"""Normalize the input image.
Parameters
----------
image : numpy.ndarray
Input image.
mean : tuple, optional
Mean values for each of the three RGB channels w... | 4b64d92e53508c9018894ca556c98fb39a7599a5 | 43,331 |
def indel_equivalence_solver(df, genome, refgene, chr_prefixed):
"""Solve indel equivalence and calculates
indels_per_gene (ipg)
Args:
df (pandas.DataFrame)
genome (pysam.FastaFile): reference genome
refgene (str): path to refCodingExon.bed.gz
chr_prefixed (bool): True ... | 845f3712d98b44bc9ac31fd40ff2bf3e762df6dd | 43,332 |
def strain(transport: Transport):
"""Assume total recrystallization during transport."""
return 0 | 2f2294f64902a65d17ab9d6214949f9709b3a8fc | 43,333 |
def generateMessage(estopState, enable, right_vel, left_vel):
"""
Accepts an input of two bools for estop and enable.
Then two velocities for right and left wheels between -100 and 100
"""
# Empty list to fill with our message
messageToSend = []
# Check the directions of the motors, False =... | 3c0d2f912ee1fca4e819b0b5813de48b7f1bb338 | 43,334 |
def editItem(category_name, item_id):
"""Item edit page handler, retrieves item from database
and renders the edit item page"""
# Get item from the database
item = session.query(Product).filter_by(id=item_id).one()
if "username" not in login_session:
# If user not logged in, redirect to lo... | 0ec3b9920b5ab7994d80419641294a57c89f9c6a | 43,335 |
def atom_periodic_number_convert(coord_input):
"""
Add a new column contain periodic number of the corresponding atom
:param coord_input: coordinate dataframe of 2D or 3D data
:type: pandas.DataFrame
:return coord: same dataframe with added column of periodic number
"""
# check input type
... | 650fca5997755faee9bb673211391beb791e8416 | 43,336 |
def response_md5_is_valid(response):
"""Checks the MD5 hash of ``response.content`` against that response's
"content-md5" header. Returns ``True`` if they match, else ``False``.
If the response does not include a ``content-md5`` header, we can't verify it,
but we should not hold up that response. Thus,... | 2c38e1a50dd7d657a0a99f6e9c7a8a93f7c5aab7 | 43,337 |
def unpatch_task(task):
"""Deprecated API. The new API uses signals that can be deactivated
via unpatch() API. This API is now a no-op implementation so it doesn't
affect instrumented tasks.
"""
deprecation(
name='ddtrace.contrib.celery.patch_task',
message='Use `unpatch()` instead',... | 0d926173ab5779e2f34d5d8b76b73977a54d0e0f | 43,338 |
def cost_deriv(a, y):
"""Mean squared error derivative"""
return a - y | 15d02e49af734f9ad95e63214055f4dda58d41f4 | 43,339 |
def hsvColor(hue, sat=1.0, val=1.0, alpha=1.0):
"""Generate a QColor from HSVa values. (all arguments are float 0.0-1.0)"""
c = QtGui.QColor()
c.setHsvF(hue, sat, val, alpha)
return c | bf99bd9064d11336b78b34f38fe4559422cbf7d9 | 43,340 |
def choose_shift(count_data, min_shift=2, max_shift=12):
"""
Helper function to choose the best shift to apply to the data before applying mixture model.
This helps automatically pick a shift vs. just having a fixed
"""
best_fit = None
best_shift = None
for count_shift in range(min_shift, m... | 6a58fa9fafbdbd2d4a915c747a1d4cbdddf09827 | 43,341 |
def general_pdist(points, distance_function = haversine):
"""
Calculate the distance bewteen each pair in a set of points given a distance function.
Author: Piotr Sapiezynski
Source: https://github.com/sapiezynski/haversinevec
Input
-----
points : array-like (shape=(N, 2))
... | 319f275a078b3e69ef6be48daae1665ae5975fdc | 43,342 |
def get_conf_option(cfp,sec):
"""
读取监控配置文件(nmshosts.conf)中某部分的选项
"""
adict = {}
#print(sec)
#print('---------------')
global V3OPTIONS
for o in V3OPTIONS:
try:
adict[o] = cfp.get(sec,o)
except:
print("%s:exception!!"%o)
adict[o]= None
... | 4beaabdb544c46d45956aa3e269a44845cb6d081 | 43,343 |
import psutil
import socket
import ipaddress
def get_interface_name():
"""
Returns the interface name of the first not link_local and not loopback interface.
"""
interface_name = ''
interfaces = psutil.net_if_addrs()
for name, details in interfaces.items():
for detail in details:
... | fee777918e588ed2fc44bcee46c37bc976fbc7fc | 43,344 |
def difference(seq1, seq2):
"""
Return all items in seq1 only
"""
return [item for item in seq1 if item not in seq2] | bd012e943e06e92ea2cf42b93a1127a2ab823e61 | 43,345 |
def get_training_data():
"""
Return python dict of data and its paths
"""
train_and_validation_data = {}
image_id_and_path = {}
datasets = {"validation": VALIDATION_DATASETS, "training": TRAINING_DATASETS}
for training_data_type, training_data in datasets.items():
for imagery_datase... | a83eab1fd92cdf1d03b8a0e4b8826f273a91cca7 | 43,346 |
def update_query_string(context, **kwargs):
"""Return the current query string updated with the provided kwargs."""
parameters = dict(context["request"].GET.items())
parameters.update(kwargs)
return "?" + urlencode(parameters) | 3583a383940474b09e8b14d5fb8399e92efc101a | 43,347 |
def default_pim_interface_policies(existing, jp_bidir):
"""Generates command list that will be used default interface
policies used for PIM such as neighbor and join-prune policies
Args:
existing (dict): key/values of the existing config
jp_bidir (bool): flag to detrmine if join-prune po... | cc6745ad9b9b34f8ddaa2e882be12850232e25c4 | 43,348 |
def _get_cuda_arch_flags(cflags=None):
"""Return the CUDA arch flags."""
if cflags is not None:
for flag in cflags:
if 'arch' in flag:
return []
supported_arches = ['3.5', '3.7',
'5.0', '5.2', '5.3',
'6.0', '6.1', '6.2',
... | f7504fa193c07e794e76c7339482971fa8990297 | 43,349 |
def get_payload_for_v36_cluster_upgrade(params):
"""Construct telemetry payload of v35 cluster upgrade.
:param dict params: defined entity instance, telemetry source_description
:return: json telemetry data for the operation
:type: dict
"""
def_entity = params.get(CLUSTER_ENTITY)
native_e... | 64098a9c99b4d6ab698ac9c2f9e36d39c2d13b5f | 43,350 |
def fetch_desikan_killiany(*args, **kwargs):
"""
Fetches Desikan-Killiany atlas shipped with `abagen`
Returns
-------
atlas : dict
Dictionary with keys ['image', 'info'] pointing to atlas image
(.nii.gz) and information (.csv) files
References
----------
Desikan, R. S.,... | 9a636ca9ee03fb99bee69f30f00a4bf472ade57b | 43,351 |
def conditional_cov_full(X1, X2, X, mu_ell_X1, mu_ell_X2, mu_ell_X, mu_ss_X1, mu_ss_X2, mu_ss_X, nonstat, V):
"""
part of the conditional post cov matrix.
"""
num_func = 1 # Fixed for one latent function
num_data = tf.shape(X)[0] ... | 695828b25330440daaf673fc90f3a896b9c54907 | 43,352 |
import os
def ReplaceEntries(image_fname, input_fname, indir, entry_paths,
do_compress=True, allow_resize=True, write_map=False):
"""Replace the data from one or more entries from input files
Args:
image_fname: Image filename to process
input_fname: Single input ilename to ... | 50c513cadad16d1ad5dd015f0ca18bb44764697e | 43,353 |
def ratio(matrix, objectives, weights):
"""Execute ratio MOORA without any validation."""
# change the sign the minimization criteria
# If we multiply by -1 (min) the weights,
# when we multipliying this weights by the matrix we emulate
# the -+ ratio mora strategy
objective_x_weights = weights ... | 102ec9321f7f165449b08154da335b6a20e03427 | 43,354 |
from sys import path
def get_ssh_config(hostname):
"""Get SSH config for given hostname
:param: hostname: hostname
:return: dict
"""
ssh_config_file = path.abspath(path.expanduser('~/.ssh/config'))
if path.exists(ssh_config_file):
ssh_config = SSHConfig()
with open(ssh_confi... | 4d53b8f57dc2afa2a0a2a3a553de440465916734 | 43,355 |
import click
def choose_profile(config_files):
"""Show brief info on each Okta environment found in loaded configuration profiles"""
click.echo("[*] Choose a configuration profile to load. E.g. 1")
while True:
choice = click.prompt("[*] Enter the number of the configuration profile to load", typ... | be29a6636823ee880912d4e51621a76612a95351 | 43,356 |
def add_new_attending(username_id, email, phone):
"""Creates a dictionary for a new attending physician
Every time the user wants to add a new attending physician
to the attending physician database, this function
must be called. This function reads in from the user the
physician’s user name, their... | d8015642c91d4217b83eb3309e47c51ee62889c2 | 43,357 |
def getCaptureArea():
# Fix not aborting issue here.
"""
Get area to work with.
"""
p1 = Pos()
p2 = Pos()
kill_key = "f2"
def getPos(p):
nonlocal kill_key
while (not keyboard.is_pressed(kill_key)) and (not ABORT_SIGNALED):
# fix loop here
QSlee... | e57d89d2939db7baa46b58390f102ed5760b9c3b | 43,358 |
from typing import Callable
def _validate_input(dataset: np.ndarray, explain_instance: Callable,
sample_size: int, explanations_number: int) -> bool:
"""
Validates input for submodular pick.
For the input parameters description, warnings and exceptions please see
the documentation... | b72e305b8f077077e5cc48154470e7b3e6a5420f | 43,359 |
def wcmp(a,b):
""" A strict ordering whisker segments in a frame """
return cmp( a.y[0], b.y[0] ) | 036ab24f24464a98f0c171b719f05e9a5581ad35 | 43,360 |
from typing import List
from typing import Dict
def render_cit_ref(tpl: str, parts: List[str], data: Dict[str, str]) -> str:
"""
>>> render_cit_ref("cit_réf", ["Dictionnaire quelconque", "2007"], defaultdict(str))
'<i>Dictionnaire quelconque</i>, 2007'
>>> render_cit_ref("cit_réf", [], defaultdict(str... | 289d7fce334078009fc34b0e30092f56f814f52c | 43,361 |
import scipy
def bandpass(samples, sample_rate):
"""Applies a 20-30khz bandpass FIR filter"""
# 25-40KHz is the range of the pinger for the roboboat competition
fir = scipy.signal.firwin(
128, [19e3 / (sample_rate / 2), 41e3 / (sample_rate / 2)],
window='hann',
pass_zero=False)
... | 6e23fe91b52b2795f33fb45ee4ba006ef7f0ac49 | 43,362 |
def list_blobs_with_prefix(bucket_name, prefix, delimiter=None):
"""Lists all the blobs in the bucket that begin with the prefix.
This can be used to list all blobs in a "folder", e.g. "public/".
The delimiter argument can be used to restrict the results to only the
"files" in the given "folder". With... | adf7825e118fb6aaf0e8c59c579b4fd57fe48b56 | 43,363 |
import time
def utc_to_local_tt(y, m, d, hrs_utc):
"""Converts from a UTC time to a local time.
y,m,d: The year, month, day for which the conversion is desired.
hrs_tc: Floating point number with the number of hours since midnight in UTC.
Returns: A timetuple with the local time.
... | 314457a106a135f00bac1e9b302a788336d39f27 | 43,364 |
def test_requests_bs4(monkeypatch):
"""test the requests and bs4 Lua interfaces"""
def get(url):
return {
'https://test.invalid/plain.txt':
Dummy(headers={'Content-Type': 'text/plain'},
text='<span>This</span> is <b>plain</b> text'),
'http://... | ed711eb8a0975fc276c7cdc37a0bb737b0089a3c | 43,365 |
def feature_max_q(q1, q2, q3, q4):
"""
Computes the max values of each signal for each quarter-window, plus the
paired differences of max values of each signal for the quarter-windows,
i.e., feature_max(q1), feature_max(q2), feature_max(q3), feature_max(q4),
(feature_max(q1) - feature_max(q2)), (feature_max(q1) ... | 56274913c8af25036bd49fb6dabbb9396e328405 | 43,366 |
import math
def get_heading(tank1,tank2):
"""returns heading of the tank in degrees, assuming tank1, tank2 are dict"""
x1,y1 = tank1["x"], tank2["y"]
x2,y2 = tank2["x"], tank2["y"]
heading = float(math.atan2((y2-y1)/(x2-x1))) #returns heading in radians
heading = float(math.degrees(heading))
... | 4b4be25a2693b6c81a9992d67a72df8c0c16a659 | 43,367 |
from typing import List
import os
def _scan_checkpoint_directory(checkpoint_dir: str) -> List[Checkpoint]:
"""
Construct checkpoint metadata directly from a directory.
State files are sometimes out of sync with directory contents. Insert
additional orphaned checkpoint files and prune missing files. T... | d087042b5dd1a7e8a8d74301cd455dfc814b4453 | 43,368 |
from typing import Callable
import asyncio
def async_wrap(func: Callable):
"""Wrap a synchronous running function to make it run asynchronous."""
async def run(*args, loop=None, executor=None, **kwargs) -> Callable:
"""Run sync function async."""
if loop is None:
loop = asyncio.ge... | 92ff9c0b796f88f9a4033fb84b0b95b7c2fd26cc | 43,369 |
def is_gs_line(line):
"""Returns True if line is a GS line"""
return line.startswith('#=GS') | cceec8ce733cef9e9a31cc5c55687c1c2f28983f | 43,370 |
import re
def replace_lookups(pre: str, partition: str, active: str) -> JNDIParts:
"""Replace Log4J lookups.
See https://logging.apache.org/log4j/2.x/manual/lookups.html and
https://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution
"""
jndi_parts = JNDIParts(
ori... | e93cfd794d4c4259a68abe49d055a4b9b715bbe8 | 43,371 |
import os
def init_weights(args, model) -> object:
"""
Initializes the neural network weights from known networks such as COCO, imagenet or from the last training.
Parameters
----------
:param args:
(object) Inputs the parameters passed to the command-line script as input --> weights
... | 9d518f367ce23aa696b7c8f36f09a5707264036b | 43,372 |
def bar(n):
"""Test helper for foo."""
return foo(n-1) | 1f34951f55250dd0db52f381cb7c94f7ab16f951 | 43,373 |
from eventkit_cloud.utils.image_snapshot import get_wmts_snapshot_image, fit_to_area
import os
def create_datapack_preview(result=None, task_uid=None, stage_dir=None, *args, **kwargs):
"""
Attempts to add a MapImageSnapshot (Preview Image) to a provider task.
"""
result = result or {}
try:
... | 84af599d7daf666682c368144133971cbdc7c620 | 43,374 |
from pathlib import Path
def read_cd_files(prefix: Path, fname: str) -> dict:
"""
result[name] = path-to-the-file
name: e.g., 08-1413.jpg
pato-to-the-file: e.g., /cifs/toor/work/2011/cyclid data/./CD9/2008-06-19/08-1413.jpg
"""
result = {}
with open(fname) as f:
for line in f:
... | c8b16b01819d00be0efb2f12cc25eeb7730facf9 | 43,375 |
def _items(mappingorseq):
"""Wrapper for efficient iteration over mappings represented by dicts
or sequences::
>>> for k, v in _items((i, i*i) for i in xrange(5)):
... assert k*k == v
>>> for k, v in _items(dict((i, i*i) for i in xrange(5))):
... assert k*k == v
"""
... | dbd9949e6cf567bb5d8df1e15db19a7c4977168d | 43,376 |
def invert(K, neig=0, tol=1e-10):
"""Inverts a positive-definite matrix A using either an eigendecomposition or
a Cholesky decomposition, depending on the rapidness of decay of eigenvalues"""
if (neig <= 0 or neig > 0.05*K.shape[0]):
try:
return invert_cholesky(np.linalg.cholesky(K))
... | 9a490bd9015b8347f92f0f8e0f84aa5f5211d6b2 | 43,377 |
from typing import Union
def apply_capping(
df: pd.DataFrame,
metric: str,
sd_threshold: int = 5,
method: Union[str, CappingMethod] = CappingMethod.STANDARD,
metric_raw: str = None,
) -> pd.Series:
"""Calculates metrics capped at threshold of given SDs from mean (upper bound capping only). Int... | 715369dec8c51a7e908fc38242c145b419b7951a | 43,378 |
def list_user_emails():
""" List user names and emails
Returns:
A JsonResponse that contains a list of user information (ID, name, and email)
"""
sess = GlobalDB.db().session
users = sess.query(User)
if not g.user.website_admin:
relevant_cgacs = [aff.cgac_id for aff in g... | 35770abd522277bf65a5cc183bbc38de46714259 | 43,379 |
def create_subnetList(topo, num):
"""
Create the subnet list of the certain Pod.
"""
subnetList = []
remainder = num % (topo.pod/2)
if topo.pod == 4:
if remainder == 0:
subnetList = [num-1, num]
elif remainder == 1:
subnetList = [num, num+1]
el... | 50590d893ccb5e640c258427b9f756b60fd25c90 | 43,380 |
def phimat(phi):
"""
Build a Busing & Levy PHI matrix. Input is in radians
"""
result = np.zeros((3, 3,), dtype='float64')
result[0][0] = cos(phi)
result[0][1] = sin(phi)
result[1][0] = -sin(phi)
result[1][1] = cos(phi)
result[2][2] = 1.
return result | ddfd74aa5385464b94acecf5f90ae314d1487e9f | 43,381 |
def _get_cube_list_for_table(cell_data, row_labels, col_labels, col_units):
"""Create :class:`iris.cube.CubeList` representing a table."""
aux_coord = iris.coords.AuxCoord(row_labels, long_name='dataset')
cubes = iris.cube.CubeList()
for (idx, label) in enumerate(col_labels):
if label in ('ECS',... | 6a744d0d8188abbd904d04dee083fc6c7ffbe3aa | 43,382 |
def _generate_spaxel_list(spectrum):
"""
Generates a list wuth tuples, each one addressing the (x,y)
coordinates of a spaxel in a 3-D spectrum cube.
Parameters
----------
spectrum : :class:`specutils.spectrum.Spectrum1D`
The spectrum that stores the cube in its 'flux' attribute.
Re... | 9d4b5339f18022607f349c326dc83e319a690a26 | 43,383 |
from .basic import calc_info_rand as calc_info
from .basic import calc_info_neighborhood_avg as calc_info
from .basic import calc_info_neighborhood_voting as calc_info
from .basic import calc_info_gaussian_laplacian as calc_info
from .basic import calc_info_mean_laplacian as calc_info
from .basic import calc_info_local... | aa99cb7d8b2207384191343f864ac4db2e2ec2aa | 43,384 |
import argparse
import sys
def setup():
"""Process command-line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-l",
"--length",
default=64,
type=int,
help="# of random characters for password (default 64)",
)
parser... | dfecb184f2b174671fa7e15e6a44a21e07f14bef | 43,385 |
import logging
import argparse
import sys
import os
def get_args():
"""
Read arguments from the command line and check they are valid.
"""
logger = logging.getLogger("stats.args")
parser = argparse.ArgumentParser(
description="Extract alignment statistics from a SAM/BAM file")
parser... | c6747dea5b9579243ef538ab1fc5fb07e0ab7e70 | 43,386 |
import re
def get_frame_rate_list(fmt):
"""Get the list of supported frame rates for a video format.
This function works arround an issue with older versions of GI that does not
support the GstValueList type"""
try:
rates = fmt.get_value("framerate")
except TypeError:
# Workaround ... | d3db15553a9bd28dc7be0754c7c8202e20aab8d2 | 43,387 |
import torch
def cosine_loss(X, mu_tilde, pi_tilde, alpha):
"""
Computes the Cosine loss.
Arguments:
X: array-like, shape=(batch_size, n_features)
Input batch matrix.
mu_tilde: array-like, shape=(batch_size, n_features)
Matrix in which each row represents the assign... | af31a24c66690105b926099c5a5ac8da47243b5b | 43,388 |
import torch
def construct_loader(x, y, batch_size, shuffle=True):
"""Construct a data loader for the provided data.
Args:
x (list): A list of molecule features.
y (list): A list of the corresponding labels.
batch_size (int): The batch size.
shuffle (bool): If True the data wi... | f8fa64b95d14fe2a85d68e88ea075c09907a8e41 | 43,389 |
def cpp_texlist(listoflines):
"""function that parses a .tex file from https://github.com/cplusplus/draft.git
and extracts all section headings as well as all impldef statements into a flat list
The return value contains tuples,
tuple[0] ... line number (starting from 1) that matched the item
tuple... | bdef835f1086ce8eaa36bf32f319ee0d1fc804a8 | 43,390 |
def show_index():
"""Display / route."""
context = {}
return flask.render_template("index.html", **context) | 5bed243cf0be3822a1701882e5f9fedee6b128fc | 43,391 |
import html
def create_header():
"""page header"""
header = html.Header(
html.Nav(
[
html.Div(
[html.Div([app.title], className="navbar-brand navbar-left")],
className="container",
)
],
classNam... | cebb3958435eb04c9dcfb9e997bf049194301c7c | 43,392 |
def update_regex_extractor(regex_extractor_id: int):
"""更新"""
data: dict = request.get_json()
regex_extractor = RegexExtractor.query.filter(
RegexExtractor.regex_extractor_id == regex_extractor_id
).first()
if not regex_extractor:
return dbu.inner_error("该不存在或已被删除")
dbu.update... | 215ee431e30b269012848e86b9d06886cb8baa24 | 43,393 |
def count(_id):
"""Update a group """
if request.method == 'GET':
try:
group = get_group(_id)
if not group:
return jsonify({'code': 400, 'msg': 'can not found group by id [{0}]'.format(_id)})
else:
result = count_group(_id)
... | b01fc38fa4369043a63dc338578eb2e0797540c2 | 43,394 |
def create_network_from_yml(directory_name):
"""
Creates a Network object form a yaml file.
"""
params_input = load_parameters(directory_name)
params = fill_out_dictionary(params_input)
for clss in params['arrival_distributions']:
dists = []
for dist in params['arrival_distributi... | 4a3390a45d6ba589a8985fd38550c2fb395f2fbd | 43,395 |
def gmail_filters():
"""Returns GMail labels object exposing labels API.
Args: None
Returns:
GMail labels object.
"""
return __gmail_v1__().settings().filters() | 3e33348ad438118884fd9fc0e3c2a8e8d57f6790 | 43,396 |
def transition_matrix(embeddings, **kwargs):
"""
Calls similarity matrix. Builds a probabilistic transition matrix
from word embeddings.
"""
#ipdb.set_trace()
## Get Similarity matrix
L = similarity_matrix(embeddings, **kwargs)
Dinv = np.diag([1. / np.sqrt(L[i].sum()) if L[i].sum() ... | aaf56084c56d610e78d974794d1d0dab21c38348 | 43,397 |
from typing import List
def domain_nameservers_should_be_exactly(value: List[str] = None,
ns: List[str] = None) -> bool:
"""
Check the given nameservers are exactly the domain's nameservers.
"""
return set(value) == set(ns) | a0021c1c7820d51196c1045e976b6c1281bb148e | 43,398 |
def get_user_pagination(page=1, per_page=10, *args, **kwargs):
"""
获取列表(分页)
Usage:
items: 信息列表
has_next: 如果本页之后还有超过一个分页,则返回True
has_prev: 如果本页之前还有超过一个分页,则返回True
next_num: 返回下一页的页码
prev_num: 返回上一页的页码
iter_pages(): 页码列表
iter_pages(left_edge=2, left_curre... | 0c566284ac2fb1450562baea4c0c695691e32795 | 43,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.