content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def model_handle_check(model_type):
"""
Checks for the model_type and model_handle on the api function,
model_type is a argument to this decorator, it steals model_handle and checks if it is
present in the MODEL_REGISTER
the api must have model_handle in it
Args:
model_type: the "type"... | 1c2bab3399dff743fd1ca1a37971a4e71f5d5b8f | 15,000 |
def train_model_mixed_data(type_tweet, split_index, custom_tweet_data = pd.Series([]), stop_words = "english"):
"""
Fits the data on a Bayes model. Modified train_model() with custom splitting of data.
:param type_tweet:
:param split_index:
:param custom_tweet_data: if provided, this is used instea... | 4c7d4e29562b63ea53f1832af0841fb112c6596a | 15,001 |
import scipy
def _fit_curves(ns, ts):
"""Fit different functional forms of curves to the times.
Parameters:
ns: the value of n for each invocation
ts: the measured run time, as a (len(ns), reps) shape array
Returns:
scores: normalised scores for each function
coef... | 9a480869d930e27d9aa988455228e6197f87417a | 15,002 |
def isolate_integers(string):
"""Isolate positive integers from a string, returns as a list of integers."""
return [int(s) for s in string.split() if s.isdigit()] | cc95f7a37e3ae258ffaa54ec59f4630c600e84e1 | 15,003 |
def extractAFlappyTeddyBird(item):
"""
# A Flappy Teddy Bird
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'The Black Knight who was stronger than even the Hero' in item['title']:
return buildReleaseMess... | ca382caa9d1d9244424a39d1bc43c141b003691d | 15,004 |
def get_trainable_vars(name):
"""
returns the trainable variables
:param name: (str) the scope
:return: ([TensorFlow Variable])
"""
return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=name) | c45b075c739e8c86d6f1dadc0b1f4eacfb1d1505 | 15,005 |
def getLambdaFasta():
"""
Returns the filename of the FASTA of the lambda phage reference.
"""
return _getAbsPath('lambdaNEB.fa') | 4cb351d874087da71d8f726802a5bb86438dacd1 | 15,006 |
from heartandsole import Activity
import warnings
def register_field(name):
"""Register a custom accessor on Activity objects.
Based on :func:`pandas.api.extensions.register_dataframe_accessor`.
Args:
name (str): Name under which the accessor should be registered. A warning
is issued if this name ... | 115893cbca27c9822f08746f45a5ae0dcf48aadf | 15,007 |
def Rotation_ECL_EQD(time):
"""Calculates a rotation matrix from ecliptic J2000 (ECL) to equatorial of-date (EQD).
This is one of the family of functions that returns a rotation matrix
for converting from one orientation to another.
Source: ECL = ecliptic system, using equator at J2000 epoch.
Targe... | d140e2c03e62fba2168faf9c3599afa6e41bb774 | 15,008 |
def _make_players_away(team_size):
"""Construct away team of `team_size` players."""
away_players = []
for i in range(team_size):
away_players.append(
Player(Team.AWAY, _make_walker("away%d" % i, i, _RGBA_RED)))
return away_players | b0beff6f06fc52f870c143c01c14d18eb77d0cc5 | 15,009 |
import json
def store_barbican_secret_for_coriolis(
barbican, secret_info, name='Coriolis Secret'):
""" Stores secret connection info in Barbican for Coriolis.
:param barbican: barbican_client.Client instance
:param secret_info: secret info to store
:return: the HREF (URL) of the newly-create... | 218bf941203dd12bc78fc7a87d6a2f9f21761d57 | 15,010 |
def wfr2_grad_single(image, sigma, kx, ky, kw, kstep, grad=None):
"""Optimized, single precision version of wfr2_grad.
Single precision might be faster on some hardware.
In addition to returning the
used k-vector and lock-in signal, return the gradient of the lock-in
signal as well, for each pixel ... | e93a0bde20a151018a07dd138d09691711946458 | 15,011 |
import random
def padding():
"""Return 16-200 random bytes"""
return URANDOM(random.randrange(16, PAD_MAX)) | 65a52c19c3b39344bd1959c58f2cd7950b0a19e4 | 15,012 |
import sys
def listener(phrase_limit: int, timeout: int = None, sound: bool = True) -> str:
"""Function to activate listener, this function will be called by most upcoming functions to listen to user input.
Args:
phrase_limit: Time in seconds for the listener to actively listen to a sound.
ti... | 87cadd28bc4c924c0db775063d16e6775f4d2381 | 15,013 |
def find():
"""Prints user message and returns the number of HP-49 connected.
"""
hps = com.find()
if len( hps ) == 0:
print "No HP49-compatible devices connected."
sys.stdout.flush()
else:
print "Number of HP49-compatible devices: %d" % len( hps )
sys.stdout.flush()
retu... | 8530fc9d6d904e8c4fe061c237af57f9874a2ea2 | 15,014 |
def get_children_templates(pvc_enabled=False):
"""
Define a list of all resources that should be created.
"""
children_templates = {
"service": "service.yaml",
"ingress": "ingress.yaml",
"statefulset": "statefulset.yaml",
"configmap": "configmap.yaml",
"secret": "... | 25db24b03542b1365529bbf1814e2fb801337022 | 15,015 |
def sort_as_int(environment, value, reverse=False, attribute=None):
"""Sort collection after converting the attribute value to an int"""
def convert_to_int(x):
val = str(x)
# Test if this is a string representation of a float.
# This is what the copy rig does and it's annoying
if... | 13e7727d1337bbfddec1a0661552c51d7015e58b | 15,016 |
def get_pretty_table_for_item(item, output_fields):
"""
"""
x = PrettyTable(["Attribute", "Value"])
attrs = _filter_attributes(item.get_attributes(), output_fields)
for attr in attrs:
row = []
row.append(attr)
row.append(getattr(item, attr))
x.add_row(row)
return... | 48d7b4c1a53884dc65de8da1167762cbf0143d2c | 15,017 |
def create_t1_based_unwarp(name='unwarp'):
"""
Unwarp an fMRI time series based on non-linear registration to T1.
NOTE: AS IT STANDS THIS METHOD DID NOT PRODUCE ACCEPTABLE RESULTS
IF BRAIN COVERAGE IS NOT COMPLETE ON THE EPI IMAGE.
ALSO: NEED TO ADD AUTOMATIC READING OF EPI RESOLUTION TO... | cbf3180e2899ac6314cde3c30ca3619ca4d3e125 | 15,018 |
def get_qnode(caching, diff_method="finite-diff", interface="autograd"):
"""Creates a simple QNode"""
dev = qml.device("default.qubit.autograd", wires=3)
@qnode(dev, caching=caching, diff_method=diff_method, interface=interface)
def qfunc(x, y):
qml.RX(x, wires=0)
qml.RX(y, wires=1)
... | 3a8cb0f47e8846338338d21896e59cba475e8351 | 15,019 |
def segment_relative_timestamps(segment_start, segment_end, timestamps):
""" Converts timestamps for a global recording to timestamps in a segment given the segment boundaries
Args:
segment_start (float): segment start time in seconds
segment_end (float): segment end time in seconds
tim... | 743938adfb8ee1450c2140f76dbbdfb88c2a3c7f | 15,020 |
def compare_dataframes_mtmc(gts, ts):
"""Compute ID-based evaluation metrics for MTMCT
Return:
df (pandas.DataFrame): Results of the evaluations in a df with only the 'idf1', 'idp', and 'idr' columns.
"""
gtds = []
tsds = []
gtcams = gts['CameraId'].drop_duplicates().tolist()
tscams ... | 002333c2be971a453727f43c257b46a99b0451cb | 15,021 |
import os
import subprocess
import time
def launch_corba(
exec_file=None,
run_location=None,
jobname=None,
nproc=None,
verbose=False,
additional_switches="",
start_timeout=60,
):
"""Start MAPDL in AAS mode
Notes
-----
The CORBA interface is likely to fail on computers with... | d877aa81aab9722a188dbe61c284564e2da3b835 | 15,022 |
def fetch_xml(url):
"""
Fetch a URL and parse it as XML using ElementTree
"""
resp=urllib2.urlopen(url)
tree=ET.parse(resp)
return tree | d0f4f5b7fe19692675cba1254f6bfa63f07e45a5 | 15,023 |
def update_hirsch_index(depth_node_dict, minimum_hirsch_value, maximum_hirsch_value):
"""
Calculates the Hirsch index for a radial tree.
Note that we have a slightly different definition of the Hirsch index to the one found in:
Gómez, V., Kaltenbrunner, A., & López, V. (2008, April).
Statistical an... | 2fdf5ca6aa216eacb3f18cd2f91875d02e0740ea | 15,024 |
import numpy
import sys
def read_trajectory(filename, matrix=True):
"""
Read a trajectory from a text file.
Input:
filename -- file to be read
matrix -- convert poses to 4x4 matrices
Output:
dictionary of stamped 3D poses
"""
file = open(filename)
data = file.read()
... | abbcaf44b51adcd7468b8e03d59170adeceff143 | 15,025 |
import json
from typing import List
import asyncio
async def async_start(hass: HomeAssistantType, config_entry=None) -> bool:
"""Start Ampio discovery."""
topics = {}
@callback
async def version_info_received(msg):
"""Process the version info message."""
_LOGGER.debug("Version %s", ms... | 1a55c944a9f3099638b5e245283a86f476b9e29b | 15,026 |
def get_E_E_fan_H_d_t(P_fan_rtd_H, V_hs_vent_d_t, V_hs_supply_d_t, V_hs_dsgn_H, q_hs_H_d_t):
"""(37)
Args:
P_fan_rtd_H: 定格暖房能力運転時の送風機の消費電力(W)
V_hs_vent_d_t: 日付dの時刻tにおける熱源機の風量のうちの全般換気分(m3/h)
V_hs_supply_d_t: param V_hs_dsgn_H:暖房時の設計風量(m3/h)
q_hs_H_d_t: 日付dの時刻tにおける1時間当たりの熱源機の平均暖房能力(-)
... | 0e2ceb9f8fbedd95d44f1c307cfb0d9ea17ea370 | 15,027 |
def load_func(func_string):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if func_string is None:
return None
elif isinstance(func_string, str):
return import_from_string(func_string)
return func_string | 99fdf6889936c95d7680ed5a70a2095474e02a9b | 15,028 |
def normalize(features):
"""
Scale data in provided series into [0,1] range.
:param features:
:return:
"""
return (features - features.min()) / (features.max() - features.min()) | a85d77e37e71c732471d7dcd42ae1aef2181f6dc | 15,029 |
def get_gitlab_template_version(response):
"""Return version number of gitlab template."""
return glom(response, 'ref', default=False).replace('refs/tags/', '') | 95e1be93ef6f14d24757e07d0ba644ce89bc0dc9 | 15,030 |
def getConfigXmlString(version, name, protocol, user, host, port, path):
"""! Arguments -> XML String. """
tag_root = ET.Element(TAG_ROOT)
tag_root.set(ATTR_VERSION, version)
tag_remote = ET.Element(TAG_REMOTE)
tag_remote.set(ATTR_NAME, name)
tag_root.append(tag_remote)
appendElement(tag_r... | da0546a2e276c16820e09807930c981bf7d5406c | 15,031 |
from typing import Optional
def phase_angle(A: Entity,
B: Entity,
C: Entity) -> Optional[float]:
"""The orbital phase angle, between A-B-C, of the angle at B.
i.e. the angle between the ref-hab vector and the ref-targ vector."""
# Code from Newton Excel Bach blog, 2014, "th... | ddbbc75909977350f89748c0afdb242ed9d741b6 | 15,032 |
def point2geojsongeometry(x, y, z=None):
"""
helper function to generate GeoJSON geometry of point
:param x: x coordinate
:param y: y coordinate
:param z: y coordinate (default=None)
:returns: `dict` of GeoJSON geometry
"""
if z is None or int(z) == 0:
LOGGER.debug('Point has n... | d825055f7cf9d5c71decce342d384eb8018546d9 | 15,033 |
def upper(string): # pragma: no cover
"""Lower."""
new_string = []
for c in string:
o = ord(c)
new_string.append(chr(o - 32) if LC_A <= o <= LC_Z else c)
return ''.join(new_string) | c13b1cc49a608bcc65a3afa87ca94f73f0deeb0b | 15,034 |
def getid(obj):
"""Return id if argument is a Resource.
Abstracts the common pattern of allowing both an object or an object's ID
(UUID) as a parameter when dealing with relationships.
"""
try:
if obj.uuid:
return obj.uuid
except AttributeError: # nosec(cjschaef): 'obj' doe... | 43160e6dd61ddc2e8e0559925bf2a35def79eb3f | 15,035 |
from datetime import datetime
import time
def dateToUsecs(datestring):
"""Convert Date String to Unix Epoc Microseconds"""
dt = datetime.strptime(datestring, "%Y-%m-%d %H:%M:%S")
return int(time.mktime(dt.timetuple())) * 1000000 | cba081ae63523c86572463249b4324f2183fcaaa | 15,036 |
def _compute_applied_axial(R_od, t_wall, m_stack, section_mass):
"""Compute axial stress for spar from z-axis loading
INPUTS:
----------
params : dictionary of input parameters
section_mass : float (scalar/vector), mass of each spar section as axial loading increases with spar depth
OUT... | 35c9a92b22b3639b6d1236ba45dd797388e25b07 | 15,037 |
import os
def glob(loader, node):
"""Construct glob expressions."""
value = loader.construct_scalar(node)[len('~+/'):]
return os.path.join(
os.path.dirname(loader.name),
value
) | e8976fdac21f8decb85bb05a23bacc929d1d56eb | 15,038 |
def categorical(p, rng=None, size=()):
"""Draws i with probability p[i]"""
if len(p) == 1 and isinstance(p[0], np.ndarray):
p = p[0]
p = np.asarray(p)
if size == ():
size = (1,)
elif isinstance(size, (int, np.number)):
size = (size,)
else:
size = tuple(size)
... | 1cee8c996206284f36f3bf72f8c6729037489f4d | 15,039 |
import argparse
def parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(description='DSNT human pose model info')
parser.add_argument(
'--model', type=str, metavar='PATH', required=True,
help='model state file')
parser.add_argument(
'--gpu', type... | 1365cf3b60004baa8fa6f07ae755d79f6d952e95 | 15,040 |
import os
def get_model(theme, corpus_all, dictionary_all, num_topics=15, passes=25, iterations=400,
eval_every=None, update_every=0, alpha='auto', eta='auto'):
"""
Get the LDA model
"""
# Check if a model with the same config already exists.
# If it does, load the model inst... | d2ab8c32ffc1cef8e620c0288866c0ee5cc4f297 | 15,041 |
from typing import List
def covariance_distance(covariances: List[Covariance],
x: np.ndarray) -> np.ndarray:
"""Euclidean distance of all pairs gp_models.
:param covariances:
:param x:
:return:
"""
# For each pair of kernel matrices, compute Euclidean distance
n_ke... | 7bfe0337c89b8476285797d1fdec394ffcd04479 | 15,042 |
def create_inputs(im, im_info, model_arch='YOLO'):
"""generate input for different model type
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
model_arch (str): model type
Returns:
inputs (dict): input of model
"""
inputs = {}
inputs['image'... | 940563f6c48cfe54e328339b0efcd44e03ad67d8 | 15,043 |
def multiplex(n, q, **kwargs):
""" Convert one queue into several equivalent Queues
>>> q1, q2, q3 = multiplex(3, in_q)
"""
out_queues = [Queue(**kwargs) for i in range(n)]
def f():
while True:
x = q.get()
for out_q in out_queues:
out_q.put(x)
t =... | ee9dac3506acb5159580a39d64e3cb046c44b204 | 15,044 |
import xml.etree.ElementTree as ET
def select_project(FILENAME):
"""
lee el fichero xml FILENAME, muestra los proyectos para que el usuario
escoja uno de ellos
input
FILENAME: fichero xml de estructura adecuada situada donde se encuentran
los scripts del programa
return:
... | 0ef7ddd4b320e2ca577c253522f512e2802569e1 | 15,045 |
def compute_average(arr):
"""Compute average value for given matrix
Args:
arr (numpy array): a numpy array
Return:
float: average value
"""
val_avg = np.average(arr)
return val_avg | c69d17f53e946f693242cfd9d90877847e7c7cc6 | 15,046 |
def _read_config(rundate, pipeline, *args, **kwargs):
"""Read the configuration of a Where analysis from file
Todo: Add this as a classmethod on Configuration
Args:
rundate: Rundate of analysis.
pipeline: Pipeline used for analysis.
session: Session in analysis.
Returns:
... | d122887d260044ebf10eb8830b247dbdf2a18274 | 15,047 |
from typing import Callable
def ta_series(func: Callable, *args, **kwargs) -> QFSeries:
"""
Function created to allow using TA-Lib functions with QFSeries.
Parameters
----------
func
talib function: for example talib.MA
args
time series arguments to the function. They are all ... | c3e4e644fd3e6ce7853cbe99441fe6c8a5ca2679 | 15,048 |
def find_trendline(
df_data: pd.DataFrame, y_key: str, high_low: str = "high"
) -> pd.DataFrame:
"""Attempts to find a trend line based on y_key column from a given stock ticker data frame.
Parameters
----------
df_data : DataFrame
The stock ticker data frame with at least date_id, y_key co... | dbe995fab1436a1c212780eebf123dc39f27f234 | 15,049 |
def find_core(read, core, core_position_sum, core_position_count, start = -1):
"""
Find the core sequence, trying "average" position first for efficiency.
"""
if start < 0 and core_position_count > 0:
core_position = round(core_position_sum/core_position_count)
if len(read) > core_po... | 3a0de472194db00fac4e65a2b0e15cfa351eb70f | 15,050 |
from functools import reduce
def clambda(n):
"""
clambda(n)
Returns Carmichael's lambda function for positive integer n.
Relies on factoring n
"""
smallvalues=[1,1,2,2,4,2,6,2,6,4,10,2,12,6,4,4,16,6,18,4,6,10,22,2,20,12,18,\
6,28,4,30,8,10,16,12,6,36,18,12,4,40,6,42,10,12,22,46,4,42,20,16,... | 0da59a30e6d7376731a868ae81aed8e1cb42e8ce | 15,051 |
def dashboard():
"""
Render the dashboard template on the /dashboard route
"""
return render_template('page/home/dashboard.html', title="Dashboard") | 12e1750a6c0b90aa8fcda29b78a463805abd45f3 | 15,052 |
import json
def get_port_status(cluster, lswitch_id, port_id):
"""Retrieve the operational status of the port"""
try:
r = do_single_request("GET",
"/ws.v1/lswitch/%s/lport/%s/status" %
(lswitch_id, port_id), cluster=cluster)
r = json.... | f5c6fdf7d23fef17f402525cbfe9c3892012e3f0 | 15,053 |
import scipy
import tqdm
import logging
def make_nearest_neighbors_graph(data, k, n=1000):
"""Build exact k-nearest neighbors graph from numpy data.
Args:
data: Data to compute nearest neighbors of, each column is one point
k: number of nearest neighbors to compute
n (optional): number of neighbors t... | dd99b42c306ac963232aeca4e86ef7e0449126ca | 15,054 |
import multiprocessing
def read_examples(input_files, batch_size, shuffle, num_epochs=None):
"""Creates readers and queues for reading example protos."""
files = []
for e in input_files:
for path in e.split(','):
files.extend(file_io.get_matching_files(path))
thread_count = multiprocessing.cpu_count... | 5265e14d02b53d7b7c8754f980573b8d8c9667ea | 15,055 |
def gen_context(n=10):
"""
method returns a random matrix which can be used to produce private prices over a bunch of items
"""
return np.random.randint(-3,4,size=(n,n)) | 51b3cf2a64530147eddacf628c8b593b7e923402 | 15,056 |
def _parallel_binning_fit(split_feat, _self, X, y,
weights, support_sample_weight,
bins, loss):
"""Private function to find the best column splittings within a job."""
n_sample, n_feat = X.shape
feval = CRITERIA[_self.criterion]
split_t = None
spl... | 5889993b9ad1ca49ac9e8ce541262ff716dea18f | 15,057 |
import subprocess
def _get_latest_template_version_w_git_ssh(template):
"""
Tries to obtain the latest template version using an SSH key
"""
cmd = 'git ls-remote {} | grep HEAD | cut -f1'.format(template)
ret = temple.utils.shell(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr = re... | 125bd2250144a96d2e4deeec72bb09ffd23b1317 | 15,058 |
def checkkeywords(keywordsarr, mdtype):
""" Check the keywords
Datasets: for Check 9
Services: for Check 9
Logic: there must be at least one keyword to get a score = 2. If keywords contain comma's (","), then a maimum of score = 1 is possible.
"""
score = 0
# keywordsarr is an array of objec... | cb165689ce820c1ead3622ed562260ee76558205 | 15,059 |
def compute_presence_ratios(
sorting,
duration_in_frames,
sampling_frequency=None,
unit_ids=None,
**kwargs
):
"""
Computes and returns the presence ratios for the sorted dataset.
Parameters
----------
sorting: SortingExtractor
The sorting result to be... | f270ff52c2d60296db25887bcbb7d203bfc23c07 | 15,060 |
def img_box_match(bboxes_gt, bboxes_pre, iou_threshold):
"""
Goal:
Returns info for mAP calculation (Precision recall curve)
Precision = TP / (TP + FP)
Recall = TP / (TP + FN)
Returns:
list of [TP/FP, conf]
num_gt_bboxes : int
Notes:
For each prediction ... | 09a7c9e9739f491777f1b0f48f745858281a0953 | 15,061 |
def random_char():
"""Return a random character."""
return Char(choice(_possible_chars)) | aca30fc1e6b7039cd5187264b89bca4d2899d169 | 15,062 |
def bond(self, atom:Atom, nBonds:int=1, main=False) -> Atom:
"""Like :meth:`__call__`, but returns the atom passed in instead, so you
can form the main loop quickly."""
self(atom, nBonds, main); return atom | e8d065f55110c37b4db06ca394c741d98ffbd446 | 15,063 |
def train_list():
"""
Return a sorted list of all train patients
"""
patients = listdir_no_hidden(INPUT_PATH)
patients.sort()
l = []
for patient in patients:
if labels[patient] != None:
l.append(patient)
return l | 7977e8ea72e826e18b4138391e812c15f3cfb6c0 | 15,064 |
def split_data(X, Y):
"""
This function split the features and the target into training and test set
Params:
X- (df containing predictors)
y- (series conatining Target)
Returns:
X_train, y_train, X_test, y_test
"""
X_train, X_test, Y_train, Y_test = train_test_split(
... | c8dbc5a6e63f0b24abf3547ba208ad0a24e5594b | 15,065 |
def get_bucket(client=None, **kwargs):
"""
Get bucket object.
:param client: client object to use.
:type client: Google Cloud Storage client
:returns: Bucket object
:rtype: ``object``
"""
bucket = client.lookup_bucket(kwargs['Bucket'])
return bucket | b71891eec3a9f7c8f9b8fad134b2dd02bfb65e51 | 15,066 |
def remove_macros(xml_tree: etree._ElementTree) -> etree._ElementTree:
"""Removes the macros section from the tool tree.
Args:
xml_tree (etree._ElementTree): The tool element tree.
Returns:
etree.ElementTree: The tool element tree without the macros section.
"""
to_remove = []
... | 77fed7e85dadbe8b2ec7511ad3b4cf7c272807a4 | 15,067 |
def flight_time_movies_2_binary_search(movie_lengths, flight_length):
"""
Solution: Sort the list of movies, then iterate it, conducting a binary
search on each item for different item, when added together, equals the
flight length.
Complexity:
Time: O(n * lg{n})
Space: O(1)
"""
if len(movie_lengths) < 2:
... | ac7e8ad340e677f6c51f1841aab61262d8c4e226 | 15,068 |
def find_vertical_bounds(hp, T):
"""
Finds the upper and lower bounds of the characters' zone on the plate based on threshold value T
:param hp: horizontal projection (axis=1) of the plate image pixel intensities
:param T: Threshold value for bound detection
:return: upper and lower bounds
"""
N = len(hp)
# F... | 8520c3b638cafe1cfb2d86cc7ce8c3f28d132512 | 15,069 |
import base64
def executeCmd(cmd,arg):
""" the meat: how we react to the SNI-based logic and execute the underlying command """
global currentPath
global currentDirList
global currentFileList
global currentFileSizeList
global agentName
commands = initCmd(cmd)
for testedCommand, alias... | b257e77c2f7c692d63aa4140cc5ce6ccc2213273 | 15,070 |
from typing import Union
from typing import Tuple
import re
async def text2image(
text: str,
auto_parse: bool = True,
font_size: int = 20,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white",
font: str = "CJGaoDeGuo.otf",
font_color: Union[str, Tuple[int, int, int]] = ... | dbdc6436c94d57aa2d1eb910dc18e4afeeadf689 | 15,071 |
def get_dosage_ann():
""" Convenience function for getting the dosage and snp annotation
"""
dos = {}
s_ann = {}
dos_path =\
("/export/home/barnarj/CCF_1000G_Aug2013_DatABEL/CCF_1000G_Aug2013_Chr"
"{0}.dose.double.ATB.RNASeq_MEQTL.txt")
SNP_ANNOT =\
("/proj/ge... | 792caa3c9b6326178ca5a706b694c52cf1bddccc | 15,072 |
import types
import typing
import re
def function_arguments(function_name: str, services_module: types.ModuleType) -> typing.List[str]:
"""Get function arguments for stan::services `function_name`.
This function parses a function's docstring to get argument names. This is
an inferior method to using `ins... | 01a12d97c6b154159c4ba2d142e1374a008befe3 | 15,073 |
def cost_n_moves(prev_cost: int, weight: int = 1) -> int:
""" 'g(n)' cost function that adds a 'weight' to each move."""
return prev_cost + weight | 77a737d68f2c74eaba484b36191b95064b05e1a9 | 15,074 |
import codecs
import re
import glob
import os
def get_email_dict(txt_dir):
"""
:param txt_dir: the input directory containing all text files.
:return: a dictionary where the key is the publication ID and the value is the list of authors' email addresses.
"""
def chunk(text_file, page_limit=2000):
... | b7d70c8ec13bc2350e7291f8bf68026de4638bbc | 15,075 |
import io
def get_gaussian_fundamentals(s, nfreq=None):
"""
Parses harmonic and anharmonic frequencies from gaussian
log file.
Input:
s: String containing the log file output.
nfreq : number of vibrational frequencies
Returns:
If successful:
Numpy 2D array of size: nfreq x 2
... | 0da2acf3eb1ca0e057da8935ad772a2c65fd251a | 15,076 |
def uniform_selection_tensor(tensor_data: np.ndarray,
p: int,
n_bits: int,
per_channel: bool = False,
channel_axis: int = 1,
n_iter: int = 10,
min... | 17f5e13443fc23ce4d0dafc0fb69de226e93fc56 | 15,077 |
import os
def _get_mock_dataset(root_dir):
"""
root_dir: directory to the mocked dataset
"""
base_dir = os.path.join(root_dir, "PennTreebank")
os.makedirs(base_dir, exist_ok=True)
seed = 1
mocked_data = defaultdict(list)
for file_name in ("ptb.train.txt", "ptb.valid.txt", "ptb.test.tx... | e16d05937f743941b1b15324b3d77ddc2b2ccf9c | 15,078 |
def calculate_bin_P(P, x, cal_type='pes'):
""" Calculate the virtual, binary transition function.
That is, this function is to calculate the transition function which
a state and action pair may visit the virtual state $z$
"""
n, m = x.world_shape
# P_z is defined for the n*m states $s$ and a vi... | db7908f2ac0f20d72a70a920c412b895bf4ccef4 | 15,079 |
def makeYbus(baseMVA, bus, branch):
"""Builds the bus admittance matrix and branch admittance matrices.
Returns the full bus admittance matrix (i.e. for all buses) and the
matrices C{Yf} and C{Yt} which, when multiplied by a complex voltage
vector, yield the vector currents injected into each line from... | 8068d6a17c99f747e8d95b0b3ba1ac65735be382 | 15,080 |
import numpy
def list_blob(math_engine, batch_len, batch_width, list_size, channels, dtype="float32"):
"""Creates a blob with one-dimensional Height * Width * Depth elements.
Parameters
---------
math_engine : object
The math engine that works with this blob.
batch_len : int, > 0
... | dab3b45173fcca32f2cfc7bfbc585e002ff34f37 | 15,081 |
def skip_on_pypy_because_cache_next_works_differently(func):
"""Not sure what happens there but on PyPy CacheNext doesn't work like on
CPython.
"""
return _skipif_wrapper(func, IS_PYPY,
reason='PyPy works differently with __next__ cache.') | b2f765f1cad292948bb456aa841e92f180222061 | 15,082 |
import random
def get_life_of_brian():
"""
Get lines from test_LifeOfBrian.
"""
count = 0
monty_list = ['coconut']
try:
with open(LIFE_OF_BRIAN_SCRIPT) as f:
lines = f.readlines()
for line in lines:
count += 1
#print(line)
... | 5b6007888f51b0b2a38eea6381bdaa5187624dda | 15,083 |
def ackley_func(x):
"""Ackley's objective function.
Has a global minimum at :code:`f(0,0,...,0)` with a search
domain of [-32, 32]
Parameters
----------
x : numpy.ndarray
set of inputs of shape :code:`(n_particles, dimensions)`
Returns
-------
numpy.ndarray
compute... | f00b729f57fbaa1534bb78589e1a64912b08b4a3 | 15,084 |
def validate_listable_type(*atype):
"""Validate a list of atype.
@validate_listable_type(str)
def example_func(a_list):
return a_list
@validate_listable_type(int)
def example_int_func(a_list):
return a_list
"""
if len(atype) != 1:
raise ValueError("Expected... | 691737184fca8bdcc7f4c3779af86b9a041b71dc | 15,085 |
def meh(captcha):
"""Returns the sum of the digits which match the next one in the captcha
input string.
>>> meh('1122')
3
>>> meh('1111')
4
>>> meh('1234')
0
>>> meh('91212129')
9
"""
result = 0
for n in range(len(captcha)):
if captcha[n] == captcha[(n + 1) ... | 2ff68455b7bb826a81392dba3bc8899374cbcc3e | 15,086 |
def check_cli(module, cli):
"""
This method checks if vRouter exists on the target node.
This method also checks for idempotency using the vrouter-bgp-show command.
If the given vRouter exists, return VROUTER_EXISTS as True else False.
If the given neighbor exists on the given vRouter, return NEIGHB... | fdeb4dafad83562a48d0d22871fb6dc5a845fc2b | 15,087 |
def is_prime(n):
""" from
https://stackoverflow.com/questions/15285534/isprime-function-for-python-language
"""
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if ... | e992badd0648d0896097df71186fee2895d20119 | 15,088 |
def load(file, encoding=None):
"""load(file,encoding=None) -> object
This function reads a tnetstring from a file and parses it into a
python object. The file must support the read() method, and this
function promises not to read more data than necessary.
"""
# Read the length prefix one char... | 939cc6f7a42daa35552e256a1e2725826d44c01c | 15,089 |
import ispyb.model.datacollection
import ispyb.model.processingprogram
import logging
import configparser
def enable(configuration_file, section="ispyb"):
"""Enable access to features that are currently under development."""
global _db, _db_cc, _db_config
if _db_config:
if _db_config == configur... | 2aa613694f01c290f4cfeea8d8a470e87000021f | 15,090 |
def MakeMsgCmd(cmdName,argList):
"""
Take a command name and an argList of tuples consisting of
pairs of the form (argName, argValue), and return a string
representing the corresponding dibs command.
"""
body = MakeStartTag(dibs_constants.cmdTagName,{'id':cmdName}) + '\n'
for argPair in arg... | 63fd4c2695c005fa7ff465cd1975285d15dd4faf | 15,091 |
def preprocess(tweet):
"""
Substitures urls with the string URL. Removes leading and trailing whitespaces
Removes non latin characters
:param tweet:
:return:
"""
# remove URL
line = remove_url(str(tweet.strip()))
# remove non Latin characters
stripped_text = ''
for c in line:... | 44bc9f9c66c6abc8f95acdf1666f9ded7c6aa610 | 15,092 |
def read_xml_file(input_file, elem):
"""Reads xml data and extracts specified elements
Parameters
----------
input_file : str
The OTA xml file
elem : str
Specified elements to be extracted
Returns
-------
list
a list of xml seat data
"""
tree = ET.parse(... | 58b8e4b86f1400d0d77856cb57e6823f0c538487 | 15,093 |
from .application import Application, ApplicationEnv
from .operator import Operator, OperatorEnv
from typing import Optional
from typing import Union
from typing import List
def env(pip_packages: Optional[Union[str, List[str]]] = None):
"""A decorator that adds an environment specification to either Operator or A... | 9404d28e56a0d8824c9f05a0fa601b9ba181c98f | 15,094 |
import time
def test_trace_propagation(
endpoint, transport, encoding, enabled, expect_spans, expect_baggage,
http_patchers, tracer, mock_server, thrift_service,
app, http_server, base_url, http_client):
"""
Main TChannel-OpenTracing integration test, using basictracer as
implement... | afd85ef71b14a263f4480a0c0f81e019dc680e34 | 15,095 |
def cost_stage_grads(x, u, target, lmbda):
"""
x: (n_states, )
u: (n_controls,)
target: (n_states, )
lmbda: penalty on controls
"""
dL = jacrev(cost_stage, (0,1)) #l_x, l_u
d2L = jacfwd(dL, (0,1)) # l_xx etc
l_x, l_u = dL(x, u, target, lmbda)
d2Ldx, d2Ldu = d2L(x, u, t... | a6137653adcb3579775a9bcc9e8ddf03bb6f2cda | 15,096 |
def create_rotation_matrix(angles):
"""
Returns a rotation matrix that will produce the given Euler angles
:param angles: (roll, pitch, yaw)
"""
R_x = Matrix([[1, 0, 0],
[0, cos(q), -sin(q)],
[0, sin(q), cos(q)]]).evalf(subs={q: angles[0]})
R_y = Matrix([[cos... | 8431dce383a83d431f9951f76624723f5697cf83 | 15,097 |
def goodput_for_range(endpoint, first_packet, last_packet):
"""Computes the goodput (in bps) achieved between observing two specific packets"""
if first_packet == last_packet or \
first_packet.timestamp_us == last_packet.timestamp_us:
return 0
byte_count = 0
seen_first = False
for pa... | aea56993771c1a250dacdfccf8328c7a0d3ce50b | 15,098 |
from typing import Sequence
def validate_scopes(
required_scopes: Sequence[str], token_scopes: Sequence[str]
) -> bool:
"""Validates that all require scopes are present in the token scopes"""
missing_scopes = set(required_scopes) - set(token_scopes)
if missing_scopes:
raise SecurityException(f... | e979cdd2eb73c89084f72fd4f70390dfe3109c17 | 15,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.