content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def read_sj_out_tab(filename):
"""Read an SJ.out.tab file as produced by the RNA-STAR aligner into a
pandas Dataframe.
Parameters
----------
filename : str of filename or file handle
Filename of the SJ.out.tab file you want to read in
Returns
-------
sj : pandas.DataFrame
... | bc96813e1e69c8017f7ad0e5c945d4bf8c17e645 | 3,651,600 |
def gc_subseq(seq, k=2000):
"""
Returns GC content of non − overlapping sub− sequences of size k.
The result is a list.
"""
res = []
for i in range(0, len(seq)-k+1, k):
subseq = seq[i:i+k]
gc = calculate_gc(subseq)
res.append(gc)
return gc | 9c2208f9dad291689ef97556e8aaa69213be6470 | 3,651,601 |
import re
import os
def get_links_from_page(text: str=None) -> set:
"""
extract the links from the HTML
:param text: the search term
:return: a set of links
:rtype: set
"""
links = set()
link_pattern = re.compile('img.src=.+') # todo expand this to get href's
# link_pattern = re.... | cc1d982a0dcfd5cab640ceecd9c715807b41c083 | 3,651,602 |
def pcursor():
"""Database cursor."""
dbconn = get_dbconn("portfolio")
return dbconn.cursor() | 50a19e3837a3846f10c44bcbb61933786d5bf84b | 3,651,603 |
import argparse
def get_args_from_command_line():
"""Parse the command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--HITId", type=str)
parser.add_argument("--worker_id", type=str)
args = parser.parse_args()
return args | 2e018c2cec3fbdd305185fc9f1190416f0d13137 | 3,651,604 |
import math
def truncate(f, n):
"""
Floors float to n-digits after comma.
"""
return math.floor(f * 10 ** n) / 10 ** n | ae7e935a7424a15c02f7cebfb7de6ca9b4c715c0 | 3,651,605 |
import json
def process_simple_summary_csv(out_f, in_f, rundate):
"""Scan file and compute sums for 2 columns"""
df = panda.read_csv(in_f)
FORMATTING_FILE = "ColumnFormatting.json"
with open(FORMATTING_FILE) as json_data:
column_details = json.load(json_data)
# this dictionary will contai... | 9f95acf84115a5fe6eb87de2e0910097bc4f2f10 | 3,651,606 |
import math
def rotY(theta):
""" returns Rotation matrix such that R*v -> v', v' is rotated about y axis through theta_d.
theta is in radians.
rotY = Ry'
"""
st = math.sin(theta)
ct = math.cos(theta)
return np.matrix([[ ct, 0., st ],
[ 0., 1., 0. ],
... | 1ed327485f9861eb8cf045a60f0a7352de1b4b25 | 3,651,607 |
def get_core_blockdata(core_index, spltcore_index, core_bases):
"""
Get Core Offset and Length
:param core_index: Index of the Core
:param splitcore_index: Index of last core before split
:param core_bases: Array with base offset and offset after split
:return: Array with core offset and core le... | 85efb96fa45ecfa3f526374c677e57c70e3dc617 | 3,651,608 |
def make_bench_verify_token(alg):
""" Return function which will generate token for particular algorithm """
privk = priv_keys[alg].get('default', priv_key)
token = jwt.generate_jwt(payload, privk, alg, timedelta(days=1))
def f(_):
""" Verify token """
pubk = pub_keys[alg].get('default',... | 4e7da537ab7027711d338d6d3155c198c371391b | 3,651,609 |
def status():
""" Status of the API """
return jsonify({'status': 'OK'}) | 579c265c88ac8e2c3b5d19000564e90f106be3f5 | 3,651,610 |
def calc_median(input_list):
"""sort the list and return median"""
new_list = sorted(input_list)
len_list = len(new_list)
if len_list%2 == 0:
return (new_list[len_list/2-1] + new_list[len_list/2] ) / 2
else:
return new_list[len_list/2] | 28c0331d1f2dab56d50d63fa59d4dda79a177057 | 3,651,611 |
def _load_eigenvalue(h5_result, log):
"""Loads a RealEigenvalue"""
class_name = _cast(h5_result.get('class_name'))
table_name = '???'
title = ''
nmodes = _cast(h5_result.get('nmodes'))
if class_name == 'RealEigenvalues':
obj = RealEigenvalues(title, table_name, nmodes=nmodes)
elif cl... | f27d65d84481e1bb91a0d2282945da0944de1190 | 3,651,612 |
def _GenerateBaseResourcesAllowList(base_module_rtxt_path,
base_allowlist_rtxt_path):
"""Generate a allowlist of base master resource ids.
Args:
base_module_rtxt_path: Path to base module R.txt file.
base_allowlist_rtxt_path: Path to base allowlist R.txt file.
Returns:... | b6b3ef988b343115e4e1b2950667f07fd3771b19 | 3,651,613 |
def finite_min_max(array_like):
""" Obtain finite (non-NaN, non-Inf) minimum and maximum of an array.
Parameters
----------
array_like : array_like
A numeric array of some kind, possibly containing NaN or Inf values.
Returns
-------
tuple
Two-valued tuple containing the fin... | c300b55d2e53685fb0ade9809e13af4cfae4b1a8 | 3,651,614 |
def list_extend1(n):
"""
using a list to built it up, then convert to a numpy array
"""
l = []
num_to_extend = 100
data = range(num_to_extend)
for i in xrange(n/num_to_extend):
l.extend(data)
return np.array(l) | 7a2240a397e32fc438f4245b92f97f103752b60c | 3,651,615 |
def ccf(tdm, tsuid_list_or_dataset, lag_max=None, tsuids_out=False, cut_ts=False):
"""
This function calculates the maximum of the cross correlation function matrix between all ts
in tsuid_list_or_dataset in a serial mode.
The result is normalized (between -1 and 1)
Cross correlation is a correlati... | be3b5ccae3686fdef2e71eca87bc8131519d0398 | 3,651,616 |
def filter_zoau_installs(zoau_installs, build_info, minimum_zoau_version):
"""Sort and filter potential ZOAU installs based on build date
and version.
Args:
zoau_installs (list[dict]): A list of found ZOAU installation paths.
build_info (list[str]): A list of build info strings
minim... | 6e6c2de214c75630091b89e55df2e57fd9be12b9 | 3,651,617 |
def make_chain(node, address, privkeys, parent_txid, parent_value, n=0, parent_locking_script=None, fee=DEFAULT_FEE):
"""Build a transaction that spends parent_txid.vout[n] and produces one output with
amount = parent_value with a fee deducted.
Return tuple (CTransaction object, raw hex, nValue, scriptPubKe... | 07f18e227f13c146c6fba0a9487c73337654a2a3 | 3,651,618 |
import argparse
def parse_args():
"""
Parse input arguments
Returns
-------
args : object
Parsed args
"""
h = {
"program": "Simple Baselines training",
"train_folder": "Path to training data folder.",
"batch_size": "Number of images to load per batch. Set ac... | 5edfea499b64d35295ffd81403e3253027503d41 | 3,651,619 |
from datetime import datetime
def timestamp(date):
"""Get the timestamp of the `date`, python2/3 compatible
:param datetime.datetime date: the utc date.
:return: the timestamp of the date.
:rtype: float
"""
return (date - datetime(1970, 1, 1)).total_seconds() | a708448fb8cb504c2d25afa5bff6208abe1159a4 | 3,651,620 |
def pratt_arrow_risk_aversion(t, c, theta, **params):
"""Assume constant relative risk aversion"""
return theta / c | ccbe6e74a150a4cbd3837ca3ab24bf1074d694c9 | 3,651,621 |
def parse_content_type(content_type):
"""
Parse a content-type and its parameters into values.
RFC 2616 sec 14.17 and 3.7 are pertinent.
**Examples**::
'text/plain; charset=UTF-8' -> ('text/plain', [('charset, 'UTF-8')])
'text/plain; charset=UTF-8; level=1' ->
('text/plain'... | ba7f93853299dafdd4afc342b5ba2ce7c6fdd3e7 | 3,651,622 |
def mapplot(df, var, metric, ref_short, ref_grid_stepsize=None, plot_extent=None, colormap=None, projection=None,
add_cbar=True, figsize=globals.map_figsize, dpi=globals.dpi,
**style_kwargs):
"""
Create an overview map from df using df[var] as color.
Plots a scatt... | e1bf50a214b169c9b13ddbf86a6bded0df5c5310 | 3,651,623 |
def generate_athena(config):
"""Generate Athena Terraform.
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
dict: Athena dict to be marshalled to JSON
"""
result = infinitedict()
prefix = config['global']['account']['prefix']
athena_config = confi... | 4fd3a18e5220e82a04451271f1ea8004978b4c65 | 3,651,624 |
def _angular_rate_to_rotvec_dot_matrix(rotvecs):
"""Compute matrices to transform angular rates to rot. vector derivatives.
The matrices depend on the current attitude represented as a rotation
vector.
Parameters
----------
rotvecs : ndarray, shape (n, 3)
Set of rotation vectors.
... | c0d468901ec7dc4d6da7f5eff7b95ac3fc176901 | 3,651,625 |
from typing import Any
def get_all_learners() -> Any:
"""Get all learner configurations which are prepared."""
return {
"learner_types": sorted(
[
possible_dir.name
for possible_dir in LEARNERS_DIR.iterdir()
if possible_dir.is_dir()
... | d05fd8d9da820061cea29d25002513e778c2b367 | 3,651,626 |
def getdate(targetconnection, ymdstr, default=None):
"""Convert a string of the form 'yyyy-MM-dd' to a Date object.
The returned Date is in the given targetconnection's format.
Arguments:
- targetconnection: a ConnectionWrapper whose underlying module's
Date format is used
- y... | 21d27c3ef4e99b28b16681072494ce573e592255 | 3,651,627 |
def thermal_dm(n, u):
"""
return the thermal density matrix for a boson
n: integer
dimension of the Fock space
u: float
reduced temperature, omega/k_B T
"""
nlist = np.arange(n)
diags = exp(- nlist * u)
diags /= np.sum(diags)
rho = lil_matrix(n)
rho.setdiag(diags)... | 80631a0575176e16e8832cb6c136030bcd589c58 | 3,651,628 |
def _get_confidence_bounds(confidence):
"""
Get the upper and lower confidence bounds given a desired confidence level.
Args:
confidence (float): [description]
# TODO: ^^
Returns:
float, float:
- upper confidence bound
- lower confidence bound
... | 26542f3a103c7e904634f0b0c6d4e2fc522d358c | 3,651,629 |
from zope.configuration import xmlconfig, config
def zcml_strings(dir, domain="zope", site_zcml=None):
"""Retrieve all ZCML messages from `dir` that are in the `domain`."""
# Load server-independent site config
context = config.ConfigurationMachine()
xmlconfig.registerCommonDirectives(context)
co... | 23c62c50b313f53b25ad151ebccd5808bf7bad59 | 3,651,630 |
def const_p(a: C) -> Projector[C]:
"""
Make a projector that always returns the same still frame
"""
return lambda _: a | d73fb818f0606f9a64cb0076c99ff57c0b3bb042 | 3,651,631 |
import json
def get_s3_bucket(bucket_name, s3):
""""
Takes the s3 and bucket_name and returns s3 bucket
If does not exist, it will create bucket with permissions
"""
bucket_name = bucket_name.lower().replace('/','-')
bucket = s3.Bucket(bucket_name)
exists = True
try:
s3.meta.cl... | 67e9ede766989894aa86d2af1c766a57c4ed7116 | 3,651,632 |
def rf_render_ascii(tile_col):
"""Render ASCII art of tile"""
return _apply_column_function('rf_render_ascii', tile_col) | d697014f019b303c3c7de0e874e8d321c5d96f7a | 3,651,633 |
import json
def index():
""" Display productpage with normal user and test user buttons"""
global productpage
table = json2html.convert(json = json.dumps(productpage),
table_attributes="class=\"table table-condensed table-bordered table-hover\"")
return render_template(... | e27de5745c9e20f8942ea1ae3b07a4afa932b0f3 | 3,651,634 |
def student_classes(id):
"""
Show students registrered to class
* display list of all students (GET)
"""
template = "admin/class_students.html"
if not valid_integer(id):
return (
render_template(
"errors/custom.html", title="400", message="Id must be intege... | b431a21e39c97cbcc21d161a411cc9f3a3746cc8 | 3,651,635 |
def _get_service_handler(request, service):
"""Add the service handler to the HttpSession.
We use the django session object to store the service handler's
representation of the remote service between sequentially logic steps.
This is done in order to improve user experience, as we avoid making
multi... | 388b0a98c24039f629e5794427877d98d702d1e2 | 3,651,636 |
def f_score(overlap_count, gold_count, guess_count, f=1):
"""Compute the f1 score.
:param overlap_count: `int` The number of true positives.
:param gold_count: `int` The number of gold positives (tp + fn)
:param guess_count: `int` The number of predicted positives (tp + fp)
:param f: `int` The beta... | 6c7c0e3e58aa7fe4ca74936ce9029b6968ed6ee3 | 3,651,637 |
import math
def phi(n):
"""Calculate phi using euler's product formula."""
assert math.sqrt(n) < primes[-1], "Not enough primes to deal with " + n
# For details, check:
# http://en.wikipedia.org/wiki/Euler's_totient_function#Euler.27s_product_formula
prod = n
for p in primes:
if p > n... | d17f0b5901602a9a530427da2b37d0402ef426ce | 3,651,638 |
import logging
def run_bert_pretrain(strategy, custom_callbacks=None):
"""Runs BERT pre-training."""
bert_config = configs.BertConfig.from_json_file(FLAGS.bert_config_file)
if not strategy:
raise ValueError('Distribution strategy is not specified.')
# Runs customized training loop.
logging.info('Train... | 16397fb83bb02e2f01c716f97f6f461e4675c319 | 3,651,639 |
import json
def add_mutes(guild_id: int, role_id: int, user_id: int, author_id: int, datetime_to_parse: str):
"""
Add a temporary mute to a user.
NOTE: datetime_to_parse should be a string like: "1 hour 30 minutes"
"""
with open("data/unmutes.json", "r+", newline='\n', encoding='utf-8') as temp_fi... | 8c762f56217ee940d8803e069f1b3bce47629a2e | 3,651,640 |
def operation_dict(ts_epoch, request_dict):
"""An operation as a dictionary."""
return {
"model": request_dict,
"model_type": "Request",
"args": [request_dict["id"]],
"kwargs": {"extra": "kwargs"},
"target_garden_name": "child",
"source_garden_name": "parent",
... | e7b63d79c6de73616b39e2713a0ba2da6f9e2a25 | 3,651,641 |
def unix_timestamp(s=None, p="yyyy-MM-dd HH:mm:ss"):
"""
:rtype: Column
>>> import os, time
>>> os.environ['TZ'] = 'Europe/Paris'
>>> if hasattr(time, 'tzset'): time.tzset()
>>> from pysparkling import Context, Row
>>> from pysparkling.sql.session import SparkSession
>>> spark = SparkSe... | 82dce864f70ef367f5a38bcc39aec1bf996d66e9 | 3,651,642 |
def memory_index(indices, t):
"""Location of an item in the underlying memory."""
memlen, itemsize, ndim, shape, strides, offset = t
p = offset
for i in range(ndim):
p += strides[i] * indices[i]
return p | ed97592aa5444cfd6d6894b042b5b103d2de6afc | 3,651,643 |
def createExpData(f, xVals):
"""Asssumes f is an exponential function of one argument
xVals is an array of suitable arguments for f
Returns array containing results of applying f to the
elements of xVals"""
yVals = []
for i in range(len(xVals)):
yVals.append(f(x... | 79c6575ec07579e792e77b65960992a48837f2e9 | 3,651,644 |
from typing import Tuple
import math
def discrete_one_samp_ks(distribution1: np.array, distribution2: np.array, num_samples: int) -> Tuple[float, bool]:
"""Uses the one-sample Kolmogorov-Smirnov test to determine if the empirical results in
distribution1 come from the distribution represented in distribution2... | 37e85c695f0e33c70566e5462fb55e7882fbcd02 | 3,651,645 |
def _get_product_refs(pkgs):
"""Returns a list of product references as declared in the specified packages list.
Args:
pkgs: A `list` of package declarations (`struct`) as created by
`packages.create()`, `packages.pkg_json()` or `spm_pkg()`.
Returns:
A `list` of product refer... | f545f261e237dfe447533c89a489abb863b994e8 | 3,651,646 |
def merge_intervals(interval_best_predictors):
"""
Merge intervals with the same best predictor
"""
predictor2intervals = defaultdict(set)
for interval, best_predictor in interval_best_predictors.items():
predictor2intervals[best_predictor].update(interval)
merged_intervals = {best_predi... | 6ebd0b5b26193c5d3885e603ab3bae68d395d6b1 | 3,651,647 |
def build_pixel_sampler(cfg, **default_args):
"""Build pixel sampler for segmentation map."""
return build_module_from_cfg(cfg, PIXEL_SAMPLERS, default_args) | f7d687b80c7bb3cfa266b65691574e40291021d2 | 3,651,648 |
def solution_to_schedule(solution, events, slots):
"""Convert a schedule from solution to schedule form
Parameters
----------
solution : list or tuple
of tuples of event index and slot index for each scheduled item
events : list or tuple
of :py:class:`resources.Event` instances
... | 7470849f90e445f8146c561a49646d4bd8bbb886 | 3,651,649 |
def flip_tiles( tiles ):
"""
Initially all tiles are white. Every time, a tile is visited based on the
directions, it is flipped (to black, or to white again).
The directions are represented in (x,y) coordinates starting from reference
tile at (0,0).
Based on the given directions to each ... | 91628f0ae4d1713f1fa12dad34d2a3e2f97b663e | 3,651,650 |
def version() -> int:
"""Return the version number of the libpq currently loaded.
The number is in the same format of `~psycopg.ConnectionInfo.server_version`.
Certain features might not be available if the libpq library used is too old.
"""
return impl.PQlibVersion() | cc8360372787d08f3852cb8d908db780fe3c9573 | 3,651,651 |
import scipy
def feature_predictors_from_ensemble(features, verbose=False):
"""generates a dictionary of the form
{"offset":offset_predictor, "sigma":sigma_predictor, ...}
where the predictors are generated from the center and spread statistics
of the feature ensemble.
features: list
... | ea26d0640fa6dd8b948c8620b266519137805979 | 3,651,652 |
import requests
def remoteLoggingConfig(host, args, session):
"""
Called by the logging function. Configures remote logging (rsyslog).
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the logging sub command
@param s... | 04417970f671f79af0157d82ea048b5c4f8f957d | 3,651,653 |
import numpy as np
from typing import Union
import pathlib
def _merge_3d_t1w(filename: Union[str, PathLike]) -> pathlib.Path:
"""
Merges T1w images that have been split into two volumes
Parameters
----------
filename : str or pathlib.Path
Path to T1w image that needs to be merged
Returns
-------
filename ... | f1eae741c270553ee18c6f4cc2eb2484215617db | 3,651,654 |
def get_partial_results(case_name, list_of_variables):
""" Get a dictionary with the variable names and the time series for `list_of_variables`
"""
reader = get_results(case_name)
d = dict()
read_time = True
for v in list_of_variables:
if read_time:
d['time'] = reader.values(... | 43954296a11bea2c8a04f2e65a709c56ea14d00a | 3,651,655 |
def take_with_time(self, duration, scheduler=None):
"""Takes elements for the specified duration from the start of the
observable source sequence, using the specified scheduler to run timers.
Example:
res = source.take_with_time(5000, [optional scheduler])
Description:
This operator accumulat... | d96ce7ae892fe6700b9f14cccbb01e3aa45b9b76 | 3,651,656 |
def add_label(hdf5_filename, key, peak, label):
"""
Function that adds a label to a peak dataset in the hdf5 file.It
has to be iterated over every single peak.
Parameters:
hdf5_filename (string): filename of experimental file
key (string): key within `hdf5_filename` of experime... | b903d59ae8e18adf2942227fc6b4c0e207dbde78 | 3,651,657 |
def _infer_color_variable_kind(color_variable, data):
"""Determine whether color_variable is array, pandas dataframe, callable,
or scikit-learn (fit-)transformer."""
if hasattr(color_variable, "dtype") or hasattr(color_variable, "dtypes"):
if len(color_variable) != len(data):
raise Value... | a1a21c6df4328331754f9fb960e64cf8bfe09be7 | 3,651,658 |
import os
def ParseChromeosImage(chromeos_image):
"""Parse the chromeos_image string for the image and version.
The chromeos_image string will probably be in one of two formats:
1: <path-to-chroot>/src/build/images/<board>/<ChromeOS-version>.<datetime>/ \
chromiumos_test_image.bin
2: <path-to-chroot>/ch... | 49652dad39bcc1df8b3decae4ec374adaf353185 | 3,651,659 |
import random
def Dense(name, out_dim, W_init=stax.glorot(), b_init=stax.randn()):
"""Layer constructor function for a dense (fully-connected) layer."""
def init_fun(rng, example_input):
input_shape = example_input.shape
k1, k2 = random.split(rng)
W, b = W_init(k1, (out_dim, input_shap... | a2b20961ff3fd23e0cd87f200d1c575d9788e076 | 3,651,660 |
from datetime import datetime
def datetime_to_epoch(date_time: datetime) -> int:
"""Convert a datetime object to an epoch integer (seconds)."""
return int(date_time.timestamp()) | 73767c663d66464420594e90a438687c9363b884 | 3,651,661 |
def parse_arguments():
"""
Merge the scar.conf parameters, the cmd parameters and the yaml
file parameters in a single dictionary.
The precedence of parameters is CMD >> YAML >> SCAR.CONF
That is, the CMD parameter will override any other configuration,
and the YAML parameters will override the... | a34525ed55514db2133c5c39d273ea48af8f8c54 | 3,651,662 |
from typing import BinaryIO
def check_signature(stream: BinaryIO) -> str:
"""
Check signature of the model file and return characters used by the model.
The characters returned are sorted in lexicographical order.
"""
uzmodel_tag = stream.read(8)
if uzmodel_tag != b'UZMODEL ':
raise I... | 3a8d2e646a2ffe08a471f5447d8e790aefd6fc68 | 3,651,663 |
def Validate(expected_schema, datum):
"""Determines if a python datum is an instance of a schema.
Args:
expected_schema: Schema to validate against.
datum: Datum to validate.
Returns:
True if the datum is an instance of the schema.
"""
schema_type = expected_schema.type
if schema_type == 'null'... | 22ed46f2d82f9c4ea53fdd707553d54958a20814 | 3,651,664 |
def get_main_play_action(action: PlayerAction) -> PlayerAction:
"""
Gets the main play, e.g., FLYOUT or SINGLE
:param action:
:return:
"""
print("Searching for main play")
# find out if the string contains any of the allowed actions
for i in PlayerActionEnum:
if i.value in acti... | ec85c305509b5f6f88eb157e7a110dbed7ad0ab4 | 3,651,665 |
from functools import reduce
def inet_aton(s):
"""Convert a dotted-quad to an int."""
try:
addr = list(map(int, s.split('.')))
addr = reduce(lambda a,b: a+b, [addr[i] << (3-i)*8 for i in range(4)])
except (ValueError, IndexError):
raise ValueError('illegal IP: {0}'.format(s))
r... | abc16c14e416f55c9ae469b4b9c1958df265433c | 3,651,666 |
def local_principals(context, principals):
""" The idea behind this is to process __ac_local_roles__ (and a boolean __ac_local_roles_block__
to disable) and add local principals. This only works if you're in correct context, though,
which does not seem to be the case.
"""
local_principals = ... | ccd2597ca1657fc7805a85c212c87d2d04cacad4 | 3,651,667 |
def helper():
"""I'm useful helper"""
data = {
"31 Dec 2019": "Wuhan Municipal Health Commission, China, reported a cluster of cases of pneumonia in Wuhan, Hubei Province. A novel coronavirus was eventually identified.",
"1 January 2020": "WHO had set up the IMST (Incident Management Support Tea... | 1f0f58505ce4179d56b2bf6e4cb29e42cdd7cfc9 | 3,651,668 |
def canonicalize_specification(expr, syn_ctx, theory):
"""Performs a bunch of operations:
1. Checks that the expr is "well-bound" to the syn_ctx object.
2. Checks that the specification has the single-invocation property.
3. Gathers the set of synth functions (should be only one).
4. Gathers the var... | 99613fb5cc78b53ca094ffb46cc927f05d5f74d4 | 3,651,669 |
def human_time(seconds, granularity=2):
"""Returns a human readable time string like "1 day, 2 hours"."""
result = []
for name, count in _INTERVALS:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip("s")
... | 25d184982e5c0c2939814938f09a72ab2d46d270 | 3,651,670 |
def cmorlet_wavelet(x, fs, freq_vct, n=6, normalization=True):
"""Perform the continuous wavelet (CWT) tranform using the complex Morlet wavelet.
Parameters
----------
x : 1D array with shape (n_samples) or
2D array with shape (n_samples, n_channels)
fs : Sampling frequency
... | 13a5e2b16c2641b8fabf997679f4d8f6724d32a9 | 3,651,671 |
import os
def update(key=None, value=None, cache_type=None, file_path=None):
"""Set the cache that depends on the file access time
:param key: the key for the cache
:param value: the value in the cache
:param cache_type: when we are using cache in different modules this param
can protects ... | 454b928dbacbcfa297aaf9385af1f185187857c9 | 3,651,672 |
from typing import Tuple
from typing import Union
from typing import List
def add_fake_planet(
stack: np.ndarray,
parang: np.ndarray,
psf_template: np.ndarray,
polar_position: Tuple[Quantity, Quantity],
magnitude: float,
extra_scaling: float,
dit_stack: float,
dit_psf_template: float,
... | f5897585934fe9609a4d6cc0f032285194a59f19 | 3,651,673 |
import os
import json
import tqdm
def make_cache(channel, subdir):
"""Reads and/or generates the cachefile and returns the cache"""
# load cache
channel_name = _get_channel_name(channel)
cachefile = f"{channel_name}.{subdir}.cache.json"
if os.path.exists(cachefile):
print(f"Loading cache f... | 35443f07821602ef380a3040ad9f80f937a9674a | 3,651,674 |
def _BD_from_Av_for_dereddening(line_lambdas, line_fluxes, A_v):
"""
Find the de-reddened Balmer decrement (BD) that would arise from "removing"
an extinction of A_v (magnitudes) from the line_fluxes.
line_lambdas, line_fluxes: As in the function "deredden".
A_v: The extinction (magnitudes), as a sc... | 280255db3669b8ee585afbcb685dc97dfbedc5c0 | 3,651,675 |
def otherEnd(contours, top, limit):
"""
top与end太近了,找另一个顶部的点,与top距离最远
"""
tt = (0, 9999)
for li in contours:
for pp in li:
p = pp[0]
if limit(p[0]) and top[1] - p[1] < 15 and abs(top[0] - p[0]) > 50 and p[1] < tt[1]:
tt = p
return tt | 4f938d33ba28c1999603cd60381ed6d9aec23815 | 3,651,676 |
import os
def plivo_webhook(event, context):
"""
Receives SMS messages and forwards them to telegram
"""
CHAT_ID = int(os.environ['CHAT_ID'])
bot = configure_telegram()
logger.info('Plivo Event: {}'.format(event))
try:
body = parse_plivo_msg(event)
except AssertionError as e:... | 580925e10f32c717116487a6c0e3623f724ad16a | 3,651,677 |
from matador.workflows.castep.common import castep_prerelax
def castep_phonon_prerelax(computer, calc_doc, seed):
""" Run a singleshot geometry optimisation before an SCF-style calculation.
This is typically used to ensure phonon calculations start successfully.
The phonon calculation will then be restart... | 4687e6cdf7150c8721329c7ea1b007e47ee3cd7e | 3,651,678 |
def get_external_links(soup):
"""Retrieve the different links from a `Lyric Wiki` page.
The links returned can be found in the `External Links` page section,
and usually references to other platforms (like Last.fm, Amazon, iTunes etc.).
Args:
soup (bs4.element.Tag): connection to the `Lyric Wik... | 9d1f654176cfe5ccdc849448b5cf1720dba4e6c5 | 3,651,679 |
def gcc():
"""Return the current container, that is the widget holding the figure and all the control widgets, buttons etc."""
gcf() # make sure we have something..
return current.container | d32b9c53694ad258976757b15cc0982431b06e8e | 3,651,680 |
def preprocessing(string):
"""helper function to remove punctuation froms string"""
string = string.replace(',', ' ').replace('.', ' ')
string = string.replace('(', '').replace(')', '')
words = string.split(' ')
return words | 17f41a566c3661ab6ffb842ac6d610425fc779d1 | 3,651,681 |
def add_input_arguments(argument_parser_object):
"""Adds input args for this script to `argparse.ArgumentParser` object.
:param argument_parser_object: `argparse.ArgumentParser` object, which may
or may not already contain input args.
:return: argument_parser_object: Same as input object, but with ... | 7e4b407aff10148c9843ba33410c233a32acc36d | 3,651,682 |
def fullUnitSphere(res):
"""Generates a unit sphere in the same way as :func:`unitSphere`, but
returns all vertices, instead of the unique vertices and an index array.
:arg res: Resolution - the number of angles to sample.
:returns: A ``numpy.float32`` array of size ``(4 * (res - 1)**2, 3)``
... | 65d83a83b17087934847ab7db8200a67c79294d4 | 3,651,683 |
def prompt_for_word_removal(words_to_ignore=None):
"""
Prompts the user for words that should be ignored in kewword extraction.
Parameters
----------
words_to_ignore : str or list
Words that should not be included in the output.
Returns
-------
ignore words, words_a... | 65615f3fe5f0391f44d60e7e9a2990d8fea35bc0 | 3,651,684 |
import time
def wait_for_image_property(identifier, property, cmp_func,
wait=20,
maxtries=10):
"""Wait for an image to have a given property.
Raises TimeoutError on failure.
:param identifier: the image identifier
:param property: the name of th... | 27ad96fceb931a73deddb49fb40975dd295ebd36 | 3,651,685 |
import os
def make_sample_ensemble_seg_plot(model2, model3, sample_filenames, test_samples_fig, flag='binary'):
"""
"make_sample_ensemble_seg_plot(model2, model3, sample_filenames, test_samples_fig, flag='binary')"
This function uses two trained models to estimate the label image from each input image
... | 635f237659c6ba123c494175925d5ce5070b850c | 3,651,686 |
def mock_requests_get_json_twice(mocker: MockerFixture) -> MagicMock:
"""Mock two pages of results returned from the parliament open data API."""
mock: MagicMock = mocker.patch("requests.get")
mock.return_value.__enter__.return_value.json.side_effect = [
{
"columnNames": ["column1", "col... | 1c546963b5a2503c8d65d87ee373c2d2c5981b2a | 3,651,687 |
def _get_rating_accuracy_stats(population, ratings):
"""
Calculate how accurate our ratings were.
:param population:
:param ratings:
:return:
"""
num_overestimates = 0
num_underestimates = 0
num_correct = 0
for employee, rating in zip(population, ratings):
if rating < em... | 6fefd6faf465a304acc692b465f575cc4c3a62e3 | 3,651,688 |
import hashlib
def genb58seed(entropy=None):
"""
Generate a random Family Seed for Ripple. (Private Key)
entropy = String of any random data. Please ensure high entropy.
## Note: ecdsa library's randrange() uses os.urandom() to get its entropy.
## This should be secure enough... but just in ... | 1bfbbbff5abffa2bac0fd2accf9480387ff2e8bb | 3,651,689 |
def convert_nhwc_to_nchw(data: np.array) -> np.array:
"""Convert data to NCHW."""
return np.transpose(data, [0, 3, 1, 2]) | 5ca229d9dfcb388d3f3a487b51719eaa0dd8fdb6 | 3,651,690 |
def get_mfcc_features(wave_data: pd.Series, n_mfcc):
"""
mfcc_feature
"""
x = wave_data.apply(lambda d: (d-np.mean(d))/(np.std(d)))
# x = wave_data
x, max_length = utils.padding_to_max(x)
features = []
for i in range(x.shape[0]):
t1 = mfcc(x[i], sr=16000, n_mfcc=n_mfcc)
t... | 2f5fa5a4f752c4d5af963bd390868f98e886c0d9 | 3,651,691 |
def download_instance_func(instance_id):
"""Download a DICOM Instance as DCM"""
file_bytes = client.orthanc.download_instance_dicom(instance_id)
return flask.send_file(BytesIO(file_bytes), mimetype='application/dicom', as_attachment=True, attachment_filename=f'{instance_id}.dcm') | bbd506904096da9d73f3c0f33dd30ba869551025 | 3,651,692 |
def generate_random_initial_params(n_qubits, n_layers=1, topology='all', min_val=0., max_val=1., n_par=0, seed=None):
"""Generate random parameters for the QCBM circuit (iontrap ansatz).
Args:
n_qubits (int): number of qubits in the circuit.
n_layers (int): number of entangling layers in the ci... | f3beaa9b36b704d8289c91c46895247275a69ef1 | 3,651,693 |
def number_of_friends(user):
"""How many friends does this user have?"""
user_id = user["id"]
friend_ids = friendships[user_id]
return len(friend_ids) | 3f17dfb1e2c3829c650727d36a34a24885d4d77d | 3,651,694 |
def get_serializer_class(format=None):
"""Convenience function returns serializer or raises SerializerNotFound."""
if not format:
serializer = BaseSerializer()
elif format == 'json-ld':
serializer = JsonLDSerializer()
elif format == 'json':
serializer = JsonSerializer()
else:... | 7660ba2f7861773d6a4e8d5796facbbe96259503 | 3,651,695 |
from typing import Optional
from typing import Any
def get_or_create_mpc_section(
mp_controls: "MpConfigControls", section: str, subkey: Optional[str] = None # type: ignore
) -> Any:
"""
Return (and create if it doesn't exist) a settings section.
Parameters
----------
mp_controls : MpConfigC... | 60b741f35e0a1c9fe924b472217e0e3b62a1d31e | 3,651,696 |
import csv
def get_sql_table_headers(csv_dict_reader: csv.DictReader) -> str:
""" This takes in a csv dictionary reader type, and returns a list of the headings needed to make a table """
column_names = []
for row in csv_dict_reader:
for column in row:
column_names.append('{} {} '.form... | b874ca3992eac45ed1708434a5adfd28fd96c1cd | 3,651,697 |
from unittest.mock import call
def greater_than(val1, val2):
"""Perform inequality check on two unsigned 32-bit numbers (val1 > val2)"""
myStr = flip_string(val1) + flip_string(val2)
call(MATH_32BIT_GREATER_THAN,myStr)
return ord(myStr[0]) == 1 | b9bba2aa776dc71320df736c654a5c0163827dff | 3,651,698 |
from re import I
def upsampling_2x_blocks(n_speakers, speaker_dim, target_channels, dropout):
"""Return a list of Layers that upsamples the input by 2 times in time dimension.
Args:
n_speakers (int): number of speakers of the Conv1DGLU layers used.
speaker_dim (int): speaker embedding size of... | e2a31c4ef7c392d86e5cf6ac96891b1a57a3692e | 3,651,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.