content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def match(rules: Rules, rule_id: str, message: str) -> List[int]:
"""Returns how many characters are possible to match in *message* starting from *rule_id*.
If none can be matched, returns the empty list, otherwise, returns a list of possibilities,
as there can be several alternat... | 4d1f278333bf3095a382015d9d0f062e655333bb | 57,500 |
import json
def parse_json(line: str) -> str:
"""
parse one line of json data, change the names of some fields and add the length of multivalued fields
:param line: a string containing document as json
:return: the modified data as string
"""
parsed = json.loads(line)
# rename authors to a... | 68f332e12fcd8600da1aa8f3f34d9b2aef01a6cb | 57,501 |
import argparse
def parse_argv():
"""Parse sys.argv"""
desc = 'Convert phitar yield files to a datagen input file'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--nrg_of_int',
required=True,
help='beam energy of interest')
p... | caa54cdf2df15a7ce3b9bd896939b4ade2706f5d | 57,502 |
def sqs_receive(fila):
"""
recupera templates da lista
"""
sqs = boto3.resource('sqs', region_name=aws_region)
conn = sqs.get_queue_by_name(QueueName=fila)
messages = conn.receive_messages(MaxNumberOfMessages=10, AttributeNames=[
'All'], WaitTimeSeconds=1)
... | d4de36bc63a8d1d967f6a1927f1e9731fbff82eb | 57,503 |
def model_to_owl_str(model: BioPaxModel) -> str:
"""Return an OWL string serialized from a BioPaxModel object.
Parameters
----------
model :
The BioPaxModel to serialize into an OWL string.
Returns
-------
:
The OWL string for the model.
"""
return xml_to_str(model.... | b036c18a1b10a069c7dd36a1d11fbdc8da813727 | 57,504 |
import warnings
def ica(data, observations , n_components, n_runs , return_info = False , copy = False , plot_projection = None , fun = 'logcosh' , algorithm = 'fastica_par'
, normalize = True , reorientation = True , whiten = True , pca_solver = 'full', chunked = False , chunk_size = None , zero_center = True... | 8462c08ef207aa75d8c798b438f2366a63ccdf91 | 57,505 |
def _find_dumb_path(challbs, preferences):
"""Find challenge path without server hints.
Should be called if the combinations hint is not included by the
server. This function either returns a path containing all
challenges provided by the CA or raises an exception.
"""
path = []
for i, cha... | 9a07cbd00e8b21d98024ae314df0291da1d598f1 | 57,506 |
def _assign_odim_moments(ds, nch, sweep, **kwargs):
"""Assign radar moments to dataset.
Parameters
----------
nch : netCDF4.Dataset handle
source netCDF4 Dataset
ds : xarray dataset
destination dataset
sweep : str
netcdf group name
Keyword Arguments
------------... | 1eba8ddadc46c287e6daf078b4e9d09f54f69efc | 57,507 |
import collections
import itertools
import unittest
def _test_or_class_decorator(test_or_class, single_method_decorator):
"""Decorate a test or class with a decorator intended for one method.
If the test_or_class is a class:
This will apply the decorator to all test methods in the class.
If the te... | 13af4b3f68d6ece781e8e665b9bf8073970a9c1d | 57,508 |
import torch
import math
def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)):
"""Convert torch Tensors into image numpy arrays.
After clamping to (min, max), image values will be normalized to [0, 1].
For differnet tensor shapes, this function will have different behaviors:
1. 4D mini-bat... | db3e0b221e0634ff2c3635c6f25dcc8e6d7b3f9e | 57,509 |
import os
def index():
"""
Returns a message with the environmental variable 'CUSTOM_ENVIRONMENTAL_VARIABLE' appended
to it
"""
# Return a message with the environmental variable retrieved appended to it
return "Message retrieved from environmental variable: " + os.environ.get(variable_name, N... | aee87302ad8e50148c3223e49ba1116dbbabc6e3 | 57,510 |
def censor(data, width=30):
""" Censor values after leading edges in time.
This is used to insert a censored period in threshold crossings.
For instance, when you find a crossing in the signal, you don't
want the next 0.5-1 ms, you just want the first crossing.
**Arguments**:
*data*:
... | f943c3c556a8ec6c667e217080509255ce76cdc7 | 57,511 |
def get_folder_parameters(folder_ref: str, filename: str):
"""Extracts sample sizes from the managed folder
:param str filename: name of the json containing the experiment parameters
:raises: :class:`ValueError`: Missing folder or filename.
:returns: sample sizes
:rtype: tuple
"""
folder =... | 59df273c57ba67669c823766d4e1e1e8cc1b8198 | 57,512 |
import psutil
import os
import subprocess
import re
def home():
"""
The main homepage showing current rips and server stats
"""
# app.logger.info('Processing default request')
# app.logger.debug('DEBUGGING')
# app.logger.error('ERROR Inside /logreader')
# Hard drive space
try:
... | 0ca825e03b02a9e6cd2fc3e7c82d4f455a9054e5 | 57,513 |
from typing import Dict
import pandas
def query_postgresql_server(database_information: DatabaseInformation, sql_command: Text,
connection_arguments: Dict = None) -> pandas.Dataframe:
"""Query PostgreSQL database.
This function will create a PostgreSQL database connection.
Ar... | 5be87d0a8168d6671768f31d23c926237591ab5f | 57,514 |
def _mt_repr(self):
"""Print mutable tuple like dict."""
return '{{{0}}}'.format(', '.join('\'{0}\': {1!r}'.format(name, getattr(self, name)) for name in self._fields)) | bc01cb22d8263ce7df77e90214d587f0553627a7 | 57,515 |
def call_view(request, username):
"""Call page."""
interlocutor = get_object_or_404(User, username=username)
return render(
request,
"call.html",
{
"interlocutor": interlocutor,
},
) | 7037d0ad5564ebcc2931899190acedcf5a2e2b76 | 57,516 |
def add_args(parser):
"""
parser : argparse.ArgumentParser
return a parser added with args required by fit
"""
# Training settings
parser.add_argument('--model', type=str, default='lr', metavar='N',
help='neural network used in training')
parser.add_argument('--datas... | 794109eaf6da5cfc52c95ef6a8a69430b98fd17d | 57,517 |
def rescale_none(pop_counts, policy, budget=None):
"""
Rescales and allows for None in policy proportion factors.
Filters out the nones, and performs rescaling on the remaining numbers.
pop_counts: dict[pop_id] -> count
policy: dict[pop_id] -> proportion factor
"""
scales = [v for k, v in p... | 330bf93707d7ee8ecee10ebb9dade916eee7d510 | 57,518 |
def check_cors(f):
"""Wraps a request handler with CORS headers checking."""
@wraps(f)
def decorated(*args, **kwargs):
self = args[0]
request = args[1]
origin = request.getHeader('Origin')
if origin:
if '*' in self.cors_origins:
request.setHeader... | 2b6354dae6ecf16fb192f14d15b9b9a14d898661 | 57,519 |
def _stc_to_label(stc, src, smooth, subjects_dir=None):
"""Compute a label from the non-zero sources in an stc object.
Parameters
----------
stc : SourceEstimate
The source estimates.
src : SourceSpaces | str | None
The source space over which the source estimates are defined.
... | fd18809322a9974418ab59423ca35680e2aab709 | 57,520 |
from pathlib import Path
def delete_ingest_pipeline(ingestPipelineName: str = Path(
default='test-pipeline', example='test-pipeline')):
"""
Delete a previously saved ingest pipeline - based on the ingest pipeline name.
"""
return _id | d2f8b318049490ae4e7d6b9976edb3350ac93515 | 57,521 |
import re
def rgb2short(rgb):
""" Find the closest xterm-256 approximation to the given RGB value.
@param rgb: Hex code representing an RGB value, eg, 'abcdef'
@returns: String between 0 and 255, compatible with xterm.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231'... | 4fe1600d6e95a921cc82bd00bbc899f24b42684e | 57,522 |
from operator import contains
def homo_inner_multi(N, m, minority_fraction, homophily, epsilon, labels, edges):
"""
samples edges according to barabasi + homophily but allows multi edges
this algorithm has strict runtime O(n + m)
"""
n_edges = 0
minority_size = int(minority_fraction * N)
m... | 37cf73ca583d0a81469b579158423a5c113d91e0 | 57,523 |
import scipy
def fit(model, trend, val='arate'):
"""Fit a 2 paramater model to a rate trend"""
try :
doffs = list(range(trend.num_rows))
params, pcov = scipy.optimize.curve_fit(model, doffs, trend[val])
return params, np.sqrt(np.diag(pcov))
except :
return [np.nan, np.nan],... | cad3f3b5ce93d15121df2d558317b442d30161e8 | 57,524 |
def get_denovo(v, samples, kids, max_alts_in_parents=1,
min_depth=5,
max_mean_depth=400,
min_allele_balance_p=0.05,
min_qual=1,
exclude=None,
HET=1):
"""
v: cyvcf2.Variant
samples: dictionary of sample: index in vcf.
kids: list of peddy.Samples() that have... | cc8ff99ad9306fa82b6c3f0dbca8b0f431048476 | 57,525 |
from typing import Tuple
from typing import Any
def parse_tuple(string: str) -> Tuple[Any, ...]:
"""Parse a tuple from a given string.
:param string: the string representation of a tuple
:type string: str
:raises ValueError: if the string cannot be interpreted as a tuple using :func:`ast.literal_eval... | b201cb1c5671ff7d873721e38ec7ad94f59a1680 | 57,526 |
async def sanitize_chnurl(chn_url: str):
"""Returns the standardized url.
Can raise `ValueError` if url not supported.
Can raise `RateLimited`.
"""
# May not be fully checking url validity.
# TODO
# !!This is may be security vulnerability!! Check the url properly!
if "." not in chn_url a... | 0d69641fa0bdf78b870d55340ef3a0335c4769bd | 57,527 |
def get_k_set_interval(vec: str, k: int, to_counter_plus_one: bool = False) -> tuple:
"""return tupl
Parameters
----------
vec : str
String of {0,1}*.
k : int
????????????????????
????????????????????
## to_counter_plus_one : bool
## If True, assume vec beggins i... | ac0dcfe0e9af6dae77942ba7beb682c9d52b57f0 | 57,528 |
import functools
import numpy
import unittest
def for_dtypes(dtypes, name="dtype"):
"""Decorator for parameterized dtype test.
Args:
dtypes(list of dtypes): dtypes to be tested.
name(str): Argument name to which specified dtypes are passed.
This decorator adds a keyword argument specif... | cb6784686cbf5adc034d0014e385a67e47d7f933 | 57,529 |
def remove_failed(data, failed):
"""
chr20 12th row, 1 based
chr21 1st row, 1 based
chr22 27th row, 1 based
"""
failed = np.array(failed)
data = np.array(data)
res = np.delete(data, failed, -1)
res = np.delete(res, failed, -2)
return res | 1406fb3fe5f5e5efbf135fd6c0cab299d7a81044 | 57,530 |
def play_and_train(env, agent, t_max=10**4):
"""
This function should
- run a full game, actions given by agent's e-greedy policy
- train agent using agent.update(...) whenever it is possible
- return total reward
"""
total_reward = 0.0
s = env.reset()
for t in range(t_max):
... | 0a4a5bf5f71a1c14946c30d39aa3a541f9a5c6fd | 57,531 |
def shap_neighbors(instance, x_init, contributions, mode):
"""
For an instance and corresponding neighbors, calculate various
metrics (described below) that are useful to evaluate local stability
Parameters
----------
instance : 2D array
Instance + neighbours with corresponding features... | e600a4d78a69e705e8162522ca6addf6cfd79937 | 57,532 |
import pandas as pd
def save_ldamodel_summary_to_excel(excel_file, topic_word_distrib, doc_topic_distrib, doc_labels, vocab,
top_n_topics=10, top_n_words=10, dtm=None,
rank_label_fmt=None, topic_labels=None):
"""
Save a summary derived from... | fe8fec0cbc8e2fe6e3923fb54015162181cc06ae | 57,533 |
def _do_transforms(graph_def, input_names, output_names, initializer_names,
transforms, saver_def=None, checkpoint_path=None):
"""Apply requested transforms to a GraphDef, including freezing.
This applies the Graph Transform Tool interleaved with graph freezing.
Args:
graph_def: A GraphDe... | 547ba9f3c7ecd95e4ce3e8c0acdf695f23f175b9 | 57,534 |
def UsersJSON():
""" This is a JSON endpoint which returns list of all registered users."""
session = DBSession()
users = session.query(User).all()
return jsonify(users=[u.serialize for u in users]) | 2412b54c30182e0388b7ba83be074d1e4d3464b7 | 57,535 |
def preprocess_default(pathname):
"""
Examples:
>>> preprocess_default("data/train_sample_0.csv")
"""
df = pd.read_csv(pathname)
df = preprocess_funcs.add_times2categorical(df)
df = preprocess_funcs.add_releaseyear(df)
df = preprocess_funcs.add_ages2categorical(df)
df = preproces... | 92702ac6e74af046e663bcbb453a8c92c73f6e15 | 57,536 |
def vertice_concatenate(pt1xstr, pt1zstr, pt1ystr, pt2xstr, pt2zstr, pt2ystr, pt3xstr, pt3zstr, pt3ystr, pt4xstr, pt4zstr, pt4ystr, pt5xstr, pt5zstr, pt5ystr, pt6xstr, pt6zstr, pt6ystr, pt7xstr, pt7zstr, pt7ystr, pt8xstr, pt8zstr, pt8ystr, pt9xstr, pt9zstr, pt9ystr, pt10xstr, pt10zstr, pt10ystr, pt11xstr, pt11zstr, pt1... | e12332d866b7b1e5acc7e9214f264d4b24e592c4 | 57,537 |
def U(W, cell=None):
"""Calculates operator `U` for the given wave functions.
Args:
W (numpy.ndarray): wave function sample points.
cell (pydft.geometry.Cell): describing the unit cell and sampling points.
"""
return np.dot(W.conjugate().T, O(W, cell)) | 846cf07f848875ebd0afddb66a3b018e0757812f | 57,538 |
def build_rescale_transform_slow(downscale_factor, image_shape, target_shape):
"""Rescale Transform.
This mimics the skimage.transform.resize function.
The resulting image is centered.
Args:
downscale_factor: float, >1
image_shape: tuple(rows, cols), input image shape
target_shape: tuple(row... | a009d89572ee6c5a686646a7c8c9df43395fc5d5 | 57,539 |
def load_h5(h5f):
"""
Load fiberbundles configurations from a hdf5 class
Parameters
----------
h5f : hdf5 class
h5-file or group object
Returns
-------
res : list(list(fiber)), fibers are (n,4)-arrays with (x,y,z,radii) for each fiber point
"""
fiber_bundles = []
f... | 47487b43ae375c5ade27c82ec083570ee9655e27 | 57,540 |
def fizz_buzzable(num):
"""
We're only interested in valid fizz buzz numbers.
"""
return num % 3 == 0 or num % 5 == 0 | 4eba37245525ead66f4f30370d9e3d97c05aca55 | 57,541 |
def hpo_sheets_chosen_create_uw_ams(
metric_choice, hpo_dictionary, datetimes, metric_dictionary):
"""
Function is used to triage how to create 'aggregate metrics'
for HPO sheets based on the kind of user input provided.
In cases where the 'aggregate metric' already exists in the
DataQualit... | 8856a012059fbec747862eda1f642a856deb1ce7 | 57,542 |
def sympy2pysmt(expression):
"""Converts a sympy formula representing a polynomial into a pysmt formula.
Args:
expression: The sympy formula to convert.
Returns:
FNode: The pysmt formula.
Raises:
WMIParsingException: If the method fails to parse the formula.
... | 24687efc367e1c8904b07e66f7f787b5282c1afd | 57,543 |
async def send_for_revision(internal_id: str, stages_ids: tp.List[str]) -> GenericResponse:
"""
Endpoint to sent current unit for revision by selected stages ids.
Empty copy of those stages will be created. Unit status will change to 'revision'.
"""
logger.info(f"Sending unit {internal_id} for revis... | e1a26f663fdec547d37d9c33a1fbc9b5410ba31d | 57,544 |
def MINUS_DM(data: xr.DataArray, timeperiod: int = 14):
"""
Minus Directional Movement (Momentum Indicators)
Inputs:
data: ['high', 'low']
Parameters:
timeperiod: 14
Outputs:
double series
"""
return multiple_series_call(talib.MINUS_DM, data, ds.TIME, ds.FIELD, [f.HIG... | 3d732ce535292af7e9031955edbad1d5c1312130 | 57,545 |
def parse_arxiv_url(url):
"""
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id and the version
"""
ix = url.rfind('/')
idversion = url[ix+1:] # extract just the id (and the version)
parts = idversion.split('v')
assert len(parts) == 2, 'error parsing url ' + url
return parts[... | 1eb44f9db2504cd569bea9ab91ca5b27f1ff1817 | 57,546 |
from typing import List
def load_file(file_path: str) -> List[str]:
"""
Just loader for file with lines
:param file_path: path to file
:return: list of lines of your data
"""
data: List[str] = list()
with open(file_path) as file_object:
for line in file_object:
data.a... | 9aadf5c0a90f5c65868862e4366276c448077944 | 57,547 |
def uniquify_tablewidgetitems(a):
""" Eliminates duplicate list entries in a list
of TableWidgetItems. It relies on the row property
being available for comparison.
"""
if (len(a) == 0):
tmp = []
else:
tmp = [a[0]]
# XXX: we need to compare row #s because
... | 942eb3fb5e172185fe7f857f5e6e5e523984b75c | 57,548 |
from Acquire.Client import Service as _Service
from Acquire.Client import LoginError
def _get_accounting_service(accounting_url=None):
"""Function to return the accounting service for the system
Args:
accounting_url (str, default=None): Accounting URL
Returns:
Service: Accounting servic... | d25e914adf75cf45755a053eea2006fe7975c3b6 | 57,549 |
def distance(s, t):
"""Returns the Levenshtein edit distance between two strings."""
m, n = len(s), len(t)
d = [range(n+1)]
d += [[i] for i in range(1,m+1)]
for i in range(0,m):
for j in range(0,n):
cost = 1
if s[i] == t[j]: cost = 0
d[i+1].append(min... | c7232ada6d66604430e9d6fe14bff18e3ede91bf | 57,550 |
def _rpl_specialstr(full, updatetype, s, name_table, get_step, get_flag, get_variant, basenamelist=None,
startindex=0, spcharinfo=None, namelist=None, namelistindex=0, stack=0):
"""
特殊文字列(#, $)を置換した文字列を返す。
"""
if spcharinfo is None:
_reset_nametable(name_table)
if namelis... | 0088309387d000e5327dadf2dcf8f24d2cf1205d | 57,551 |
def build_app_list(app_list):
"""Create response payload for app list."""
app_list = [
{"app_id": app_id, "title": app_name, "type": MEDIA_TYPE_APP}
for app_name, app_id in app_list.items()
]
return BrowseMedia(
media_class=MEDIA_CLASS_DIRECTORY,
media_content_id=None,
... | 7bd1a83da7ffaed68fd90ecefc28f0ca48e4de8e | 57,552 |
import random
def random_colors(*commands):
"""From tuple of commands, generate random but unique colors."""
colors = ["blue", "green", "red", "yellow", "magenta", "cyan", "white"]
num_colors = len(colors)
num_commands = len(commands)
if num_commands >= num_colors:
colors += colors
u... | 2f55ce480a8550d94b595b94017371e525b8a8b4 | 57,553 |
def greeting() -> str:
"""The standard greeting.
>>> assert greeting() == 'hello'
"""
return 'hello' | eba4ada1f6dd154dc8197bce0c0128fea3d7e31e | 57,554 |
def ncread(mdataset, grid, varname, elem=slice(None)):
"""Read a variable from a MDataset and returns it as a Marray
consistent with `grid`
"""
assert varname in variables, f"this `{varname}` is not implemented"
var = mdataset.variables[varname]
# data = var[elem]
attrs = var.attrs
stagg... | 4871449210a7501715a81776279b0f645efae6c5 | 57,555 |
def impute_dates(df, freq, dt_stop=None):
"""Fill missing dates in the timeseries dataframe.
Parameters
----------
dd : pd.DataFrame
freq : str
dt_stop : str or datetime, optional
The final date in the timeseries, it will be inferred if not specified.
Otherwise, dates will be im... | 01ab0c4aee61f23e10a220e603e05d794a5a5792 | 57,556 |
from datetime import datetime
import copy
import sys
def local_search(
local_search_starting_points,
local_search_random_points,
param_space,
fast_addressing_of_data_array,
enable_feasible_predictor,
optimization_function,
optimization_function_parameters,
scalarization_key,
number... | fdefe10afa9528d7408bc81062c5e898962b0bda | 57,557 |
def get_num_antennas(ms):
"""Return number of antennas in a MS."""
tb.open(ms + '/ANTENNA', nomodify=True)
num_stations = tb.nrows()
tb.close()
return num_stations | ef815dd1c038c6f31686dfa0160edd42ad576be3 | 57,558 |
def compare_records(azara_record, rui_record):
"""
:param azara_record: tuple - a (treasure, coordinate) pair.
:param rui_record: tuple - a (location, coordinate, quadrant) trio.
:return: bool - True if coordinates match, False otherwise.
"""
return azara_record[1] == rui_record[1][0] + rui_re... | e0ee6ceddee0be3bcb5ce4fb283ba560c0998fe9 | 57,559 |
import random
def mutation_chromossome(chromossomes, mutation_function, mutation_rate):
"""
:param: chromossomes -
:param: mutation_function -
:param: mutation_rate -
:return: chromossomes -
"""
number_chromossomes_to_mutate = int(len(chromossomes) * mutation_rate)
ran... | 30a9a92724a91e70d10ba5c35fef0e1aef85300d | 57,560 |
def pcmd(progressive, lr, fb, vv, va):
"""
Makes the drone move (translate/rotate).
Parameters:
progressive -- True: enable progressive commands, False: disable (i.e.
enable hovering mode)
lr -- left-right tilt: float [-1..1] negative: left, positive: right
rb -- front-back tilt: float ... | 4534ac48f00a39c944b1be01ea0818235aea2559 | 57,561 |
def model_with_multiple_training_tensors():
""" Return model with multiple batchnorms using different training tensors """
inputs = tf.keras.Input(shape=(32, 32, 3,))
# Should create a keras learning phase tensor
x = tf.keras.layers.BatchNormalization(momentum=.3, epsilon=.65)(inputs)
is_training =... | 18d3bcf6d47d3f911a7d8568e705a2ca8ac8c610 | 57,562 |
def consume(generator): # pragma: no cover
"""
Helper function to consume a synchronous or asynchronous generator.
Arguments:
generator (generator|asyncgenerator): generator to consume.
Returns:
list
"""
# If synchronous generator, just consume and return as list
if hasatt... | cba35032ee327a4feacb547d59de6c70d8b1bb74 | 57,563 |
def b2h(n):
"""Convert bytes int into human friendly string format.
>>> b2h(10000)
'9.8 KB'
>>> b2h(100001221)
'95.4 MB'
"""
t = "{0:.2f} {1}".format
symbols = ("KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
prefix = {s: 1 << (i + 1) * 10 for i, s in enumerate(symbols)}
for s i... | 6337fa1d1c7a2e324bcbe99eac28225551f84ef5 | 57,564 |
def modules_to_opt_conf(*modules,**opt_kwargs)->"a list of PyTorch optimizer config":
"""
put in a sequence of pytorch modules,
return optimizer param groups of configs
"""
param_list = []
param_list_nd = []
no_decay = ["bias", "LayerNorm.weight"]
for m in modules:
for n,p in m... | 721c92fd9749b678f03fe5910da8167faab930b7 | 57,565 |
import os
def _mkdir_local(uri, local=None):
"""
Create local directory specified by URI.
Args:
uri: parsed URI to create.
local: local context options.
Returns:
On success: True.
On failure: False.
"""
try:
os.makedirs(uri['chopped_path'])
excep... | bbdf365f603d60985e53fd9fc79b4d6d4675809b | 57,566 |
from typing import List
from typing import Tuple
def get_residual_blocks_for_ferminet_backflow(
spin_split: ParticleSplit,
ndense_list: List[Tuple[int, ...]],
kernel_initializer_unmixed: WeightInitializer,
kernel_initializer_mixed: WeightInitializer,
kernel_initializer_2e_1e_stream: WeightInitiali... | 63ce43eacba2b8179efa046b6a963697acd2515b | 57,567 |
def adjoin(space, *lists):
"""
Glues together two sets of strings using the amount of space requested.
The idea is to prettify.
"""
outLines = []
newLists = []
lengths = [max(map(len, x)) + space for x in lists[:-1]]
# not the last one
lengths.append(max(map(len, lists[-1])))
m... | 7eb2df83aed2c0b4f32926940bbb9f4d2b497832 | 57,568 |
def lambda_tokenize(string):
""" Tokenizes a lambda-calculus statement into tokens.
Inputs:
string: a lambda-calculus string
Outputs:
a list of tokens.
"""
space_separated = string.split(" ")
new_tokens = []
# Separate the string by spaces, then separate based on existence... | b704ad3361b1e188c1577b22b90545069199eda7 | 57,569 |
import requests
def series_id(TVDB_id, JWT=None):
"""TV series data search of TheTVDB by TheTVDB series id.
Arguments:
TVDB_id: TheTVDB episode id to search.
JWT: Java Web Token for authentication as a string, if None, will run
authentication function.
Returns:
JSON ... | b0212564d06d9e2a7f4fb3057f7b2a81e24ef5d7 | 57,570 |
def delete_listas_cmd(listas_id):
"""
Construct a command to delete a listas
:param listas_id: listas's id
:return: Command
"""
return DeleteNode(listas_id) | 2d5589fe9418703872f51edaea7cefaeb7f5dad1 | 57,571 |
import requests
def GetUserStatus(accesskey):
""" Queries keepa for available tokens """
url = 'https://api.keepa.com/token/?key={:s}'.format(accesskey)
r = requests.get(url)
status_code = r.status_code
# Return parsed response if successful
if status_code == 200:
response = r.json(... | 3f8c21cdb667b62755cede1ae2bfc66e84cea862 | 57,572 |
def _create_pbp_df_json(pbp, gameinfo):
"""
Creates a pandas dataframe from the pbp, making use of gameinfo (from schedule file) as well
:param pbp: dict, from pbp json
:param gameinfo: dict, single row from schedule file
:return: dataframe
"""
index = [i for i in range(len(pbp))]
per... | 2685a7fc017ba990956956068b0a108acd577bee | 57,573 |
def aten_gather(mapper, graph, node):
""" 构造gather激活的PaddleLayer。
TorchScript示例:
%result.3 : Tensor = aten::gather(%input.5, %18, %19, %20, %21)
参数含义:
%result.3 (Tensor): 输出,gather后的结果。
%result.5 (Tensor): 需要gather的Tensor。
%18 (int): 需要gather的维度。
%19 (Tensor): 需要... | de7d2205baa0714ab972da71c9db0ae48edfd1c3 | 57,574 |
import importlib
def get_module(name: str):
"""Import a module dynamically."""
if name.lower() == "std":
return std
module = importlib.import_module(name)
print(f"Loaded {module}")
return module | 2e3e5eb2245bd89a7c259a1069493ae6627e1a33 | 57,575 |
from typing import Union
import os
def cmd_nlu_trsx2qnlp(mixcli: MixCli, **kwargs: Union[str, int]):
"""
Default function when nlu import command is called.
:param mixcli: MixCli instance
:param kwargs: keyword arguments from command line
:return: None
"""
# we just use user name as names... | acf593ca24a48d0c65607ed2f18cc0e3d1155c2d | 57,576 |
def html_to_text_h2t(html: str):
"""
从html提取核心内容text
:param html:
:return:
"""
doc = Document(html)
h = html2text.HTML2Text()
h.ignore_links = True
h.bypass_tables = False
h.unicode_snob = False
text = h.handle(doc.summary())
return text.strip() | b6c673f8670330987eba83359a0664b763c0dc1a | 57,577 |
import numpy as np
def f_calculate_thresholds(combined_uncertainties, phi=0.95):
"""
Calculates EDMF thresholds for provided target reliability of identification
Developed by : Sai G.S. Pai (ETH Singapore)
Contact : saiganesh89@gmail.com
Date: June 30, 2020
INPUTS:
... | b82feca1823c2bd772f1f6ba06a6053f6d30ad15 | 57,578 |
import json
def check_blacklist(method):
"""
API请求参数校验黑名单
"""
def request_decorator(func):
def func_wrapper(self, *args, **kwargs):
self.set_header("content-type", "application/json")
query = unquote(self.get_argument("query", "")
) if method... | 168061508a4f56cf3e3e239f9aa012d2b12811b0 | 57,579 |
def MSB(num: int, size: int) -> int:
"""
Get the most significant bit of a `size`-byte number `num`.
:param num: A number.
:param size: The number of bytes in this number.
:return:
"""
return (num >> (size * 8 - 1)) & 1 | eff28af2e71234e6188cc27f2fea48a2496a43b4 | 57,580 |
def guess_uom(property_kind, minimum, maximum, support, facet_type = None, facet = None):
"""Returns a guess at the units of measure for the given kind of property.
arguments:
property_kind (string): a valid resqml property kind, lowercase
minimum: the minimum value in the data for which the unit... | 0005fef0f4ec6a6726a54411fa8b46ffc6061e03 | 57,581 |
def ismarkdown(file_path):
"""
Check if file at given path is a .md file by extension
:param file_path: The path of the given file
:return: True if ends with .md. Otherwise, return False
"""
return hasextension(file_path, ".md") | e3af6385e1758d9c0d098d48e5d19c2eb5563899 | 57,582 |
def addToSession(session, flaskform):
"""
Function used in the hiringmanger tab. It must keep backward compatibility
with the fields named commentOne..., commentTwo..., commentThree...,
commentFour... since the DB was built in this way at first.
"""
if 'evaluatorName' in flaskform:
sessi... | 8ecaf782373730efa6c251a4354de4355cf31884 | 57,583 |
import functools
import traceback
import sys
def handle_stream_exception(iorigin="stream_exception"):
"""
decorator for stream exceptions
"""
def real_decorator(fn):
@functools.wraps(fn)
def wrapped(*args, **kwargs):
try:
fn(*args, **kwargs)
exce... | 867e277de19218cd952a6b21b52862e368ca7f04 | 57,584 |
def test_module(client: Client, *_) -> str:
"""Performs basic get request to get ip geo data.
Args:
client: Client object with request.
Returns:
string.
"""
client.ip_geo_get_request(ip_='1.1.1.1')
return 'ok' | 20ea497b8f57c59bc44637e9b3c243febe741497 | 57,585 |
import time
def go_up(seconds):
"""Endpoint for the table to go up."""
seconds = int(seconds)
GPIO.output(17, GPIO.HIGH)
time.sleep(seconds)
GPIO.output(17, GPIO.LOW)
return '<a href="up/{0}">Go up {1} seconds again</a>'.format(
seconds, seconds) | 73242fdf9a710e728d5f904452a331d2c41891e1 | 57,586 |
from pathlib import Path
def read_dlc(dlc_file, drop_first_column=False):
"""
Read DeepLabCut output, regardless of format
:param dlc_file: DeepLabCut output file
:param drop_first_column: Remove the first column with timepoint index
:return: Dataframe of the DLC results
"""
file_type = P... | ed777b439c3811c17f551e9e0433ce934aa5494f | 57,587 |
def dashboard(lti=lti, lti_exception=None):
"""
:type lti: controllers.pylti.flask.lTI
"""
force_default_assignment = maybe_bool(request.values.get('force_default_assignment', "false"))
if 'user' not in g and not g.user:
return "You are not logged in."
course_id = get_course_id()
use... | 10c7059c4e1dffc78e7d4516939eae0af6fd601b | 57,588 |
import os
import errno
def makedirs(directory):
"""
Create a directory and any missing parent directories.
It is not an error if the directory already exists.
:param directory: The pathname of a directory (a string).
:returns: :data:`True` if the directory was created, :data:`False` if it alread... | b5eecd5e27b086f8d5619802a205c85ae697980c | 57,589 |
def check_legal_moves(board):
"""Return the legal moves on the board.
"""
return board[:, :, 0] == board[:, :, 1] | a8643c6cd06722b0110a09d8c12f34a20f03a31d | 57,590 |
def wordnet_pos(tag: str) -> str:
"""Transform a `nltk` part-of-speech tag string to a `wordnet` part-of-speech tag
string.
Arguments:
tag:
An `nltk` part-of-speech tag string.
Returns:
The corresponding `wordnet` part-of-speech tag string.
"""
return getattr(
... | ca2f3f8032265e5c3c6fa0aebf63f06624812a0b | 57,591 |
import sys
def getDist(mode, origins, destinations, timestamp = None, isArrivalTime = True,
googleApiKey = None, useSuggestions = True, optimistic = 0, avoidTolls = False,
useRATP = True, dispProgress = False):
"""
Returns a table of time (seconds) results for each couple of origin / destination,
... | 0aac22ecff776022cd832be80e02e5665745dbe1 | 57,592 |
def enhance_fprint_1(matrix, block_size=10, alpha=0.7):
"""
Enhance image using locally calculating average
and then thresholding against it.
Block size determines the window for computing average
Thresholding is done using computed mean times alpha
assuming ridges are represented by high values... | 09e428d538e4462d9d53c39109c95f297a84288b | 57,593 |
def basic_debug_session(basic_wrapped_connections):
""" A basic DebugSession object with two SQLite connections """
return dbreak.sessions.DebugSession(
current_connection_name="conn1",
connections=basic_wrapped_connections
) | da7409011e7dafd8b34e67b5dc1994a79a99012d | 57,594 |
import functools
def loss_function_for_data(loss_function, X):
"""Get a loss function for a fixed dataset
Parameters
----------
loss_function : function
The loss function to use. The data parameter for the function must
be `X`
X : coo_matrix
coo_matrix of data to apply lo... | 2b45bdfd229fb79fd866dd67e9a6d8d44325a112 | 57,595 |
import logging
def reporterFromSettings(info):
"""
Returns appropriate Reporter based upon settings
"""
logger = logging.getLogger(__name__)
logger.info("building reporter")
logger.debug("settings: %r", info)
try:
_slack = info['Slack']
name = _slack.get('name')
ret... | 73978c32acde9a5418c13aead1984b74c8b0c5e2 | 57,596 |
def remove_brew():
"""Render the index page."""
args = request.get_json()
if 'id' not in args:
return jsonify({'success': False,
'error': 'ID not found in request!'})
c = mongo.db[app.config['BREWS_COLLECTION']]
remove_id = paranoid_clean(args.get('id'))
c.remove(... | 8922483373056da58fe1c4ba46a4c982af5a88b7 | 57,597 |
from typing import List
from typing import Tuple
def plotlines(
optical_start: List[float], ratio_wanted: List[float]
) -> Tuple[List[float], List[float], List[float]]:
"""Draws the 'Distance Lines' for the main plot.
Takes inputs of desired optical and radio limits of where the distance
lines should... | 5c2b83b881c8b8101a5177709096c79dfce8c16c | 57,598 |
def nl_cont_matrix(vf_f, vf_g, xx, n_extra_cols=0):
"""
'Controllability' (or 'Reachability') matrix for the nonlinear system based on iterated
lie bracketts.
:param vf_f: drift vector filed ((n x 1) sympy-matrix)
:param vf_g: input vector field ((n x 1) sympy-matrix)
:pa... | da12ecba05d2b0149cecddcf9ef5542ff9a16904 | 57,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.