content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def days_in_month(year, month):
""" return number of days in that month in that year """
if not 1 <= month <= 12:
return 'Invalid Month'
if month == 2 and is_leap(year):
return 29
return month_days[month] | 8e9e5878fcfb595518d33a38baaf5bdc1b45c8ed | 19,100 |
def tmm_normal(fPath, bFilter=True):
"""
Function to obtain the Voom normal Count
Args:
fPath string Path with the raw counts
outPath string File output
bFilter Bool Bool to FIlter low expression genes
Returns:
tmm dataframe DataFrame with the log2(TMM) counts
... | 4741a6af490e24485bd4ad28e7289dd320abf77d | 19,101 |
import math
def StrainFitness(all_cix_series,
all_cntrl_sum,
debug_print=False):
"""
Args:
all_cix_series (pandas Series): The current experiment name column of values from all_df_used
length = nAllStrainsCentralGoodGenes
... | 8237c99bd9af25fe728c6c133572abf2f4cba1ad | 19,102 |
import base64
def np_to_base64(img_np):
"""
Convert numpy image (RGB) to base64 string
"""
img = Image.fromarray(img_np.astype("uint8"), "RGB")
buffered = BytesIO()
img.save(buffered, format="PNG")
return "data:image/png;base64," + base64.b64encode(
buffered.getvalue()).decode("asc... | 2856e8ccf5402b5f6615bc8b66a364cef3e3a01c | 19,103 |
def sample_unknown_parameters(_params, _n=None):
"""
AW - sample_unknown_parameters - Sample the parameters we do not fix and hence wish to marginalize over.
:param _params: SimpNameSp: dot accessible simple name space of simulation parameters.
:return: SimpNameSp: dot accessible simple name spac... | 700d4ab80cd3e798fa87f9249194015377d19cc7 | 19,104 |
import logging
def vector2Table (hdu, xlabel='wavelength',ylabel='flux') :
"""
Reads a 1-D vector from a FITS HDU into a Table.
If present, the wavelength scale is hopefully in a simple, linear WCS!
"""
hdr = hdu.header
if hdr['NAXIS'] != 1 :
logging.error ('vector2Table can only construct 1-D tables!')
ret... | b0ff458f8cf6de660ae5c314f3e9db1f50aeaf3c | 19,105 |
def get_zarr_size(fn):
"""Get size of zarr file excluding metadata"""
# Open file
grp = zarr.open_group(fn)
# Collect size
total = 0
for var in list(grp.keys()):
total += grp[var].nbytes_stored
return total | e2fe053bf239156e74038672a435144cf7bc5216 | 19,106 |
def rotation_matrix(a, b):
""" Calculate rotation matrix M, such that Ma is aligned to b
Args:
a: Initial vector direction
b: Target direction
"""
# np.allclose might be safer here
if np.array_equal(a, b):
return np.eye(3)
# Allow cases where a,b are not unit vectors, s... | 948eb08758b81a6b9f2cc0f518dbb74f04970a1c | 19,107 |
from sys import version_info
def bind(filename=None, blockpairs=1):
""" Open a connection. If filename is not given or None, a filename
is chosen automatically. This function returns blockpairs number
of Writer, Reader pairs.
"""
# Open memory mapped file, deduced file size from number of blocks
... | 1cae390b7644219ca07335fa7ed078fe24bf6ca8 | 19,108 |
def saveuserprefs():
""" Fetch the preferences of the current user in JSON form """
user = current_user()
j = request.get_json(silent=True)
# Return the user preferences in JSON form
uf = UserForm()
uf.init_from_dict(j)
err = uf.validate()
if err:
return jsonify(ok=False, err=e... | 0b2e893623432f0337014df3f0a67a4d2174a082 | 19,109 |
import os
def process_args(args):
""" Process the options got from get_args()
"""
args.input_dir = args.input_dir.strip()
if args.input_dir == '' or not os.path.exists(os.path.join(args.input_dir, 'model.meta')):
raise Exception("This scripts expects the input model was exist in '{0}' directo... | 255ef1df0c5402b8d8d4dc21221f4bfd369fadf6 | 19,110 |
import torch
def make_features(batch, side, data_type='text'):
"""
Args:
batch (Tensor): a batch of source or target data.
side (str): for source or for target.
data_type (str): type of the source input.
Options are [text|img|audio].
Returns:
A sequence of src/t... | 6ffed5546ea35a7be559f58521aa119d576ed465 | 19,111 |
def page_dirs_to_file_name(page_dirs):
"""
[カテゴリ1,カテゴリ2,ページ]というディレクトリの配列状態になっているページパスを
「カテゴリ1_._カテゴリ2_._ページ」というファイル名形式に変換する。
:param page_dirs:
:return:
"""
file_name = ""
for page_dir in page_dirs:
if page_dir:
file_name = file_name + page_dir.strip() + '_._'
fil... | 1e7bb5f04900440824e7a223fbb88599add86c07 | 19,112 |
def has_field(feature_class, field_name):
"""Returns true if the feature class has a field named field_name."""
for field in arcpy.ListFields(feature_class):
if field.name.lower() == field_name.lower():
return True
return False | afe2352a1a17b9c0c48e68b68ab41595230343f9 | 19,113 |
from re import T
def process_settings(settings: AttrDict, params: T.Optional[T.Set[str]] = None, ignore: T.Iterable[str]=()) -> AttrDict:
"""
Process an dict-like input parameters, according to the rules specified in the
`Input parameter documentation <https://sqsgenerator.readthedocs.io/en/latest/input_... | 0cd49f857fe2923d71fb4be46cac4eefa1fa11bf | 19,114 |
def serialize_block(block: dict) -> Block:
"""Serialize raw block from dict to structured and filtered custom Block object
Parameters
----------
block : dict
Raw KV block data from gRPC response
Returns
-------
Block
Structured, custom defined Block object for more controll... | 05931685b970a562b108df134e26c6857bd9bb6a | 19,115 |
from pandas import get_option
def repr_pandas_Series(series, _):
"""
This function can be configured by setting the `max_rows` attributes.
"""
return series.to_string(
max_rows=repr_pandas_Series.max_rows,
name=series.name,
dtype=series.dtype,
length=get_option("displa... | 86009d8fc1559dd97361a8c5e113c5477ff73de2 | 19,116 |
def convert_fmt(fmt):
"""rs.format to pyglet format string"""
return {
rs.format.rgb8: 'RGB',
rs.format.bgr8: 'BGR',
rs.format.rgba8: 'RGBA',
rs.format.bgra8: 'BGRA',
rs.format.y8: 'L',
}[fmt] | b2f34498969d2e29d8c21367788ddcaebe205acf | 19,117 |
import math
def train_ALS(train_data, validation_data, num_iters, reg_param, ranks):
"""
Grid Search Function to select the best model based on RMSE of hold-out data
"""
# initial
min_error = float('inf')
best_rank = -1
best_regularization = 0
best_model = None
for rank in ranks:
... | 99d0584e9374a529632024caeadb88d85c681b81 | 19,118 |
import sys
def parse_input_vspec (opts):
"""Parses input from vspec and returns excitation energies in the
form [energy, f], in eV and atomic units units, respectively."""
lines = sys.stdin.readlines ()
inside_data = False
roots = []
for l in lines:
if "<START>" in l:
... | cd381ee4ab67c13a43311b9bc1bdc185c46ed86d | 19,119 |
import os
def is_yaml_file(filename):
"""Return true if 'filename' ends in .yml or .yaml, and false otherwise."""
return os.path.splitext(filename)[1] in (".yaml", ".yml") | 5d9f6faf485e3724aaef19294cfde52671505a7f | 19,120 |
import copy
def response_ack(**kwargs):
""" Policy-based provisioning of ACK value. """
try:
tlv, code, policy, post_c2c = kwargs["tlv"], kwargs["code"], kwargs["policy"], kwargs["post_c2c"]
new_tlv = copy.deepcopy(tlv)
if post_c2c is not True:
ret = policy.get_ava... | ff34cf196e0d565ebac7700f5b412f615685ca37 | 19,121 |
def is_file(path, use_sudo=False):
"""
Check if a path exists, and is a file.
"""
func = use_sudo and sudo or run
with settings(hide('running', 'warnings'), warn_only=True):
return func('[ -f "%(path)s" ]' % locals()).succeeded | 9b3402205fe972dbedfa582117b6d03bdb949122 | 19,122 |
def bounded_random_walk(minval, maxval, delta_min, delta_max, T,
dtype=tf.float32, dim=1):
"""
Simulates a random walk with boundary conditions. Used for data augmentation
along entire tube.
Based on: https://stackoverflow.com/questions/48777345/vectorized-random-
... | 18bba29b9f0c320da04eb2419a49483ee301e178 | 19,123 |
def validate_photo_url(photo_url, required=False):
"""Parses and validates the given URL string."""
if photo_url is None and not required:
return None
if not isinstance(photo_url, str) or not photo_url:
raise ValueError(
'Invalid photo URL: "{0}". Photo URL must be a non-empty '
... | 9c6d617d4b618f626c29977b0a7c4c9dc9b3f9ab | 19,124 |
def to_flp(stipples, dpi=300, x_mm=0, y_mm=0, laser_pwr=35000,
ticks=500, base=100):
"""" Converts a set of stipples into a list of FLP packets
dpi is the image's DPI
x_mm and y_mm are the corner location of the image (default 0,0)
(where 0,0 is the center of the b... | 9d826b6174478cbfb3d2033e05b9ccafb5dca79c | 19,125 |
def GetSchema(component):
"""convience function for finding the parent XMLSchema instance.
"""
parent = component
while not isinstance(parent, XMLSchema):
parent = parent._parent()
return parent | 3445acb7bade3cca15d4eeeb3da4d548ea44a206 | 19,126 |
def ranked_bots_query(alias="ranked_bots"):
"""
Builds a query that ranks all bots.
This is a function in case you need this as a subquery multiple times.
"""
return sqlalchemy.sql.select([
bots.c.user_id,
bots.c.id.label("bot_id"),
bots.c.mu,
bots.c.sigma,
b... | f6641efa611884721e33453f4fcc4af0503b4aaf | 19,127 |
def marathon_deployments_check(service):
"""Checks for consistency between deploy.yaml and the marathon yamls"""
the_return = True
pipeline_deployments = get_pipeline_config(service)
pipeline_steps = [step['instancename'] for step in pipeline_deployments]
pipeline_steps = [step for step in pipeline_... | 3f2df53652efad4b731a05b3ecc17929d65982ac | 19,128 |
def get_book_info(book_id, books):
"""Obtain meta data of certain books.
:param book_id: Books to look up
:type: int or list of ints
:param books: Dataframe containing the meta data
:type: pandas dataframe
:return: Meta data for the book ids
:rtype: List[str], List[str], List[str]
"... | 64a91a498f9bf9df918d256a7ce705e98dadbbd9 | 19,129 |
import functools
import six
def save_error_message(func):
"""
This function will work only if transition_entity is defined in kwargs and
transition_entity is instance of ErrorMessageMixin
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwa... | 9ac592100445a0232efc4afaa3807b050c8eddff | 19,130 |
def EMV(data,n=20,m=23):
"""
"""
def emv(high,low,vol,n=14):
MID = np.zeros(len(high))
MID[1:] = (np.array(high[1:])+np.array(low[1:])-np.array(high[:-1])-np.array(low[:-1]))/2.
BRO = np.array(vol)/(100000000.*(np.array(high)-np.array(low)))
EM = MID/BRO
return ta.S... | a3555738c2f0c047ad4c21ae32dcfed460a9ec5b | 19,131 |
from typing import Tuple
def desired_directions(state: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Given the current state and destination, compute desired direction."""
destination_vectors = state[:, 4:6] - state[:, 0:2]
directions, dist = normalize(destination_vectors)
return directions, dist | 02088734bd3ef6ec2e1b009d5c43e6ea9f008aab | 19,132 |
import operator
def binary_repr(number, max_length = 1025):
"""
Return the binary representation of the input *number* as a
string.
This is more efficient than using :func:`base_repr` with base 2.
Increase the value of max_length for very large numbers. Note that
on 32-bit machines, 2**1023 ... | 40d0198067722d8d4c1ef1e1a195ce6817ab0935 | 19,133 |
def df_fc_overlap_9():
"""Scenario case with 3 sets of 2 overlapping fragments, bound to a common combination of 2 redundant fragments."""
mol = Chem.MolFromSmiles('NC1C(O)C(CCCC2CC2CCC2CC2)C1CCC1CC(C(N)C1O)C1CCC(O)C(N)C1')
return DataFrame([
['mol_fc_overlap_9', 'XXX', 'O1', 0, 'O1:0', ... | 5a86bce8741b76ac265b5a1865f7d3d1ad8970ea | 19,134 |
import requests
import json
def check_cal(es_url, es_index, id):
"""Query for calibration file with specified input ID."""
query = {
"query":{
"bool":{
"must": [
{ "term": { "_id": id } },
]
}
},
"fields": [],... | 10aab4dd6587b901cda543298c13662e6edeb0e1 | 19,135 |
def mountpoint_create(name, size):
"""Service Layer to create mountpoint"""
mountpoint = MountPoint(name, size)
return mountpoint | d52be1773b3cfad62423d2695b42d56ca83f7eaf | 19,136 |
import requests
import json
def GetTSAWaitTimes(airportCode):
"""
Returns data from the TSA Wait Times API for a particular airport shortcode.
:param airportCode: 3-letter shortcode of airport
:return: Returns the full parsed json data from TSA Wait Times API
"""
base_url = "http://apps.tsa.dh... | bd03be14c95a3892ac75a0396da12ca04b52a59b | 19,137 |
def False(context):
"""Function: <boolean> false()"""
return boolean.false | 93d1f1c9fbe9cf7bb02d5caac2c01ed7d0d9a2dc | 19,138 |
def namedtuple_to_dict(model_params):
"""Transfers model specification from a
named tuple class object to dictionary."""
init_dict = {}
init_dict["GENERAL"] = {}
init_dict["GENERAL"]["num_periods"] = model_params.num_periods
init_dict["GENERAL"]["num_choices"] = model_params.num_choices
... | 9ac2f23aff3b9c57599eb2c2c6cacd455ac711a5 | 19,139 |
def roberts(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#roberts"""
return filter(stream, roberts.__name__, *args, **kwargs) | ff58eaea65d536b47614050600c91136dc2d6f7e | 19,140 |
import json
def run_code():
"""
codec api response
{
"error": {
"decode:": "error message"
},
"output": {
"status_code": 0,
"result": {
"data_type": "event",
"data": {
"humidity": {
"time": 1547... | 96118a1c74b027716a68d7c1f25eb3585e1a255c | 19,141 |
from typing import Mapping
from pathlib import Path
import os
def _strip_paths(notebook_json: Mapping, project_root: Path):
"""Strip user paths from given notebook."""
project_root_string = str(project_root) + os.sep
mutated = False
for cell in notebook_json["cells"]:
if cell["cell_type"] ==... | 318493239c964104b4838ffe2ba2b37a295ef792 | 19,142 |
def build_dense_conf_block(x, filter_size=32, dropout_rate=None):
"""
builds a dense block according to https://arxiv.org/pdf/1608.06993.pdf
:param x:
:param dropout_rate:
:param filter_size
:return:
"""
x = BatchNormalization(axis=-1, epsilon=1.1e-5)(x)
x = Activation('relu')(x)
... | 2cb9639ed620d32c513ecbccf2c311360cc3cb9d | 19,143 |
def _viz_flow(u, v, logscale=True, scaledown=6):
"""
Copied from @jswulff:
https://github.com/jswulff/pcaflow/blob/master/pcaflow/utils/viz_flow.py
top_left is zero, u is horizon, v is vertical
red is 3 o'clock, yellow is 6, light blue is 9, blue/purple is 12
"""
color_wheel = _color_wheel()
n_cols =... | 43901f227bc30367910bc41f9ba324bcc217bdbf | 19,144 |
def submission_history(request, course_id, learner_identifier, location):
"""Render an HTML fragment (meant for inclusion elsewhere) that renders a
history of all state changes made by this user for this problem location.
Right now this only works for problems because that's all
StudentModuleHistory rec... | dd0459844b4f30e653dacf474cdb5ddf186ed0dc | 19,145 |
def tou(month, weekday, hour):
""" Calculate TOU pricing
"""
if weekday in [0, 6]:
return OFFPEAK
else:
if month in [5, 6, 7, 8, 9, 10]:
if hour in [11, 12, 13, 14, 15, 16]:
return ONPEAK
elif hour in [7, 8, 9, 10, 17, 18, 19, 20]:
... | 31708916be97d52d229499053b0b3d29603fdfb9 | 19,146 |
import json
def get_job(request):
""" Retrieve a specific Job
URL: /admin/Jobs/GetOne
:param request:
:return:
"""
id = request.GET.dict().get("id")
response = {
'status': 1,
'status_message': 'Success',
'job': job.objects.filter(id=id)
}
return HttpRe... | 82d4c981b48fb0274ae4f2f888149b11ed731b88 | 19,147 |
def cpt_lvq_merid_deriv(temp, sphum):
"""Meridional derivative of c_p*T + L_v*q on pressure coordinates."""
deriv_obj = LatCenDeriv(cpt_lvq(temp, sphum), LAT_STR)
return deriv_obj.deriv() | 629a630bb0663b16f20fb0f7d68ca54ebebc7e21 | 19,148 |
import os
def ZonalStats(fhs, dates, output_dir, quantity, unit, location, color = '#6bb8cc'):
"""
Calculate and plot some statictics of a timeseries of maps.
Parameters
----------
fhs : ndarray
Filehandles pointing to maps.
dates : ndarray
Datetime.date object correspondi... | f27f15c4dee0e2c163fd3b1d748a264768bae7e2 | 19,149 |
def hubert_pretrain_large(
encoder_projection_dropout: float = 0.0,
encoder_attention_dropout: float = 0.0,
encoder_ff_interm_dropout: float = 0.0,
encoder_dropout: float = 0.0,
encoder_layer_drop: float = 0.0,
) -> HuBERTPretrainModel:
# Overriding the signature so that the return type is corre... | dd57cfcb803424ed46fcb597a71aa8e88de3ad32 | 19,150 |
def random_scaled_rotation(ralpha=(-0.2, 0.2), rscale=((0.8, 1.2), (0.8, 1.2))):
"""Compute a random transformation matrix for a scaled rotation.
:param ralpha: range of rotation angles
:param rscale: range of scales for x and y
:returns: random transformation
"""
affine = np.eye(2)
if rsc... | f6216486e94fa7eac0be75b2a420fc1f251987c2 | 19,151 |
import time
def time_as_int() -> int:
"""
Syntactic sugar for
>>> from time import time
>>> int(time())
"""
return int(time.time()) | f7f6d037d156c09a01c0ff13f8b43418133ab1b0 | 19,152 |
from unittest.mock import Mock
from unittest.mock import patch
def test_end_response_is_one_send():
"""Test that ``HAPServerHandler`` sends the whole response at once."""
class ConnectionMock:
sent_bytes = []
def sendall(self, bytesdata):
self.sent_bytes.append([bytesdata])
... | 7c28c6b6fb8f123daa75f9710c26d5345810160b | 19,153 |
def compute_norm_cond_entropy_corr(data_df, attrs_from, attrs_to):
"""
Computes the correlations between attributes by calculating
the normalized conditional entropy between them. The conditional
entropy is asymmetric, therefore we need pairwise computation.
The computed correlations are stored in ... | 12dafa7ecb941c008ab2bb7c93ed6e0c8b1302ad | 19,154 |
def should_retry_http_code(status_code):
"""
:param status_code: (int) http status code to check for retry eligibility
:return: (bool) whether or not responses with the status_code should be retried
"""
return status_code not in range(200, 500) | 69acb5bd34b06e1ff1e29630ac93e60a3ccc835c | 19,155 |
def softmax(x):
"""Calculates the softmax for each row of the input x.
Your code should work for a row vector and also for matrices of shape (n, m).
Argument:
x -- A numpy matrix of shape (n,m)
Returns:
s -- A numpy matrix equal to the softmax of x, of shape (n,m)
"""
# Apply exp() el... | d4905ec1a145aae47532b43a66a00a29180a37e4 | 19,156 |
def inertia_tensor_eigvals(image, mu=None, T=None):
"""Compute the eigenvalues of the inertia tensor of the image.
The inertia tensor measures covariance of the image intensity along
the image axes. (See `inertia_tensor`.) The relative magnitude of the
eigenvalues of the tensor is thus a measure of the... | af48827b709b48cdae7b2a8fe7ad3723845ee6cd | 19,157 |
def extract_values(inst):
"""
:param inst: the instance
:return: python values extracted from the instance
"""
# inst should already be python
return inst | 087bb00ee6e3666b4a9e682ca420623982a12102 | 19,158 |
def voc_ap(rec, prec, use_07_metric=False):
""" ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
"""
if use_07_metric:
# 11 point metric
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec ... | e9a4ebec8908e306bcf12e2e9538a8de8b74e84b | 19,159 |
def is_on_path(prog):
"""Checks if a given executable is on the current PATH."""
r = runcmd("which %s" % prog)
if r.failed:
return False
else:
return r | 1019ab3b08ef97c307588f8902a7884a89039998 | 19,160 |
def validate_entry(new_text) -> bool:
"""Função callback para validação de entrada dos campos na janela
ExperimentPCR.
É chamada toda vez que o usuário tenta inserir um valor no campo de
entrada.
Uma entrada válida deve atender os seguintes requisitos:
-Ser composto apenas de números intei... | 8e0f5f126d0688279fc28a8be287fda00d346a59 | 19,161 |
import io
def eia_cbecs_land_call(*, resp, url, **_):
"""
Convert response for calling url to pandas dataframe, begin
parsing df into FBA format
:param resp: df, response from url call
:param url: string, url
:return: pandas dataframe of original source data
"""
# Convert response to d... | 396079863ecc2faa6420e90f3d608ff997a3fb39 | 19,162 |
def add_l2_interface(interface_name, interface_desc=None, interface_admin_state="up", **kwargs):
"""
Perform a POST call to create an Interface table entry for physical L2 interface.
:param interface_name: Alphanumeric Interface name
:param interface_desc: Optional description for the interface. Defaul... | d27b4b5ec738a5a508a3fc9d8852ecf5df56debe | 19,163 |
import pkg_resources
def language_descriptions():
"""
Return a dict of `LanguageDesc` instances keyed by language name.
"""
global languages
if languages is None:
languages = {}
for language in pkg_resources.WorkingSet().iter_entry_points(
group='textx_languages'):
... | 236b8fd595f1b4754eeca2b8b17a88fa36090ca5 | 19,164 |
import six
def load_fixtures(fixtures_dict=None):
"""
Loads fixtures specified in fixtures_dict. This method must be
used for fixtures that don't have associated data models. We
simply want to load the meta into dict objects.
fixtures_dict should be of the form:
{
'actionchains': ['act... | b43c1303a7c54a571a0e3ddf7881d7113371e293 | 19,165 |
def generate_sbm(sizes, probs, maxweight=1):
"""Generate a Stochastic Block Model graph.
Assign random values drawn from U({1, ..., maxw}) to the edges.
sizes : list of sizes (int) of the blocks
probs : matrix of probabilities (in [0, 1]) of edge creation
between nodes dependi... | c6b0a106d88016afc99bf45abeb7c60af2981d77 | 19,166 |
import re
def eq_portions(actual: str, expected: str):
"""
Compare whether actual matches portions of expected. The portions to ignore are of two types:
- ***: ignore anything in between the left and right portions, including empty
- +++: ignore anything in between left and right, but non-empty
:p... | 704b2a83575347c5143c2dc0aca5227a8fc5bd4b | 19,167 |
def _get_encoder(
in_features: int,
embed_dim: int,
dropout_input: float,
pos_conv_kernel: int,
pos_conv_groups: int,
num_layers: int,
num_heads: int,
attention_dropout: float,
ff_interm_features: int,
ff_interm_dropout: float,
drop... | 72ff9887575905172db0b095b3d6822ee6b51411 | 19,168 |
def _soft_threshold(a, b):
"""Soft-threshold operator for the LASSO and elastic net."""
return np.sign(a) * np.clip(np.abs(a) - b, a_min=0, a_max=None) | 34f28c1154cf9eefecc19e1ece8dfa3ca82e677e | 19,169 |
def predict(input_tokens):
"""register predict method in pangu-alpha"""
token_ids, valid_length = register.call_preprocess(preprocess, input_tokens)
############# two output ###################
# p, p_args = register.call_servable(token_ids)
# add_token = register.call_postprocess(postprocess, p, p_... | f2de6ff2ba78c3cac47a823bfe7a201a9a6b93ad | 19,170 |
import dbm
def get_sim_data():
"""
Create the data needed to initialize a simulation
Performs the steps necessary to set up a stratified plume model simulation
and passes the input variables to the `Model` object and
`Model.simulate()` method.
Returns
-------
profile : `ambient.Profi... | e253665f451b167a188c997ff36fc406e0f3a587 | 19,171 |
import numpy as np
def _organize_arch(fils, pth):
"""Allocate data from each specific type of file (keys from the input dict) to a new dict
Arguments:
fils {dict} -- Dictionary containing type of files and list of files
Returns:
[dict] -- [description]
"""
imgdata ... | c62c9b23bf4735c2062090d77278ce5a8acbd668 | 19,172 |
def gather_allele_freqs(record, all_samples, males, females, pop_dict, pops, no_combos = False):
"""
Wrapper to compute allele frequencies for all sex & population pairings
"""
#Get allele frequencies
calc_allele_freq(record, all_samples)
if len(males) > 0:
calc_allele_freq(record, male... | 0f74616fa64ee5b3582467da27161906abf28463 | 19,173 |
def get_selected(n=1):
"""
Return the first n selected object, or None if nothing is selected.
"""
if get_selection_len():
selection = bpy.context.selected_objects
if n == 1:
return selection[0]
elif n == -1:
return selection[:]
else:
r... | 6049900ef069731b1fbe9f40fff184085940c83e | 19,174 |
def label_src_vertno_sel(label, src):
""" Find vertex numbers and indices from label
Parameters
----------
label : Label
Source space label
src : dict
Source space
Returns
-------
vertno : list of length 2
Vertex numbers for lh and rh
src_sel : array of int ... | a1858258b6c789557d6bdeff9428cc7aacbe4655 | 19,175 |
def get_subjects(creative_work):
"""
Returns generated html of subjects associated with the
Creative Work HTML or 0-length string
Parameters:
creative_work -- Creative Work
"""
html_output = ''
#! Using LOC Facet as proxy for subjects
facets = list(
REDIS_DATASTORE.smembers(... | 328aeadb21a22972c0843efdba251b2f6c5f937d | 19,176 |
import argparse
import subprocess
import logging
def run_tests(runner: cmake_runner.CMakeRunner, args: argparse.Namespace,
build_config: str) -> bool:
"""Run tests for the current project.
Args:
runner: Cmake runner object.
args: Arguments for cmake.
build_config: Name of configuration ... | f448029f6983c9e37d75cf318717d8c7c65d1295 | 19,177 |
def sort(request):
"""Boolean sort keyword for concat and DataFrame.append."""
return request.param | 83f35eb41bc0cf7eecea932ae4f14646d9e8732f | 19,178 |
def is_comprehension(leaf):
"""
Return true if the leaf is the beginning of a list/set/dict comprehension.
Returns true for generators as well
"""
if leaf.type != 'operator' or leaf.value not in {'[', '(', '{'}:
return False
sibling = leaf.get_next_sibling()
return (sibling.type in... | 11fff76ff8ed19b3d57359b56db886c003603a86 | 19,179 |
def get_class(x):
"""
x: index
"""
# Example
distribution = [0, 2000, 4000, 6000, 8000, 10000]
x_class = 0
for i in range(len(distribution)):
if x > distribution[i]:
x_class += 1
return x_class | 1ae95f3d9bc6f342169232ab10cd08a42de0f692 | 19,180 |
from re import T
def square(x):
"""Elementwise square of a tensor. """
return T.sqr(x) | c052e31a450b91eb1e6a08843f99afd6e618da9d | 19,181 |
import re
def update_email_body(parsed_email, key):
"""
Finds and updates the "text/html" and "text/plain" email body parts.
Parameters
----------
parsed_email: email.message.Message, required
EmailMessage representation the downloaded email
key: string, required
The object key... | d942a4cf47af9d7c1e36a4a2af5d0239b90464d8 | 19,182 |
import json
def create_collaborators(collaborators, destination_url, destination, credentials):
"""Post collaborators to GitHub
INPUT:
collaborators: python list of dicts containing collaborators info to be POSTED to GitHub
destination_url: the root url for the GitHub API
destination: ... | 2d39a2970d9f52af5209b1f4717c0b4d39e1cb5c | 19,183 |
import scipy
def complexity_recurrence(signal, delay=1, dimension=3, tolerance="default", show=False):
"""Recurrence matrix (Python implementation)
Fast Python implementation of recurrence matrix (tested against pyRQA). Returns a tuple
with the recurrence matrix (made of 0s and 1s) and the distance matri... | cc93a80ff34fffc5774f7b52109fd09d8b0ac69e | 19,184 |
import torch
import tqdm
import time
def train(params):
"""
Trains error model.
Arguments:
params (dict): hyperparameters with which to train
"""
p, x = load_error_data()
# calculate means
p_mean = p.mean(axis=(0, 1))
p_std = p.std(axis=(0, 1))
x_mean = x.mean(axis=(0, 1)... | 3dc2e014c31cac3bbc42d5972184b6d24175a8db | 19,185 |
def get_awb_shutter( f ):
"""
Get AWB and shutter speed from file object
This routine extracts the R and B white balance gains and the shutter speed
from a jpeg file made using the Raspberry Pi camera. These are stored as text in
a custom Makernote.
The autoexposure and AWB white balance valu... | cfafdf531809729ae0ec96ab90a60a4961b9437a | 19,186 |
def rgb2lab(rgb_arr):
"""
Convert colur from RGB to CIE 1976 L*a*b*
Parameters
----------
rgb_arr: ndarray
Color in RGB
Returns
-------
lab_arr: ndarray
Color in CIE 1976 L*a*b*
"""
return xyz2lab(rgb2xyz(rgb_arr)) | 3eba11b8017908393e1e238e6b4ae046dd265520 | 19,187 |
def format_rfidcard(rfidcard):
"""
:type rfidcard: apps.billing.models.RfidCard
"""
return {
'atqa': rfidcard.atqa if len(rfidcard.atqa) > 0 else None,
'sak': rfidcard.sak if len(rfidcard.sak) > 0 else None,
'uid': rfidcard.uid,
'registered_at': rfidcard.registered_at.is... | 120ca8e338b01235b2ba12ae3f874fd317ffebe8 | 19,188 |
def make_exposure_shares(exposure_levels, geography="geo_nm", variable="rank"):
"""Aggregate shares of activity at different levels of exposure
Args:
exposure_levels (df): employment by lad and sector and exposure ranking
geography (str): geography to aggregate over
variable (str): varia... | 02d990f2b08e3acb2a2b8ac01e44848770bdea71 | 19,189 |
import collections
def init_ranks(mpi_comm):
"""Returns rank information of the local process in `mpi_comm`.
Args:
mpi_comm (type:TODO)
MPI Communicator from mpi4py
Returns:
rank_info (list):
Elements are:
* rank (`mpi_comm.rank`)
... | 334bfa7856049e612f3f6d1f6ec82873926040b1 | 19,190 |
def boxscores(sports=["basketball/nba"], output="dict", live_only=True, verbose=False):
"""
~ 10 seconds
"""
links = boxlinks(sports=sports, live_only=live_only, verbose=verbose)
boxes = [boxscore(link) for link in links]
return boxes | 9cdc1bd4ec90d8ab9593d49316669dc6b801cf2e | 19,191 |
def runningMedian(seq, M):
"""
Purpose: Find the median for the points in a sliding window (odd number in size)
as it is moved from left to right by one point at a time.
Inputs:
seq -- list containing items for which a running median (in a sliding window)
is t... | b37af61c9f6f62bd6fbd395bc2c423a770ba2797 | 19,192 |
def min_max_normalize(img):
""" Center and normalize the given array.
Parameters:
----------
img: np.ndarray
"""
min_img = img.min()
max_img = img.max()
return (img - min_img) / (max_img - min_img) | faaafbc8e0b36f26f8319b671de326dd6a97e6f9 | 19,193 |
def find_common_features(experiment: FCSExperiment,
samples: list or None = None):
"""
Generate a list of common features present in all given samples of an experiment. By 'feature' we mean
a variable measured for a particular sample e.g. CD4 or FSC-A (forward scatter)
Paramete... | 8022a97721eb9ff26efcba347e4f631aff3ede84 | 19,194 |
import heapq
def generate_blend_weights(positions, new_p, n_neighbors):
""" Use inverse distance and K-Nearest-Neighbors Interpolation to estimate weights
according to [Johansen 2009] Section 6.2.4
"""
distances = []
for n, p in positions.items():
distance = np.linalg.norm(new_p - p)
... | f9db2b47d5847cdb2e7367cebe9b9bf81809b11d | 19,195 |
def check_method(adata):
"""Check that method output fits expected API."""
assert "connectivities" in adata.obsp
assert "distances" in adata.obsp
return True | 0ad772187c6d2960149723df17f6b0cf3fa703d1 | 19,196 |
def load_model(Model, params, checkpoint_path='', device=None):
""" loads a model from a checkpoint or from scratch if checkpoint_path='' """
if checkpoint_path == '':
model = Model(params['model_params'], **params['data_params'])
else:
print("model:", Model)
print(f... | 8f1339b5548024714f731de037ef320535fc3b69 | 19,197 |
import inspect
def get_widget_type_choices():
"""
Generates Django model field choices based on widgets
in holodeck.widgets.
"""
choices = []
for name, member in inspect.getmembers(widgets, inspect.isclass):
if member != widgets.Widget:
choices.append((
"%s.... | 143ff91ee3bc4166e5091e344a38fb2bbb72934e | 19,198 |
import array
def iau2000a(jd_tt):
"""Compute Earth nutation based on the IAU 2000A nutation model.
`jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats
Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of
a micro-arcsecond. Each value is either a float, or a NumPy... | beadd6469a85b475dc22ca1e2a967310555140a9 | 19,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.