content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_xml_content(
segmentation: list[dict],
lang_text: list[str],
split: str,
src_lang: str,
tgt_lang: str,
is_src: bool,
) -> list[str]:
"""
Args:
segmentation (list): content of the yaml file
lang_text (list): content of the transcription or translation txt file
... | 6af6b5fcdaccd5bd81ad202bdb22fad3910afc2b | 9,333 |
def style_string(string: str, fg=None, stylename=None, bg=None) -> str:
"""Apply styles to text.
It is able to change style (like bold, underline etc), foreground and background colors of text string."""
ascii_str = _names2ascii(fg, stylename, bg)
return "".join((
ascii_str,
string,
... | 6d61c33a632c88609cb551ae0a1d55d8ee836937 | 9,334 |
def select_all_genes():
"""
Select all genes from SQLite database
"""
query = """
SELECT GENE_SYMBOL, HGNC_ID, ENTREZ_GENE_ID, ENSEMBL_GENE, MIM_NUMBER FROM GENE
"""
cur = connection.cursor()
cur.execute(query)
rows = cur.fetchall()
genes = []
for row in rows:
... | fb73e890d62f247939c1aa9a1e16a8e5f5a75866 | 9,335 |
def test_enum_handler(params):
""" 测试枚举判断验证
"""
return json_resp(params) | c3a4a9589b5d06813d6afaa55c8f6d9fafa80252 | 9,336 |
def get_staff_timetable(url, staff_name):
"""
Get Staff timetable via staff name
:param url: base url
:param staff_name: staff name string
:return: a list of dicts
"""
url = url + 'TextSpreadsheet;Staff;name;{}?template=SWSCUST+Staff+TextSpreadsheet&weeks=1-52' \
'&days=1-7&... | 0e52604c08bef70d5cfc1fc889c8ced766f49ae5 | 9,337 |
def find_ccs(unmerged):
"""
Find connected components of a list of sets.
E.g.
x = [{'a','b'}, {'a','c'}, {'d'}]
find_cc(x)
[{'a','b','c'}, {'d'}]
"""
merged = set()
while unmerged:
elem = unmerged.pop()
shares_elements = False
for s in merged.copy... | 4bff4cc32237dacac7737ff509b4a68143a03914 | 9,338 |
def read_match_df(_url: str, matches_in_section: int=None) -> pd.DataFrame:
"""各グループの試合リスト情報を自分たちのDataFrame形式で返す
JFA形式のJSONは、1試合の情報が下記のような内容
{'matchTypeName': '第1節',
'matchNumber': '1', # どうやら、Competitionで通しの番号
'matchDate': '2021/07/22', # 未使用
'matchDateJpn': '2021/07/22',
'matchDateWe... | 0dae5f1669c3e1a1a280967bc75780a7b1aa91a0 | 9,339 |
import re
def tokenize(text):
"""Tokenise text with lemmatizer and case normalisation.
Args:
text (str): text required to be tokenized
Returns:
list: tokenised list of strings
"""
url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
det... | 56c7dc6ce557257f8716bd502958093eb01a8c50 | 9,340 |
def reinforce_loss_discrete(classification_logits_t,
classification_labels_t,
locations_logits_t,
locations_labels_t,
use_punishment=False):
"""Computes REINFORCE loss for contentious discrete action spaces... | 7296f0647d792ce0698cd48d2b56e30941ca1afb | 9,341 |
import itertools
def distances(spike_times, ii_spike_times, epoch_length=1.0, metric='SPOTD_xcorr'):
"""Compute temporal distances based on various versions of the SPOTDis, using CPU parallelization.
Parameters
----------
spike_times : numpy.ndarray
1 dimensional matrix containing all spike t... | 3696f33929150ac2f002aa6a78822654eeb50581 | 9,344 |
def format_object_translation(object_translation, typ):
"""
Formats the [poi/event/page]-translation as json
:param object_translation: A translation object which has a title and a permalink
:type object_translation: ~cms.models.events.event.Event or ~cms.models.pages.page.Page or ~cms.models.pois.poi.... | 11499d53d72e071d59176a00543daa0e8246f89a | 9,345 |
def _FormatKeyValuePairsToLabelsMessage(labels):
"""Converts the list of (k, v) pairs into labels API message."""
sorted_labels = sorted(labels, key=lambda x: x[0] + x[1])
return [
api_utils.GetMessage().KeyValue(key=k, value=v) for k, v in sorted_labels
] | 3f2dd78951f8f696c398ab906acf790d7923eb75 | 9,346 |
def gen_unique(func):
""" Given a function returning a generator, return a function returning
a generator of unique elements"""
return lambda *args: unique(func(*args)) | 703dc6f80553fc534ca1390eb2c0c3d7d81b26eb | 9,347 |
def admin_inventory(request):
"""
View to handle stocking up inventory, adding products...
"""
context = dict(product_form=ProductForm(),
products=Product.objects.all(),
categories=Category.objects.all(),
transactions=request.user.account.transact... | ec8f38947ab95f82a26fc6c6949d569a5ec83f7d | 9,348 |
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
print(f'METHOD @ snippet_list= {request.method}')
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(seriali... | 959245f7d194470c4bccef338ead8d0b35abe1bc | 9,349 |
def generate_submission(args: ArgumentParser, submission: pd.DataFrame) -> pd.DataFrame:
"""Take Test Predictions for 4 classes to Generate Submission File"""
image, kind = args.shared_indices
df = submission.reset_index()[[image, args.labels[0]]]
df.columns = ["Id", "Label"]
df.set_index("Id", inpl... | e5b3f1c65adbe1436d638667cbc7bae9fb8a6a1e | 9,350 |
import numba
def nearest1d(vari, yi, yo, extrap="no"):
"""Nearest interpolation of nD data along an axis with varying coordinates
Warning
-------
`nxi` must be either a multiple or a divisor of `nxo`,
and multiple of `nxiy`.
Parameters
----------
vari: array_like(nxi, nyi)
yi: ar... | f7a9c03b1cca3844a9aad3d954fa2a189134a69f | 9,351 |
def registros():
"""Records page."""
return render_template('records.html') | b72cffbdf966f8c94831da76fd901ce9cba60aac | 9,352 |
def cal_evar(rss, matrix_v):
"""
Args:
rss:
matrix_v:
Returns:
"""
evar = 1 - (rss / np.sum(matrix_v ** 2))
return evar | 21f1d71ba98dafe948a5a24e4101968531ec1e30 | 9,353 |
def split_path(path):
"""
public static List<String> splitPath(String path)
* Converts a path expression into a list of keys, by splitting on period
* and unquoting the individual path elements. A path expression is usable
* with a {@link Config}, while individual path elements are usable with a... | 9e102d7f7b512331165f51e6055daeaf4f56b61a | 9,354 |
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated_d():
"""Dilated hparams."""
hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated()
hparams.gap_sizes = [0, 16, 64, 16, 64, 128, 256, 0]
return hparams | b0a56031e06cff42df4cdeab55e01322be8e439d | 9,356 |
def leaveOneOut_Input_v4( leaveOut ):
"""
Generate observation matrix and vectors
Y, F
Those observations are trimed for the leave-one-out evaluation. Therefore, the leaveOut
indicates the CA id to be left out, ranging from 1-77
"""
des, X = generate_corina_features('ca')
X = np.delete... | 0078bda71345d31cf24f4d1c4ceeafa768357ad4 | 9,357 |
import logging
def common_inroom_auth_response(name, request, operate, op_args):
"""
> 通用的需要通过验证用户存在、已登录、身处 Room 的操作。
参数:
- name: 操作名,用于日志输出;
- request: Flask 传来的 request;
- operate: 具体的操作函数,参数为需要从 request.form 中提取的值,返回值为成功后的response json;
- op_args: operate 函数的 参数名 str 组成的列表。
返回:res... | b11607f2d0a6a656c65cf464010f10634389f0bf | 9,358 |
def get_pca(acts, compute_dirns=False):
""" Takes in neuron activations acts and number of components.
Returns principle components and associated eigenvalues.
Args:
acts: numpy array, shape=(num neurons, num datapoints)
n_components: integer, number of pca components to reduce
... | 25620178e340f58b3d13ed0de4ee6d324abcb3ef | 9,359 |
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
#imgCopy = np.uint8(img)
return cv2.Canny(img, low_threshold, high_threshold) | 80e8d4ad99c769887e85577b46f6028ceea0b9f6 | 9,362 |
def pairwise_two_tables(left_table, right_table, allow_no_right=True):
"""
>>> pairwise_two_tables(
... [("tag1", "L1"), ("tag2", "L2"), ("tag3", "L3")],
... [("tag1", "R1"), ("tag3", "R3"), ("tag2", "R2")],
... )
[('L1', 'R1'), ('L2', 'R2'), ('L3', 'R3')]
>>> pairwise_two_tables(
... | aabcccc2ade9b00ed5bdac32f9cc4a7a4cc718c3 | 9,363 |
def augment_stochastic_shifts(seq, augment_shifts):
"""Apply a stochastic shift augmentation.
Args:
seq: input sequence of size [batch_size, length, depth]
augment_shifts: list of int offsets to sample from
Returns:
shifted and padded sequence of size [batch_size, length, depth]
"""
shift_index = ... | 1afd682e1f665d4d0786e729e6789a6459b4457c | 9,364 |
def _SourceArgs(parser):
"""Add mutually exclusive source args."""
source_group = parser.add_mutually_exclusive_group()
def AddImageHelp():
"""Returns detailed help for `--image` argument."""
template = """\
An image to apply to the disks being created. When using
this option, the size o... | dfa44ed54c4efba666f19c850a0eacffe85cafa0 | 9,365 |
def get_all_species_links_on_page(url):
"""Get all the species list on the main page."""
data, dom = get_dom(url)
table = dom.find('.tableguides.table-responsive > table a')
links = []
for link in table:
if link is None or link.text is None:
continue
links.append(dict(
... | 4a63d78b699150c37ccc9aa30d9fa6dae39d801b | 9,366 |
def gen_image_name(reference: str) -> str:
"""
Generate the image name as a signing input, based on the docker reference.
Args:
reference: Docker reference for the signed content,
e.g. registry.redhat.io/redhat/community-operator-index:v4.9
"""
no_tag = reference.split(":")[0]
... | ccaecfe91b5b16a85e3a3c87b83bbc91e54080b1 | 9,367 |
def adaptive_confidence_interval(values, max_iterations=1000, alpha=0.05, trials=5, variance_threshold=0.5):
""" Compute confidence interval using as few iterations as possible """
try_iterations = 10
while True:
intervals = [confidence_interval(values, try_iterations, alpha) for _ in range(trials... | 47c1861384d94a13beaf86eed5ad88a2ad2fb80f | 9,368 |
def get_chat_id(update):
"""
Get chat ID from update.
Args:
update (instance): Incoming update.
Returns:
(int, None): Chat ID.
"""
# Simple messages
if update.message:
return update.message.chat_id
# Menu callbacks
if update.callback_query:
return ... | 1669382fd430b445ea9e3a1306c1e68bf2ec0013 | 9,369 |
def chooseCommertialCity(commercial_cities):
"""
Parameters
----------
commercial_cities : list[dict]
Returns
-------
commercial_city : dict
"""
print(_('From which city do you want to buy resources?\n'))
for i, city in enumerate(commercial_cities):
print('({:d}) {}'.for... | 6e39c1922a1560f6d3d442cf5d14b764f2c08437 | 9,371 |
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
"""Reusable code for making a simple neural net layer.
It does a matrix multiply, bias add, and then uses relu to nonlinearize.
It also sets up name scoping so that the resultant graph is easy to read,
and adds a number of summary o... | 38976aa68de06e131f0e2fd8056216ce9bfcba77 | 9,372 |
def get_validate_platform(cmd, platform):
"""Gets and validates the Platform from both flags
:param str platform: The name of Platform passed by user in --platform flag
"""
OS, Architecture = cmd.get_models('OS', 'Architecture', operation_group='runs')
# Defaults
platform_os = OS.linux.value
... | 3b9150c400ed28e322108ba531c7f4c5ac450da1 | 9,374 |
def get_path_cost(slice, offset, parameters):
"""
part of the aggregation step, finds the minimum costs in a D x M slice (where M = the number of pixels in the
given direction)
:param slice: M x D array from the cost volume.
:param offset: ignore the pixels on the border.
:param parameters: stru... | 06348e483cd7cba012354ecdcadcd0381b0b7dfb | 9,375 |
def generate_cyclic_group(order, identity_name="e", elem_name="a", name=None, description=None):
"""Generates a cyclic group with the given order.
Parameters
----------
order : int
A positive integer
identity_name : str
The name of the group's identity element
Defaults to 'e'
... | ed79547dfde64ece136456a8c5d7ce00c4317176 | 9,376 |
def loadTextureBMP(filepath):
"""
Loads the BMP file given in filepath, creates an OpenGL texture from it
and returns the texture ID.
"""
data = np.array(Image.open(filepath))
width = data.shape[0]
height = data.shape[1]
textureID = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, textu... | dd80584afc644fa23c2aef919a24152ea5b3696e | 9,377 |
def get_pixeldata(ds: "Dataset") -> "np.ndarray":
"""Return a :class:`numpy.ndarray` of the pixel data.
.. versionadded:: 2.1
Parameters
----------
ds : pydicom.dataset.Dataset
The :class:`Dataset` containing an :dcm:`Image Pixel
<part03/sect_C.7.6.3.html>` module and the *Pixel Da... | 418603d30bf272affc0e63615e94d4cce11b1bf2 | 9,378 |
import time
def timeit(method):
""" Timing Decorator Function Written by Fahim Sakri of PythonHive (https://medium.com/pthonhive) """
def timed(*args, **kwargs):
time_start = time.time()
time_end = time.time()
result = method(*args, **kwargs)
if 'log_time' in kwargs:
... | 598667950bc707b72239af9f4e5a3248dbe64d96 | 9,379 |
def allot_projects():
"""
The primary function that allots the projects to the employees.
It generates a maximum match for a bipartite graph of employees and projects.
:return: A tuple having the allotments, count of employees allotted and
total project headcount (a project where two people need to... | 774df8714cd47eb2a7affe34480dfec682010341 | 9,380 |
import requests
def upload_record(data, headers, rdr_project_id):
""" Upload a supplied record to the research data repository
"""
request_url = f"https://api.figsh.com/v2/account/projects/{rdr_project_id}/articles"
response = requests.post(request_url, headers=headers, json=data)
return res... | 7431234757668f9157f90aa8a9c335ee0e2a043b | 9,381 |
def datetime_to_ts(str_datetime):
"""
Transform datetime representation to unix epoch.
:return:
"""
if '1969-12-31' in str_datetime:
# ignore default values
return None
else:
# convert to timestamp
if '.' in str_datetime: # check whether it has milliseconds or no... | 83b40abc6c5ce027cf04cd2335b2f35e235451d0 | 9,382 |
import functools
def is_codenames_player(funct):
"""
Decorator that ensures the method is called only by a codenames player.
Args:
funct (function): Function being decorated
Returns:
function: Decorated function which calls the original function
if the user is a codenames pla... | 814bc929bbd20e8c527bd5c922a25823a4bdbefc | 9,383 |
def get(args) -> str:
"""Creates manifest in XML format.
@param args: Arguments provided by the user from command line
@return: Generated xml manifest string
"""
arguments = {
'target': args.target,
'targetType': None if args.nohddl else args.targettype,
'path': args.path,
... | 7b859952d7eda9d6dedd916bb3534d225c3d9593 | 9,385 |
from typing import Callable
def elementwise(op: Callable[..., float], *ds: D) -> NumDict:
"""
Apply op elementwise to a sequence of numdicts.
If any numdict in ds has None default, then default is None, otherwise the
new default is calculated by running op on all defaults.
"""
keys: set... | 4e7dce60d01e8bcec722a5a6d60d15920a6a91c5 | 9,386 |
import torch
def sigmoid_focal_loss(
inputs: torch.Tensor,
targets: torch.Tensor,
alpha: float = -1,
gamma: float = 2,
reduction: str = "none",
) -> torch.Tensor:
"""
Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
Args:
inputs: A float tensor of a... | e792c1bea37bcc26ff323a764fc56e0f4bbd0bc5 | 9,387 |
def arcsin(x):
"""Return the inverse sine or the arcsin.
INPUTS
x (Variable object or real number)
RETURNS
if x is a Variable, then return a Variable with val and der.
if x is a real number, then return the value of arcsin(x).
EXAMPLES
>>> x = Variable(0, name='x')
>>> t = arcsin(x)
>>> print(t.val, t.d... | a5d899dae9b4fc33b6ddf2e2786ec6eee8508541 | 9,388 |
import tqdm
def preprocessing(texts, words, label, coef=0.3, all_tasks=False, include_repeat=True, progressbar=True):
"""
the function returns the processed array for the Spacy standard
"""
train = []
enit = {}
assert 0 < coef <= 1, f"The argument must be in the range (0 < coef <= 1) --> {coe... | f10c27f8ed686d45a1c778bdf557f88ad3f3bdfa | 9,389 |
import numpy
import math
def rotate(
input,
angle,
axes=(1, 0),
reshape=True,
output=None,
order=3,
mode="constant",
cval=0.0,
prefilter=True,
*,
allow_float32=True,
):
"""Rotate an array.
The array is rotated in the plane defined by the two axes given by the
`... | 04b7f3dc66d09c0b69ba97579972e131cc96b375 | 9,390 |
def generate_url_fragment(title, blog_post_id):
"""Generates the url fragment for a blog post from the title of the blog
post.
Args:
title: str. The title of the blog post.
blog_post_id: str. The unique blog post ID.
Returns:
str. The url fragment of the blog post.
"""
... | c846e6203fa4782c6dc92c892b9e0b6c7a0077b5 | 9,391 |
def update_cluster(cluster, cluster_args, args,
api=None, path=None, session_file=None):
"""Updates cluster properties
"""
if api is None:
api = bigml.api.BigML()
message = dated("Updating cluster. %s\n" %
get_url(cluster))
log_message(message, log_fil... | d07e3969e90cbc84f5329845e540c3b1a03d86b5 | 9,392 |
def get_post_by_user(user_id: int, database: Session) -> Post:
"""
"""
post = database.query(Post).filter(
Post.user == user_id).order_by(Post.id.desc()).all()
logger.info("FOI RETORNADO DO BANCO AS SEGUINTES CONTRIBUIÇÕES: %s", post)
return post | 9274caf4d484e68bdc7c852aff6360d9674b2957 | 9,393 |
import yaml
def unformat_bundle(formattedBundle):
"""
Converts a push-ready bundle into a structured object by changing
stringified yaml of 'customResourceDefinitions', 'clusterServiceVersions',
and 'packages' into lists of objects.
Undoing the format helps simplify bundle validation.
:param ... | fcc6067fab89dffa8e31e47da42060ca11a48478 | 9,394 |
def supports_box_chars() -> bool:
"""Check if the encoding supports Unicode box characters."""
return all(map(can_encode, "│─└┘┌┐")) | 82a3f57429d99dc2b16055d2b7103656ec2e05e5 | 9,395 |
def calculate_intersection_over_union(box_data, prior_boxes):
"""Calculate intersection over union of box_data with respect to
prior_boxes.
Arguments:
ground_truth_data: numpy array with shape (4) indicating x_min, y_min,
x_max and y_max coordinates of the bounding box.
prior_boxes:... | 6ac634953a92f1b81096f72209ae5d25d46aa4e6 | 9,396 |
def get_report(analytics, start_date, end_date = 'today'):
"""Queries the Analytics Reporting API V4.
Args:
analytics: An authorized Analytics Reporting API V4 service object.
Returns: The Analytics Reporting API V4 response.
"""
return analytics.reports().batchGet(
body={
'reportRequests': [
... | cac0b27a40f6a648a4d3f41aa9615dc114700f84 | 9,397 |
def write_pinout_xml(pinout, out_xml=None):
"""
write the pinout dict to xml format with no attributes. this is verbose
but is the preferred xml format
"""
ar = []
for k in sort_alpha_num(pinout.keys()):
d = pinout[k]
d['number'] = k
# ar.append({'pin': d})
ar.a... | 7f2fff341b11eb29bf672a4f78b0fc0971a26cbc | 9,398 |
import json
def get_solution(request, level=1):
"""Returns a render of answers.html"""
context = RequestContext(request)
cheat_message = '\\text{Ulovlig tegn har blitt brukt i svar}'
required_message = '\\text{Svaret ditt har ikke utfylt alle krav}'
render_to = 'game/answer.html'
if request.... | f6d5b7c90b656d2302c1aaf2935fc39bcf882a03 | 9,399 |
def get_work_log_queue():
""" json格式为::
{'func':'transform',
'kw':{ ... # 和前面task_queue相同
},
"runtime":{ # 队列运行相关信息
'created':12323423 #进入原始队列时间
'queue':'q01' # 是在哪个原子原子队列
'start':123213123 #转换开始时间
'end':123213123 #转换结束时间
'worker':'w01... | 26b2e3c73f7dd05b44659d3a02ca8d2b8205057e | 9,400 |
def is_first_buy(ka, ka1, ka2=None, pf=False):
"""确定某一级别一买
注意:如果本级别上一级别的 ka 不存在,无法识别本级别一买,返回 `无操作` !!!
一买识别逻辑:
1)必须:上级别最后一个线段标记和最后一个笔标记重合且为底分型;
2)必须:上级别最后一个向下线段内部笔标记数量大于等于6,且本级别最后一个线段标记为底分型;
3)必须:本级别向下线段背驰 或 本级别向下笔背驰;
4)辅助:下级别向下线段背驰 或 下级别向下笔背驰。
:param ka: KlineAnalyze
本级别
... | 5ea35d728f3ddfaa5cff09a2e735c480f1e3c622 | 9,401 |
def preprocess(path, l_pass=0.7, h_pass=0.01, bandpass=True, short_ch_reg=False, tddr=True, negative_correlation=False, verbose=False, return_all=False):
"""
Load raw data and preprocess
:param str path: path to the raw data
:param float l_pass: low pass frequency
:param float h_pass: high pass freq... | 01d508de322fa007886e34838911d2cccea79aab | 9,402 |
def geomapi_To2d(*args):
"""
* To intersect a curve and a surface. This function builds (in the parametric space of the plane P) a 2D curve equivalent to the 3D curve C. The 3D curve C is considered to be located in the plane P. Warning The 3D curve C must be of one of the following types: - a line - a circle - a... | 7a8a6436f364e933d71ba8fb47617f01b0e13b47 | 9,403 |
import yaml
def get_object_list():
"""Returns the object name list for APC2015.
Args:
None.
Returns:
objects (list): List of object name.
"""
pkg_path = rospkg.RosPack().get_path(PKG)
yaml_file = osp.join(pkg_path, 'data/object_list.yml')
with open(yaml_file) as f:
... | 7fd1268ef8804eb394a42a6b2fdc9fc223cd4316 | 9,404 |
def gtMakeTAKBlobMsg(callsign, text, aesKey=False):
"""
Assemble an ATAK plugin compatible chat message blob
(suitable for feeding to gtMakeAPIMsg() )
With optional AES encryption, if a key is provided
"""
body = (callsign + b': ' + text)[:230]
# Apply optional encryption (and base64 encod... | ecc562e92a72a0a6e0d5cc45563d1c89962d931b | 9,405 |
import re
def validate_json_with_extensions(value, rule_obj, path):
""" Performs the above match, but also matches a dict or a list. This it
just because it seems like you can't match a dict OR a list in pykwalify
"""
validate_extensions(value, rule_obj, path)
if not isinstance(value, (list, dict... | ef4d5744adf0c2d3ca326da66cbe608b306a2ca3 | 9,406 |
def artists_by_rating(formatter, albums):
"""Returns the artists sorted by decreasing mean album rating.
Only artists with more than 1 reviewed albums are considered.
"""
artist_tags = set([album["artist_tag"] for album in albums])
artists = []
# build the list of artists and compute their ratin... | fdf443973b4187650d95f76f8cde2a61ea7a1a3f | 9,407 |
def st_max(*args):
"""Max function.
Parameters
----------
x : float, int, MissingValue instance, or None
(2 or more such inputs allowed)
Returns
-------
max(x1, x2, ...) if any x is non-missing (with missing values ignored).
Otherwise, MISSING (".") returned.
"... | 978cab7522250541890c723fcf33d2ded9539293 | 9,408 |
def is_button_controller(device: Device) -> bool:
"""Return true if the device is a stateless button controller."""
return (
CAP_PUSHABLE_BUTTON in device.capabilities
or CAP_HOLDABLE_BUTTON in device.capabilities
or CAP_DOUBLE_TAPABLE_BUTTON in device.capabilities
) | aa16170469f6a65d2ed94ab251817e722082ef16 | 9,409 |
def list_parts(bucket, key, upload_id):
"""Lists the parts that have been uploaded for a specific multipart upload.
This operation must include the upload ID, which you obtain by
sending the initiate multipart upload request (see
CreateMultipartUpload ). This request returns a maximum of 1,000
uplo... | eb343e071ce72ea326fc479934984fdff425dfec | 9,411 |
def leap_year():
"""
This functions seeks to return a leap year after user input << integer(4).
Rules for a leap year:
As you surely know, due to some astronomical reasons, years may be leap or common.
The former are 366 days long, while the latter are 365 days long.
Since the introduction of t... | 5cf459514ce768c1cf633fdddab5f986004bc1c8 | 9,412 |
import math
def parse(files, **kwargs):
"""Parse all BAM files."""
parsed = []
if kwargs["meta"].has_field("base_coverage"):
cov_range = kwargs["meta"].field_meta("base_coverage")["range"]
else:
cov_range = [math.inf, -math.inf]
if kwargs["meta"].has_field("read_coverage"):
... | c12b068f2a32052cbaa583a4704f86c25e577947 | 9,413 |
def login(request):
"""Login view for GET requests."""
logged_in = request.authenticated_userid is not None
if logged_in:
return {'logged_in': True,
'form_enabled': False,
'status': u'Already logged in',
'status_type': u'info'}
status = u''
s... | 8cab36d8d059d0683ef2e84a40cca5c99a27c6fc | 9,414 |
def of_type(_type, value_1, *args) -> bool:
"""
Check if a collection of values are of the same type.
Parameters:
_type (any): The type to check for.
value_1 (any): The first value to check.
*args (any): Rest of values to check against given type.
Return... | eab1e70655ff74b1cbfc338a893719b7f0681f4a | 9,415 |
import yaml
def read_config(path):
"""
Reads the Kong config file (YAML).
"""
if path is None:
raise Exception(
"empty path provided. please provide a path using `--config=<config.yml>`"
)
with open(path, "r") as stream:
try:
return yaml.safe_load(st... | 343fabb8fa1c4cc78ace63466c864e50cf5dc974 | 9,417 |
def generate_grid_world(grid, prob, pos_rew, neg_rew, gamma=.9, horizon=100):
"""
This Grid World generator requires a .txt file to specify the
shape of the grid world and the cells. There are five types of cells: 'S' is
the starting position where the agent is; 'G' is the goal state; '.' is a
norma... | 753fa30327f2dddfb4a459fbb40e842b28b0eda8 | 9,418 |
def sqrt_quadrature_scheme(N_poly, N_poly_log):
""" Returns quadrature rule that is exact on 0^1 for
p(x) + q(x)sqrt(x) for deg(p) <= N_poly and deg(q) <= N_poly_sqrt.
"""
nodes, weights = sqrt_quadrature_rule(N_poly, N_poly_log)
return QuadScheme1D(nodes, weights) | c39539604955f473c0a77816090fe180645670ae | 9,419 |
def check_dataset_update(args, dataset):
"""Checks if the dataset information must be updated.
"""
return (args.dataset_attributes or
args.import_fields or
(args.shared_flag and r.shared_changed(args.shared, dataset)) or
(((hasattr(args, 'max_categories') and args.max_ca... | 005700a0d544333f018ec423a6e3d287ab982553 | 9,420 |
from typing import Dict
from typing import List
import json
def get_package_extras(provider_package_id: str) -> Dict[str, List[str]]:
"""
Finds extras for the package specified.
:param provider_package_id: id of the package
"""
if provider_package_id == 'providers':
return {}
with ope... | 15ac01740e60d2af73458b7ef46330708831a0ca | 9,421 |
def e(a: float, b: float) -> float:
"""
e = sqrt(1 + (b * b) / (a * a))
:param a: semi-major axis
:type a: float
:param b: semi-minor axis
:type b: float
:return: eccentricity
:rtype: float
"""
return np.sqrt(1 + (b * b) / (a * a)) | f2eec5065d735984daa5197b8401ec3a60914d25 | 9,422 |
from pathlib import Path
import sh
def parse_note(path: Path) -> dict:
""" convert note in plain text to a dictionary.
Line #1 ~ #5 are meta data of the note.
Line #9 to end is the body.
"""
header_line_number = 5
body_start_line = 9
res = {}
with open(path) as f:
for x... | 792f4bace60fa52b1a7cbeeaf0dabd881ffd4a24 | 9,423 |
def get_previous_sle_for_warehouse(last_sle, exclude_current_voucher=False):
"""get stock ledger entries filtered by specific posting datetime conditions"""
last_sle['time_format'] = '%H:%i:%s'
if not last_sle.get("posting_date"):
last_sle["posting_date"] = "1900-01-01"
if not last_sle.get("pos... | 7fdc0db05564cc54555784c474c7bc4cb33e280a | 9,424 |
import networkx as nx
def forest_str(graph, with_labels=True, sources=None, write=None, ascii_only=False):
"""
Creates a nice utf8 representation of a directed forest
Parameters
----------
graph : nx.DiGraph | nx.Graph
Graph to represent (must be a tree, forest, or the empty graph)
w... | 3486545035b9c2a8954102bdb92ebe9dd7b1fa24 | 9,425 |
import copy
def rotated_shower(shower, alt, az):
"""
Return a rotated shower object from a shower object and a direction (alt, az)
Parameters
----------
shower: shower class object
Returns
-------
copy of the given shower but rotated
"""
rot_shower = copy(shower)
rot_showe... | d420c408083a54837c87db405a8d65abfe46a5f8 | 9,426 |
def angle2circle(angles):
"""from degree to radians multipled by 2"""
return np.deg2rad(2 * (np.array(angles) + 7.5)) | 4c944725fd44480b5f7261c24608b3e06cec013a | 9,427 |
def _make_source(cls_source: str, cls_name: str, instance_method: str):
"""Converts a class source to a string including necessary imports.
Args:
cls_source (str): A string representing the source code of a user-written class.
cls_name (str): The name of the class cls_source represents.
... | 105ca5d34c0de2bfc81937aaaf14b4d610eaa35a | 9,428 |
def prepend_pass_statement(line: str) -> str:
"""Prepend pass at indent level and comment out the line."""
colno = num_indented(line)
right_side = line[colno:]
indent = " " * colno
return indent + "pass # " + right_side | 7d7156581167fcd6ec5c4afc482cf8bf3dea11bc | 9,429 |
from datetime import datetime
import time
def download_spot_by_dates(start=datetime(2011, 1, 1)):
"""
下载数据,存储为csv文件
:param start: 2011-01-01 最早数据
:return: True 下载文件 False 没有下载文件
"""
file_index = get_download_file_index(SPREAD_DIR, start=start)
if file_index.empty:
return False
... | 34574d4cd5d1985850fe681c3e5e4f6a3ebdc1a4 | 9,430 |
def truncate_range(data, percMin=0.25, percMax=99.75, discard_zeros=True):
"""Truncate too low and too high values.
Parameters
----------
data : np.ndarray
Image to be truncated.
percMin : float
Percentile minimum.
percMax : float
Percentile maximum.
discard_zeros : ... | a273db14c8f651dcbdaa39825e1150bd0cdc119b | 9,431 |
async def payment_list(request):
"""
---
description: Show outgoing payments, regarding {bolt11} or {payment_hash} if set Can only specify one of {bolt11} or {payment_hash}
tags:
- payments
produces:
- application/json
parameters:
- in: body
name: body
required: false
... | 3a4fe428adb10dd53e9b2564fea59cdc4b7c87ff | 9,432 |
import io
def write_opened(dir, file_dict, data_dict, verbose=True):
"""
read in dictionary with open files as values
and write data to files
"""
for game_id, vals in data_dict.items():
f = file_dict.get(game_id)
if not f:
fn = dir + str(game_id) + ".csv"
f... | eb3ac9b95b70df31eb1ea24b94b5e416966b7bc5 | 9,433 |
def get_accessible_cases(item, user):
"""Return all accessible for a cohort and user."""
return getattr(item, "get_accessible_cases_for_user")(user) | 42d54ebf672ce401ac311f9868f6b19f93418065 | 9,434 |
def aux_conv5(A, B, n, idx):
"""
Performs the convolution of A and B where B = A* (enumerate-for-loop)
:param A: Coefficients matrix 1 (orders, buses)
:param B: Coefficients matrix 2 (orders, buses)
:param c: last order of the coefficients in while loop
:param indices: bus indices array
:ret... | 0acaece3da86ac578672b7ab7e0f506117e752d3 | 9,435 |
def plot_phaseogram(phaseogram, phase_bins, time_bins, unit_str='s', ax=None,
**plot_kwargs):
"""Plot a phaseogram.
Parameters
----------
phaseogram : NxM array
The phaseogram to be plotted
phase_bins : array of M + 1 elements
The bins on the x-axis
time_bi... | b7a3b8aa0cf6a16e67e3d5059049082b6d308d7e | 9,436 |
def load_rapidSTORM_track_header(path):
"""
Load xml header from a rapidSTORM (track) single-molecule localization file and identify column names.
Parameters
----------
path : str, bytes, os.PathLike, file-like
File path for a rapidSTORM file to load.
Returns
-------
list of st... | 584baa4bd0a634608bb2c254314ad80a9c7650de | 9,437 |
def hex_to_byte(hexStr):
""" Convert hex strings to bytes. """
bytes = []
hexStr = ''.join(hexStr.split(" "))
for i in range(0, len(hexStr), 2):
bytes.append(chr(int(hexStr[i:i + 2], 16)))
return ''.join(bytes) | a424d65b0a02c0d10ee5c7c25409f4a0ce477528 | 9,438 |
def _vital_config_update(cfg, cfg_in):
"""
Treat a vital Config object like a python dictionary
Args:
cfg (kwiver.vital.config.config.Config): config to update
cfg_in (dict | kwiver.vital.config.config.Config): new values
"""
# vital cfg.merge_config doesnt support dictionary input
... | 35a0092013229f3b71a1ba06bbb660f861ef391c | 9,439 |
def SubscriberReceivedStartEncKeyVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartEncKeyVector(builder, numElems) | 7c2875af0ba92e66f747bdeb2754f3123c337372 | 9,440 |
import struct
def _read_extended_field_value(value, rawdata):
"""Used to decode large values of option delta and option length
from raw binary form."""
if value >= 0 and value < 13:
return (value, rawdata)
elif value == 13:
return (rawdata[0] + 13, rawdata[1:])
elif value == 14:... | 12a1f665f133f6ea5ffc817bf69ec0a9e0e07dbc | 9,441 |
def add_uint(a, b):
"""Returns the sum of two uint256-ish tuples."""
a = from_uint(a)
b = from_uint(b)
c = a + b
return to_uint(c) | 0da42542210e72f30f00b1a41919cdad882963d0 | 9,442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.