content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
import tarfile
import subprocess
def upload_processing(self, *args, **kwargs):
"""
Executes on Node. Uploads Forcing results to Central and sends LoggingMessage to Central
Is linked to signals which will send messages back to the central
* failure_handler
* success_handler
:param s... | e7d92e5f77229fe5d7cba58d29b6858f8918bb23 | 3,625,400 |
def create_controls(pagesize):
"""
Create an LDAP control with a page size of "pagesize".
"""
if LDAP24API:
return SimplePagedResultsControl(True, size=pagesize, cookie='')
else:
return SimplePagedResultsControl(ldap.LDAP_CONTROL_PAGE_OID, True,
... | 4875878b6e96fb3d06cf580f4a82f1104bf520e3 | 3,625,401 |
def threshold_measurement(state, instruction, shots):
"""
NOTE: This function calculates only by using torontonian.
"""
if not np.allclose(state.xpxp_mean_vector, np.zeros_like(state.xpxp_mean_vector)):
raise NotImplementedError(
"Threshold measurement for displaced states are not s... | 5f07f01ebb2883d6a36f4e27003d1c6341fea779 | 3,625,402 |
def white(N, sigma=1, prng=None):
""" Create white noise.
Parameters
---------
N : numeric
Length of 1d noise array to return
sigma : numeric
Standard deviation
prng : np.random.RandomState, None
A RandomState instance, or None
"""
prng = process_prng(pr... | 40178bb71786ed9da558f7dcd34090e033e9a202 | 3,625,403 |
from pathlib import Path
from typing import Tuple
from typing import List
import gzip
def get_sequence(
series: pd.Series, path_to_pdb: Path
) -> Tuple[str, str, int, int, List[int]]:
"""Gets a sequence of from PDB file, CATH fragment indexes and secondary structure labels.
Parameters
----------
... | 17b3132b0d1050154595bb746cfc1e3ddf505ddb | 3,625,404 |
import os
def upload_file(parameters):
"""Based on uploadFileAsync. Note that this doesn't take
index because we don't need it to do HTTP requests like the typescript code
does."""
# Skip gzip as it is unneeded for now.
total_file_size = os.path.getsize(parameters['file'].absolute_file_path)
if not upload... | 5b2c19831e235409c0411a3b3db42f10907d2a66 | 3,625,405 |
def generate_without_options():
"""
Returns 1 to 6 Pokemon based on default generator values
"""
# Generator chooses how many Pokemon to generate
number_of_pokemon = randint(1,6)
try:
api_response = _send_api_request(num_pokemon=number_of_pokemon)
except:
return statement(re... | e8104227b0494b6cd4e9475b421542e6dbd86de7 | 3,625,406 |
import numpy
def fit_harmonic_decay(data, deltat=1.0, numcoef=DEFCOEF, axis=-1):
"""Fit harmonic functions with exponential decay.
Can be used to fit frequency-domain fluorescence image data with
photobleaching.
Parameters
----------
data : array_like
Experimental data (observed valu... | 07a3c2080ed58f6febc1271a335dc9fef5750887 | 3,625,407 |
import math
def lab_to_lch(lab):
"""Din99o Lab to Lch."""
l, a, b = lab
h = math.degrees(math.atan2(b, a))
c = math.sqrt(a ** 2 + b ** 2)
# Achromatic colors will often get extremely close, but not quite hit zero.
# Essentially, we want to discard noise through rounding and such.
if c <=... | 6c63eb19a7581f2bf41053cef99fc0dc23b79d6c | 3,625,408 |
def moments(data, n_neighbors=30, n_pcs=30, mode='connectivities', method='umap', metric='euclidean', use_rep=None,
recurse_neighbors=False, renormalize=False, copy=False):
"""Computes moments for velocity estimation.
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated dat... | c6e2db61e2b12274039342454fc87849723d8ed8 | 3,625,409 |
def QuadRemeshAsync1(thisMesh, parameters, guideCurves, progress, cancelToken, multiple=False):
"""
Quad remesh this mesh asynchronously.
Args:
guideCurves (IEnumerable<Curve>): A curve array used to influence mesh face layout
The curves should touch the input mesh
Set Guide... | b59c11c8c42e2131828c22ff17eb26cbbf7c6b0c | 3,625,410 |
def are_close(col1, col2):
"""This function used to compare values of collections with numeric data
"""
if len(col1) != len(col2):
raise ValueError("Different size of input collections")
result = []
for x, y in zip(col1, col2):
result.append(abs(abs(x) - abs(y)) < 0.4)
r = T... | 72896f522a5fc7cb9f4f96e873c14797009877fe | 3,625,411 |
def compute_depression(input_dem, scale_factor=1, curvature_percentile=75, return_polygon=True, alpha=0.5):
"""
Compute depressions and return a new image with largest depressions filled in.
Parameters
----------
input_dem : np.array, rd.rdarray
2d array of elevation DNs, a DEM
... | 3341b7c88ad82a0437a2a264ac91f00bf24de471 | 3,625,412 |
from typing import Dict
from typing import Any
def _deregister_ec2_instance(
public_address: str, require_no_running_jobs: bool, region_name: str
) -> bool:
"""
Deregisters an EC2 instance. If require_no_running_jobs is true, then only
deregisters if there are no currently running jobs on the instance... | c43f15b3ba3bedfb478889caaf91eeb1fee7df41 | 3,625,413 |
def convert(n):
"""convert(n) -> Integer""" # TODO
try:
for character in n:
if character in roman_numbers:
return "Roman"
except:
return "Arabic" | 7bca8632853d099086738cbf2a5dbf0e4328c47b | 3,625,414 |
def mse(pred, labs):
"""
Calculates MSE
:param pred: sequence of Strings / predicted score values as strings
:param labs: sequence of Strings / true score values as strings
:return: (Int, Int) / MSE of valid samples AND number of invalid samples
"""
idx = np.where(np.array([isfloat(x) for x ... | 69b28cfadde29b9d80ec07d41a82521e04e048bb | 3,625,415 |
def described_field_type(singular_type_field):
"""
Human readable equivalent of a singular avro type - e.g. long -> number.
"""
if isinstance(singular_type_field, dict):
if "logicalType" in singular_type_field:
return singular_type_field["logicalType"]
else:
if si... | 11514dec5fe2ee6b501a5c03d7321ed1f6a861af | 3,625,416 |
import os
def findFile(ext="", directory=c.DIRECTORY_PROCESSING):
"""
To find a file given extension and return is name.
"""
name = ""
if ext == "":
# Return the first file in the directory that is not crypted
for f in os.listdir(directory):
if not (f.endswith("kat"))... | 6a9f868342cdfb874d462cffe042c5b6287e78b0 | 3,625,417 |
def package_releases(name, show_hidden=True):
"""return a list of package releases"""
return pypi.package_releases(name, show_hidden) | e820369935e56b3b0074257cedeaf633fd08512c | 3,625,418 |
def _randomize_network(network, keep):
"""
This function returns a network with the same nodes and edge number as the input network.
However, each edge is placed randomly.
:param network: NetworkX object
:param keep: List of conserved edges
:return: Randomized network
"""
null = nx.Grap... | eb0881625bdd73f0a94018feb0facb76c868ffb9 | 3,625,419 |
import six
def get_docstring(value, module_name=None):
"""
Return the docstring for the given value; or C{None} if it
does not have a docstring.
@rtype: C{unicode}
"""
docstring = getattr(value, '__doc__', None)
if docstring is None:
return None
elif isinstance(docstring, six.t... | e68e997e843d4110ec608ad6eadac46fdef74eda | 3,625,420 |
import os
def rescale(gray_img, min_value=0, max_value=255):
"""Rescale image.
Inputs:
gray_img = Grayscale image data
min_value = (optional) new minimum value for range of interest. default = 0
max_value = (optional) new maximum value for range of interest. default = 255
... | f29078885816db43d449b60967ca8781f976b901 | 3,625,421 |
import requests
def _classswitch_file(url, header, params):
"""
文件存储类型转换请求
:param url:string类型,文件存储类型转换的url
:param header: dict类型,http 请求header,键值对类型分别为string,比如{'User-Agent': 'Google Chrome'}
:param params: dict类型,http 请求的查询参数,键值对类型分别为string类型
:return: ret: return message, None if response s... | c61af20073932c67a5d4607325eee780da224ccb | 3,625,422 |
def cofa(session=None):
"""
Return location class of current COFA.
Parameters
----------
session: db session to use
"""
h = Handling(session)
located = h.cofa()
h.close()
return located | 363fb61bee4cc0e5c9b95a2c2623050f693e2b0e | 3,625,423 |
def identity(*args, **kwargs):
"""
An identity function used as a default task to test the timing of.
"""
return args, kwargs | 472808f6b5260569538f26513f24ffcb1bd88c4d | 3,625,424 |
def _with_largest_possible_masks(oneof):
"""Add masks to enable all possible ops / filters in the search space."""
if oneof.tag == basic_specs.OP_TAG:
n = len(oneof.choices)
mask = tf.constant([1 / n] * n, dtype=tf.float32)
elif oneof.tag == basic_specs.FILTERS_TAG:
largest_index = None
for i, cho... | c7a9bfb4bb875abe3f6232873f64ad70334c71f8 | 3,625,425 |
def list_merger_list0(*lists):
"""Picks leading list, discards everything else"""
return lists[0] | c571adb593de991f633a28b086e61fa7888cbc7e | 3,625,426 |
def serialize():
"""
Get dict with internal data
"""
with _exception_log_lock:
return {'exceptions': _exceptions.copy()} | aacebcf8d18e7f1654ed2e16ed846dfe35668532 | 3,625,427 |
def cmp(a,b):
"""3-way comparison like the cmp operator in perl"""
if a is None:
a = ''
if b is None:
b = ''
return (a > b) - (a < b) | 97c5a33e9161196119abbc323841be0b1cfdda14 | 3,625,428 |
def _pixel_to_map(coordinates, geotransform):
"""Apply a geographical transformation to return map coordinates from
pixel coordinates.
Parameters
----------
coordinates : :class:`numpy:numpy.ndarray`
2d array of pixel coordinates
geotransform : :class:`numpy:numpy.ndarray`
geogr... | 4aee896d9185625b838c12215835e513996f15b7 | 3,625,429 |
def median_filter(ts: pd.Series, stats: pd.DataFrame = None,
second_pass=False):
"""Apply rolling median filter to time series"""
_ts = ts.dropna() # Make sure there are no empty values
filtered = _ts.copy()
# Assing rolling median from 2nd to 2nd last index
filtered.iloc[1:-1] ... | d9b21f26eb47584aea0376ab0f4a2ca3d055432d | 3,625,430 |
def calculate_pairwise_correlations(df_variable: pd.DataFrame) -> dict:
"""For each pair of modalities, calculate correlations, and put them together into a column"""
modalities = list(df_variable.columns.values)
df_dict = {}
modality_iterator = itt.combinations(modalit... | 9aef93cf3ccf040f7c4a0ee804a171f38ac7646c | 3,625,431 |
from datetime import datetime
def event_context_vars(env_deployment):
"""Return context variables for zaza-events configuration params.
Note that it is cached because env_deployment is immutable, and the date
should only be evaluated the first time.
The "bundle" var is derived from the first model i... | b618e00cec98e93c3ec44df400a1c5e022063c27 | 3,625,432 |
import base64
import os
def generate_random_string(length):
"""Generates a random string of the specified length.
Args:
length: int. Length of the string to be generated.
Returns:
str. Random string of specified length.
"""
return base64.urlsafe_b64encode(os.urandom(length)) | 10f22582cbe17ac0a4a41b52a8691e12036593d2 | 3,625,433 |
def update_model(model, player, winner, board_hist, move_hist, learnig_rate):
"""
Updates 2 layer policy network weights using gradient descent (policy gradients) according to the played game data.
Parameters
----------
model: dict {"W1": [numpy Hx9 array], "W2": [numpy 9xH array]}
Policy n... | c7dd57005fc8892be2d3682b562d8097277758a6 | 3,625,434 |
def init(base_url, username=None, password=None, verify=True):
"""Initialize ubersmith API module with HTTP request handler."""
handler = RequestHandler(base_url, username, password, verify)
set_default_request_handler(handler)
return handler | 07b0ab1f076b0ae79dc6f4eaba87078d9f8c700e | 3,625,435 |
def view_mol(option, maps=None, out_put=None, target_id=None, extra=None):
"""Function to render the 3D coordinates of a molecule
Takes a PDB code as input
Returns an SD block"""
my_mols = Molecule.objects.filter(prot_id__code=option)
new_mol = ""
for mol in my_mols:
new_mol += (str(mol.... | e42b583e63f3ac2ad6cb7d241754491604b66455 | 3,625,436 |
def left_fit_width(s, width, fill=' '):
"""Make a string fixed width by padding or truncating.
Note: fill can't be full width character.
"""
s = trim_width(s, width)
s += fill * (width - str_width(s))
return s | 11d285b6065ac1f95d9a9f9f31bd55849c53f8d6 | 3,625,437 |
def create_item_selection_window():
"""
This function contains all the logic of the item selection window and will run the window by it's own.
:return: None
"""
item_selection_window = sg.Window("Item selection", generate_item_selection_layout(), finalize=True,
... | d33eb2858786dc38d90b22147ec1145236c206c3 | 3,625,438 |
def check(consumer_households_in_siumulation, prosumer_households_in_siumulation):
"""[summary]
Checks if a new user needs to be added to the simulation or if a user is removed
Args:
consumer_households_in_siumulation ([list]): [List of current consumers in the simulation]
prosumer_hous... | 00d84b25ce1533406b78aa455c8605269978983b | 3,625,439 |
def create_model(inner_settings:InnerModelSettings,outer_settings:OuterModelSettings) -> OuterModel:
"""
function creates an OuterModel with provided settings.
Args:
inner_settings: an instannce of InnerModelSettings
outer_settings: an instannce of OuterModelSettings
"""
model = Out... | 28e0f47b2130ecb4a5e08886c08e9589af04a932 | 3,625,440 |
def create_logdir(method, weight, label, rd):
""" Directory to save training logs, weights, biases, etc."""
return "bigan/train_logs/mnist/{}/{}/{}/{}".format(weight, method, label, rd) | 4b4edcc9c0c36720e76013a6fb0faf1b49472bc0 | 3,625,441 |
def ontocreate():
"""View function for the standard vocabulary creator module.
Returns:
str: HTML page for the standard creator module.
"""
form = OntologyDescript()
form2 = InvertLangButton()
return render_template("ontocreate.html", form=form, form2=form2) | 83197d6062ed8d78882980542949f43ba8df3982 | 3,625,442 |
def log_spherical_gaussian(theta, variance):
"""Unnormalized log density of a spherical Gaussian"""
return -np.sum(theta**2) / (2 * variance) | d113c4014b72a41c2f0cb252a2a6b6e2ae5f3e0b | 3,625,443 |
def apply_target(rule, substitutions):
"""Return target string with non-terminals replaced with substitutions."""
if rule.arity != len(substitutions):
raise ValueError
output = []
for token in rule.target:
if token == NT_1:
output.append(substitutions[0])
elif token == NT_2:
output.appen... | 595333291d2fcce159c927f09666de7a1f7be3bf | 3,625,444 |
import io
import sqlite3
def adapt_array(arr):
"""
"""
# https://stackoverflow.com/a/18622264
# http://stackoverflow.com/a/31312102/190597 (SoulNibbler)
out = io.BytesIO()
np.save(out, arr)
out.seek(0)
return sqlite3.Binary(out.read()) | 74ca1db4ed25dd60f6ec91ade3c150be313fd1c6 | 3,625,445 |
from typing import List
def usage_stats_invalid_messages_exist(messages: List[str]) -> bool:
"""
Since the usage stats functionality does not raise exceptions but merely logs them, we need to check the logs for errors.
"""
return any(
[
UsageStatsExceptionPrefix.INVALID_MESSAGE.va... | 3de0e6bc0fa82c57b07209e8ccda5ade3465f668 | 3,625,446 |
def spike_train_from_string(s, edges, sep=' ', is_sorted=False):
""" Converts a string of times into a :class:`.SpikeTrain`.
:param s: the string with (ordered) spike times.
:param edges: interval defining the edges of the spike train.
Given as a pair of floats (T0, T1) or a single float... | 1ecfaa7b8ac7320eef95e8b4db16775669adef9a | 3,625,447 |
def cli(ctx):
"""TODO: Undocumented
Output:
???
"""
return ctx.gi.cannedcomments.findAllComments() | f1ad009e8e0b32f60f813ca4154403f3a4c5caf9 | 3,625,448 |
def batch_effective_sample_size(x, mu, var, logger=None):
"""
Calculate the effective sample size of sequence generated by MCMC.
:param x:
:param mu: mean of the variable
:param var: variance of the variable
:param logger: log
:return: effective sample size of the sequence
We calculate ... | 808b4bb4f5294c58d6c3eee42af772d9818c91f9 | 3,625,449 |
def copy_ecf_ord_players_post_2006_rules(widget, logwidget=None):
"""Import a new ECF downloadable OGD rating list csv file.
widget - the manager object for the ecf data import tab.
Downloads have been produced in this format since mid-2020.
These are available for all lists since 1994 according to
... | af72186f0cad73e0d37dcd996991d901912de1c7 | 3,625,450 |
from io import StringIO
import io
def _str_io(*args, **kwargs):
"""Helper for PY2/Py3 StringIO"""
if StringIO:
return StringIO.StringIO(*args, **kwargs)
return io.StringIO(*args, **kwargs) | b9013fae9ca9231dfb74064ee293727734c38697 | 3,625,451 |
import functools
def eval_mode(f):
"""a decorator designed for nn.Module methods which wraps the function call in the eval context.
Note:
you can use this decorator for any function that takes a model as first parameter.
but it's reccommended to use on nn.Module methods.
"""
@functoo... | 740936b7118dda0e4a28c73914344de50d73e9cb | 3,625,452 |
from datetime import datetime
def read_logs(start_time=None):
""" Read all log messages after a certain time from the latest text file log
Parameters
----------
start_time : datetime
The earliest timestamp from which to read logs
Returns
-------
string, datetime
The relev... | 8a3a3feeb7c98fe5938e81e2fd5afa06bbd7b02a | 3,625,453 |
import logging
import optparse
import sys
import unittest
def main(argv=None):
"""
parse_inputrc main function
Keyword Arguments:
argv (list): commandline arguments (e.g. sys.argv[1:])
Returns:
int: zero
"""
prs = optparse.OptionParser(usage="%prog : args")
prs.add_optio... | dea74269dd8184a3a732fe4e43845b552bb39d89 | 3,625,454 |
def _hist2d_add(list_results: list):
"""
Quick helper function that we can submit to dask cluster to sum the results of running hist2d_numba_seq on multiple
chunks of data.
Parameters
----------
list_results
list, list of numpy ndarray histograms that we want to sum to get global result... | e00efe2716e83b26354c0f6ca3c339a470921592 | 3,625,455 |
def dwnld_worker(qtbot, mocker, workdir):
"""A fixture for the WeatherDataGapfiller."""
dwnld_worker = RawDataDownloader()
return dwnld_worker | c3f0d6b57d8a39c7e90e202106a6708d662f1031 | 3,625,456 |
import re
def camel_case_to_title_case(camel_case_string):
"""
Turn Camel Case string into Title Case string in which first characters of
all the words are capitalized.
:param camel_case_string: Camel Case string
:return: Title Case string
"""
if not isinstance(camel_case_string, str):
... | bcc40753a8672355519741f5aec64c262431d582 | 3,625,457 |
def add_subplot_axes(ax, rect):
"""
Plotting utility
"""
fig = plt.gcf()
box = ax.get_position()
width = box.width
height = box.height
inax_position = ax.transAxes.transform(rect[0:2])
transFigure = fig.transFigure.inverted()
infig_position = transFigure.transform(inax_position)
... | c91126c81e1608e35ef3a7aa48ae9ea9da4ea684 | 3,625,458 |
def starfind(data, snr, background, noise, fwhm, mask=None, box_size=35,
sharp_limit=(0.2, 1.0), round_limit=(-1.0, 1.0),
logger=logger):
"""Find stars using daofind AND sexfind."""
# First, we identify the sources with sepfind (fwhm independent)
sources = sepfind(data, snr, backgr... | 1f9792f75a9a0d877993260118d7ca95480a85ba | 3,625,459 |
import torch
def displace(a, delta):
"""
fns = {
-1: lambda x: -x,
0: lambda x: 1 - np.abs(x),
1: lambda x: x,
}"""
delta_x, delta_y = delta[:, :, :, 0], delta[:, :, :, 1]
delta_x = delta_x.unsqueeze(3)
delta_y = delta_y.unsqueeze(3)
# BatchSize x Height X Width x 3
x_multipliers = torch.relu(torch.cat(... | cf8819193d331c7edcb1a90989bf0fb2e3896370 | 3,625,460 |
def inferType(fname):
"""Return the type of the given X5 file - either ``'linear'`` or
``'nonlinear'``.
:arg fname: Name of a X5 file
:returns: ``'linear'`` or ``'nonlinear'``
"""
with h5py.File(fname, 'r') as f:
ftype = f.attrs.get('Type')
if ftype not in ('linear', 'nonlin... | 7be135f126dc20da70c6fb0f9e2d5f2f5ebc0a1c | 3,625,461 |
def pmr_corr(vlos, r, d):
"""
Correction on radial proper motion due to apparent contraction/expansion
of the cluster.
Parameters
----------
vlos : float
Line of sight velocity, in km/s.
r : array_like, float
Projected radius, in degrees.
d : float
Cluster distan... | c9136c5ae33e89d6f57b936b92c23001fd30ccfa | 3,625,462 |
def get_min_corner(sparse_voxel):
"""
Voxel should either be a schematic, a list of ((x, y, z), (block_id, ?)) objects
or a list of coordinates.
Returns the minimum corner of the bounding box around the voxel.
"""
if len(sparse_voxel) == 0:
return [0, 0, 0]
# A schematic
if len(... | 371b25b795a1a2ffeb0fc3724f01f1a329f917ae | 3,625,463 |
def ExtractListsFromVertices(vertexProp, g):
"""
Method to extract the lists at each vertex of a vertex property,
vertexProp, belonging to a graph, g, and to return a list of lists,
where each sub-list is a list of values from each vertex
:param vertexProp:
:param g:
:return:
... | fd10e9285f9382511a526468e41e8a516a6f50bd | 3,625,464 |
def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" +
event['session']['application']['applicationId'])
"... | 651532a7337322171f8fcf8874048a5b840505cf | 3,625,465 |
import sys
def get_runtime_python_tag():
"""Identify the Python tag of the current runtime.
:returns: Python tag.
"""
python_minor_ver = sys.version_info[:2]
try:
sys_impl = sys.implementation.name
except AttributeError:
sys_impl = PYTHON_IMPLEMENTATION.lower()
# pylint:... | 202dcdb3d014e4823518b426be9acc2c6d02ef10 | 3,625,466 |
def _traverse_dirtable(rsrc, off, rtype):
"""Recursively traverse the dirtable, returning all data entries under the given type id."""
# resource directory header
resdir = _IMAGE_RESOURCE_DIRECTORY.from_bytes(rsrc, off)
number = resdir.NumberOfNamedEntries + resdir.NumberOfIdEntries
# followed by re... | 51de90b056fae726faea0732f3fcd09ba8ec1db8 | 3,625,467 |
def i18n_enabled():
"""
Return the projects i18n setting
"""
return getattr(settings, "USE_I18N", False) | 35931fcfc6fbfd19508024c8fa3405d82bd59dfb | 3,625,468 |
def partial_waveletpacketdec2(data, wavelet, mode='symmetric', level=None, axes=(-2, -1)):
"""
Multilevel 2D Partial Discrete Wavelet Packet Transform.
Parameters
----------
data : ndarray
2D input data
wavelet : Wavelet object or name string, or 2-tuple of wavelets
Wavelet to us... | ea8e8f700b16388faf42f6012a0cd017d6e8d297 | 3,625,469 |
def delete(request, testplan_id, rule_id):
"""
Delete test plan based on testplan_id.
"""
dbc = db_model.connect()
try:
testplan = dbc.testplan.find_one({"_id": ObjectId(testplan_id)})
except InvalidId:
return HttpResponseNotFound("testplan '%s' not found" % testplan_id)
if t... | 473d87f8ea5f586e8e1c6803d3bc10bdcb3e5f49 | 3,625,470 |
def _third_order(B3, Y_res, C3, R, n3, m3, lambdax):
"""Compute third order sensitivities."""
Y_ijk = np.zeros((R, n3)) # Initialize 1st order contributions
T3 = np.zeros((m3, R, n3)) # Initialize T(emporary) matrix - 1st
# First order individual estimation
for j in range(n3):
# Re... | ebc33133cdb8fa5006c47621b1f867230cc9d73d | 3,625,471 |
import optparse
import os
import sys
import logging
def process_commandline():
"""Process command-line options, load prefs, configure module path."""
parser = optparse.OptionParser(__doc__.strip())
if os.getuid() == 0:
support_path = "/Library/"
else:
os.path.expanduser("~/Library/")
preference_file... | d6a0d0b01cf5be62564711c3ab65bc6affcbab79 | 3,625,472 |
from typing import Optional
def _query_statistics(
total_queries_name: str = TOTAL_QUERIES_NAME,
total_documents_name: str = TOTAL_DOCUMENTS_NAME,
min_documents_name: str = MIN_DOCUMENTS_NAME,
max_documents_name: str = MAX_DOCUMENTS_NAME,
eval_config: Optional[config_pb2.EvalConfig] = None,
mo... | 4472dd35220a2788005f366b46a5275dcc3b207d | 3,625,473 |
def get_scrapyd(client):
"""
get scrapyd of client
:param client: client
:return: scrapyd
"""
if not client.auth:
return ScrapydAPI(scrapyd_url(client.ip, client.port))
return ScrapydAPI(scrapyd_url(client.ip, client.port), auth=(client.username, client.password)) | 40c0fd8afb4b499aaf05264f66d0a6558109f5c2 | 3,625,474 |
def byteListToU32leList(data):
"""Convert a list of bytes to a list of 32-bit integers (little endian)"""
res = []
for i in range(len(data) / 4):
res.append(data[i * 4 + 0] |
data[i * 4 + 1] << 8 |
data[i * 4 + 2] << 16 |
data[i * 4 + 3] << 24... | a06cdb918070837728c5f6100ca237bab4a4773f | 3,625,475 |
import os
import json
import numbers
def read_server_config(config_path):
"""
给定config的path,读取里面的config。如果config不存在,则按照默认的值创建
:param config_path: str
:return: dict, config的内容
"""
config = ConfigParser(allow_no_value=True)
if not os.path.exists(config_path):
config_dir = os.path.dir... | 462560a88e6ece1342bac29d8d5557a41a126a3d | 3,625,476 |
def normalize_fr(fr):
"""Normalize an input flavor combination to a flavor ratio.
Parameters
----------
fr : list, length = 3
flavor combination
Returns
----------
numpy ndarray flavor ratio
Examples
----------
>>> from fr import normalize_fr
>>> print(normalize_fr... | b290c0e03b862306d995c5426b833d701b4093d1 | 3,625,477 |
import gzip
import os
def csp2mtx(vcff0, vcff1, out_dir):
"""
@abstract Fix ref & alt for cellsnp mode 2 vcf and output new Ref & Alt matrices
@param vcff0 Sorted vcf containing correct ref & alt in target region [str]
@param vcff1 Raw cellsnp mode 2 vcf to be fixed [str]
@param out_di... | d8714cd6c091b0819054032f18f78ce6862964fa | 3,625,478 |
def max_row_by_row(arrays,NaN=False):
"""Perform row by row min"""
if NaN:
rowmax=[max_w_nan(arr) for arr in arrays]
else:
rowmax=[max(arr) for arr in arrays]
return rowmax | 5897efc74f473d1d2d40f8479df11ce0f08c607d | 3,625,479 |
from typing import Tuple
from typing import Dict
import os
import itertools
def correlation_report(
data: pd.DataFrame,
interval_cols: list = None,
bins=10,
quantile: bool = False,
do_outliers: bool = True,
pdf_file_name: str = "",
significance_threshold: float = 3,
correlation_thresho... | b9b5bf85cb1fb52bb52411337b80ba44dbe6c7f2 | 3,625,480 |
def is_palindrome_letters_only(str):
"""
Confirm Palindrome, even when string contains non-alphabet letters and ignore capitalization.
casefold() method, which was introduced in Python 3.3, could be used instead of this older method,
which converts to lower().
"""
i = 0
j = hi = len(str) - ... | 5f95add0ecf3fbe31af2b9cd0e27aac36b2c3985 | 3,625,481 |
def extract_std_bandwidth(spectrogram, doppler_bins, render = False, render_time = None, idstr = None):
""" Extracts the mean time between peaks in the spectrogram.
"""
spectrogram, doppler_bins = clean_spectrogram(spectrogram, doppler_bins)
bandwidth = get_bandwidth(spectrogram, doppler_bins)
std_b... | 1a0c83786825fb54e6c3c285becdd6adbf9e29a8 | 3,625,482 |
import json
def Schedule(name, config, scheduled_by, executor_requirements, priority=0):
"""Adds a new Task with given name, config, user and requirements."""
webhook = json.loads(config)['task'].get('webhook', None)
task = Task(parent=MakeParentKey(),
name=name,
config=config,
... | 73924c5a590a4b9791673f16f52a0a19f03c743f | 3,625,483 |
import time
import logging
def createResponseBody(lines, context, client, lang='en'):
"""Parse the **lines** from an incoming email request and determine how to
respond.
:param list lines: The list of lines from the original request sent by the
client.
:type context: class:`bridgedb.email.ser... | 663bdf2b90a471b4b65db26de7d8165f6a6ec2f0 | 3,625,484 |
from typing import Any
def validate_delta(delta: Any) -> float:
"""Make sure that delta is in a reasonable range
Args:
delta (Any): Delta hyperparameter
Raises:
ValueError: Delta must be in [0,1].
Returns:
float: delta
"""
if (delta > 1) | (delta < 0):
raise ... | 1fd3084c047724a14df753e792b8500a103a34c0 | 3,625,485 |
def deparagraph(element: Element, doc: Doc) -> Element:
"""Panflute filter function that converts content wrapped in a Para to
Plain.
Use this filter with pandoc as::
pandoc [..] --filter=lander-deparagraph
Only lone paragraphs are affected. Para elements with siblings (like a
second Para... | aff8bdb03baa8427f4026c22a125d286a1fb323b | 3,625,486 |
import os
import yaml
def parse_config(config_file, config_type=None):
"""Parse configurations in YAML file.
Each configuration type must be defined as a dictionary with a
Parameters
----------
config_file : str
filename of YAML file
config_type : str
{'extract','select','pred... | 2d19c01762527249bfcfd8f44f9d7186ca04e832 | 3,625,487 |
def get_residual_loss(query_images, encoded_images, params):
"""Gets residual loss between query and encoded images.
Args:
query_images: tensor, query image input for predictions.
encoded_images: tensor, image from generator from encoder's logits.
params: dict, user passed parameters.
... | 2d3614a6f1b0d99f7b7a8907d0a90d1b1ce69cbc | 3,625,488 |
def directed_connected_components(digr):
""" Returns a list of strongly connected components
in a directed graph using Kosaraju's two pass algorithm """
if not digr.DIRECTED:
raise Exception("%s is not a directed graph" % digr)
finishing_times = DFS_loop(digr.get_transpose())
# use finishing... | 4e0b69aa6d7feeccafc94354210568c21ecbc775 | 3,625,489 |
from typing import Any
async def leave_group_by_id(id: str, number: str) -> Any:
"""
leave a group by id
"""
cmd = ["-u", quote(number), "quitGroup", "-g", quote(id)]
await run_signal_cli_command(cmd)
return id | c0fc42a00a67e50c53a5f1608516a066ec2d3141 | 3,625,490 |
from datetime import datetime
def capacitytoactivity(trade, outPutFile, input_data):
"""
builds the CapacityToActivityUnit (Region, Technology, CapacitytoActivityUnit)
-------------
Arguments
trade, outPutFile, input_data
outPutFile: is a string containing the OSeMOSYS parameters file
... | 88560b00505c31e8f438206e4ff6da03362df634 | 3,625,491 |
import numpy as np
def molpos_1Dbin(data,bins,diameter):
"""Creates a 1D histogram from X,Y location data of a single tracked molecule over time
Args:
data (pandas dataframe): time series 2D location data of a tracked molecule
bins (int): # of rectangular bins to discretize cell with (bin... | fbc05b9c14d82c19f62ae30ec1d05b7e314b57e8 | 3,625,492 |
import test
def suite():
""" A test suite for the ITU-P Recommendations. Recommendations tested:
* ITU-P R-676-9
* ITU-P R-676-11
* ITU-P R-618-12
* ITU-P R-618-13
* ITU-P R-453-12
* ITU-P R-837-6
* ITU-P R-837-7
* ITU-P R-838-3
* ITU-P R-839-4
* ITU-P R-840-4
* ITU-P R... | c1b87ef1781945e0b7ffb3577959176ea28b4469 | 3,625,493 |
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} | 74c2e4e4188b608120f241aadb20d8480ac84008 | 3,625,494 |
def add_ops(op_classes):
"""
Decorator to add default implementation of ops.
"""
def f(cls):
for op_attr_name, op_class in op_classes.items():
ops = getattr(cls, f"{op_attr_name}_ops")
ops_map = getattr(cls, f"{op_attr_name}_op_nodes_map")
for op in ops:
... | c2721444a5b211d2d7f3a78c61df3e68e143f3f4 | 3,625,495 |
def clear_history_fixture_test():
"""define a function that will run each time you pass it to a test, it is called a fixture"""
return Calculations.clear_history() | 6baac016824cef4d710366f376e4ea3ff2d74990 | 3,625,496 |
def get_bool_mask_from_ivar(ivar):
"""
Return mask determined by pixels that are nonzero in all ivar maps.
Parameters
----------
ivar : (..., nsplit, 1, ny, nx) ndmap
Inverse variance maps for N splits.
Returns
-------
mask : (ny, nx) bool enmap
Mask, True in ob... | 8776e4089dcb612cbe32e58f3a9d654c0a29e938 | 3,625,497 |
from typing import Optional
def check_if_function_can_be_run(
ctx: typer.Context, param: typer.CallbackParam, value: str
) -> Optional[str]:
"""Callback that validates if a function can be run"""
if not is_function_built(value):
raise typer.BadParameter(
f"Function - '{value}' is not a... | d6cff1f76c41acc7b7a1732536c7b50e2cd217ef | 3,625,498 |
import math
def random_rotate(X, y, rotation_range=0):
"""Randomly rotate centroids and appearances.
Args:
X (dict): Dictionary of feature data.
rotation_range (int): Maximum rotation range in degrees.
Returns:
dict: Rotated ``X`` data.
"""
appearances = X['appearances']
... | ad7b1bd47e4fd5e1cdda6bd6b192df67475ade0f | 3,625,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.