content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _ComputeRelativeAlphaBeta(omega_b, position_b, apparent_wind_b):
"""Computes the relative alpha and beta values, in degrees, from kinematics.
Args:
omega_b: Array of size (n, 3). Body rates of the kite [rad/s].
position_b: Array of size (1, 3). Position of the surface to compute local
a... | 6aa5f82e85b50abab0c72800b5e2b11ec613bcbd | 22,271 |
def make_chord(midi_nums, duration, sig_cons=CosSignal, framerate=11025):
"""Make a chord with the given duration.
midi_nums: sequence of int MIDI note numbers
duration: float seconds
sig_cons: Signal constructor function
framerate: int frames per second
returns: Wave
"""
freqs = [midi... | babc9d22b92b2e7085680178718959cd7ef15eca | 22,272 |
def calculate_percent(partial, total):
"""Calculate percent value."""
if total:
percent = round(partial / total * 100, 2)
else:
percent = 0
return f'{percent}%' | 4d3da544dd1252acec3351e7f67568be80afe020 | 22,273 |
import requests
def okgets(urls):
"""Multi-threaded requests.get, only returning valid response objects
:param urls: A container of str URLs
:returns: A tuple of requests.Response objects
"""
return nest(
ripper(requests.get),
filt(statusok),
tuple
)(urls) | 0933f4df68745a6c9d69d0b42d4bb005c1c69772 | 22,274 |
def worker(args):
"""
This function does the work of returning a URL for the NDSE view
"""
# Step 1. Create the NDSE view request object
# Set the url where you want the recipient to go once they are done
# with the NDSE. It is usually the case that the
# user will never "finish" with the N... | abcb2a94e5d14519a708ae8d531e47f30bc3c0da | 22,275 |
import warnings
import math
def plot_horiz_xsection_quiver_map(Grids, ax=None,
background_field='reflectivity',
level=1, cmap='pyart_LangRainbow12',
vmin=None, vmax=None,
u_vel_c... | 7f093435ad5488226232a6028d94e6f22b1a2688 | 22,276 |
def register(registered_collection, reg_key):
"""Register decorated function or class to collection.
Register decorated function or class into registered_collection, in a
hierarchical order. For example, when reg_key="my_model/my_exp/my_config_0"
the decorated function or class is stored under
registered_col... | affba6b7ee1294040633f488752623b3fa0462e4 | 22,277 |
def form_hhaa_records(df,
team_locn='h',
records='h',
feature='ftGoals'):
"""
Accept a league table of matches with a feature
"""
team_records = []
for _, team_df in df.groupby(by=team_locn):
lags = range(0, len(team_df))
... | af618fa0fe3c1602018ba6830c381bde73c158c3 | 22,278 |
def process_dataset(material: str, frequency: float, plot=False,
pr=False) -> float:
"""
Take a set of data, fit curve and find thermal diffustivity.
Parameters
----------
material : str
Gives material of this dataset. 'Cu' or 'Al'.
frequency : float
Frequenc... | 64e25b326ddf33adf568b395320e9dddcc9c637d | 22,279 |
def make_ln_func(variable):
"""Take an qs and computed the natural log of a variable"""
def safe_ln_queryset(qs):
"""Takes the natural log of a queryset's values and handles zeros"""
vals = qs.values_list(variable, flat=True)
ret = np.log(vals)
ret[ret == -np.inf] = 0
ret... | 200c17c011788e53aa3f678ede22c02bad10613a | 22,282 |
def calc_all_energies(n, k, states, params):
"""Calculate all the energies for the states given. Can be used for Potts.
Parameters
----------
n : int
Number of spins.
k : int
Ising or Potts3 model.
states : ndarray
Number of distinct states.
params : ndarray
... | 9de47da0f0dfa2047fdddc7796ada861d7be0f6b | 22,283 |
from heroku_connect.models import TriggerLog, TriggerLogArchive
def create_heroku_connect_schema(using=DEFAULT_DB_ALIAS):
"""
Create Heroku Connect schema.
Note:
This function is only meant to be used for local development.
In a production environment the schema will be created by
... | bb7eacbf4775bb08f723b69adc6a43c10ffe9287 | 22,284 |
import re
def extract_sentences(modifier, split_text):
"""
Extracts the sentences that contain the modifier references.
"""
extracted_text = []
for sentence in split_text:
if re.search(r"\b(?=\w)%s\b(?!\w)" % re.escape(modifier), sentence,
re.IGNORECASE):
e... | 4e31a250520b765d998aa8bc88f2414fe206901c | 22,285 |
def get_1_neighbours(graph, i):
"""
This function gets all the 1-neighborhoods including i itself.
"""
nbhd_nodes = graph.get_out_neighbours(i)
nbhd_nodes = np.concatenate((nbhd_nodes,np.array([i])))
return nbhd_nodes | 4b19f6eb2cbd7044cf0da26e6770a2be85ae901d | 22,286 |
def window_slice(frame, center, window):
"""
Get the index ranges for a window with size `window` at `center`, clipped to the boundaries of `frame`
Parameters
----------
frame : ArrayLike
image frame for bound-checking
center : Tuple
(y, x) coordinate of the window
window : ... | 111c53b7b2ead44e462cc3c5815e9d44b4c3d024 | 22,287 |
def revnum_to_revref(rev, old_marks):
"""Convert an hg revnum to a git-fast-import rev reference (an SHA1
or a mark)"""
return old_marks.get(rev) or b':%d' % (rev+1) | 13730de4c1debe0cecdd1a14652490b9416b22f5 | 22,288 |
def onset_precision_recall_f1(ref_intervals, est_intervals,
onset_tolerance=0.05, strict=False, beta=1.0):
"""Compute the Precision, Recall and F-measure of note onsets: an estimated
onset is considered correct if it is within +-50ms of a reference onset.
Note that this metric ... | aa4747925a59116246ece29e4cec55a2f91a903d | 22,289 |
def parse_acs_metadata(acs_metadata, groups):
"""Returns a map of variable ids to metadata for that variable, filtered to
specified groups.
acs_metadata: The ACS metadata as json.
groups: The list of group ids to include."""
output_vars = {}
for variable_id, metadata in acs_metadata["variabl... | f0bfb0172b0b2d5fec92b613b5f2e2baf6e7c8f0 | 22,290 |
def split_series_using_lytaf(timearray, data, lytaf):
"""
Proba-2 analysis code for splitting up LYRA timeseries around locations
where LARs (and other data events) are observed.
Parameters
----------
timearray : `numpy.ndarray` of times understood by `sunpy.time.parse_time`
function.
... | 2cc509ede0f2f74f999fae180acb23049a87f165 | 22,291 |
def getrqdata(request):
"""Return the request data.
Unlike the now defunct `REQUEST
<https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.REQUEST>`_
attribute, this inspects the request's `method` in order to decide
what to return.
"""
if request.method in (... | d385943c4c8c7fc7e0b5fc4b1d0f1ba0bc272a13 | 22,292 |
from typing import List
def generate_per_level_fractions(highest_level_ratio: int, num_levels: int = NUM_LEVELS) -> List[float]:
"""
Generates the per-level fractions to reach the target sum (i.e. the highest level ratio).
Args:
highest_level_ratio:
The 1:highest_level_ratio ratio for... | 6c7aee63a2b89671ae65bd28fb8616ffc72d014b | 22,293 |
def choose_transformations(name):
"""Prompts user with different data transformation options"""
transformations_prompt=[
{
'type':'confirm',
'message':'Would you like to apply some transformations to the file? (Default is no)',
'name':'confirm_transformations',
... | f24c560cb23573daa57e4fece7a28b3a809ae478 | 22,294 |
from typing import Dict
from typing import Tuple
def update_list_item_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]:
"""Updates a list item. return outputs in Demisto's format
Args:
client: Client object with request
args: Usually demisto.args()
Returns:
Outputs
... | 6471170d72bec7dd19d102470e2b29dec2131e17 | 22,295 |
import torch
def fft(input, inverse=False):
"""Interface with torch FFT routines for 3D signals.
fft of a 3d signal
Example
-------
x = torch.randn(128, 32, 32, 32, 2)
x_fft = fft(x)
x_ifft = fft(x, inverse=True)
Parameters
----------
x : te... | 8b7bdfbaeaf712ee8734c7d035f404fd154d3838 | 22,296 |
def dbdescs(data, dbname):
"""
return the entire set of information for a specific server/database
"""
# pylint: disable=bad-continuation
return {
'admin': onedesc(data, dbname, 'admin', 'rw'),
'user': onedesc(data, dbname, 'user', 'rw'),
'viewer': onedesc(data, dbname, 'viewer', 'ro')
} | 895f87300192fbad1045665eef0a08c64c6ba294 | 22,297 |
from datetime import datetime
def format_date(date):
"""Format date to readable format."""
try:
if date != 'N/A':
date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').strftime('%d %b %Y')
except ValueError:
logger.error("Unexpected ValueError while trying to format date... | 48d6d426925e45f0c3b92e492efa5d23e1550a2f | 22,298 |
def estimate_perfomance_plan(sims, ntra, stateinit, destination, plan=list(), plot=False, verbose=True):
"""
Estimates the performances of two plans and compares them on two scenarios.
:param list() sims: List of :class:`simulatorTLKT.Simulator`
:param int ntra: Number of trajectories used to estimate ... | 274ebadafa7f7637e27a0f25a013171a0955d4ce | 22,300 |
def xls_dslx_ir_impl(ctx, src, dep_src_list):
"""The implementation of the 'xls_dslx_ir' rule.
Converts a DSLX source file to an IR file.
Args:
ctx: The current rule's context object.
src: The source file.
dep_src_list: A list of source file dependencies.
Returns:
DslxModuleIn... | 119112184086ccb469157eae1b17e1a0f38b57ef | 22,301 |
def split_data(images, labels):
"""
Split data into training (80%), validation (10%), and testing (10%)
datasets
Returns (images_train, images_validate, images_test, labels_train,
labels_validate, labels_test)
Assumes that num_covid_points <= num_normal_points and num_virus_points
"""
... | 87950ef842781abb8500961a11d997b254bde6af | 22,302 |
import random
def randomlyInfectRegions(network, regions, age_groups, infected):
"""Randomly infect regions to initialize the random simulation
:param network: object representing the network of populations
:type network: A NetworkOfPopulation object
:param regions: The number of regions to expose.
... | 213450bfbdba56a8671943905d6ac888a548c8aa | 22,303 |
def timestamp_to_uint64(timestamp):
"""Convert timestamp to milliseconds since epoch."""
return int(timestamp.timestamp() * 1e3) | 165df202cb5f8cee5792bfa5778114ea3e98fa65 | 22,304 |
def extensible(x):
"""
Enables a function to be extended by some other function.
The function will get an attribute (extensible) which will return True.
The function will also get a function (extendedby) which will return a
list of all the functions that extend it.
"""
extensible_functions.a... | a810e90e386441e8b223824c77ee452b4f7ff6d5 | 22,305 |
def _validate_user_deploy_steps(task, user_steps, error_prefix=None):
"""Validate the user-specified deploy steps.
:param task: A TaskManager object
:param user_steps: a list of deploy steps. A deploy step is a dictionary
with required keys 'interface', 'step', 'args', and 'priority'::
... | 58cf55b444c533ec96a86ad09b76ca9bc275f7dd | 22,306 |
from operator import gt
def is_period_arraylike(arr):
""" return if we are period arraylike / PeriodIndex """
if isinstance(arr, pd.PeriodIndex):
return True
elif isinstance(arr, (np.ndarray, gt.ABCSeries)):
return arr.dtype == object and lib.infer_dtype(arr) == 'period'
return getattr... | f675f56dbca7ef80dc75bbe454a4f6e11a419c50 | 22,307 |
def reset_password_step_2(token):
"""Processing the second step of changing the password (password change)"""
email = confirm_token_reset_password(token)
if not email:
return redirect(url_for('web_pages.reset_password_step_1'))
form = EditPassword()
if form.validate_on_submit():
pass... | dcec97ba112ff96af4510488f801926190cfe221 | 22,308 |
def FStarTypeRole(typ, rawtext, text, lineno, inliner, options={}, content=[]):
"""An inline role to highlight F* types."""
#pylint: disable=dangerous-default-value, unused-argument
return nodes.literal(typ, rawtext, text, lineno, inliner, options=options, content=content) | 970ed43558e87a4319aed91c33d781fbe6a39d20 | 22,309 |
def matobj2dict(matobj):
"""A recursive function which converts nested mat object
to a nested python dictionaries
Arguments:
matobj {sio.matlab.mio5_params.mat_struct} -- nested mat object
Returns:
dict -- a nested dictionary
"""
ndict = {}
for fieldname in matobj._fieldnam... | 6b8413fd0c4dc9bb4e778944e7a6d4c260b56fa1 | 22,310 |
import io
def download_from_vt(client: vt.Client, file_hash: str) -> bytes:
"""
Download file from VT.
:param vt.Client client: the VT client
:param str file_hash: the file hash
:rtype: bytes
:return: the downloaded data
:raises ValueError: in case of any error
"""
try:
buf... | 055cd636d853d81921034d197bac9ad7a9c206c2 | 22,311 |
import torch
def divide_and_conquer(x, k, mul):
"""
Divide and conquer method for polynomial expansion
x is a 2d tensor of size (n_classes, n_roots)
The objective is to obtain the k first coefficients of the expanded
polynomial
"""
to_merge = []
while x[0].dim() > 1 and x[0].size(0) ... | 64bdf2d50cf7cbf7da814b93521df5cee41623fe | 22,312 |
def calculate_operating_pressure(feed_state_block=None, over_pressure=0.15,
water_recovery=0.5, NaCl_passage=0.01, solver=None):
"""
estimate operating pressure for RO unit model given the following arguments:
feed_state_block: the state block of the RO feed that has t... | 2252910515ad6b6188c06bbf3add2a36b37da1ea | 22,313 |
from bs4 import BeautifulSoup
def parse_pypi_index(text):
"""Parses the text and returns all the packages
Parameters
----------
text : str
the html of the website (https://pypi.org/simple/)
Returns
-------
List[str]
the list of packages
"""
soup = BeautifulSoup(te... | 68d831aab69f3ffdd879ea1fa7ca5f28fc1b1e75 | 22,314 |
def _get_score_measure(func, alphabeta, color, board, alpha, beta, depth, pid):
"""_get_score_measure
"""
measure(pid)
return _get_score(func, alphabeta, color, board, alpha, beta, depth, pid) | e36723d03c2ee686177ea3f8ce34874b250c2058 | 22,316 |
def mousePressed():
"""
Return True if the mouse has been left-clicked since the
last time mousePressed was called, and False otherwise.
"""
global _mousePressed
if _mousePressed:
_mousePressed = False
return True
return False | 37fd34e71ee7e9c4a671a5ba5a4a946a7441c0da | 22,317 |
def variable_on_cpu(name, shape, initializer):
"""
Next we concern ourselves with graph creation.
However, before we do so we
must introduce a utility function ``variable_on_cpu()``
used to create a variable in CPU memory.
"""
# Use the /cpu:0 device for scoped operations
with tf.devic... | 10e724f900d7c7334e81f3380fc4764ca935b284 | 22,318 |
def adaptive_generate_association_rules(patterns, confidence_threshold):
"""
Given a set of frequent itemsets, return a dictof association rules
in the form {(left): (right)}
It has a check with 2048 thus will only retain multimodal rules.
"""
missed = 0
rules = defaultdict(set)
for setn... | 35589916f91aab789a8d31559bcdbaca37bfdcd1 | 22,319 |
from typing import Union
from typing import Collection
def scored_ngrams(
docs: Documents,
n: int = 2,
metric: str = "pmi",
tokenizer: Tokenizer = DEFAULT_TOKENIZER,
preprocessor: CallableOnStr = None,
stopwords: Union[str, Collection[str]] = None,
min_freq: int = 0,
fuse_tuples: bool ... | a77b42eb1361c55cb23a1b168e99d4abb1ef9af1 | 22,321 |
def imurl(image_url, return_as_array = False , **kwargs):
"""
Read image from url and convert to bytes or ndarray
Paramters
---------
image_url: http / https url of image
return_as_array: Convert image directly to numpy array
default: False
kwargs:
Keyword argu... | c6c93ab7a2b97b522bca2d6673bfd843fdc8bb72 | 22,323 |
def generate_command(config, work_dir, output_analysis_id_dir, errors, warnings):
"""Build the main command line command to run.
Args:
config (GearToolkitContext.config): run-time options from config.json
work_dir (path): scratch directory where non-saved files can be put
output_analysi... | bb24ff62f3c4fa579eedf721708e84bf4cf3920c | 22,324 |
def ip(
context,
api_client,
api_key,
input_file,
output_file,
output_format,
verbose,
ip_address,
):
"""Query GreyNoise for all information on a given IP."""
ip_addresses = get_ip_addresses(context, input_file, ip_address)
results = [api_client.ip(ip_address=ip_address) for ... | b4c52e1bb1abb03679b977d4b15f5e0295c1e0c2 | 22,325 |
def get_layer(neurons, neuron_loc, depth=None, return_closest: bool=False):
"""Obtain the layer of neurons corresponding to layer number or specific depth."""
layers = np.unique(neuron_loc[2, :])
if depth is not None:
if depth in layers:
pass
elif return_closest:
de... | d221d294bbe974554b0180ea9d41394294de41dc | 22,326 |
def _format_unpack_code_level(message,
signal_names,
variable_lines,
helper_kinds):
"""Format one unpack level in a signal tree.
"""
body_lines = []
muxes_lines = []
for signal_name in signal_names:
... | b88362f6fd3cb5ccaf3a3f76472f2002ac9c1518 | 22,327 |
def fileGDB_schema() -> StructType:
"""Schema for dummy FileGDB."""
return StructType(
[
StructField("id", LongType()),
StructField("category", StringType()),
StructField("geometry", BinaryType()),
]
) | 0ef7ad136d64f19e392bb8a9ff471478094193fe | 22,329 |
def set_atom_stereo_parities(sgr, atm_par_dct):
""" set atom parities
"""
atm_dct = mdict.set_by_key_by_position(atoms(sgr), atm_par_dct,
ATM_STE_PAR_POS)
return _create.from_atoms_and_bonds(atm_dct, bonds(sgr)) | 1e733291ce12e614b538054c2c05fc3892ce3206 | 22,330 |
def clean(expr):
"""
cleans up an expression string
Arguments:
expr: string, expression
"""
expr = expr.replace("^", "**")
return expr | f7c990146094c43d256fe15f9543a0ba90877ee3 | 22,331 |
def atom_stereo_keys(sgr):
""" keys to atom stereo-centers
"""
atm_ste_keys = dict_.keys_by_value(_atom_stereo_parities(sgr),
lambda x: x in [True, False])
return atm_ste_keys | c084c30f4601d18941d98c313d3a74b93153cd80 | 22,332 |
def get_node_rd(graph, k=3):
"""
Get k nodes to defend based on Recalculated Degree (RD) Removal :cite:`holme2002attack`.
:param graph: an undirected NetworkX graph
:param k: number of nodes to defend
:return: a list of nodes to defend
"""
return get_node_rd_attack(graph, k) | dbbf501353133a1cb222f6d2d4f632faa07bad1c | 22,333 |
def get_frog():
"""Returns the interface object to frog NLP. (There should only be one
instance, because it spawns a frog process that consumes a lot of RAM.)
"""
global FROG
if FROG is None:
FROG = frog.Frog(frog.FrogOptions(
tok=True, lemma=True, morph=False, daringmorph=False,... | 5701b2856532241d797eb77d9734fd67ee838312 | 22,334 |
import requests
def fetch(url: str, **kwargs) -> Selector:
"""
Send HTTP request and parse it as a DOM selector.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions.
"""
kwargs.setdefault('headers', D... | f5bbe41f3b7bc83d0092d0b2165681df096413d1 | 22,335 |
import math
def growth(x, a, b):
""" Growth model. a is the value at t=0. b is the so-called R number.
Doesnt work. FIX IT """
return np.power(a * 0.5, (x / (4 * (math.log(0.5) / math.log(b))))) | 6276fd00f270ef72f52ed7493f431dd0e3b34326 | 22,336 |
from datetime import datetime
import pytz
def __to_localdatetime(val):
"""Convert val into a local datetime for tz Europe/Amsterdam."""
try:
# "timestamp": "2019-02-03T19:20:00",
dt = datetime.strptime(val, __DATE_FORMAT)
dt = pytz.timezone(__TIMEZONE).localize(dt)
return dt
... | e2eea5da625a3514b6872e5604336d5dfb6f0ccb | 22,337 |
import warnings
def imgMinMaxScaler(img, scale_range):
"""
:param img: image to be rescaled
:param scale_range: (tuple) (min, max) of the desired rescaling
"""
warnings.filterwarnings("ignore")
img = img.astype("float64")
img_std = (img - np.min(img)) / (np.max(img) - np.min(img))
img_... | f55795167f6a284ea81609413edc73c1336a2a5e | 22,338 |
def xor(text, key):
"""Returns the given string XORed with given key."""
while len(key) < len(text): key += key
key = key[:len(text)]
return "".join(chr(ord(a) ^ ord(b)) for (a, b) in zip(text, key)) | 3cae903ef4751b2f39e0e5e28d448b8d079ce249 | 22,340 |
from pathlib import Path
def get_emojis_voc_counts(path):
"""
Generate a value count of words for every emoji present in the csv files
found in the child directories of "path"
Args:
path (str): parent path of the csv files
Return:
em2vocab [dict of dict]: a dict associating each ... | b4525be35e191c84a9ea0d781d510f348724ff42 | 22,341 |
from unittest.mock import Mock
from unittest.mock import patch
import asyncio
async def test_camera_snapshot_connection_closed(driver):
"""Test camera snapshot when the other side closes the connection."""
loop = MagicMock()
transport = MagicMock()
transport.is_closing = Mock(return_value=True)
co... | 636f22f167d07699d7e591f74ae92ecde8f460c4 | 22,342 |
import numpy
from re import T
def _as_scalar(res, dtype=None):
"""Return None or a TensorVariable whose type is in T.float_scalar_types"""
if dtype is None:
dtype = config.floatX
if numpy.all(res.type.broadcastable):
while res.owner and isinstance(res.owner.op, T.DimShuffle):
r... | c5a8b6041a6eb160cec23f6957c9d9cc9147d4f7 | 22,343 |
import datasets
import torch
def partition_dataset():
""" Partitioning MNIST """
dataset = datasets.MNIST(
'./data',
train=True,
download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307, ), (0.3081, ))
]))... | 6922ae2cc80655d93eeee23d31f1224f172de1cc | 22,344 |
def add_size_to_nus(demo_graph, pop, time_left):
"""
adds either nu, or [nu0, growth_rate], where nu0 is the size at the beginning of the epoch
use time_left to set nu0 to the size at the beginning of the epoch
"""
if 'nu' in demo_graph.nodes[pop]:
return demo_graph.nodes[pop]['nu']
else... | 6e655b157389ca8672433b26baa1f2362f5dde34 | 22,345 |
def _rand_lognormals(logs, sigma):
"""Mock-point"""
return np.random.lognormal(mean=logs, sigma=sigma, size=logs.shape) | 8fbf51e548293ff6c4dee8f385af69ecaaf34cde | 22,346 |
def add_start_end_qualifiers(statement, startVal, endVal):
"""Add start/end qualifiers to a statement if non-None, or return None.
@param statement: The statement to decorate
@type statement: WD.Statement
@param startVal: An ISO date string for the starting point
@type startVal: str, unicode, or No... | 9a87feff53aca00ce257a5d0b967621461a5d15a | 22,347 |
def _CheckFilter(text):
"""CHecks if a string could be a filter.
@rtype: bool
"""
return bool(frozenset(text) & FILTER_DETECTION_CHARS) | 0d0dfed55df78ea6f49e4f615e9f7fe5758f9bc1 | 22,348 |
def listProxyServers():
"""return a list of proxy servers as a list of lists.
E.g. [['nodename','proxyname'], ['nodename','proxyname']].
Typical usage:
for (nodename,proxyname) in listProxyServers():
callSomething(nodename,proxyname)
"""
return listServersOfType("PROXY_SERVER") | 0e2ae4a874fa0ca030a04e694c7eacefde4f45f6 | 22,349 |
def api_version(func):
"""
API版本验证装饰器
:param func:
:return:
"""
@wraps(func)
def wrapper(*args, **kwargs):
# 验证api版本
verify_result = verify_version(kwargs.get('version'))
if not verify_result:
raise ApiVersionException() #抛出异常,返回结果状态码400, message:api versi... | 2e73bc7899a4052004246c1e3392001507469c86 | 22,350 |
from typing import List
from typing import Union
def is_prefix(a: List[Union[int, str]], b: List[Union[int, str]]):
"""Check if `a` is a prefix of `b`."""
if len(a) >= len(b):
return False
for i in range(len(a)):
if a[i] != b[i]:
return False
return True | 4b0605af536aa5fa188cfca0cee62588fe41bf5d | 22,351 |
import glob
def shm_data_find(ifo, ldr_type, start, stride, directory='.', verbose=False):
"""a routine to automate discovery of frames within /dev/shm
"""
end = start+stride
frames = []
for frame in sorted(glob.glob(shm_glob_tmp%(directory, ifo, ifo, ldr_type))):
s, d = utils.extract_st... | f4aba39ba77edf5d22cdaa0da16f888c26999512 | 22,352 |
def backward_inference(protocol, subsys_x, t_x, subsys_y, t_y, silent=True):
"""
Forward inference answers the question:
Given a measurement result of 'subsys_y' at the end of the protocol,
what can I say about the result an Agent would have received had she done
a measurement of 'subsys_x' before t... | 22e73ff5c4b90b535e9387cf71829bf88745a95d | 22,353 |
def rainfall_interception_hbv(Rainfall, PotEvaporation, Cmax, InterceptionStorage):
"""
Returns:
TF, Interception, IntEvap,InterceptionStorage
"""
Interception = pcr.min(
Rainfall, Cmax - InterceptionStorage
) #: Interception in mm/timestep
InterceptionStorage = (
Intercept... | 0e95a1088a36d25d0d1210384a56945d0b032fda | 22,354 |
from rspn.learning.structure_learning import get_next_operation, learn_structure
def learn_mspn(
data,
ds_context,
cols="rdc",
rows="kmeans",
min_instances_slice=200,
threshold=0.3,
max_sampling_threshold_cols=10000,
max_sampling_threshold_rows=100000,
... | 6ac8117b4d448c89fe148c4c97828da4a09dc471 | 22,355 |
def generate_image_anim(img, interval=200, save_path=None):
"""
Given CT img, return an animation across axial slice
img: [D,H,W] or [D,H,W,3]
interval: interval between each slice, default 200
save_path: path to save the animation if not None, default None
return: matplotlib.animation.Animatio... | 90ebd9d0e21b58f75a2eca8623ac7a9d12b4a820 | 22,357 |
def square_root(s):
""" Function to compute square roots using the Babylonian method
"""
x = s/2
while True:
temp = x
x = (1/2) * ( x + (s/x) )
if temp == x:
return x
# Como la convergencia se alcanza rápidamente, llega un momento en que el error
# e... | 9af22ce073bcb8d131736efba6133a92d9d7dc74 | 22,359 |
def quisort(uslist, lo=None, hi=None):
"""Sort in-place an unsorted list or slice of a list
lo and hi correspond to the start and stop indices for the list slice"""
if hi is None:
hi = len(uslist) - 1
if lo is None:
lo = 0
def partition(uslist, lo, hi):
"""Compare and swap... | a33adbe819ec1c60149e6d9a50ab78555f6021d5 | 22,360 |
def is_generator(f):
"""Return True if a function is a generator."""
isgen = (f.__code__.co_flags & CO_GENERATOR) != 0
return isgen | 239d0854e27a16d9e99102ff9c698086119b8e35 | 22,361 |
import torch
def reward(sample_solution, use_cuda=True, name='reward'):
"""
Args:
sample_solution seq_len of [batch_size]
"""
'''
if 'TSP' in name:
batch_size = sample_solution[0].size(0)
n = len(sample_solution)
tour_len = Variable(torch.zeros([batch_size]))
... | fed916437085d15b2c9c6a04486e43251c3b0422 | 22,362 |
def addRegionEntry(Id: int, parentId: int, name: str, RegionType: RegionType, alias=''):
"""
添加自定义地址信息
:param Id: 地址的ID
:param parentId: 地址的父ID, 必须存在
:param name: 地址的名称
:param RegionType: 地址类型,RegionType,
:param alias: 地址的别名, default=''
:return:
"""
geocoding = jpype.JClass('io.... | ba6c78842f847939f1a44b859156d15738adca58 | 22,363 |
def check_movement(pagination):
"""Check for ability to navigate backward or forward between pages."""
pagination_movements = pagination.find_element_by_xpath(
'.//div[@class="search_pagination_right"]'
).find_elements_by_class_name("pagebtn")
# Check for ability to move back
try:
mo... | 37bb55ae4509f8bdc98d3bf52bbef4a4a1e5d600 | 22,364 |
def glint_correct_image(imarr, glintarr, nir_band=7):
"""
Apply the sunglint removal algorithm from section III of Lyzenga et al.
2006 to a multispectral image array.
Parameters
----------
imarr : numpy array (RxCxBands shape)
The multispectral image array. See `OpticalRS.RasterDS` for ... | 2982883b37fa2452b12311c62f4d0c404f1718f9 | 22,365 |
def get_named_game(id):
"""Get specific game from GB API."""
query_uri = f"{GB_GAME_URL}{id}?format=json&api_key={API_KEY}"
return query_for_goty(query_uri, expect_list=False, always_return_something=False) | 4b4c7efeecace2d07b5ce7052cfa550d233a61bb | 22,366 |
from datetime import datetime
import pytz
def isoweek_datetime(year, week, timezone='UTC', naive=False):
"""
Returns a datetime matching the starting point of a specified ISO week
in the specified timezone (default UTC). Returns a naive datetime in
UTC if requested (default False).
>>> isoweek_da... | d109d8ca0443b6454c7ab58a9482d5c52ec90799 | 22,367 |
def returned(n):
"""Generate a random walk and return True if the walker has returned to
the origin after taking `n` steps.
"""
## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk
for pos in randwalk() >> drop(1) >> takei(xrange(n-1)):
if pos == Origin:
return True
return... | 6c501a58c6d2abe9d9fa76736fabf75f3f78dbd9 | 22,368 |
def get_ego_as_agent(frame: np.ndarray) -> np.ndarray:
"""Get a valid agent with information from the AV. Ford Fusion extent is used.
:param frame: The frame from which the Ego states are extracted
:return: An agent numpy array of the Ego states
"""
ego_agent = np.zeros(1, dtype=AGENT_DTYPE)
eg... | 249ca88c8aa01c7f06c6acf2d8427ca158926603 | 22,369 |
import json
def load_users(dir="private/users"):
"""load_users will load up all of the user json files in the dir."""
files = get_files_in_dir(dir)
dict = {}
for filename in files:
user = {}
filepath = join(dir, filename)
with open(filepath) as file:
try:
... | e9181ff8f34a6c351f874649ec328d14b4ba2784 | 22,370 |
def _scale_annots_dict(annot, new_sz, ann_im_sz):
"""Scale annotations to the new_sz, provided the original ann_im_sz.
:param annot: bounding box in dict format
:param new_sz: new size of image (after linear transforms like resize)
:param ann_im_sz: original size of image for which the bounding boxes we... | 44a0f9bf0b1a9befbaea95fd6b6fd5d9440178a4 | 22,371 |
from typing import Any
from typing import Tuple
from typing import List
import inspect
def get_handlers_in_instance(inst: Any) -> Tuple[List[Handler], List[Handler]]:
"""Get all handlers from the members of an instance.
Args:
inst: Instance to get handlers from.
Returns:
2-tuple containi... | c4f268d06fba208ce2a40bac3700b2c43d394051 | 22,372 |
def django_op_to_flag(op):
"""
Converts a django admin operation string to the matching
grainy permission flag
Arguments:
- op <str>
Returns:
- int
"""
return DJANGO_OP_TO_FLAG.get(op, 0) | 6d221271d69db3ed923395b920ee7aba30b50bab | 22,373 |
def rgb2gray(images):
"""将RGB图像转为灰度图"""
# Y' = 0.299 R + 0.587 G + 0.114 B
# https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
return np.dot(images[..., :3], [0.299, 0.587, 0.114]) | f011345d43f49e1b7d625a4d379a72ec684cab00 | 22,374 |
def mIou(y_true, y_pred, n_classes):
"""
Mean Intersect over Union metric.
Computes the one versus all IoU for each class and returns the average.
Classes that do not appear in the provided set are not counted in the average.
Args:
y_true (1D-array): True labels
y_pred (1D-array): Pr... | aebb9a367f45172b999ddda8eb024371f3e0df3d | 22,376 |
import operator
def drop_last(iterable, n=1):
"""Drops the last item of iterable"""
t1, t2 = tee(iterable)
return map(operator.itemgetter(0), zip(t1, islice(t2, n, None))) | edef599cc1697cd4d8f1e1df2d479e123945aa41 | 22,377 |
def density(height: float) -> float:
"""
Returns the air density in slug/ft^3 based on altitude
Equations from https://www.grc.nasa.gov/www/k-12/rocket/atmos.html
:param height: Altitude in feet
:return: Density in slugs/ft^3
"""
if height < 36152.0:
temp = 59 - 0.00356 * height
... | ec85f9384035808084a024eb5a374ecfe7a64a2f | 22,378 |
def has_paired_before() -> bool:
"""Simple check for whether a device has previously been paired.
This does not verify that the pairing information is valid or up to date.
The assumption being - if it's previously paired, then it has previously
connected to the internet.
"""
identity = Identity... | f43ddf1290fcb101f0a0ae3d0fb6eabc368113c2 | 22,380 |
def caller_linkedin(user_input: dict) -> dict:
"""
Call LinkedIn scraping methods to get info about found and potential subjects.
Args:
`user_input`: user input represented as a dictionary.
Returns:
`dict`: the dictionary with information about found or potential subjects.
"""
r... | abb6277e699efa184949faf2b5c6585734be2f53 | 22,381 |
def service_request_eqf(stub_response):
"""
Return a function to be used as the value matching a ServiceRequest in
:class:`EQFDispatcher`.
"""
def resolve_service_request(service_request_intent):
eff = concretize_service_request(
authenticator=object(),
log=object(),
... | f2a052f975ad8c94a58de50c1eb8aaa563522ca1 | 22,382 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.