content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def geo_to_string(value):
"""
Convert geo objects to strings, because they don't support equality.
"""
if isinstance(value, list):
return [geo_to_string(x) for x in value]
if isinstance(value, dict):
result = {}
for dict_key, dict_value in value.iteritems():
result[dict_key] = geo_to_string(dict_value)
... | 9566a980128767ea4b2d651c88d715673e7ef005 | 3,652,662 |
import http
def page_not_found(request, template_name='404.html'):
"""
Default 404 handler.
Templates: `404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
"""
t = loader.get_template(template_name) # You need to create a 404.html t... | de0348f3c3bf963f1614d13ffc32bb79d30437b0 | 3,652,664 |
import csv
def load_data(filename):
"""
Load shopping data from a CSV file `filename` and convert into a list of
evidence lists and a list of labels. Return a tuple (evidence, labels).
evidence should be a list of lists, where each list contains the
following values, in order:
- Administr... | eb2465d0ebfb7398a3742d8fb79463d3d7b076f0 | 3,652,665 |
def instance_mock(cls, request, name=None, spec_set=True, **kwargs):
"""
Return a mock for an instance of *cls* that draws its spec from the class
and does not allow new attributes to be set on the instance. If *name* is
missing or |None|, the name of the returned |Mock| instance is set to
*request.... | ccc60e2f90f63a131059714b3ddb213246807a0b | 3,652,666 |
import functools
import torch
def auto_fp16(apply_to=None, out_fp32=False):
"""Decorator to enable fp16 training automatically.
This decorator is useful when you write custom modules and want to support
mixed precision training. If inputs arguments are fp32 tensors, they will
be converted to fp16 aut... | 1b3292ce6382f82b210d07ec48557f3c06ed7259 | 3,652,667 |
def get_loci_score(state, loci_w, data_w, species_w, better_loci,
species_counts, total_individuals, total_species,
individuals):
"""
Scoring function with user-specified weights.
:param state:
:param loci_w: the included proportion of loci from the original data se... | e5e12bf2f9f76e994289a33b52d4cdc3d641ec8e | 3,652,668 |
def make_per_cell_fastqs(
reads,
outdir,
channel_id,
output_format,
cell_barcode_pattern,
good_barcodes_filename):
"""Write the filtered cell barcodes in reads
from barcodes_with_significant_umi_file
fastq.gzs to outdir
Parameters
----------
reads... | 16f45364e8a081addf7b126c3d5af4fb00de4bdc | 3,652,669 |
def plot_roc_curve(data, cls_name, title='ROC curve'):
"""
:param data: list [(fpr, tpr), (), ...]
:param cls_name: tuple of names for each class
:param title: plot title
:return:
"""
def cal_auc(tpr, fpr):
return np.trapz(tpr, fpr)
def plot_single_curve(fpr, tpr, cls_ind):
... | 5b2a56c3f193954173431341185b3bdc53c33c7a | 3,652,670 |
import time
def train(elastic_coordinator, train_step, state):
"""
This is the main elastic data parallel loop. It starts from an initial 'state'.
Each iteration calls 'train_step' and returns a new state. 'train_step'
has the following interface:
state, worker_stats = train_st... | ea7886bba7db96ff85e1687b3b3e24cbc8f8af9d | 3,652,671 |
import torch
def softmax_mask(w: torch.Tensor,
dim=-1,
mask: torch.BoolTensor = None
) -> torch.Tensor:
"""
Allows having -np.inf in w to mask out, or give explicit bool mask
:param w:
:param dim:
:param mask:
:return:
"""
if mask is N... | 6cf295b308040d3ad4019ab8292b37a679fb6e27 | 3,652,673 |
from jack.readers.multiple_choice.shared import MultipleChoiceSingleSupportInputModule
from jack.readers.natural_language_inference.modular_nli_model import ModularNLIModel
from jack.readers.multiple_choice.shared import SimpleMCOutputModule
from typing import Union
def modular_nli_reader(resources_or_conf: Union[dic... | 03032966355fcb3405cbc2f311908d7be1f2485d | 3,652,674 |
def move_box_and_gtt(n_targets=3,
time_limit=DEFAULT_TIME_LIMIT,
control_timestep=DEFAULT_CONTROL_TIMESTEP):
"""Loads `move_box_or_gtt` task."""
return _make_predicate_task(
n_boxes=1,
n_targets=n_targets,
include_gtt_predicates=True,
include_move_bo... | 4ae2377d0449b93d3dc0ff34e18010c7bff004d8 | 3,652,675 |
import json
def get_body(data_dict, database_id, media_status, media_type):
"""
获取json数据
:param media_type:
:param media_status:
:param data_dict:
:param database_id:
:return:
"""
status = ""
music_status = ""
if media_status == MediaStatus.WISH.value:
status = "想看... | 4d09b4000c47dc1dc56aa73ca7b176d40f360e97 | 3,652,676 |
def _find_full_periods(events, quantity, capacity):
"""Find the full periods."""
full_periods = []
used = 0
full_start = None
for event_date in sorted(events):
used += events[event_date]['quantity']
if not full_start and used + quantity > capacity:
full_start = event_date... | 16c36ce8cc5a91031117534e66c67605e13e3bd4 | 3,652,677 |
import random
def crop_image(img, target_size, center):
""" crop_image """
height, width = img.shape[:2]
size = target_size
if center == True:
w_start = (width - size) / 2
h_start = (height - size) / 2
else:
w_start = random.randint(0, width - size)
h_start = random... | c61d4410155501e3869f2e243af22d7fc13c10ee | 3,652,678 |
def _histogram(
data=None,
bins="freedman-diaconis",
p=None,
density=False,
kind="step",
line_kwargs={},
patch_kwargs={},
**kwargs,
):
"""
Make a plot of a histogram of a data set.
Parameters
----------
data : array_like
1D array of data to make a histogram o... | cc766f3367c0c7b5c3c1f56c120f8e682c14a8fb | 3,652,679 |
def getGarbageBlock():
"""获取正在标记的众生区块
{
?block_id=
}
返回 json
{
"is_success":bool,
"data": {"id": ,
"election_period":
"beings_block_id":
"votes":
"vote_list":
"status":
"create_time":
"""
try:
beings_block... | 9faff268d1f492adde467a100d93e99d0b2cc583 | 3,652,680 |
from typing import Dict
import itertools
def cluster_confusion_matrix(pred_cluster:Dict, target_cluster:Dict) -> EvalUnit:
""" simulate confusion matrix
Args:
pred_cluster: Dict element: cluster_id (cluster_id from 0 to max_size)| predicted clusters
target_cluster: Dict element:cluster_id (c... | b3a5afb5c01cf5cb07c43e3666111d06e9229259 | 3,652,682 |
def change_short(x, y, limit):
"""Return abs(y - x) as a fraction of x, but with a limit.
>>> x, y = 2, 5
>>> abs(y - x) / x
1.5
>>> change_short(x, y, 100)
1.5
>>> change_short(x, y, 1) # 1 is smaller than 1.5
1
>>> x = 0
>>> change_short(x, y, 100) # No error, even though... | 1d4965650f12c95ba54f1ce38fc63e1e6eb39573 | 3,652,683 |
import copy
import tqdm
def generate_correlation_map(f, x_data, y_data, method='chisquare_spectroscopic', filter=None, resolution_diag=20, resolution_map=15, fit_args=tuple(), fit_kws={}, distance=5, npar=1):
"""Generates a correlation map for either the chisquare or the MLE method.
On the diagonal, the chisq... | 1294f1a93a98602ee50e5e52aacea6e678625520 | 3,652,684 |
import socket
def local_ip():
"""find out local IP, when running spark driver locally for remote cluster"""
ip = ((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(
("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(soc... | d45978f3f433adba5cb1181d71cb367ceabd880f | 3,652,685 |
def string_to_int_replacements(setting, item, for_property):
"""Maps keys to values from setting and item for replacing string
templates for settings which need to be converted to/from Strings.
"""
replacements = common_replacements(setting, item)
replacements.update({
'$string_to_int': str... | c6ae6a55fdda2fe13bd3ac7001da528d704e3df7 | 3,652,686 |
import struct
def UnpackU32(buf, offset=0, endian='big'):
""" Unpack a 32-bit unsigned integer into 4 bytes.
Parameters:
buf - Input packed buffer.
offset - Offset in buffer.
endian - Byte order.
Return:
2-tuple of unpacked value, new buffer offset.
"""
... | 061ba5e8c4db891100549d0181475b8915d9fb0a | 3,652,689 |
def get_reset_token(user, expires_sec=1800):
"""
Create a specify token for reset user password
Args:
user:
expires_sec:
Returns:
token: string
"""
hash_token_password = Serializer(APP.config['SECRET_KEY'], expires_sec)
return hash_token_password.dumps({'user_name': u... | 6477f03ca25a206db18c4a0a59ae0fac1106e262 | 3,652,690 |
from typing import Union
def _on_error_resume_next(*sources: Union[Observable, Future]) -> Observable:
"""Continues an observable sequence that is terminated normally or
by an exception with the next observable sequence.
Examples:
>>> res = rx.on_error_resume_next(xs, ys, zs)
Returns:
... | ed604de1b566bc73b394143bb0b8bc487646ac1a | 3,652,691 |
def prompt_for_value(field_name: str, field_type):
"""Promt the user to input a value for the parameter `field_name`."""
print_formatted_text(
f"No value found for field '{field_name}' of type '{field_type}'. "
"Please enter a value for this parameter:"
)
response = prompt("> ")
whi... | 3483b718f09d5a99a37a9d6086e462acf546cbf3 | 3,652,692 |
def create_dist_list(dist: str, param1: str, param2: str) -> list:
""" Creates a list with a special syntax describing a distribution
Syntax: [identifier, param1, param2 (if necessary)]
"""
dist_list: list = []
if dist == 'fix':
dist_list = ["f", float(param1)]
elif dist == 'binary'... | 19cb93867639bcb4ae8152e4a28bb5d068a9c756 | 3,652,694 |
def compute_arfgm(t, qd, p, qw=0.0):
"""computes relative humidity from temperature, pressure and specific humidty (qd)
This might be similar to https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.relative_humidity_from_specific_humidity.html
algorithm from RemapToRemo addgm
**Arguments:*... | 3e74be0b2099774482c32e2a3fbc4e2ee3f339fe | 3,652,695 |
def load_data():
""" loads the data for this task
:return:
"""
fpath = 'images/ball.png'
radius = 70
Im = cv2.imread(fpath, 0).astype('float32')/255 # 0 .. 1
# we resize the image to speed-up the level set method
Im = cv2.resize(Im, dsize=(0, 0), fx=0.5, fy=0.5)
height, width = Im... | 3caaa20ecb43853910f1d42667bd481bbe62e17d | 3,652,697 |
def create_response_body(input_json):
"""Create a json response with specific args of input JSON."""
city_name = str(input_json['name'])
country_code = str(input_json['sys']['country'])
temp_celsius = get_val_unit(input_json, 'main', 'temp', ' °C')
wind_speed = get_val_unit(input_json, 'wind', 'spee... | 4696f6d6929eea941697bf7aab49d139e4bd6229 | 3,652,698 |
def _get_count(_khoros_object, _user_id, _object_type):
"""This function returns the count of a specific user object (e.g. ``albums``, ``followers``, etc.) for a user.
:param _khoros_object: The core :py:class:`khoros.Khoros` object
:type _khoros_object: class[khoros.Khoros]
:param _user_id: The User I... | 5e0cb02a74a819984ab271fcaad469a60f4bdf43 | 3,652,701 |
def antiSymmetrizeSignal(y, symmetryStep):
"""
Dischard symmetric part of a signal by
taking the difference of the signal at x[n] and x[n + symmetry_step]
get your corresponding x data as x[0:len(y)/2]
Parameters
----------
y : array_like
numpy array or list of... | 0936d5fc3883d3ce6ee2f6c77fb9b4bc59177426 | 3,652,702 |
def lms_to_rgb(img):
"""
rgb_matrix = np.array(
[[0.0809444479, -0.130504409, 0.116721066],
[0.113614708, -0.0102485335, 0.0540193266],
[-0.000365296938, -0.00412161469, 0.693511405]
]
)
"""
rgb_matrix = np.array(
[[ 2.85831110e+00, -1.62870796e+00, -2.481... | 76ce7a5f73712a6d9f241d66b3af8a54752b141d | 3,652,703 |
import time
def timeit(func):
"""
Decorator that returns the total runtime of a function
@param func: function to be timed
@return: (func, time_taken). Time is in seconds
"""
def wrapper(*args, **kwargs) -> float:
start = time.time()
func(*args, **kwargs)
total_time = ... | 68723a74c96c2d004eed9533f9023d77833c509b | 3,652,704 |
def merge_count(data1, data2):
"""Auxiliary method to merge the lengths."""
return data1 + data2 | 8c0280b043b7d21a411ac14d3571acc50327fdbc | 3,652,705 |
def orthogonal_procrustes(fixed, moving):
"""
Implements point based registration via the Orthogonal Procrustes method.
Based on Arun's method:
Least-Squares Fitting of two, 3-D Point Sets, Arun, 1987,
`10.1109/TPAMI.1987.4767965 <http://dx.doi.org/10.1109/TPAMI.1987.4767965>`_.
Also see ... | 5818c67e478ad9dd59ae5a1ba0c847d60234f222 | 3,652,706 |
def make_model(arch_params, patch_size):
""" Returns the model.
Used to select the model.
"""
return RDN(arch_params, patch_size) | 6cf91ea68bcf58d4aa143a606bd774761f37acb0 | 3,652,707 |
def calc_error(frame, gap, method_name):
"""Calculate the error between the ground truth and the GAP prediction"""
frame.single_point(method_name=method_name, n_cores=1)
pred = frame.copy()
pred.run_gap(gap=gap, n_cores=1)
error = np.abs(pred.energy - frame.energy)
logger.info(f'|E_GAP - E_0|... | 9a3eb0b115c394703cb7446852982fa1468607ad | 3,652,708 |
def find_model(sender, model_name):
"""
Register new model to ORM
"""
MC = get_mc()
model = MC.get((MC.c.model_name==model_name) & (MC.c.uuid!=''))
if model:
model_inst = model.get_instance()
orm.set_model(model_name, model_inst.table_name, appname=__name__, model_path='')
... | 4c78f135b502119fffb6b2ccf5f09335e739a97a | 3,652,709 |
def list_subtitles(videos, languages, pool_class=ProviderPool, **kwargs):
"""List subtitles.
The `videos` must pass the `languages` check of :func:`check_video`.
All other parameters are passed onwards to the provided `pool_class` constructor.
:param videos: videos to list subtitles for.
:type vi... | f5d9fa450f0df5c71c320d972e54c2502bbfd37d | 3,652,710 |
def public_incursion_no_expires(url, request):
""" Mock endpoint for incursion.
Public endpoint without cache
"""
return httmock.response(
status_code=200,
content=[
{
"type": "Incursion",
"state": "mobilizing",
"staging_solar_s... | 31d008b6479d8e2a5e4bc9f2d7b4af8cc4a40b03 | 3,652,711 |
def bad_topics():
""" Manage Inappropriate topics """
req = request.vars
view_info = {}
view_info['errors'] = []
tot_del = 0
if req.form_submitted:
for item in req:
if item[:9] == 'inapp_id_':
inapp_id = int(req[item])
db(db.zf_topic_inappropri... | 64c40b98a77c5934bd0593c9f5c4f31370980e8a | 3,652,712 |
def get_min_id_for_repo_mirror_config():
"""
Gets the minimum id for a repository mirroring.
"""
return RepoMirrorConfig.select(fn.Min(RepoMirrorConfig.id)).scalar() | 21a99988a1805f61ede9d689494b59b61c0391d8 | 3,652,713 |
def check_series(
Z,
enforce_univariate=False,
allow_empty=False,
allow_numpy=True,
enforce_index_type=None,
):
"""Validate input data.
Parameters
----------
Z : pd.Series, pd.DataFrame
Univariate or multivariate time series
enforce_univariate : bool, optional (default=F... | 5831c75953b8953ec54982712c1e4d3cccb22cc8 | 3,652,714 |
def B(s):
"""string to byte-string in
Python 2 (including old versions that don't support b"")
and Python 3"""
if type(s)==type(u""): return s.encode('utf-8') # Python 3
return s | b741bf4a64bd866283ca789745f373db360f4016 | 3,652,715 |
def gather_tiling_strategy(data, axis):
"""Custom tiling strategy for gather op"""
strategy = list()
base = 0
for priority_value, pos in enumerate(range(len(data.shape) - 1, axis, -1)):
priority_value = priority_value + base
strategy.append(ct_util.create_constraint_on_tensor(tensor=data... | afceb113c9b6c25f40f4f885ccaf08860427291f | 3,652,716 |
def redscreen(main_filename, back_filename):
"""
Implements the notion of "redscreening". That is,
the image in the main_filename has its "sufficiently"
red pixels replaced with pized from the corresponding x,y
location in the image in the file back_filename.
Returns the resulting "redscreened"... | 96824872ceb488497fbd56a662b8fb5098bf2341 | 3,652,718 |
def density_speed_conversion(N, frac_per_car=0.025, min_val=0.2):
"""
Fraction to multiply speed by if there are N nearby vehicles
"""
z = 1.0 - (frac_per_car * N)
# z = 1.0 - 0.04 * N
return max(z, min_val) | 95285a11be84df5ec1b6c16c5f24b3831b1c0348 | 3,652,719 |
def int_to_datetime(int_date, ds=None):
"""Convert integer date indices to datetimes."""
if ds is None:
return TIME_ZERO + int_date * np.timedelta64(1, 'D')
if not hasattr(ds, 'original_time'):
raise ValueError('Dataset with no original_time cannot be used to '
'convert ints to dateti... | 2e081ff019628800fb5c44eec4fa73333d755dde | 3,652,721 |
def show_plugin(name, path, user):
"""
Show a plugin in a wordpress install and check if it is installed
name
Wordpress plugin name
path
path to wordpress install location
user
user to run the command as
CLI Example:
.. code-block:: bash
salt '*' wordpre... | fded4735eda73dc19dd51dc13a1141345505b3b9 | 3,652,722 |
def get_receiver_type(rinex_fname):
"""
Return the receiver type (header line REC # / TYPE / VERS) found
in *rinex_fname*.
"""
with open(rinex_fname) as fid:
for line in fid:
if line.rstrip().endswith('END OF HEADER'):
break
elif line.rstrip().endswith... | 7391f7a100455b8ff5ab01790f62518a3c4a079b | 3,652,723 |
def is_cyclone_phrase(phrase):
"""Returns whether all the space-delimited words in phrases are cyclone words
A phrase is a cyclone phrase if and only if all of its component words are
cyclone words, so we first split the phrase into words using .split(), and then
check if all of the words are cyclone w... | 8014490ea2391b1acec1ba641ba89277065f2dd9 | 3,652,724 |
def wl_to_wavenumber(wl, angular=False):
"""Given wavelength in meters, convert to wavenumber in 1/cm. The wave
number represents the number of wavelengths in one cm. If angular is true,
will calculate angular wavenumber. """
if angular:
wnum = (2*np.pi)/(wl*100)
else:
wnu... | ca34e3abc5f9ed0d555c836819c9f3c8d3ab9e4b | 3,652,725 |
def easeOutCubic(n):
"""A cubic tween function that begins fast and then decelerates.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
"""
_checkRange(... | 20aea25b2ee937618df2b674178f2a767c373da7 | 3,652,726 |
import re
def _fix_entries(entries):
"""recursive function to collapse entries into correct format"""
cur_chapter_re, chapter_entry = None, None
new_entries = []
for entry in entries:
title, doxy_path, subentries = entry
if subentries is not None:
new_subentries = _fix_entr... | 1f8ac466533c17c1ad4e7cf2d27f2e7ff098ae79 | 3,652,728 |
def _check_bulk_delete(attempted_pairs, result):
"""
Checks if the RCv3 bulk delete command was successful.
"""
response, body = result
if response.code == 204: # All done!
return body
errors = []
non_members = pset()
for error in body["errors"]:
match = _SERVER_NOT_A_... | 2bf99d74a23d3522a2a53a711fbb2c8d43748eb1 | 3,652,729 |
def get_frontend_ui_base_url(config: "CFG") -> str:
"""
Return ui base url
"""
return as_url_folder(urljoin(get_root_frontend_url(config), FRONTEND_UI_SUBPATH)) | 4c34a1830431e28ec084853be6d93f1e487865a9 | 3,652,730 |
def read_image(name):
"""
Reads image into a training example. Might be good to threshold it.
"""
im = Image.open(name)
pix = im.load()
example = []
for x in range(16):
for y in range(16):
example.append(pix[x, y])
return example | be510bfee0a24e331d1b9bfb197b02edaafd0d70 | 3,652,731 |
def l3tc_underlay_lag_config_unconfig(config, dut1, dut2, po_name, members_dut1, members_dut2):
"""
:param config:
:param dut1:
:param dut2:
:param po_name:
:param members_dut1:
:param members_dut2:
:return:
"""
st.banner("{}Configuring LAG between Spine and Leaf node.".format('... | de4c8775b178380e5d9c90ee3c74082d6553d97f | 3,652,732 |
def _xrdcp_copyjob(wb, copy_job: CopyFile, xrd_cp_args: XrdCpArgs, printout: str = '') -> int:
"""xrdcp based task that process a copyfile and it's arguments"""
if not copy_job: return
overwrite = xrd_cp_args.overwrite
batch = xrd_cp_args.batch
sources = xrd_cp_args.sources
chunks = xrd_cp_args... | ce4475329a6f75d1819874492f26ceef7113a0f2 | 3,652,733 |
import logging
def merge_preclusters_ld(preclusters):
"""
Bundle together preclusters that share one LD snp
* [ Cluster ]
Returntype: [ Cluster ]
"""
clusters = list(preclusters)
for cluster in clusters:
chrom = cluster.gwas_snps[0].snp.chrom
start = min(gwas_snp.snp.pos for gwas_snp in cluster.gwas... | fd5409c1fc8463a2c795b2cc2685c1cf1a77f4ad | 3,652,734 |
def cross_recurrence_matrix( xps, yps ):
"""Cross reccurence matrix.
Args:
xps (numpy.array):
yps (numpy.array):
Returns:
numpy.array : A 2D numpy array.
"""
return recurrence_matrix( xps, yps ) | 017fa50fdd3c68e4bf1703635365d84c3508d0b3 | 3,652,735 |
import numpy
def define_panels(x, y, N=40):
"""
Discretizes the geometry into panels using 'cosine' method.
Parameters
----------
x: 1D array of floats
x-coordinate of the points defining the geometry.
y: 1D array of floats
y-coordinate of the points defining the geometry.... | e34ae13a7cdddc8be69e5cbba84b964bd11e6ec3 | 3,652,736 |
def compile_for_llvm(function_name, def_string, optimization_level=-1,
globals_dict=None):
"""Compiles function_name, defined in def_string to be run through LLVM.
Compiles and runs def_string in a temporary namespace, pulls the
function named 'function_name' out of that namespace, opt... | 61494afcde311e63138f75fb8bf59244d5c6d4e0 | 3,652,737 |
def setup_svm_classifier(training_data, y_training, testing_data, features, method="count", ngrams=(1,1)):
"""
Setup SVM classifier model using own implementation
Parameters
----------
training_data: Pandas dataframe
The dataframe containing the training data for the classifi... | 111937690db2c170852b57cdbfc3135c628ac26c | 3,652,738 |
def buildHeaderString(keys):
"""
Use authentication keys to build a literal header string that will be
passed to the API with every call.
"""
headers = {
# Request headers
'participant-key': keys["participantKey"],
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': keys["subscrip... | 4505fb679dec9727a62dd328f92f832ab45c417b | 3,652,739 |
from typing import List
from typing import cast
def build_goods_query(
good_ids: List[str], currency_id: str, is_searching_for_sellers: bool
) -> Query:
"""
Build buyer or seller search query.
Specifically, build the search query
- to look for sellers if the agent is a buyer, or
- to ... | 97cccadc265743d743f3e2e757e0c81ff110072b | 3,652,740 |
def make_piecewise_const(num_segments):
"""Makes a piecewise constant semi-sinusoid curve with num_segments segments."""
true_values = np.sin(np.arange(0, np.pi, step=0.001))
seg_idx = np.arange(true_values.shape[0]) // (true_values.shape[0] / num_segments)
return pd.Series(true_values).groupby(seg_idx)... | d6004488ae0109b730cb73dc9e58e65caaed8798 | 3,652,741 |
def convert_rational_from_float(number):
"""
converts a float to rational as form of a tuple.
"""
f = Fraction(str(number)) # str act as a round
return f.numerator, f.denominator | f3a00a150795b008ccc8667a3a0437eb2de2e2af | 3,652,742 |
def classname(obj):
"""Returns the name of an objects class"""
return obj.__class__.__name__ | 15b03c9ce341bd151187f03e8e95e6299e4756c3 | 3,652,743 |
def train(epoch, model, dataloader, optimizer, criterion, device, writer, cfg):
"""
training the model.
Args:
epoch (int): number of training steps.
model (class): model of training.
dataloader (dict): dict of dataset iterator. Keys are tasknames, values are correspon... | 41de6aa37b41c837d9921e673414a70cc798478b | 3,652,744 |
def custom_timeseries_widget_for_behavior(node, **kwargs):
"""Use a custom TimeSeries widget for behavior data"""
if node.name == 'Velocity':
return SeparateTracesPlotlyWidget(node)
else:
return show_timeseries(node) | 34b296ab98b0eb6f9e2ddd080d5919a0a7158adc | 3,652,745 |
def db_tween_factory(handler, registry):
"""A database tween, doing automatic session management."""
def db_tween(request):
response = None
try:
response = handler(request)
finally:
session = getattr(request, "_db_session", None)
if session is not Non... | 5e5150855db08931af8ba82e3f44e51b6caf54f3 | 3,652,746 |
import time
def calibrate_profiler(n, timer=time.time):
"""
Calibration routine to returns the fudge factor. The fudge factor
is the amount of time it takes to call and return from the
profiler handler. The profiler can't measure this time, so it
will be attributed to the user code unless it's s... | ee1f0af52f5530542503be4f277c90f249f83fb5 | 3,652,747 |
def getbias(x, bias):
"""Bias in Ken Perlin’s bias and gain functions."""
return x / ((1.0 / bias - 2.0) * (1.0 - x) + 1.0 + 1e-6) | 0bc551e660e133e0416f5e426e5c7c302ac3fbbe | 3,652,748 |
from typing import Dict
from typing import Optional
def get_exif_flash_fired(exif_data: Dict) -> Optional[bool]:
"""
Parses the "flash" value from exif do determine if it was fired.
Possible values:
+-------------------------------------------------------+------+----------+-------+
| ... | 82b4fc095d60426622202243f141614b9632340f | 3,652,749 |
import requests
import json
def get_geoJson(addr):
"""
Queries the Google Maps API for specified address, returns
a dict of the formatted address, the state/territory name, and
a float-ified version of the latitude and longitude.
"""
res = requests.get(queryurl.format(addr=addr, gmapkey=gmapke... | 500c2aa18c8b3b305c912b91efcc9f51121ca7b3 | 3,652,751 |
def display_data_in_new_tab(message, args, pipeline_data):
""" Displays the current message data in a new tab """
window = sublime.active_window()
tab = window.new_file()
tab.set_scratch(True)
edit_token = message['edit_token']
tab.insert(edit_token, 0, message['data'])
return tab | a64b7ac4138b921a53adb96b9933f1825048b955 | 3,652,752 |
def _cost( q,p, xt_measure, connec, params ) :
"""
Returns a total cost, sum of a small regularization term and the data attachment.
.. math ::
C(q_0, p_0) = .01 * H(q0,p0) + 1 * A(q_1, x_t)
Needless to say, the weights can be tuned according to the signal-to-noise ratio.
"""
s,r = params ... | 193d23a11d9704867d0a89846a6a7187de1e953a | 3,652,753 |
def get_full_lang_code(lang=None):
""" Get the full language code
Args:
lang (str, optional): A BCP-47 language code, or None for default
Returns:
str: A full language code, such as "en-us" or "de-de"
"""
if not lang:
lang = __active_lang
return lang or "en-us" | 1e0e49797dc5ed3f1fd148ac4ca1ca073231268c | 3,652,754 |
def acquire_images(cam, nodemap, nodemap_tldevice):
"""
This function acquires and saves 10 images from a device.
:param cam: Camera to acquire images from.
:param nodemap: Device nodemap.
:param nodemap_tldevice: Transport layer device nodemap.
:type cam: CameraPtr
:type nodemap: INodeMap
... | dd3454b3ddbff27dd73750c630ff5e63737fa50c | 3,652,755 |
import importlib
def apply_operations(source: dict, graph: BaseGraph) -> BaseGraph:
"""
Apply operations as defined in the YAML.
Parameters
----------
source: dict
The source from the YAML
graph: kgx.graph.base_graph.BaseGraph
The graph corresponding to the source
Returns... | d78410d27da574efc30d08555eaefde0c77cb513 | 3,652,756 |
def tt_logdotexp(A, b):
"""Construct a Theano graph for a numerically stable log-scale dot product.
The result is more or less equivalent to `tt.log(tt.exp(A).dot(tt.exp(b)))`
"""
A_bcast = A.dimshuffle(list(range(A.ndim)) + ["x"])
sqz = False
shape_b = ["x"] + list(range(b.ndim))
if len(... | f543557a0b24159ede7d8cc0c8ed5df3ed2123f4 | 3,652,757 |
def _check_like(val, _np_types, _native_types, check_str=None): # pylint: disable=too-many-return-statements
"""
Checks the follwing:
- if val is instance of _np_types or _native_types
- if val is a list or ndarray of _np_types or _native_types
- if val is a string or list of strings that can... | ab7875d329c09a491178b721c112b64142d2e566 | 3,652,758 |
def rotation_matrix(x, y, theta):
""" Calculate the rotation matrix. Origin is assumed to be (0, 0)
theta must be in radians
"""
return [np.cos(theta) * x - np.sin(theta) * y, np.sin(theta) * x + np.cos(theta) * y] | 53f646429f7a4b719b197cacbc71442ebef719d4 | 3,652,759 |
from typing import List
def create_players(num_human: int, num_random: int, smart_players: List[int]) \
-> List[Player]:
"""Return a new list of Player objects.
<num_human> is the number of human player, <num_random> is the number of
random players, and <smart_players> is a list of difficulty lev... | 10a7e840992417d46c79d794e66e1de5de16dd95 | 3,652,760 |
def extract_test_params(root):
"""VFT parameters, e.g. TEST_PATTERN, TEST_STRATEGY, ..."""
res = {}
'''
xpath = STATIC_TEST + '*'
elems = root.findall(xpath) + root.findall(xpath+'/FIXATION_CHECK*')
#return {e.tag:int(e.text) for e in elems if e.text.isdigit()}
print(xpath)
for e i... | ebd0e1d86af8d741ff993fc54b6ef4b3a7be6ac4 | 3,652,762 |
from typing import Optional
from typing import List
def csc_list(
city: str,
state: Optional[str] = None,
country: Optional[str] = None,
) -> List[db.Geoname]:
"""
>>> [g.country_code for g in csc_list('sydney')]
['AU', 'CA', 'US', 'US', 'ZA', 'VU', 'US', 'US', 'CA']
>>> [g.name for g in c... | 6c27a16c22a40d095bd3e3fad7660bbee867751e | 3,652,763 |
from typing import Iterable
from typing import Tuple
def calculate_frame_score(current_frame_hsv: Iterable[cupy.ndarray],
last_frame_hsv: Iterable[cupy.ndarray]) -> Tuple[float]:
"""Calculates score between two adjacent frames in the HSV colourspace. Frames should be
split, e.g. cv2.... | db5819ab0696364569f79f326ab7e28f0f0371b3 | 3,652,764 |
def huber_loss_function(sq_resi, k=1.345):
"""Robust loss function which penalises outliers, as detailed in Jankowski et al (2018).
Parameters
----------
sq_resi : `float` or `list`
A single or list of the squared residuals.
k : `float`, optional
A constant that defines at which dis... | bf8d5f3aa042297014b7b93316fe557784c4c5b1 | 3,652,765 |
import re
def clean_sentence(sentence: str) -> str:
"""
Bertに入れる前にtextに行う前処理
Args:
sentence (str): [description]
Returns:
str: [description]
"""
sentence = re.sub(r"<[^>]*?>", "", sentence) # タグ除外
sentence = mojimoji.zen_to_han(sentence, kana=False)
sentence = neolog... | bf5f9df5ab04ff96ae7f8199dfbeafae30d764eb | 3,652,766 |
from typing import Union
from enum import Enum
def assert_user(user_id: int, permission: Union[str, Enum] = None) -> bool:
"""
Assert that a user_id belongs to the requesting user, or that
the requesting user has a given permission.
"""
permission = (
permission.value if isinstance(permiss... | 6ef54d60a0b62e4ffb1330dba7bffeeac0df03c7 | 3,652,767 |
def single_prob(n, n0, psi, c=2):
"""
Eq. 1.3 in Conlisk et al. (2007), note that this implmentation is
only correct when the variable c = 2
Note: if psi = .5 this is the special HEAP case in which the
function no longer depends on n.
c = number of cells
"""
a = (1 - psi) / psi
F = (... | 05c0c627a05bb683fa3c20cacefa121f5cddba14 | 3,652,768 |
def array_pair_sum_iterative(arr, k):
"""
returns the array of pairs using an iterative method.
complexity: O(n^2)
"""
result = []
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] + arr[j] == k:
result.append([arr[i], arr[j]])
return... | c4f0eb5e290c784a8132472d85023662be291a71 | 3,652,769 |
def merge_named_payload(name_to_merge_op):
"""Merging dictionary payload by key.
name_to_merge_op is a dict mapping from field names to merge_ops.
Example:
If name_to_merge_op is
{
'f1': mergeop1,
'f2': mergeop2,
'f3': mergeop3
},
Then t... | ee20147b7937dff208da6ea0d025fe466d8e92ed | 3,652,770 |
def euclidean_distance(this_set, other_set, bsf_dist):
"""Calculate the Euclidean distance between 2 1-D arrays.
If the distance is larger than bsf_dist, then we end the calculation and return the bsf_dist.
Args:
this_set: ndarray
The array
other_set: ndarray
The com... | 7055c0de77cad987738c9b3ec89b0381002fbfd4 | 3,652,771 |
def host(provider: Provider) -> Host:
"""Create host"""
return provider.host_create(utils.random_string()) | 36e1b6f0ddf8edc055d56cac746271f5d3801111 | 3,652,773 |
def bj_struktur_p89(x, n: int = 5, **s): # brute force
"""_summary_
:param x: _description_
:type x: _type_
:param n: _description_, defaults to 5
:type n: int, optional
:return: _description_
:rtype: _type_
"""
gamma, K = gamma_K_function(**s)
b_j = np.empty((x.size, n + 1))
... | d21fc501411ada9f2173da7ca447418e2f51a86f | 3,652,774 |
def _get_pulse_width_and_area(tr, ipick, icross, max_pulse_duration=.08):
"""
Measure the width & area of the arrival pulse on the displacement trace
Start from the displacement peak index (=icross - location of first zero
crossing of velocity)
:param tr: displacement trace
:type tr: ob... | 43598f797f2956def740881b33b38d8824ba7ff3 | 3,652,775 |
def load_backend(name, options=None):
"""Load the named backend.
Returns the backend class registered for the name.
If you pass None as the name, this will load the default backend.
See the documenation for get_default() for more information.
Raises:
UnknownBackend: The name is not recogn... | 1df4c1b0c0d9d81e607a5884f3391883ab6ea3c5 | 3,652,776 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.