content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
import logging
def _GetSharedLibraryInHost(soname, sosize, dirs):
"""Find a shared library by name in a list of directories.
Args:
soname: library name (e.g. libfoo.so)
sosize: library file size to match.
dirs: list of directories to look for the corresponding file.
Returns:
host libr... | 6ed492053f78fd76fdbb1deab5bd557d13e650de | 3,653,300 |
import os
def check_n_jobs(n_jobs: int) -> int:
"""Check `n_jobs` parameter according to the scikit-learn convention.
Parameters
----------
n_jobs : int, positive or -1
The number of jobs for parallelization.
Returns
-------
n_jobs : int
Checked number of jobs.
"""
... | a7eca51f4431eda45c574844ea6e4576de13b1fe | 3,653,301 |
def validateFilename(value):
"""
Validate filename.
"""
if 0 == len(value):
raise ValueError("Name of SimpleGridDB file must be specified.")
return value | b8b3c23772437c1ddca597c44c66b239955a26fb | 3,653,302 |
def readPNM(fd):
"""Reads the PNM file from the filehandle"""
t = noncomment(fd)
s = noncomment(fd)
m = noncomment(fd) if not (t.startswith('P1') or t.startswith('P4')) else '1'
data = fd.read()
ls = len(s.split())
if ls != 2 :
name = "<pipe>" if fd.name=="<fdopen>" else "Filename = {0}".format(fd.nam... | c03633069b2b8f3302a8f28e03f4476ac7478055 | 3,653,303 |
def gdxfile(rawgdx):
"""A gdx.File fixture."""
return gdx.File(rawgdx) | 6138077fa959cecd4a7402fe3c7b6b7dee5d99f9 | 3,653,304 |
import typing
from typing import Union
from typing import Dict
from typing import Any
def AppBar(
absolute: bool = None,
app: bool = None,
attributes: dict = {},
bottom: bool = None,
children: list = [],
class_: str = None,
clipped_left: bool = None,
clipped_right: bool = None,
col... | 51de728b0d2935161bd040248d94b3d15aba5d16 | 3,653,305 |
import os
def check_file(filename):
"""Check if "filename" exists and is a file.
Returns:
True if file exists and is a file.
False if filename==None or is not a file.
"""
file_ok = True
error_mssg = ""
if(filename == None):
error_mssg = "Error: file is missing."
... | 4a9e9284648c5d6222a44f1156b198f6e64dd409 | 3,653,306 |
def conjoin(*funcs):
"""
Creates a function that composes multiple predicate functions into a single predicate that tests
whether **all** elements of an object pass each predicate.
Args:
*funcs (callable): Function(s) to conjoin.
Returns:
Conjoin: Function(s) wrapped in a :class:`C... | 835c2962bcc3a2c3dcf0bf19649221aebb73b63b | 3,653,307 |
import hashlib
def calculate_file_sha256(file_path):
"""calculate file sha256 hash code."""
with open(file_path, 'rb') as fp:
sha256_cal = hashlib.sha256()
sha256_cal.update(fp.read())
return sha256_cal.hexdigest() | bfa7a43516e51a80ccd63ea3ace6be6e5e9dd2c0 | 3,653,308 |
from collections import OrderedDict
import warnings
def select_columns_by_feature_type(df, unique_value_to_total_value_ratio_threshold=.05, text_unique_threshold=.9,
exclude_strings = True, return_dict = False, return_type='categoric'):
""" Determine if a column fits into one of the followin... | 6335152405bc175805e8484ff23f58d4f6ce6f6a | 3,653,309 |
def _Counter_random(self, filter=None):
"""Return a single random elements from the Counter collection, weighted by count."""
return _Counter_randoms(self, 1, filter=filter)[0] | 95dc2ab7857b27a831b273af7dba143b8b791b27 | 3,653,310 |
def EnsureAndroidSdkPackagesInstalled(abi):
"""Return true if at least one package was not already installed."""
abiPackageList = SdkPackagesForAbi(abi)
installedSomething = False
packages = AndroidListSdk()
for package in abiPackageList:
installedSomething |= EnsureSdkPackageInstalled(packa... | b43ee6094dc4cd8f71ec1319dbd5bd32d272b55a | 3,653,311 |
def dataframe_like(value, name, optional=False, strict=False):
"""
Convert to dataframe or raise if not dataframe_like
Parameters
----------
value : object
Value to verify
name : str
Variable name for exceptions
optional : bool
Flag indicating whether None is allowed
... | 016ffcda7050ac639d04522a666526753eb52a84 | 3,653,312 |
def pcaFunc(z, n_components=100):
"""
PCA
"""
pca = PCA(n_components=100)
pca_result = pca.fit_transform(z)
re = pd.DataFrame()
re['pca-one'] = pca_result[:, 0]
re['pca-two'] = pca_result[:, 1]
re['pca-three'] = pca_result[:, 2]
# Not print Now
# print('Explained variation pe... | 1dda1542a045eab69aab5488be2c754bde555311 | 3,653,313 |
def choose_optimizer(discriminator, generator, netD, netG, lr_d=2e-4, lr_g=2e-3):
"""
Set optimizers for discriminator and generator
:param discriminator: str, name
:param generator: str, name
:param netD:
:param netG:
:param lr_d:
:param lr_g:
:return: optimizerD, optimizerG
"""... | b3784d98c1743c10e3d1e9bca76288bd45c9c99e | 3,653,314 |
def prod(*args: int) -> int:
"""
This function is wrapped and documented in `_polymorphic.prod()`.
"""
prod_ = 1
for arg in args:
prod_ *= arg
return prod_ | eec30bf6339280173e0e2fa517558e6a452b9c37 | 3,653,315 |
def field_value(field):
"""
Returns the value for this BoundField, as rendered in widgets.
"""
if field.form.is_bound:
if isinstance(field.field, FileField) and field.data is None:
val = field.form.initial.get(field.name, field.field.initial)
else:
val = field.dat... | 5dc3792e0d6cd2cb6173c2479a024881f80a6d2b | 3,653,316 |
def distances(p):
"""Compute lengths of shortest paths between all nodes in Pharmacophore.
Args:
p (Pharmacophore): model to analyse
Returns:
dist (numpy array): array with distances between all nodes
"""
if not isinstance(p, Pharmacophore):
raise TypeError("Expected Pharmac... | 40e77672ad9447ed4c7b69b14aadbc2f125cb499 | 3,653,317 |
def initial_data(logged_on_user, users_fixture, streams_fixture):
"""
Response from /register API request.
"""
return {
'full_name': logged_on_user['full_name'],
'email': logged_on_user['email'],
'user_id': logged_on_user['user_id'],
'realm_name': 'Test Organization Name'... | b85eafbf359a6c34decc866f4d1fbb494ac907f8 | 3,653,318 |
def affine_relu_backward(dout, cache):
"""
Backward pass for the affine-relu convenience layer
"""
fc_cache, relu_cache = cache
da = relu_backward(dout, relu_cache)
dx, dw, db = affine_backward(da, fc_cache)
return dx, dw, db | 201f37d4d6ac9e170a52766f41d892527681a3d1 | 3,653,319 |
from typing import List
def create_initial_population() -> List[Image]:
"""
Create population at step 0
"""
return [random_image() for _ in range(POP_SIZE)] | 895632869962014695382e34961f6e6636619fbe | 3,653,320 |
from typing import Any
def adapt(value: Any, pg_type: str) -> Any:
"""
Coerces a value with a PG type into its Python equivalent.
:param value: Value
:param pg_type: Postgres datatype
:return: Coerced value.
"""
if value is None:
return None
if pg_type in _TYPE_MAP:
re... | f040cd6fbf5aa8a396efa36879b83e13b5d89da7 | 3,653,321 |
import uuid
from datetime import datetime
def createPREMISEventXML(eventType, agentIdentifier, eventDetail, eventOutcome,
outcomeDetail=None, eventIdentifier=None,
linkObjectList=[], eventDate=None):
"""
Actually create our PREMIS Event XML
"""
eventX... | 25836d6cd4b40ad672ca3438ba3583cd147a52bb | 3,653,322 |
def get_primary_key(conn, table, columns):
""" attempts to reverse lookup the primary key by querying the table using the first column
and iteratively adding the columns that comes after it until the query returns a
unique row in the table.
:param
conn: an SQLite connection object
... | 3b74f85214e89af322fd1da1e6c8de1eba4f4ca7 | 3,653,323 |
def redirect_to_docs():
"""Redirect to API docs when at site root"""
return RedirectResponse('/redoc') | f284167e238845651eedaf3bcc1b85e64979df6a | 3,653,324 |
def init_neighbours(key):
"""
Sets then neighbouring nodes and initializes the edge count to the neighbours to 1
:param key: str - key of node to which we are searching the neighbours
:return: dictionary of neighbours with corresponding edge count
"""
neighbours = {}
neighbouring_nodes = gra... | 6fa49ffa75051eeca9bd1714ec3e4817ef429bad | 3,653,325 |
def computeNumericalGradient(J, theta):
""" Compute numgrad = computeNumericalGradient(J, theta)
theta: a matrix of parameters
J: a function that outputs a real-number and the gradient.
Calling y = J(theta)[0] will return the function value at theta.
"""
# Initialize numgrad with zeros
numgrad = np.zer... | 2d4e4ed190bbb0c5507ecb896c13d33fcd7aa1b5 | 3,653,326 |
def get_error_msg(handle):
"""
Get the latest and greatest DTrace error.
"""
txt = LIBRARY.dtrace_errmsg(handle, LIBRARY.dtrace_errno(handle))
return c_char_p(txt).value | 73d945367e3003beb29505852004f0c71b205873 | 3,653,327 |
def sigma_hat(frequency, sigma, epsilon=epsilon_0, quasistatic=False):
"""
conductivity with displacement current contribution
.. math::
\hat{\sigma} = \sigma + i \omega \\varepsilon
**Required**
:param (float, numpy.array) frequency: frequency (Hz)
:param float sigma: electrical con... | 17aee0f33ba8786934d750e37e1afd0617e8aa1d | 3,653,328 |
def encode_list(key, list_):
# type: (str, Iterable) -> Dict[str, str]
"""
Converts a list into a space-separated string and puts it in a dictionary
:param key: Dictionary key to store the list
:param list_: A list of objects
:return: A dictionary key->string or an empty dictionary
"""
... | 6cde65017d20e777e27ac86d7f8eb1d025d04947 | 3,653,329 |
async def delete_relationship(request: web.Request):
"""
Remove relationships of resource.
Uses the :meth:`~aiohttp_json_api.schema.BaseSchema.delete_relationship`
method of the schema to update the relationship.
:seealso: http://jsonapi.org/format/#crud-updating-relationships
"""
relation... | 6397ebab365b9339dca7692b4188945401d54779 | 3,653,330 |
def cost_efficiency(radius, height, cost):
"""Compute and return the cost efficiency of a steel can size.
The cost efficiency is the volume of the can divided by its cost.
Parameters
radius: the radius of the steel can
height: the height of the steel can
cost: the cost of the steel ... | e21f767676d5a1e9e5d97ba8bd8f943ecaad5060 | 3,653,331 |
def process_response():
"""
Outer scope for processing the response to a request via the '/response' endpoint. Ensure all data is present,
request exists in Pending table and then change case status and notify app about the response via webhook.
:return: status code, message
TODO set up
TOD... | c2cef76031b2f7396d504eb1c10769bb37b145e0 | 3,653,332 |
def cb_xmlrpc_register(args):
"""
Register as a pyblosxom XML-RPC plugin
"""
args['methods'].update({'pingback.ping': pingback})
return args | e9f5cdde32d1a7b3145918d4fadfc80f4de7301f | 3,653,333 |
def try_except(method):
"""
A decorator method to catch Exceptions
:param:
- `func`: A function to call
"""
def wrapped(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except self.error as error:
log_error(error, self.logger, self.erro... | 069c5abd6a2f2dcab8424c829f1dae27e8a294b8 | 3,653,334 |
def sosfilter_double_c(signal, sos, states=None):
"""Second order section filter function using cffi, double precision.
signal_out, states = sosfilter_c(signal_in, sos, states=None)
Parameters
----------
signal : ndarray
Signal array of shape (N x 0).
sos : ndarray
Second order... | 387d921f86ec6bc9c814d0ca757b36f803d122af | 3,653,335 |
import logging
import yaml
import sys
import os
def setup_logging(name, default_path='graphy/logging.yaml', default_level=logging.INFO):
""" Setup logging configuration """
path = files.get_absolute_path(default_path, from_project=True)
try:
with open(path, 'r') as f:
config = yaml.saf... | c6114284982244e29792866bbff52591d0787597 | 3,653,336 |
import logging
def node_exporter_check():
"""
Checks existence & health of node exporter pods
"""
kube = kube_api()
namespaces = kube.list_namespace()
ns_names = []
for nspace in namespaces.items:
ns_names.append(nspace.metadata.name)
result = {'category': 'observability',
... | 25a1c23107654a6b561d54ffce08aa6025ae1d2e | 3,653,337 |
import time
import os
import json
def create(cmd, resource_group_name=None, workspace_name=None, location=None, storage_account=None, skip_role_assignment=False, provider_sku_list=None):
"""
Create a new Azure Quantum workspace.
"""
client = cf_workspaces(cmd.cli_ctx)
if not workspace_name:
... | deace233f9f357137c83e3b58eec8316abceafd2 | 3,653,338 |
def functional_domain_min(braf_gene_descr_min,
location_descriptor_braf_domain):
"""Create functional domain test fixture."""
params = {
"status": "preserved",
"name": "Serine-threonine/tyrosine-protein kinase, catalytic domain",
"id": "interpro:IPR001245",
... | 905e6b3dc4c1507c57d71879b582794cd66cdd8e | 3,653,339 |
def rsa_encrypt(rsa_key, data):
"""
rsa_key: 密钥
登录密码加密
"""
data = bytes(data, encoding="utf8")
encrypt = PKCS1_v1_5.new(RSA.importKey(rsa_key))
Sencrypt = b64encode(encrypt.encrypt(data))
return Sencrypt.decode("utf-8") | 07384216eff4d0f109e9a0b3bf45c0c1ab108b26 | 3,653,340 |
import numpy
def shuffle_and_split_data(data_frame):
"""
Shuffle and split the data into 2 sets: training and validation.
Args:
data_frame (pandas.DataFrame): the data to shuffle and split
Returns:
2 numpy.ndarray objects -> (train_indices, validation_indices)
Eac... | dfcad7edb9ec17b81057e00816fe3d5bdadc39be | 3,653,341 |
def parse_array_from_string(list_str, dtype=int):
""" Create a 1D array from text in string.
Args:
list_str: input string holding the array elements.
Array elements should be contained in brackets [] and seperated
by comma.
dtype: data type of the array elements. Default ... | b05204a1c6d516a4f4eed298819bda97c5637f37 | 3,653,342 |
def Maj(x, y, z):
""" Majority function: False when majority are False
Maj(x, y, z) = (x ∧ y) ⊕ (x ∧ z) ⊕ (y ∧ z)
"""
return (x & y) ^ (x & z) ^ (y & z) | 7d4013dfc109b4fc39fd3b0bd3f2f5947d207ff0 | 3,653,343 |
import pickle
def get_package_data():
"""Load services and conn_states data into memory"""
with open(DATA_PKL_FILE, "rb") as f:
services, conn_states = pickle.load(f)
return services, conn_states | 8bff214f2256f98e43599f4e5ce73d53232e9a7a | 3,653,344 |
import os
def is_module(module):
"""Check if a given string is an existing module contained in the
``MODULES_FOLDER`` constant."""
if (os.path.isdir(os.path.join(MODULES_FOLDER, module)) and
not module.startswith('_')):
return True
return False | ac3ab55cbc2c359207aaa9d4c83d2aba5e0de895 | 3,653,345 |
import os
def _finalize_sv(solution_file, data):
"""Add output files from TitanCNA calling optional solution.
"""
out = {"variantcaller": "titancna"}
with open(solution_file) as in_handle:
solution = dict(zip(in_handle.readline().strip("\r\n").split("\t"),
in_handle... | 922642e8450f4345082383d9b80509198912747a | 3,653,346 |
def reload_county():
""" Return bird species, totals, location to map """
# receive data from drop-down menu ajax request
bird = request.args.get("bird")
county = request.args.get("county")
# get the zoom level of the new chosen county
zoomLevel = get_zoom(county)
# reset session data fr... | 6c3ad39e12483579d0c9031b5c9a56babcac3823 | 3,653,347 |
import re
def get_conv2d_out_channels(kernel_shape, kernel_layout):
"""Get conv2d output channels"""
kernel_shape = get_const_tuple(kernel_shape)
if len(kernel_shape) == 4:
idx = kernel_layout.find("O")
assert idx >= 0, "Invalid conv2d kernel layout {}".format(kernel_layout)
return... | 4b26979b873f36b79f5e29d0c814417a4c21eb32 | 3,653,348 |
def bindparam(key, value=None, type_=None, unique=False, required=False, callable_=None):
"""Create a bind parameter clause with the given key.
:param key:
the key for this bind param. Will be used in the generated
SQL statement for dialects that use named parameters. This
v... | 5dc1b311d0dfae04b31d1e869015dbaef9fc2f42 | 3,653,349 |
def create_dictionary(timestamp, original_sentence, sequence_switched, err_message, suggestion_list):
"""Create Dictionary Function
Generates and exports a dictionary object with relevant data for website interaction to take place.
"""
if len(suggestion_list) != 0:
err_message_str = "Possible e... | 057d407089a7bb4e445bd0db2632dfcb9f291ed6 | 3,653,350 |
import pandas as pd
import os
def benefits(path):
"""Unemployment of Blue Collar Workers
a cross-section from 1972
*number of observations* : 4877
*observation* : individuals
*country* : United States
A time serie containing :
stateur
state unemployment rate (in %)
statemb
state max... | 651b3b1798f340d668a55241dd4ba6b54ec22881 | 3,653,351 |
def get_L_BB_b2_d_t(L_BB_b2_d, L_dashdash_b2_d_t):
"""
Args:
L_BB_b2_d: param L_dashdash_b2_d_t:
L_dashdash_b2_d_t:
Returns:
"""
L_BB_b2_d_t = np.zeros(24 * 365)
L_BB_b2_d = np.repeat(L_BB_b2_d, 24)
L_dashdash_b2_d = np.repeat(get_L_dashdash_b2_d(L_dashdash_b2_d_t), 24)
... | 51b3551e68e9bbccbe756156d0d623b32a47c23f | 3,653,352 |
def _get_tab_counts(business_id_filter, conversation_tab, ru_ref_filter, survey_id):
"""gets the thread count for either the current conversation tab, or, if the ru_ref_filter is active it returns
the current conversation tab and all other tabs. i.e the value for the 'current' tab is always populated.
Calls... | 9e79d7d692661496a49db93754716e10644bccf2 | 3,653,353 |
def IsInverseTime(*args):
"""Time delay is inversely adjsuted, proportinal to the amount of voltage outside the regulating band."""
# Getter
if len(args) == 0:
return lib.RegControls_Get_IsInverseTime() != 0
# Setter
Value, = args
lib.RegControls_Set_IsInverseTime(Value) | e0c1b3fef4d3c8b6a822a2946703503628a3f775 | 3,653,354 |
def create_userinfo(fname, lname, keypass):
"""
function to create new user
"""
new_userinfo = Userinfo(fname, lname, keypass)
return new_userinfo | ec7ae9a8cf79482498218571d04bee11ab767d98 | 3,653,355 |
from typing import Dict
def get_networks() -> Dict[str, SpikingNetwork]:
"""Get a set of spiking networks to train."""
somatic_spike_fn = get_spike_fn(threshold=15)
dendritic_nl_fn = get_default_dendritic_fn(
threshold=2, sensitivity=10, gain=1
)
neuron_params = RecurrentNeuronParameters(
... | d20f93eb849134c5104c22e9724bcadf09a4a141 | 3,653,356 |
import os
import tqdm
def process_files(pair_path):
"""
Process all protein (pdb) and ligand (sdf) files in input directory.
Args
pair_path dir (str): directory containing PDBBind data
Returns
structure_dict (dict): dictionary containing each structure, keyed by PDB code. Each PDB is a... | 1932e4507b4a1cefca3085940de32488814256d4 | 3,653,357 |
import collections
def metric_group_max(df, metric_names=None):
"""Find the step which achieves the highest mean value for a group of metrics."""
# Use METRIC_NAMES defined at the top as default
metric_names = metric_names or METRIC_NAMES
group_to_metrics = collections.defaultdict(set)
for metric in metric_... | 6f58e9f3a18f6185c1956a994b47f9f4fb9936ea | 3,653,358 |
def get_settings_value(definitions: Definitions, setting_name: str):
"""Get a Mathics Settings` value with name "setting_name" from definitions. If setting_name is not defined return None"""
settings_value = definitions.get_ownvalue(setting_name)
if settings_value is None:
return None
return set... | 3d05b234f85a13746b47ca97f3db578d3c7d6856 | 3,653,359 |
def show_clusterhost(clusterhost_id):
"""Get clusterhost."""
data = _get_request_args()
return utils.make_json_response(
200,
_reformat_host(cluster_api.get_clusterhost(
clusterhost_id, user=current_user, **data
))
) | a49a0027b8f7ab1ce20e762f960b6d8285d8850c | 3,653,360 |
import math
def resize3d_cubic(data_in, scale, coordinate_transformation_mode):
"""Tricubic 3d scaling using python"""
dtype = data_in.dtype
d, h, w = data_in.shape
new_d, new_h, new_w = [int(round(i * s)) for i, s in zip(data_in.shape, scale)]
data_out = np.ones((new_d, new_h, new_w))
def _c... | 42f1a14e5c1133c7ce53b5770d62001e1dacbc6d | 3,653,361 |
def seasurface_skintemp_correct(*args):
"""
Description:
Wrapper function which by OOI default applies both of the METBK seasurface
skin temperature correction algorithms (warmlayer, coolskin in coare35vn).
This behavior is set by the global switches JWARMFL=1 and JCOOLFL=1. The
... | 80ccf63dcf961a4fa488a89023c2516e69862f86 | 3,653,362 |
import random
import os
def run_experiment_here(
experiment_function,
variant=None,
exp_id=0,
seed=0,
use_gpu=True,
gpu_id=0,
# Logger params:
exp_name="default",
snapshot_mode='last',
snapshot_gap=1,
git_infos=None,
scrip... | f48cda086feef7fefb96c7b0412471bc66f2d206 | 3,653,363 |
def extract_character_pairs(letter_case, reverse_letter_case):
"""
Extract character pairs. Check that two unicode value are also a mapping value of each other.
:param letter_case: case mappings dictionary which contains the conversions.
:param reverse_letter_case: Comparable case mapping table which c... | 29e5415afc4e4a3bff5cd74c1fa14f78cf715384 | 3,653,364 |
def after_timestep(simulation, is_steady, force_steady=False):
"""
Move u -> up, up -> upp and prepare for the next time step
"""
# Stopping criteria for steady state simulations
vel_diff = None
if is_steady:
vel_diff = 0
for d in range(simulation.ndim):
u_new = simul... | 7aa3436ba8bcc4ec395ba6f030b83e6fc3cb4bf3 | 3,653,365 |
def get_summary_indices(df, on='NOSC'):
""" Get the summary stats for the indices: median, mean, std, weighted mean and weighted std """
samples = get_list_samples(df)
samples.append(on)
t = df[samples]
t = t.melt(id_vars=[on], var_name='SampleID', value_name='NormIntensity')
t = t[t['NormI... | 1c430a9ad377e3d550e292b381af072d4adc78f0 | 3,653,366 |
def view_evidence(evidence_id: int):
"""View a single Evidence model."""
evidence = manager.get_evidence_by_id_or_404(evidence_id)
return render_template(
'evidence/evidence.html',
evidence=evidence,
manager=manager,
) | 8a51a3c6279a1501c26fb2de09c4450660546bf3 | 3,653,367 |
import os
def get_filenames(split, mode, data_dir):
"""Returns a list of filenames."""
if not split:
data_dir = os.path.join(data_dir, 'cifar-10-batches-bin')
assert os.path.exists(data_dir), (
'Run cifar10_download_and_extract.py first to download and extract the '
'CIFAR-10 data.')
if spli... | a1303f80acc21a3b32fda3b915565c26b6ea9fa6 | 3,653,368 |
def rigidBlades(blds, hub=None, r_O=[0,0,0]):
""" return a rigid body for the three blades
All bodies should be in a similar frame
"""
blades = blds[0].toRigidBody()
for B in blds[1:]:
B_rigid = B.toRigidBody()
blades = blades.combine(B_rigid, r_O=r_O)
blades.name='blades'
re... | 89b48ba43f748fa4b2db7ee768eabe9e79e9a453 | 3,653,369 |
def mea_slow(posterior_matrix, shortest_ref_per_event, return_all=False):
"""Computes the maximum expected accuracy alignment along a reference with given events and probabilities.
Computes a very slow but thorough search through the matrix
:param posterior_matrix: matrix of posterior probabilities with r... | 4b7165a0145d2e1ad2d0550910e03de5a775733c | 3,653,370 |
import trace
def predict(cart_tree, feature_set, data_set):
"""Predict the quality."""
feature_dict = {}
for index, feature in enumerate(feature_set):
feature_dict[feature] = index
results = []
for element in data_set:
# Append a tuple.
results.append((trace(cart_tree, feat... | c7f50557202c4320194ecc5264059c1701e0de73 | 3,653,371 |
def test_incorporate_getitem_through_switch(tag):
""" test_incorporate_getitem_through_switch """
fns = FnDict()
scalar_gt = Primitive('scalar_gt')
@fns
def before(x, y):
def f1(x, y):
return x, y
def f2(x, y):
return y, x
return tuple_getitem(
... | df128faf55c48ba698340d06b3c232ebc0140511 | 3,653,372 |
def response_json(status, message, response):
"""
Helper method that converts the given data in json format
:param success: status of the APIs either true or false
:param data: data returned by the APIs
:param message: user-friendly message
:return: json response
"""
data = {
"status": status,
"message": me... | 9c7e30e81c5412998bc8523b0e45a353c82b5a41 | 3,653,373 |
from . import conf
def settings(request):
"""
"""
conf = dict(vars(conf))
# conf.update(ThemeSite.objects.get_theme_conf(request=request, fail=False))
data = request.session.get('cms_bs3_theme_conf', {})
conf.update(data)
return {'bs3_conf': conf} | 1230171ce1263083aabbd0fb79928c9236af31a9 | 3,653,374 |
def NDVI(R, NIR):
""" Compute the NDVI
INPUT : R (np.array) -> the Red band images as a numpy array of float
NIR (np.array) -> the Near Infrared images as a numpy array of float
OUTPUT : NDVI (np.array) -> the NDVI
"""
NDVI = (NIR - R) / (NIR + R + 1e-12)
return NDVI | aa1789c80720c09aa464b3ae67da7de821e2ba97 | 3,653,375 |
from typing import Union
from typing import Optional
from datetime import datetime
def get_nearby_stations_by_number(
latitude: float,
longitude: float,
num_stations_nearby: int,
parameter: Union[Parameter, str],
time_resolution: Union[TimeResolution, str],
period_type: Union[PeriodType, str],... | e53896ea4644bcce6351671ec950fe8165a2cb12 | 3,653,376 |
import scipy
def get_state(tau, i=None, h=None, delta=None, state_0=None, a_matrix=None):
"""
Compute the magnetization state.
r(τ) = e^(Aτ)r(0) eq (11) at[1]
"""
if a_matrix is not None:
# get state from a known A matrix
# A matrix can be shared and it takes time to build
... | a4ae277d41b64c9caf49758d62767030db0b244b | 3,653,377 |
import os
import re
def get_version():
"""Returns version number, without module import (which can lead to ImportError
if some dependencies are unavailable before install."""
contents = read_file(os.path.join('webscaff', '__init__.py'))
version = re.search('VERSION = \(([^)]+)\)', contents)
versio... | c945b404376f071d1a9f43f6865aea6d677f946f | 3,653,378 |
import aacgmv2._aacgmv2 as c_aacgmv2
import logging
def convert_latlon_arr(in_lat, in_lon, height, dtime, code="G2A"):
"""Converts between geomagnetic coordinates and AACGM coordinates.
Parameters
------------
in_lat : (np.ndarray or list or float)
Input latitude in degrees N (code specifies ... | d9efc4d58925ef9cd63e7c800258b99c91e14f7a | 3,653,379 |
import os
from datetime import datetime
def get_entsoe_renewable_data(file=None, version=None):
"""
Load the default file for re time series or a specific file.
Returns
-------
Examples
--------
>>> my_re=get_entsoe_renewable_data()
>>> int(my_re['DE_solar_generation_actual'].sum())
... | 854e97ef3159ac1839145e833bed1708de01c607 | 3,653,380 |
import re
def getPredictedAnchor(title: str) -> str:
"""Return predicted anchor for given title, usually first letter."""
title = title.lower()
if title.startswith('npj '):
return 'npj series'
title = re.sub(r'^(the|a|an|der|die|das|den|dem|le|la|les|el|il)\s+', '',
title)
... | 972eaa495078bc3929967a052f031c50d439fbdc | 3,653,381 |
from typing import Optional
from typing import Mapping
def get_contact_flow(contact_flow_id: Optional[str] = None,
instance_id: Optional[str] = None,
name: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
type: Optional... | ed57d1b17c19f66c38e67613e49653b11c13f699 | 3,653,382 |
def jensen_alpha_beta(risk_returns ,benchmark_returns,Rebalancement_frequency):
"""
Compute the Beta and alpha of the investment under the CAPM
Parameters
----------
risk_returns : np.ndarray
benchmark_returns : np.ndarray
Rebalancement_frequency : np.float64
... | ac9d1cf638e2ce67219ed16dbbffc652ff47c541 | 3,653,383 |
def cycles_run() -> int:
"""Number of cycles run so far"""
return lib.m68k_cycles_run() | 145dc9a154a0ec4c2e46fecdeb7106134307cf10 | 3,653,384 |
def loop_and_return_fabric(lines):
"""
loops lines like:
#1196 @ 349,741: 17x17
"""
fabric = {}
for line in lines:
[x, y, x_length, y_length] = parse_line(line)
i_x, i_y = 0, 0
while i_y < y_length:
i_x = 0
while i_x < x_length:
thi... | d5fd18c5b90c0e6576767a77c954b3546cbaef1a | 3,653,385 |
def get_sample(id):
"""Returns sample possessing id."""
for sample in samples_global:
if sample.id == id:
return sample
raise Exception(f'sample "{id}" could not be found') | 524305fe77ef5cc03ba51af3eb61301b697b9c1f | 3,653,386 |
def transcriptIterator(transcriptsBedStream, transcriptDetailsBedStream):
""" Iterates over the transcripts detailed in the two streams, producing
Transcript objects. Streams are any iterator that returns bedlines or empty
strings.
"""
transcriptsAnnotations = {}
for tokens in tokenizeBedStream(transcriptDe... | 2be2bbca915667be89220d92c42b8a8dce905cc4 | 3,653,387 |
import re
def convert_check_filter(tok):
"""Convert an input string into a filter function.
The filter function accepts a qualified python identifier string
and returns a bool.
The input can be a regexp or a simple string. A simple string must
match a component of the qualified name exactly. A r... | 9d1aaa9a5007371e4f33ce3b4fbc86edd15875c6 | 3,653,388 |
def region_stats(x, r_start, r_end):
"""
Generate basic stats on each region. Return a dict for easy insertion into a DataFrame.
"""
stats = Munch()
stats["start"] = r_start
stats["end"] = r_end
stats["l"] = r_end - r_start
stats["min"] = np.min(x[r_start:r_end])
stats["max"] = np.ma... | cb52f6320952be13f9715cb2259b32996bdbb0da | 3,653,389 |
def resnet_v1_generator(block_fn, layers, num_classes,
data_format='channels_first', dropblock_keep_probs=None,
dropblock_size=None):
"""Generator for ResNet v1 models.
Args:
block_fn: `function` for the block to use within the model. Either
`residual_blo... | 54e0d2eca651c50075916bac783ed871156469e7 | 3,653,390 |
import sys
import array
def read_hotw(filename):
"""
Read cross-section file fetched from HITRAN-on-the-Web.
The format of the file line must be as follows:
nu, coef
Other lines are omitted.
"""
f = open(filename,'r')
nu = []
coef = []
for line in f:
pars = line.spli... | bda8d2419e48cbe6503e1c5af0da5fd265041995 | 3,653,391 |
def _sql_type(ptype):
"""Convert python type to SQL type"""
if "Union" in ptype.__class__.__name__:
assert len(ptype.__args__) == 2, "Cannot create sql column with more than one type."
assert type(None) in ptype.__args__, "Cannot create sql column with more than one type."
return f"{pty... | 331734ce050ca261d2d78876ebd78540a088597b | 3,653,392 |
def rescale_data(data: np.ndarray,
option: str,
args: t.Optional[t.Dict[str, t.Any]] = None) -> np.ndarray:
"""Rescale numeric fitted data accordingly to user select option.
Args:
data (:obj:`np.ndarray`): data to rescale.
option (:obj:`str`): rescaling strate... | 5f885233c262fb2d766417e64f783f807212355e | 3,653,393 |
def extract_labels(text, spacy_model):
"""Extract entities using libratom.
Returns: core.Label list
"""
try:
document = spacy_model(text)
except ValueError:
logger.exception(f"spaCy error")
raise
labels = set()
for entity in document.ents:
label, _ = Label.o... | 782fdcb4bdd817b55a38c5efe03db676f0e00eed | 3,653,394 |
from typing import Callable
import click
def variant_option(command: Callable[..., None]) -> Callable[..., None]:
"""
An option decorator for a DC/OS variant.
"""
function = click.option(
'--variant',
type=click.Choice(['auto', 'oss', 'enterprise']),
default='auto',
hel... | 4c89dc15b46c9d147445ef458b721c7ce835cbe7 | 3,653,395 |
def GetSegByName(name):
"""
@return Address of the first byte in the Segment
with the provided name, or BADADDR
"""
for Segment in ida.Segments():
if ida.SegName(Segment) == name:
return Segment
return ida.BADADDR | 4b0353da187735095805b5a80bb0e23a2ce6491b | 3,653,396 |
def sample_points_from_plateaus(all_plateaus, mode, stack_size=10, n_samples=1):
"""
Samples points from each plateau in each video
:param all_plateaus: dictionary containing all plateaus, keys are plateaus's ids, values are the plateau objects
:param mode: either `flow` or `rgb`
:param stack_size:... | 1dd12721acc9b126d244902016e939792b220d1e | 3,653,397 |
def mobile_user_meeting_list(request):
"""
返回用户会议列表
:param request:
:return:
"""
dbs = request.dbsession
user_id = request.POST.get('user_id', '')
start_date = request.POST.get('start_date', '')
end_date = request.POST.get('end_date', '')
error_msg = ''
if not user_id:
... | 55e9a61a755ef957f4b6bf504b3efe721b13cfd7 | 3,653,398 |
import ctypes
def get_current_thread_cpu_time():
"""
<Purpose>
Gets the total CPU time for the currently executing thread.
<Exceptions>
An AssertionError will be raised if the underlying system call fails.
<Returns>
A floating amount of time in seconds.
"""
# Get the current thread handle
... | 6d83314e8ceee0336b6c0ed7f71fa49e89b24ca8 | 3,653,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.