content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def get_latest_ckpt(tr_model_dir):
"""find previous ckpt and return the filename of the latest ckpt."""
tf.logging.info('model dir={}'.format(
os.path.join(tr_model_dir, '*.ckpt.index')))
list_of_ckpt = tf.gfile.Glob(os.path.join(
tr_model_dir,
'*.ckpt.index')) # * means all if need... | 2d33e4d96df0c70228861185fd8cbba69a17808a | 3,600,200 |
def uploadcomentario(request):
"""Essa função carrega o arquivo do cliente
É chamada pelo cliente(específico) enviar o
arquivo/comentario para o funcionário"""
context = {}
if request.method == "POST":
uploaded_file = request.FILES["document"]
fs = FileSystemStorage()
... | 04f701a73119f82fdc9e281e3c995dae8263b3fe | 3,600,201 |
import os
def dpath(path):
"""
get path to a data file (relative to the directory this test lives in)
"""
return os.path.join(os.path.dirname(__file__), path) | 000bb169050820243181b88f221b522c24267361 | 3,600,202 |
from typing import Tuple
def spectrum_linear_fit( spec: Spectrum, wl_low: float = None, wl_high: float = None ) -> Tuple[ float, float ]:
"""
Applies a linear fit to a Specturm over the specified wavelength range. If no wl_ values are passed,
the entirely of the spectrum range is used.
Returns a... | ffd4ffb2f4e274e0a422ac4f7787d2606eb918ad | 3,600,203 |
def qats_prediction(poly_coeffs, order, lambda_values):
"""Quantum alchemy predictions using a nth-order Taylor series.
Parameters
----------
poly_coeffs : :obj:`numpy.ndarray`
Polynomial coefficients in increasing order (e.g., zeroth, first,
second, etc.).
order :obj:`int`
... | 7be48a28153827fd3beb4976583352099e356987 | 3,600,204 |
def is_odd(self, allow_rescaling_flag=True):
"""
Returns true iff after rescaling by some appropriate factor, the
form represents some odd integers. For more details, see parity().
Requires that Q is defined over `ZZ`.
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 2, [1, 0, 1])
sage: Q.... | 3e9465a19c2ad91a024b8358d27693573c620d8d | 3,600,205 |
def _embedding_dimension_correlation(signal, dimension_seq, delay=1, **kwargs):
"""Return the Correlation Dimension (CD) for a all d in dimension_seq."""
CDs = np.zeros(len(dimension_seq))
for i, d in enumerate(dimension_seq):
CDs[i] = fractal_correlation(signal, dimension=d, delay=delay, **kwargs)[... | 1c12e8c4a2a0121d562b6ead93d27f1971e73417 | 3,600,206 |
def evaluate_body_part_of_response(body_combine_response, body, body_toggle):
""" Evaluate the body part of combine response """
tag = globe.config.body.non_priority_start + globe.config.body.non_priority_end
body_test_cases = []
if body_toggle == 'indexes':
body_test_cases = body_combine_respon... | 34faa27bea6bc27d9f8d7d757ea5dd76250e4d7c | 3,600,207 |
def find_related(item, item_type, related_type, address):
"""Returns a list of the entities of related_type which share a datastream with item"""
datastreams = related_datastreams(item['@iot.id'], item_type, address)
result = []
for related_datastream in datastreams:
related_result = get_entitie... | 9931812bf66330d5203bc9a1b06644811fc37f1e | 3,600,208 |
def getTasksets(config):
"""
Load task sets from xml
Return: list of names of task sets
"""
xml = etree.parse(config)
return [tag.attrib['name'] for tag in xml.findall('//tasks')] | b23269659471b9bec39495be36698bf868e24036 | 3,600,209 |
def do_eval(dataset=None, network=None, num_class=2, assessment_method="accuracy", load_checkpoint_path=""):
""" do eval """
if load_checkpoint_path == "":
raise ValueError("Finetune model missed, evaluation task must load finetune model!")
net_for_pretraining = network(albert_net_cfg, False, num_cl... | 29a0053d9e7f71ebd2afe831e98c426355361d0b | 3,600,210 |
import time
def query_view():
"""GET/POST HTTP handler for query route"""
if request.method == 'POST':
start = time.time()
query = request.form['query']
customer_id = request.form['customer-id']
page = int(request.form['page'])
df = services.run_query_to_df(customer_i... | d08e3bb7899bbdf858d7f210c4d3dd64ee0d594f | 3,600,211 |
def _construct_url(resource, action, params=None):
"""
Constructs rest of API url based on resource, action and parameters.
Multiple parameters must be a list.
Single parameters must be a single string
Internal usage
"""
final_url = '{}/{}'.format(resource, action)
if type(params) == ... | 38b85a4400e362887f965c0035b3a2b10e7ecce4 | 3,600,212 |
def _predict(model, data, proba=False, dtype=np.float32, **kwargs):
"""Inner predict routine.
Parameters
----------
model :
data : dask array of shape = [n_samples, n_features]
Input feature matrix.
proba : bool
Should method return results of predict_proba (proba == True) or pr... | 1fd2c86660c56bb148b15c407ced4c17e67a9990 | 3,600,213 |
def expm1(x):
"""!
@brief exponential - 1.0 helper
"""
return np.exp(x, dtype=np.longdouble) - 1.0 | bb4754a50891320ea1b7116604e5ff72422667e2 | 3,600,214 |
from typing import List
def _split_inputs(inputs: str, named_groups: dict) -> List[str]:
"""
Identify and split inputs for torch operations.
This assumes that no quotes, apostrophes, or braces show up in the operation string.
Currently, items in lists that are not within functions will be broken up in... | 5edc3c53fb9b7a19557504335eb04eb15dd3c932 | 3,600,215 |
def plot_chl(ax, val, zeta=None, v=None, num_levels=21, cmap=DIFF_r, title='', ssh_range=np.linspace(-0.05, 0.05, 11)):
"""
The function plots 2D data (originating from composites, e.g. surface chl) and configures the figure accordingly.
"""
# levels for ssh
levels = ssh_range
# init vmin and vmax
vmin, vmax = N... | f9266e8224d39ae9816a4f3304ed0ea64bf91f55 | 3,600,216 |
def autoenv_settings(prefix='AES'):
"""
Example with aes prefix and kwargs:
{
"mail.password": "1234567",
"mail.username": "marcelomoraes",
"mail.host": "smtp.pyramid.com"
}
environment: AES_MAIL_PASSWORD=foobar
:return {
"mail.password": ... | c36d6193b3db8f4b73e8a5e61df6599df470108a | 3,600,217 |
def get_analysis_file(filename: str) -> str:
"""
:param filename: The name of the file containing the source code.
:return: The expected name of the file containing the analysis.
"""
return filename.rsplit('.', 1)[0] + '.ll.cm' | 6a147b5bf69078dde81fdc72585907ece6c2f461 | 3,600,218 |
def fmt_type_name(data_type):
"""
Returns the JSDoc name for the given data type.
(Does not attempt to enumerate subtypes.)
"""
if is_user_defined_type(data_type):
return fmt_pascal('%s%s' % (data_type.namespace.name, data_type.name))
else:
fmted_type = _base_type_table.get(data_... | 947d676e20bd5f441a5c38394f46e9ab310b083c | 3,600,219 |
def mersenne_prime(n: int) -> int:
"""
Returns the nth Mersenne prime.
Conditions:
1) n > 0
:param n: natural number
:return: the nth Mersenne prime
"""
p = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281,
3217, 4253, 4423, 9689, 9941, 11213, 19937... | b93d495a3f4fac750b9c817ba6b742c6600f6845 | 3,600,220 |
import sqlite3
def delete_user(lid: str) -> bool:
"""
从user_list移除监听对象(注意: 该函数不用于群订阅操作)
:param lid: 愿望单url中的lid, 可以为唯一标识一个Amazon账号开设的愿望单
"""
with sqlite3.connect(DB_PATH) as connection:
success = False
cursor = connection.cursor()
# 查看主表中是否已有记录
user_exist = cursor.e... | 6def29ce0526bf59687187e157b15e1e452f59f8 | 3,600,221 |
def load_schema(schema_path):
"""
"""
with open(schema_path) as yaml_file:
"""
Get the path of the CommonwWorkflowLanguage schema and return a list of DICT
"""
schema_list = ryaml.load(yaml_file, Loader=ryaml.Loader)
return schema_list | 9b24a34a5280892fa5c73e04f40bb6dbd03ae50b | 3,600,222 |
def cutoutbbox(image,psf,cat):
""" Get image cutout that covers that catalog of stars."""
ny,nx = image.shape
hpsfpix = psf.npix//2
xmin = np.min(cat['x'])
xmax = np.max(cat['x'])
ymin = np.min(cat['y'])
ymax = np.max(cat['y'])
xlo = np.maximum(int(np.round(xmin)-hpsfpix),0)
xhi... | fcb6e5889560d88a0b3745f9d185d30d2997374a | 3,600,223 |
import os
def load_tests(loader, tests, pattern):
"""Provide a TestSuite to the discovery process."""
NEEDED_ENV = ["AODH_SERVICE_URL", "GNOCCHI_SERVICE_URL",
"HEAT_SERVICE_URL", "NOVA_SERVICE_URL",
"GLANCE_IMAGE_NAME", "ADMIN_TOKEN"]
for env_variable in NEEDED_ENV:
... | 3f2f2e8dd10b4a9490ecc88583f091d9bb4232e8 | 3,600,224 |
def wsgi_xmlrpc_1(environ, start_response):
""" The main OpenERP WSGI handler."""
if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'].startswith(XML_RPC_PATH_1):
length = int(environ['CONTENT_LENGTH'])
data = environ['wsgi.input'].read(length)
params, method = xmlrpclib.load... | d8703d2406e91553d0c78a22770c13038d15c192 | 3,600,225 |
def _prep_server_detail(compute_client, image_client, server):
"""Prepare the detailed server dict for printing
:param compute_client: a compute client instance
:param server: a Server resource
:rtype: a dict of server details
"""
info = server._info.copy()
server = utils.find_resource(com... | 04200ff1e0d28d358ebbc77c606091787cc062ee | 3,600,226 |
def unassign_users(request, domain):
"""
Unassign all users from their locations. This is for downgraded domains.
"""
for user in get_users_assigned_to_locations(domain):
if user.is_web_user():
user.unset_location(domain)
elif user.is_commcare_user():
user.unset_... | 1b113518627b7c50003c26833571eb6f827912d3 | 3,600,227 |
def psnr(y_true, y_pred):
"""Peak signal-to-noise ratio averaged over samples and channels."""
mse = K.mean(K.square(y_true*255 - y_pred*255), axis=(-3, -2, -1))
return K.mean(20 * K.log(255 / K.sqrt(mse)) / np.log(10)) | 294a55dac0d5b59b34df1df449c956fa7c4be5b7 | 3,600,228 |
from typing import Optional
import asyncio
async def find_device(
name: Optional[str] = None,
service: str = PYBRICKS_SERVICE_UUID,
timeout: float = 10,
) -> BLEDevice:
"""Finds a BLE device that is currently advertising that matches the
given parameters.
Arguments:
name:
... | e7015fa1ea8fc4dcc3b63b4091179a2c6d82f229 | 3,600,229 |
def pol_energy(aa, slr, ecc):
"""
Calculate energy for polar Kerr case.
Parameters:
aa (mpf): spin parameter (0, 1)
slr (mpf): semi-latus rectum [6, inf)
ecc (mpf): eccentricity
Returns:
En (mpf): energy
"""
try:
prec = mp.prec
mp.prec += 10
... | a3c53efa5878f2e0430af2d3b929d10edf1ba103 | 3,600,230 |
import numpy
def run_kmeans(find_closest_centroids_func, compute_centroids_func, x_array, centroids, max_iters=10, plot_progress=False):
"""
Runs the K-means algorithm.
Parameters
----------
x_array : array_like
The data set of size (m, n). Each row of x_array is a single example of n dim... | 3737f04be7305d2ddf3d3ae43fdd91c20d0005d5 | 3,600,231 |
def get_info_block():
"""Return Div object."""
text = """
<h4>Info links</h4>
<ul>
<li><a href="https://docs.bokeh.org/en/latest/docs/user_guide/tools.html" target="_blank">Bokeh toolbar info</a></li>
<li><a href="https://github.com/sharksmhi/sharkpylib/tree/master/sharkpylib/qc" target="_bl... | 3bb188bc24b74c6673dea86a4d572481d7cf400a | 3,600,232 |
def __determineVersion__():
"""Check if required '_package_version_' or required '_platform_' has been nominated by callee/importer
This is variables declared within the importing script, eg:
_foo_version_ = '1.1.1.1.1' #where the level of points is the level of accuracy required
_python_version_ = '2.2... | 475c1dc5418a174369c5d8832b48e03056c61edd | 3,600,233 |
def load_rule_and_env(rule_dir_path, env_yaml, product=None):
"""
Loads a rule and returns the combination of the RuleYAML class and
the corresponding local environment for that rule.
"""
# First build the path to the rule.yml file
rule_path = get_rule_dir_yaml(rule_dir_path)
# Load rule c... | 383a0e3b9d4660d22e9d398d669d2fcd3acadfec | 3,600,234 |
def validate_3octets(value):
"""
Validate 3-octets string.
:param value:
:return:
"""
is_valid = False
try:
is_valid = int(value, base=16) >= 0 and len(value) == 6
except ValueError:
is_valid = False
except TypeError:
is_valid = False
return is_valid | 10e8240398ccde624e6bcee702acaa319289102a | 3,600,235 |
from scipy.signal import find_peaks
def _peaks(meta):
"""
Find peaks of signals
"""
peaks, _ = find_peaks(meta.iloc[:,0].values)
return meta.iloc[peaks,:] | 44f265040aba80ade6b26a782e330e3b14e3bc83 | 3,600,236 |
import logging
import sys
def save_seed_to_list(url_list_file):
"""Save seed uri address.
Save the seed html address into unique set as well as queue.
Args:
url_list_file: The file address which contains seed uri.
Returns:
Two Objects, (unique_html_queue, unique_html_set).
T... | 68ed2d3ffba32b46c3514f692df56143fd4e8f09 | 3,600,237 |
from typing import Tuple
from pathlib import Path
from typing import Optional
import argparse
def parse_arguments() -> Tuple[str, Path, Optional[int]]:
"""Parse command line arguments
Returns:
Tuple[str, Path, Path]: (identifier, path to save log, path to VLC)
"""
parser = argparse.ArgumentPa... | cf3e7528177510fbfdcdd3b615010f4ffc2e59b9 | 3,600,238 |
def add_neologisms_to_db(neolist,neosinfo, lang):
""" add neologisms to database for web interface validation """
log.info("Saving neologisms to database" + str(neolist) + ' : and info : ' + str(neosinfo))
#for neo in neolist:
# log.info("Saving neologism : " + neo + " : " + str(len(neolist[neo])) +... | e3a97f22ef2fb4dacd636d826dff2ec952fd714b | 3,600,239 |
def _isnotebook():
"""
Determine if code is being run from a Jupyter notebook
``_isnotebook`` is True if running Jupyter notebook, else False
:references:
- https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-
is-executed-in-the-ipython-notebook/39662359#39662359
... | f30988d3b2d719a8c125b2e9eb22281552ddd342 | 3,600,240 |
def detect_timestep(data):
"""
Get the time steps present in the loaded data
"""
same_trace = data.shift(-1).trace_id == data.trace_id
dts = data.shift(-1).time - data.time
dts[~same_trace] = np.nan
return dts.mean(), dts.min(), dts.max() | 805c907cf08d96f0b677fc0263108f422fc93a84 | 3,600,241 |
from DB.pgSQL import PgSQL
from SMail import smail
import sys
import traceback
def event1(data=None):
"""
>>> from DB.pgSQL import PgSQL
>>> db = PgSQL()
procpid: 3945
>>> query = ""SELECT c.id AS cliente_id, v.placa, c.nombre1, c.nombre2, c.apellido1, c.apellido2,
... | c61c52f88619bb1addaf62d11e090b82193c63ed | 3,600,242 |
from typing import Tuple
import torch
def get_semantic_one_hot(
input: Tensor,
n_classes: int,
normalize: bool = False,
input_range: Tuple[float, float] = (-1.0, 1.0),
) -> Tensor:
"""
Converts a tensor of indices to a one-hot tensor.
Args:
input: (N, 1, H, W) semantic label, rang... | 93e1f2b79d38d4abcfa206dbf9c6553bc81d6179 | 3,600,243 |
def _viewer_urls(spectra, zoom=13, layer='ls-dr9'):
"""Return legacysurvey.org viewer URLs for all spectra.
Note: `layer` does not apply to the JPEG cutout service.
"""
u = "https://www.legacysurvey.org/viewer/jpeg-cutout?ra={0:f}&dec={1:f}&zoom={2:d}"
v = "https://www.legacysurvey.org/viewer/?ra={... | 6fe781b92f929f9265d464935929490b67a6e9a7 | 3,600,244 |
def jsdate(d):
"""formats a python date into a js Date() constructor.
"""
try:
return "new Date({0},{1},{2})".format(d.year, d.month - 1, d.day)
except AttributeError:
return 'undefined' | 0c8331f928cf26e4cac7663dd6619c62cfff0fae | 3,600,245 |
from unittest.mock import Mock
import json
def fakeQnAMakerAPIreplaceCallBroken(method, url, headers, data: str = ""):
"""Faked API return data based on Method and URL
second call breaks
"""
if method == "GET" and url == "https://localhost/dest/knowledgebases/456":
returnvalue = Mock()
... | df7fb2e3e0a86aee66759afdd5e02fe3962f465a | 3,600,246 |
def get_component(request):
"""Get Android Component."""
data = {}
try:
env = Environment()
comp = request.POST['component']
bin_hash = request.POST['hash']
if is_attack_pattern(comp) or not is_md5(bin_hash):
return invalid_params()
comp = env.android_comp... | da6f4d0a0a2285cc6ff051e9d912e34cbe3370c8 | 3,600,247 |
import typing
import asyncio
import functools
def run_sync(
target: typing.Callable[..., typing.Any],
*args,
timeout: int = 10,
new_loop: bool = False,
**keywords,
) -> typing.Any:
"""Run async tasks synchronously with a timeout
:param target:
:param args:
:param timeout:
:par... | 6c3af5a29e79d2e5fcd2b4422895a5a761e7295a | 3,600,248 |
def data_merge(data_list, path):
"""merge seperated sets for trainning set.
:param data_list: a list of the seperated dataset.
:param path: the path of the generated files.
"""
if len(data_list) != 0:
test_list = data_list.pop(0)
num_list = range(len(data_list))
comb_list = list(comb... | 236e81e46f1520f36818d978c34a08b267b0284e | 3,600,249 |
import random
def mutate(chromosome):
"""
Pick a random bit to mutate by XOR and shifting the selected bit. This
ensures diversity in the population.
"""
altered_bit_position = random.randint(0, 31)
mutation = chromosome ^ (1 << altered_bit_position)
return mutation | ff93fb19d7d83c558172d005fbd140284e2b16c2 | 3,600,250 |
from typing import Sequence
from re import T
import os
import joblib
def to_local(sequence: Sequence[T], path: str, n_jobs: int = 4) -> Local[T]:
"""
Download a sequence of pickleable objects to a local path.
Args:
sequence: pickleable objects to dump locally
path: local directory, will b... | 6668d55d47151e68b76108998c83e5c01def9844 | 3,600,251 |
from azure.cli.core.auth.identity import ServicePrincipalAuth
def login(cmd, username=None, password=None, service_principal=None, tenant=None, allow_no_subscriptions=False,
identity=False, use_device_code=False, use_cert_sn_issuer=None, scopes=None, client_assertion=None):
"""Log in to access Azure sub... | 6eee8eb66fe99a9fcaa946e8b927134900956770 | 3,600,252 |
def _calculate_transform_between_points(target_points, source_points):
"""Calculate a transform that maps matched sets of points.
Args:
target_points (np.ndarray): A set of matched points from the target image, of shape (n_samples, n_dimensions).
source_points (np.ndarray): A set of matched poi... | 6a40ca20a7abe11cf79f9f034f0b83e443ebe9ca | 3,600,253 |
import torch
def create_multimodal_gan_siamese_evaluator(
generator,
discriminator,
metrics=None,
device=None,
non_blocking=False,
prepare_batch=prepare_batch_siamese,
output_transform=output_transform_evaluator_siamese,
prepare_batch_variables=prepare_multimodal_batch_variables,
):
... | 213b6c30fbd37e3e460d3e5bb9c59fef17bccbba | 3,600,254 |
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
cnt = 0
for s in dna :
if s == nucleotide :
cnt... | 855c29cca451f635291f4aa80fd3814f21218539 | 3,600,255 |
import torch
import functools
def count_flops_params(model, x, custom_ops=None, verbose=True, mode='default'):
"""
Count FLOPs and Params of the given model. This function would
identify the mask on the module and take the pruned shape into consideration.
Note that, for sturctured pruning, we only ide... | 706b741d25ff49df3c70e5b84f754b7c5cf4422d | 3,600,256 |
def impulse(iir, ts, n):
"""
Computa la respuesta al impulso de un filtro digital IIR
en punto fijo.
El filtro se representa como una secuencia ordenada de
etapas de segundo orden, cada una representada por los
coeficientes de su ecuación en diferencias más una
ganancia: [b0, b1, b2, a1, a2... | 8c97da341096fe8695164b8cc5ae6387db89d773 | 3,600,257 |
import os
def convergence_plot(sample, expected, qoi_name, absolute_deviation=False, save=False):
"""
This function is a custom-made convergence plot for some Monte-Carlo
sample.
Parameters
----------
sample : Series, 1d-array, or list.
A vector of random observations.
expected : ... | 271d8493b0a7d4da905aaa1d07b28347b8b4bf98 | 3,600,258 |
def str2int(v):
"""
Convert string to boolean to integer
"""
return int(str2bool(v)) | 420c6d18e1ad234ff3ac850ba987767dbba64e07 | 3,600,259 |
def fixed_point_sample(point_cloud, num_points, seed=0):
"""
:param point_cloud: (B, C, N) Point cloud data.
:param num_points: Number of samples.
:param seed: if you want fixed, set seed.
:returns: (B, C, num_points) Sampled point cloud. /
(B, num_points) Sampled point cloud indic... | 64150d4d823cc5f3d19f13ca2c5b755073662755 | 3,600,260 |
def get_experimental_pdb_info(pdbids, site="rcsb"):
"""
returns list of tuples (pdb_id, resolution, rwork, rfree) and dict
pdbid: (resolution, rwork, rfree)
"""
rlist = []
rdict = {}
assert site in ["rcsb"]
pdb_list = ",".join(pdbids)
url = web_urls.get(site).format(pdb_list=pdb_list)
data = libtbx.... | 1d38b0263914a32e8ad047ab738860aa42174a74 | 3,600,261 |
from datetime import datetime
from typing import OrderedDict
import pickle
def verification(config, output_file=None, use_cf6=True, use_climo=True, force_rain_quantity=False):
"""
Generates verification data from MesoWest and saves to a file, which is used to train the model and check test
results.
:... | 211f37e6cc938e869811dba93e88f4e2d83be613 | 3,600,262 |
def get_openapi_spec():
"""Get OpenAPI Spec."""
return jsonify(current_app.config['OPENAPI_SPEC']) | 1085fa157bdaccb624bf25d7af38ac63232c522a | 3,600,263 |
def AXIS_FILTER(arg_value):
"""Only keeps ints in the range [-1, limits.MAX_NUM_DIMENSIONS)."""
return (arg_value.type is int and
-1 <= arg_value.value < limits.MAX_NUM_DIMENSIONS) | 7095f40659a82e91c5a3afb10886a910c515ec1f | 3,600,264 |
def pairwise_diagonal_interactions_indices(num_qubits):
"""List of 1- and 2- qubit diagonal interaction terms."""
all_ints = pairwise_interactions_indices(num_qubits)
return [interaction for interaction in all_ints if is_diagonal_interaction(interaction)] | 936ff315430a35b8fe7351ca57876459efd521f5 | 3,600,265 |
def mileage_format(value):
""" Custom formatting for mileage. """
return "{:,} miles".format(value) | 056f5fbf5d291ac892bd8f2c16cda16937f758da | 3,600,266 |
from typing import Union
from pydantic_factories import ModelFactory
import inspect
def get_settings(model: Union[Model, ModelFactory]) -> Settings:
"""Get the parameters of a SAX model function"""
signature = inspect.signature(model)
settings: Settings = {
k: (v.default if not isinstance(v, dic... | 2d2a59f1bc21f574e13008fd9b2f18fb669abbbf | 3,600,267 |
def merge_patches(patches=None, image_size=(0, 0), patch_size=(0, 0), offset_row_col=None):
"""
Merge different pieces of image to form a full image. Overlapped regions are averaged.
:param patches: List of all patches to merge in order (left to right).
:param image_size: Full image size
:param patc... | 37dc011b16e61d12ae18e9e39cb394c5a6472809 | 3,600,268 |
import click
def init():
"""Return top level command handler."""
@click.command()
@click.argument('aliases')
def check(aliases):
"""Check aliases."""
subproc.load_packages(aliases.split(':'))
for exe in subproc.get_aliases():
success = True
fullpath = s... | 6bfe123a98ff997b4c2f1de960b77ac7748e3236 | 3,600,269 |
def to_TProfile3D(
fName,
fTitle,
data,
fEntries,
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fTsumwy,
fTsumwy2,
fTsumwxy,
fTsumwz,
fTsumwz2,
fTsumwxz,
fTsumwyz,
fTsumwt,
fTsumwt2,
fSumw2,
fBinEntries,
fBinSumw2,
fXaxis,
fYaxis,
fZaxis,... | f1d0a6eaa41360bb7675ed5e7784a8701f7245f6 | 3,600,270 |
def sol_dec(day_of_year):
"""
Calculate solar declination from day of the year.
Based on FAO equation 24 in Allen et al (1998).
:param day_of_year: Day of year integer between 1 and 365 or 366).
:return: solar declination [radians]
:rtype: float
"""
return 0.409 * np.sin(((2.0 * np.pi ... | ebe21378383a28881804609f9e0f87e309937d4f | 3,600,271 |
def run_sync_mock(_config, _cmd):
"""mock of RemoteCmd.run_sync()"""
return lib.remote_cmd.RemoteCmd(None, None, None, 0) | d2eda62c0238d0447f4228f2d466cbb4da345a80 | 3,600,272 |
from typing import List
def drain_sock(sock: SubSocket, wait_for_one: bool = False) -> List[capnp.lib.capnp._DynamicStructReader]:
"""Receive all message currently available on the queue"""
ret: List[capnp.lib.capnp._DynamicStructReader] = []
while 1:
if wait_for_one and len(ret) == 0:
dat = sock.rece... | 4f9a51bd2e436ae2ebbe77f18b2bb81594f8583e | 3,600,273 |
def get_rows_from_times(mission_table, times):
"""
Examples
--------
>>> start = np.arange(2, 4)
>>> end = np.arange(3, 5)
>>> labels = ['AA', 'BB']
>>> mission_table = QTable({'mjdstart': start, 'mjdend': end, 'label': labels})
>>> times = np.array([1.5, 2.1, 3.5, 4.5, 5.5])
>>> ta... | 7f1b59eef11d70b94795efee153e1cea9ead70a3 | 3,600,274 |
def api_docs(request):
"""Api Docs Route."""
context = {
'title': 'REST API Docs',
'api_key': api_key(),
'version': settings.MOBSF_VER,
}
template = 'general/apidocs.html'
return render(request, template, context) | 09fb9e1659bb75ab8c3a189856f83ed96b592bae | 3,600,275 |
def _list(key: str, vals: dict) -> list:
"""Get a key from a dictionary of values and ensure it is a list."""
result = vals.get(key, [])
if not isinstance(result, list):
result = [result]
return result | cf8a5da580dc4d95f83f18a92f82f646be5c4cb3 | 3,600,276 |
def abundance(n):
"""Returns the difference between the sum of the positive
proper divisors of a number and the number.
Examples
========
>>> from sympy.ntheory import abundance, is_perfect, is_abundant
>>> abundance(6)
0
>>> is_perfect(6)
True
>>> abundance(10)
-2
>>> ... | af119159a8f62f0c62cccd9a30864ec539b54204 | 3,600,277 |
def structureSvInstance(stackedLine, tabSpace, alignCol, alignCom):
"""
This function restructures an input "stacked line" module declaration
from a .sv file. Expecting a module declaration on one line in the form
of:
blockName#(param1,param2,param3,...)(port1,port2,port3,...)
or:
blockNam... | 8939cb6cbd2115b8b6bae3866bd4be78d32e1954 | 3,600,278 |
def flatten(array):
"""Convierte un array de habilidades en dataframe.
Esta funcion convierte un array de tipo:
[
"Hola - Adios - Como - Estas",
"Hola - Como - Estas",
"Hola - Adios - Como",
"Adios - Como - Estas",
"Hola - Adios",
"Hola",
]
Y regresa un dataframe de tipo:
hab1, hab2, h... | 72d0d1c45cde76a3fb9238f2c77c2be98a0de497 | 3,600,279 |
import urllib
def unquote(string):
"""Decodes a URL-encoded string.
:param str string: the string to decode
:return str: the decoded ``string``
.. note::
This is a convenient shortcut for ``urllib.parse.unquote``.
"""
# TODO deprecated?
return urllib.parse.unquote(string) | 36deea9ddac7677409744b2e98499a1a87041c79 | 3,600,280 |
import subprocess
def shell_call(command, **kwargs):
"""Calls shell command with parameter substitution.
Args:
command: command to run as a list of tokens
**kwargs: dirctionary with substitutions
Returns:
whether command was successful, i.e. returned 0 status code
Example of usage:
shell_ca... | 21d376e6d488c54396127270485beb890a67732c | 3,600,281 |
def load_vaccine_data():
""" Function to load data
param DATA_URL: data_url
return: pandas dataframe
"""
DATA_URL = 'data/df_vaccine.csv'
data = pd.read_csv(DATA_URL)
data['date'] = pd.to_datetime(data['date']).dt.strftime('%Y-%m-%d')
return data | d7195714dd1f11b1595be0081131aacbdab729b9 | 3,600,282 |
def linkify_with_outgoing(text, nofollow=True, only_full=False):
"""Wrapper around bleach.linkify: uses get_outgoing_url."""
callbacks = [linkify_only_full_urls] if only_full else []
callbacks.append(linkify_bounce_url_callback)
if nofollow:
callbacks.append(bleach.callbacks.nofollow)
return... | bda4256a6a8a09403e2002a87280aa4a8db617a0 | 3,600,283 |
import ast
def to_annotation(typ):
"""
Converts the typ to an annotation
:param typ: A string representation of the type to annotate with. Else return give identity.
:type typ: ```Union[str, AST]```
:return: The annotation as a `Name` (usually) or else some more complex type
:rtype: ```AST``... | 7a2488eda282376b4cbc028e157e368519d8c55c | 3,600,284 |
from sklearn.neighbors import KNeighborsClassifier
def sc_knn(input_dict):
"""
:param input_dict (input): {u'n_neighbors': u'5', u'weights': u'uniform', u'algorithm': u'auto'}
:param n_neighbors : int, optional (default = 5). Number of neighbors to use by default for k_neighbors queries.
:param weigh... | 3b36ceb716b48de6c0e880ff072965acfe61a029 | 3,600,285 |
def contrast_color(hex_color):
"""
Util function to know if it's best to use a white or a black color on the foreground given in parameter
:param str hex_color: the foreground color to analyse
:return: A black or a white color
"""
r1 = int(hex_color[1:3], 16)
g1 = int(hex_color[3:5], 16)
... | 470f713af48673d7b9fb8aa3bb30f7e1498da9b5 | 3,600,286 |
def to_equity_through_by_id(uni_id: str) -> dict:
"""
根据统一社会信用代码列表,返回股权穿透信息
:param uni_id:
:return:
"""
result = {'uni_id': uni_id, 'equity': None}
method_id = 'c2e25afe-65eb-4990-a609-110ffdf5963e'
params = {
'keyWord': uni_id,
'level': '4'
}
task = to_task_inv... | 4869fec237f9ef33ffc1cb46bcf4e4bafde54e15 | 3,600,287 |
from typing import Union
from typing import List
def _toPhonemeList(phoneList: Union[PhonemeList, List[str]]) -> PhonemeList:
"""Utility function to unify the input to be PhonemeList"""
if isinstance(phoneList, list):
return PhonemeList(phoneList)
elif isinstance(phoneList, PhonemeList):
r... | 7fe961884cda936a585ebd375aa6715dd3556424 | 3,600,288 |
def search(board):
"""
Return score and best move, relative to board.turn.
The search is an implementation of a depth-unlimited
Negamax-algorithm, a variant of Minimax.
"""
# If game is over we know the score.
decided, score = board.is_decided_and_score
if decided:
# tb[board.a... | a4d1c70221703f2dc1a2f97d8a98f2e46559aab4 | 3,600,289 |
def project_lookup(auth, name_or_id):
"""Tries to find a single project by name or ID. Raises an error if
none or multiple projects found."""
try:
return keystone_project(auth, name_or_id)
except HTTPError:
# failed lookup assuming it was an id, must be a name?
pass
projects... | 07ff1a3e039cf4aabc836d3b0c66fdb3f4b05a9f | 3,600,290 |
import subprocess
def link(*objects):
"""Links multiple LLVM bitcode files into a single file.
Args:
objects: The bitcode files to link.
Returns:
The path to the linked file.
"""
command = [shared.LLVM_LINK] + list(objects)
with get_temp_file('.bc') as out: ret = subprocess.call(command, stdout=... | 6ea35abb4d6dc8abae317c954079d32c60de406a | 3,600,291 |
def get_ips(filename: str) -> list:
""" Reads ips from a list of files """
ips = []
with open(filename, 'r') as f:
ips = f.read().splitlines()
return ips | 6dfd326dc57df8a8297cd27a0d3d01fbe11db3f4 | 3,600,292 |
def remove_corrupted_frames(frame_list, min_pix=18000):
"""
Remove frames that are identified as corrupted, i.e., those with pixel
values < min_pix in any image extension. Return a list of candidate
"good" frames.
"""
if getJobName() == 'scan_mode_analysis_BOT':
return frame_list
go... | 49a49c8f665f39a628852af96f7968c61a9176f6 | 3,600,293 |
def get_vlan_member(dut, vlan_list=[], cli_type="click"):
"""
To Get VLANs vs list of Members.
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param dut:
:param vlan_list:
:param cli_type:
:return:
"""
vlan_val = {}
vlan_li = map(str, vlan_list) if isinstance(vlan_list, l... | 82dc830ba73da93a2f95c47bb3ca44c84dae93b2 | 3,600,294 |
import sys
def check_source_target(db_source_atoms, res_target_atoms, dbatoms):
"""
several checks if the atoms in the dsr command line are consistent
:param db_source_atoms: ['C1', 'O1', 'C2', ...]
:param res_target_atoms: ['C1', 'Q2', 'C3_2', ...]
:param dbatoms: [['C1', 1, '-0.0014... | db592ad544a20f536b425409ef1a0d8ddbfb1c42 | 3,600,295 |
def all_packages(request, verbose=False):
"""List all packages"""
if verbose:
packages = request.db.summary()
else:
packages = request.db.distinct()
i = 0
while i < len(packages):
package = packages[i]
name = package if isinstance(package, str) else package["name"]
... | 76103ea29f787b7cd28ff8bc9aca37daea603432 | 3,600,296 |
def variances_scaled_to_real(scaled_variances, bounds):
"""Convert variance in scaled dimensionless values to physical units
Parameters
----------
scaled_variances : array_like, shape=(n,m)
Input variances (scaled)
bounds : array_like, shape=(m,2)
Bounds to scale `scaled_variances`.... | 03c397658c43e2516aeddfff51314ae78c76c672 | 3,600,297 |
def joindicts(dest, *dictlist, prefix=''):
"""Merges one or more dictionaries into dest recursively.
Dictionaries are merged, lists are merged. Scalars and strings are ignored.
Returns the generated result.
To merge with overwrite, use the native dict update method.
"""
result = dest
for in... | 678a6fc5fc8c7b9bbd0980900760f8693d734d7c | 3,600,298 |
from typing import Callable
from typing import Any
def use_update_form(valid_user_api_client: APIClient):
"""
Uses the default edit form and view for a model to update an object to have
the passed new data and returns the new version of the object.
The ``new_data`` dictionary should contain callable ... | c844fb9a9def9c9e842623a0b063af3c24fb267a | 3,600,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.