content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dispatch_per_device(games):
"""Helper fo split dataset per device."""
num_games = list(games._asdict().values())[0].shape[0]
num_devices = jax.local_device_count()
batch_size = batch_size_per_device(num_games, num_devices=num_devices)
def dispatch(x):
if hasattr(x, 'shape'):
return jnp.reshap... | dc43bbe11ed6dfd10f2e8418d941310e7271b047 | 44,300 |
def xml_prettify(elem):
"""Return a pretty-printed XML string for the XML element."""
text = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(text)
return reparsed.toprettyxml(indent=" ") | 28c71c0d22b60c7d4f8f9aee905707b4f37c32a8 | 44,301 |
def fix_matrix_gauge(emat):
"""Fix gauge of an energy matrix such that the minimum value
of each column is zero (columns correspond to positions), and
overall matrix norm is equal to 1."""
# fix mean
for j in range(emat.shape[1]):
emat[:,j] = emat[:,j] - sp.mean(emat[:,j])
# fix sum of v... | dcdf722c398d858789ff80c188383bff18833b66 | 44,302 |
import re
def clean_html(X):
""" Strip html
:texts: collection - the collection of texts to change
:returns: list of texts cleaned from html
"""
return [re.sub('(\\<.*?\\>)','',text) for text in X if text!=None] | 5881fa4e7df0b3a8d1c6cfcaaa17bc3d381230d0 | 44,303 |
from datetime import datetime
def parse_datetime(value):
"""Parses a string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raises ``ValueError`` if the input isn't well formatted.
"""... | 672d0f831374a27489af8a38e253c7dc76a9f51a | 44,304 |
def post(host, path, body=None, headers={}):
"""
HTTPS POST request
"""
return request('POST', host, path, body, headers) | 418f7ecc14fafada0c3962ea07920ae3060edf4a | 44,305 |
def issiso(sys, strict=False):
"""
Check to see if a system is single input, single output
Parameters
----------
sys : LTI system
System to be checked
strict: bool (default = False)
If strict is True, do not treat scalars as SISO
"""
if isinstance(sys, (int, float, compl... | ad72fe7661d3aba91a99c9bf3af606b3e0077c03 | 44,306 |
def get_optimizer(encoder, model, args, learning_rate, remove_pooler=False):
"""
get BertAdam for encoder / classifier or BertModel
:param model:
:param classifier:
:param args:
:param remove_pooler:
:return:
"""
param_optimizer = list(encoder.named_parameters())
param_optimizer... | f886b2b2dc632fdb85b75d1905e339905c1177a4 | 44,307 |
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
:return: None
"""
if STRIPE_PLANS is None:
return None
for _, value in STRIPE_PLANS.iteritems():
plan = PaymentPlan.retrieve(value.get('id'))
if plan:
PaymentPlan.update(id=value.get('id'),
... | 329c8f8e2f0dc7c7950278ce1a2c0e07878ef58d | 44,308 |
import binascii
def b32decode(todecode, casefold=False, map01=None):
"""Decode a Base32 encoded byte string.
todecode is the byte string to decode. Optional casefold is a flag
specifying whether a lowercase alphabet is acceptable as input.
For security purposes, the default is False.
RFC 3548 a... | 2720d19e608e8dee9142c5a19829847ff492c5cb | 44,309 |
import os
import shutil
def _install_node_module_for(config, library_dir, library_name, dest_root_dir=None, include_tests=False):
"""
Installs the node module into the node module cache directory, which
includes downloading all dependencies. The dev dependencies are
loaded into the cache, but are not... | 16e3214e79e931c6cb206470d6fae473c8673b1c | 44,310 |
def check_visitors(cls):
"""Check that a checker's visitors are correctly named.
A checker has methods named visit_NODETYPE, but it's easy to mis-name
a visit method, and it will never be called. This decorator checks
the class to see that all of its visitors are named after an existing
node class... | 704d1c2c73cfa1c38b4e07b626329a8359c9ca9b | 44,311 |
def flesch_reading_ease(n_syllables, n_words, n_sents, lang=None):
"""
Readability score usually in the range [0, 100], related (inversely) to
:func:`flesch_kincaid_grade_level()`. Higher value => easier text.
Note:
Constant weights in this formula are language-dependent;
if ``lang`` is ... | 34f474a3eeb06a8453f9b21b4b324dcfe0f7582f | 44,312 |
def shufflenetv2_x1_5(pretrained=False, **kwargs):
"""shufflenetv2_x1_5 model
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
Examples:
.. code-block:: python
from paddle.vision.models import shufflenetv2_x1_5
# build ... | cf45e4490d1339d8ba0cad84d51e33e6e1ee5ffb | 44,313 |
def gen_snv_transition_matrix(ts_tv_p=0.71,
ts_hm_ht_p=0.5,
tv_l_p=0.5,
tv_hm_ht_p=0.8):
""" Function to compute SNV matrix of transition probabilities,
default rates follow SInC reference (Fig1.a) """
G_ref = {'AA':0... | 26b5ab2d58c0d9c7364bd098967e1f8f8937203c | 44,314 |
import random
import copy
import hashlib
def make_event(action_type, device, file, timestamp, opt=None):
"""Create an audit event."""
if action_type == ACT_WRITE:
# Simulate writing data to the file. Create a new randomized file and
# copy _some_ of it's attributes.
mutation = make_fil... | 2f8c11f9901494bf389c986a21b9a34241f586b8 | 44,315 |
import yaml
def parse_config_file(config_file) -> dict:
"""Read config.yaml file with params.
Returns
-------
dict
Dict of config
"""
with open(config_file, 'r') as stream:
try:
CONFIG = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(... | 8f1fb9bcda94ef5c21edbf5e5bf95b327efd8c96 | 44,316 |
def Property(func): # pylint: disable = C0103
"""
Property with improved docs handling
:Parameters:
`func` : ``callable``
The function providing the property parameters. It takes no arguments
as returns a dict containing the keyword arguments to be defined for
``property``. Th... | 061b5f6b4ec151888a64a590e2b5c974d2666301 | 44,317 |
def add_files(struct: Structure, opts: ScaffoldOpts) -> ActionParams:
"""Add .pre-commit-config.yaml file to structure
Since the default template uses isort, this function also provides an
initial version of .isort.cfg that can be extended by the user
(it contains some useful skips, e.g. tox and venv)
... | 1f0a5f836bbc5e2596b3bd1a4bb2d6607f9ea831 | 44,318 |
import os
def get_subjectdirs() -> list:
"""
Returns subject directory names (not full path) based on the path_bidsdata (bids_data directory).
@rtype: list
@return: list of subdirectories in path_bidsdata that start with the prefix sub
"""
bidsdir_contents = os.listdir(cfg.path_bidsdata)
... | 1de6e706913ca86781c34925b584ee3ca56935de | 44,319 |
import csv
def get_entities_sentence(dataset_file, sentence):
"""
:param dataset_file:
:param sentence:
:return: sentence : [[entity1, id, char1, char2], [entity2, id, char3, char4],
relation], [[entity1, id, char1, char2], [entity2, id, char3, char4],
... | 10762f373ff42123fb42e14fa3768a83bcf13797 | 44,320 |
def ground(expr, env):
"""Replace all variables with their values in expr."""
if scheme_symbolp(expr):
resolved = lookup(expr, env)
if expr != resolved:
return ground(resolved, env)
else:
return expr
elif scheme_pairp(expr):
return Pair(ground(expr.fir... | 230f4eb9c27170ec84df04dc63ca90776b55d4a6 | 44,321 |
def parse_maintainers_line(line):
"""Parse one line of Maintainers.txt, returning any match group and its key."""
for key, expression in EXPRESSIONS.items():
match = expression.match(line)
if match:
return key, match.group(key)
return None, None | 3f2b15ef310f87eed50e59a1c1dbb3521ced5ab9 | 44,322 |
def open(name, mode="copyonwrite", memmap=0):
"""Factory function to open a FITS file and return an HDUList object.
name: Name of the FITS file to be opened.
mode: Open mode, 'readonly' (default), 'update', or 'append'.
memmap: Is memmory mapping to be used? default=0.
"""
# instantia... | 7aef96b47426e96916e490b2c18f8298ee45cbce | 44,323 |
from typing import get_args
def query_other_gene_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short ... | 1a6151ee2677b2b6964c72bec1173ab0b38c1d7b | 44,324 |
def cbc_cloud_api():
"""Create CBCloudAPI singleton."""
return CBCloudAPI(url="https://example.com",
org_key="test",
token="abcd/1234",
ssl_verify=False) | 16527b89ccb3c1d285c23c63404a130b1140a89b | 44,325 |
def get_extension_manager():
"""Return the extension manager used by Review Board.
The same instance will be returned every time.
Returns:
ExtensionManager:
The extension manager used by Review Board.
"""
global _extension_manager
if not _extension_manager:
_extension_... | 2f31e8d74dbef8e96ef862798daad4aab5bc0196 | 44,326 |
def get_title(dbname, page_id, replicas_port, user, password):
"""
Get title of the page with id as `page_id`.
:param dbname: Which database the module corresponds to.
:param page_id: The Id of the page whose page title is to be fetched.
:param replicas_port: port for connecting to meta table throu... | 9354cd4046b413ab1c5d0a7a1c81c6c04709048e | 44,327 |
import os
def fuse_cfg():
"""Return a test telliot configuration for use on polygon-mumbai
If environment variables are defined, they will override the values in config files
"""
cfg = TelliotConfig()
# Override configuration for fuse testnet
cfg.main.chain_id = 122
accounts = find_acco... | 30b674eb08e8b76d4cab551c99a1f2030a6da546 | 44,328 |
from typing import Optional
def resolve_url_param(param: UrlParam, context: Optional[Context] = None) -> ResolvedUrlParam:
"""
Resolve a URL parameter.
Args:
param: A URL parameter, which is one of the items below.
- A URL parameter value.
- A list of URL parameter values.... | ae7c1c273307adbf403ec217ec9f443b0c6ff879 | 44,329 |
def fifo(jobs,num_frames):
""" Frame list
Each item in this list will be a tuple as follows:
Tuple[0] - represents the number of the page frame sequentially, 1,2,3, etc..
Tuple[1] - reresents the job current in this frame
Tuple[2] - represents the moment that job arrived (starting with 0 for first m... | 6fabcbab27cc3270e72eabbda79166b1b4393239 | 44,330 |
import os
def _netcdf_gsm_plev(gsm_dir, fcst_time, tsel):
"""netCDFファイルを読み込む(GSM、pres)
Parameters:
----------
msm_dir: str
GSMデータを置いたディレクトリ、またはretrieve、force_retrieve
retrieve:データ取得を行う。既に存在している場合は取得しない。
force_retrieve:データ取得を行う。既に存在している場合にも再取得する。
ディレクトリ名:新たにデータ取得は行わず、指定... | 16b801c0e0f1375cc3e147189cff11e53f618c13 | 44,331 |
def CMYKratio_to_CIE(cmykr):
"""Converts CMYK color space (ratio representation) to CIE"""
rgb = CMYKratio_to_RGB(cmykr)
return RGB_to_CIE(rgb) | 58464be2c201ce33a849a2278e79cc8df1d346cf | 44,332 |
def laptops_list(request):
"""View a list of LNL's laptops"""
laptops = Laptop.objects.filter(retired=False)
return render(request, 'laptops/laptops_list.html', {"laptops": laptops}) | e6ea36883787783c4d09c3bbe40442f357825862 | 44,333 |
def get_bcl(signal_markers: pd.DataFrame):
"""Function to return estimates of the cycle length for a recording
For a given train of signal markers (either QRS start, AT, or other), will estimate the cycle length as the
difference between successive markers, with an estimate made that the last cycle length ... | b41828fbf758a7b595ddb97d5859dcfa12cc0934 | 44,334 |
def exponential_head_correction(r, V, cutoff):
"""Use an exponential function to smoothly force V to a finite value at V(0)
Parameters
----------
r : np.ndarray
Separation values
V : np.ndarray
Potential at each of the separation values
cutoff : int
The last real value o... | eae10963883e5c9c7ae45cf0430fcfcb020797bf | 44,335 |
def fa_to_en(string):
"""Convert Persian digits to EN
Usage::
>>> from persiantools import digits
>>> converted = digits.fa_to_en("۰۱۲۳۴۵۶۷۸۹")
:param string: A string, will be converted
:rtype: str
"""
digits_map = {
"۰": "0",
"۱": "1",
... | 3687dae8663d855200f2f79b81cb85d23ecabf74 | 44,336 |
def plugin_get(request, plugin_id, fields):
"""Get plugin info."""
plugin = iotronicclient(request).plugin.get(plugin_id, fields)
return plugin | c949b9ea1e2c21f5afc2633a8a6a8b73a70e52d5 | 44,337 |
import six
def _bytes_list_feature(values):
"""
:param values:
:return:
"""
def _norm2bytes(value):
return value.encode() if isinstance(value, str) and six.PY3 else value
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[_norm2bytes(values)])) | e9e0272ce582d174b0795fa901c254fc1c3f6b8c | 44,338 |
def quicklook_region(request, region_id=10000002, type_id=34):
"""
Generates system level overview for a specific type.
Defaults to tritanium & the forge.
"""
# Get the item type
type_object = InvType.objects.get(id=type_id)
# Get list of materials to build
materials = InvTypeMaterial.... | ede0e36a305eed2ea233a995dda7f719a275a262 | 44,339 |
def delete_event_subscription( context, id ):
"""
Deletes an event subscription
Args:
context: The Redfish client object with an open session
id: The identifier for the subscription
Returns:
The response of the DELETE
"""
# Get the current subscriptions
subscriptio... | e47b8e09b8daaa5f33598ccda6d5e1279de1f592 | 44,340 |
def preprocess_data(data_frame, label_columns_list, data_file_name):
"""
start preprocessing the data
"""
print '\npreprocessing..'
print Style.RESET_ALL
for col in label_columns_list:
data_frame[col] = data_frame[col].apply(lambda arr: arr.strip(""))
data_frame[col] = data_frame... | 51e2ecd45b392a2cd12cae4f47f7dc16560a97a0 | 44,341 |
def get_prayer(id):
"""Returns specific prayer from id."""
return Prayer.query.get(id) | 95e4425e28d9c9e2b028dc5b144eaacc69289cbb | 44,342 |
def docstring_parameters_section(obj):
"""
Return the parameters section of a docstring
"""
return docstring_section_lines(obj.__doc__, 'parameters') | afb01bd0c18ecc3d8d7294bda7dd00c09b831465 | 44,343 |
def split_string_by_bytes(s: str, bytes_count: int) -> list[bytes]:
"""A function that splits a string into N-byte particles"""
s = s.encode()
return [s[i : i + bytes_count] for i in range(0, len(s), bytes_count)] | 58a2dcdda7cab6832eecd15200af2c7d10dbd367 | 44,344 |
import collections
def score_urls(*args, \
search_terms=config.search_terms, **kwargs):
"""
Returns urls ordered by search relevance
"""
def search_key(tokens, default=0):
score, _, _ = search_terms.replace_terms(tokens)
return -(score or default)
tags = collections.Counter... | 0c8aeaae6b43b923d85a36968799234c28297163 | 44,345 |
import logging
def recipe(recipe_file, ctype=container_type.DOCKER, single_stage=False,
userarg=None):
"""Recipe builder"""
# Make user arguments available
USERARG = {} # pylint: disable=unused-variable
if userarg:
USERARG = userarg # alias
# Consider just 2 stages for the tim... | b0f77150404ada6120e6ae2c5f6a155c043996d2 | 44,346 |
def get_collective_group_size(group_name: str = "default") -> int:
"""Return the size of the collective group with the given name.
Args:
group_name: the name of the group to query
Returns:
The world size of the collective group, -1 if the group does
not exist or the process doe... | 1ab6e69f7f8d2f4c11c3d93a5e8d94422f22d462 | 44,347 |
def collision(object1, object2):
"""detect collision between two objects using circles
Tests for collision between two objects by testing whether two circles
centered on the objects overlap. Objects must have a
a "radius" attribute, which is used to create the circle.
Args:
object1: First ... | e42bcce7a111fa7f8de2c10b16a91c0d49992ddb | 44,348 |
import os
def _multiprocessing_save_sp(in_out_path):
"""
A function that saves spacy embeddings and is suitable for use
with the multiprocessing library because it is globally namespaced
and accepts just one argument as input.
"""
vp, np = in_out_path
if not os.path.exists(np + '.npz'):
... | 832af75438e0b8a6f9d91d3195173e02be160a76 | 44,349 |
import pandas as pd
import numpy as np
def rm_standard_dev(var,window,ravelmodeltime,numOfEns):
"""
Smoothed standard deviation
"""
print('\n\n-----------STARTED: Rolling std!\n\n')
if var.ndim == 3:
rollingstd = np.empty((var.shape))
for i in range(var.shape[1]):
... | 5eacda1f79e1f4fe00c3cb8d32222f75f9eb3562 | 44,350 |
def compute_purity(cluster_assignments, class_assignments):
"""Computes the purity between cluster and class assignments.
Compare to https://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-clustering-1.html
Args:
cluster_assignments (list): List of cluster assignments for every point.
... | ee6c8e84c7833125fdaa2581acb90cbe92610514 | 44,351 |
def add(a,b):
"""
Return the addition of the arguments
>>> add(1,2)
3
>>> add('a','b')
'ab'
>>> add(1, '2')
Traceback (most recent call last):
File "test.py", line 43, in <module>
add(1, '2')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
"""
retu... | ecf8728670525cb1f8c6c558021fc468ef4c8780 | 44,352 |
def get_vlan_binding(netid):
"""Lists the vlan given a network_id."""
LOG.debug(_("get_vlan_binding() called"))
session = db.get_session()
try:
binding = (session.query(l2network_models.VlanBinding).
filter_by(network_id=netid).one())
return binding
except exc.NoRe... | 2b15a3e35d18af1b709f3b1a98358c38783ff393 | 44,353 |
def ida_star(root, goal, heuristic):
""" Based on https://en.wikipedia.org/wiki/Iterative_deepening_A* """
bound = heuristic(root, goal)
path = StackSet([root])
while True:
t = search(path, 0, bound, goal, heuristic)
if t == 'FOUND':
return (path, bound)
... | a02cd44d8145fb342ce791f41c9e3db1583b3b06 | 44,354 |
def extract_call(function, arguments, ignore_self=False):
"""Validates the a dict of arguments can be used to call the given function"""
require_type(dict, arguments, "arguments")
args, kwargs, varargs, varkwargs = get_args_spec_from_function(function, ignore_self=ignore_self)
if varargs:
signa... | 92a30eac4cf3a19a4e84bbda3c0ff5ad14856a2e | 44,355 |
def getLiterature(movieID, indexF, dataF):
"""Return literature information for a movie."""
return _parseColonList(movieID, indexF, dataF, 'MOVI: ', _lit) | a7ce5a50fd0dda6d3a8228ca1605e49527bbd6a9 | 44,356 |
def find_key_symptom(tariffs, cause_reduction, cause, endorsements,
rules=None):
"""Find the key endorsed symptom for a cause
Args:
tariffs (dict): processed tariff matrix
cause_reduction (dict): mapping from cause46 to cause34
cause (int): cause number at the cause... | e8805fd29bf09cd3e0269ae4203f4fd7912f5c72 | 44,357 |
def all_gather(x, replication_factor, name):
""" Gather the data on all replicas to all other replicas. Each replica will
have the exact same output.
Args:
x: The tensor to gather
replication_factor: The replication factor of the model.
name: Optional op name.
Returns:
A tensor o... | 22d039fb1e921ef0bee39e93255aee09dee87a02 | 44,358 |
def generate_legend_file(split_names, legend_file_name, out_dir,
hdfs_client=None):
"""
generate legend file for each all the splits
"""
legend_file = '{0}/{1}'.format(out_dir, legend_file_name)
if hdfs_client is None:
with open(legend_file, 'a+') as f:
... | c10acf8c7ad6402082f09fe011336070a1d54cc7 | 44,359 |
import socket
def get_ip4_from_socket() -> str:
"""Get the public IPv4 of this system by inspecting a socket connection.
Warning: This returns a local IP address when running behind a NAT, e.g. on Docker.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((IP4_SOCKET_E... | 4952ca64362b8fb4c2515d06cc23785bf60fd28e | 44,360 |
import csv
import re
def _get_parse(str_src, ns_args):
"""Return {'tree':, 'rulerrow':, 'alignments':} parse
from text and ArgParse options
"""
if ns_args.sourceformat != None:
e_fmt = ns_args.sourceformat
if e_fmt == FMT_CSV:
try:
o_dialect = csv.Sniff... | 3eda4ef949d574a5707e3a00c02860050a9a8866 | 44,361 |
def transform(tokens):
"""
Accumulate tokens in lines.
Add token (and white spaces) to a line until it overflow 80 chars.
"""
lines = []
current_line = []
for t in tokens:
if sum([len(x) + 1 for x in current_line]) + len(t) > 80:
lines.append(current_line)
cu... | c30af21db61b2b00848b0263552461f9682a6d08 | 44,362 |
def get_input(calc_params_crystal, elements, bs_repo, label):
"""
Generates a test input
"""
calc_params_crystal['title'] = label
return write_input(calc_params_crystal, [bs_repo[el] for el in elements]) | f3c91caa0322006085edad0262545799cadf11b5 | 44,363 |
import json
def ocr_loader(json_path):
"""Helper function to load ocr data from json file
Args:
json_path (string):
Path to the json file with OCR output data
Returns:
string:
OCR text output
"""
json_path = json_path.replace('\\', '/')
with open(json_... | 7e182b184b305bffc97dadf59b139a1aa53250b1 | 44,364 |
def precision_posterior_prior(samples, mean, variance,
a_prior=5, b_prior=6):
""" This using the solution of Question 3 from Exercise 3
Parameters
----------
samples : array [n_samples,]
the samples from data distribution (i.e. X ~ Normal(mu, sigma^2))
mean : a scalar
th... | 1c462fc9db7a096a3c532ac1f75fd6945675ecc6 | 44,365 |
import re
def tokenize_only(text):
"""
first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token
filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)
Args:
text:
Returns:
"""
tokens = [
word.lower()
... | f4863258976dece4075b83a540a16beb11f23bdb | 44,366 |
def locations_list():
"""Returns a dictionary of ASNs as keys, list of associated locations, router hostnames, and \
router display names as keys. Used by Flask to populate the /routers/<asn> route, which is \
ingested by a JS Ajax call to populate the list of locations associated with the selected \
ne... | d71aa6634247788bfcd041a8b9b14204a12ae82c | 44,367 |
def check_min_area( prob_mask, frame, min_area = p.min_area, type = 2,
check_area = p.check_area, **kwargs):
"""Finds contours in image and optinally checks if area bigger than `min_area`
Parameters
------------
prob_mask : ndarray
2D probability map output of `prob_mas... | bd821438bd6a9a785c0108a988068dc635978d2f | 44,368 |
def video(request, id=None):
"""
*/entry/videos/<id>*, */entry/videos/new*
The entry interface's edit/add/delete video view. This view creates
the edit page for a given video, or the "new video" page if it
is not passed an ID. It also accepts POST requests to create or edit
videos.
If call... | 651f4e18a73267af26ce558feecc0b8041c0ac38 | 44,369 |
def country(get_response):
"""Detect the user's country and assign it to `request.country`."""
def _country_middleware(request):
client_ip = get_client_ip(request)
if client_ip:
request.country = get_country_by_ip(client_ip)
if not request.country:
request.countr... | 340fde4c5b2000ec688af6f5024200ada264c8cc | 44,370 |
def extract_clips_with_consecutive_frames(path, num_clips, num_frames_per_clip):
"""
Args:
path: path of a video
num_clips: expected numbers of splitted clips
num_frames_per_clip: number of frames in a single clip, pretrained model only supports 16 frames
Returns:
A list of r... | 87d285d6b30bdfa075eebfec6fc21bf7cc66508b | 44,371 |
import time
def solve_classical(args):
""" Classical Model Solver """
t_init = time()
# Create the model and load the spectra.
data = map(oracle.specutils.Spectrum.load, args.spectra_filenames)
model = oracle.models.StellarSpectrum(args.config_filename, data)
# Sort the spectra from blue to... | 5e93199eb8bd168dce7c232fa6077456787c8ae2 | 44,372 |
def layer_modelformset(extra=0):
""" Form set for film layers """
return forms.modelformset_factory(ReflectivityLayer, form=LayerForm, extra=extra,
fields=('name', 'thickness', 'sld', 'i_sld', 'roughness', 'remove', 'layer_number',
... | fe053473b09e9522d296298d5513de5dafeb3cdd | 44,373 |
import json
def setup(hass, config):
"""Set up the MQTT export component."""
pub_topic = config[DOMAIN].get("publish_topic", DEFAULT_TOPIC)
global PAYLOAD
PAYLOAD = dict(states=None, details=None)
# Add the configuration
PAYLOAD["details"] = hass.config.as_dict()
def mqtt_event_listener... | e2d02e99c70bae0c65216ea8c423bf2880da1793 | 44,374 |
from .test_broadcasting import broadcast_shapes
def two_broadcastable_shapes(draw, shapes=shapes):
"""
This will produce two shapes (shape1, shape2) such that shape2 can be
broadcast to shape1.
"""
shape1, shape2 = draw(two_mutually_broadcastable_shapes)
if broadcast_shapes(shape1, shape2) !... | 78f0a0b22db6bdaee0dc81da5197fcc88e4bed9c | 44,375 |
import os
def get_data_path(file_name=None):
"""Return the path to a file in the test data directory."""
if file_name is None:
file_name = ""
return os.path.join(DATA_DIR, file_name) | 2527d09b243ecadf602687975ff7595897a741bc | 44,376 |
def observed(data):
"""Computes the observed agreement, Pr(a), between annotators."""
total = float(np.sum(data))
agreed = np.sum(data.diagonal())
percent_agreement = agreed / total
return percent_agreement | 6a7b8f5b9df47acc67f55018fd805b8d77feebf1 | 44,377 |
def number_name(item):
"""The English name for that number
>>> assert number_name(5) == 'five'
"""
return _inlection.number_to_words(item) | e71bf1b86ddf725ba5b76a0a5247869a858aa3ed | 44,378 |
def create_nmt_model(session, forward_only, model_path=None, use_best=False, FLAGS=None, buckets=None, translate=False):
"""Create translation model and initialize or load parameters in session."""
assert FLAGS is not None
assert buckets is not None
decode_input = FLAGS.decode_input
decode_file = ... | 4d0a2849eefd4fb472630e62b411989ce2f63b3e | 44,379 |
def pay_cash(amount, *args):
"""This exists so we can update the global cash counter.
:param amount: Amount to pay
:type args: bool[]
"""
paid = app_character.statblock.pay_cash(amount, *args)
return paid | a2b86cf8ff86eae587add6d8d37ef7c716dba3ae | 44,380 |
def degeneracyOrientation(G):
"""Directed version of G with <= degeneracy out-neighbors per vertex."""
D = {}
for v,d in degeneracySequence(G):
D[v] = {w for w in G[v] if w not in D}
return D | 42ecc0b31c892553e12b8dc62a9d8d47b2abf0c8 | 44,381 |
import asyncio
async def get_tec_status() -> TecStatus:
"""Analyze the current TEC subsystem status.
side effect
This will initialize all temp. ramps on units that are active but have
an undefined ramp state.
:raises TecError: Couldn't get ambient temperatures.
"""
# pylint: disa... | 4a92ba7845f2d086b5a28011ec427fa9019e47fb | 44,382 |
import json
def update_job_by_id(user, job_id):
"""Update a job
"""
# get If-Match header
if_match_etag = utils.check_and_get_etag(flask.request.headers)
values = clean_json_with_schema(update_job_schema, flask.request.json)
job = v1_utils.verify_existence_and_get(job_id, _TABLE)
job = d... | ca74f95a7a54a0ba81a994e4932c8c36d2083ad4 | 44,383 |
def _kalman_info_sample(J_ini, h_ini, log_Z_ini,
J_dyn_11, J_dyn_21, J_dyn_22, h_dyn_1, h_dyn_2, log_Z_dyn,
J_obs, h_obs, log_Z_obs):
"""
Information form Kalman sampling for time-varying linear dynamical system with inputs.
"""
T, D = h_obs.shape
# Run... | 8112835eb895845b369e666aeabe5a4cd355b5bf | 44,384 |
import json
import requests
def generate_pdf(layout: LabelLayout, api: str = DEFAULT_LABEL_API) -> bytes:
"""
Generate a PDF from the given *layout* using the `Lab Labels
<https://github.com/MullinsLab/Lab-Labels>`_ web service *api*.
Returns a byte string.
"""
spec = json.dumps(layout.spec()... | 31e0398fb32773a247ad5283fcd7eefd903dd224 | 44,385 |
from typing import Optional
from datetime import datetime
def get_term_start_end_from_date_for_actual_working_time(
start_date: Optional[str], end_date: Optional[str], tzinfo: Optional[datetime.tzinfo] = None
) -> tuple[Optional[str], Optional[str]]:
"""開始日と終了日から、実績作業時間を取得するAPIに渡すクエリパラメタterm_startとterm_endを返し... | cb93cb6880eb4e663df65e765fb1b338eb1d8369 | 44,386 |
def cwipc_source_netclient(address, verbose=False):
"""Return cwipc_source-like object that reads individual compressed pointclouds from a TCP-based server specified as host:port"""
source = _NetClientSource(address, verbose=verbose)
return source | e1779fd9c47d06bf851abd895d3aafbd79d685e5 | 44,387 |
def create_msa_matrix(chimerics, msa):
"""
Convert a msa from chimerics to a matrix.
Each cell has the subexon number (Index) or nan for gaps and padding.
"""
if not chimerics:
return np.empty((0, 0), dtype=object)
n_seq = len(msa)
n_col = msa.get_alignment_length()
msa_matrix =... | 99bf3d8404ed55064bc028675406a371f6795edf | 44,388 |
from typing import Union
def number_of_objectives(obj_instance: Union[_ScalarObjective, VectorObjective]) -> int:
"""Return the number of objectives in the given obj_instance.
Args:
obj_instance (Union[_ScalarObjective, VectorObjective]): An instance of one of
the objective classes
R... | 0f4dd7722ee4d68faa31ab582fb09de325ece338 | 44,389 |
def to_ps(obj, parlen=False):
"""Converts object into postscript literal
>>> to_ps(None)
'null'
>>> to_ps(123)
'123'
>>> to_ps(456.78)
'456.78'
>>> to_ps(True), to_ps(False)
('true', 'false')
>>> to_ps('foo bar baz')
'foo bar baz'
>>> to_ps('foo bar baz', parlen=True)
... | 11fa2888678970f9ab37e4827e87bbf67856898c | 44,390 |
import os
import subprocess
def run(*args, cwd=None,
input=None, capture_stdout=False, capture_stderr=False,
shell=False, env=None, check=True, quiet=False):
"""Runs a subprocess.
Args:
*args: The subprocess arguments.
cwd: The working directory. If None, specifies the current... | c4e3c620f316f1af8d0ec0fe3395459179bf8ea1 | 44,391 |
def undistort_image(img, mtx, dist, newcameramtx=None):
"""
Use camera intrinsics to undistort raw image
:param img: Raw Image
:param mtx: Camera Intrinsics matrix
:param dist: Distortion Coefficient
:param newcameramtx: Camera Intrinsics matrix after correction
:return: Undistorted image
... | 6d88e800d24d98ada522b087b16d5187dcba571d | 44,392 |
def voigt_tau(wave, par):
""" Find the optical depth at input wavelengths
Taken from linetools.analysis.voigt
This is a stripped down routine for calculating a tau array for an
input line. Built for speed, not utility nor with much error
checking. Use wisely. And take careful note of the expected... | 372164dba3032596d591c57d9ac66491b036608d | 44,393 |
def enum_member_name(state):
"""
All enum member names have the form <EnumClassName>.<EnumMemberName>. For
our rendering we only want the member name, so we take their representation
and split it.
"""
return str(state).split('.', 1)[1] | d6fa9320c1f96209fd6d547f1a7715ade391c672 | 44,394 |
def combine_datasets(lma_data):
""" lma_data is a list of xarray datasets of the type returned by
pyxlma.lmalib.io.cf_netcdf.new_dataset or
pyxlma.lmalib.io.read.to_dataset
"""
# Get a list of all the global attributes from each dataset
attrs = [d.attrs for d in lma_data]
# Create a ... | 48087548d182b6dce4914a82675ec91686ef1454 | 44,395 |
def gene_pvalue_burden_nb(df_model):
""" Calculate burden P-values based on the transfered NB model params
"""
# PVAL_SYN, PVAL_MIS, PVAL_NONS, PVAL_SPL, PVAL_TRUNC, PVAL_NONSYN = [], [], [], [], [], []
# for i, row in df_model.iterrows():
# PVAL_SYN.append(nb_model.nb_pvalue_greater_midp(row.O... | 52544dbd8fa3ec12c4539ac2017a110fcd6c7691 | 44,396 |
from typing import Counter
import re
def seq2polyA(seq):
""" input seq
output polyA report
(1) pass or not
(2) Left or Right
(3) most common character
(4) length of polyA
(5) length of isoseq
"""
lst = []
L = seq[0:10]
R = seq[-10:]
end = L + R
... | 61517f86dc776863d3586c2013115c2e9c0afd96 | 44,397 |
def multiscale_entropy(timeseries, stat_name, scales, **kwds):
"""
Calculates multi-scale entropy for any of the entropies defined above.
Idea from Costa, Goldberger and Peng, "Multiscale Entropy Analysis of
Complex Physiologic Time Series", Phys. Rev. Lett. 89, No.6, July 2002
timeseries: pd.Series... | 78e44ef40d956d7ae145c275b365cf406acc906a | 44,398 |
def setbit(target, bit):
"""
Устанавливает бит bit в 1 в байте target
"""
return target | (1 << bit) | 55f073fb82c5a29a50b8505be6a8a3971ebaf872 | 44,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.