content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from pathlib import Path
def directory_size_bytes(dir_path):
"""Return the size of the directory's contents in bytes."""
dir_path = Path(dir_path)
if not dir_path.is_dir():
raise QgrRuntimeError(f'`dir_path` must be a directory. Got {dir_path}')
contents = dir_path.glob('**/*')
total_size... | d5ef21a98e60e03d3cc3a3635b80749a818f7ab8 | 61,300 |
def gf_factor(f, p, K, **args):
"""Factor (non square-free) polynomials in `GF(p)[x]`.
Given a possibly non square-free polynomial `f` in `GF(p)[x]`, returns
its complete factorization into irreducibles::
f_1(x)**e_1 f_2(x)**e_2 ... f_d(x)**e_d
where each `f_i` is a moni... | 0d411ad75fd4ec1e58b92da13881b9557e26db03 | 61,301 |
def get_first_attachment(email):
"""Return the file path of the first attachment from an email.
Parameters
----------
email : Message
An email |Message| object.
Returns
-------
|str| or |None|
The file path to the first attachment in the email, if one
exists and is ... | b066a7ebe660f7b6bd8f91a8fa9aa958dcae135b | 61,302 |
def instance2xml_base(anno, bbox_type='xyxy'):
"""bbox_type: xyxy (xmin, ymin, xmax, ymax); xywh (xmin, ymin, width, height)"""
assert bbox_type in ['xyxy', 'xywh']
E = objectify.ElementMaker(annotate=False)
anno_tree = E.annotation(
E.folder('VOC2014_instance/person'),
E.filename(anno['... | a739b4a4ce61db319a625625b2a412a3f3fcbbe2 | 61,303 |
import json
def _dump_user_paths(user, paths, **kwargs):
"""Helper function for dumping a user paths file. Returns whether or
not the dump occured successfully.
"""
if 'raise_errors' not in kwargs:
kwargs['raise_errors'] = False
user_path_file = _user_path_file(user)
with flock(user_pa... | fc7b17f952af6c173fcf42eef1b1855f58a22347 | 61,304 |
def get_reading_type(meter_id, quantity_id, start_date, end_date, my_cursor):
"""
Return the reading type for meter METER_ID with quantity id QUANTITY_ID
between START_DATE and END_DATE (Totalization, Interval) or NONE if an error
occurs. Uses cursor MY_CURSOR.
"""
monotonic_sql = """
SE... | c7be18e960cad51a759380e3084622debaa469a5 | 61,305 |
def concept_uri(lang, text, *more):
"""
`concept_uri` builds a representation of a concept, which is a word or
phrase of a particular language, which can participate in relations with
other concepts, and may be linked to concepts in other languages.
Every concept has an ISO language code and a text... | 4c9ff7c10b6ddb86a782ca1b878f63db6601d165 | 61,306 |
def baby_names_collapsed_from_list(a_baby_names_list):
"""
a_baby_names_list is a list of lists, each element [name, rank]
Collapse list element to a string
"""
print('baby_names_collapsed_from_list')
baby_names_collapsed = []
for baby_element in a_baby_names_list:
baby_names_collap... | f874c1fb205e0a86e46db8a3e2c0002712db82cb | 61,307 |
from typing import Union
def deserialize_timestamp(timestamp: Union[int, str, FVal]) -> Timestamp:
"""Deserializes a timestamp from a json entry. Given entry can either be a
string or an int.
Can throw DeserializationError if the data is not as expected
"""
if timestamp is None:
raise Des... | 7a787164a4a6f4730fea9b23d8ce341d1d1aae46 | 61,308 |
def exp_lr_scheduler(optimizer,init_lr,epoch,lr_decay=2):
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
lr = init_lr * (0.1**(epoch // lr_decay))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return optimizer | c18885263fab2b6cab39a2147465f3f71f9514a0 | 61,309 |
import copy
def check_output(output, expected_output):
"""
Return True if output and expected_output
contains the same lists, False otherwise.
Note that the ordering of the list is not important.
Examples:
check_output([ [0, 1], [1, 0] ] ], [ [1, 0], [0, 1] ]) returns True
Args:
... | c09a9aaa2fb226318e2d0a71f3da08d5772a9a8d | 61,310 |
from typing import Sequence
import torch
def pretty_print_double(contents1: dict, contents2: dict, args):
""" Prints a nice summary of the top-level contens in a checkpoint dictionary. """
col_size = max(max(len(str(k)) for k in contents1), max(len(str(k)) for k in contents2))
common_keys = list(contents1... | 795a902f7ffcd48338b48c57c0e708f3b255e12f | 61,311 |
def HeadingStr(heading):
"""
Gives a heading string given the heading float
"""
headstr = "?"
if heading != None:
if heading < 22.5 or heading >= 337.5:
headstr = "N"
elif heading >=22.5 and heading < 67.5:
headstr = "NE"
elif heading >= 67.5 and heading < 112.5:
headstr = "E"
elif heading >= 112.... | 1f1276e3f8f9c963703ced42d9391d1ee0598e3e | 61,312 |
def test_then_compute_adds_computation_result_to_behaviour(result_ready_behaviour_builder, behaviour):
"""
:type result_ready_behaviour_builder: BehaviourBuilder
:type behaviour: Behaviour
"""
def function(*args, **kwargs):
return None
result_ready_behaviour_builder.then_compute(functio... | d725fc25d0a588b447bf5aa0d3cc8df5c6e8ed3f | 61,313 |
def counting_sort(arr: list, max_value: int = None, place_value: int = None) -> list:
"""Sort a list using counting sort
Args:
arr (list): the list to be sorted
Returns:
list: the sorted list
"""
size = len(arr)
# Get the max value
if max_value is None:
max_value =... | 590b4f84d3cc7675f907f28182326c2f46b82326 | 61,314 |
def make_context(source, frmat='table'):
"""Return a new context from source string in the given format.
>>> c = make_context('''
... |male|female|adult|child|
... man | X | | X | |
... woman| | X | X | |
... boy | X | | | X |
... girl | | X ... | 93e00d7a95e96f7d0efa02a5cded1bff32b4c4e8 | 61,315 |
import pickle
import requests
import json
def room_list(campus):
"""/user/room/list
campus
1=建工/2=燕巢/3=第一/4=楠梓/5=旗津
get campus room list
In this function, without use cache_ap_query
use webap_crawler.query and use GUEST account.
Returns:
[str]: result type is json
error:... | bf859231c9dfa86360ae173d4dbf3f09eae3a32e | 61,316 |
def polyval(p,x):
"""
Replacement for the polyval routine in numpy. This version doesnt check the
input variables to make sure they are array_like. This means that when
masked arrays are treated correctly when they are passed to this routine.
Parameters
----------
p : a 1D array of coeffi... | 7887e504aef74f35bc014462e9bb0eb2c4548971 | 61,317 |
def _authorize_package_action(method, context, data_dict):
"""
Authorize access to core CKAN package actions, to ensure that these actions are not used
directly for modifying metadata records.
:param method: 'create' | 'update' | 'delete'
:param context: should include 'invoked_action' to indicate ... | bde4452b43a33be332152d80a18c751552210efd | 61,318 |
from pathlib import Path
import fnmatch
def apply_path_wildcard(stats, path_wildcard):
"""Filter the given DirectoryListing object using the given PathWildcard."""
paths = Paths(tuple(Path(normpath(join(path_wildcard.symbolic_path, basename(s.path))), s)
for s in stats.dependencies
... | c69f32f10c409dcbf03e208864681bf3b0029477 | 61,319 |
def get_kappa_log_weights_vectorized(k_bnn, omega_post_samples, log_p_k_given_omega_int):
"""Evaluate the log weights used to reweight individual kappa posteriors
Parameters
----------
k_bnn : np.array of shape `[n_test, n_samples]`
omega_post_samples : np.array of shape `[n_omega, 2]`
log_p_k_... | 93d17a773ef7b84e82abf717aafb42d2ad23541a | 61,320 |
def getMatches(sku=None,
division=None,
round=None,
instance=None,
matchnum=None,
scheduled=None,
field=None,
team=None,
scored=None,
season=None,
get_all=False):
"""Return a list of matches matching the given criteria.
For sets of criteria that match a la... | f57dd6cb63e4172d20f5cd4d457686de2e3d13e0 | 61,321 |
def minimum_bounding_circle(geometry, **kwargs):
"""Computes the minimum bounding circle that encloses an input geometry.
Parameters
----------
geometry : Geometry or array_like
**kwargs
For other keyword-only arguments, see the
`NumPy ufunc docs <https://numpy.org/doc/stable/refere... | bc5d1218f79ec7ea2e46ee752ab14fe07a17ec51 | 61,322 |
def dict_of_dict_to_columns(main_df, dict_column, dict_key):
"""Converts a dictionary entry of a dictionary defined in string format into columns"""
if isinstance(main_df[dict_column][0], dict):
# Already of type dict
pass
else:
# Convert unicode to dict in dict_column
... | 601f797770b5c726bbd0c41798d6dd9153152fd4 | 61,323 |
def foobar_unstructured(module, name):
"""
텐서 내 다른 모든 항목들을 제거하여 `module` 에서 `name` 이라는 파라미터에 대해 가자치기 기법을 적용
다음 내용에 따라 모듈을 수정 (또는 수정된 모듈을 반환):
1) 가지치기 기법에 의해 매개변수 `name` 에 적용된 이진 마스크에 해당하는 명명된 버퍼 `name+'_mask'` 를 추가합니다.
`name` 파라미터는 가지치기 기법이 적용된 것으로 대체되며, 가지치기 기법이 적용되지 않은
기존의 파라미터는 `... | 44a3c7ec5f631e8d414208ddde3e046260cb3b39 | 61,324 |
def generateBnode(name=None, prefix=''):
"""
Generates blank nodes (bnodes), AKA anonymous resources
"""
global _bNodeCounter, _sessionBNodeUUID
_bNodeCounter += 1
name = name or str(_bNodeCounter)
return BNODE_BASE + prefix + _sessionBNodeUUID + name | 5cfb1c3a3fb717877100a412ecae33f5ad197628 | 61,325 |
def get_user_by_email(email, db_model):
"""Take an email from request and return user object if existed.
"""
return db_model.query.filter(db_model.email == email).first() | 656ccd8b7fc66141a1e2023ebcfda84dd1caea16 | 61,326 |
def handler_get_user_interests_from_id(userID):
"""Get the interests of the user with the given ID.
.. :quickref: Users; Get the interests of the user with the given ID.
:param int userID: The ID of the user to retrieve the collection from
:status 200: The list was correctly retrieved
:status ... | 41a706234e188d0538ea90f1a82739a0e8e161f9 | 61,327 |
def validate(data_home=None, silence=False):
"""Validate if the stored dataset is a valid version
Args:
data_home (str): Local path where the dataset is stored.
If `None`, looks for the data in the default directory, `~/mir_datasets`
Returns:
missing_files (list): List of file ... | cf7de1084957b55ef0a8a46c826199fae76bbe5e | 61,328 |
import collections
def get_nbest(prelim_predictions, features, example, n_best_size, do_lower_case):
"""get nbest predictions"""
_NbestPrediction = collections.namedtuple(
"NbestPrediction", ["text", "start_logit", "end_logit"])
seen_predictions = {}
nbest = []
for pred in prelim_predicti... | a793a5cf29c0ead2a247a33435e8e6f61ee65867 | 61,329 |
from collections import defaultdict
def E():
"""
Сеть компании состоит из серверов. Серверы соединены друг с другом в кластеры.
Каждый сервер может скачивать файлы только с серверов в его кластере.
Составьте программу, которая сообщать, из каких источников определённый
сервер может скачать необход... | c5ce5e64f2be3c25e63d3f413970b13c1a094725 | 61,330 |
import secrets
def random_key(length: int = 16) -> str:
"""Generate a random key of specified length from the allowed secret characters.
Args:
length: The length of the random key.
"""
secret_allowed_chars = (
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
)... | a50daa81f3a01430a211299ae7123196a4b34264 | 61,331 |
import re
def fetch(name: str, **kwargs):
""" """
func = f"""_fetch_{re.sub("[_-]+dict", "", name.lower()).replace("-", "_")}"""
retval = eval(f"{func}(**kwargs)")
return retval | 62fbe0e478bbb81955e7aa5205b9ddf5197d7fe5 | 61,332 |
def running():
"""Running
Note: Endpoint to check if API is running.
Returns:
flask.jsonify: {'detail': 'Running...'}
"""
return flask.jsonify({'detail': 'Running...'}), 200 | 496f7dd30651895fc9d9674c69a57299dbafd8d7 | 61,333 |
from typing import Union
def peekStep(x:Union[Header, Message], n:int=0) -> Step:
"""Returns the nth Step in x"""
if isinstance(x, Message):
return peekStep(x.header, n)
else:
if len(x.steps) > n:
return x.steps[n]
else:
return Step() | d3f0ec880f1615d6092a0c13c1e174240fff20d6 | 61,334 |
def plot_alpha_vs_width(widths=[pi/24,pi/12,pi/9,pi/6,pi/4,pi/2], tlim=(-5,5), ax=None,
norm=True, legend=True, **kwargs):
"""Plot alpha (phase error) across time for different cue sizes (widths)
Additional keyword arguments are passed to error.alpha().
"""
widths = np.asarray(widths)
if a... | 25d0975d4e620479c5cf3ef97597faa56671417a | 61,335 |
def create_hparams(hparams_string=None, verbose=False):
"""Create model hyperparameters. Parse nondefault from given string."""
hparams = contrib.training.HParams(
################################
# Experiment Parameters #
################################
epochs=50000,
... | 064d8911db2889ecfabfbc053d0c4f22452bd4d5 | 61,336 |
from typing import List
import os
def load_source_vocabs(folder: str) -> List[Vocab]:
"""
Loads source vocabularies from folder. The first element in the list is the primary source vocabulary.
Other elements correspond to optional additional source factor vocabularies found in folder.
:param folder: ... | 6da8a025b98c947964ed048589ec40bc017de340 | 61,337 |
from typing import Optional
import re
def extract_issue_number_from_ref(ref: str) -> Optional[int]:
"""从 Ref 中提取议题号"""
match = re.search(rf"{BRANCH_NAME_PREFIX}(\d+)", ref)
if match:
return int(match.group(1)) | 7f570ef1b914816b405892bf75a85e6b62b2cd66 | 61,338 |
def get_edge_weights_canny_mask(
image,
mask,
dilate_kernel_size=11,
erode_kernel_size=11,
w_edge=1.0,
canny_thr=3.0,
):
"""
Args:
image: NCHW
mask: N1HW
"""
edge_map = get_canny_edge_tensor(image, canny_thr, device=image.device)
mask_edge_weight = compute_mas... | aa4308e6de1b4eb966b8c98e2b5ad3798fe79491 | 61,339 |
def getvar(wrfin, varname, timeidx=0,
method="cat", squeeze=True, cache=None, meta=True,
**kwargs):
"""Returns basic diagnostics from the WRF ARW model output.
A table of all available diagnostics is below.
.. include:: ../../_templates/product_table.txt
Args:
wrfin (:c... | 3e02fce7164d2c402f41e0aa72e9ab758837b6e6 | 61,340 |
import os
def get_init_file():
"""
LOGIC
a) if dsl.ini credentials file in WD that overrides everything
b) try user level credentials ("~/.dimensions/")
c) try navigating up directory tree for dsl.ini
=> a) and c) are useful for jup notebooks without system wide installation
=> b) is th... | 3fb6ead5d2cfc7d333d42c5d4f0b4cf7b6261f01 | 61,341 |
def money_to_decimal(money: Money):
"""
测试自定义的Money类型,会转换成Decimal
:param money: 金额
:return:
"""
return money | 62e24b7f45f4f2383d5d38bd0c303693a36e5363 | 61,342 |
def merge_molecules_xyz(protein_xyz, ligand_xyz):
"""Merges coordinates of protein and ligand.
"""
return np.array(np.vstack(np.vstack((protein_xyz, ligand_xyz)))) | 86b19d4b78feaa98e24d37f60bb71338918cb5aa | 61,343 |
def get_authenticated_session():
"""Return a :py:class:`requests.Session` object authenticated to introspect
tokens. The return value is cached.
"""
cached_session = getattr(get_authenticated_session, '_cached', None)
if cached_session is not None:
return cached_session
get_authenticate... | eac3fd839f216aaf5d0e81b111167421de4d74e2 | 61,344 |
import re
def commit_message_contains_query(message, query_terms):
"""
Check if the commit message contains the query terms
@param message: The commit message
@param query_terms: The terms that we look for in the message
@return:
"""
tester = r'\b(' + '|'.join(query_terms) + ')'
has_re... | b701dac00971658be13a6b7207f8685c3388609e | 61,345 |
def updateContact(request):
"""
연동회원의 담당자 정보를 수정합니다.
- https://docs.popbill.com/message/python/api#UpdateContact
"""
try:
# 팝빌회원 사업자번호
CorpNum = settings.testCorpNum
# 팝빌회원 아이디
UserID = settings.testUserID
# 담당자 정보
updateInfo = ContactInfo(
... | 1912b4a2b19be68e7fb3102d5d7640fdde349b81 | 61,346 |
from typing import Dict
def convert_relus_to_fat(module: Module, **kwargs) -> Dict[str, FATReLU]:
"""
Replace all of the ReLUs in a module with FATReLU instances.
Note: only works if the ReLUs are layers in the module,
will not work with torch.functional ones.
:param module: the module to replac... | ff89ebbe7e7c78db47e481b61c94c7a75ad28fb6 | 61,347 |
def gradient(initial_theta, X, y, initial_lambda):
"""
求梯度,其实就是求偏导
:param initial_theta:
:param X:
:param y:
:param initial_lambda:
:return:
"""
m = len(y)
h = sigmoid(np.dot(X, initial_theta))
theta1 = initial_theta.copy()
theta1[0] = 0
grad = np.zeros((initial_theta... | 2a6bb32371aec1e9b277bb597d6bd1263d479e5b | 61,348 |
def get_event_role(bot, guild):
"""Return the event role, if it exists"""
result = bot.db.get_event_role_id(guild.id)
if result:
for role in guild.roles:
if role.id == result.get('event_role_id'):
return role | 85656ee6b65896762197008108c7b09830a5a4a8 | 61,349 |
def wbrykmap(anchors: tuple[float, float, float] = (1/4, 1/2, 3/4)
) -> LinearSegmentedColormap:
"""
Custom colormap that goes from white to blue to red to yellow to black
inspired by http://paulbourke.net/fractals/juliaset/
Parameters
----------
anchors : tuple[float, float, floa... | 65a85ef19233542c81b3430c6f7384981c9b061f | 61,350 |
def create_dataloader(dataset,
trans_fn=None,
mode='train',
batch_size=1,
batchify_fn=None):
"""
Creats dataloader.
Args:
dataset(obj:`paddle.io.Dataset`): Dataset instance.
trans_fn(obj:`callable`, opti... | 2b1b5d3c83b1406e7239a759c37b908776248a92 | 61,351 |
from typing import Dict
from typing import List
from typing import Set
from typing import Tuple
def create_majority_digraph(profile: Dict[str, List[Set[str]]]) -> Tuple[Set[str], Edges]:
"""
:param profile:
:return:
"""
alternatives: Set[str] = determine_alternatives(profile)
edge_list: List[... | 476477323bd961ba62c24b399f3b941c6f92a699 | 61,352 |
def laser(asteroid_angles):
"""
Takes list of relative asteroid positions with manhattan distances and
relative angles from (0,1), sorted in order of increasing angle and increasing
distance where angles are equal.
Simulates firing a laser from 0 radians (along (0,1)) to 2 pi radians and
de... | 80947e23f1c01d60d73a2fc2f41fa5304b9b1ab4 | 61,353 |
def _plug_compass_ex_east(area, widget, frame, guide):
""" Create a east tab widget from the widget and frame.
"""
return _tabify_helper(area, widget, frame, QDockTabWidget.East) | 85af5f3069c1574d63b022451b489381d18369a5 | 61,354 |
def get_buildings_on_street(city, min_house_area, nodelist_buildings):
"""
Get all building with the same address.
Using "streets". This is a list of the street names in the city, which was created in the function "get_lists(city)".
:param city: str, cit... | 73a9e14e9f747562818178c0900363207687c1b3 | 61,355 |
from typing import Callable
import os
def create_train_fn(train_steps: int = gin.REQUIRED,
batch: int = gin.REQUIRED,
model: SV2P = gin.REQUIRED,
strategy: tf.distribute.Strategy = gin.REQUIRED,
save_rewards: bool = True) -> Callable[[Tex... | b5b68a426b536d5fbe26c75f6e21a1bf8faaedaf | 61,356 |
def get_team_iterations(team, timeframe=None, organization=None, project=None, detect=None):
"""List iterations for a team.
:param team: The name or id of the team.
:type team: str
:param timeframe: A filter for which iterations are returned based on relative time.
Only Current is supported current... | 73178fa498f3600fbb0dad5f34c675f1d8eada67 | 61,357 |
import os
def add_property_list(request):
"""
Adds one property list
From: property_list/add/
:param request:
:return:
"""
form = False
files = False
if request.method == 'POST' and "file" in request.POST:
form = RecipeForm(request.POST.get('file')).html_output()
else:
... | e2df356d3fbe0438ccc4b53357453d42aa70234f | 61,358 |
def copy_adjust(files=None, tmp=None, documents=None, **kwargs):
"""
Read the contents of the .lst file (start). Copy the files, maintaining
the relative folder path) to a temporary folder. The copied files will
have markdown intra-document links adjusted to point to .html instead of
the .md files.... | 2e2c46970c21119ac5f3aacc8a6632a928920616 | 61,359 |
def euclidean(s1, s2):
"""Euclidean distance.
Calculates the distance between two sets of summary statistics by pairwise
computing the Euclidean distance and then averaging.
Parameters
----------
s1: array_like
First set of summary statistics.
s2: array_like
Second set of s... | 2dd1f0a2664ff670b8986e0ce41ead8fff4e61bb | 61,360 |
from typing import Union
from typing import Any
from typing import Callable
def correct_type(vartype: type, expected_type: type) -> bool:
"""
Checks if the type is correct.
So far only supports primitive types, classes, Unions and Optionals.
non-trivial Dicts or Lists are not supported. Scusi.
:pa... | 954add548f5d5b5ae09257c8b084cfb0eff2d347 | 61,361 |
def start_pb_type(
tile_name,
pin_assignments,
input_wires,
output_wires,
root_pb_type,
root_tag='pb_type'
):
""" Starts a pb_type by adding input, clock and output tags. """
pb_type_xml = ET.Element(
root_tag,
{
'name': add_vpr_tile_pr... | 2de94e7adbdb2cb1aa51b5c63d5c5673b41e0246 | 61,362 |
import csv
def get_shipping(f):
"""Get shipping costs function."""
shipping = {}
with open(f, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
row[1] = float(row[1])
shipping[row[0]] = row[1]
return shipping | 1af402c2e62cb7fba76aff333ddd0f873b3ed7f6 | 61,363 |
def adjusted_mutual_information(labels_true, labels_pred, n_jobs = -1, emi_method="parallel", use_cython=True,
average_method='arithmetic'):
"""Adjusted Mutual Information.
Adjusted Mutual Information (AMI) is an adjustment of the Mutual
Information (MI) score to account for c... | e32e767bfed1cfea5605748aabcb12da7b2cddde | 61,364 |
import os
import re
def parse_captions(path):
"""Parse lines from captions"""
lines = []
for fname in os.listdir(path):
if re.findall(r'\.vtt$', fname):
with open(os.path.join(path, fname), 'r') as f:
get_next = False
for line in f.readlines():
... | c8c52c650578aa03d16982963f4abcf1436dcfe4 | 61,365 |
from typing import Optional
from typing import Dict
from typing import Any
def commit_draft(
access_key: str,
url: str,
owner: str,
dataset: str,
*,
draft_number: int,
title: str,
description: Optional[str] = None,
) -> Dict[str, str]:
"""Execute the OpenAPI `POST /v2/datasets/{own... | 395070863b678892ca1004de20ac1b163d6e2da8 | 61,366 |
import os
def get_individuals(vcf=None, case_lines=None, case_type='ped'):
"""Get the individuals from a vcf file, and/or a ped file.
Args:
vcf (str): Path to a vcf
case_lines(Iterable): Ped like lines
case_type(str): Format of ped lines
... | e1dca21fe2a78ba37b21a698475af0f43d826709 | 61,367 |
def is_polygon(f, e):
"""
checks if the shape of the points in f is the convex hull of the eigenvalues e
@param f: numpy complex array with points representing the numerical range
@param e: array of the eigenvalues of the matrix
@return: true if the numerical range is a polygon that is the convex hu... | a1ec18da0b638be4c6b71a4ee19e3a5fbf288e76 | 61,368 |
def wielding(weapon):
"""
Make a character to wield a weapon
"""
action = WieldAction(weapon)
return action | b0859c84f789cb5edf9bc90c3ae68d469c11c508 | 61,369 |
def DotProduct_DML(feat, M, query=None,
is_sparse=False, is_trans=False):
""" DotProduct distance with DML.
"""
if query is None:
query = feat
return -query.dot(M).dot(feat.T) | 7a1d1173e351d6f621755fe5dfc64bcbdcc95b97 | 61,370 |
import os
import sys
import pickle
def read_vest_pickle(gname, score_dir):
"""Read in VEST scores for given gene.
Parameters
----------
gname : str
name of gene
score_dir : str
directory containing vest scores
Returns
-------
gene_vest : dict or None
dict cont... | 517f07242240d4767a0f573c2a02446cb363aa70 | 61,371 |
def _truncated_svd(A, rank=None):
"""Private helper function for calculating truncated singular value
decompositions.
Given a matrix A and a rank K computes the truncated singular value
decomposition U, S, V of A where the K largest singular values are kept and
the rest are truncated to zero. If A ... | a204a74c4433c4ed78abab43d70098517f2c8f13 | 61,372 |
def default_load(*args, **kwargs):
"""Do default deserialize."""
return _DEFAULT_LOAD(*args, **kwargs) | b41f4a7c8eda2a8436f472f7a35cfb42fddc88be | 61,373 |
def random_combination(iterable, r):
"""Return a random *r* length subsequence of the elements in *iterable*.
>>> random_combination(range(5), 3) # doctest:+SKIP
(2, 3, 4)
This equivalent to taking a random selection from
``itertools.combinations(iterable, r)``.
"""
pool = tuple(... | 13434b86aba68300be8e09ca9098d1c813b802f0 | 61,374 |
def pad(line, n=16, start=0):
"""Given a string, substrings to start,
and right pads n spaces. Returns
an n long string.
"""
logger.debug(FUNCTION_CALL_MSG)
padding = " " * n
line = line[start:] + padding
line = line[:n]
return line | de851088bcc3a7e4cdb82dbce4ba3fd2a023c557 | 61,375 |
def zncc(var1, var2):
"""Zero-Normalized Cross-Correlation ZNCC
(normalized correlation of deviation from mean)
"""
N = var1.shape[0] * var1.shape[1]
sigma_1 = np.std(var1)
sigma_2 = np.std(var2)
mu_1 = np.mean(var1)
mu_2 = np.mean(var2)
return 1/N * np.sum(1/(sigma_1 * sigma_2) * (v... | fa1e2c7b9bfb0e641479f005f46d0fdd376a31b6 | 61,376 |
import random
def create_fake_risk(data):
"""
Since the raw data had almost only 'unknown_risk' values and I wanted to
have my visualisations look cool, I decided to do a Diederik Stapeltje and
make up the data myself. ¯\_(ツ)_/¯
"""
risks = []
# for a specific amount of times, add the di... | c42edc03a57913d96701cc8b36c388d42c1c9bfc | 61,377 |
import functools
import os
def section_from_file(fname: str, relpath: bool = True, text_var: str = "text"):
"""Make a decorator for providing a default argument from a text file
Args:
fname (str): Name of the file to be read
relpath (bool): If :data:`True` (default), the file name is interpreted
as... | 261b6b7d846d2435c1dbe8e77f771b97fea5abe6 | 61,378 |
from typing import Mapping
from typing import Union
import yaml
def read_solutions_from_yaml(
filename: str
) -> Mapping[str, Union[SolutionI, SolutionII]]:
"""Reads the solutions(s) contained in a YAML file.
Args:
filename: name of the YAML file to read, it has to have the extension
``.... | 3c395cd57fece19addbfd34393d3a4c9d46766a7 | 61,379 |
def prepareuser_dict(user_dict: dict) -> dict:
"""
Prepare the dict before saving it to redis. Converts data to str or int.
:param user_dict: User data taken from user.to_dict()
:return: dict
"""
d = {}
for k, v in user_dict.items():
d[k] = makesafe(v)
return d | 3e8acf611f4b0bdedbecd757ccc1c7500304ab35 | 61,380 |
import random
def capnp_id() -> str:
"""
Generates a valid id for a capnp schema.
Returns:
str -- capnp id
"""
# the bitwise is for validating the id check capnp/parser.c++
return hex(random.randint(0, 2 ** 64) | 1 << 63) | 55ae4e112c3ba223168627d7d06fab327a0d4f82 | 61,381 |
def linspace(start,stop,np):
"""
Emulate Matlab linspace
"""
return [start+(stop-start)*i/(np-1) for i in range(np)] | b1be58298ff9983f6e2f6c5156cb4497ef8668d9 | 61,382 |
def zScoreStep(**kwargs):
"""
Parameters
----------
kwargs: axis: on which axis to apply the z-score, default to None
Returns
-------
data after z-score
"""
data = kwargs['data']
axis = setDefaultVal(kwargs, 'axis', None)
return data.map(lambda x: zscore(x, axis=axis)) | a40aebe55bea66c3bb32719863d43ea690441465 | 61,383 |
def allow_logged_in(*args, **kwargs):
"""Permission that checks if the community owner is making the request."""
def can(self):
"""Check that the current user is the community's owner."""
return current_user.is_authenticated
return type('AllowCommunityOwner', (), {'can': can})() | 42b1a137f0924a7c637f6cbafbc3e54d6c0bf0f1 | 61,384 |
def make_clf():
"""
Takes no argument, and return a pipeline of linear classifier, containing a scaler and a linear estimator
"""
clf = []
clf.append(('vectorizer',Vectorizer())) # vectorize the 3D matrix along the last 2 dimensions
clf.append(('scaler',StandardScaler()))
estimator = SVC(ker... | bef25a3fe95a4569be621f983e361a350e245f0d | 61,385 |
import pandas
def _coerce_numeric(table):
"""Coerce a table into numeric values."""
for i in range(table.shape[1]):
table.iloc[:, i] = pandas.to_numeric(table.iloc[:, i], errors='coerce')
return table | cba1a224655e3536e361212569b7d6397a58786e | 61,386 |
from cacao_accounting.database import Entidad
def entidades():
"""Listado de entidades."""
CONSULTA = Entidad.query.order_by(Entidad.entidad.desc()).paginate(
request.args.get("page", default=1, type=int), MAXIMO_RESULTADOS_EN_CONSULTA_PAGINADA, False
)
TITULO = "Listado de Entidades - " + AP... | f0d8de42b5fa87e037a6b0354f2c7924e583ab87 | 61,387 |
def motion_plot(
uv_motion_field,
plot_type="quiver",
ax=None,
geodata=None,
axis="on",
plot_kwargs=None,
map_kwargs=None,
step=20,
):
"""
Function to plot a motion field as arrows (quiver) or as stream lines (streamplot).
.. _`quiver_doc`: https://matplotlib.org/api/_as_gen... | e45d74050a00b0eade3b6d1dee1ac1d0f2ec05cf | 61,388 |
def get_token_from_auth_header(header_string):
"""Obtains the Access Token from the Authorization Header
"""
if not header_string:
raise AuthError(
{
"code": "authorization_header_missing",
"description": "Authorization header is expected",
},
... | 22f3021d96f580abbff5bdd202d1837b9772ec66 | 61,389 |
from pathlib import Path
def parse_yaml(filename):
"""
Given input path filename, parse YAML file.
"""
inf = Path(filename)
yml = ruamel.yaml.YAML()
return yml.load(inf) | 01cd38f35a4392d09ac4100fd17abca5aedb8305 | 61,390 |
def get_scene_model(point_cloud, is_training, num_class, sigma, bn_decay=None, weight_decay = None):
""" Semantic segmentation PointNet, input is BxNx3, output Bxnum_class """
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
end_points = {}
l0_xyz = point_c... | 3cd3f1a5b71cc4eafa5403e5ab714a7d684323c2 | 61,391 |
def vgg16(**kwargs):
"""
VGG-16 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,'
https://arxiv.org/abs/1409.1556.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/mo... | c05ed87aecc689b69750fabeb075582b960e86d7 | 61,392 |
from typing import Tuple
def to_mido_note_on_note_off(
note: Note, channel: int, use_note_off_message: bool = False
) -> Tuple[Message, Message]:
"""Return a Note object as mido Message objects.
Timing is in absolute time, NOT in delta time.
Parameters
----------
note : :class:`muspy.Note` o... | e8fd486046dba34c7773a9885e7688cbf5e949eb | 61,393 |
def plot_exposures(pointings, Aeff_fact, index=1, lat=0., lon=np.radians(260.),
Earth=True, antiEarth=False, NSIDE=32, doplot=True):
"""Short descrtiption of this function.
Parameters
----------
pointings : dictionary
Dictionary with the pointings of the detectors.
Aeff... | 2584411db280b9c7ab5ab87a1fe6303c7f1cd0de | 61,394 |
import unicodedata
import sys
from HTMLParser import HTMLParser
import html
def clean(text):
"""
A function for cleaning a string of text.
Returns valid ASCII characters.
"""
text = clean_whitespace(text)
# Remove links from message
# text = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+... | 42ec680fbac40f007b0684847a1b9c366dbdf6e4 | 61,395 |
from typing import Any
def get_user_if_token_user(user: Any):
"""
Support for django-rest-framework-simplejwt TokenUser.
Makes sure to always use the actual user model with save capability.
Returns None for anonymous users
"""
if user:
if not user.is_authenticated:
return N... | 100a4970bea67d5b2709b964f5b462094ab201e7 | 61,396 |
def assert_normalized(probs, tolerance=0.01, raise_error=True):
""" Normalize probs so they sum to one. The probability should already so to ~1, but not exactly 1 due to rounding.
:param probs: A list of probabilities
:param tolerance: The maximum tolerance (i.e. should sum to 1. +- tolerance)
... | bb9dd8797c21b5067f7bc66800683c9d5e44c132 | 61,397 |
def add_ta_features(df, ta_settings):
"""Add technial analysis features from typical financial dataset that
typically include columns such as "open", "high", "low", "price" and
"volume".
http://mrjbq7.github.io/ta-lib/
Args:
df(pandas.DataFrame): original DataFrame.
ta_settings(dic... | 2c435fb98fe1326a08a093c28f53e5eee1515762 | 61,398 |
def dm_to_npy(dm_path):
"""
Converts a dm3 or dm4 image to a uint8 numpy array with a contrast limit
suggested in the dm file.
"""
# Load the dm4 file and extract the image data.
signal = dm.file_reader(dm_path)[0]
image_data = signal['data']
# get the contrast limits from the file
m... | e619a8c386aa8ac6af4785e1d3510a4735686256 | 61,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.