content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
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 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 |
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 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 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 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 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 |
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 |
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 |
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 |
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 |
def actor_path(data, actor_id_1, goal_test_function):
"""
Creates the shortest possible path from the given actor ID to
any actor that satisfies the goal test function.
Returns a a list containing actor IDs.
If no actors satisfy the goal condition, returns None.
"""
agenda = {actor... | 8e41d7075b3ade8f75481959f9aa376a096aaa1c | 3,651,700 |
def M_to_E(M, ecc):
"""Eccentric anomaly from mean anomaly.
.. versionadded:: 0.4.0
Parameters
----------
M : float
Mean anomaly (rad).
ecc : float
Eccentricity.
Returns
-------
E : float
Eccentric anomaly.
"""
with u.set_enabled_equivalencies(u.di... | 071f33a294edf6627ad77caa256de48e94afad76 | 3,651,702 |
def encrypt(plaintext, a, b):
"""
加密函数:E(x) = (ax + b)(mod m) m为编码系统中的字母数,一般为26
:param plaintext:
:param a:
:param b:
:return:
"""
cipher = ""
for i in plaintext:
if not i.isalpha():
cipher += i
else:
n = "A" if i.isupper() else "a"
... | 0cbb57250d8d7a18740e19875f79127b8057ab06 | 3,651,704 |
def _url_as_filename(url: str) -> str:
"""Return a version of the url optimized for local development.
If the url is a `file://` url, it will return the remaining part
of the url so it can be used as a local file path. For example,
'file:///logs/example.txt' will be converted to
'/logs/example.txt'... | d1aef7a08221c7788f8a7f77351ccb6e6af9416b | 3,651,707 |
from typing import Dict
def hard_max(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]):
""" ONNX Hardmax to XLayer AnyOp conversion function
Input tensor shape: N dims
Output tensor shape: 2D
"""
logger.info("ONNX Hardmax -> XLayer AnyOp")
... | 5f412e98836cd377d40a759ab0487aa81cc4f3dc | 3,651,708 |
from typing import AnyStr
from typing import List
def sol_files_by_directory(target_path: AnyStr) -> List:
"""Gathers all the .sol files inside the target path
including sub-directories and returns them as a List.
Non .sol files are ignored.
:param target_path: The directory to look for .sol files
... | e41ad3da26ffa1d3c528f34362ac1aeeadeb2b3c | 3,651,709 |
def _call(sig, *inputs, **kwargs):
"""Adds a node calling a function.
This adds a `call` op to the default graph that calls the function
of signature `sig`, passing the tensors in `inputs` as arguments.
It returns the outputs of the call, which are one or more tensors.
`sig` is OpDefArg.a `_DefinedFunction`... | 6fd65281118e33bbcd9d567a7c528d85976e75e7 | 3,651,710 |
import torch
def cov(x, rowvar=False, bias=False, ddof=None, aweights=None):
"""Estimates covariance matrix like numpy.cov"""
# ensure at least 2D
if x.dim() == 1:
x = x.view(-1, 1)
# treat each column as a data point, each row as a variable
if rowvar and x.shape[0] != 1:
x = x.t(... | 6b5666a3e7fa6fe0c0e115286e10d2e756ba8ee9 | 3,651,712 |
def threadsafe_generator(f):
"""A decorator that takes a generator function and makes it thread-safe.
Args:
f(function): Generator function
Returns:
None
"""
def g(*args, **kwargs):
"""
Args:
*args(list): List of non-key worded,variable length arguments.
... | 6a3e53984c85c951e5ffefa2ed238af86d8fc3e3 | 3,651,713 |
def load_many_problems(file, collection):
"""Given a ZIP file containing several ZIP files (each one a problem),
insert the problems into collection"""
problems = list()
try:
with ZipFile(file) as zfile:
for filename in zfile.infolist():
with zfile.open(filename) a... | 08d60f5c7905397254715f80e74019f3496d84e5 | 3,651,714 |
def CheckStructuralModelsValid(rootGroup, xyzGridSize=None, verbose=False):
"""
**CheckStricturalModelsValid** - Checks for valid structural model group data
given a netCDF root node
Parameters
----------
rootGroup: netCDF4.Group
The root group node of a Loop Project File
xyzGri... | d11ce42b041b8be7516f827883a37b40f6f98477 | 3,651,715 |
def get_load_balancers():
"""
Return all load balancers.
:return: List of load balancers.
:rtype: list
"""
return elbv2_client.describe_load_balancers()["LoadBalancers"] | b535f47ce94106a4c7ebe3d84ccfba7c57f22ba9 | 3,651,716 |
def file_preview(request):
"""
Live preview of restructuredtext payload - currently not wired up
"""
f = File(
heading=request.POST['heading'],
content=request.POST['content'],
)
rendered_base = render_to_string('projects/doc_file.rst.html', {'file': f})
rendered = restructur... | e83570b7b31b4a2d526f1699f8b65c5623d6f7ee | 3,651,718 |
def makeMask(n):
"""
return a mask of n bits as a long integer
"""
return (long(2) << n - 1) - 1 | c0fe084ec9d6be1519115563cce3c0d3649947c6 | 3,651,719 |
def link_name_to_index(model):
""" Generate a dictionary for link names and their indicies in the
model. """
return {
link.name : index for index, link in enumerate(model.links)
} | ba0e768b1160218908b6ecf3b186a73c75a69894 | 3,651,720 |
import json
def photos_page():
"""
Example view demonstrating rendering a simple HTML page.
"""
context = make_context()
with open('data/featured.json') as f:
context['featured'] = json.load(f)
return make_response(render_template('photos.html', **context)) | dfb172e01f659be163c7dffdb13cc5cbaa28ab10 | 3,651,722 |
import json
def get_user_by_id(current_user, uid):
""" Получение одного пользователя по id в json"""
try:
user_schema = CmsUsersSchema(exclude=['password'])
user = CmsUsers.query.get(uid)
udata = user_schema.dump(user)
response = Response(
response=json.dumps(udat... | 9f91319020fb0b386d506b4365c2912af3ed5874 | 3,651,723 |
def update_bond_lists_mpi(bond_matrix, comm, size, rank):
"""
update_bond_lists(bond_matrix)
Return atom indicies of angular terms
"""
N = bond_matrix.shape[0]
"Get indicies of bonded beads"
bond_index_full = np.argwhere(bond_matrix)
"Create index lists for referring to in 2D arrays"
indices_full = create_... | 60fd4e5ee7418d182f0c29b0d69e0f148a5a40ee | 3,651,724 |
from ibis.omniscidb.compiler import to_sql
def compile(expr: ibis.Expr, params=None):
"""Compile a given expression.
Note you can also call expr.compile().
Parameters
----------
expr : ibis.Expr
params : dict
Returns
-------
compiled : string
"""
return to_sql(expr, dia... | 01bfe1be13b9a78adba04ca37a08aadbf551c827 | 3,651,726 |
def get_border(border, size):
"""
Get border
"""
i = 1
while size - border // i <= border // i: # size > 2 * (border // i)
i *= 2
return border // i | 45233f53cdf6f0edb5b4a9262b61f2a70ac42661 | 3,651,727 |
def load_normalized_data(file_path, log1p=True):
"""load normalized data
1. Load filtered data for both FACS and droplet
2. Size factor normalization to counts per 10 thousand
3. log(x+1) transform
4. Combine the data
Args:
file_path (str): file path.
Returns:
adata_combin... | 3c180c1f2ba1e118678331795eb42b7132686ed6 | 3,651,728 |
def from_copy_number(
model: cobra.Model,
index: pd.Series,
cell_copies: pd.Series,
stdev: pd.Series,
vol: float,
dens: float,
water: float,
) -> cobra.Model:
"""Convert `cell_copies` to mmol/gDW and apply them to `model`.
Parameters
----------
model: cobra.Model
cob... | 858d563ad0f4ae16e83b36db3908895671809431 | 3,651,729 |
import re
def _get_values(attribute, text):
"""Match attribute in text and return all matches.
:returns: List of matches.
"""
regex = '{}\s+=\s+"(.*)";'.format(attribute)
regex = re.compile(regex)
values = regex.findall(text)
return values | 59a0fdb7a39221e5f728f512ba0aa814506bbc37 | 3,651,731 |
def time_axis(tpp=20e-9, length=20_000) -> np.ndarray:
"""Return the time axis used in experiments.
"""
ts = tpp * np.arange(length)
ten_percent_point = np.floor(length / 10) * tpp
ts -= ten_percent_point
ts *= 1e6 # convert from seconds to microseconds
return ts | 6cd18bcbfa6949fe98e720312b07cfa20fde940a | 3,651,732 |
from cyder.core.ctnr.models import CtnrUser
def _has_perm(user, ctnr, action, obj=None, obj_class=None):
"""
Checks whether a user (``request.user``) has permission to act on a
given object (``obj``) within the current session CTNR. Permissions will
depend on whether the object is within the user's cu... | 998119c3aa9b50fcdd9fdec1f734374f04fe51c6 | 3,651,733 |
def read_chunk(file: File, size: int=400) -> bytes:
""" Reads first [size] chunks from file, size defaults to 400 """
file = _path.join(file.root, file.name) # get full path of file
with open(file, 'rb') as file:
# read chunk size
chunk = file.read(size)
return chunk | dfa1fd576fe14c5551470fb76a674dccd136e200 | 3,651,734 |
def parse_input(file_path):
"""
Turn an input file of newline-separate bitrate samples into
input and label arrays. An input file line should look like this:
4983 1008073 1591538 704983 1008073 1008073 704983
Adjacent duplicate entries will be removed and lines with less than
two samples will ... | 1e1aada5b8da01d362f7deb0b2145209bb55bcc0 | 3,651,735 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.