content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def update_output(list_of_contents, list_of_names, list_of_dates):
"""
check for upload of the files
"""
if list_of_names:
if len(list_of_names) == 1:
if list_of_contents is not None:
children = [
parse_contents(c, n, d) for c, n, d in
... | 9d462947e82687030d22047bef8b53f9f7106d91 | 54,023 |
import logging
def upload(csv_file, bucket_name, blob_name):
"""Uploads csv_file to bucket_name.
Args:
csv_file: CSV file to upload.
bucket_name: Bucket to upload the files to.
blob_name: Path of the file in the bucket.
Returns:
The path of the uploaded file in GCS.
""... | 8f8d4d9ce1722d1356093209a19e81aca4754fa8 | 54,024 |
def lift(cra, crb):
"""Returns the relative uplift in conversion rate.
Parameters
----------
cra: float
Conversion rate of Group A
crb: float
Conversion rate of Group B
Returns
-------
float
Relative uplift in conversion rate
"""
return ((crb - cra) / cra)... | 2489fef702153657f007751bc5234d11d8333f75 | 54,025 |
import logging
def get_asso_words(txt, stopwords, w, window=2, t=2, s=0.5, m=10):
"""Main method for getting keywords
Keyword arguments:
txt -- txt-file address
stopwords -- stopwords-file address
word -- the keyword to query
window -- adjacent window ... | 3d99735e2372a35b3fd03e7eef816d5d38e6241b | 54,026 |
def convert_object_to_float(x):
"""
Convert input object to float
:param x: input series/signal as datatype not a float
:return: same series/signal with datatype float.
"""
if isinstance(x, str):
x = x.strip('\'')
try:
return float(x)
except ValueError:
... | 6b862b1202e0180bf2ee6d1d0916c0cf4aed09ae | 54,027 |
import numpy
def _get_pressures(sounding_dict):
"""Returns pressure levels in soundings.
:param sounding_dict: Dictionary created by
`_convert_interp_table_to_soundings` or `_pressure_to_height_coords`.
:return: pressure_matrix_pascals: N-by-P numpy array of pressures.
"""
if PRESSURE_LE... | 3032dfc577743b64c229b68be56708b36ad920af | 54,028 |
import ast
def load(symbol_id: str) -> ast.Name:
"""Returns an AST Name node that loads a variable."""
return ast.Name(id=symbol_id, ctx=ast.Load()) | 94a76bdac89a9e7b1f766832dd2aef63469704ac | 54,029 |
import tests
async def subprocess() -> tests.helpers.Subprocess:
"""Return an asynchronous executor for testing subprocesses."""
return tests.helpers.Subprocess() | 00016d30b7033c72c85742aa2e43566ec8fbd9b0 | 54,030 |
def controller_encryption_key_id_generate(handle, controller_type,
controller_slot, server_id=1):
"""
Generates a random key id for the given controller
Args:
handle (ImcHandle)
controller_type (str): Controller type
'... | 3c29230b745bf61f09f7ba390b17c5e3f60e4602 | 54,031 |
def is_videoid_in_db(videoid):
"""Return True if the video is in the database, else False"""
if videoid.mediatype == common.VideoId.MOVIE:
return G.SHARED_DB.movie_id_exists(videoid.value)
if videoid.mediatype == common.VideoId.SHOW:
return G.SHARED_DB.tvshow_id_exists(videoid.value)
if ... | cf6df695e6d6ce33e02a22267416069570762d3d | 54,032 |
def image_frame_to_camera_frame(image_frame, camera_intrinsics):
"""Un-project points that are in image frame to the camera fame.
Given a camera intrinsics matrix K, and a set of 2d points in image frame,
this functions returns the 3D points at unit depth.
Currently this function only supports a linear camera... | e8f2bb1fd5d4cb393977ef7fd1cc9d65e08c9043 | 54,033 |
def descent(X, targets, thetas, hypothesis, calc_cost, **kwargs):
"""Gradient descent"""
MAX_ITS = kwargs.pop('max_its', DEF_MAX_ITERATIONS)
LRN_RT = kwargs.pop('lrn_rt', DEF_LEARNING_RATE)
REG_P = kwargs.pop('reg_p', DEF_REG_P)
MIN_DELTA = kwargs.pop('min_delta', DEF_MIN_DELTA)
m = len(targets)
cost_his... | 8a1416fe0b1bc261f0282e3df444e06840d8112b | 54,034 |
def sharpe(returns, rfr=0, expanding=0):
"""
returns: periodic return string
rfr: risk free rate
expanding: bool
"""
if expanding:
excess = excess_returns(returns, rfr)
return pd.expanding_mean(excess) / pd.expanding_std(returns)
else:
return excess_returns(returns, r... | 1d8fff9ea219fb8a3ccbb56ede4d36414080f571 | 54,035 |
def _NegGrad(_, grad):
"""Returns -grad."""
return -grad | c2a2800e1d80c3151019425e3871c235485c9324 | 54,036 |
def utilize_ListOf(schema, data, **kwargs):
""" Validate a list with arbitrary length.
Validate each value from `data` against `schema.schema`.
`schema` is a `ListOf` instance. """
schema_list = [schema.schema for item in data]
return utilize_list(schema=schema_list, data=data, **kwargs) | 180bcdf358615075d705ea8614e4eec75ea273c9 | 54,037 |
from typing import OrderedDict
def init_vec(f, names, data):
"""Initialize resizable 1d arrays to hold the outputs."""
# Iterate over 'names' and columns of 'data'
dset = [
(name, f.create_dataset(name, data=d, maxshape=(None,)))
for name, d in zip(names, data.T)
] # -> list
retu... | ed024e176da68d1a6753da305cea0a36d21e0e7a | 54,038 |
import inspect
import builtins
def getclosurevars(func):
"""
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be re... | 4e726ed1d748b9b3331cf5f6556702a015ccc31e | 54,041 |
def clean_url(url):
"""
Reformat a URL with all querystrings stripped
:param url: The URL
:return: A clean URL
"""
return url[:url.find('?')] | 56edc6db7b59e1550a68377dcdcb80a83b79e854 | 54,042 |
import tqdm
def get_camera_bouma(df, fieldfile='../data/camera_boresights_SNE-shifted.csv'):
"""
Like get_camera, only better
"""
camdf = get_camera_coords(fieldfile)
observed = np.zeros((df.shape[0], camdf.shape[0]), dtype='int')
for ix, row in tqdm(camdf.iterrows(), total=camdf.shape[0]):
... | f516a780b7bbbf13fc9073c260b875007c114a20 | 54,043 |
def animal_categories():
"""Return list of strings"""
categories = open(CATEGORIES_ANIMAL_PATH).readlines()
categories = [c.strip() for c in categories]
return categories | 2dfeb18cd3819565b18933e71b6b39ef7345fa56 | 54,044 |
import json
def read_json(path: str) -> dict:
"""
This method reads the file specified in
:param path: resource path
:return: json object
"""
with open(path) as f:
data = json.load(f)
return data | 9bb4b4c43fb3585dfd004f2d297997b99a68b19b | 54,045 |
def rmseff(x, c=0.68):
"""Compute half-width of the shortest interval
containing a fraction 'c' of items in a 1D array.
"""
x = np.sort(x, kind="mergesort")
m = int(c * len(x)) + 1
return np.min(x_sorted[m:] - x_sorted[:-m]) / 2.0 | c69c26da13a5c26c85f572360d0e2cd1eb2e39c9 | 54,046 |
def small_movies_json_file():
"""
Runs once per session. Provides the content of small_movies.json from read.
"""
with open('./datasets/small_movies.json', 'r', encoding='utf-8') as movie_json_file:
return movie_json_file.read().encode('utf-8') | b6a744a01411b93aa96580a75c3cfb3786f49a35 | 54,047 |
def get_router_connection(deploy_config: dict) -> paramiko.SSHClient:
"""
Opens a connection to the configured router
Can throw:
- ValueError
- BadHostKeyException
- AuthenticationException
- SSHException
- socket.error
"""
router_config = deploy_config["rout... | 470e84210981cac27021d6be13d69c5a4c137b4d | 54,048 |
import re
def isValid(text):
"""
Returns True if the input is related to the meaning of life.
Arguments:
text -- user-input, typically transcribed speech
"""
return bool(
re.search(
r'email',
text,
re.IGNORECASE)) or bool(
re.sea... | a03fc94f223397f163382b40bee885101ef4420a | 54,049 |
def _has_abstract_methods(node):
"""Determine if the given `node` has abstract methods.
The methods should be made abstract by decorating them
with `abc` decorators.
"""
return len(utils.unimplemented_abstract_methods(node)) > 0 | a2276ede374bb9d12ec0de81d03646f631cd291e | 54,050 |
def simplify_tags(tags):
"""
>>> simplify_tags([set([('defined(world)', True), ('defined(hello)', True)]),
... set([('defined(world)', False), ('defined(hello)', True)])])
[set([('defined(hello)', True)])]
>>> simplify_tags([set([('defined(LIBEV_EMBED)', True), ('defined(_WIN32)', Tru... | 43f8a7aa16ea054daaa8f948144304beef998668 | 54,051 |
import torch
def mol_to_graph_data_obj_simple(
mol,
partial_charge=False,
substruct_input=False,
pattern_path=None,
mask=False,
hops=5,
pooling_indicator=False,
):
"""
Converts rdkit mol object to graph Data object required by the pytorch
geometric package. NB: Uses simplified ... | b8f9e1f5bcd9be90882b0695e1543209200189c8 | 54,052 |
def level_is_rtl(lev):
"""
Return True if `lev' is a Right-to-Left level, False otherwise.
"""
return lev & 1 | 5c3d6127bcef2f17b347c7c26a86f723f25ab6a7 | 54,053 |
from datetime import datetime
def bpcalc(request):
"""Calculate blueprint production details for X number of days"""
# Get a valid number of days
try:
days = max(1, int(request.GET.get('days', '7')))
except ValueError:
days = 7
# Initialise variabls
bpis = []
bpi_totals = ... | e7221802f64b98feedf85bbc24b974ef8ff878a5 | 54,054 |
def calc_E_E_L_d_t(n_p, A_A, A_MR, A_OR, L):
"""1 時間当たりの照明設備の消費電力量(kWh/h)
Args:
n_p(float): 仮想居住人数
A_A(float): 床面積の合計[m^2]
A_MR(float): 主たる居室の床面積[m^2]
A_OR(float): その他の居室の床面積[m^2]
L(dict): 照明設備仕様辞書
Returns:
ndarray: E_E_L_d_t 日付dの時刻tにおける 1 時間当たりの照明設備の消費電力量[kWh/h]
"... | efe38cbfbc414109f2e7036651d3b1cf9e57ace5 | 54,055 |
def safe_divide(numerator, denominator, ones=False):
"""Divide ignoring div by zero warnings"""
if isinstance(numerator, pd.Series):
numerator = numerator.values
if isinstance(denominator, pd.Series):
denominator = denominator.values
numerator = numerator.astype(float)
denominator ... | 29c1a8d98838996fb5803f9d663ca51b37662413 | 54,056 |
def fgt_set_sensorRegulation(sensor_index, pressure_index, setpoint):
"""Sets the flow rate on the specified flow rate channel, using the
specified pressure channel as an actuator"""
c_error = c_ubyte(lib.fgt_set_sensorRegulation(c_uint(sensor_index),
c_uint(pressure_index), c_f... | b501de599d588cc35e0a3ccb24fec9d1656805a0 | 54,057 |
def _read_solvr(f):
"""Read SOLVR block data."""
fmt = block_to_format["SOLVR"]
solvr = {}
line = next(f)
data = read_record(line, fmt)
solvr["solver"] = {
"method": data[0],
"z_precond": data[2],
"o_precond": data[4],
"rel_iter_max": data[5],
"eps": data... | 2322711f2dbe934e53a7ab67db812b82e6e0de1c | 54,058 |
import torch
def default_states_preprocessor(states):
"""
Convert list of states into the form suitable for model. By default we assume Variable
:param states: list of numpy arrays with states
:return: Variable
Obtained from https://github.com/Shmuma/ptan/blob/master/ptan/agent.py
"""
... | 997f3e9e21cfd9dac0fa78d23ee41232b0aeea82 | 54,060 |
from typing import List
def get_candidates_for_bid(bid_id: str) -> List[helpling_schema.DecoratedPotentialCandidateEdge]:
"""
Query the API for all (i.e. the first 1000) candidates for a given bid. The bid must have been parametrized already.
Note that not all fields are actually requested from the backen... | 55a327daec333ed99613d55ce593714e1829f734 | 54,061 |
import math
def arc_svg_to_parametric(src, dst, rx, ry, x_axis_rot, large_flag, sweep_flag):
"""Convert arc from SVG arguments to parametric curve
This code mostly comes from arc implementation notes from svg sepc
(Arc to Parametric)[https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes]
Re... | 52d6de27dac64978987e11156f1f597d8910a753 | 54,062 |
def GroupBuilder(size, builderFunc, indAttr):
"""size - the number of members of the group
indAttr - a list of [size, possList, probList] for IndividualBuilder
file - the csv file to rebuild an existing group from"""
individualSize = indAttr[0]
possList = indAttr[1]
probList = indAttr[2]
... | 8bd144c71acd177518b12ce2dd209d2838c6fff4 | 54,063 |
def _read_timestamp(file):
"""Get start and end time from timestamp csv file."""
try:
with open(file, 'r') as f:
rows = f.readlines()
starttime, endtime = float(rows[0].split(",")[0]), float(rows[-1].split(",")[0])
starttime, endtime = starttime / (10**3), endtime / (10**... | be403b62623f45e6cf43c6239c1c068a48987183 | 54,065 |
from typing import Dict
def _refine_resourcedetails(response: Dict, Translator: DataFields) -> ResourceDetails:
"""Parse the resource details response.
Args:
response: Ganttic API response
Translator: Description of fields
Returns: task Details Pydantic.
"""
res = response.copy(... | ed237682657b44a33cef0d914d702989c7672540 | 54,066 |
def plot_sim_matrix(clusterings, scoring):
"""
Plot a similarity matrix between a list of clusterings, using the provided scoring function.
:param clusterings: list of clusterings to compare
:param scoring: the scoring function to use
:return: a ClusterGrid instance
Example:
>>> from cdli... | cb6d78637dbb3f1fb94d7cd1d90a8447e98c685f | 54,067 |
def _copy_attachments(syn: Synapse, entity_wiki: Wiki) -> list:
"""Copy wiki attachments
Args:
syn: Synapse connection
entity_wiki: Wiki you are copying
Returns:
Synapse Attachment filehandleids
"""
# All attachments must be updated
if entity_wiki["attachmentFileHandle... | 6efde5c82784adab0dbcb01eeeef808c727044a4 | 54,068 |
def generic_actor(name=None, health=None,
r=None, g=None, b=None, y=None,
x=None, m=None, h=None, c=None):
"""Simple factory to keep tests focused."""
base = (50, 100)
health = health or base
r = r or base
g = g or base
b = b or base
y = y or base
x = ... | ac6bce23951eddd0edd84733017d87d214097a47 | 54,069 |
def error_not_found(message, redirect):
"""
Shows an error message that a page couldn't be found.
"""
return error('Not found: {}'.format(message), redirect) | 15ec1c261027b6e610adb06107e8e4fde2098ef6 | 54,070 |
import math
def Rz(angle:float, use_degrees:bool=False) -> np.ndarray:
"""Rotation matrix, for a rotation about the z-axis.
Args:
angle (float): Counter-clockwise angle of rotation as viewed
looking back along the postive direction of the rotation axis.
use_degrees (bool): Handle... | 541dffe668dae30fdc2f4daf12e049a8274c9991 | 54,071 |
def __folha(soup):
"""
Gets the most read news from the Folha de Sao Paulo page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Folha de Sao Paulo Page
"""
news = []
anchors = soup.find('ol', class_='c-most-read__list').find_all('a')
for a in anc... | c2f518776ac6969be93f96b4320dc596f708ecd6 | 54,072 |
def get_table_cols_w_type(table, conn_handler=None):
"""Returns the column headers and its type
Parameters
----------
table : str
The table name
conn_handler : SQLConnectionHandler, optional
The connection handler object connected to the db
Returns
-------
list of tuple... | 3663f9cb1b34adafbd43a6dc6dcecd8f9efd537b | 54,073 |
from typing import Callable
from typing import Awaitable
def _require_auth(
handler: Callable[[web.Request, "User"], Awaitable],
*,
redirect: bool = True,
admin: bool = False,
) -> Callable[[web.Request], Awaitable]:
"""This does the heavy lifting for the authorization check"""
@wraps(handler... | ffaba778620eb5eb0286733bbf4f0cf8f9adcee0 | 54,074 |
import torch
def generate_padding_mask(x: torch.Tensor, length: torch.Tensor) -> torch.Tensor:
"""
Args:
x: tensor of shape [batch_size, length]
length: tensor of shape [batch_size]
Returns:
float tensor of shape [batch_size, length]
"""
assert x.dim() == 2
assert lengt... | d475cfa6eb81525745bed8613827c59bac57aa5d | 54,075 |
import functools
import time
def slow_down(_func=None, *, rate=1):
"""Sleep given amount of seconds before calling the function"""
def decorator_slow_down(func):
@functools.wraps(func)
def wrapper_slow_down(*args, **kwargs):
time.sleep(rate)
return func(*args, **kwargs)... | 15018e0012fb3486d10a3883a8603235c876d651 | 54,078 |
def RegularStrandCurvature(**kwargs):
"""
Returns angle and dihedral constraints strings that dictate the curvature of strands
without bulges. Given a strand, place curvature and twist constraints every 2*level positions.
Angle constraints, for curvature, are placed on CA atoms. Dihedral... | 15e5590b06b9a9c7934693504bd464abdf45f8d6 | 54,079 |
import pathlib
def test_get_save_file(mocker, tmp_path):
"""
test get_save_file
"""
def mock_user_data_dir(appname, appauthor, version):
return tmp_path / appname / appauthor / version
mocker.patch.object(resources.appdirs, "user_data_dir",
mock_user_data_dir)
m... | 07ac2e90233521c3fb6d3ccb8885c38a78105a14 | 54,080 |
def _compose_tfms(args):
"""Create a composite transform from inputs."""
in_file, in_xform, ifargs, index, newpath = args
out_file = fname_presuffix(in_file, suffix='_xform-%05d' % index,
newpath=newpath, use_ext=True)
xfm = ants.ApplyTransforms(
input_image=in_fi... | 363bc3a021a9afc297e638ad445561d37d08943a | 54,081 |
async def changelog() -> HTMLResponse:
""" Display the changelog for this API """
return HTMLResponse(content=_get_changelog_html()) | e342cd507807bcb2f4e9019e98096e012af341ba | 54,082 |
def set_level(world_number, char): # used for changing to a new level and reloading level
"""
Changes the level and soft-resets the character state.
The total gold collected is stored, while current gold is reset.
The character's position is also set to the new world's start position.
If not all t... | c7975142227b73cd47c5e466232fbb7a75d109dc | 54,083 |
def apply(df, target_func, n_cpus=None):
"""
Apply row-wise a user-defined target function to the file index. Each row
is passed as input to the function. The call for each row is done in parallel.
Parameters
----------
- df: a DataFrame with the file index.
- target_func: a user-defined f... | 5f6d5c1abf04638c0d033e7b9aecb566956d5832 | 54,084 |
def load_mnist() -> Dataset:
"""Loads the MNIST dataset using OpenML.
OpenML dataset link: https://www.openml.org/d/554
"""
mnist_openml = openml.datasets.get_dataset(554)
Xy, _, _, _ = mnist_openml.get_data(dataset_format="array")
X = Xy[:, :-1] # the last column contains labels
y = Xy[:, ... | 5f781c803dae9b609ae1b4d1912493661babed0b | 54,085 |
from typing import Union
from typing import Callable
import torch
from typing import Dict
from typing import Optional
from typing import Any
def gen_save_best_models_by_val_score(
save_handler: Union[Callable, BaseSaveHandler],
evaluator: Engine,
models: Union[torch.nn.Module, Dict[str, torch.nn.Module]],... | a78792c2ac45199100851ad2a6c6eaa88f15de4f | 54,086 |
def favicon():
""" Returns the favicon when working in dev. """
return flask.send_from_directory('static/images', 'favicon.ico') | 6298a327f0764a227e95020d7da21765e16b0521 | 54,087 |
def load_np(filename, control=False):
"""
Load the raw data from h5 files
:param filename: [string] filename to be read in
:return: 4 x [np array[float64]] leads, [np array[int]] time vector,
[np array[int]] heartrate vector from machine, [np array[float64]] abs pos sum ECG signal
"""
pr... | 2115c898d5cf6e2cce6948ce8f9ba6848b399e60 | 54,088 |
def get_ent(s):
"""
Return 1 if there is no enantiomer and 2 if there is based on
@ sign appearing in the smiles
"""
sites = 0
xyz = get_xyz(s)
s2 = get_smiles(xyz)
frags = s2.split('[')
for frag in frags:
if '@' in frag:
sites += 1
ent = 2.**sites
retu... | 62d39b6a6ce44ab018ab9108c8db6724f739a3a6 | 54,089 |
from typing import Union
def read_pkg_info(path: Union[bytes, str, PathLike]) -> Message:
"""Read a PKG-INFO or METADATA file."""
with open(path, encoding="utf-8") as headers:
return Parser().parse(headers) | 728914c88bc8eac5e02b3f537bb935166788f335 | 54,090 |
import __builtin__
def isdefined(obj, force_import=False, namespace=None):
"""Return True if object is defined in namespace
If namespace is None --> namespace = locals()"""
if namespace is None:
namespace = locals()
attr_list = obj.split('.')
base = attr_list.pop(0)
if len(base) == 0:
... | 0163770ada4122f7e690ab15fe2226da4005f885 | 54,091 |
from typing import Dict
from typing import Any
from typing import Type
from typing import Optional
from typing import Callable
from re import T
def deserialize_namedtuple(
obj: Dict[str, Any],
to: Type[NT],
attr_deserializers: Optional[Dict[str, Callable[[PrimitiveType], T]]] = None,
type_deserializer... | 5bd86c986385bfd0d54455df839417de5cdf05dc | 54,092 |
def infer_reader(file_path, word_dict):
"""
Reader interface for prediction
:param data_dir: data directory
:type data_dir: str
:param word_dict: path of word dictionary,
the dictionary must has a "UNK" in it.
:type word_dict: Python dict
"""
def reader():
UNK_ID = word... | 6c8c3bace7fc61342e048de3d383f85a1b9b9278 | 54,093 |
def object_func(x, A, b):
""" Objective function for the optimization for L-BFGS-B
"""
y = A * x - b
return 0.5 * y.dot(y) | 8a9453f6f93f4b7c7e2f5202a2a81750df5c27df | 54,094 |
def create_wallet(request):
"""Create wallet from the form data."""
if request.method == "POST":
form = CreateWalletForm(request.POST)
if form.is_valid():
wallet_id = add_wallet(
form.cleaned_data["name"], form.cleaned_data["password"]
)
if ... | 4468f6af82222045652c73dfec44a0d9e62b0eaf | 54,095 |
def random_binomial(shape, p=0.0, dtype=None, seed=None):
"""Returns a tensor with random binomial distribution of values.
# Arguments
shape: A tuple of integers, the shape of tensor to create.
p: A float, `0. <= p <= 1`, probability of binomial distribution.
dtype: String, dtype of ret... | b7e58fd0d0796d9a0b7cd9c0ea30873b34a61f64 | 54,096 |
def generate_user_data(count=1):
"""
generate a list of dictionaries containing data necessary to create a User object
:param count:
:return:
"""
return [{'username': 'user_{:03}'.format(i)} for i in range(1, count + 1)] | cd1aebc0414d7b31d5636ed3938a6bbc6d5e98bf | 54,097 |
def fast_gen(generator, cond):
"""generate with padded input"""
p = generator.compute_padding_values()[0]
cond = jnp.pad(cond, [(0, 0), (p, p), (0, 0)], mode="reflect")
return generator(cond) | 591f967bbd10bf0a27a62f82b29babd21615f2c4 | 54,099 |
def computeJz(bx, by, bx_err, by_err, conf_disambig, bitmap, nx, ny):
"""function: computeJz
This function computes the z-component of the current.
In discretized space like data pixels, the current (or curl of B) is calculated as the integration
of the field Bx and By along the circumference of the ... | 09f831d0bde7a3d1cba3051aad4a0fa7f66132f3 | 54,100 |
def hw5ode3(t, x):
"""Function containing the third ODE
(Van der Pol’s equation with \\eta = 2).
- **parameters**, **types**, **return** and **return types**::
:param t: current time
:param x: state at current time
:type t: np.float
:type x: np.array[float]
:return: Derivative of state at current time
:... | 946cdd729a04c7c0d7da85869092dd0fd1428cc9 | 54,101 |
def write_refkey_to_file(refkey_file, password, key_pem, key_der, cert, encode_format): # pylint: disable=too-many-arguments
"""
Write reference key into file
:param refkey_file: File name to store reference key
:param password: Password for encryption of pkcs12 reference key
:param key_pem: Refere... | b82ab3f95f0f5cde06e10193ceceee82d7ad16f4 | 54,102 |
def plot_learning_curve(sample_sizes, learning_curves, curve_labels, xscale='log', ax=None):
""" Plot the learning curve.
Parameters
----------
sample_sizes : array
The sample sizes in which the classifier is run.
learning_curves : array
List of learning_cur... | aa77b82cf9d20e59f83861286d8169c827c02d29 | 54,103 |
def quantumvolume(nbits=6, measure=True):
"""
This is a nbit quantum volume circuit
reference: https://qiskit.org/textbook/ch-quantum-hardware/measuring-quantum-volume.html
"""
qubit_lists = [list(range(0, nbits))]
qv_circs, qv_circs_nomeas = qv.qv_circuits(qubit_lists, 1)
if measure... | 886e37706cc9bc3b852a63a8a97a3110bc0228ea | 54,104 |
from pathlib import Path
def get_frontend_dir() -> Path:
"""Get the frontend directory."""
if LOCAL_APP_DIR.exists():
logger.info("Using local DEVELOPMENT frontend directory.")
return LOCAL_APP_DIR
elif GLOBAL_FRONTEND_DIR.exists():
logger.info("Using global frontend directory.")
... | df7c656a29ec7fc8377e90954c253391c6fbea6f | 54,105 |
from sklearn.datasets import fetch_mldata
def mnist(missingness="mcar", thr=0.2):
""" Loads corrupted MNIST
Parameters
----------
missingness: ('mcar', 'mar', 'mnar')
Type of missigness you want in your dataset
th: float between [0,1]
Percentage of missing data in generated data
... | 1aca3246dc73f28704249fa56e693eee6165241b | 54,107 |
def run_images(tags):
"""Run a list of docker images, in background."""
print "### Running images ###"
return [run_image(tag) for tag in tags] | 9de9bb498b456ffe3be921ea025bfeeb8f51b3af | 54,108 |
import struct
def _transitive_proto_descriptor_sets_impl(ctx):
"""Implementation of transitive_proto_descriptor_sets rule.
Args:
ctx: The rule context.
Returns:
All transitive proto descriptor files as default output.
"""
gathered = _gather_transitive_protos_deps(ctx.attr.deps)
d... | 3c0aa7c81e25f39a3e10a86ddb5d3d28412c3474 | 54,109 |
import typing
from typing import TypeGuard
from datetime import datetime
def is_timelength_timedelta(
timelength: typing.Any,
) -> TypeGuard[spec.TimelengthTimedelta]:
"""return bool of whether input is TimelengthTimedelta"""
return isinstance(timelength, datetime.timedelta) | de7f4eba31f479bd6a81119f98ad2d9051bc3f46 | 54,110 |
def hef_command(s, *args):
"""
Create fully qualified HEF command (add prefix and postfix the CRC).
:param s: command string
"""
return build_command('3', s, *args) | 6e8b5f3a37205a754bc6d98d92af3a8654d9cdee | 54,111 |
def list_folder():
"""List a folder.
Return a dict mapping unicode filenames to
FileMetadata|FolderMetadata entries.
"""
path = DROPBOX_PROJECT_PATH
try:
res = dbx.files_list_folder(path)
except dropbox.exceptions.ApiError as err:
return {}
else:
return res.entri... | f034e9f41b21809a80d94cf23563fe9978056529 | 54,112 |
def genomic_del1_free_text_lse(genomic_del1_free_text,
genomic_del1_free_text_seq_loc):
"""Create a test fixture for genomic del LSE."""
_id = "ga4gh:VA.DdtLZ_d22R0O0VU020WcCLvNhXNZtU2j"
genomic_del1_free_text["variation_id"] = _id
genomic_del1_free_text["variation"] = {
... | 1a197b97b615e063c6409c48a3cbcd802a66e058 | 54,113 |
def min(iterable):
"""
min() overwrites python built-in,
checks if all constants and computes np.min() in that case
"""
if not any(isinstance(elem, Expression) for elem in iterable):
return np.min(iterable)
return Minimum(iterable) | f7b774a6a671491ce33d3e1cd50946e58c624752 | 54,114 |
from typing import Union
from typing import List
def mode(x: Union[List[float], np.ndarray]) -> float:
"""Calculate the mode of a list of numbers.
Args:
x: List or Numpy array.
Returns:
Mode.
Examples:
>>> mode(x=[1., 2., 3., 4., 5.])
2.0
>>> mode(x=[1., 2., ... | f9324ff8d5b8a45f2183ec02ec882e360c054cdc | 54,115 |
def topic_scores(run_scores):
"""
Use this function for a dictionary that contains the topic scores for each measure outputted by trec_eval.
@param run_scores: The run scores of the previously evaluated run.
@return: Dictionary containing the topic scores for every measure outputted by trec_eval.
"... | 5e909d20304530dc3e4c85f7a342c001e1298c8f | 54,117 |
import collections
def _make_args(args_list, session, fw_props):
"""
Converts the given list of arguments into a list (args) and a
dictionary (kwargs).
All arguments with an assignment are put into kwargs, others in args.
:param args_list: The list of arguments to be treated
:param session: T... | 94f4c25dbfbe5ffb3cef532e5aae85c54abe0783 | 54,118 |
from typing import OrderedDict
def create_profile(name, node):
"""
Create a :class:`Profiler` for the Iteration/Expression tree ``node``.
The following code sections are profiled: ::
* The whole ``node``;
* A sequence of perfectly nested loops that have common :class:`Iteration`
... | 92e076bfdb5d1eacba276a2ead0e5e2c01b24f65 | 54,119 |
def jaccard(pred: np.ndarray, target: np.ndarray, eps: float = 1e-7) -> np.ndarray:
"""
Calculate Jaccard coefficient
Args:
pred (np.ndarray): predicted masks of shape [B, H, W]
target (np.ndarray): target masks of shape [B, H, W]
eps (float): smooth value
Returns:
np.n... | c2054eeb8059efe124f624d73bba30331769ed0e | 54,120 |
def has_prefix(sub_s, d):
"""
:param sub_s:
:return:
"""
for key in d:
if key.startswith(sub_s):
return True | c9544f3937a47eb7d9b18b4209acd3fa9283de12 | 54,121 |
def slow_closest_pair(cluster_list):
"""
Compute the distance between the closest pair of clusters in a list (slow)
Input: cluster_list is the list of clusters
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum ... | 701885531ba00d1a72337651b4e6276e034d61b8 | 54,122 |
def requires_true(attrs=[]):
"""
This decorator is used to require that a certain set of class attributes are
set to True.
Otherwise it will trigger a WebUIError.
"""
return _requires_value(True, attrs) | fbec2bdd2bece58fc987f68bb7c61bd6ef012a12 | 54,123 |
import copy
def explicit_k(obj):
"""explicit_k solver.
Used to compute one time step of systems with x-dependent thermal
contuctivity.
"""
x = copy.copy(obj.temperature)
# computes
for i in range(1, obj.num_points - 1):
eta = obj.dt / (2. * obj.rho[i] * obj.Cp[i] * obj.dx * ob... | d9b90169448a257fbf7e1bbc5604170c19ec6fa6 | 54,126 |
import urllib
import requests
import json
def get_wikidata_desc(wikidata_id):
"""Return the image for the Wikidata item with *wikidata_id*. """
dapp = urllib.parse.urlencode({'action':'wbgetentities','ids':get_wikidata_id(wikidata_id),'languages':'de'})
query_string = "https://www.wikidata.org/w/api.php?"... | 5af37fba17655efaf911bdfa596b59723886f23e | 54,127 |
def bayesdb_generator_modelnos(bdb, generator_id):
"""Return list of model numbers associated with given `generator_id`."""
sql = '''
SELECT modelno FROM bayesdb_generator_model AS m
WHERE generator_id = ?
ORDER BY modelno ASC
'''
return [row[0] for row in bdb.sql_execute... | e7cbb96679f25815df6a28e3eb89ad61e4b20e09 | 54,128 |
from typing import List
def format_terminal_call(cmd: List[str]) -> str:
"""
Format commands to/from the terminal for readability
:param cmd: List of strings much like sys.argv
:return: Formatted string used for display purposes
"""
return ' '.join(cmd).replace("--", " \\ \n\t--") | 63af43a7d8a5cb708f8a9f6d7467e62e378876b4 | 54,130 |
def plot_attribution(a, a_display=None, title=None, ylabel='',
conf_level=0.95):
"""Produce a plot of the ensemble forecasts
Returns
----------
plt object
"""
a = a.reset_index(drop=True)
if type(a) is not pd.core.frame.DataFrame:
raise Exception('a, the attribution data... | e5800e844806145777b6cca2abb5a62b57b48a49 | 54,131 |
def process_first_section(section_text, filename, context):
"""Special treatment for the first top-level section of a Vim doc file."""
output = []
hits, misses = 0, 0
output.append("[discrete]")
output.append("== First section")
mark_unprocessed_text_start(output, context)
for c, line in enu... | 0b47889eb8f00f58fc1e8d41d6279cfaaf9ce163 | 54,132 |
def evaluate_and_log_bleu(estimator, bleu_source, bleu_ref, vocab_file_path):
"""Calculate and record the BLEU score."""
subtokenizer = tokenizer.Subtokenizer(vocab_file_path)
uncased_score, cased_score = translate_and_compute_bleu(
estimator, subtokenizer, bleu_source, bleu_ref)
tf.logging.info("Bleu s... | ca76832397503f56a66cd3adaff4ef67b72653bb | 54,133 |
def isSameCapacityAndSpeed(drives,raids):
""" Check if all the HDDs in the RAID container have the
same capacity and speed. Return True if so, if not
return an error message.
"""
if len(raids) <= 0:
return True
else:
slots = raids[0]['sas_id'].split(',')
drivesOnRAID = fi... | d03f9ae1786370538eebdb17f4cca57528493bf5 | 54,134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.