content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def passwordbox(**kwargs):
"""
This wrapper is for making a dialog for changing your password.
It will return the old password, the new password, and a confirmation.
The remaining keywords are passed on to the autobox class.
"""
additional_fields = kwargs.get("additional_fields") and kwar... | ff38d854a8d7303bbf58654e220c0b24b3ede105 | 3,652,313 |
def unravel_hpx_index(idx, npix):
"""Convert flattened global map index to an index tuple.
Parameters
----------
idx : `~numpy.ndarray`
Flat index.
npix : `~numpy.ndarray`
Number of pixels in each band.
Returns
-------
idx : tuple of `~numpy.ndarray`
Index array... | c7fa097ffeae3219d59526ed76d62383277d317b | 3,652,314 |
def parse_revdep(value):
"""Value should be an atom, packages with deps intersecting that match."""
try:
targetatom = atom.atom(value)
except atom.MalformedAtom as e:
raise argparser.error(e)
val_restrict = values.FlatteningRestriction(
atom.atom,
values.AnyMatch(values.F... | eb2118af7644fac15fa4ebedba6684d20ab18d47 | 3,652,316 |
def is_context_word(model, word_a, word_b):
"""Calculates probability that both words appear in context with each
other by executing forward pass of model.
Args:
model (Mode): keras model
word_a (int): index of first word
word_b (int): index of second word
"""
# define ... | a7b0642cfc97b21e53f8b42eaddbed69689a0f1d | 3,652,317 |
def next_method():
"""next, for: Get one item of an iterators."""
class _Iterator:
def __init__(self):
self._stop = False
def __next__(self):
if self._stop:
raise StopIteration()
self._stop = True
return "drums"
return next(_... | 85cdd08a65ae66c2869ba2067db81ff37f40d0b8 | 3,652,319 |
import json
def get_ingress_deployment(
serve_dag_root_node: DAGNode, pipeline_input_node: PipelineInputNode
) -> Deployment:
"""Return an Ingress deployment to handle user HTTP inputs.
Args:
serve_dag_root_node (DAGNode): Transformed as serve DAG's root. User
inputs are translated t... | 33f7ca9218e59af168fccdd8e0d0392964febaf2 | 3,652,320 |
def get_project_settings(project):
"""Gets project's settings.
Return value example: [{ "attribute" : "Brightness", "value" : 10, ...},...]
:param project: project name or metadata
:type project: str or dict
:return: project settings
:rtype: list of dicts
"""
if not isinstance(project... | 298d00eedff7c70ae8745e47f2eff48642988c7b | 3,652,321 |
def guard(M, test):
"""Monadic guard.
What it does::
return M.pure(Unit) if test else M.empty()
https://en.wikibooks.org/wiki/Haskell/Alternative_and_MonadPlus#guard
"""
return M.pure(Unit) if test else M.empty() | 9184310fcebec10ca1cc7cdb25e36831b327cbb0 | 3,652,322 |
def get_git_hash() -> str:
"""Get the git hash."""
rv = _run("git", "rev-parse", "HEAD")
if rv is None:
return "UNHASHED"
return rv | 978eca015aeb534e500dbbc5e9ab7aad5b487865 | 3,652,323 |
def primary_style():
""" a blue green style """
return color_mapping(
'bg:#449adf #ffffff',
'bg:#002685 #ffffff',
'#cd1e10',
'#007e3a',
'#fe79d1',
'#4cde77',
'#763931',
'#64d13e',
'#7e77d2',
'bg:#000000 #ffffff',
) | aecbe4cccb18763cf961ba08d6d9c04188080989 | 3,652,324 |
def decrypt_files(rsa_key):
"""
Decrypt all encrypted files on host machine
`Required`
:param str rsa_key: RSA private key in PEM format
"""
try:
if not isinstance(rsa_key, Crypto.PublicKey.RSA.RsaKey):
rsa_key = Crypto.PublicKey.RSA.importKey(rsa_key)
if not rsa... | ccc5d253b5ab7a7851195751a798ba4e18fef983 | 3,652,325 |
def _bivariate_uc_uc(
lhs,rhs,
z,
dz_dl, # (dz_re_dl_re, dz_re_dl_im, dz_im_dl_re, dz_im_dl_im)
dz_dr # (dz_re_dr_re, dz_re_dr_im, dz_im_dr_re, dz_im_dr_im)
):
"""
Create an uncertain complex number as a bivariate function
This is a utility method for implementing mathematical
function... | f3b2c778cd1152910c951e893861f0c900978a4e | 3,652,326 |
def smoothing_filter(time_in, val_in, time_out=None, relabel=None, params=None):
"""
@brief Smoothing filter with relabeling and resampling features.
@details It supports evenly sampled multidimensional input signal.
Relabeling can be used to infer the value of samples at
... | 7af0f6925d255c0445c7b5dfdfb330f4058f8afc | 3,652,327 |
def get_selector_qty(*args):
"""get_selector_qty() -> int"""
return _idaapi.get_selector_qty(*args) | 82ea62d3220893456358c42b0ec931e5c2cf9053 | 3,652,328 |
from typing import Optional
from typing import Dict
from typing import Any
import requests
def get(
host: str,
path: str,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
authenticated: bool = True,
stream: bool = False,
) -> requests.Response:
"""
Sen... | 7f0188ad2d678c0edef5d4fce623a5faee5c13db | 3,652,329 |
def inner_xml(xml_text):
"""
Get the inner xml of an element.
>>> inner_xml('<div>This is some <i><b>really</b> silly</i> text!</div>')
u'This is some <i><b>really</b> silly</i> text!'
"""
return unicode(INNER_XML_RE.match(xml_text).groupdict()['body']) | dcba13de5a75d4b9956c2a27f02a289212d9789e | 3,652,330 |
def store_tags():
"""Routing: Stores the (updated) tag data for the image."""
data = {
"id": request.form.get("id"),
"tag": request.form.get('tags'),
"SHOWN": 0
}
loader.store(data)
next_image = loader.next_data()
if next_image is None:
return redirect("/finished... | ec433586e7ad60d2b85ac8ff2ccc209f4c00a110 | 3,652,331 |
def getAssets(public_key: str) -> list:
"""
Get all the balances an account has.
"""
balances = server.accounts().account_id(public_key).call()['balances']
balances_to_return = [ {"asset_code": elem.get("asset_code"), "issuer": elem.get("asset_issuer"), "balance": elem.get("balance")} for elem in ba... | 71c1b89edd79f0dc4092b909c2d7f505b35d5391 | 3,652,332 |
def parse_pattern(format_string, env, wrapper=lambda x, y: y):
""" Parse the format_string and return prepared data according to the env.
Pick each field found in the format_string from the env(ironment), apply
the wrapper on each data and return a mapping between field-to-replace and
values for each.
... | fdd5057929ed06f5ee984019e967df45d683fb75 | 3,652,333 |
def u1_series_summation(xarg, a, kmax):
"""
5.3.2 ROUTINE - U1 Series Summation
PLATE 5-10 (p32)
:param xarg:
:param a:
:param kmax:
:return: u1
"""
du1 = 0.25*xarg
u1 = du1
f7 = -a*du1**2
k = 3
while k < kmax:
du1 = f7*du1 / (k*(k-1))
u1old = u1
... | e54cb5f68dd5ecba5dd7f540ac645ff8d70ae0e3 | 3,652,334 |
def mask_iou(masks_a, masks_b, iscrowd=False):
"""
Computes the pariwise mask IoU between two sets of masks of size [a, h, w] and [b, h, w].
The output is of size [a, b].
Wait I thought this was "box_utils", why am I putting this in here?
"""
masks_a = masks_a.view(masks_a.size(0), -1)
mas... | 585bb48b3b8460660739acd102d8a0f5e1716078 | 3,652,335 |
import torch
def normalized_grid_coords(height, width, aspect=True, device="cuda"):
"""Return the normalized [-1, 1] grid coordinates given height and width.
Args:
height (int) : height of the grid.
width (int) : width of the grid.
aspect (bool) : if True, use the aspect ratio to scal... | 7ddd1c5eda2e28116e40fa99f6cd794d9dfd48cc | 3,652,336 |
from typing import Optional
from pathlib import Path
from typing import Iterable
from typing import List
from typing import Any
import ray
import traceback
def ray_map(task: Task, *item_lists: Iterable[List[Any]], log_dir: Optional[Path] = None) -> List[Any]:
"""
Initialize ray, align item lists and map each ... | a033bb1f2d84b7a37bffd4db4643ed5c2291b3ba | 3,652,337 |
def consensus_kmeans(data=None,
k=0,
linkage='average',
nensemble=100,
kmin=None,
kmax=None):
"""Perform clustering based on an ensemble of k-means partitions.
Parameters
----------
data : array
... | 25ee74ac24883a4981db98c730c9010d13866840 | 3,652,338 |
def to_cftime(date, calendar="gregorian"):
"""Convert datetime object to cftime object.
Parameters
----------
date : datetime object
Datetime object.
calendar : str
Calendar of the cftime object.
Returns
-------
cftime : cftime object
Cftime ojbect.
"""
... | cfd968e1fd74f105ef7b44ce6700d646d4470910 | 3,652,339 |
def poly_to_mask(mask_shape, vertices):
"""Converts a polygon to a boolean mask with `True` for points
lying inside the shape. Uses the bounding box of the vertices to reduce
computation time.
Parameters
----------
mask_shape : np.ndarray | tuple
1x2 array of shape of mask to be generat... | 13dec3d1057cff4823fa989e268f5103756bc263 | 3,652,340 |
def get_nn_edges(
basis_vectors,
extent,
site_offsets,
pbc,
distance_atol,
order,
):
"""For :code:`order == k`, generates all edges between up to :math:`k`-nearest
neighbor sites (measured by their Euclidean distance). Edges are colored by length
with colors between 0 and `order - 1`... | dfc55a3696c18769bbe3d4b15f068afbc763b6bf | 3,652,341 |
import math
def unit_vector(data, axis=None, out=None):
"""Return ndarray normalized by length, i.e. eucledian norm, along axis.
>>> v0 = numpy.random.random(3)
>>> v1 = unit_vector(v0)
>>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0))
True
>>> v0 = numpy.random.rand(5, 4, 3)
>>> v1 = uni... | eb29e86d33ff576f290ea11aa6e2e6180a04d56e | 3,652,344 |
import torch
def negative_f1_score(probs, labels):
"""
Computes the f1 score between output and labels for k classes.
args:
probs (tensor) (size, k)
labels (tensor) (size, 1)
"""
probs = torch.nn.functional.softmax(probs, dim=1)
probs = probs.numpy()
labels = l... | bd308d70934ed5ada0868f454b07c0f554384f32 | 3,652,345 |
import requests
def search_usb_devices_facets():
"""Facet USB Devices"""
data = {"terms": {"fields": ["status"]}}
usb_url = USB_DEVICES_FACETS.format(HOSTNAME, ORG_KEY)
return requests.post(usb_url, json=data, headers=HEADERS) | d4f09b8374fe2461ac5e7c121822287bf8e80494 | 3,652,346 |
import struct
def pack4(v):
"""
Takes a 32 bit integer and returns a 4 byte string representing the
number in little endian.
"""
assert 0 <= v <= 0xffffffff
# The < is for little endian, the I is for a 4 byte unsigned int.
# See https://docs.python.org/2/library/struct.html for more info.
... | bbaeb0026624a7ec30ec379466ef11398f93d573 | 3,652,347 |
def index():
"""
"""
category = Category.get_categories()
pitch = Pitch.get_all_pitches()
title = "Welcome to Pitch Hub"
return render_template('index.html', title = title, category = category, pitch =pitch) | 6758964bf9a304d62d9048e9b9248cee39d04742 | 3,652,348 |
def maximum_sum_increasing_subsequence(numbers, size):
"""
Given an array of n positive integers. Write a program to find the sum of
maximum sum subsequence of the given array such that the integers in the
subsequence are sorted in increasing order.
"""
results = [numbers[i] for i in range(size... | a684ead4dcd9acbf8c796f5d24a3bf826fb5ad9d | 3,652,349 |
def lstsqb(a, b):
"""
Return least-squares solution to a = bx.
Similar to MATLAB / operator for rectangular matrices.
If b is invertible then the solution is la.solve(a, b).T
"""
return la.lstsq(b.T, a.T, rcond=None)[0].T | 4b046896ce29b79e9edcb434b1a01c652654867c | 3,652,350 |
def multivariateGaussian(X, mu, sigma2):
"""
多元高斯分布
:param X:
:param mu:
:param sigma2:
:return:
"""
k = len(mu)
if sigma2.shape[0] > 1:
sigma2 = np.diag(sigma2)
X = X - mu
argu = (2 * np.pi) ** (-k / 2) * np.linalg.det(sigma2) ** (-0.5)
p = argu * np.exp(-0.5 * n... | 67a466318c473eef2749bf23e26d45de1149c5dc | 3,652,351 |
from datetime import datetime
def get_day(input):
"""
Convert input to a datetime object and extract the Day part
"""
if isinstance(input, str):
input = parse_iso(input)
if isinstance(input, (datetime.date, datetime.datetime)):
return input.day
return None | 8a18e1832b85faf0612667ce3431176301502523 | 3,652,352 |
def read_ds(tier, pos_source=None):
"""
Like read_pt above, given a DS tier, return the DepTree object
:param tier:
:type tier: RGTier
"""
# First, assert that the type we're looking at is correct.
assert tier.type == DS_TIER_TYPE
# --1) Root the tree.
root = DepTree.root()
#... | 797503380a3ff697440da8cd5d409b5c89384f4f | 3,652,353 |
def get_local_ontology_from_file(ontology_file):
""" return ontology class from a local OWL file """
return ow.get_ontology("file://" + ontology_file).load() | c022aac464c4afdbc088455a5edf8a4d91bc5586 | 3,652,354 |
import urllib
def get_wolframalpha_imagetag(searchterm):
""" Used to get the first image tag from the Wolfram Alpha API. The return value is a dictionary
with keys that can go directly into html.
Takes in:
searchterm: the term to search with in the Wolfram Alpha API
"""
base_url = 'htt... | 958e09d6498b1f1d98de72fe9089e45e48988f20 | 3,652,355 |
def get_synset_definitions(word):
"""Return all possible definitions for synsets in a word synset ring.
:param word (str): The word to lookup.
:rtype definitions (list): The synset definitions list.
"""
definitions = []
synsets = get_word_synsets(word)
for _synset in synsets:
defini... | 70d522777cd413902157df6c0d96bdf378d7cf69 | 3,652,356 |
import json
def getResourceDefUsingSession(url, session, resourceName, sensitiveOptions=False):
"""
get the resource definition - given a resource name (and catalog url)
catalog url should stop at port (e.g. not have ldmadmin, ldmcatalog etc...
or have v2 anywhere
since we are using v1 api's
... | 883a393018b068b8f15a8c0ea5ac6969c1a386b6 | 3,652,357 |
def _merge_sse(sum1, sum2):
"""Merge the partial SSE."""
sum_count = sum1 + sum2
return sum_count | 0aae96262cfb56c6052fdbe5bbd92437d37b1f76 | 3,652,358 |
def earliest_deadline_first(evs, iface):
""" Sort EVs by departure time in increasing order.
Args:
evs (List[EV]): List of EVs to be sorted.
iface (Interface): Interface object. (not used in this case)
Returns:
List[EV]: List of EVs sorted by departure time in increasing order.
... | f1a57586b9993d890ddda6c309dafbea4ae16554 | 3,652,359 |
import re
def auto_load(filename):
"""Load any supported raw battery cycler file to the correct Datapath automatically.
Matches raw file patterns to the correct datapath and returns the datapath object.
Example:
auto_load("2017-05-09_test-TC-contact_CH33.csv")
>>> <ArbinDatapath object>... | 6b3ccf40296f62c15ea005cfe5e87e397d8e9f88 | 3,652,360 |
def print_param_list(param_list, result, decimal_place=2, unit=''):
"""
Return a result string with parameter data appended. The input `param_list` is a list of a tuple
(param_value, param_name), where `param_value` is a float and `param_name` is a string. If `param_value`
is None, it writes 'N/A'.
... | f92fd926eaf312e625058c394c42e9909cac7a43 | 3,652,361 |
def get_veh_id(gb_data):
"""
Mapping function for vehicle id
"""
veh_ref = gb_data['Vehicle_Reference']
acc_id = get_acc_id_from_data(gb_data)
veh_id = common.get_gb_veh_id(acc_id, int(veh_ref))
return veh_id | de3a8f99a099737cedb00534ad21bc7dd1a900c5 | 3,652,362 |
def linreg_qr_gramschmidt_unencrypted(clientMap, coordinator, encryLv=3, colTrunc=False):
"""
Compute vertical federated linear regression using QR.
QR decomposition is computed by means of Numpy/Scipy builtin algorithm and Gram-Schmidt method.
Parameters
----------
clientMap : List
The... | 59fee17cff911a22c4e6cfc6daf13ce7559d32a7 | 3,652,363 |
def has_soa_perm(user_level, obj, ctnr, action):
"""
Permissions for SOAs
SOAs are global, related to domains and reverse domains
"""
return {
'cyder_admin': True, #?
'ctnr_admin': action == 'view',
'user': action == 'view',
'guest': action == 'view',
}.get(user_l... | 6b32c9f3411d9341d9692c46e84a7506d649f36d | 3,652,364 |
def check_skyscrapers(input_path: str) -> bool:
"""
Main function to check the status of skyscraper game board.
Return True if the board status is compliant with the rules,
False otherwise.
"""
board = read_input(input_path)
return check_not_finished_board(board) and check_uniqueness_in_rows... | a4a2c77049bad429e548c749ef3e34ef27081de4 | 3,652,367 |
from typing import Optional
async def get_station(station: avwx.Station, token: Optional[Token]) -> dict:
"""Log and returns station data as dict"""
await app.station.add(station.lookup_code, "station")
return await station_data_for(station, token=token) or {} | 659bf56ff274ccd460dfdf240d6f4776fb7586a6 | 3,652,368 |
def add_check_numerics_ops():
"""Connect a `check_numerics` to every floating point tensor.
`check_numerics` operations themselves are added for each `half`, `float`,
or `double` tensor in the graph. For all ops in the graph, the
`check_numerics` op for all of its (`half`, `float`, or `double`) inputs
is gua... | 8a5026ff07a0cfce7f0acac58641996cef76fb2e | 3,652,369 |
def get_text(part):
"""Gmailの本文をdecode"""
if not part['filename'] and \
part['body']['size'] > 0 and \
'data' in part['body'].keys():
content_type = header(part['headers'], 'Content-Type')
encode_type = header(part['headers'], 'Content-Transfer-Encoding')
data = decod... | 2d32b30539c39dc89cb3680e2d21e14eb9ce24c4 | 3,652,370 |
import dataclasses
def run(ex: "interactivity.Execution"):
"""Specify the target function(s) and/or layer(s) to target."""
selection: "definitions.Selection" = ex.shell.selection
is_exact = ex.args.get("exact", False)
functions = ex.args.get("functions", False)
layers = ex.args.get("layers", False... | 9389ada1c657b1f2794650e9b2b2d9a40039b64f | 3,652,371 |
def ByName(breakdown_metric_name):
"""Return a BreakdownMetric class by name."""
breakdown_mapping = {
'distance': ByDistance,
'num_points': ByNumPoints,
'rotation': ByRotation,
'difficulty': ByDifficulty
}
if breakdown_metric_name not in breakdown_mapping:
raise ValueError('Invalid ... | 06a1a44f8453375cfc83729339062948829d950c | 3,652,373 |
def deserialize_structure(serialized_structure, dtype=np.int32):
"""Converts a string to a structure.
Args:
serialized_structure: A structure produced by `serialize_structure`.
dtype: The data type of the output numpy array.
Returns:
A numpy array with `dtype`.
"""
return np.asarray(
[toke... | ec8f3d096f3eedea4343576f7b204da15ae73ca6 | 3,652,374 |
from typing import List
def get_all_text_elements(dataset_name: str) -> List[TextElement]:
"""
get all the text elements of the given dataset
:param dataset_name:
"""
return data_access.get_all_text_elements(dataset_name=dataset_name) | fa4c2e0bff9818f1026095b5b6b774b09652b989 | 3,652,375 |
def form_x(form_file,*args):
"""
same as above, except assumes all tags in the form are number, and uses the additional arguments in *args to fill out those tag values.
:param form_file: file which we use for replacements
:param *args: optional arguments which contain the form entries for the file in question, by n... | e2d45e71ff18ce626a89d9a097389fc27b34fa82 | 3,652,376 |
import click
def init():
"""Manage IAM users."""
formatter = cli.make_formatter('aws_user')
@click.group()
def user():
"""Manage IAM users."""
pass
@user.command()
@click.option('--create',
is_flag=True,
default=False,
he... | b237e6ba7c10aafa1a499944f1553eaceed0fb2a | 3,652,377 |
def fix_units(dims):
"""Fill in missing units."""
default = [d.get("units") for d in dims][-1]
for dim in dims:
dim["units"] = dim.get("units", default)
return dims | d3a47ad84e1b4e44bedebb1e5739778df975a6fe | 3,652,378 |
def annotate_movement(raw, pos, rotation_velocity_limit=None,
translation_velocity_limit=None,
mean_distance_limit=None, use_dev_head_trans='average'):
"""Detect segments with movement.
Detects segments periods further from rotation_velocity_limit,
translation_ve... | f89e48281cb70da6aa27b7dde737a8a587024f08 | 3,652,379 |
from typing import Any
def run_in_executor(
func: F,
executor: ThreadPoolExecutor = None,
args: Any = (),
kwargs: Any = MappingProxyType({}),
) -> Future:
"""将耗时函数加入到线程池 ."""
loop = get_event_loop()
# noinspection PyTypeChecker
return loop.run_in_executor( # type: ignore
execu... | dfa40f30e359d785e3582f48910d3936659bd2fa | 3,652,380 |
def find_entry_with_minimal_scale_at_prime(self, p):
"""
Finds the entry of the quadratic form with minimal scale at the
prime p, preferring diagonal entries in case of a tie. (I.e. If
we write the quadratic form as a symmetric matrix M, then this
entry M[i,j] has the minimal valuation at the prim... | 737a6dd1c3a1f416f4e22b79440b7731a5048fe0 | 3,652,381 |
import awkward._v2._connect.pyarrow
def from_arrow(array, highlevel=True, behavior=None):
"""
Args:
array (`pyarrow.Array`, `pyarrow.ChunkedArray`, `pyarrow.RecordBatch`,
or `pyarrow.Table`): Apache Arrow array to convert into an
Awkward Array.
highlevel (bool): If True... | a3c0cea2f2f3763f8997978e2963654cc08ed4e1 | 3,652,382 |
def Get_EstimatedRedshifts( scenario={} ):
""" obtain estimated source redshifts written to npy file """
return np.genfromtxt( FilenameEstimatedRedshift( scenario ), dtype=None, delimiter=',', names=True, encoding='UTF-8') | 0696cfee6783c093b8cf4b7c9703fec18e9799a4 | 3,652,384 |
def get_national_museums(db_connection, export_to_csv, export_path):
"""
Get national museum data from DB
"""
df = pd.read_sql('select * from optourism.state_national_museum_visits', con=db_connection)
if export_to_csv:
df.to_csv(f"{export_path}_nationalmuseums_raw.csv", index=False)
... | d34b9ff8f7f95025f932078e8d6e8b179bcff27e | 3,652,385 |
from re import A
def hrm_configure_pr_group_membership():
"""
Configures the labels and CRUD Strings of pr_group_membership
"""
T = current.T
s3db = current.s3db
settings = current.deployment_settings
request = current.request
function = request.function
table = s3db.pr_group... | f5ec66e00063bf8101505de8b1b8a767227b6bbd | 3,652,386 |
import torch
def inverse_sphere_distances(batch, dist, labels, anchor_label):
"""
Function to utilise the distances of batch samples to compute their
probability of occurence, and using the inverse to sample actual negatives to the resp. anchor.
Args:
batch: torch.T... | 9bcb7f56f08fd850f6a9fa70175e1f83df603705 | 3,652,387 |
from functools import reduce
def wrap_onspace(text, width):
"""
A word-wrap function that preserves existing line breaks
and most spaces in the text. Expects that existing line
breaks are posix newlines (\n).
"""
return reduce(lambda line, word, width=width: '%s%s%s' %
(line,... | 13387fa67dcff2b0329463dfe1ab7d6721255afc | 3,652,389 |
def xsd_simple_type_factory(elem, schema, parent):
"""
Factory function for XSD simple types. Parses the xs:simpleType element and its
child component, that can be a restriction, a list or an union. Annotations are
linked to simple type instance, omitting the inner annotation if both are given.
"""
... | 27ab47787923fadef6364828e2cc7604b006d76d | 3,652,390 |
def amen_solve(A, f, x0, eps, kickrank=4, nswp=20, local_prec='n',
local_iters=2, local_restart=40, trunc_norm=1, max_full_size=50, verb=1):
""" Approximate linear system solution in the tensor-train (TT) format
using Alternating minimal energy (AMEN approach)
:References: Sergey Dolgov,... | 15b35bedd6e07f867ae1bae54992f8988b1b56cb | 3,652,391 |
def get_vss(ts, tau_p):
""" Compute candidates of VS for specified task tau_p """
if tau_p == None:
return []
C, T, D = extract(ts)
R = rta(C, T)
_VS = _get_vs(C, T, R, task_name_to_index(ts, tau_p))
_VS.sort()
VS = []
vs = Server(0, 0, None)
# ignore duplicates
for s i... | a6b0abc26d32d8e62e4026ee59a6491a02dd6a32 | 3,652,392 |
from typing import Iterable
from typing import Dict
from typing import Hashable
from typing import List
def groupby(
entities: Iterable["DXFEntity"], dxfattrib: str = "", key: "KeyFunc" = None
) -> Dict[Hashable, List["DXFEntity"]]:
"""
Groups a sequence of DXF entities by a DXF attribute like ``'layer'``... | 0eecfc2263c1f5716615cb4add6bc092edbb2b8b | 3,652,393 |
def train_test_split(data_filepath, num_train=10, num_test=10):
"""Split a dataset into training and test sets."""
df = pd.read_csv(data_filepath, sep=',', header=None)
data = df.values
train = data[:2*num_train, :]
test = data[2*num_train:2*(num_train+num_test), :]
ind = np.argsort(train[:,-1... | 650979e62667ade3f88d89f2058bedf8675a5ae5 | 3,652,394 |
import requests
def get_filings(app: Flask = None):
"""Get a filing with filing_id."""
r = requests.get(f'{app.config["LEGAL_URL"]}/internal/filings')
if not r or r.status_code != 200:
app.logger.error(f'Failed to collect filings from legal-api. {r} {r.json()} {r.status_code}')
raise Excep... | 4b2ba1a3d15918fe5d7b706a20006d0c85818176 | 3,652,395 |
def _uno_struct__setattr__(self, name, value):
"""Sets attribute on UNO struct.
Referenced from the pyuno shared library.
"""
return setattr(self.__dict__["value"], name, value) | 6b66213e33bb8b882407ff33bcca177701fb98cd | 3,652,396 |
from datetime import datetime
def register():
"""Registers the user."""
if g.user:
return redirect(url_for('user_home'))
error = None
if request.method == 'POST':
if not request.form['username']:
error = 'You have to enter a username'
elif not request.form['email'... | 572ee30c9f4981f6d526f115178ba8988e2b93c1 | 3,652,398 |
def test_single_while_2():
"""
Feature: JIT Fallback
Description: Test fallback with control flow.
Expectation: No exception.
"""
@ms_function
def control_flow_while():
x = Tensor(7).astype("int32")
y = Tensor(0).astype("int32")
while x >= y:
y += x
... | 8334819ee7d4ea24085e2a2f1ab3d18fb732c8cc | 3,652,399 |
import cuml
from cuml.metrics import confusion_matrix
def build_and_predict_model(ml_input_df):
"""
Create a standardized feature matrix X and target array y.
Returns the model and accuracy statistics
"""
feature_names = ["college_education", "male"] + [
"clicks_in_%d" % i for i in range(... | 2d3e192986c680d910a401c9a4da295595fe236e | 3,652,400 |
def codes_new_from_file(fileobj, product_kind, headers_only=False):
"""
@brief Load in memory a message from a file for a given product.
The message can be accessed through its id and will be available\n
until @ref grib_release is called.\n
\b Examples: \ref get_product_kind.py "get_product_kind.p... | 47ed09dbf5bf59160dcab4c36dfd202ae7b190a5 | 3,652,401 |
from datetime import datetime
def list_resources(path, long_format=None, relations=False):
"""List resources in a given DMF workspace.
Args:
path (str): Path to the workspace
long_format (bool): List in long format flag
relations (bool): Show relationships, in long format
Returns... | 904f04a008efb8add2d7744bfe1dc71009faff17 | 3,652,402 |
def calc_streamtemp(tas):
""" Global standard regression equation from Punzet et al. (2012)
Calculates grid cell stream temperature based on air temperature
Both input and output temperature are in K"""
# global constants, taken from Punzet et al., 2012
c0 = 32; c1 = -0.13; c2 = 1.94
... | 493d1ca3b3543db9bfabc8c0e2a4f013da794028 | 3,652,403 |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured data to conform to the schema.
"""
# nothing more to process
return proc_data | 7585a8810667f39d6d6a787f2617590aee1ec8cf | 3,652,404 |
import requests
def get_station_info(my_token, station_id):
"""
This function gets all the information on the station
----------
Input:
my_token (str)
token generated from "token request page"
station_id (str)
----------
Output:
dictionary of station information
"""
station_url = '{}stations/{}'.... | 9abcb5b74cb0be45396c1b182845467e3fc0829c | 3,652,405 |
def check_fit_input(coordinates, data, weights, unpack=True):
"""
Validate the inputs to the fit method of gridders.
Checks that the coordinates, data, and weights (if given) all have the same
shape. Weights arrays are raveled.
Parameters
----------
coordinates : tuple of arrays
Ar... | eef22bb026aad657f096ac4de00a6d2a5a6fa0f8 | 3,652,407 |
def get_local_beneficiaries(map_lat: float, map_lng: float, map_zoom: int) -> DataFrame:
"""Return only projects that are fairly close to the map's centre."""
return beneficiaries[
(map_lat - 100 / map_zoom < beneficiaries.lat) &
(beneficiaries.lat < map_lat + 100 / map_zoom) &
(map_lng... | 30e0d7255a70c15a25f499e867974c711ae3f750 | 3,652,409 |
def create_atoms(atoms, atom_dict):
"""Transform the atom types in a molecule (e.g., H, C, and O)
into the indices (e.g., H=0, C=1, and O=2).
"""
atoms = [atom_dict[a] for a in atoms]
return np.array(atoms) | 10f0e0d0669c2148db7cdcd487a6b72ade2e2f06 | 3,652,411 |
def uint2float(A,bits,x_min,x_max=None):
"""
Converts uint[bits] to the corresponding floating point value in the range [x_min,x_max].
"""
if x_max is None:
x_min,x_max = x_range(x_min)
return x_min + (x_max - x_min) * A / ((1 << bits) - 1) | 242b72824309a7e0724c42f29e259e52b11a90d2 | 3,652,412 |
def partCmp(verA: str, verB: str) -> int:
"""Compare parts of a semver.
Args:
verA (str): lhs part to compare
verB (str): rhs part to compare
Returns:
int: 0 if equal, 1 if verA > verB and -1 if verA < verB
"""
if verA == verB or verA == "*" or verB == "*":
return 0
if int(verA) > int(verB):
return 1
... | d9417ce482bf0c2332175412ba3125435f884336 | 3,652,413 |
import io
def OrigPosLemConcordancer(sentences, annots, textMnt, wordType="word", nrows=10):
"""Output HTML for the text (including lemma and pos tags) identified by the AQAnnotation (typically a sentence annotation).
Below the sentence (in successive rows) output the original terms, parts of speech, and lem... | f11f0240cbee58954901bd57e728cd54ab51b6dd | 3,652,414 |
def show_hidden_article(request, id):
"""
展示隐藏的文章
"""
db = connect_mongodb_database(request)
article = db.articles.find_one({
'Id':int(id), 'IsPublic': False
})
if article is None:
return HttpResponse(404)
return render_admin_and_back(request, 'show-hidden-article.html',... | 5f9f9c3bc21ed267d8c13226d51a7f44877af976 | 3,652,416 |
def MakeNormalPmf(mu, sigma, num_sigmas, n=201):
"""Makes a PMF discrete approx to a Normal distribution.
mu: float mean
sigma: float standard deviation
num_sigmas: how many sigmas to extend in each direction
n: number of values in the Pmf
returns: normalized Pmf
"""
pmf = Pmf()
... | 9bca22cfd3b3b94fa233be9f78696361d9e36726 | 3,652,417 |
def histogram(a, bins, ranges):
"""
Examples
--------
>>> x = np.random.uniform(0., 1., 100)
>>> H, xedges = np.histogram(x, bins=5, range=[0., 1.])
>>> Hn = histogram(x, bins=5, ranges=[0., 1.])
>>> assert np.all(H == Hn)
"""
hist_arr = np.zeros((bins,), dtype=a.dtype)
return ... | a53a8204180c8f9d2a3fb36595d14c07da262cbd | 3,652,419 |
def is_valid_python_code(src_string: str):
"""True if, and only if, ``src_string`` is valid python.
Valid python is defined as 'ast.parse(src_string)` doesn't raise a ``SyntaxError``'
"""
try:
ast_parse(src_string)
return True
except SyntaxError:
return False | 03ee9d915797ba1cfcbcaf8630d38df529744f1b | 3,652,421 |
def rss_format_export_post():
"""
:return:
"""
try:
payload = request.get_json(force=True) # post data in json
except:
payload = dict(request.form) # post data in form encoding
if 'link' in payload:
link = read_value_list_or_not(payload, 'link')
else:
link... | 2ddc5b814cabec3fd84f024d44cb04b0063890c5 | 3,652,422 |
def setup_agents(model, initial_locations):
"""Load the simulated initial locations and return a list
that holds all agents.
"""
initial_locations = initial_locations.reshape(2, model["n_types"], 30000)
agents = []
for typ in range(model["n_types"]):
for i in range(model["n_agents_by_t... | 40368819f0968b3fcaed6a1953f7e4fec453f471 | 3,652,425 |
async def get_active_infraction(
ctx: Context,
user: MemberOrUser,
infr_type: str,
send_msg: bool = True
) -> t.Optional[dict]:
"""
Retrieves an active infraction of the given type for the user.
If `send_msg` is True and the user has an active infraction matching the `infr_t... | 63361319b75e072489544e2956d21ff5cbe08590 | 3,652,426 |
def plot_arb_images(label, data, label_string):
"""
Neatly displays arbitrary numbers of images from the camera
returns fig
Parameters:
-----------
label: array of values that each image is labeled by, e.g. time
data: array of arrays of image data
label_string: string describing label,... | 56e22d9f7a0651d56e93873b95c2228162f4a602 | 3,652,428 |
def listGslbServer(**kargs):
""" List the Servers of KT Cloud GSLB.
* Args:
- zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2]
* Examples: print(gslb.listGslbServer(zone='KR-M'))
"""
my_apikey, my_secretkey = c.read_config()
if not 'zone' in kargs:
return c.printZoneHelp()
... | 18d8f0e6699b7cb3080eef5a3d040420ea45329d | 3,652,429 |
import numpy
def imencode(image, pix_fmt=IM_RGB, quality=DEFAULT_QUALITY):
"""
Encode image into jpeg codec
Adapt convert image pixel color with pix_fmt
Parameters
----------
image: source
pix_fmt: format of pixel color. Default: RGB
quality: JPEG quality image.
Retur... | 65750d176275e56da55c0660370a56f44baa6e48 | 3,652,430 |
def split_train_test_data(X, Y, train_rate):
"""
将数据集划分为训练集与测试集
:param X: 数据集的特征
:param Y: 数据集的标签
:param train_rate: 训练集的比例
:return: 训练集的特征;训练集的标签;测试集的特征;测试集的标签
"""
number = len(X)
number_train = int(number * train_rate)
number_test = number - number_train
train_X = []
tr... | 7943278bc662968f8e019368ed8744d9e2a23929 | 3,652,431 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.