content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from pathlib import Path
def get_create_data_dir():
"""Get the data directory.
When the directory does not exist it is created.
"""
# Calculate the dataset data dir
data_dir = Path(get_data_dir()).expanduser()
dataset = _dataset_settings['name']
dataset_dir = data_dir / dataset
# Ens... | 8fd7631504ab7b926f1f6b533d0fdabaa8cad592 | 3,639,485 |
def interpolate_bezier(points, steps=100, **kwargs):
"""Generates an array of waypoints which lie on a 2D Bezier curve described by n (x, y) points. The trajectory is
guaranteed to include the start and end points though only on (x, y, z) axes.
The curve generated is of the nth degree, where n = len(points... | 403d8f6242947bc240920ea15ae6c0d72ec2d547 | 3,639,486 |
def _EAMS(track, Xmin=0.55, i0=12):
"""
Early-Age Main Sequence. Without this, the low-mass tracks do not
reach an EEP past the ZAMS before 15 Gyr.
"""
i_EAMS = _IorT_AMS(track, Xmin, i0)
return i_EAMS | 4cde6c1e598366bbaf25ab98d2ec14b9f5a34d86 | 3,639,487 |
def decode(tokenizer, token):
"""decodes the tokens to the answer with a given tokenizer"""
answer_tokens = tokenizer.convert_ids_to_tokens(
token, skip_special_tokens=True)
return tokenizer.convert_tokens_to_string(answer_tokens) | 4bbb58a6a0ed0d33411f9beee35ad0f2fb43698f | 3,639,489 |
def davis_jaccard_measure(fg_mask, gt_mask):
""" Compute region similarity as the Jaccard Index.
:param fg_mask: (ndarray): binary segmentation map.
:param gt_mask: (ndarray): binary annotation map.
:return: jaccard (float): region similarity
"""
gt_mask = gt_mask.astype(np.bool)
fg_mask =... | 96e6c47cd3b8d71206f9cf903b3827840803cf10 | 3,639,490 |
def extract_logits(logits = None, seq_pos = None):
"""
Args
logits: Tensor(batch_size,seq_length,vocab_size) e.g.(8,1024,50257)
seq_pos: list(batch_size)
Return:
output_logits: Tensor(batch_size,1,vocab_size) extract the Specified logit according to the seq_pos list .
"""
... | 008931ca8677461de947d7a365521e1e72c53866 | 3,639,491 |
def padRect(rect, padTop, padBottom, padLeft, padRight, bounds, clipExcess = True):
"""
Pads a rectangle by the specified values on each individual side,
ensuring the padded rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h).
"""
# Unpack th... | 032cafd373b59b725b8e2e28ba91e263ccae6e12 | 3,639,493 |
def gcs_csv_to_table(full_table_id: str, remote_csv_path: str) -> Table:
"""
Insert CSV from Google Storage to BigQuery Table.
:param full_table_id: Full ID of a Google BigQuery table.
:type full_table_id: str
:param remote_csv_path: Path to uploaded CSV.
:type remote_csv_path: str
:returns... | bb0713848249e2eb4e6b89db652152c6485af0ee | 3,639,494 |
import math
def turn_xyz_into_llh(x,y,z,system):
"""Convert 3D Cartesian x,y,z into Lat, Long and Height
See http://www.ordnancesurvey.co.uk/gps/docs/convertingcoordinates3D.pdf"""
a = abe_values[system][0]
b = abe_values[system][1]
e2 = abe_values[system][2]
p = math.sqrt(x*x + y*y)
long = math.atan(... | 304facd429083032e611f2f9aca09b298a40a48b | 3,639,496 |
def _TileGrad(op, grad):
"""Sum reduces grad along the tiled dimensions."""
input_shape = array_ops.shape(op.inputs[0])
# We interleave multiples and input_shape to get split_shape,
# reshape grad to split_shape, and reduce along all even
# dimensions (the tiled dimensions) to get the result
# with shape in... | 21294667ac3a31082cc2a3d09120330ce3ec1564 | 3,639,497 |
def obj_spatial_error_sum_and_naturalness_jac(s, data):
""" jacobian of error function. It is a combination of analytic solution
for motion primitive model and numerical solution for kinematic error
"""
# Extract relevant parameters from data tuple.
# Note other parameters are used for calli... | e0f57a88e3b490abc8eb9dbc636701c4a06ffc05 | 3,639,498 |
from datetime import datetime
def today():
"""Ritorna il giorno di oggi in formato YYYYMMDD"""
today = datetime.date.today()
return today.strftime("%Y%m%d") | fdf9c83153667fb3324f31893bf3721566dea4d3 | 3,639,499 |
from .common import OcrResult
def recognize(img, lang, *, hints=None):
"""
识别图像中的文本并返回 OcrResult
:param img: 需要识别的图像, PIL.Image.Image 对象
:param lang: 需要识别的语言,BCP-47 格式字符串
:param hints: 对 OCR 引擎的提示,OcrHint 中定义的值的列表
:returns: OcrResult
OcrResult = {
lines: Tuple[OcrLine],
e... | ea2ef038122b4953e49d787753ef112a6efe8c1c | 3,639,500 |
def check_missing_requirements ():
"""This list of missing requirements (mencoder, mplayer, lame, and mkvmerge).
Returns None if all requirements are in the execution path.
"""
missing = []
if which("mencoder") is None:
missing.append("mencoder")
if which("mplayer") is None:
miss... | 6351621a8a2ebfb52b06cb1f99fce0e02a263d08 | 3,639,501 |
def getExpMat(xy, shape, start, end, r, repeats=5):
"""
Get the expected interaction contact matrix.
xy is [[x,y]]
shape is () shape from the observed matrix.
r is resolution
"""
mat = []
i = 0
while i < repeats:
a = xy[:, 0]
b = xy[:, 1]
np.random.shuffle(a)
... | 1aefed157a961447a562f5ea214ea55cdf6340b8 | 3,639,502 |
from crds.tests import test_table_effects, tstmod
def main():
"""Run module tests, for now just doctests only."""
return tstmod(test_table_effects) | c8eaba2e58c8f3b75250e8ca250d123f11670635 | 3,639,504 |
def etminan(C, Cpi, F2x=3.71, scale_F2x=True):
"""Calculate the radiative forcing from CO2, CH4 and N2O.
This function uses the updated formulas of Etminan et al. (2016),
including the overlaps between CO2, methane and nitrous oxide.
Reference: Etminan et al, 2016, JGR, doi: 10.1002/2016GL071930
... | 8f80ecb153c94b806edbeffe3d384722333d2226 | 3,639,506 |
def render_manage_data_store_pages(request, html_file):
"""
Generate management pages for data_stores.
"""
# initialize session
session_maker = app.get_persistent_store_database('main_db',
as_sessionmaker=True)
session = session_maker()
... | ae73c2f1f88566f7a44992c1a8c5063cc099bf93 | 3,639,507 |
def validate_password_form(p1, p2, is_open, btn, sp1, sp2):
"""Validade password form
Returns
Output('password1', 'invalid'),
Output('password2', 'invalid'),
Output('password1', 'title'),
Output('password2', 'title'),
"""
invalid = {'p1':sp1, 'p2':sp2}
title = {'p1':N... | d94d577951dc11eafa10d3dbe1cf17ce32957e85 | 3,639,508 |
def cardinal_spline(points,tension=0.5):
"""Path instructions for a cardinal spline. The spline interpolates the control points.
Args:
points (list of 2-tuples): The control points for the cardinal spline.
tension (float, optional): Tension of the spline in the range [0,1]. Defaults to 0.5.
... | a549b5fcd8df2cb311563a495029901bc1edb1c1 | 3,639,509 |
def extract(x, *keys):
"""
Args:
x (dict or list): dict or list of dicts
Returns:
(tuple): tuple with the elements of the dict or the dicts of the list
"""
if isinstance(x, dict):
return tuple(x[k] for k in keys)
elif isinstance(x, list):
return tuple([xi[k] for ... | c0730556786586011b0b22ae5003c2fe9ccb2894 | 3,639,510 |
def get_source_config_from_ctx(_ctx,
group_name=None,
hostname=None,
host_config=None,
sources=None):
"""Generate a source config from CTX.
:param _ctx: Either a NodeInstance or a Relati... | 40b293ac9e63d96919b43cd60650e7d46ff34d57 | 3,639,511 |
def index(request):
"""Show welcome to the sorting quiz."""
template = loader.get_template("ggpoll/index.html")
context = {}
return HttpResponse(template.render(context, request)) | 68eb4afde5066f1a4a097f0d725ec682e803ace4 | 3,639,512 |
def get_all_random_experiment_histories_from_files(experiment_path_prefix, net_count):
""" Read history-arrays from all specified npz-files with net_number from zero to 'net_count' and return them as
one ExperimentHistories object. """
assert net_count > 0, f"'net_count' needs to be greater than 0, but is {... | fc36d2234025aea0e6232f15ac505adc489795c5 | 3,639,514 |
def convert_index_to_indices(index_ls, shape):
"""
将 index_ls 格式的坐标列表转换为 indices_ls 格式
"""
assert index_ls.size <= np.prod(shape)
source = np.zeros(shape=shape)
zip_indices = np.where(source >= 0)
indices_ls = convert.zip_type_to_indices(zip_indices=zip_indices)
indices_ls = indices... | 3f1861820f81d27b7a6b0878bc768dca84fd6b3b | 3,639,516 |
def _gen_off_list(sindx):
"""
Given a starting index and size, return a list of numbered
links in that range.
"""
def _gen_link_olist(osize):
return list(range(sindx, sindx + osize))
return _gen_link_olist | 863ccdc08f6a7cadccc3c5ccfd0cb92a223aadda | 3,639,518 |
def report_operation_log_list(request):
"""
返回常规操作的日志列表
:param request:
:return:
"""
return administrator.report_operation_log_list(request) | c2bbeda9a3342e9ce9667f9ec6f232f171a164e0 | 3,639,519 |
def connect_redis(redis_host, redis_port, redis_db):
""" connect to redis """
global _conn
if _conn is None:
print "connect redis %s (%s)" % ("%s:%s" % (redis_host, redis_port),
os.getpid())
_conn = redis.Redis(host=redis_host, port=redis_port,
db=redis_db)
... | 0b3f51fcbe78e7d8075398675b62ae95f56f06b6 | 3,639,520 |
def loadSV(fname, shape=None, titles=None, aligned=False, byteorder=None,
renamer=None, **kwargs):
"""
Load a delimited text file to a numpy record array.
Basically, this function calls loadSVcols and combines columns returned by
that function into a numpy ndarray with stuctured dtype. A... | 94ac8943ff50273162066db53040107406f27059 | 3,639,522 |
def rationalize_quotes_from_table(table, rationalizeBase=10000):
"""
Retrieve the data from the given table of the SQLite database
It takes parameters:
table (this is one of the Quote table models: Open, High, Low, or Close)
It returns a tuple of lists
"""
first_row = table.select().limit(... | ee1c8310c12e7e53e9ca2677dd61d7d2525603fd | 3,639,523 |
def k(func):
"""定义一个装饰器函数"""
def m(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return m | 3cc958033fd66547e523882435494f27ae81b096 | 3,639,524 |
import requests
def get_playlist_object(playlist_url, access_token):
"""
playlist_url : url of spotify playlist
access_token : access token gotten from client credentials authorization
return object containing playlist tracks
"""
playlist_id = playlist_url.split("/")[-1]
playlist_endp... | 8c7ed1a1b9574e2e0870d3091452accf5909f982 | 3,639,525 |
from typing import Tuple
def guess_identifiers(fuzzy_base_name: str) -> Tuple[str, str]:
"""
Given a fuzzy base name, guess the corresponding (item ID, base name)
identifier pair.
:param fuzzy_base_name: The base name to be matched.
:return: The identifier pair with the closest matching base name... | 6ac609268a92c16408eb414d7944cbd09fedfcc5 | 3,639,526 |
def make_image(center=(.1,-.4),dpi=500,X_cut_min = -.59 -xcut_offset,Y_cut_max = 1.61
+ ycut_offset,X_cut_max = .12-xcut_offset,Y_cut_min = .00 +ycut_offset,bands=23 ):
"""make visual count it by area then have hist values for normalization wih movement data
to be exported and then can be cou... | a90a92318b30e5e4069dc415d5a4693d844b8c18 | 3,639,527 |
def read_answer_patterns(pattern_file_path):
"""load answer patterns into qid2patterns dictionary
"""
qid2patterns = {}
last_qid = None
with open(pattern_file_path) as f:
for line in f :
qid, pattern = line.strip().split("\t")
if qid != last_qid : # start collectin... | da8f018deb15088b359044f22cfa71f0b8305af7 | 3,639,528 |
def fitness(coords, solution):
"""
Total distance of the current solution path.
"""
N = len(coords)
cur_fit = 0
for i in range(N):
cur_fit += dist(coords[solution[i % N]], coords[solution[(i + 1) % N]])
return cur_fit | 716dee705be75bbf6f64ec55b39187ab567edfa0 | 3,639,529 |
import numpy as np
def f_of_sigma(sigma,A=0.186,a=1.47,b=2.57,c=1.19):
"""
The prefactor in the mass function parametrized
as in Tinker et al 2008. The default values
of the optional parameters correspond to a mean
halo density of 200 times the background. The
values can be found in table 2 of... | 89abe82df8a4384e74eb556172c9d46193b731da | 3,639,530 |
from typing import Sequence
import time
def create_role(
role_name: str,
base_session: boto3.Session,
region: str,
auto_trust_caller_identity=True,
allowed_services: Sequence[str] = [],
allowed_aws_entities: Sequence[str] = [],
external_id: str = None,
):
"""
Creates a role that le... | 7fe2043235f3391af96c0767fa7e79f2ef9d8ce3 | 3,639,531 |
def get_auto_switch_state(conn):
"""Get the current auto switch enabled / disabled state"""
packet = _request(conn, GET_AUTO_SWITCH_STATE)
if not _validate_packet(packet):
raise ChecksumError()
return _decode_toggle(packet) | f87f838bafb03e9d9fbea6e9a6285ede56dbb09d | 3,639,532 |
def SGD(X, y, lmd, gradient, n_epochs, M, opt = "SGD", eta0 = None, eta_type = 'schedule', t0=5, t1=50, momentum = 0., rho = 0.9, b1 = 0.9, b2 = 0.999):
"""Stochastic Gradient Descent Algorithm
Args:
- X (array): design matrix (training data)
- y (array): output dataset (training data)
... | 916edb97d98757b6f18092a3c83622fb982ddfcb | 3,639,533 |
def get_last_oplog_entry(client):
"""
gets most recent oplog entry from the given pymongo.MongoClient
"""
oplog = client['local']['oplog.rs']
cursor = oplog.find().sort('$natural', pymongo.DESCENDING).limit(1)
docs = [doc for doc in cursor]
if not docs:
raise ValueError("oplog has no... | 069497ffd6eb0354c00858695d065695c617b5e6 | 3,639,534 |
import math
def schmidt_quasi_norm(size):
"""
Returns an array of the Schmidt Quasi-normalised values
Array is symmetrical about the diagonal
"""
schmidt = square_array(size)
for n in range(size):
for m in range(n + 1):
if n == 0:
double = 1
else... | b71b6a7733eb2b88f107ca904cf570c8f5841263 | 3,639,535 |
def _merge_jamos(initial, medial, final=None):
"""Merge Jamos into Hangul syllable.
Raises:
AssertionError: If ``initial``, ``medial``, and ``final`` are not in
``INITIAL``, ``MEDIAL``, and ``FINAL`` respectively.
"""
assert initial in INITIALS
assert medial in MEDIALS
final = "∅" if final is Non... | 9ff0e53d8decfc3db74d319fd366595bcac18e5c | 3,639,536 |
def get_feature_set(eq, features):
"""Get features from their strings
Arguments:
eq {Equity} -- equity to build around
features {string array} -- features and params to use
Returns:
list -- list of ndarray of floats
"""
feature_set = []
for feature in features:
... | 78b4ad05b98ec776e7f07f16736739c909ce1e64 | 3,639,537 |
from typing import Optional
def class_http_endpoint(methods: METHODS, rule_string: str, side_effect: Optional[HTTP_SIDE_EFFECT] = None, **kwargs):
"""
Creates an HTTP endpoint template. Declare this as a class variable in your webserver subclass to automatically add
the endpoint to all instances. Can be ... | 62449e088ff66080a7165497d6f2434971818f62 | 3,639,538 |
def value(iterable, key=None, position=1):
"""Generic value getter. Returns containing value."""
if key is None:
if hasattr(iterable, '__iter__'):
return iterable[position]
else:
return iterable
else:
return iterable[key] | df49496ab8fa4108d0c3d04035ffa318a9c6a035 | 3,639,539 |
def find_aa_seqs(
aa_seq: str,
var_sites: str,
n_flanking: int = 7
):
"""Grabs the flanking AA sequence around a given location in a protein sequence string.
Args:
aa_seq: Protein sequence string.
var_sites: Integer location of the site of interest (1-indexed, not 0-inde... | f6b75215347eb829d2b023138abeff3a44ab1d36 | 3,639,540 |
def compact_interval_string(value_list):
"""Compact a list of integers into a comma-separated string of intervals.
Args:
value_list: A list of sortable integers such as a list of numbers
Returns:
A compact string representation, such as "1-5,8,12-15"
"""
if not value_list:
return ''
value_li... | b479b45dc68a0bce9628a19be17185437f3edca6 | 3,639,542 |
def _mk_asm() -> str:
"""
Generate assembly to program all allocated translation tables.
"""
string = ""
for n,t in enumerate(table.Table._allocated):
string += _mk_table(n, t)
keys = sorted(list(t.entries.keys()))
while keys:
idx = keys[0]
entry = t.e... | a1e6725b20877c10a400d8f13890e914adf8024b | 3,639,543 |
def getNuitkaModules():
""" Create a list of all modules known to Nuitka.
Notes:
This will be executed at most once: on the first time when a module
is encountered and cannot be found in the recorded calls (JSON array).
Returns:
List of all modules.
"""
mlist = []
for m ... | 7596c18f2b38883f1f8c3201597b57fc6096752b | 3,639,544 |
def run_model(network):
"""
Runs a model with pre-defined values.
"""
model = network(vocab_size+1, EMBEDDING_SIZE)
model.cuda()
EPOCHS = 20
train_model(model, train, epochs=EPOCHS, echo=False)
return model | a10980b6f8dd5ff9e048b07ee64215187acb8467 | 3,639,545 |
def is_prime(num):
""" Assumes num > 3 """
if num % 2 == 0:
return False
for p in range(3, int(num**0.5)+1, 2): # Jumps of 2 to skip odd numbers
if num % p == 0:
return False
return True | e898026d0362967400cfee4e70a74ac02a64b6f1 | 3,639,546 |
def verify_password(email_or_token, password):
"""
电子邮件和密码是由User模型中现有的方法验证,如果登录密令正确,这个验证回调函数就返回True;
验证回调函数把通过认证的用户保存在Flask的全局对象g中,如此一来,视图函数便能进行访问。
注意:匿名登录时,这个函数返回True并把Flask-login提供的AnonymousUser类实例赋值给g.current_user
:param email:
:param password:
:return:
"""
if email_or_token == ''... | 09890ad0ae33f7e700148b56098df6e3ecc69d39 | 3,639,547 |
def is_valid_orcid_id(orcid_id: str):
"""adapted from stdnum.iso7064.mod_11_2.checksum()"""
check = 0
for n in orcid_id:
check = (2 * check + int(10 if n == "X" else n)) % 11
return check == 1 | 5866e4465a24f46aa4c7015902eac53684da7b04 | 3,639,548 |
def extract_entity(entities, entity_type=_PERSON):
"""
Extract name from the entity specified in entity_type.
We use the JSON format to extract the entity information:
-
:param entities:
:param entity_type:
:return:
"""
if not entity_type:
raise ValueError('Invalid entit... | c357c0cc5d4365ea59f1b852b5e800fe513dfe3c | 3,639,549 |
def reconstruct_from_patches(img_arr, org_img_size, stride=None, size=None):
"""[summary]
Args:
img_arr (numpy.ndarray): [description]
org_img_size (tuple): [description]
stride ([type], optional): [description]. Defaults to None.
size ([type], optional): [description]. Defa... | 1ad80afd7d4f09de1ece4e8ba74844477d2d99be | 3,639,551 |
import requests
def process_highlight(entry, img_width):
"""
Function processing highlights extracted from DOM tree. Downloads image based
on its url and scales it. Prettifies text by inserting newlines and
shortening author lists.
Parameters
----------
entry : dict of str
Dictio... | 6a09cb87971725fa3df9eb8e6e98cee315701af4 | 3,639,552 |
from geometry_msgs.msg import Pose, Point, Quaternion
def SE3ToROSPose(oMg):
"""Converts SE3 matrix to ROS geometry_msgs/Pose format"""
xyz_quat = pin.SE3ToXYZQUATtuple(oMg)
return Pose(position=Point(*xyz_quat[:3]), orientation=Quaternion(*xyz_quat[3:])) | ebf806bd52a4b60252a2001fe2de8122bd7cd201 | 3,639,554 |
def calib_graph_to_infer_graph(calibration_graph_def, is_dynamic_op=False):
"""Convert an existing calibration graph to inference graph.
Args:
calibration_graph_def: the calibration GraphDef object with calibration data
is_dynamic_op: whether to create dynamic static engines from calibration
Returns:
... | a29b556775aff27eed8dad404c3684e452e88c86 | 3,639,555 |
def calc_minimum_angular_variance_1d(var_r, phi_c, var_q):
"""Calculate minimum possible angular variance of a beam achievable with a correction lens.
Args:
var_r (scalar): real space variance.
phi_c (scalar): real-space curvature - see above.
var_q (scalar): angular variance of the bea... | c5e2144f44b532acbf8eb9dfb83c991af3756abf | 3,639,556 |
def grid_subsampling(points, features=None, labels=None, ins_labels=None, sampleDl=0.1, verbose=0):
"""
CPP wrapper for a grid subsampling (method = barycenter for points and features)
:param points: (N, 3) matrix of input points
:param features: optional (N, d) matrix of features (floating number)
... | 3aebd24307307344c0ff804b3ee189ff4da98f0d | 3,639,557 |
def delete_all_collections_from_collection(collection, api_key=None):
"""
Delete *ALL* Collections from a Collection.
:param collection: The Collection to remove *all* Collections from.
:type collection: str
:param api_key: The API key to authorize request against.
:type api_key: str
:retur... | 1a039c850f1bbf82f0c6683081874e1971c40255 | 3,639,558 |
import torch
def generate_kbit_random_tensor(size, bitlength=None, **kwargs):
"""Helper function to generate a random k-bit number"""
if bitlength is None:
bitlength = torch.iinfo(torch.long).bits
if bitlength == 64:
return generate_random_ring_element(size, **kwargs)
rand_tensor = tor... | c87fc7f353b15a4dd4b6d980cf2e365f6ac6a4bc | 3,639,559 |
import pickle
def cache_by_sha(func):
""" only downloads fresh file, if we don't have one or we do and the sha has changed """
@wraps(func)
def cached_func(*args, **kwargs):
cache = {}
list_item = args[1]
dest_dir = kwargs.get('dest_dir')
path_to_file = list_item.get('path'... | d95010ba433c9b9f27dcb2f3fe05d3b609cee3fb | 3,639,561 |
def rewrite_by_assertion(tm):
"""
Rewrite the tm by assertions. Currently we only rewrite the absolute boolean variables.
"""
global atoms
pt = refl(tm)
# boolvars = [v for v in tm.get_vars()] + [v for v in tm.get_consts()]
return pt.on_rhs(*[top_conv(replace_conv(v)) for _, v in atoms.items... | 51eb546b9b0414091152d018aac6a6eaf2149d39 | 3,639,562 |
import json
def hash_cp_stat(fdpath, follow_symlinks=False, hash_function=hash):
""" Returns hash of file stat that can be used for shallow comparision
default python hash function is used which returns a integer. This
can be used to quickly compare files, for comparing directories
see hash_walk().
... | c16e2f00fb278d69e9307b8d528a7807d7c404d6 | 3,639,563 |
def multi_label_head(n_classes,
label_name=None,
weight_column_name=None,
enable_centered_bias=False,
head_name=None,
thresholds=None,
metric_class_ids=None,
loss_fn=None):
... | b1820584de6c4f9f987100c313793f41de0b73fc | 3,639,564 |
def render_macros(line, macros):
"""Given a line of non-preprocessed code, and a list of macros, process macro expansions until done.
NOTE: Ignore comments"""
if line.startswith(";"):
return line
else:
while [macro_name for macro_name in macros.keys() if macro_name in line]:
... | b78892d5708e9ca2d7e596d4f92ca7e8a6d17a64 | 3,639,565 |
def calc_qpos(x, bit = 16):
"""
引数の数値を表現できる最大のQ位置を返す。
:param x: float
:return: int
"""
for q in range(bit):
maxv = (2 ** (q - 1)) - 1
if x > maxv:
continue
return bit - q
return bit | b85b458989425bc5698547cae93d8729bd452e76 | 3,639,567 |
def person(request):
"""
Display information on the specified borrower (person)
"""
title = "Find a person"
if 'person_id' in request.GET:
person_id = request.GET['person_id']
try:
person = Person.objects.get(id_number=person_id)
title = unicode(person)
... | 53550d5ebefc6fb36601049f86c227b073d715d5 | 3,639,569 |
def _follow_word_from_node(node, word):
"""Follows the link with given word label from given node.
If there is a link from ``node`` with the label ``word``, returns the end
node and the log probabilities and transition IDs of the link. If there are
null links in between, returns the sum of the log prob... | a21a20ee4ad2d2e90420e30572d41647b3938f4b | 3,639,570 |
def normalize_code(code):
"""Normalize object codes to avoid duplicates."""
return slugify(code, allow_unicode=False).upper() if code else None | 27f3b079c4fb5cc9d87e310282838f77c4aed981 | 3,639,571 |
def get_weights_for_all(misfit_windows, stations, snr_threshold, cc_threshold, deltat_threshold, calculate_basic, print_info=True):
"""
get_weights_for_all: calculate weights.
"""
weights_for_all = {}
# * firstly we update the weight of snr,cc,deltat
for net_sta in misfit_windows:
weigh... | 0f64a968d00391ab18e2e91f2453b1ecc6a2a426 | 3,639,572 |
def tree_feature_importance(tree_model, X_train):
"""
Takes in a tree model and a df of training data and prints out
a ranking of the most important features and a bar graph of the values
Parameters
----------
tree_model: the trained model instance. Must have feature_importances_ and estima... | 4c347a7bad8d541c3166942f51efa6f18882bde5 | 3,639,573 |
def chhop_microseconds(delta: timedelta) -> timedelta:
"""
chop microseconds from timedelta object.
:param delta:
:return:
"""
return delta - timedelta(microseconds=delta.microseconds) | fac46d727540f607164029d23324e678a276b296 | 3,639,574 |
def __renumber(dictionary) :
"""Renumber the values of the dictionary from 0 to n
"""
count = 0
ret = dictionary.copy()
new_values = dict([])
for key in dictionary.keys() :
value = dictionary[key]
new_value = new_values.get(value, -1)
if new_value == -1 :
new_values[value] = count
new_value = count
... | a4611f04360b2c03ac17f22e349371f58f65ed9b | 3,639,575 |
def get_user_list():
"""
return user list if the given
authenticated user has admin permission
:return:
"""
if requires_perm() is True:
return jsonify({'user_list': USER_LIST,
'successful': True}), 200
return jsonify({'message': 'You are not '
... | 38598ed7d54dd4d93a8b22c6344f22736bc3b805 | 3,639,576 |
def rm_words(user_input, stop_words):
"""Sanitize using intersection and list.remove()"""
# Downsides:
# - Looping over list while removing from it?
# http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python
stop_words = set(stop_words)
for sw in stop_... | aead9c1cd5586bb20611ea8fbf57aa66aa3f5ede | 3,639,577 |
import struct
def getValueForCoordinate(inputFile, lon, lat, noDataAsNone):
"""
Reads the pixel value of a GeoTIFF for a geographic coordinate
:param inputFile: full path to input GeoTIFF file
:type inputFile: str
:param lon: longitude
:type lon: float
:param lat: latitude
:type lat: ... | 4bfe9bf3de3dc277a84dad9e1fa523b2213b9b6d | 3,639,578 |
def convert_xrandr_to_index(xrandr_val: float):
"""
:param xrandr_val: usually comes from the
config value directly, as a string (it's
just the nature of directly retrieving
information from a .ini file)
:return: an index representation
of the current brightness level, useful
for switch... | eed5f7a6c79f7dcb29c627521d31dc59e5cd430b | 3,639,579 |
def get_message(name, value):
"""Provides the message for a standard Python exception"""
if hasattr(value, "msg"):
return f"{name}: {value.msg}\n"
return f"{name}: {value}\n" | 7755c63cc9a16e70ad9b0196d662ef603d82b5f6 | 3,639,580 |
import math
def calculate_page_info(offset, total_students):
"""
Takes care of sanitizing the offset of current page also calculates offsets for next and previous page
and information like total number of pages and current page number.
:param offset: offset for database query
:return: tuple consi... | e9af8bd4f511f42f30f60685d68fb043a54668de | 3,639,581 |
def download_office(load=True): # pragma: no cover
"""Download office dataset.
Parameters
----------
load : bool, optional
Load the dataset after downloading it when ``True``. Set this
to ``False`` and only the filename will be returned.
Returns
-------
pyvista.Structured... | 5dd307bf815e7d7cbaef81b7542728b446b7f2cb | 3,639,584 |
import time
def test_duplicated_topics(host):
"""
Check if can remove topics options
"""
# Given
duplicated_topic_name = get_topic_name()
def get_topic_config():
topic_configuration = topic_defaut_configuration.copy()
topic_configuration.update({
'name': duplicated... | 68524bf675da4b52f05ee31ae35def7b461572cd | 3,639,585 |
def register(request):
"""
注册账号界面
"""
message = ""
if request.session.get('is_login', None):
return redirect('/account/')
if request.method == 'POST':
username = request.POST.get('username')
email = request.POST.get('email')
password1 = request.POST.get('password... | 2a3963f6549cd20f4d994cbab336f0e0eb91e685 | 3,639,586 |
def cosh(x):
"""Evaluates the hyperbolic cos of an interval"""
np = import_module('numpy')
if isinstance(x, (int, float)):
return interval(np.cosh(x), np.cosh(x))
elif isinstance(x, interval):
#both signs
if x.start < 0 and x.end > 0:
end = max(np.cosh(x.start), np.co... | dd362392cce1aae2d19c589d49559b7b165c9f1e | 3,639,587 |
def tree_intersection(tree_one, tree_two):
"""Checks for duplicate values between two trees and returns those values as a set."""
first_values = []
second_values = []
table = HashTable()
dupes = set([])
tree_one.pre_order(first_values.append)
tree_two.pre_order(second_values.append)
fo... | 06ab08015cb02747fd3fea4055217a1dbeefc4b8 | 3,639,588 |
def new():
"""Deliver new-question interface."""
return render_template('questionNew.html', question_id='') | bca210aa5661d034256c6ef06209f45ea4923aa9 | 3,639,589 |
def merge_dict_recursive(base, other):
"""Merges the *other* dict into the *base* dict. If any value in other is itself a dict and the base also has a dict for the same key, merge these sub-dicts (and so on, recursively).
>>> base = {'a': 1, 'b': {'c': 3}}
>>> other = {'x': 4, 'b': {'y': 5}}
>>> want =... | 10ea2bbcf7d2ee330c784efff684974339d48b5d | 3,639,590 |
def two_points_line(feature):
"""Convert a Polyline to a Line composed of only two points."""
features = []
coords = feature['geometry']['coordinates']
for i in range(0, len(coords) - 1):
segment_coords = [coords[i], coords[i+1]]
geom = geojson.LineString(segment_coords)
features... | 49c0197c6a072c690a2507df4b9a517a95c9919e | 3,639,591 |
def transform_world_to_camera(poses_set, cams, ncams=4):
"""
Project 3d poses from world coordinate to camera coordinate system
Args
poses_set: dictionary with 3d poses
cams: dictionary with cameras
ncams: number of cameras per subject
Return:
t3d_camera: dictionary with 3d poses... | c67c61e7746fd67ca62a848b3641e27e068348a5 | 3,639,592 |
def div66():
"""
Returns the divider OOOOOOOOOOOO
:return: divider66
"""
return divider66 | fbade8a4b3aa445985686c180f3cbad71832498f | 3,639,594 |
def extract_square_from_file(image_number=1):
"""Given a number of the image file return a cropped sudoku."""
image_string = '/home/james/Documents/projects/sudoku/img/'
image_string += str(image_number) + '.jpg'
binary = read_binary(image_string)
threshold = get_threshold(binary)
square = get_... | def244273d2e329b771a61b5fb4fb980e120831d | 3,639,595 |
def sequence_extractor(graph, path):
"""
returns the sequence of the path
:param graph: a graph object
:param path: a list of nodes ordered according to the path
:return: sequence of the path
"""
# check if path exists
if len(path) == 1:
return graph.nodes[path[0]].seq
eli... | 1f83fcbf75add7234f9395e801d22d95d55804a9 | 3,639,597 |
from typing import Optional
from typing import List
from typing import Union
from typing import Literal
from typing import Tuple
from typing import Dict
def plot_matplotlib(
tree: CassiopeiaTree,
depth_key: Optional[str] = None,
meta_data: Optional[List[str]] = None,
allele_table: Optional[pd.DataFram... | a26a8146f4f5fb3bc3564367774740645e04caf3 | 3,639,598 |
import jinja2
from datetime import datetime
import time
import hashlib
def print_order(order: Order, user_id: int = 0):
"""
订单打印
:param order:
:param user_id:
:return:
"""
shop_id = order.shop.id
shop = get_shop_by_shop_id(shop_id)
receipt_config = get_receipt_by_shop_id(shop_id)
... | bdfdbe51b854093172f2ab2c4b9d1abd15856847 | 3,639,599 |
def get_IoU_from_matches(match_pred2gt, matched_classes, ovelaps):
"""
if given an image, claculate the IoU of the segments in the image
:param match_pred2gt: maps index of predicted segment to index of ground truth segment
:param matched_classes: maps index of predicted segment to class number
:par... | 2488c590d86a639898fc1e84c6a6d24afb7c2df4 | 3,639,600 |
def id_queue(obs_list, prediction_url='http://plants.deep.ifca.es/api', shuffle=False):
"""
Returns generator of identifications via buffer.
Therefore we perform the identification query for the nxt observation
while the user is still observing the current information.
"""
print "Generating the ... | 37773fc9d688b000a1d02b083f89e0b4996a52ea | 3,639,601 |
def periodogram(x, nfft=None, fs=1):
"""Compute the periodogram of the given signal, with the given fft size.
Parameters
----------
x : array-like
input signal
nfft : int
size of the fft to compute the periodogram. If None (default), the
length of the signal is used. if nfft... | 899cacc316cf80e79871d01b0c0b3a84deda8042 | 3,639,602 |
def handle_429(e):
"""Renders full error page for too many site queries"""
html = render.html("429")
client_addr = get_ipaddr()
count_ratelimit.labels(e, client_addr).inc()
logger.error(f"Error: {e}, Source: {client_addr}")
return html, 429 | b7a27e55f753dc254e19d1b51ddb169c8e683a2c | 3,639,603 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.