content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
from typing import Dict
def prepare_answer_extraction_samples(context: str, answer_list: List[Dict] = None):
"""
Args:
context: str (assumed to be normalized via normalize_text)
answer_list: [
{'text': str, 'answer_start': int},
{'text': str, 'an... | 3cb431fa2ec6472f3e060cb7f85eb0a52cfbfe6c | 23,309 |
from typing import Optional
from typing import Callable
from typing import List
import abc
def mix_in(
source: type,
target: type,
should_copy: Optional[Callable[[str, bool], bool]] = None,
) -> List[str]:
"""
Copy all defined functions from mixin into target. It could be
usefull when you cann... | 702552f01d4a915f11d6d3d618aaf151bf5b8af3 | 23,310 |
def get_img_num_per_cls(cifar_version, imb_factor=None):
"""
Get a list of image numbers for each class, given cifar version
Num of imgs follows emponential distribution
img max: 5000 / 500 * e^(-lambda * 0);
img min: 5000 / 500 * e^(-lambda * int(cifar_version - 1))
exp(-lambda * (int(cifar_ver... | 941be25ed96ef336e11c16bd9b81f2973c25bcf2 | 23,311 |
def xml():
"""
Returns the lti.xml file for the app.
"""
try:
return Response(render_template(
'lti.xml'), mimetype='application/xml'
)
except:
app.logger.error("Error with XML.")
return return_error('''Error with XML. Please refresh and try again. If this... | c40ffb52e4931fd41e6627778331a1c7acf9558b | 23,312 |
def log_get_level(client):
"""Get log level
Returns:
Current log level
"""
return client.call('log_get_level') | 2a3915d8c6576187a0af738d3021d495b4efda21 | 23,313 |
def cal_pivot(n_losses,network_block_num):
"""
Calculate the inserted layer for additional loss
"""
num_segments = n_losses + 1
num_block_per_segment = (network_block_num // num_segments) + 1
pivot_set = []
for i in range(num_segments - 1):
pivot_set.append(min(num_block_per_se... | d23324fc39f2f1aeec807a4d65a51234a2b76cde | 23,314 |
import asyncio
async def scan_host(
host: IPv4Address,
semaphore: asyncio.Semaphore,
timeout: int,
verbose: bool,
):
"""
Locks the "semaphore" and tries to ping "host" with timeout "timeout" s.
Prints out the result of the ping to the standard output.
"""
async with semaphore:
... | 66bd0165dbbb7b717fd6ded19c78cb901f89a588 | 23,315 |
def _emit_post_update_statements(
base_mapper, uowtransaction, cached_connections, mapper, table, update
):
"""Emit UPDATE statements corresponding to value lists collected
by _collect_post_update_commands()."""
needs_version_id = (
mapper.version_id_col is not None
and mapper.version_i... | 13444703b45030a2d0e1dc1f2371a729cd812c11 | 23,316 |
import copy
def build_grid_search_config(params_dict):
"""
传入一个json,按网格搜索的方式构造出符合条件的N个json, 目前网格搜索只作用在optimization范围内
:param params_dict:
:return: param_config_list
"""
model_params_dict = params_dict.get("model")
opt_params = model_params_dict.get("optimization", None)
if not opt_para... | a5f2b8249f9a50cad7da855d6a49a3225715fb00 | 23,317 |
def cutoff_countmin_wscore(y, scores, score_cutoff, n_cm_buckets, n_hashes):
""" Learned Count-Min (use predicted scores to identify heavy hitters)
Args:
y: true counts of each item (sorted, largest first), float - [num_items]
scores: predicted scores of each item - [num_items]
score_cut... | 99ab1b6174d49ccf4f4517fe713f98cecd65d978 | 23,318 |
def test_lcc_like_epi():
"""
Takes about 5 mins with epicyclic
If burnin is too short (say 200 steps) won't actually find true solution
"""
TORB_FUNC = trace_epicyclic_orbit
mean_now = np.array([50., -100., 25., 1.1, -7.76, 2.25])
age = 10.
mean = TORB_FUNC(mean_now, times=-age)
dx... | 43583e06741632aba41400ee1a6562cd6fc226be | 23,319 |
import numpy as np
def uniquePandasIndexMapping(inputColumn):
"""quickly mapps the unique name entries back to input entries
Keyword arguments:
inputDataToAssess -- a SINGLE column from a pandas dataframe, presumably with
duplications. Will create a frequency table and a mapping back to the sou... | c26fce9b8617963737c4b8dd05c0e8429c92daa3 | 23,320 |
def non_max_suppression(boxlist, thresh, max_output_size, scope=None):
"""Non maximum suppression.
This op greedily selects a subset of detection bounding boxes, pruning
away boxes that have high IOU (intersection over union) overlap (> thresh)
with already selected boxes. Note that this only works for a sing... | aa8990ea579ed5d4614561b617717c9e7b73f798 | 23,321 |
def gen_weekly_ccy_df( start,end ):
""" Generate weekly ccy data table
"""
currency_li =[ "USD_Index",
"EURUSD","GBPUSD","AUDUSD","CADUSD",
"JPYUSD",
"CNYUSD","HKDUSD","TWDUSD",
"KRWUSD","THBUSD","SGDUSD","MYRUSD",
... | cf856535d148378826fd99a6d8afef5e1eb77778 | 23,323 |
def demean_and_normalise(points_a: np.ndarray,
points_b: np.ndarray):
"""
Independently centre each point cloud around 0,0,0, then normalise
both to [-1,1].
:param points_a: 1st point cloud
:type points_a: np.ndarray
:param points_b: 2nd point cloud
:type points_b: ... | 249bb8edf5ef423613748f0ce599c98e4f437960 | 23,324 |
import yaml
import six
def ParseCustomLevel(api_version):
"""Wrapper around ParseCustomLevel to accept api version."""
def VersionedParseCustomLevel(path):
"""Parse a YAML representation of custom level conditions.
Args:
path: str, path to file containing custom level expression
Returns:
... | e5e414ea29324233d4fc8291f0ea829176805d99 | 23,325 |
def specMergeMSA(*msa, **kwargs):
"""Returns an :class:`.MSA` obtained from merging parts of the sequences
of proteins present in multiple *msa* instances. Sequences are matched
based on species section of protein identifiers found in the sequence labels.
Order of sequences in the merged MSA will fol... | fdb605347bdc88df4c844fa8765640dc5a91b88d | 23,326 |
def parse(filePath):
"""
Returns a full parsed Maya ASCII file.
:type filePath: str
:rtype: mason.asciiscene.AsciiScene
"""
return asciifileparser.AsciiFileParser(filePath).scene | 2f7d50724fcda1d4ef240e362ae6ee3f18bdfacd | 23,327 |
def d_psi(t):
"""Compute the derivative of the variable transform from Ogata 2005."""
t = np.array(t, dtype=float)
a = np.ones_like(t)
mask = t < 6
t = t[mask]
a[mask] = (np.pi * t * np.cosh(t) + np.sinh(np.pi * np.sinh(t))) / (
1.0 + np.cosh(np.pi * np.sinh(t))
)
return a | 8b0fc652a60d2ba45623bc098b7e9d0fae2c7dbe | 23,330 |
from typing import Dict
from typing import Any
import io
def build_environ(request: HTTPRequest, errors: Errors) -> Dict[str, Any]:
"""
参考 https://www.python.org/dev/peps/pep-3333/ 构建 environ
"""
headers = {
f"HTTP_{k.upper().replace('-','_')}": v for k, v in request.header.items()
}
e... | b2e98d726bf256b06d1c2f82679bd75ada7181cf | 23,331 |
def loadPage(url, filename):
"""
作用:根据url发送请求,获取服务器响应文件
url: 需要爬取的url地址
filename : 处理的文件名
"""
print "正在下载 " + filename
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"}
... | 7250a42d03bc1af7e9f30aa22198f3d4a56605f3 | 23,332 |
def get_exporter_class():
"""Returns exporter class based on preferences and support."""
if _use_xlsx() is True:
return XLSXExporter
else:
return CSVExporter | 3d66e0e0abe8c936e2f86598427ff27180dac6b4 | 23,333 |
def get_twitter_token():
"""This is used by the API to look for the auth token and secret
it should use for API calls. During the authorization handshake
a temporary set of token and secret is used, but afterwards this
function has to return the token and secret. If you don't want
to store this in... | 218f16141473e76c4318870bec9516c77f1dfe1b | 23,334 |
def is_text_serializer(serializer):
"""Checks whether a serializer generates text or binary."""
return isinstance(serializer.dumps({}), str) | f08f40662da7fd34f5984028e601d664cac943df | 23,335 |
def plot_power(ngroups, mesh_shape, directory, mode="show"):
"""Plot the integrated fission rates from OpenMC and OpenMOC, as well as
the relative and absolute error of OpenMOC relative to OpenMC.
Parameters:
-----------
ngroups: int; number of energy groups
mesh_shape: str; name of the mesh shape
di... | e9db852e840d2f3f8013f006acc191276a74e9d7 | 23,336 |
def glDeleteFramebuffersEXT( baseOperation, n, framebuffers=None ):
"""glDeleteFramebuffersEXT( framebuffers ) -> None
"""
if framebuffers is None:
framebuffers = arrays.GLuintArray.asArray( n )
n = arrays.GLuintArray.arraySize( framebuffers )
return baseOperation( n, framebuffers ) | 514fe96d8088210bfe1251a8a9c7c93856f19504 | 23,337 |
def backtostr(dayback=1, format="%Y/%m/%d", thedate=date.today()):
"""Print backto datetime in string format."""
return(backto(dayback=dayback, thedate=thedate).strftime(format)) | c79b10962537d9eef939e7f49697275f31e900e2 | 23,339 |
def no_conflict_require_POST(f):
"""
Catches resource conflicts on save and returns a 409 error.
Also includes require_POST decorator
"""
@require_POST
@wraps(f)
def _no_conflict(*args, **kwargs):
try:
return f(*args, **kwargs)
except ResourceConflict:
... | 98a28b5fbc2824eaa5d5020f8be1d55878974fc4 | 23,340 |
def Transition_rep(source_State_name, target_State_name):
"""Representation of a transition
:param source_State_name: The sequence of "name" values of State objects referred to by attribute "source" in this Transition
:type source_State_name: Array
:param target_State_name: The sequence of "name" value... | 2e5f7048722997e0931fd6ec3a2d9e880a160359 | 23,342 |
from typing import List
from typing import Any
def search_model(trial: optuna.trial.Trial) -> List[Any]:
"""Search model structure from user-specified search space."""
model = []
n_stride = 0
MAX_NUM_STRIDE = 5
UPPER_STRIDE = 2 # 5(224 example): 224, 112, 56, 28, 14, 7
n_layers = trial.sugges... | 228180bc1f02c793273a763db271889f4dcd4f26 | 23,344 |
def create_search_forms(name, language_code, script_code):
"""Return a list of names suitable for searching.
Arguments:
name -- string name
language_code -- string code of language
script_code -- string code of script
"""
# QAZ: It would be useful if something could be done here (or
# ... | a417fe9ab37e544c094341fcb7f1249feaed43c6 | 23,345 |
def iv_params(*, N_s, T_degC, I_ph_A, I_rs_1_A, n_1, I_rs_2_A, n_2, R_s_Ohm, G_p_S,
minimize_scalar_bounded_options=minimize_scalar_bounded_options_default,
newton_options=newton_options_default):
"""
Compute I-V curve parameters.
Inputs (any broadcast-compatible combination of ... | 7998b52f02482d79bae6c0732e99ed5e151326fa | 23,346 |
def update_domain(
uuid, name=None, disabled=None, project_id=None, user_id=None):
"""Update an existing domain."""
res = get_domain(uuid=uuid)
if disabled is not None:
res['disabled'] = disabled
if name is not None:
res['name'] = name
if project_id is not None:
res[... | 7cdc53c96e17d79dd0998165b87dd745b8afd73e | 23,348 |
def ja_of(tree: Tree) -> str:
"""tree string in the Japanese CCGBank's format
Args:
tree (Tree): tree object
Returns:
str: tree string in Japanese CCGBank's format
"""
def rec(node):
if node.is_leaf:
cat = node.cat
word = normalize(node.word)
... | 7722e9de3b31354be4820cc32a8949ffac333e5f | 23,349 |
def cut_flowlines_at_points(flowlines, joins, points, next_lineID):
"""General method for cutting flowlines at points and updating joins.
Only new flowlines are returned; any that are not cut by points are omitted.
Parameters
----------
flowlines : GeoDataFrame
joins : DataFrame
flowli... | e535f6d5e073955b74784f5ce3121a929f9bc200 | 23,350 |
def export(gen, directory, file_prefix='{uid}-', **kwargs):
"""
Export a stream of documents to nxstxm_baseline.
.. note::
This can alternatively be used to write data to generic buffers rather
than creating files on disk. See the documentation for the
``directory`` parameter below... | ec1b1237f63fc29c8e8d1b14283b392523e86426 | 23,351 |
def services():
"""
Returns the grader-notebook list used as services in jhub
Response: json
example:
```
{
services: [{"name":"<course-id", "url": "http://grader-<course-id>:8888"...}],
groups: {"formgrade-<course-id>": ["grader-<course-id>"] }
}
```
"""
service... | b1fbc2c90b344f75027538037c5d6786bda810c8 | 23,353 |
def chunks(l, k):
"""
Take a list, l, and create k sublists.
"""
n = len(l)
return [l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)] for i in range(k)] | 7cf0c39941ed8f358c576046154af6b3ee54b70a | 23,354 |
def bfs(adj, src, dst, cache=None):
"""BFS search from source to destination. Check whether a path exists, does
not return the actual path.
Work on directed acyclic graphs where we assume that there is no path to the
node itself.
Args:
adj: Adjacency matrix.
src: Source node index, 0-based.
dst: ... | 5e224ffa575dd0bd471142023e828a8e36d1782e | 23,355 |
import _ast
import ast
def get_source_ast(name: str) -> _ast.Module:
"""
Return ast of source code
"""
with open(name, "r") as f:
data = f.read()
return ast.parse(data) | 8e0826175df538bdd894f05b0c6cf143b0b0f69b | 23,356 |
import math
def floor(base):
"""Get the floor of a number"""
return math.floor(float(base)) | 8b00ffccf30765f55ff024b35de364c617b4b20c | 23,358 |
def TranslateSecureTagsForFirewallPolicy(client, secure_tags):
"""Returns a list of firewall policy rule secure tags, translating namespaced tags if needed.
Args:
client: compute client
secure_tags: array of secure tag values
Returns:
List of firewall policy rule secure tags
"""
ret_secure_tags... | 5cbf71885c167d5c9d0dcae3294be017512db73a | 23,359 |
from typing import Callable
from typing import Dict
from typing import Any
import functools
def memoize(func: Callable):
"""
A decorator that memoizes a function by storing its inputs and outputs.
Calling the function again with the same arguments will return the cached
output.
This function is s... | 7ba9500c57c867abcb43bf5ffe58087270ebef08 | 23,361 |
def mini_batch(positive_rdd, negative_rdd, num_iterations):
"""get the positive and negative classes with index for mini-batch"""
# mini-batch preparation
pos_num = int(batch_size / 46)
neg_num = pos_num * 45
i = num_iterations % int(74 / pos_num)
# get the new mini-batch rdd for this iteration
new_rdd = positi... | e523c170d66cf9bdabf5f12ab78af417c59333a2 | 23,362 |
import math
def draw_polygon(img, max_sides=8, min_len=32, min_label_len=64):
""" Draw a polygon with a random number of corners and return the position
of the junctions + line map.
Parameters:
max_sides: maximal number of sides + 1
"""
num_corners = random_state.randint(3, max_sides)
... | 1dc1cdb18424c8d47ee95777d52713c884eedc5d | 23,363 |
def order_budget_update(request, order_id):
"""
Update budget for order
"""
serializer = OrderBudgetSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
order = get_object_or_404(Order, pk=order_id)
budget = serializer.validated_data['budget']
order.bud... | adc708d7cbc429ea6e5d81c5f9db60d0fa5f298a | 23,364 |
def analyse_readability_metrics(article_text):
"""
Use the textstat library to report multiple readability measures.
The readability metrics analysed are:
* The Flesch Reading Ease Score. A score from 100 (very easy to read) to 0 (very confusing).
* The grade score using the Flesch-Kincaid Grade Fo... | 32a89cf4788d469a164f9cdd606f1675ddf219b8 | 23,365 |
def dx(data):
"""
Derivative by central difference
Edges are takes as difference between nearest points
Parameters
----------
data : ndarray
Array of NMR data.
Returns
-------
ndata : ndarray
Derivate of NMR data.
"""
z = np.empty_like(data)
z[..., 0] ... | 6e88618750ff69662ec7f41ecfc50efbaab717db | 23,366 |
def grad(w):
""" Dao ham """
N = Xbar.shape[0]
return 1/N * Xbar.T.dot(Xbar.dot(w) - y) | 8bcce8c10eeb7ffae6e2af3e2f273f03b6984885 | 23,367 |
import random
def random_binary():
"""
测试 cached 缓存视图的装饰器 设置 key
:return:
"""
return [random.randrange(0, 2) for i in range(500)] | 3c30014d1222c136cb7d3d2fbe6e0d972decc776 | 23,369 |
def remove_from_end(string, text_to_remove):
"""
Remove a String from the end of a string if it exists
Args:
string (str): string to edit
text_to_remove (str): the text to remove
Returns: the string with the text removed
"""
if string is not None and string.endswith(text_to_rem... | 19cebd002fcf5aea5290a6998129427363342319 | 23,370 |
def get_node_number(self, node, typ) -> str:
"""Get the number for the directive node for HTML."""
ids = node.attributes.get("ids", [])[0]
if isinstance(self, LaTeXTranslator):
docname = find_parent(self.builder.env, node, "section")
else:
docname = node.attributes.get("docname", "")
... | f88227ef727d45d14cd9343ee26bdbfb15f6a2fc | 23,372 |
def get_client(client, aws_access_key_id, aws_secret_access_key, region=None):
"""Shortcut for getting an initialized instance of the boto3 client."""
return boto3.client(
client,
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=regio... | 4ebed5da9ca146b79563c0efb5bf04e7bc13f791 | 23,374 |
import logging
import traceback
import json
def main(req: func.HttpRequest) -> func.HttpResponse:
""" main function for status/http """
logging.info('Status processed a request.')
try:
response = get_http_response_by_status(200)
if req.get_body() and len(req.get_body()):
respo... | ac464fd479c0df9f9d462f37d884542bf670dfef | 23,375 |
def _variable_map_by_name(variables):
"""
Returns Dict,representing referenced variable fields mapped by name.
Keyword Parameters:
variables -- list of 'variable_python_type' Warehouse support DTOs
>>> from pprint import pprint
>>> var1 = { 'column':'frob_hz', 'title':'Frobniz Resonance (Hz)'... | 91c27ceb84614313d036ec216ef4c4d567a68255 | 23,376 |
def true_divide(x, y):
"""Divides x / y elementwise (using Python 3 division operator semantics).
NOTE: Prefer using the Tensor operator or tf.divide which obey Python
division operator semantics.
This function forces Python 3 division operator semantics where all integer
arguments are cast to flo... | 3bdcf5052730fd2c3e2e25a395b0e16534d2dcf9 | 23,377 |
def ObjectNotFoundError(NDARError):
"""S3 object not found"""
def __init__(self, object):
self.object = object
return
def __str__(self):
return 'Object not found: %s' % self.object | 3cc552f7074f8117ed18fd975bc5ac0b09f8016a | 23,378 |
def hello():
"""
Say hello using a template file.
"""
return render_template('index.html') | b2b09afd651a69fdc270238dbf3f724fa9f40ae4 | 23,379 |
def pause_sale(ctx):
"""
Pause the token sale
:param ctx:GetContext() used to access contract storage
:return:bool Whether pausing the sale was successful
"""
if CheckWitness(TOKEN_OWNER):
Put(ctx, SALE_STATUS_KEY, SALE_PAUSED)
return True
return False | 63e99802a852146f7a20460a28a7d277c4104954 | 23,380 |
def parse_item_hash(value):
"""
Parses the item-hash datatype, e.g. sha-256:5b8e5ee02caedd0a6f3539b19d6b462dd2d08918764e7f476506996024f7b84a
:param value: a string to parse
:return: parsed value
"""
if isinstance(value, ItemHash):
return value
if not isinstance(value, str):
r... | 6275ab41d437728ea3448bf150f068668c3f1819 | 23,381 |
def __convert_swizzle_scale(scale, export_settings):
"""Convert a scale from Blender coordinate system to glTF coordinate system."""
if export_settings[gltf2_blender_export_keys.YUP]:
return Vector((scale[0], scale[2], scale[1]))
else:
return Vector((scale[0], scale[1], scale[2])) | 19c2f62c9cd3c267a3edc2451c5f0eba3208c34f | 23,382 |
from pathlib import Path
from typing import Type
from typing import cast
def load_config_from_expt_dir(experiment_dir: Path, loop_config: Type[OptimizerConfig]) -> OptimizerConfig:
"""
Locate a config file in experiment_dir or one of its subdirectories (for a per-seed config).
Config files are now normall... | 5c609b877c6c40f019d234b685caed17b287aca0 | 23,384 |
def glsadf_delay(order, stage):
"""Delay for glsadf
Parameters
----------
order : int
Order of glsadf filter coefficients
stage : int
-1 / gamma
Returns
-------
delay : array
Delay
"""
return np.zeros(_sptk.glsadf_delay_length(order, stage)) | dacf0a754ba2040ba7ae004658f02df3060c6251 | 23,385 |
def find_next(s: str)->[int]:
"""
input:string
output:the next array of string
"""
if len(s) == 1:
return [-1]
result = [0 for i in range(len(s))]
result[0] = -1
result[1] = 0
i = 2
cn = 0
while i < len(result):
if s[i-1] == s[cn]:
cn += 1
... | 455297eee28360f75a4f714172f62a7645ca49e0 | 23,386 |
from datetime import datetime
def _read_date():
""" read date from input; default to today """
# show date
while 1:
dts = prompt("Date", default=str(datetime.date.today()))
try:
datetime.datetime.strptime(dts, "%Y-%m-%d")
break
except ValueError:
... | 45cd0e68cc6ca14552c2e2953edd2cc15809f122 | 23,387 |
def handle_pending_submission(self, request, layout=None):
""" Renders a pending submission, takes it's input and allows the
user to turn the submission into a complete submission, once all data
is valid.
This view has two states, a completable state where the form values
are displayed without a fo... | b591246498c22d6079181654a94b4cd6290732ec | 23,388 |
import functools
def i18n_view(tpl_base_name=None, **defaults):
"""
Renders a template with locale name as suffix. Unlike the normal view
decorator, the template name should not have an extension. The locale names
are appended to the base template name using underscore ('_') as separator,
and lowe... | 46c33f2be90fb9cca8059ba1f13f97c3e5a61807 | 23,389 |
def git_file_list(path_patterns=()):
"""Returns: List of files in current git revision matching `path_patterns`.
This is basically git ls-files.
"""
return exec_output_lines(['git', 'ls-files', '--exclude-standard'] + path_patterns, False) | 0c8cf1a3570d39e6d5c7f1658fd85b6ef2938d8a | 23,390 |
def unreserve_id():
"""
Removes the reservation of a SCSI ID as well as the memo for the reservation
"""
scsi_id = request.form.get("scsi_id")
reserved_ids = get_reserved_ids()["ids"]
reserved_ids.remove(scsi_id)
process = reserve_scsi_ids(reserved_ids)
if process["status"]:
RESE... | 6665297f37420a5ad3498f9aa9a705f5b8f1830f | 23,391 |
def integral_sqrt_a2_minus_x2(x, a):
"""Integral of $\sqrt(a^2 - x^2)$ --- see (30) at
http://integral-table.com.
"""
return 0.5*x*np.sqrt(a**2 - x**2) + 0.5*a**2*np.arctan2(x, np.sqrt(a**2 - x**2)) | 778a5dc745c62727f192616448b6c98da3d93b5c | 23,392 |
def read_length(file_obj): # pragma: no cover
""" Numpy trick to get a 32-bit length from four bytes
Equivalent to struct.unpack('<i'), but suitable for numba-jit
"""
sub = file_obj.read(4)
return sub[0] + sub[1]*256 + sub[2]*256*256 + sub[3]*256*256*256 | 82c311c3a8e2d2e277979c19aaae665b0227f9cd | 23,393 |
import json
def ifttt_comparator_alpha_options():
""" Option values for alphanumeric comparators """
errmsg = check_ifttt_service_key()
if errmsg:
return errmsg, 401
data = {"data": [
{"value": "ignore", "label": "ignore"},
{"value": "equal", "label": "is equal to"},
{... | d04d1f421eeda42324372702b7caf1777dfba964 | 23,396 |
def flat_abs_maximum(data, preserve_sign=True):
"""
Function to return the absolute maximum value in an array. By default,
this function will preserve the sign, meaning that if an array contains [-75, -25, 0, 25, 50]
then the function will return -75 because that value has the highest magnitude but it w... | 6276c874ba9e1dcd047b087f6954a11ee3b680a9 | 23,397 |
def get_image_to_groundplane_homography(P):
"""Given the 3x4 camera projection matrix P, returns the homography
mapping image plane points onto the ground plane."""
return np.linalg.inv(get_groundplane_to_image_homography(P)) | 189bb5b80243c9145065260c591fe00c29a9a947 | 23,398 |
import logging
def create_object_detection_edge_training(
train_object_detection_edge_model_request: TrainImageEdgeModel,
):
"""[Train a Object Detection Model for Edge in AutoML GCP]
Args:
train_object_detection_edge_model_request (TrainImageEdgeModel): [Based on Input Schema]
Raises:
... | afff20623b96195294740056de6e327add72148f | 23,399 |
from typing import List
def readOneLineFileWithCommas(filepath: str) -> List[str]:
"""
Reads a file that is one line long, separated by commas
"""
try:
with open(filepath) as fp:
s: str = fp.readline()
return s.split(",")
except:
raise Exception(f"Failed to open {filepath}... | 4c181523192fab0ea01ae5da0883c543565119c6 | 23,400 |
from operator import or_
def package_search(filters, context, limit=None, catalog=False):
"""Search packages with different filters
Catalog param controls the base query creation. Catalog queries
only search packages a user can deploy. Non-catalog queries searches
packages a user can edit.
... | 0d15d2936f713437e3d9dad794cd07faf1ca3090 | 23,401 |
def _jitter_boxes(gt_boxes, jitter=0.05):
"""
"""
jittered_boxes = gt_boxes.copy()
ws = jittered_boxes[:, 2] - jittered_boxes[:, 0] + 1.0
hs = jittered_boxes[:, 3] - jittered_boxes[:, 1] + 1.0
width_offset = (np.random.rand(jittered_boxes.shape[0]) - 0.5) * jitter * ws
height_offset = (np.ra... | 570fa7a6bd2f898ce1d64dd9f6e666e50251fcf5 | 23,403 |
def lcm_gcd(a, b):
"""Finds the least common multiple of two integers
Args:
a, b: integers greater than or equal to 1
"""
return a * b//greatest_common_divisor(a, b) | 3b23d04164c8e69eee26e48ab2b1a60e8e99fd14 | 23,405 |
def test_ahocorasick_rs_overlapping(benchmark, test_data):
"""ahocorasick_rs overlapping matches."""
patterns, haystacks = test_data
ac = ahocorasick_rs.AhoCorasick(patterns)
def run():
for haystack in haystacks:
x = ac.find_matches_as_strings(haystack, overlapping=True)
ret... | 3c53369e8006502a5071fb73a75ace4705421a84 | 23,406 |
import warnings
def merge_frames(frames):
"""
Merge the multiple data files downloaded from the M2M system or the Gold
Copy THREDDS server into a single xarray data set. Keep track of how many
files fail to merge.
:param frames: The data frames to concatenate/merge into a single data set
:ret... | b8b083d8f0e9360df325fbeb812b64fffc8d1d0f | 23,407 |
import re
def sorted_nicely(l):
""" This function sorts the given iterable in the way that is expected
Obtained from:
https://arcpy.wordpress.com/2012/05/11/sorting-alphanumeric-strings-in-python/
:param l: The iterable to be sorted
:return: Sorted iterable
"""
convert =... | c2e398e7a654a1a1ec7cc113fcad500beefd876a | 23,408 |
def run_board(effects: list, audio: np.array, sample_rate: float) -> np.array:
"""Run board on input audio data.
Args:
board (list): List of Pedalboard effects.
audio (np.array): Input audio data.
Returns:
Output (effected) audio data
"""
board = Pedalboard(effects, sample_... | 062f7d34aa7eadad5401e64df1e96857606cbcf6 | 23,409 |
def html_escape( s ):
"""
"""
s = s.replace( '&', '&' )
s = s.replace( '<', '<' )
s = s.replace( '>', '>' )
return s | eb47ba4d4651763cb74f081095b78d53ee9bebc1 | 23,410 |
def model_query(context, model, *args, **kwargs):
"""Query helper.
:param context: context to query under
:param session: if present, the session to use
"""
session = kwargs.get('session') or object_sqla.get_session()
query = session.query(model, *args)
return filter_by_project(context, q... | c6e5fb09b7e9a4d85ab6c6abc1e03e227010591f | 23,411 |
def bert_dropout_model(num_classes,
bert_config,
use_mc_dropout_mha=False,
use_mc_dropout_att=False,
use_mc_dropout_ffn=False,
use_mc_dropout_output=False,
channel_wise_dropout_mha=F... | 6ee1d09b2070e54ba631bd6e1b8e3e453960073a | 23,412 |
def calculate_monthly_sales(year: int, month: int, beer_style: str) -> int:
"""Calculates the sales of a particular type of beer in a given month.
param: month -- an int ranges from 1 to 12, beer_style;
return: total_sales
"""
total_sales = 0
for item in data:
if item[2].year =... | fa448a8e9dfb7186652a6dc3000d3a8465320994 | 23,413 |
def check_canopy_height(region_info, regional_lookup):
"""
Check the regional canopy height.
"""
mean_canopy_height = region_info['mean_canopy_height']
if mean_canopy_height == 'no data':
mean_canopy_height = 0
return mean_canopy_height | 5f04ad71df7f0b1c9ef73e97bbe99bea1916ae5e | 23,414 |
def annotated_var(prs):
"""
Parser for annotated variable in parentheses.
Annotation is parsed with prs.
Parser output is a var token
annotation is stored in attribute 'annotation' of var token.
Sample input to parser:
(x : A)
"""
def trt(acc):
v,ann = acc
... | 42acdf6eb09952701d17fab73a2ee8fc20c7dc5e | 23,415 |
def action_from_json(project, value):
"""return a action from the given json
"""
json_type = value.get('type')
for class_ in sftoolbox.engine.action_classes_register:
if json_type == class_.json_type:
return class_.from_json(project, value)
return DummyAction.from_json(project, ... | 69658b53e839c7d112b7509e3ecdf57a82de817a | 23,416 |
def get_springer_doi(node):
"""
:param node:
:return:
"""
for elem in find_key(node, 'occurrence'):
if isinstance(elem, list):
for sub_elem in elem:
if isinstance(sub_elem, dict):
values = sub_elem.values()
if len(values) =... | ca8773f10e6fed6b41064a5a5ad6717afd540bb5 | 23,417 |
def check_versions(versions=[]):
""" Check if there are version to build the changelog. """
if len(versions) == 0:
raise NotEnoughVersionsError()
return True | f9c7f81c02f08a867f27f329554ed85eddc34243 | 23,418 |
def create_fnet(widths, nfeat, nfeato, orthoinit, llbias):
""" Creates feature-generating network, a multi-layer perceptron.
Parameters:
widths: list of widths of hidden layers
nfeat, nfeato: # input and output channels of the convolution
orthoinit: whether to use orthogonal weight initialization
... | 3bdfdd89d77b6ba172e2ac85df191b11e78ab049 | 23,419 |
def pytorch_array_setitem(op):
"""Implementation of array_setitem for pytorch."""
def _impl(array, begin, end, strides, value):
idx = tuple(slice(b, e, s) for b, e, s in zip(begin, end, strides))
ret = array.clone()
ret[idx] = value
return (ret,)
return _impl, op.inputs[1:] | b0c6504b2c0d1971ec16e5fdf198b20a911d4946 | 23,420 |
def time_series_seasonal_test(x: pd.Series, expected_lags: list):
"""
通过自相关系数来获取不同lag的相关系数,通过相关系数来判断时序数据的周期值
PS:需要列出lag的值的列表
:param x: 时序数据x,type: Series
:param expected_lags: 可供选择的的滞后值
:return: 返回滞后值值的自相关性排序序列
"""
acf_scores = []
for lag in expected_lags:
acf_score = acf(x.v... | 5c0614b986eb8dfe576821245e80ef0244c70c69 | 23,421 |
def comment_like():
"""
- 1.判断用户是否登陆
- 2.获取参数
- 3.校验参数,为空校验
- 4.操作类型校验
- 5.根据评论编号取出,评论对象
- 6.判断评论对象是否存在
- 7.根据操作类型,点赞,取消点赞
- 8.返回响应
:return:
"""
# - 1.判断用户是否登陆
if not g.user:
return jsonify(errno=RET.NODATA, errmsg="用户未登录")
# - 2.获取参数
comment_id = req... | 09564653f3d843c7d82e16946507c8a081374ce6 | 23,422 |
def create_relationships(model_cls, data):
"""
Create the relationship dict of the specified model class with the data
:param model_cls:
:param data:
:return:
"""
relationships = model_cls.get_relationships()
relationship_map = {}
for key in relationships.keys():
relationship... | 6ed811b180141190cde5eaa20d4fca817647c970 | 23,424 |
import requests
def get_news_items_from_web(url):
"""
Calls the Athletics News RSS API, parses the resulting response and returns a list of parsed news_items to be
stored in DynamoDB
:param url: Url for the RSS API for UBCO Heat
:return: Parsed news items in a JSON formatted list
"""
try:... | aff75310b155475d185f15c5bbaadeda9902aae3 | 23,425 |
def get_node_model(manager, handle_id=None, node=None):
"""
:param manager: Context manager to handle transactions
:type manager: Neo4jDBSessionManager
:param handle_id: Nodes handle id
:type handle_id: str|unicode
:param node: Node object
:type node: neo4j.v1.types.Node
:return: Node mo... | a8c42b8e72b6ae96e897bd5c7f5a06b5820b4b56 | 23,426 |
from functools import reduce
def convert_hcp_plane(plane: list) -> np.ndarray:
"""
four index notion to three index notion for hcp and rhombohedral plane
Args:
plane (list): four index notion
Returns:
three index notion of plane
"""
u1 = plane[0]
v1 = plane[1]
w1 = p... | aa6d7527a55d8b14bd03b2f6660ed94c8cf760a8 | 23,427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.