content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def timeseries_to_str(ts, fmt="%.18e"):
"""Transforms a time series to its representation as a string (used when saving time series to disk).
Parameters
----------
ts : array-like
Time series to be represented.
fmt : string (default: "%.18e")
Format to be used to write each value.
... | 898d129e239071a92b1de4a07e7613198c275833 | 74,480 |
def get_url(url, data=None):
"""
Возвращает открытый файловый объект
Запускает исключение parse_html.URLError в случае ошибки"""
res = True
msg = ''
try:
f = urllib2.urlopen(url, data)
except urllib2.HTTPError, err:
res = False
msg = str(err.code) # 404, ...
... | 5bf2dec2fb166fd2dce660351b417cd28651063d | 74,481 |
import skimage.restoration
def shift_invariant_denoising(x, max_shifts, func='denoise_wavelet', out_dtype='image', **kwargs):
""" A wrapper of the skimage.restoration module.
Unfinished, only support denoise_wavelet now.
"""
if not callable(func):
if isinstance(func, str):
fun... | 1513d7f95f161f46d682e7df184c74e1101a3847 | 74,482 |
from typing import List
def one_minus(data: List[float]) -> List[float]:
"""
return 1 - each element in list
"""
return list(map(lambda elem: 1 - elem, data)) | bb5c9a3d27866b408e519541778c7cdb8bd9ac13 | 74,483 |
def call_method(obj, methodName):
"""
Execute a method of an object using previously passed arguments with setarg filter
"""
method = getattr(obj, methodName)
if hasattr(obj, '__call_arguments'):
ret = method(*obj.__call_arguments)
del obj.__call_arguments
return ret
retu... | 7bd94cdf81f448a8b73bbf3bcdda47cf4f5580cd | 74,484 |
from typing import List
def boxes2polygons(boxes: np.ndarray or List[np.ndarray]):
"""
将矩形框转为多边形轮廓
:param self:
:param boxes:[num_polygons,4], box is [xmin, ymin, xmax, ymax]
:return: polygons: [num_polygons,num_point,2]
"""
polygons = []
for box in boxes:
xmin, ymin, xmax, yma... | 64dec0756d8d15c6b4ddc88f04b383c60bf8aa41 | 74,485 |
def get_bracketing_pattern_feature(dataset):
"""
Return bracketing_pattern feature (sorted tuple of adj_quantities seen).
"""
grouped = dataset.groupby(
['tube_assembly_id', 'supplier', 'quote_date'])
bracketing_pattern = [None] * len(dataset)
for t_s_q, indices in grouped.groups.iterite... | 9b262fcff8e227dc50ea769ac8953df0aeba62b7 | 74,486 |
import array
def sliceAtoms(atoms, select):
"""Slice *atoms* using the selection defined by *select*.
:arg atoms: atoms to be selected from
:type atoms: :class:`Atomic`
:arg select: a :class:`Selection` instance or selection string
:type select: :class:`Selection`, str
"""
if atoms == ... | 9a99a7d1b0ce198488c69b2069876ee527e9f37a | 74,487 |
import copy
def _deep_split(filenames, size_per_shard, parsed_formats):
"""Split files into roots using the first FileFormat.
Deep split can split within a file. It tells the first format how big
a split it wants and the first format will do the actually splitting
because only the first format knows how to o... | c1002dd5b6db28cbe6e8652d11d583bcc023a841 | 74,488 |
def files_in_handler(ctx, param, value):
"""Process and validate input file names"""
return tuple(file_in_handler(ctx, param, item) for item in value) | 9ca82d8b2b2fb4366a5d77f2291c55c225910174 | 74,489 |
def vCPA3(v_known, r1, r2, omg1=0, omg2=0):
"""
Complex-algebraic velocity analysis, Theory of Machines and Mechanisms
The unknowns are V1_T, V2_T
v_known + v_r1 = v_r2
"""
A = [[-np.cos(np.angle(r1)), np.cos(np.angle(r2))],
[-np.sin(np.angle(r1)), np.sin(np.angle(r2))]]
... | 2513ace57d568c865e2a016bb925bd419177620c | 74,490 |
from manubot.pandoc.bibliography import (
load_bibliography as load_bibliography_pandoc,
)
from manubot.cite.csl_item import CSL_Item
import pathlib
import logging
def load_bibliography(path: str) -> list:
"""
Load a bibliography as CSL Items (a CSL JSON Python object).
For paths that already ... | 026cd7218dbd0e4909db0e5915bf595a798415e1 | 74,491 |
def listObjects(s3, bucket_name, filepath):
"""Get list of filepaths to objects in bucket_name, filepath
Args:
bucket_name (str): s3 bucket name
filepath (str): Path to folder
"""
try:
list_object_key = [obj.key for obj in list(self.s3session.Bucket(self.bucket_name).objects.fil... | 2f2151c89718ea8167ec1ec3fd5732b82929193f | 74,492 |
def versions(request):
"""List version details of components used by the API."""
adapter_version = get_adapter_factory(request).describe_adapter()
adapter_version['type'] = 'adapter'
twitcher_version = {
'name': 'Twitcher',
'version': __version__.__version__,
'type': 'application... | 41846123112e75b148b60c2ac207aff29d744f70 | 74,493 |
def exercise_output(template):
"""Outputs the way specified in the exercise"""
result = """Marca: {0}
Modelo: {1}
Preco: {2}
Motor: {3}
Ano: {4}
Km: {5}
Combustivel: {6}
Cambio: {7}
Direcao: {8}
Cor: {9}
Ar-cond: {10}
Opcionais: {11}\n"""
return result.format(
template["Brand"],
template["Mo... | 0944b47d28c8b95c7eab32b799066af14b2b95ea | 74,495 |
import torch
def load_dataset(name, device, args, return_nid=False):
"""
Load dataset and move graph and features to device
"""
if name not in ["ogbn-products","ogbn-papers100M"]:
raise RuntimeError("Dataset {} is not supported".format(name))
dataset = NodePropPredDataset(name=name, root=... | 6677245a9ecc4074cd6e2177987436b7c93b3ca2 | 74,496 |
def strings_to_ints(lst):
"""transforms a list of strings to a list of ints
ARGS:
list of strings
RETURNS:
list of ints
RAISES:
ValueError: when the string in the list is not a number
"""
return None | ec399c6e4ed7f737cdfe243112fe30bc4c4dd21e | 74,497 |
def get_table(tables, var, phi):
"""
Table Searching function
"""
if phi>=50:
phi = 50
#First find phi index
idx=0
while(True):
if tables['phi'][idx]>=phi:
break
idx+=1
if(tables['phi'][idx-1]==phi):
return tables[var][idx-1]
else:
... | 55a0feae3d67c960f815a46bb0bc43f0ed7cf5a9 | 74,498 |
async def get_genres_csv(csv_or_wild):
"""
Get genre fields by id or name when wild. ?full=0 for basic information.
"""
genres = []
for id in csv_or_wild.split(','):
genres.append(Genre(id=id))
action = {"mode":"get", "args":request.args}
outgoing = Manage_DATA(action=action, genres... | 5edea14a26ab734f97d7043eff95631beb48e679 | 74,499 |
def device_session_token(db: Session, device: Device) -> str:
"""
Get session token for a device.
A device session token consists of two parts:
<base64_encoded device id>.<random token>
The hash of the session token is stored in the database.
"""
session_token, session_token_hash = ses... | be3de12065b9b6ec0e89e6954d81186d2b25b5d9 | 74,500 |
def spearman_score(true_probs, pred_probs):
"""
A metric to assess multilabel regression performance using the
un-weighted class-average 0-clipped Spearman Correlation.
can be passes to sklearn make_scorer
"""
m, c = true_probs.shape
assert m == pred_probs.shape[0]
i... | a8658ba7940ebfa9d98f23f4e103429b6c18d35a | 74,501 |
def _GetMetdataValue(metadata, key):
"""Finds a value corresponding to a given metadata key.
Args:
metadata: metadata object, i.e. a dict containing containing 'items'
- a list of key-value pairs.
key: name of the key.
Returns:
Corresponding value or None if it was not found.
"""
for item ... | e4ec468fe1e79605d3d7199a703981bae02bfaa3 | 74,502 |
def uuid():
"""Generates random UUID used as user token for verification, reseting password etc.
Returns:
string: 32 characters long string
"""
return uuid4().hex | 952d5ff50e9b326e729c8fdb2d02cac016268211 | 74,503 |
import codecs
def readme():
"""
render long description for setup function
"""
with codecs.open('README.md', encoding='UTF-8') as handle:
return handle.read() | dfecd416b15572cb1335db226736f185190f2985 | 74,504 |
def _tokenize_query_string(query_string, match_stopwords):
"""
Returns a list of WordDocumentField keys to fetch
based on the query_string
"""
# We always lower case. Even Atom fields are case-insensitive
query_string = query_string.lower()
branches = query_string.split(" or ")
... | 4d9118e67cdf7a0a5cf3fb195b2c910775515f8f | 74,505 |
def _get_sentence_tokens(s: Sentence, replace_entities=True, mark_boundaries=False):
"""
Get the list of sentence tokens.
:param s: a sentence object
:param replace_entities: optionally replace the entities with a placeholder.
:param mark_boundaries: optionally add sentence start and end markers.
... | f7da9bb081f577cc8312d828f16e234d9ff0e494 | 74,506 |
from typing import OrderedDict
def updateConfOptions(
conf_options: t.MutableMapping[str, t.Dict[t.Any, t.Any]]
) -> "OrderedDict[str, t.Dict[t.Any, t.Any]]":
"""
Return Conf Options from all array types
"""
conf_options = update_dict(conf_options, rpi.CONF_OPTIONS)
conf_options = update_dict(... | c042bf945e154ce0335013dde7eb49b4f669a639 | 74,507 |
def log_exception(method):
"""Decorator for logging the exception from vtgatev2.
The convert_exception method interprets and recasts the exceptions
raised by lower-layer. The inner function calls the appropriate vtdb_logger
method based on the exception raised.
Args:
exc: exception raised by calling cod... | 2fb28b11bec0423b3a943e6041d7f0f3d478373b | 74,508 |
import re
def match_is_ipv4_address(value):
"""Match given value as a valid dotted-quad IPv4 address."""
# Apply the dotted-quad pattern to the string and detect a mismatch
try:
match = re.search(r'^(\d+)\.(\d+)\.(\d+)\.(\d+)$', value)
except TypeError:
return u'{0} must be a string in... | d4573d5919d1811b83c26928f3e403d070c41f37 | 74,509 |
import click
def init():
"""Top level command handler."""
@click.command()
@click.option('--port',
required=True,
type=int,
help='Service port to listen on.')
@click.option('--account-id',
required=True,
help='A... | 9174b056d2c70e06e19ff9c26e8fcfb7bf57f042 | 74,510 |
def _get_options(ret=None):
"""
Get the pushover options from salt.
"""
defaults = {"priority": "0"}
attrs = {
"pushover_profile": "profile",
"user": "user",
"device": "device",
"token": "token",
"priority": "priority",
"title": "title",
"api... | b6f0c97efe2d05d6f066f55d2ecc84b238c738e7 | 74,511 |
def binary_crossentropy(input_t, target_t):
"""
Binary cross entropy operation.
arguments
input_t Tensor
must be the result
of sigmoid operation.
target_t Tensor
target probabilities
... | 76ef80e5bc7cdc5e1bd6eabd317ac1ec833cf106 | 74,513 |
def context_find(reptile, configs, result):
""" 内容元素搜寻算法 """
document = reptile['document']
for k, v in configs.items():
# 特殊标识
if k[:4] == 'ext|':
result[k[4:]] = v
continue
# 多重选择器 每个选择器均进行一次元素查找
arr_v = v.split('||')
tmp_context = ""
... | cda96a2bbe75b222fe5b8f72a5a3c30fbd64b5bf | 74,514 |
import math
def smooth(low, high, x):
"""Smoothly goes from low to high"""
return low + (high - low) * (1 + math.cos(math.pi * (1-x))) / 2 | 3278891277048a4d6a19f7a5450a0a8a5f1d0ad9 | 74,515 |
def make_url(imdb_id):
"""Return IMDb URL of the given ID"""
return u'https://www.imdb.com/title/%s/' % imdb_id | 7fbb77a0ae7858608b5ee2516d8a464e6952dcd7 | 74,516 |
from typing import Callable
from typing import List
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: Callable[[List[Entity]], None],
):
"""Setup sensor platform."""
context = hass.data[DOMAIN][entry.entry_id]
if not isinstance(context, RctPowerContext)... | 1cc69e9cf81f428967abe79a90009851e316030b | 74,517 |
import re
def parser_factory(*args):
"""
Instantiate the right parser based on input. See MeshParser for
arguments.
"""
if re.search(r"\.mesh\s*$", args[0]):
parser = ParseMESHFormat(args[0])
elif re.search(r"\.msh\s*$", args[0]):
parser = ParseMSHFormat(*args)
elif re.sear... | 8c63af35c52053a05b4a8b0ed1ee937833ed2b8f | 74,518 |
def compose_fundamental_matrix(K1, T1, K2, T2):
"""Compose fundamental matrix.
Args:
K1 (array): intrinsic of 1st camera
T1 (array): extrinsic of 1st camera
K2 (array): intrinsic of 2nd camera
T2 (array): extrinsic of 2nd camera
Returns:
array: fundamental matrix
... | f1f88ba7973912406ce3c8d58bf502d00281bc7c | 74,519 |
import logging
def get_logger():
"""
Return the default logger.
:return:
"""
logging.setLoggerClass(CustomLogging)
return logging.getLogger(APP_LOGGER) | a1a5ed43e4d5e5aef574e204c1e4c75fc92c8dc7 | 74,520 |
def stis_identify(origin, *args, **kwargs):
"""Check whether given file contains HST/STIS spectral data."""
with fits.open(args[0]) as hdu:
if hdu[0].header['TELESCOP'] == 'HST' and hdu[0].header['INSTRUME'] == 'STIS':
return True
return False | 27721d69dbaa0fe4d2d2130afc9458579bc99405 | 74,521 |
def _parse_header(path):
"""Parses all GAMMA header file fields into a dictionary"""
with open(path) as f:
text = f.read().splitlines()
raw_segs = [line.split() for line in text if ':' in line]
# convert the content into a giant dict of all key, values
return dict((i[0][:-1], i[1:]) for... | 93e512388f3c5c5f8ee0e9f0365fa5328b0ea864 | 74,522 |
from typing import Optional
def ssc_to_sm(
ssc_simfile: SSCSimfile,
*,
simfile_template: Optional[SMSimfile] = None,
chart_template: Optional[SMChart] = None,
invalid_property_behaviors: InvalidPropertyBehaviorMapping = {},
) -> SMSimfile:
"""
Convert an SSC simfile to an equivalent SM si... | 356c9dae0a3b0611e6bb5a899498497b7efb975f | 74,523 |
def parse_trousers_input_args(s):
"""Parses Trspi family's input arguments.
Given a string from of input arguments of a trousers API, the input arguments
parsed into tokens and then convert to tuples. For example:
"BYTE *s, unsigned *len"
->
[("BYTE *", "s"), ("unsigned *", "len")]
Args:
s: String r... | 366edb8d3b8f1369b8c4b095e037a2192b056e0d | 74,524 |
import urllib2, urllib
def defunct_post_rings_convert(inputstream):
"""
#impossible to do with urllib2
posts input glycan stream to the new converter tool at RINGS
http://rings.t.soka.ac.jp/cgi-bin/tools/utilities/convert/index.pl
http://rings.t.soka.ac.jp/cgi-bin/tools/utilities/convert/convert_i... | 33039b390063a98876c03f71438e839bb3bedede | 74,525 |
import unicodedata
def blacklist(filtr=FILTR):
"""Blacklisted unicode characters"""
return [c for c in chars() if unicodedata.category(c) in filtr] | 6d340b9aa70bac44bc8c52e263f4497d10c9d1a5 | 74,527 |
import torch
def mix_up(images, labels, alpha=0.2):
"""
mix up inputs pairs of target and lambda
:param images:
:param labels:
:return:
"""
if alpha > 0:
np.random.beta(alpha, alpha)
beta_distributed = torch.distributions.beta.Beta(alpha, alpha)
lambda_ = beta_distr... | 3423d56df178d3249a2a63998fd978157a7a09c4 | 74,528 |
def _census_table(projection_admits, hosp_los, icu_los, vent_los) -> pd.DataFrame:
"""ALOS for each category of COVID-19 case (total guesses)"""
los_dict = {
"hosp": hosp_los,
"icu": icu_los,
"vent": vent_los,
}
census_dict = dict()
for k, los in los_dict.items():
c... | 47460ca0e0d9fb48caafa05102164a347ab51668 | 74,529 |
def encode_color(rgb):
"""rgb to 8-color pallete"""
r = "1" if rgb[0] > 127 else "0"
g = "1" if rgb[1] > 127 else "0"
b = "1" if rgb[2] > 127 else "0"
for i in range(8):
if r + g + b == format(i, '03b'):
return i | 81c04e6307eb3d36459cd24c1780e26d792ea6ab | 74,530 |
def mergeFlavor(flavor, mergeBase):
"""
Merges the given flavor with the mergeBase - if flavor
doesn't contain use flags, then include the mergeBase's
use flags. If flavor doesn't contain an instruction set, then
include the mergeBase's instruction set(s)
"""
if flavor is None:
retu... | ceec4ec695802559ca46a66c5e4cdc49d65f8c8a | 74,531 |
def incremental_booking_limits(cum_book_lim):
"""Convert cumulative booking limits to incremental booking limits.
If element in `cum_book_lim` is null, set the resulting incremental
booking limit to zero.
"""
incremental_limits = np.zeros(cum_book_lim.shape)
notnull = ~np.isnan(cum_book_lim)
... | 0e781eac097cd0563adffa0e94a4d17c114c6d45 | 74,532 |
from pathlib import Path
def make_unique_filename(name):
""" Creates filename that does not collide with existing files.
May add random stuff between name and extension to make filename unique.
Returns Path object.
May return original name when fails to construct a unique name.
"""
name = Path(name)
parent, st... | 6da56fc220ca7cea6f4dec9ab1c9fb760c174178 | 74,533 |
def query_location_vendor(cid):
"""
Get hardware location and vendor's name by CID
:param cid: string
:return: string, string.
"""
result = query_over_api_hardware(cid)
if result['location']:
info_location = result['location'].get('name', 'NA')
else:
info_location = 'NA... | db0d9f795cfa147d1b511417575eb4651dd5f953 | 74,534 |
import doctest
def load_tests(loader, tests, ignore):
"""Include doctests as unit tests."""
tests.addTests(doctest.DocTestSuite(posh_ohai))
return tests | 432ffab47ba2f71572c83a0c636e0edac0d83c4c | 74,535 |
def columnsBySubmission(submissions, columns):
""" create map submissionName -> set(columnNames)
"""
columnsBySubm = {}
for submission in submissions.keys():
template = submissions[submission]
columnsBySubm[submission] = set(columns[template].keys())
return columnsBySubm | 8364faef492941fb31008e5b31ee570bd2d29a04 | 74,536 |
def van_der_pol_generator(_mu, x_init, _dt=0.01, len_t=100):
"""
:param _mu: float, system parameter
:param x_init: 1 x 2 vector, initial states
:param _dt: time step
:param len_t: time length of simulation
:return: 2 x (len_t+1) numpy array of the trajectory
"""
_t = np.arange(0, len_t... | d8aac35cdbf0312e33bb56803a9e66a33a3b7d13 | 74,537 |
def minimum_bounding_box(geojson):
"""Gets the minimum bounding box for a geojson polygon.
Args:
geojson (dict): A geojson dictionary.
Returns:
tuple: Returns a tuple containing the minimum bounding box in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (3... | 08956c6c78faaa6306667b3c6725554f90f7d0bb | 74,538 |
def useScaleGlyph(unicodeValue, glyphList):
""" Determines whether or not to use scaled glyphs for glyphs in passed glyph_list """
for i in glyphList:
if isinstance(i, tuple):
if i[0] <= unicodeValue <= i[1]:
return True
else:
if unicodeValue == i:
return True
return False | 37fc8ee07ccbf58520b558f0d48ba96f50ce3ae3 | 74,540 |
from typing import List
from typing import Optional
from typing import Dict
def invalidate_batch(
component,
batch_attribute,
invalidations: List[Invalidation],
cache_prefix: Optional[str] = None,
lock_ttl=DEFAULT_LOCK_TTL,
schema_version: Optional[str] = None,
):
"""
Invalidates a set... | 7a9f14153ec0700f141a43bef05921c84b81b210 | 74,541 |
def ddcov(nb, n, Ri, Rj, nv):
""" double-differenced measurement error covariance ---------------------------
*
* nb[n]: # of sat pairs in group
* n: # of groups (2 for each system, phase and code)
* Ri[nv]: variances of first sats in double diff pairs
* Rj[nv]: variances of 2nd sats in double diff pa... | bbad3954976fca51050440d5d2371deb97524422 | 74,542 |
from typing import Dict
import torch
def measure_gradient_norms(model: nn.Module, norm: str = 'l1') -> Dict[str, float]:
"""
Compute the norms of the gradients for each of model's parameters.
:param model: a torch.nn.Module instance
:param norm: how to compute the norm. Available values: 'l1', 'l2', ... | d9541f265f11e02e8cbc0a382178a449911bdcfa | 74,543 |
def redirect_to_root_outcome_group_for_context_courses(request_ctx, course_id, **request_kwargs):
"""
Convenience redirect to find the root outcome group for a particular
context. Will redirect to the appropriate outcome group's URL.
:param request_ctx: The request context
:type request_ctx... | 0570caa24df82cb46b292b8e8961b39355dc1284 | 74,544 |
def stylesheet_link(*urls, **attrs):
"""Return CSS link tags for the specified stylesheet URLs.
``urls`` should be the exact URLs desired. A previous version of this
helper added magic prefixes; this is no longer the case.
"""
if "href" in attrs:
raise TypeError("keyword arg 'href' not all... | f386bba3463235e08c2da7474e9bc89acbf47b1f | 74,545 |
def test_decorator_measureit(fs_one_socket):
"""
Test to measure the energy consumption of a function using the measure decorator
- decorate a function with the measure decorator and use a CSVOutput
- launch the function
- read the produced csv file
Test if:
- the file contains 1 line + ... | c50cc95313c0660b97395ef1ed0045c4ead3e94b | 74,546 |
def len_prefixed_string(length_rw, is_binary=False):
"""Build a ReadWriter for strings prefixed with their length.
.. code-block:: python
len_prefixed_string(number(2)) # == str~2
:param length_rw:
ReadWriter for the length of the string
:param is_binary:
Whether the string i... | 4366aca1115b6f5e1a4ed2862f5b2624f3c49d34 | 74,547 |
import json
def deploy(args, repo):
"""Deploy a pod from a bundle."""
pod_file = args.pod_file
if pod_file.is_dir():
pod_file = pod_file / models.POD_JSON
scripts.ensure_file(pod_file)
bundle_pod = models.Pod(
json.loads(pod_file.read_text()),
pod_file.parent.absolute(),
... | 0c1084dce3b9098832a06637fff7fb5dc2628fd8 | 74,548 |
def get_data_parallel_group():
"""Get the data parallel group the caller rank belongs to."""
assert _DATA_PARALLEL_GROUP is not None, \
'data parallel group is not initialized'
return _DATA_PARALLEL_GROUP | f8d5f5f98922fe90c022f989a26bc915d2d83d0a | 74,549 |
from typing import BinaryIO
from typing import Tuple
def load_mix_audio(fhandle: BinaryIO) -> Tuple[np.ndarray, float]:
"""Load an ikala mix.
Args:
fhandle (str or file-like): File-like object or path to audio file
Returns:
* np.ndarray - audio signal
* float - sample rate
"... | 7e3e48557c81ea8e4d51c5468600dc992e356237 | 74,550 |
def ebalance(sdat: StagyyData) -> Tseries:
"""Compute energy balance.
Compute Nu_t - Nu_b + V*dT/dt as a function of time using an explicit
Euler scheme. This should be zero if energy is conserved.
Args:
sdat: a :class:`~stagpy.stagyydata.StagyyData` instance.
Returns:
energy balan... | b6112e3c1e40412eaa9e370a68b69a44b9be6a5e | 74,551 |
def py_multiplicative_inverse(a, n):
"""Multiplicative inverse of a modulo n (in Python).
Implements extended Euclidean algorithm.
Args:
a: int-like np.ndarray.
n: int.
Returns:
Multiplicative inverse as an int32 np.ndarray with same shape as a.
"""
batched_a = np.asarray... | 87f4e21f9f8b5a9f10dbf4ec80128a37c1fa912c | 74,552 |
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
"""
Make a scatter plot of circles.
Similar to plt.scatter, but the size of circles are in data scale.
Parameters
----------
x, y : scalar or array_like, shape (n, )
Input data
s : scalar or array_like, shape (n, )
... | 6af166be21e45920391d1a8277859f1edd4e6a4f | 74,554 |
from typing import Union
from typing import Tuple
def process__get_username_domain_for_pid(thread_pid: DWORD) -> Union[Tuple[str, str], WindowsErrorMessage]:
"""
:param thread_pid:
:return: the tuple (username, domain) for the user that owns the pid.
"""
OpenProcessToken = windll.advapi32.OpenPro... | 67a7681cf1dfdf56e2aa5d3484fdca3d2de98546 | 74,555 |
import re
def find_ids_range(code):
"""
Parse the given function and return a dictionary mapping "ids" to
"line ranges". Ids are identified by comments with a special syntax::
# "myid" corresponds to the whole line
print 'foo' # ID: myid
"""
result = {}
start_lineno = code.co... | 1df66d5be216bd884cf572da18427e7b77167111 | 74,556 |
def update_Q(env, episode, Q, alpha, gamma):
""" updates the action-value function estimate using the most recent episode """
states, actions, rewards = zip(*episode)
# prepare for discounting
discounts = np.array([gamma**i for i in range(len(rewards)+1)])
for i, state in enumerate(states):
... | d6ca93280af5f97a75e831291c6f068d53e5e8ed | 74,557 |
def actEvap_unsat_SBM(RootingDepth, WTable, UStoreDepth, zi_layer, UStoreLayerThickness, sumLayer, RestPotEvap, maskLayer, ZeroMap, layerIndex, sumActEvapUStore,ust=0):
"""
Actual evaporation function:
- first try to get demand from the saturated zone, using the rootingdepth as a limiting factor
- seco... | 3614cce605cc709675cf03fa40026ce6206023d7 | 74,558 |
def _generate_csr(cn, san):
"""Generates a csr for testing purposes"""
key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, 1024)
req = OpenSSL.crypto.X509Req()
if cn:
req.get_subject().CN = cn
if san:
sn = ([OpenSSL.crypto.X509Extension("subjectAltName", False, ... | d57a2f6def77d7fac42190e900aca7c134cfdbdc | 74,559 |
def process_results(city="Los Angeles", parameter="pm25"):
"""returns [(utc date), (value), (city), (country)]
Pulls data from the openaq api and process the results to return a list
of tuples with the observation utc time, air quality value, the city,
and country that the observation was taken in.
... | c8c0f97a420e595b7cb8cbeddbfeb63c77d41cc4 | 74,560 |
def registerStack(ref, mov, mode="rigid"):
"""
Register stack to a static reference using constrained transformations
@param ref: 2D static reference image
@type ref: numpy.ndarray
@param mov: 3D stack to be mapped onto ref
@type mov: numpy.ndarray
@param mode: contraints of registration pa... | f9bdd29d3542700ff9249fbd62050f58e4175eb5 | 74,561 |
def find_permutation2(W, Wgt):
"""Check if *W* is a permutated version of *Wgt*.
:param W: A matrix containing *H'* dictionay elements.
:type W: ndarray (D x H')
:param Wgt: A matrix containing *H* dictionary elements
:type Wgt: ndarray (D x H)
:rtype: ndarray (dtype=int)
This implem... | 41de8925f2ec25e917694a7797607dc21f243f1c | 74,564 |
import requests
def word_paradigm(word):
""" Find alternative form for a given word form, e.g. word_variant('spiste', 'pres-part') """
r = requests.get("https://api.nb.no/ngram/paradigm", params = {'word': word})
return r.json() | 28304a5e212821a3ebfb35e3c24de49a341b943d | 74,565 |
def slice_forSparse(Matrix, a, b):
"""
Parameters
----------
Matrix : float array
Arbitrary array
a, b : int lists or arrays
list of rows and columns to be selected from `Matrix`
Returns
-------
Matrix : float array
"""
Maa = Matrix[a,:].toarray()
Maa = Maa[:, a]
Mab = Matrix[a,:].toarray()
Mab =... | 3cc9970063c76e6168747a2d0cfa48fde3697a44 | 74,566 |
from typing import Concatenate
def to_multi_gpu(model, n_gpus=2):
"""Given a keras [model], return an equivalent model which parallelizes
the computation over [n_gpus] GPUs.
Each GPU gets a slice of the input batch, applies the model on that slice
and later the outputs of the models are concatenated ... | d545bde68ca117bef77975de81873061c49efdcb | 74,569 |
def get_data(ticker, granularity, target=None):
"""Function that enqueues indicator calculations in celery to be actioned
by a rabbitmq backend."""
_id = None
shift = -1
entry = db_session.query(getTickerTask).filter(
getTickerTask.ticker == ticker, getTickerTask.price == 'M',
getTi... | 4af193dc64995bf98d6be18e1ca97e414c9925d7 | 74,570 |
import traceback
def err_to_scratch_buffer(func):
"""Decorator that will catch any Exception that 'func' throws and displays
it in a new Vim scratch buffer."""
# Gotcha: static function, so now 'self'
@wraps(func)
def wrapper(*args, **kwds):
# noinspection PyBroadException
try:
... | 312de4a72a295a1f8b6c777016d1ab12daecdf6f | 74,571 |
def is_password_valid_with_old_rules(dataset):
""" Validate password according to the old rules """
letter_count = dataset['password'].count(dataset['letter'])
return int(dataset['first']) <= letter_count and letter_count <= int(dataset['last']) | 99a63ece8e3b8520fd71028bd01bb3a1a7e677a7 | 74,572 |
def answer() -> str:
"""
Returns the answer to the problem as a string.
"""
return str(lpoad(
"73167176531330624919225119674426574742355349194934"
"96983520312774506326239578318016984801869478851843"
"85861560789112949495459501737958331952853208805511"
"125406987471585238... | ae535c4e1be396ce41569c3daa781236310a4958 | 74,573 |
import re
def snakecase(string: Text) -> Text:
"""Convert string into snake case.
Join punctuation with underscore
Inspired by: https://github.com/okunishinishi/python-stringcase
License: MIT
:param string: String to convert.
:returns: snake_case_string.
Examples
--------
>>>... | bc9104fdf2dee28547aeb0bcaef32ddddf932414 | 74,576 |
def _f(x, t, s, cls):
"""Return True if x equals t,
or x is an instance of cls and x equals cls(t),
or x.lower().startswith(s)"""
return x == t or \
(isinstance(x, cls) and x == cls(t)) or \
(isinstance(x, str) and x.lower().startswith(s)) | 91d9c518b58528f01034ca67738c220a17f7f40d | 74,577 |
import threading
import functools
def synchronized(wrapped):
"""Simple synchronization decorator.
Decorating a method like so:
.. code-block:: python
@synchronized
def foo(self, *args):
...
ensures that only one thread will execute the foo method at a time.
"""
lock = t... | 85af7bbd8b7d72f13bfaecc5f1df459745358ab5 | 74,578 |
def solve(lists, n):
"""
Get the missing list.
Parameters
----------
lists : list of lists
2*n - 1 lists with integers
n : int
Returns
-------
strictly increasing list of n integers.
"""
numbers = {}
for list_ in lists:
for el in list_:
if el... | 001645ff1a9ae00169ab3565eaed5cb7764f0c7a | 74,579 |
def read_config_file(file_path):
"""
Reads a config data structure (dict for now) from the file path specified
"""
return read_dict_from_file(file_path) | 782bc0a74e11b2e18705ca9ff8513f365a83068c | 74,580 |
def _split_repo_url(url):
"""Split a repository URL into an org / repo combination."""
if "github.com/" in url:
end = url.split("github.com/")[-1]
org, repo = end.split("/")[:2]
else:
logger.warning(f"Currently Thebe repositories must be on GitHub, got {url}")
org = repo = No... | 1080d5357879c4e3d691ea926918ddc20916938c | 74,581 |
from typing import Any
def get_sub_keys(root: Any, reg_path: str) -> list:
"""This function will retrieve a list of sub-keys under the path
of `root` + `reg_path`.
Args:
root(Any): Root registry.
reg_path(str): The relative specific path under the root registry.
Returns:
The ... | a41e267f3d5a0a13c609687d233f03ca27af56b8 | 74,582 |
def counter(countables):
"""
Counter for counting the values inside a particular list or dict.
This is just a scratch/vanilla version of collections.Counter
Args:
countables: List of countables to be counted.
"""
counts = dict()
for k in countables:
if not k in list(counts.keys(... | 42bcf22f000de70e0453f9f9078ea8d7c5f74db2 | 74,585 |
import functools
import time
def timer(func):
"""Print the runtime of the decorated function"""
@functools.wraps(func)
def wrapper_timer(*args, **kwargs):
start_time = time.perf_counter() # 1
value = func(*args, **kwargs)
end_time = time.perf_counter() # 2
run_time = end_time - start_time # 3
... | ab94ce0d8bb18c38302a25b785ce5b890202ed60 | 74,586 |
def leave_group():
""" Leave the group by removing the current user from the group
:param room_id: the room_id of the group
"""
incoming = request.get_json()
Participant.delete_participant_with_user_id_and_room_id(session['user_id'], incoming['room_id'])
return jsonify(results = incoming['room_i... | 3b552c17dda61e653f10fea6031d4b2709a0fc12 | 74,587 |
def query_api(term, location):
"""Queries the API by the input values from the user.
Args:
term (str): The search term to query.
location (str): The location of the business to query.
"""
bearer_token = obtain_bearer_token(API_HOST, TOKEN_PATH)
response = search(bearer_token, term,... | 4f7661e46447947c28ff3012d2b26ef0d20287dc | 74,588 |
def createTiles (n_tiles, n_row, image_path, image_map, map_patch_size, patch_size, density_threshold=200, random_noise=0, prop_patho = 0.7):
"""
Given an image path and a patch_size, return a list of xmin, ymin, xmax, ymax of the images patchs
"""
# Loading image with openslide
slide = openslide... | 99c3504b8381dd5cbc84b78e76fbe59e380e654a | 74,589 |
def drs4_pedestal_exists(run_id: int) -> bool:
"""Return true if drs4 pedestal file was already produced."""
file = get_drs4_pedestal_file(run_id)
return file.exists() | 32dc32db2f86ab121f6084220e2e1779d512aa48 | 74,590 |
def TopOpeBRepTool_TOOL_minDUV(*args):
"""
:param F:
:type F: TopoDS_Face &
:rtype: float
"""
return _TopOpeBRepTool.TopOpeBRepTool_TOOL_minDUV(*args) | 9a87a4cc737e35e3e939c0284a1ad7e4d3bc516b | 74,591 |
def get_alignment_pdb_id(alignment):
"""
Returns a string of the four letter PDB ID found in alignment
:param alignment:
:return: 'pdb id'
"""
pdb_chain_id = alignment.hit_def.encode('ascii').split()[0]
pdb_id = pdb_chain_id.split('_')[0].lower()
return pdb_id | 35a6abcd18e411328e5b7fb8c5a4f1dba8fe2391 | 74,592 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.