content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
from datetime import datetime
def filter_archives(
archives: List[Archive],
intervals: List[datetime.timedelta],
current_date: datetime.datetime = None,
) -> List[Archive]:
"""
Return a list of archive names which should be kept.
``archives`` is a list of ``jdsnap.Arch... | 82dd416734ba9b7811a71c0ef2661b369db4ff62 | 3,599,300 |
def get_action(state, player):
"""
Returns an action from the _ACTION_CATALOGUE, given the state.
Args:
state (connect_x.game.connect_x.ConnectXState): The state.
player (int): The player.
Returns:
int: The action.
"""
matrix = bitmaps_to_matrix(state.bitmaps)
mark ... | 03e10eeca9cf9d912d226766cc0bb3f7cf0af5a6 | 3,599,301 |
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
"""Returns a path corresponding to the scheme.
``scheme`` is the install scheme name.
"""
return get_paths(scheme, vars, expand)[name] | 755223fea25a7153a3441ca048ffeb0aad68123f | 3,599,302 |
def get_bot():
"""
Gets the already instantiated Telegram client
:return: Telegram client instance
:rtype: telegram.Bot
"""
if not _bot:
initialize_bot()
return _bot | 4be9e7a3bdc4ee21a2bc126f7fcefb92daee6714 | 3,599,303 |
def get_binwise_reduced_column(a_gpu, stride, a_range):
"""
description:
calls the cuda jit function calc_binwise_reduced_column and
returns the result
input:
- a_gpu -> single col nd-array
- stride -> stride value
- a_range -> min-max values (ndarray => shape(2,))
... | 2dddf4012480d5645d86e9b0c2a61c8175977ad5 | 3,599,304 |
from typing import Dict
def select_dict_from_resname(u: Universe) -> Dict[str, str]:
"""
Infer select_dict (possibly interested atom species selection) from resnames in a MDAnalysis.universe object.
The resname must be pre-assigned already.
Args:
u: The universe object to work with.
retu... | a9e844ade104303ffc9c8b1f6b5c742570353156 | 3,599,305 |
import binascii
def mangleNec(code, freq=40):
"""Convert NEC code to shorthand notation"""
# base time is 550 microseconds
# unit of burst time
# lead in pattern: 214d 10b3
# "1" burst pattern: 0226 0960
# "0" burst pattern: 0226 0258
# lead out pattern: 0226 2000
# there's large di... | 99619206b2470526c1037a28cc8ae05393d88aa2 | 3,599,306 |
def _init_bot(bot_type, game, player_id):
"""Initializes a bot by type."""
rng = np.random.RandomState(FLAGS.seed)
if bot_type == "mcts":
evaluator = mcts.RandomRolloutEvaluator(FLAGS.rollout_count, rng)
return mcts.MCTSBot(
game,
player_id,
FLAGS.uct_c,
FLAGS.max_simulatio... | 744d2f4adf47f3a2eb59c371c10336d00f8afcb2 | 3,599,307 |
def _stacked_separable_conv(net, stride, operation, filter_size):
"""Takes in an operations and parses it to the correct sep operation."""
num_layers, kernel_size = _operation_to_info(operation)
for layer_num in range(num_layers - 1):
net = tf.nn.relu(net)
net = slim.separable_conv2d(
net,
... | 182c8fe6910927fe318f53f91bb2b8c25ad857d4 | 3,599,308 |
def get_account_by_name(account_name):
"""
Retrieves an account plus any additional custom fields
"""
account = Account.query.filter(Account.name == account_name).first()
manager_class = account_registry.get(account.account_type.name)
account = manager_class()._load(account)
db.session.expun... | c4e1a08c7f47a4ba55691904b5d27adc4d156e57 | 3,599,309 |
def first_not_none(*args):
"""
Returns the first argument that is not None.
"""
for i in args:
if i is not None:
return i
return i | 77ad9ecf4136f9a346f35fd0d027250056126f59 | 3,599,310 |
def generate_launch_description():
"""Fixture for tests."""
return LaunchDescription([
launch.actions.DeclareLaunchArgument(
'example',
default_value='example',
description='example argument'),
]) | 02bc929ec9f4185007a3cf8ab08cb1bfec42be55 | 3,599,311 |
def _ignore_epochs_exceeding_validity(dset: "Dataset") -> np.ndarray:
"""Remove GNSS observations which exceeds the validity length of a broadcast navigation record
How long a broadcast ephemeris block is valid depends on the GNSS:
- BeiDou: Not defined. Fit interval of 1 hour is used. This is an a... | fd8177806465d4c5fe5b6b8e8223538b9735f5cd | 3,599,312 |
import math
def setup_rotmat(c0, nst, it, cc, ang, pmx):
"""Setup rotation matrix.
:param c0: nugget constant (isotropic)
:param nst: number of nested structures (max. 4)
:param it: TODO
:param cc: multiplicative factor of each nested structure
:param ang: TODO
:param pmx: TODO
:return... | f5a019bb0ca4a359bda9661121180bec05644f7c | 3,599,313 |
def fetch_news_info(
ticker_list,
meta_list=[]
):
"""Process ticker_list and save news endpoints
NOTE: Step1, needs to run as first step
Args:
ticker_list (:obj:`list` str): list of tickers to fetch news feeds on
meta_list (:obj:`list`, optional): special list of index ticke... | 4bff2ec9f7c59e7ab52ec97132271f9ceb95b419 | 3,599,314 |
def omega(freq):
"""Angular frequency, omega"""
return 2.*np.pi*freq | 4f7ed2e29127bef0a3a19fd9886509379fd18955 | 3,599,315 |
def _filter3(meta, filter_peak=0.5):
"""
Filter peak based on the number of cells.
"""
meta = meta[(meta>0).sum(axis=1)>meta.shape[1]*filter_peak]
return meta.T | 06842b557422cd63589c63d96ce3b19853357844 | 3,599,316 |
from typing import Tuple
def create_categorical_encoder_and_decoder(categorical_variables: list[str]) -> Tuple[dict, dict]:
"""
Given a list of categorical variables, returns an encoder and decoder.
Encoder Key = category. Value = integer encoding.
Decoder Key = integer encoding. Value = category.
... | 70de5c8a3e1667da2776a3750c1fae1edf9fd8ae | 3,599,317 |
def bin_pop_rate(times, senders, binwidth=1.):
"""
times: spike times
senders: associated sender
binwidth: how many ms to bin in
"""
t_min = np.min(times)
t_max = np.max(times)
N_senders = len(np.unique(senders))
rate, bin_edges = np.histogram(times, np.arange(t_min, t_m... | 1880c94bfb665ab087ea01824f5273520d395218 | 3,599,318 |
def _sentinel_visitor(path, key, value):
"""If `value` is a `Sentinel` return the value it represents. Else `default_visit`"""
if isinstance(value, Sentinel):
return (key, value.retrieve_by_sentinel())
return (key, value) | 170ec197e8a882931dfd301e20f7877fb05b9624 | 3,599,319 |
def render(filename, context):
"""
template.render(filename, context) -> rendered html
filename is location of the template relative to template.TEMPLATES_DIR
context is a dictionary of values to give to the template
Raises an error if template is invalid
"""
template = parser.Template(open(TEMPLATES_DIR + '... | 368ddd01d3d24f62355318a502c71e705a7e027a | 3,599,320 |
def find_bb_centre(
x: "np.ndarray",
y: "np.ndarray",
image: "np.ndarray",
bb_diameter: float,
edge_lengths: TwoNumbers,
penumbra: float,
field_centre: TwoNumbers,
field_rotation: float,
bb_repeats: int = DEFAULT_BB_REPEATS,
bb_consistency_tol: float = DEFAULT_BB_CONSISTENCY_TOL,... | 60198b68355a3ce81d873c28702ce0f45fcc0683 | 3,599,321 |
def cf_NIG(u, t=1, mu=0, theta=-0.1, sigma=0.2, kappa=0.1):
"""
Characteristic function of a Normal Inverse Gaussian random variable at time t
mu: additional drift
theta: Brownian motion drift
sigma: Brownian motion diffusion
kappa: Inverse Gaussian process variance
"""
return np.ex... | 9237bc40462f7b365ca6f8f95b463ecc2a4f576a | 3,599,322 |
def update_dependencies(new_dependencies, existing_dependencies):
"""Update the source package's existing dependencies.
When a user passes additional dependencies from the command line,
these dependencies will be added to the source package's existing dependencies.
If the dependencies passed from the c... | 7f520c0c980cd0b929be32d9d4cceb8c99f75934 | 3,599,323 |
def zeta_real(s):
"""
zeta function for a real positive value s.
zeta(s) = \sum n^{-s} = \prod (1 - p^{-s})^{-1}
"""
zeta_s = 1
for p in prime.generator():
euler_factor = 1 - 1/p**s
if euler_factor == 1:
break
zeta_s /= euler_factor
return zeta_s | f548b0c922893d590973bb906b9add7d8abb8135 | 3,599,324 |
def do_compress(data, pid):
""" this *must* succeed adding the pdf"""
try:
# compress
data = pdf_compress(data)
except:
pass
db = get_mongo('paper')
db.update({'_id': pid}, {'$set': {'pdf': Binary(data)}} )
log_info("Updated pdf {0}: size={1}".format(
pid, parse_... | 9b5d58cd6b3fb74922fa25a3207c11055ae80d24 | 3,599,325 |
def dask_client(request):
"""
This fixture is meant to be called one per pytest session.
The goal of this function is to create a global client at the start
of the testing phase. We can create clients at the start of the
session (this case, as above scope is session), module, class or function
l... | 3aa97336a26fc13cd8712234248d4e29f393a244 | 3,599,326 |
def BuildService(credentials=None):
"""Build the directory api service.
Args:
credentials: Optional credentials to use instead of any in the datastore.
Returns:
service object for interacting with the directory api
Raises:
Exception: An exception that that the PEM file content is not valid.
"""... | 48c5c84417d99c8b3ea9d867a1d7bf9fa61263ca | 3,599,327 |
def norm_xcorr(a, v):
"""
Compute the normalized cross-correlation (lag plot)
args
a : time series #1
v : time series #2
returns
normlized cross correlation (where 1.0 is 100% correlated)
"""
a = (a - np.mean(a)) / (np.std(a) * len(a))
v = (v - np.mean(v)) / np.std... | 1d7aa0d9857a91e234b681b963ebb163afb356fd | 3,599,328 |
def get_modules(model_params, action_spec):
"""Get agent modules."""
model_params, n_q_fns = model_params
if len(model_params) == 1:
model_params = tuple([model_params[0]] * 2)
elif len(model_params) < 2:
raise ValueError('Bad model parameters %s.' % model_params)
def q_net_factory():
return netwo... | 1a266420496dc8da6b0a763379a4f5f95c6be57f | 3,599,329 |
import logging
def main(bugs: list, main_plugin: MainPlugin or MetaPlugin, **kwargs: dict) -> None:
"""
Run all given bugs
:param bugs: bugs to run
:param main_plugin: the main plugin enabled for the run
:param kwargs: additional information for bug triggering
"""
change_coredump_filter()
... | 0438310a30fa7937daedccfeb067835da4fcd479 | 3,599,330 |
def hidden50(**kwargs):
"""Constructs a ResNet-50 model.
"""
model = Hidden(2304,2304,2)
return model | bdc0cc3a86412b0e34cba8bc99841a82ea1b56f2 | 3,599,331 |
def parse(message_text, retrieve_url_titles=True, url_timeout=0.5):
"""
Parse message and extract mentions, emoticons and links.
Args:
message_text [str]: A string of text to be parsed
retrieve_url_titles [bool]: whether or not to try to retrieve titles
for detected links
... | 3938f93f4da8cd4bd18549438cc7a6b7e2b4a75e | 3,599,332 |
import functools
def trace_info(tmpdir_factory):
"""Return a TracedCommand that uses temporary directories.
"""
remote_dir = str(tmpdir_factory.mktemp("remote"))
local_dir = str(tmpdir_factory.mktemp("local"))
cls = functools.partial(TracedCommand,
remote_dir=remote_dir... | f8351290e729f3df83e11dc3eb9b977910fd8c2e | 3,599,333 |
def long_decrypt(s, kx, spice, blocksize, lmask=None):
""" Decryption of Long Subciphers (128 < blocksize < 513) """
if not lmask: lmask = (1 << 64) - 1
for cycle_num in reversed(range(1 + BACKUP + BACKUPSUBCIPHER[4])):
for i in range(len(s)-1):
s[i] = m_sub(s[i], kx[(blocksize&255)+8+... | 017a8d2ee64fee2be597b6ff10f7d189875f3e24 | 3,599,334 |
from datetime import datetime
def hfeed(value, arg=None, autoescape=None):
"""
Formats a value to conform with the hFeed Microformat fragment
Inspired by the markup found here:
http://microformats.org/wiki/hatom-examples
"""
if isinstance(value, datetime.datetime) or isinstance(value, st... | 1db040228d3bdbab4f3939889585832ba700b199 | 3,599,335 |
def read_brecon(infile, tree, stree):
"""
Reads branch reconciliation from file
"""
brecon = {}
for line in infile:
tokens = line.rstrip().split("\t")
# parse node
node_name = tokens[0]
if node_name.isdigit():
node_name = int(node_name)
node = t... | 366295c2196df5c45bae9d8a59d068814285b168 | 3,599,336 |
import logging
def get_VGG16_model(input_shape: list, model_path: str) -> tf.keras.models.Model:
"""saving and returning the base model extracted from VGG16 model
Args:
input_shape (list): shape of the input image
model_path (str): path to save the base model
Returns:
tf.keras... | 2a5367b52fa43560e37c7c9fb40ec0e269f0088c | 3,599,337 |
import json
def ontology_add_term():
"""
Title: Add new ontology term
URL: /ontology/add
Description : Add a new term to the ontology term list and link to parent, synonyms
Method: POST
URL Params:
Data Params: JSON
{
"term" : str
the new term to add (de... | 802538a9a88bb5a96b5161ef6d2521ae983f48cd | 3,599,338 |
def _convert_to_int_list(check_codes):
"""Takes a comma-separated string or list of strings and converts to list of ints.
Args:
check_codes: comma-separated string or list of strings
Returns:
list: the check codes as a list of integers
Raises:
ValueError: if conversion fails
... | 965a68466d0aab358043cedb4838ac9d99ce3249 | 3,599,339 |
import collections
def _build_personalize_fn(optimizer_fn):
"""Builds a personalization function given an optimizer constructor."""
optimizer = optimizer_fn()
@tf.function
def personalize_fn(model, train_data, test_data, context=None):
def train_fn(num_examples_sum, batch):
"""Runs gradient descen... | 14e8d4df295f77e7f4b5beeb657cebf0b4aae2b7 | 3,599,340 |
from typing import Optional
def analize_variadic_generic(
ctx: AnalyzeTypeContext,
validate_callback: Optional[_ValidateCallback] = None,
) -> MypyType:
"""
Variadic generic support.
What is "variadic generic"?
It is a generic type with any amount of type variables.
Starting with 0 up to ... | e072788ba599bd0b58627f83f2eadcae7394ddf7 | 3,599,341 |
def _get_functions(expr, ldelim="(", rdelim=")"):
"""Parse function calls."""
tpars = _pair_delims(expr, ldelim=ldelim, rdelim=rdelim)
alphas = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fchars = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "_"
tfuncs = []
... | 1b6d5ee905275b5da01fb26032c1afdbd2fd1265 | 3,599,342 |
import xml
def CreateUIActionList(actions_per_command, num_commands, given_seed=None):
"""Generate user-like pseudo-random action sequences.
Args:
actions_per_command: length of each ui action sequence.
num_commands: number of sequences to generate.
seed: optional rand seed for this list.
Returns:... | 09bd3e983e5e53ea05ae7db436e3b9e9a4bc95c2 | 3,599,343 |
import time
def benchmark(get_response):
"""
Prints the time needed to perform a request.
"""
def middleware(request):
# Start timer.
start = time.time()
# Performs the request
response = get_response(request)
# Elapsed time.
delta = int((time.time()... | 288d72e9b96253d68bd5ee4727aa99ffaaae4f30 | 3,599,344 |
def get_note_freq(p):
"""
Return the frequency corresponding to a particular
note number
Parameters
----------
p: int
Note number, in halfsteps. 0 is a concert a
"""
return 440*2**(p/12) | cec12355f481494fa53fb0ed535ecd82fd038016 | 3,599,345 |
import pickle
def main(refs,sys_outs,out_file):
"""
inputs::
refs: a txt file with a list of labels for each wav-fileid in the format: <id> <label>
sys_outs: a txt file with a list of scores (probability of being covid positive) for each wav-fileid in the format: <id> <score>
threshold (optional):... | 7aaa0adbca42771bd0c7b9befbe7569e78453098 | 3,599,346 |
def eval_dfcell(cell_value):
""" Returns None if cell is NaN else, the value """
if dfcell_is_empty(cell_value):
return None
return cell_value | 9d7789f25b776c0b9c807d49c974a165eaf95594 | 3,599,347 |
import os
def upload_aixm_dataset() -> ResponseType:
"""
Uploads a dataset after applying some validation.
The max size of the file is handled by nginx.
:return:
"""
try:
file = utils.validate_file_form(request.files)
except ValueError as e:
raise BadRequestError(descripti... | 7b045208558f53c6d938c2179b83c81e43e19537 | 3,599,348 |
def stringify_parameters(items):
"""
Convert all items in list to string.
"""
return [str(item) for item in items] | 41a47f611d1514043eeac27de6c8be6c01607649 | 3,599,349 |
def count_missing(genotypes, axis=None):
"""Count non-missing genotype calls.
Parameters
----------
genotypes : array_like, int
An array of shape (n_variants, n_samples, ploidy) or
(n_variants, ploidy) or (n_samples, ploidy), where each
element of the array is an integer corres... | d15bac11ed2a7fd2d64d80a9f54095040020685a | 3,599,350 |
def get_current_spec_list(ctx):
"""
Get the current spec list, either from -p/--project-specs or --specs-to-include-in-project-generation or
specs_to_include_in_project_generation in user_settings.options
:param ctx: Current context
:return: The current spec list
"""
try:
return ctx.... | e0e2788b86bf005b6986ab84f507d784ef837cca | 3,599,351 |
import torch
def inner_prod(x, y):
"""A function that returns the inner product of two complex vectors,
x and y (<x|y>).
:param x: A complex vector.
:type x: torch.Tensor
:param y: A complex vector.
:type y: torch.Tensor
:raises ValueError: If x and y are not complex vectors with their f... | e89d97845941f09120272669eb09a882fba90fed | 3,599,352 |
def kpt_mapping_back(kpts, img_shape, scale_factor, flip):
"""Map bboxes from testing scale to original image scale"""
new_kpts = kpt_flip(kpts, img_shape) if flip else kpts
new_kpts = new_kpts / scale_factor
return new_kpts | 336f1d0c679c45ee363438aa4883ff45f734e9bc | 3,599,353 |
def get_Emission_Likelihoods(tHMMobj, E: list = None) -> list:
"""
Emission Likelihood (EL) matrix.
Each element in this N by K matrix represents the probability
:math:`P(x_n = x | z_n = k)`,
for all :math:`x_n` and :math:`z_n` in our observed and hidden state tree
and for all possible discre... | 5b0569acbc45bb11c46226784a43770598d701f8 | 3,599,354 |
import requests
import json
def retrieve_user_name_from_user_id(user_id):
"""Return a user name given a user ID.
"""
url = '{0}/api/3/users/{1}'.format(BASE_URL, user_id)
response = requests.get(url, auth=AUTH, headers=generate_headers())
if response.status_code != 200:
print("[-] User ID... | f720753072fa1d7e22233ec41f350231b8d64874 | 3,599,355 |
import os
import subprocess
def create_pager(highlight_text=None):
""" Returns a pipe to PAGER or "less" """
pager_cmd = os.environ.get('PAGER')
if not pager_cmd:
pager_cmd = ['less', '-r']
if highlight_text:
pager_cmd.extend(['-p', highlight_text])
pager = subprocess.Pop... | 1fde7ecffd050122b2f9b41b5cf5e43b0e7e688c | 3,599,356 |
def title_from_name(name):
"""
Create a title from an attribute name.
"""
def _():
"""
Generator to convert parts of title
"""
try:
int(name)
yield 'Item #%s'% name
return
except ValueError:
pass
it = iter(n... | 44182a7aefc552701517292563717884835230aa | 3,599,357 |
def check_address_exists_pc(request, list_id):
""" 检测地址池是否在母子账户中。
"""
try:
MailList.objects.get(id=list_id, customer=request.user)
return True
except:
try:
MailList.objects.get(id=list_id, user=request.user.parent)
return True
except:
r... | e34bd02b5384eb1e36c35dd1102d2d53042bbf0a | 3,599,358 |
def parse_subexp(
pattern: str, timings: list[str], args: list[str]
) -> tuple[str, list[RuleDef]]:
"""Parse a susecion of o or more consecutive rules."""
subexp: list[RuleDef] = []
while pattern:
pattern, rule = parse_rule(pattern, timings, args)
if rule is not None:
sube... | c9f64e5ac3100cd2bd9fca24a60e884ec2a73d75 | 3,599,359 |
def sort_reagents(gras):
""" Sort reagents by size, from largest to smallest
:param gras: the reagent (i.e. reactant or product) graphs
:returns: the reagent graphs, in sorted order
"""
gras = tuple(gras)
idxs = argsort_reagents(gras)
gras = tuple(map(gras.__getitem__, idxs))
return gra... | a59d8f815ec0d9caf1f99243c6fd214b3c1c579f | 3,599,360 |
import os
def check_dir(p, fix_guards=False):
"""Walk recursively over a directory checking .h files"""
def prune(d):
if d[0] == '.' or d == 'third_party':
return True
return False
for root, dirs, paths in os.walk(p):
# Prune dot directories like .git
[dirs.re... | aef1c4f6e8e9d616d39de0faab300a1825bde5df | 3,599,361 |
def fill_empties(abstract):
"""Fill empty cells in the abstraction
The way the row patterns are constructed assumes that empty cells are
marked by the letter `C` as well. This function fill those in. The function
also removes duplicate occurrances of ``CC`` and replaces these with
``C``.
P... | cc27354fd50ac8588c8374e06025a2ceeff691c6 | 3,599,362 |
def normal_shock_density_ratio(M, gamma):
"""GIves the normal shock density ratio as a function of upstream Mach number."""
return ((gamma+1.0)*M**2.0)/(2.0+(gamma-1.0)*M**2.0) | 780e435602278f02d3a1839f460edf1ce40a5a5a | 3,599,363 |
def garage_door():
"""Opens the garage door and takes a picture to show state"""
date_string = time.strftime("%Y-%m-%d-%H:%M:%S")
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(25, GPIO.OUT)
GPIO.setup(23, GPIO.IN)
# activate input with PullUp
GPIO.setup(23, GPIO.IN, pull_... | 690d0633f93e43de2b8d66801822b54db11d398a | 3,599,364 |
import pandas
def fast_api_query(client=None, url=None, name=None, team=None,
project=None, version=None, password=None,
as_df=False):
"""
Retrieves the list of dataframe based on partial information.
:param client: for unittest purpose
:param url: API url (can b... | f6c289a5fec0dde98e363d83b7eda9aa42a179c8 | 3,599,365 |
def _corrupt_contrast(image, mask):
"""Randomly applies a random contrast change."""
cond_contrast = tf.cast(tf.random_uniform(
[], maxval=2, dtype=tf.int32), tf.bool)
image = tf.cond(cond_contrast, lambda: tf.image.random_contrast(
image, 0.2, 1.8), lambda: tf.identity(image))
return im... | 1bfd28a0b8008ae41c0aba794af8a0b4f19b0305 | 3,599,366 |
import time
import http
import urllib
import json
def get_verifycode():
"""
获取验证码
"""
# 获取当前时间戳
timestamp = time.time()
url = 'http://newxk.urp.seu.edu.cn/xsxkapp/sys/xsxkapp/student/4/vcode.do?timestamp=' + \
str(int(timestamp))
# global vtoken
# 创建cooliejar对象
cookie = htt... | 668a41f3779d5d6e2e606ebf1b6860ec731329e1 | 3,599,367 |
def _find_ebcdic_codec(code_name):
"""
The `codec.CodecInfo` matching `codec_name` provided it is part of the
package, otherwise `None`.
"""
return _codec_name_to_info_map.get(code_name) | c4370c76cdeaf2025af153602fcdd276ad00f74c | 3,599,368 |
def get_default_out() -> tuple[str, str, str]:
"""To return private default values.
Returns:
Returns three strings. The first describes the default string for describing
the purchase price. The second the default string for the sum of all sales
taxes of the purchase and the third the de... | ca04785570be033d3ca176425ab0103d8e2e5e38 | 3,599,369 |
def my_train_k():
"""交易训练页面"""
return render_template("train_k.html") | 267360cd4cf4e624be126f22b51a08df49657509 | 3,599,370 |
def np_json_value(x):
"""Ensures values are json compabible."""
if np.isnan(x):
return None
else:
return str(x) | 151c8c45ab79afc46d652f9a60180d729d0705a0 | 3,599,371 |
def run_with_PI_exploration(PI=None, exploration=0.2, N_Iter = 100, render_flag=False):
"""
Return buff_df if done, otherwise return None
"""
if PI is None:
# No PI, action will be determined fully randomly
exploration = 1.0
s = flake.reset()
if render_flag: flake.render()
... | cb1d4898a71b76c8f39934c565019ef5d7e3fde7 | 3,599,372 |
import configparser
def aws():
"""Read and parse config file and create AWS API connection."""
config = configparser.ConfigParser()
config.read('config.ini')
config.sections()
my_config = Config(region_name=config['aws']['region'],
signature_version='v4',
... | 5753e14e8df32956eb8e3a983f714b9345033ab0 | 3,599,373 |
def rfc822date(text):
""":rfc822date: Date. Returns a date using the same format used in email
headers: "Tue, 18 Aug 2009 13:00:13 +0200".
"""
return util.datestr(text, "%a, %d %b %Y %H:%M:%S %1%2") | 7af6e856c2b906ec39d76e0f997faab414f9cbab | 3,599,374 |
def pretty_print(state):
""" Returns a 3x3 string matrix representing the given state. """
assert len(state) == 9
str_state = [str(i) for i in state]
lines = [' '.join(map(str, l)) for l in [state[:3], state[3:6], state[6:]]]
return '\n'.join(lines) | 67fb7b091e7256d1fa71f2936d3c8989d5a90f0e | 3,599,375 |
def get_rules_packages(opts=None):
"""
The AWS Inspector Rules Packages data source allows access to the list of AWS
Inspector Rules Packages which can be used by AWS Inspector within the region
configured in the provider.
"""
__args__ = dict()
if opts is None:
opts = pulumi.Invoke... | 20b611e8082c853108ff098b0428ee7fa002874a | 3,599,376 |
import time
import torch
def validate(Dataset, model, criterion, epoch, writer, device, args):
"""
Evaluates/validates the model
Parameters:
Dataset (torch.utils.data.Dataset): The dataset
model (torch.nn.module): Model to be evaluated/validated
criterion (torch.nn.criterion): Los... | a2165748647062a7882464968e3fceedde310a4d | 3,599,377 |
def make_df(nrow: int, ncol: int) -> pd.DataFrame:
"""make toy DataFrame"""
df = pd.DataFrame(np.random.randint(100_000, 1_000_000, size=(nrow, ncol)),
columns=[f'col{i}' for i in range(ncol)]).astype(float)
return df | 8aab14f9e0673f989befc203c78bdb512cbb5b28 | 3,599,378 |
import requests
def user_info(handles):
"""
Returns information about one or several users.
Return value: Returns a list of User objects for requested handles.
Parameter:
- handles (Required): Semicolon-separated list of handles. No
more than 10000 handles is a... | 690dbe93d3693389ef62fa19d0a678b44d69bf72 | 3,599,379 |
def field_output_format(override=None, field_name=None):
"""
Decorator in charge of giving the output its correct format, either
json or pandas
Parameters
----------
func: function
The function to be decorated
override: str
Override the internal format of the call, default n... | 5b3134c000aed03aaae21001ae2cc74e325607f3 | 3,599,380 |
def time_difference(dataset, since, until):
"""
For the given dataset returns dataframe with time differences between measurements of buses' locations.
:param dataset: List of pandas.DataFrames, each corresponding to one moment of time. Each of these dataframes should have columns: "Lines", "Lon", "VehicleN... | 82e2540cbeb278b2f0a37ccb54ae840d62dbfc54 | 3,599,381 |
def dask_detrend_data(data, output_arr):
"""
Detrend data using a linear fit.
Parameters
----------
data: dask.array
Input dataset to detrend. Assumes leading axis is sampling dimension.
output_arr: ndarray-like
Output array with same shape as data to store detrended data.
... | db8cb60e3a4c2cf87a44eb53a559715734fb442a | 3,599,382 |
def I_props(D, B, TF, TW, ETABS=True):
"""Properties of an I-section
>>> I_props(12, 15, 3, 2)
{'P': 74, 'A': 90, 'Avy': 72, 'Avz': 30, 'Iyy': 2767.5, 'Izz': 858.0}
"""
A = B*D - (B-TW)*(D-2*TF)
Iyy = B*D**3/12 - (B-TW)*(D-2*TF)**3/12
Zyy = 2 * Iyy / D
Syy = B * TF * (D - TF) + 0.25 * TW... | c10d8c0e0bf65bfa17d4b29250d42db30466eccc | 3,599,383 |
import ssl
def get_server_context(verify=True):
"""Our TLS configuration for the server"""
server_ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
server_ctx.set_ecdh_curve('prime256v1')
server_ctx.verify_mode = ssl.CERT_OPTIONAL if not verify else ssl.CERT_REQUIRED
server_ctx.set_ciphers(CIPHERS)
... | f12b26246d76e1244c7cd068a75f4b5d16ae07ee | 3,599,384 |
def listofilesuploaded(currentuser):
"""
Function to return list of files uploaded by a user.
"""
session=DBSession()
files=session.query(Filedetails).filter_by(userid=currentuser.userid)
listoffiles=[]
for i in files:
filedata={}
filedata['fileid']=i.fileid
filedata[... | 5cb6a0da1838436c9bf5b5e50abcc99e222157bc | 3,599,385 |
def statistic(current):
""" Categorize and count the samples
Return an numpy.record whose dtype=[('x',int),('f',int)]"""
samprob = {}
for x in current:
xind = state2ind(x)
if xind in samprob:
samprob[xind] += 1
else:
samprob[xind] =1
memory = [(x, samprob[x]) for x in samprob]
memory = np.asarray(memo... | 35282e1d91284dd0b5735aab7ed36d8802619888 | 3,599,386 |
import os
import sys
def load_txt(archive, dt, date1):
"""
Opens and reads an archive .txt with data only (without dates).
:Parameters:
| **file:** filename
| **dt:** A number. Time-step of the vector. Example: Hourly, daily, monthly, etc.
| **date1:** A number. The initial time of t... | c440906d7a3c44d62d98e9ae3d1aa2121a2d0ac8 | 3,599,387 |
def traceroute(params):
"""
Execute some `traceroute` commands via subprocess.
Args:
params ([TracerouteParams]): params for the `traceroute` commands
Returns:
[TracerouteResult]: stats from the executed `traceroute` commands
"""
return subprocess_workflow.exec_and_parse_subpro... | fe8407a0a2b56ee38eea2031ce3236ae6fb1511e | 3,599,388 |
def load_fourier_spectrum(fname):
"""Load Fourier amplitude spectrum file created by fas_drvr.exe.
Inputs
------
fname : string
File name of the data file
Returns
-------
event : dict
Dictionary containing the event
"""
assert fname.endswith('_fs.col')
rows = np... | 7c9b1bc9c62d7d4f84344533e579ea3972503749 | 3,599,389 |
from typing import List
from typing import Dict
from typing import Any
def expand_decks_list(
decks: List[Dict[str, Any]],
deck_info: Dict[str, Any],
) -> List[Dict[str, Any]]:
""" Given a list of decks and their cards,
fills in the missing information using the detailed decks specification
"""
... | 1a50f5c2ba461be54605cf7637d64a8257200494 | 3,599,390 |
import json
def decode_req_encode_rsp(f):
"""Decorator to decode incoming requests and encode responses."""
def decode_inner(req):
return json.dumps(f(json.loads(req)))
return decode_inner | ee41df3de3c41fbe2f32ddf4a07e769abfe31fda | 3,599,391 |
def jamieson_pth(v, v0, c0, s, gamma0, q, theta0, n, z, mass, c_v,
three_r=3. * constants.R, t_ref=300.):
"""
calculate thermal pressure from Hugoniot data using the constq
formulation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param c0: velo... | 55c662c60a5cdcbc6bae1deaafb17afb1f2b8eeb | 3,599,392 |
def init_circuit(state: QuantumCircuit | Statevector) -> QuantumCircuit:
"""Initialize state."""
if isinstance(state, QuantumCircuit):
return state
if not isinstance(state, Statevector):
state = Statevector(state)
qc = QuantumCircuit(state.num_qubits)
qc.append(Initialize(state), qar... | 318967530295d80861186055554f9a7f4c000b0a | 3,599,393 |
def vinth2p(datai, hbcofa, hbcofb, plevo, psfc, intyp, p0, ii, kxtrp):
"""
Interpolates CCSM hybrid coordinates to pressure coordinates. A
multi-dimensional NumPy array of the same shape as datai is
returned, except that the input level coordinate is replaced by
plevo.
array = Ngl.vinth2p(datai, hbcofa, hbcofb, ple... | 50164358db897412d3fe7df9434223c9f1ced65a | 3,599,394 |
import re
def find_images(document):
"""Returns the list of image filepaths used by the `document`."""
images = []
for line in document:
match = re.match(r"\.\. image::\s+(img\/.+)", line)
if match:
images.append(match[1])
return list(set(images)) | 2c58b04974f5ec0d1752cb405cfd314de81a841c | 3,599,395 |
import html
def card_cutouts(data):
""" Add a card containing cutouts
Parameters
----------
data: java.util.TreeMap
Results from a HBase client query
Returns
----------
card: dbc.Card
Card with the cutouts drawn inside
"""
card = dbc.Card(
dbc.CardBody(
... | 2a568fa6416d70ce5d423c40d0ecc6f38af946f0 | 3,599,396 |
from datetime import datetime
def _read_time_from_string(str1):
"""
Reads the time from a string in the format HH:MM:SS.S and returns
:class: datetime.time
"""
full_time = [float(x) for x in str1.split(':')]
hour = int(full_time[0])
minute = int(full_time[1])
if full_time[2] > 59.99:
... | d876c47b60827acfd7fba05794124136734be017 | 3,599,397 |
def extract_kwargs_from_ctx(ctx):
""" Extracts kwargs from Click context manager. """
args = []
i = 0
for arg in ctx.args:
if arg[:2] == '--':
args.append([arg[2:]])
i += 1
else:
args[(i-1)].append(arg)
for i, arg in enumerate(args):
if le... | 678a819daf33a26c599cea08817397741bfbef8a | 3,599,398 |
def load_config(cfgfile):
""" Parses a configuration file """
cfgf = open(cfgfile,'r')
cfg = {}
for l in cfgf:
ps = [p.strip() for p in l.split(':')]
if len(ps)==2:
try:
cfg[ps[0]] = float(ps[1])
except ValueError:
cfg[ps[0]] = ps[... | 283a36f1d92c58b0018fe62714cc9dc23f96c898 | 3,599,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.