content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
def get_byte_range_bounds(byte_range_str: str, total_size: int) -> Tuple[int, int]:
"""Return the start and end byte of a byte range string."""
byte_range_str = byte_range_str.replace("bytes=", "")
segments = byte_range_str.split("-")
start_byte = int(segments[0])
# chrome... | f376f5af0771901d9850e06f08ebd32b13243176 | 3,650,212 |
def privmsg(recipient, s, prefix='', msg=None):
"""Returns a PRIVMSG to recipient with the message msg."""
if conf.supybot.protocols.irc.strictRfc():
assert (areReceivers(recipient)), repr(recipient)
assert s, 's must not be empty.'
if minisix.PY2 and isinstance(s, unicode):
s = s.en... | 1ff0087794732a06c7e2151ad6c255ca863ffb37 | 3,650,213 |
def char_decoding(value):
""" Decode from 'UTF-8' string to unicode.
:param value:
:return:
"""
if isinstance(value, bytes):
return value.decode('utf-8')
# return directly if unicode or exc happens.
return value | b8054b4a5012a6e23e2c08b6ff063cf3f71d6863 | 3,650,214 |
def inv2(x: np.ndarray) -> np.ndarray:
"""矩阵求逆"""
# np.matrix()废弃
return np.matrix(x).I | 9b1b18dc0cbd248c977fd0ae0c35a65b4cd5b797 | 3,650,215 |
def clean_remaining_artifacts(image):
"""
Method still on development. Use at own risk!
Remove remaining artifacts from image
:param image: Path to Image or 3D Matrix representing RGB image
:return: Image
"""
img, *_ = __image__(image)
blur = cv2.GaussianBlur(img, (3, 3), 0)
# conve... | 54473dcce5eb5764e80304836f0ca16ce4d82a77 | 3,650,216 |
def max_simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: самый большой простой делитель числа
"""
return max(simple_dividers(a)) | 3fc2fb51e2940ed07db97285886e7cb30e99d5a0 | 3,650,217 |
def to_light_low_sat(img, new_dims, new_scale, interp_order=1 ):
"""
Turn an image into lightness
Args:
im : (H x W x K) ndarray
new_dims : (height, width) tuple of new dimensions.
new_scale : (min, max) tuple of new scale.
interp_order : interpolation order, de... | 2aca96378551a2a083f1762f30582efe1560f2fb | 3,650,218 |
def get_slug_blacklist(lang=None, variant=None):
"""
Returns a list of KA slugs to skip when creating the channel.
Combines the "global" slug blacklist that applies for all channels, and
additional customization for specific languages or curriculum variants.
"""
SLUG_BLACKLIST = GLOBAL_SLUG_BLAC... | e06dd582812ddd8d2d2e929c733dc957abb748d6 | 3,650,219 |
def get_level_rise(station):
"""For a MonitoringStation object (station), returns a the rate of water level rise, specifically
the average value over the last 2 days"""
#Fetch data (if no data available, return None)
times, values = fetch_measure_levels(station.measure_id, timedelta(days=2))
#O... | 59de80a5bdb5b24711f45395ec9cbc282ad6ad44 | 3,650,220 |
def get_mask_indices(path):
"""Helper function to get raster mask for NYC
Returns:
list: returns list of tuples (row, column) that represent area of interest
"""
raster = tiff_to_array(path)
indices = []
it = np.nditer(raster, flags=['multi_index'])
while not it.finished:
if i... | ff957ffac0f79635e729f8880457d8aa33379185 | 3,650,221 |
def about(isin:str):
"""
Get company description.
Parameters
----------
isin : str
Desired company ISIN. ISIN must be of type EQUITY or BOND, see instrument_information() -> instrumentTypeKey
Returns
-------
TYPE
Dict with description.
"""
params = {'isin': is... | 86554c393087670637859d991bd2ae740ea4ff86 | 3,650,222 |
def aesEncrypt(message):
"""
Encrypts a message with a fresh key using AES-GCM.
Returns: (key, ciphertext)
"""
key = get_random_bytes(symmetricKeySizeBytes)
cipher = AES.new(key, AES.MODE_GCM)
ctext, tag = cipher.encrypt_and_digest(message)
# Concatenate (nonce, tag, ctext) and return ... | 06a13bb605f9038d8096f73681932a09022107b1 | 3,650,223 |
def getType(o):
"""There could be only return o.__class__.__name__"""
if isinstance(o, LispObj):
return o.type
return o.__class__.__name__ | a3602469d8a7d5f6372c6e74d868a903651f85f7 | 3,650,227 |
def failed_revisions_for_case_study(
case_study: CaseStudy, result_file_type: MetaReport
) -> tp.List[str]:
"""
Computes all revisions of this case study that have failed.
Args:
case_study: to work on
result_file_type: report type of the result files
Returns:
a list of fail... | 2e9d5ab3818343e7a07fc3ff7242206f4b231e89 | 3,650,229 |
def bytes_load(path):
"""Load bytest from a file."""
with open(path, 'rb') as f:
return f.read() | ebbeb4bfcecfb94a1fa1ef8640f4e749bfa0dfcb | 3,650,231 |
def get_relationship_length_fam_mean(data):
"""Calculate mean length of relationship for families DataDef 43
Arguments:
data - data frames to fulfill definiton id
Modifies:
Nothing
Returns: added_members
mean_relationship_length - mean relationship length of families
"""
families... | 4d9b76c4dca3e1f09e7dd2684bd96e25792177fd | 3,650,232 |
def convert_hapmap(input_dataframe, recode=False, index_col=0):
""" Specifically deals with hapmap and 23anMe Output
"""
complement = {'G/T': 'C/A', 'C/T': 'G/A', "G/A" : "G/A", "C/A": "C/A", "A/G" : "A/G",
"A/C": "A/C"}
dataframe = input_dataframe.copy()
if recode:
recode = data... | c328cfe41e25f7fd3ff2274861fb6fc89effa181 | 3,650,233 |
def to_base64(message):
"""
Returns the base64 representation of a string or bytes.
"""
return b64encode(to_bytes(message)).decode('ascii') | d3f091f7dbf04850e8c40bca8e7fb0ec06f2848f | 3,650,234 |
import traceback
def create_alerts():
"""
Function to create alerts.
"""
try:
# validate post json data
content = request.json
print(content)
if not content: raise ValueError("Empty value")
if not 'timestamp' in content or not 'camera_id' in content or not 'c... | ca824f0f356cf2b42e7a598810dc89f7121664ba | 3,650,235 |
import numpy
def load_catalog_npy(catalog_path):
"""
Load a numpy catalog (extension ".npy")
@param catalog_path: str
@return record array
"""
return numpy.load(catalog_path) | 912281ad17b043c6912075144e6a2ff3d849a391 | 3,650,238 |
def pgd(fname, n_gg=20, n_mm=20, n_kk=20, n_scale=1001):
"""
:param fname: data file name
:param n_gg: outer iterations
:param n_mm: intermediate iterations
:param n_kk: inner iterations
:param n_scale: number of discretized points, arbitrary
:return:
"""
n_buses, Qmax, Qmin, Y, V_... | 5a00b6992ecf5c4f3b89fcf5151cae71c4a36298 | 3,650,239 |
def find_first_empty(rect):
"""
Scan a rectangle and find first open square
@param {Array} rect Board layout (rectangle)
@return {tuple} x & y coordinates of the leftmost top blank square
"""
return _find_first_empty_wrapped(len(rect[0]))(rect) | d266805761cda903733cef7704baff6d38576b04 | 3,650,240 |
import re
def parseArticle(text: str) -> str:
"""
Parses and filters an article. It uses the `wikitextparser` and custom logic.
"""
# clear the image attachments and links
text = re.sub("\[\[Податотека:.+\]\][ \n]", '', text)
text = wikipedia.filtering.clearCurlyBrackets(text)
# repl... | 7a17e31ec960b568debb9c6e7ccb8018bba19218 | 3,650,241 |
import torch
def exp2(input, *args, **kwargs):
"""
Computes the base two exponential function of ``input``.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.exp2(ttorch.tensor([-4.0, -1.0, 0, 2.0, 4.8, 8.0]))
tensor([6.2500e-02, 5.0000e-01, 1.0... | 17cbc0917acf19932ec4d3a89de8d78545d02e31 | 3,650,242 |
def list_default_storage_policy_of_datastore(
datastore,
host=None,
vcenter=None,
username=None,
password=None,
protocol=None,
port=None,
verify_ssl=True,
):
"""
Returns a list of datastores assign the storage policies.
datastore
Name of the datastore to assign.
... | caf729c258a4ece895d14fdd93ba1f23879453e8 | 3,650,243 |
import numpy
def action_stats(env, md_action, cont_action):
"""
Get information on `env`'s action space.
Parameters
----------
md_action : bool
Whether the `env`'s action space is multidimensional.
cont_action : bool
Whether the `env`'s action space is continuous.
Returns
-------
n_actions_per_dim : list of len... | 8a08b3fe5be20f274680fe33df9ca02456bb511f | 3,650,244 |
def count(pred: Pred, seq: Seq) -> int:
"""
Count the number of occurrences in which predicate is true.
"""
pred = to_callable(pred)
return sum(1 for x in seq if pred(x)) | 09726935174d7590030331da62322da870e216aa | 3,650,245 |
def lambda_k(W, Z, k):
"""Coulomb function $\lambda_k$ as per Behrens et al.
:param W: Total electron energy in units of its rest mass
:param Z: Proton number of daughter
:param k: absolute value of kappa
"""
#return 1.
gammak = np.sqrt(k**2.0-(ALPHA*Z)**2.0)
gamma1 = np.sqrt(1.-(ALPHA... | 9f6a59bd730460c09a3c7f855550254ffb5cdc66 | 3,650,246 |
import pprint
import json
def tryJsonOrPlain(text):
"""Return json formatted, if possible. Otherwise just return."""
try:
return pprint.pformat( json.loads( text ), indent=1 )
except:
return text | 2431479abf6ab3c17ea63356ec740840d2d18a74 | 3,650,247 |
import aiohttp
import websockets
import random
def create_signaling(args):
"""
Create a signaling method based on command-line arguments.
"""
if args.signaling == "apprtc":
if aiohttp is None or websockets is None: # pragma: no cover
raise Exception("Please install aiohttp and web... | f9fe4ed35555381468dbf15379ab70a4af289ac9 | 3,650,248 |
def get_corpus_gene_adjacency(corpus_id):
"""Generate a nugget table."""
corpus = get_corpus(corpus_id)
data = get_gene_adjacency(corpus)
return jsonify(data), 200 | 9dd86e11eba5e5bc5094d89bd15dd9315df40480 | 3,650,249 |
def get_pool_health(pool):
""" Get ZFS list info. """
pool_name = pool.split()[0]
pool_capacity = pool.split()[6]
pool_health = pool.split()[9]
return pool_name, pool_capacity, pool_health | 1a9dbb8477d8735b225afc2bdd683f550602b36e | 3,650,250 |
def resize_short(img, target_size):
""" resize_short """
percent = float(target_size) / min(img.shape[0], img.shape[1])
resized_width = int(round(img.shape[1] * percent))
resized_height = int(round(img.shape[0] * percent))
resized_width = normwidth(resized_width)
resized_height = normwidth(resi... | ca9a71dc97a57c5739419c284514466e86dc3fa1 | 3,650,251 |
def _scale(aesthetic, name=None, breaks=None, labels=None, limits=None, expand=None, na_value=None, guide=None,
trans=None, **other):
"""
Create a scale (discrete or continuous)
:param aesthetic
The name of the aesthetic that this scale works with
:param name
The name of the ... | c8d98a52f2b87340e0a1df46b9f36ca811c18d5d | 3,650,252 |
def logsubexp(x, y):
"""
Helper function to compute the exponential
of a difference between two numbers
Computes: ``x + np.log1p(-np.exp(y-x))``
Parameters
----------
x, y : float or array_like
Inputs
"""
if np.any(x < y):
raise RuntimeError('cannot take log of nega... | a0b0434fb2714f3d1dec24b88ce0fa9ff0110bc0 | 3,650,253 |
def is_sequence_of_list(items):
"""Verify that the sequence contains only items of type list.
Parameters
----------
items : sequence
The items.
Returns
-------
bool
True if all items in the sequence are of type list.
False otherwise.
Examples
--------
>... | e53e5d31e1c4f5649b2f03edf792f810bc398446 | 3,650,254 |
def sum_fib_dp(m, n):
"""
A dynamic programming version.
"""
if m > n: m, n = n, m
large, small = 1, 0
# a running sum for Fibbo m ~ n + 1
running = 0
# dynamically update the two variables
for i in range(n):
large, small = large + small, large
# note that (i + 1)... | 5be6e57ddf54d185ca6d17adebd847d0bc2f56fc | 3,650,255 |
def fibo_dyn2(n):
"""
return
the n-th fibonacci number
"""
if n < 2:
return 1
else:
a, b = 1, 1
for _ in range(1,n):
a, b = b, a+b
return b | e8483e672914e20c6e7b892f3dab8fb299bac6fc | 3,650,256 |
import time
import math
def build_all(box, request_list):
"""
box is [handle, left, top, bottom] \n
request_list is the array about dic \n
****** Attention
before running the function, you should be index.
After build_all, function will close the windows about train tr... | 59db695f802867e85a5e920f2efa8f652ac12823 | 3,650,257 |
def select_results(results):
"""Select relevant images from results
Selects most recent image for location, and results with positive fit index.
"""
# Select results with positive bestFitIndex
results = [x for x in results['items'] if x['bestFitIndex'] > 0]
# counter_dict schema:
# counter... | 85940fe93b33d79ca0a799ca52a9e68439e7e822 | 3,650,258 |
def dc_session(virtual_smoothie_env, monkeypatch):
"""
Mock session manager for deck calibation
"""
ses = endpoints.SessionManager()
monkeypatch.setattr(endpoints, 'session', ses)
return ses | 06876e5ce2d599086efcb37688f5181f32392068 | 3,650,259 |
def is_available(_cache={}):
"""Return version tuple and None if OmnisciDB server is accessible or
recent enough. Otherwise return None and the reason about
unavailability.
"""
if not _cache:
omnisci = next(global_omnisci_singleton)
try:
version = omnisci.version
... | 0edcbfcd1ecb6a56b4b4a6f55907271c9094b8d8 | 3,650,260 |
import copy
def pitch_info_from_pitch_string(pitch_str: str) -> PitchInfo:
"""
Parse a pitch string representation. E.g. C#4, A#5, Gb8
"""
parts = tuple((c for c in pitch_str))
size = len(parts)
pitch_class = register = accidental = None
if size == 1:
(pitch_class,) = parts
e... | cc1b6c0fe64834fe3fdc5249078e10e8f3af1434 | 3,650,261 |
def determine_word_type(tag):
"""
Determines the word type by checking the tag returned by the nltk.pos_tag(arr[str]) function.
Each word in the array is marked with a special tag which can be used to find the correct type of a word.
A selection is given in the dictionaries.
Args:
tag : String tag from the nltk... | 4505d2cf69f961ecdec4e3c693ea85b916acce96 | 3,650,262 |
def get_normalized_map_from_google(normalization_type, connection=None, n_header_lines=0):
"""
get normalized voci or titoli mapping from gdoc spreadsheets
:param: normalization_type (t|v)
:param: connection - (optional) a connection to the google account (singleton)
:param: n_header_lines - (optio... | 61056536cae2da9053f21d2739488c5512546a68 | 3,650,263 |
import io
def parse_file(fname, is_true=True):
"""Parse file to get labels."""
labels = []
with io.open(fname, "r", encoding="utf-8", errors="igore") as fin:
for line in fin:
label = line.strip().split()[0]
if is_true:
assert label[:9] == "__label__"
... | ea6cbd4b1a272f472f8a75e1cc87a2209e439205 | 3,650,264 |
def make_mesh(object_name, object_colour=(0.25, 0.25, 0.25, 1.0), collection="Collection"):
"""
Create a mesh then return the object reference and the mesh object
:param object_name: Name of the object
:type object_name: str
:param object_colour: RGBA colour of the object, defaults to a shade of g... | 73fd8d13d471c55258a06feb71eec51ca51f23f9 | 3,650,266 |
import optparse
def _OptionParser():
"""Returns the options parser for run-bisect-perf-regression.py."""
usage = ('%prog [options] [-- chromium-options]\n'
'Used by a try bot to run the bisection script using the parameters'
' provided in the auto_bisect/bisect.cfg file.')
parser = optpars... | 7485db294d89732c2c5223a3e3fe0b7773444b49 | 3,650,267 |
def calc_radiance(wavel, Temp):
"""
Calculate the blackbody radiance
Parameters
----------
wavel: float or array
wavelength (meters)
Temp: float
temperature (K)
Returns
-------
Llambda: float or arr
monochromatic radiance (W/m^2/m/sr)
... | 9a957b42e0e92614709f7157765f0185e1dd532a | 3,650,268 |
def _JMS_to_Fierz_III_IV_V(C, qqqq):
"""From JMS to 4-quark Fierz basis for Classes III, IV and V.
`qqqq` should be of the form 'sbuc', 'sdcc', 'ucuu' etc."""
#case dduu
classIII = ['sbuc', 'sbcu', 'dbuc', 'dbcu', 'dsuc', 'dscu']
classVdduu = ['sbuu' , 'dbuu', 'dsuu', 'sbcc' , 'dbcc', 'dscc']
if... | 5629a4e88996bd3ba30bd68cc8758b3d55abd093 | 3,650,270 |
from typing import Any
def get_parsed_args() -> Any:
"""Return Porcupine's arguments as returned by :func:`argparse.parse_args`."""
assert _parsed_args is not None
return _parsed_args | 9e4dc1eadc3c68d8a8e5a5a885fecf7c0ec89856 | 3,650,271 |
def get_license_description(license_code):
"""
Gets the description of the given license code. For example, license code '1002' results in 'Accessory Garage'
:param license_code: The license code
:return: The license description
"""
global _cached_license_desc
return _cached_license_desc[lic... | 3de38be73d303036872b285c2dd7c0048ba5660f | 3,650,272 |
import pickle
import getpass
def db_keys_unlock(passphrase) -> bool:
"""Unlock secret key with pass phrase"""
global _secretkeyfile
try:
with open(_secretkeyfile, "rb") as f:
secretkey = pickle.load(f)
if not secretkey["locked"]:
print("Secret key file is already u... | 4d1af86143384ff6228ad086d92f797b7529c73e | 3,650,273 |
def list_domains():
"""
Return a list of the salt_id names of all available Vagrant VMs on
this host without regard to the path where they are defined.
CLI Example:
.. code-block:: bash
salt '*' vagrant.list_domains --log-level=info
The log shows information about all known Vagrant e... | af04859c5d6e0cd2edb3d3cec88ebebd777c93d6 | 3,650,274 |
def get_old_options(cli, image):
""" Returns Dockerfile values for CMD and Entrypoint
"""
return {
'cmd': dockerapi.inspect_config(cli, image, 'Cmd'),
'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'),
} | eed75800ae3afdc99fdcd5c0f5dc36504d5db96c | 3,650,275 |
def line_crops_and_labels(iam: IAM, split: str):
"""Load IAM line labels and regions, and load line image crops."""
crops = []
labels = []
for filename in iam.form_filenames:
if not iam.split_by_id[filename.stem] == split:
continue
image = util.read_image_pil(filename)
... | f223ded3c2dc9254985ad450995f8dc598dc5411 | 3,650,276 |
def convert(chinese):
"""converts Chinese numbers to int
in: string
out: string
"""
numbers = {'零':0, '一':1, '二':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '壹':1, '贰':2, '叁':3, '肆':4, '伍':5, '陆':6, '柒':7, '捌':8, '玖':9, '两':2, '廿':20, '卅':30, '卌':40, '虚':50, '圆':60, '近':70, '枯':80, '无':90}
... | cf2ece895698e2d99fde815efa0339687eadda97 | 3,650,277 |
def computeZvector(idata, hue, control, features_to_eval):
"""
:param all_data: dataframe
:return:
"""
all_data = idata.copy()
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
m_indexes = list(all_data[hue].unique().astype('str'))
query_one = ""
for el in contr... | d80e6a9fe754cb8558598c72ab2f076fab329750 | 3,650,278 |
def getjflag(job):
"""Returns flag if job in finished state"""
return 1 if job['jobstatus'] in ('finished', 'failed', 'cancelled', 'closed') else 0 | bf0c0a85cb1af954d25f4350e55b9e3604cf7c79 | 3,650,279 |
import copy
def json_parse(ddict):
"""
https://github.com/arita37/mlmodels/blob/dev/mlmodels/dataset/test_json/test_functions.json
https://github.com/arita37/mlmodels/blob/dev/mlmodels/dataset/json/benchmark_timeseries/gluonts_m5.json
"deepar": {
"model_pars": {
"model_... | 30b037531ac129a2a597b146c935fe344566a547 | 3,650,280 |
def read_viz_icons(style='icomoon', fname='infinity.png'):
""" Read specific icon from specific style
Parameters
----------
style : str
Current icon style. Default is icomoon.
fname : str
Filename of icon. This should be found in folder HOME/.dipy/style/.
Default is infinity... | 8d97ebb450b94dce5c4feb3f631cd9deebcdb1c1 | 3,650,281 |
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="12345",
domain=DOMAIN,
data={CONF_API_KEY: "tskey-MOCK", CONF_SYSTEM_ID: 12345},
unique_id="12345",
) | cb2a5b8d7e84d1b825e79a9b4e3aebc8f8c60783 | 3,650,282 |
import datasets
def get_mnist_loader(batch_size, train, perm=0., Nparts=1, part=0, seed=0, taskid=0, pre_processed=True, **loader_kwargs):
"""Builds and returns Dataloader for MNIST and SVHN dataset."""
transform = transforms.Compose([
transforms.Grayscale(),
transform... | 2181ffa0abd4f1357ec7cc8cdf52b0eb86a2d13c | 3,650,283 |
def read_data(filename):
"""
Reads orbital map file into a list
"""
data = []
f = open(filename, 'r')
for line in f:
data += line.strip().split('\n')
f.close()
return data | 7c2f5669735e39352b0b655425a70993baae32ef | 3,650,284 |
from typing import Union
def _form_factor_pipi(
self, s: Union[float, npt.NDArray[np.float64]], imode: int = 1
) -> Union[complex, npt.NDArray[np.complex128]]:
"""
Compute the pi-pi-V form factor.
Parameters
----------
s: Union[float,npt.NDArray[np.float64]
Square of the center-of-mas... | 92438400debb52bff6480791631e2b60043c758f | 3,650,285 |
import re
import click
def string_to_epoch(s):
"""
Convert argument string to epoch if possible
If argument looks like int + s,h,md (ie, 30d), we'll pass as-is
since pushshift can accept this. Per docs, pushshift supports:
Epoch value or Integer + "s,m,h,d" (i.e. 30d for 30 days)
:param s: ... | b45db1d589cbe71eec5f11d53d2851dee258da8f | 3,650,287 |
import array
def spline_filter(Iin, lmbda=5.0):
"""Smoothing spline (cubic) filtering of a rank-2 array.
Filter an input data set, `Iin`, using a (cubic) smoothing spline of
fall-off `lmbda`.
"""
intype = Iin.dtype.char
hcol = array([1.0,4.0,1.0],'f')/6.0
if intype in ['F','D']:
I... | ee606bdceaf974671ccf36b9d498204613c12f51 | 3,650,288 |
def _construct_aline_collections(alines, dtix=None):
"""construct arbitrary line collections
Parameters
----------
alines : sequence
sequences of segments, which are sequences of lines,
which are sequences of two or more points ( date[time], price ) or (x,y)
date[time] may be ... | 863fd8c6e8d0b1a39c5a79bca7a0eaa5b2204aea | 3,650,289 |
def is_mergeable(*ts_or_tsn):
"""Check if all objects(FermionTensor or FermionTensorNetwork)
are part of the same FermionSpace
"""
if isinstance(ts_or_tsn, (FermionTensor, FermionTensorNetwork)):
return True
fs_lst = []
site_lst = []
for obj in ts_or_tsn:
if isinstance(obj... | de5f4fc47874e328bcdd078e2bdf8d6f53d6d4e6 | 3,650,290 |
def query_for_account(account_rec, region):
""" Performs the public ip query for the given account
:param account: Account number to query
:param session: Initial session
:param region: Region to query
:param ip_data: Initial list. Appended to and returned
:return: update ip_data list
"""... | 61055939990175c6e2cb850ede7d448a261ccdff | 3,650,292 |
from typing import List
def filter_list_of_dicts(list_of_dicts: list, **filters) -> List[dict]:
"""Filter a list of dicts by any given key-value pair.
Support simple logical operators like: '<,>,<=,>=,!'. Supports
filtering by providing a list value i.e. openJobsCount=[0, 1, 2].
"""
for key, val... | f926b7c478400d3804d048ced823003e48fd5ef1 | 3,650,293 |
def construct_pos_line(elem, coor, tags):
"""
Do the opposite of the parse_pos_line
"""
line = "{elem} {x:.10f} {y:.10f} {z:.10f} {tags}"
return line.format(elem=elem, x=coor[0], y=coor[1], z=coor[2], tags=tags) | 21ca509131c85a2c7bc24d00a28e7d4ea580a49a | 3,650,294 |
def compute_pcs(predicts, labels, label_mapper, dataset):
"""
compute correctly predicted full spans. If cues and scopes are predicted jointly, convert cue labels to I/O labels depending on the
annotation scheme for the considered dataset
:param predicts:
:param labels:
:return:
"""
def ... | 5f046c1599617ad7620ea9a618f85f02dd93e28c | 3,650,295 |
def pentomino():
"""
Main pentomino routine
@return {string} solution as rectangles separated by a blank line
"""
return _stringify(
_pent_wrapper1(tree_main_builder())(rect_gen_boards())) | 07e448efdbfe5cb43ce943f33f24a7887878001f | 3,650,296 |
def do_login(request, username, password):
""" Check credentials and log in """
if request.access.verify_user(username, password):
request.response.headers.extend(remember(request, username))
return {"next": request.app_url()}
else:
return HTTPForbidden() | f7c076c6f4a6ac51bf5a3ea39116166002ce1833 | 3,650,297 |
from tokenize import Token
import re
def _interpolate(format1):
"""
Takes a format1 string and returns a list of 2-tuples of the form
(boolean, string) where boolean says whether string should be evaled
or not.
from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee)
"""
def ma... | 9af06b91f0ad2e15fd7479ac2e1dedc5443b6e34 | 3,650,298 |
def approxIndex(iterable, item, threshold):
"""Same as the python index() function but with a threshold from wich values are considerated equal."""
for i, iterableItem in rev_enumerate(iterable):
if abs(iterableItem - item) < threshold:
return i
return None | 45ec7b816674231a5efa8a559e9f9416a81987f5 | 3,650,299 |
import random
def delete_important_words(word_list, replace=''):
"""
randomly detele an important word in the query or replace (not in QUERY_SMALL_CHANGE_SETS)
"""
# replace can be [MASK]
important_word_list = set(word_list) - set(QUERY_SMALL_CHANGE_SETS)
target = random.sample(important_w... | 336518cb1c52f896fc9878e1c11b3f0e72c4f36a | 3,650,300 |
import numpy as np
def prot(vsini, st_rad):
"""
Function to convert stellar rotation velocity vsini in km/s to rotation period in days.
Parameters:
----------
vsini: Rotation velocity of star in km/s.
st_rad: Stellar radius in units of solar radii
Returns
------
... | db2ef4648c5142a996e4a700aee0c7df0f02a394 | 3,650,301 |
def dialog_sleep():
"""Return the time to sleep as set by the --exopy-sleep option.
"""
return DIALOG_SLEEP | cc40ffa09c83bd095f685b3b1d237545b8d7dd34 | 3,650,302 |
def required_overtime (db, user, frm) :
""" If required_overtime flag is set for overtime_period of dynamic
user record at frm, we return the overtime_period belonging to
this dyn user record. Otherwise return None.
"""
dyn = get_user_dynamic (db, user, frm)
if dyn and dyn.overtime_perio... | 052e1289a0d7110100b3a1ea0ad90fa7bd000cce | 3,650,303 |
def get_best_fit_member(*args):
"""
get_best_fit_member(sptr, offset) -> member_t
Get member that is most likely referenced by the specified offset.
Useful for offsets > sizeof(struct).
@param sptr (C++: const struc_t *)
@param offset (C++: asize_t)
"""
return _ida_struct.get_best_fit_member(*arg... | 7d4032d5cedb789d495e658eda939c36591f3506 | 3,650,304 |
def convert_time(time):
"""Convert given time to srt format."""
stime = '%(hours)02d:%(minutes)02d:%(seconds)02d,%(milliseconds)03d' % \
{'hours': time / 3600,
'minutes': (time % 3600) / 60,
'seconds': time % 60,
'milliseconds': (time % 1) * 1000}
return st... | 948e6567c8bc17ccb5f98cf8c8eaf8fe6e8d0bec | 3,650,305 |
def Returns1(target_bitrate, result):
"""Score function that returns a constant value."""
# pylint: disable=W0613
return 1.0 | 727e58e0d6d596cf4833ca3ca1cbcec6b9eedced | 3,650,306 |
def test_abstract_guessing():
"""Test abstract guessing property."""
class _CustomPsychometric(DiscriminationMethod):
def psychometric_function(self, d):
return 0.5
with pytest.raises(TypeError, match="abstract method"):
_CustomPsychometric() | 996f6fb4d6b819e15fb3a931c0dc2a1f211e3d58 | 3,650,307 |
import re
def remove_repeats(msg):
"""
This function removes repeated characters from text.
:param/return msg: String
"""
# twitter specific repeats
msg = re.sub(r"(.)\1{2,}", r"\1\1\1", msg) # characters repeated 3 or more times
# laughs
msg = re.sub(r"(ja|Ja)(ja|Ja)+(j)?", r"jaja",... | 590ab42f74deaa9f8dc1eb9c8b11d81622db2e6d | 3,650,308 |
def _legend_main_get(project, row):
"""
forma la leyenda de la serie principal del gráfico
input
project: es el tag project del proyecto seleccionado
en fichero XYplus_parameters.f_xml -en XYplus_main.py-
row: es fila activa devuelta por select_master) de donde se
ex... | 3938d723bd44a67313b86f956464fd186ef25386 | 3,650,309 |
def ordinal_mapper(fh, coords, idmap, fmt=None, n=1000000, th=0.8,
prefix=False):
"""Read an alignment file and match reads and genes in an ordinal system.
Parameters
----------
fh : file handle
Alignment file to parse.
coords : dict of list
Gene coordinates table... | 955c411e608fdb3cf55d0c52350b38061f87cd3a | 3,650,311 |
def file_lines(filename):
"""
>>> file_lines('test/foo.txt')
['foo', 'bar']
"""
return text_file(filename).split() | b121ba549606adeac244b063ff679192951c2ff8 | 3,650,312 |
def repr_should_be_defined(obj):
"""Checks the obj.__repr__() method is properly defined"""
obj_repr = repr(obj)
assert isinstance(obj_repr, str)
assert obj_repr == obj.__repr__()
assert obj_repr.startswith("<")
assert obj_repr.endswith(">")
return obj_repr | 28537f4f48b402a2eba290d8ece9b765eeb9fdc3 | 3,650,313 |
def indexName():
"""Index start page."""
return render_template('index.html') | 0340e708a82052a98e6e9e92bfde2eb04128d354 | 3,650,317 |
def translate_http_code():
"""Print given code
:return:
"""
return make_http_code_translation(app) | c9b501b57323aeb765be47af134dd2de1c1d084e | 3,650,318 |
import warnings
def parmap(f, X, nprocs=1):
"""
parmap_fun() and parmap() are adapted from klaus se's post
on stackoverflow. https://stackoverflow.com/a/16071616/4638182
parmap allows map on lambda and class static functions.
Fall back to serial map when nprocs=1.
"""
if nprocs < 1:
... | 66a498966979ca00c9a7eedfc1113a07b9076245 | 3,650,320 |
def is_char_token(c: str) -> bool:
"""Return true for single character tokens."""
return c in ["+", "-", "*", "/", "(", ")"] | 3d5691c8c1b9a592987cdba6dd4809cf2c410ee8 | 3,650,321 |
import numpy
def _float_arr_to_int_arr(float_arr):
"""Try to cast array to int64. Return original array if data is not representable."""
int_arr = float_arr.astype(numpy.int64)
if numpy.any(int_arr != float_arr):
# we either have a float that is too large or NaN
return float_arr
else:
... | 73643757b84ec28ed721608a2176b292d6e90837 | 3,650,322 |
def latest(scores: Scores) -> int:
"""The last added score."""
return scores[-1] | 393c1d9a4b1852318d622a58803fff3286db98af | 3,650,323 |
def get_dp_2m(wrfin, timeidx=0, method="cat", squeeze=True,
cache=None, meta=True, _key=None, units="degC"):
"""Return the 2m dewpoint temperature.
This functions extracts the necessary variables from the NetCDF file
object in order to perform the calculation.
Args:
... | e16a5a3951312254eb852a5e03987aab32a91373 | 3,650,324 |
def fit_uncertainty(points, lower_wave, upper_wave, log_center_wave, filter_size):
"""Performs fitting many times to get an estimate of the uncertainty
"""
mock_points = []
for i in range(1, 100):
# First, fit the points
coeff = np.polyfit(np.log10(points['rest_wavelength']),
... | cca5193e55d7aeef710a08fb16df8c896bbeef90 | 3,650,325 |
def from_dateutil_rruleset(rruleset):
"""
Convert a `dateutil.rrule.rruleset` instance to a `Recurrence`
instance.
:Returns:
A `Recurrence` instance.
"""
rrules = [from_dateutil_rrule(rrule) for rrule in rruleset._rrule]
exrules = [from_dateutil_rrule(exrule) for exrule in rruleset.... | cd5ab771eebbf6f68ce70a8d100ad071561541de | 3,650,326 |
import re
def error_038_italic_tag(text):
"""Fix the error and return (new_text, replacements_count) tuple."""
backup = text
(text, count) = re.subn(r"<(i|em)>([^\n<>]+)</\1>", "''\\2''", text, flags=re.I)
if re.search(r"</?(?:i|em)>", text, flags=re.I):
return (backup, 0)
else:
re... | b0c2b571ade01cd483a3ffdc6f5c2bbb873cd13c | 3,650,327 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.