content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def start_nodenetrunner(nodenet_uid):
"""Starts a thread that regularly advances the given nodenet by one step."""
nodenets[nodenet_uid].is_active = True
if runner['runner'].paused:
runner['runner'].resume()
return True | 7511f217beb64936d403a5f5472036206f446c90 | 16,280 |
def transform_coordinates_3d(coordinates, RT):
"""
Input:
coordinates: [3, N]
RT: [4, 4]
Return
new_coordinates: [3, N]
"""
if coordinates.shape[0] != 3 and coordinates.shape[1]==3:
coordinates = coordinates.transpose()
coordinates = np.vstack([coordinates, np.on... | 8a31f97bddd1c84a21d4b396e877c2b327e6890b | 16,281 |
def _get_misclass_auroc(preds, targets, criterion, topk=1, expected_data_uncertainty_array=None):
"""
Get AUROC for Misclassification detection
:param preds: Prediction probabilities as numpy array
:param targets: Targets as numpy array
:param criterion: Criterion to use for scoring on misclassifica... | 282ef66926092e99a62003152daccf733913b6c2 | 16,282 |
from typing import Iterable
from typing import List
def flatten(l: Iterable) -> List:
"""Return a list of all non-list items in l
:param l: list to be flattened
:return:
"""
rval = []
for e in l:
if not isinstance(e, str) and isinstance(e, Iterable):
if len(list(e)):
... | 2d2202c21e6da7064491d55d5519c259d10f42c0 | 16,283 |
def create_note(dataset_id, fhir_store_id, note_id): # noqa: E501
"""Create a note
Create a note # noqa: E501
:param dataset_id: The ID of the dataset
:type dataset_id: str
:param fhir_store_id: The ID of the FHIR store
:type fhir_store_id: str
:param note_id: The ID of the note that is b... | 396f81b4a6035a9f295faebdd1aa313131d0da2b | 16,284 |
def load_credential_from_args(args):
"""load credential from command
Args:
args(str): str join `,`
Returns:
list of credential content
"""
if ',' not in args:
raise
file_path_list = args.split(',')
if len(file_path_list) != 2:
raise
if not file_path_list... | 4f2e0b1e57ee3baaeb1bab3dc0e7e3874aaeec7c | 16,285 |
def encode(string: str, key: str) -> str:
"""
Encode string using the Caesar cipher with the given key
:param string: string to be encoded
:param key: letter to be used as given shift
:return: encoded string
:raises: ValueError if key len is invalid
"""
if len(key) > 1:
raise Val... | ddba41c5efc01df06290cd6496ef8eb54dbb28be | 16,286 |
def compile_binary(binary, compiler, override_operator=None, **kw):
"""
If there are more than 10 elements in the `IN` set, inline them to avoid hitting the limit of \
the number of query arguments in Postgres (1<<15).
""" # noqa: D200
operator = override_operator or binary.operator
if operato... | 1798ded35c12d6a3bf2e5edc34dcf11ff70ce697 | 16,287 |
from typing import Callable
from typing import Iterable
from typing import Iterator
import itertools
def flat_map(
fn: Callable[[_T], Iterable[_S]], collection: Iterable[_T]
) -> Iterator[_S]:
"""Map a function over a collection and flatten the result by one-level"""
return itertools.chain.from_iterable(m... | a1a09611f920078cb25a23279004acd00ac23142 | 16,288 |
def create_vector_clock(node_id, timeout):
"""This method builds the initial vector clock for a new key.
Parameters
----------
node_id : int
the id of one node in the cluster
timeout : int
the expire timeout of the key
Returns
-------
dict
the vector clock as di... | ed6df0e7e493d448f52e5fe47b55df8a1de94543 | 16,289 |
def ParseStateFoldersFromFiles(state_files):
"""Returns list of StateFolder objects parsed from state_files.
Args:
state_files: list of absolute paths to state files.
"""
def CreateStateFolder(folderpath, parent_namespace):
del parent_namespace # Unused by StateFolder.
return state_lib.StateFolde... | c70421da1f193ca2dc86f12e7cffd84a1011af22 | 16,290 |
def spectral_norm(inputs, epsilon=1e-12, singular_value="left"):
"""Performs Spectral Normalization on a weight tensor.
Details of why this is helpful for GAN's can be found in "Spectral
Normalization for Generative Adversarial Networks", Miyato T. et al., 2018.
[https://arxiv.org/abs/1802.05957].
Args:
... | eb6961e984fbb8eb5c3d807faa7fa6d016c011b5 | 16,291 |
def rs_for_staff(user_id):
"""Returns simple JSON for research studies in staff user's domain
---
tags:
- User
- ResearchStudy
operationId: research_studies_for_staff
parameters:
- name: user_id
in: path
description: TrueNTH user ID, typically subject or staff
... | 9d36a02cc4909e336730fb27b3bcfe284bcd5d82 | 16,292 |
import re
import click
def validate_memory(_ctx, _param, value):
"""Validate memory string."""
if value is None:
return None
if not re.search(r'\d+[KkMmGg]$', value):
raise click.BadParameter('Memory format: nnn[K|M|G].')
return value | c050863a974c08ccc18fdaa2f03388c8f6674835 | 16,294 |
def BlockAvg3D( data , blocksize , mask ):
"""
3-D version of block averaging. Mainly applicable to making superpixel averages of datfile traces.
Not sure non-averaging calcs makes sense?
mask is a currently built for a 2d boolean array of same size as (data[0], data[1]) where pixels to be averaged a... | 4c0c9cb60c80f47289e7bff3e50ae3e39dd31c63 | 16,295 |
def build(buildconfig: BuildConfig, merge_train_and_test_data: bool = False):
"""Build regressor or classifier model and return it."""
estimator = buildconfig.algorithm.estimator()
if merge_train_and_test_data:
train_smiles, train_y = buildconfig.data.get_merged_sets()
else:
train_smile... | 9a98f15ae9b966e42cda848169b38a651e727205 | 16,296 |
def stellar_radius(M, logg):
"""Calculate stellar radius given mass and logg"""
if not isinstance(M, (int, float)):
raise TypeError('Mass must be int or float. {} type given'.format(type(M)))
if not isinstance(logg, (int, float)):
raise TypeError('logg must be int or float. {} type given'.fo... | 2afbd991c7461d7861370f18d90df840569da857 | 16,298 |
def set_plus_row(sets, row):
"""Update each set in list with values in row."""
for i in range(len(sets)):
sets[i].add(row[i])
return sets | 87f448dc3199c8d3137d5811dd184b3d2bd7cbe3 | 16,299 |
from typing import List
from typing import Union
def bytes_to_string(
bytes_to_convert: List[int], strip_null: bool = False
) -> Union[str, None]:
"""
Litteral bytes to string
:param bytes_to_convert: list of bytes in integer format
:return: resulting string
"""
try:
value = "".joi... | a04dee89fb8aed33b6069a7ff0ca8c497d0a6062 | 16,300 |
def interpolate(t,y,num_obs=50):
"""
Interpolates each trajectory such that observation times coincide for each one.
Note: initially cubic interpolation gave great power, but this happens as an artifact of the interpolation,
as both trajectories have the same number of observations. Type I error wa... | 2418aaf207b214069f45571a21a2b97ecd25f244 | 16,301 |
import re
def locktime_from_duration(duration):
"""
Parses a duration string and return a locktime timestamp
@param duration: A string represent a duration if the format of XXhXXmXXs and return a timestamp
@returns: number of seconds represented by the duration string
"""
if not duration:
... | c65339ee00e750e4425a68215b0600c71136ee68 | 16,302 |
def black_payers_swaption_value_fhess_by_strike(
init_swap_rate,
option_strike,
swap_annuity,
option_maturity,
vol):
"""black_payers_swaption_value_fhess_by_strike
Second derivative of value of payer's swaption with respect to strike
under black model.
See :py:fun... | 0645992c65e9e13ee44ad3debfe30fb0b05bfae7 | 16,303 |
def get_resource(cls):
""" gets the resource of a timon class if existing """
if not cls.resources:
return None
resources = cls.resources
assert len(resources) == 1
return TiMonResource.get(resources[0]) | 370f0af23fcfe0bf5da3b39012a5e1e9c29b6f0e | 16,304 |
def _log(x):
"""_log
to prevent np.log_log(0), caluculate np.log(x + EPS)
Args:
x (array)
Returns:
array: same shape as x, log equals np.log(x + EPS)
"""
if np.any(x < 0):
print("log < 0")
exit()
return np.log(x + EPS) | e7e7b963cf3cec02ace34256ccdf954a2d61dd4a | 16,305 |
import math
def gauss_distribution(x, mu, sigma):
"""
Calculate value of gauss (normal) distribution
Parameters
----------
x : float
Input argument
mu :
Mean of distribution
sigma :
Standard deviation
Returns
-------
float
Probability, values f... | 05cf2c14b337b45a81ddbe7655b4d7cf21e352cd | 16,306 |
def extend_vocab_OOV(source_words, word2id, vocab_size, max_unk_words):
"""
Map source words to their ids, including OOV words. Also return a list of OOVs in the article.
WARNING: if the number of oovs in the source text is more than max_unk_words, ignore and replace them as <unk>
Args:
source_w... | 2d1b92d9d6b9b3885a7dda6c8d72d80d3b8ecad0 | 16,307 |
def isint(s):
"""**Returns**: True if s is the string representation of an integer
:param s: the candidate string to test
**Precondition**: s is a string
"""
try:
x = int(s)
return True
except:
return False | b15598aee937bcce851ee6c39aa2ba96a84a5dd5 | 16,308 |
def create_app(config_name):
"""function creating the flask app"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(config[config_name])
app.config.from_pyfile('config.py')
app.register_blueprint(v2)
app.register_error_handler(404, not_found)
app.register_error_han... | 7e49a1ee9bae07a7628842855c3524794efaa9c5 | 16,309 |
def build_attention_network(features2d,
attention_groups,
attention_layers_per_group,
is_training):
"""Builds attention network.
Args:
features2d: A Tensor of type float32. A 4-D float tensor of shape
[batch_size, height,... | c665994b88027c24ed86e01514fa3fc176a3258a | 16,310 |
def get_catalog_config(catalog):
"""
get the config dict of *catalog*
"""
return resolve_config_alias(available_catalogs[catalog]) | 4d36bc8be8ca2992424f0b97f28d3ac8d852c027 | 16,311 |
def manhatten(type_profile, song_profile):
"""
Calculate the Manhatten distance between the profile of specific
output_colums value (e.g. specific composer) and the profile of a
song
"""
# Sort profiles by frequency
type_profile = type_profile.most_common()
song_profile = song_profile.mo... | 4703585f9f60551bf2a5e2762612d45efb47a453 | 16,312 |
def raven(request):
"""lets you know whether raven is being used"""
return {
'RAVEN': RAVEN
} | 3e047db45a597cf808e5227b358a9833fc0a4fc3 | 16,313 |
from typing import Union
def _non_max_suppress_mask(
bbox: np.array,
scores: np.array,
classes: np.array,
masks: Union[np.array, None],
filter_class: int,
iou: float = 0.8,
confidence: float = 0.001,
) -> tuple:
"""Perform non max suppression on the detection output if it is mask.
... | 742261f1854f2ad6d01046926c6017b72a1917a4 | 16,314 |
def _mark_untranslated_strings(translation_dict):
"""Marks all untranslated keys as untranslated by surrounding them with
lte and gte symbols.
This function modifies the translation dictionary passed into it in-place
and then returns it.
"""
# This was a requirement when burton was written, but... | d15ac2d0fe8d50d5357bcc1e54b9666f7076aefd | 16,316 |
import warnings
import codecs
def build(app, path):
"""
Build and return documents without known warnings
:param app:
:param path:
:return:
"""
with warnings.catch_warnings():
# Ignore warnings emitted by docutils internals.
warnings.filterwarnings(
"ignore",
... | 09049aad0d46d07144c3d564deb0e5aaf1b828ca | 16,317 |
def SMWatConstrained(CSM, ci, cj, matchFunction, hvPenalty = -0.3, backtrace = False):
"""
Implicit Smith Waterman alignment on a binary cross-similarity matrix
with constraints
:param CSM: A binary N x M cross-similarity matrix
:param ci: The index along the first sequence that must be matched to c... | a66f17bb40e201a6758c1add4a1590672724dc3e | 16,319 |
def check_images(
coords,
species,
lattice,
PBC=[1, 1, 1],
tm=Tol_matrix(prototype="atomic"),
tol=None,
d_factor=1.0,
):
"""
Given a set of (unfiltered) frac coordinates, checks if the periodic images are too close.
Args:
coords: a list of fractional coordinates
... | 20f3ada0aa391d989b638a835581226bd79439f7 | 16,320 |
def get_hamming_distances(genomes):
"""Calculate pairwise Hamming distances between the given list of genomes
and return the nonredundant array of values for use with scipy's squareform function.
Bases other than standard nucleotides (A, T, C, G) are ignored.
Parameters
----------
genomes : list... | dad2e9583bd7fcbbbb87dd93d180e4de39ea3083 | 16,321 |
from typing import Dict
def serialize(name: str, engine: str) -> Dict:
"""Get dictionary serialization for a dataset locator.
Parameters
----------
name: string
Unique dataset name.
engine: string
Unique identifier of the database engine (API).
Returns
-------
dict
... | 9ab11318050caf3feb4664310e491ed48e7e5357 | 16,322 |
import torch
def repackage_hidden(h):
"""
Wraps hidden states in new Variables, to detach them from their history.
"""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(v.detach() for v in h) | 0ab8cffeaafaf6f39e2938ce2005dbca1d3d7496 | 16,323 |
def support_acctgroup_acctproject(version):
"""
Whether this Lustre version supports acctgroup and acctproject
"""
if version.lv_name == "es2":
return False
return True | 858ec772a90e66431731ffcdd145fa7e56daad02 | 16,325 |
def decodeInventoryEntry_level1(document):
"""
Decodes a basic entry such as: '6 lobster cake' or '6' cakes
@param document : NLP Doc object
:return: Status if decoded correctly (true, false), and Inventory object
"""
count = Inventory(str(document))
for token in document:
if token.p... | a283f3630a18cdbb0cc22664e583f00866ff759b | 16,326 |
from typing import Collection
def from_ir_objs(ir_objs: Collection[IrCell]) -> AnnData:
"""\
Convert a collection of :class:`IrCell` objects to an :class:`~anndata.AnnData`.
This is useful for converting arbitrary data formats into
the scirpy :ref:`data-structure`.
{doc_working_model}
Param... | 55e95b2673d6aec02ae5aa7fb5cec014db17cdc7 | 16,328 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/start<br/>"
f"/api/v1.0/start/end"
) | bac64c3b2d2e5d883f627dada658cdd9359b61b0 | 16,330 |
from typing import List
def get_cases_from_input_df(input_df: pd.DataFrame) -> List[Case]:
"""
Get the case attributes
:return:
"""
cases: List[Case] = []
for index, row in input_df.iterrows():
# Create a case object from the row values in the input df
cases.append(Case.from_... | 34b820880691456fde3ab260be02646590aeafd7 | 16,331 |
from typing import AnyStr
import unicodedata
def normalize_nfc(txt: AnyStr) -> bytes:
"""
Normalize message to NFC and return bytes suitable for protobuf.
This seems to be bitcoin-qt standard of doing things.
"""
str_txt = txt.decode() if isinstance(txt, bytes) else txt
return unicodedata.norm... | 12b6e037225878e0bbca1d52d9f58d57abb35746 | 16,333 |
from typing import Callable
from typing import Any
import threading
import functools
def synchronized(wrapped: Callable[..., Any]) -> Any:
"""The missing @synchronized decorator
https://git.io/vydTA"""
_lock = threading.RLock()
@functools.wraps(wrapped)
def _wrapper(*args, **kwargs):
wit... | 39da1efeb93c8dbdba570763d2e66dc8d9d84fc5 | 16,334 |
def corrgroups60__decision_tree():
""" Decision Tree
"""
return sklearn.tree.DecisionTreeRegressor(random_state=0) | fb2405c54208705a105b225e1dd269d45892b7be | 16,335 |
def auth_required(*auth_methods):
"""
Decorator that protects enpoints through multiple mechanisms
Example::
@app.route('/dashboard')
@auth_required('token', 'session')
def dashboard():
return 'Dashboard'
:param auth_methods: Specified mechanisms.
"""
login_... | c6613e594abbb979352fe3ec96018fe52109bab0 | 16,336 |
def _get_default_data_dir_name():
"""
Gets default data directory
"""
return _get_path(DATA_DIR) | b4207e108a9f08a72b47c44ab43b3971e67e8165 | 16,337 |
def point_inside_triangle(p, t, tol=None):
"""
Test to see if a point is inside a triangle. The point is first
projected to the plane of the triangle for this test.
:param ndarray p: Point inside triangle.
:param ndarray t: Triangle vertices.
:param float tol: Tolerance for barycentric coordina... | a7a4dd52dfa65fdd9e3cb3ac151c7895acb3abb8 | 16,338 |
from datetime import datetime
def merge_dfs(x, y):
"""Merge the two dataframes and download a CSV."""
df = pd.merge(x, y, on='Collection_Number', how='outer')
indexed_df = df.set_index(['Collection_Number'])
indexed_df['Access_Notes_Regarding_Storage_Locations'].fillna('No note', inplace=True)
tod... | 9856d4394ca628fd7eb0f58e6cc805494410c51e | 16,339 |
def consumer(func):
"""A decorator function that takes care of starting a coroutine automatically on call.
See http://www.dabeaz.com/generators/ for more details.
"""
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start | e834a081c1f43545684bb4102a92b186c8825f30 | 16,340 |
def convert_openfermion_op(openfermion_op, n_qubits=None):
"""convert_openfermion_op
Args:
openfermion_op (:class:`openfermion.ops.QubitOperator`)
n_qubit (:class:`int`):
if None (default), it automatically calculates the number of qubits required to represent the given operator
... | 416eccc82fbd7dbdcf61ba62f5176ca3e12a01db | 16,341 |
def recommend(uid, data, model, top_n = 100):
"""
Returns the mean and covariance matrix of the demeaned dataset X (e.g. for PCA)
Parameters
----------
uid : int
user id
data : surprise object with data
The entire system, ratings of users (Constructed with reader from surpri... | b156826359e3310c8872a07428d0073795ef071b | 16,345 |
def cluster_info(arr):
""" number of clusters (nonzero fields separated by 0s) in array
and size of cluster
"""
data = []
k2coord = []
coord2k = np.empty_like(arr).astype(np.int64)
k = -1
new_cluster = True
for i in range(0,len(arr)):
if arr[i] == 0:
new_clu... | 23a3d58b13ba4af4977cd25a1dc45d116fd812b5 | 16,347 |
def set_or_none(list_l):
"""Function to avoid list->set transformation to return set={None}."""
if list_l == [None]:
res = None
else:
res = set(list_l)
return res | ee5fb4539e63afc7fd8013610229d9ab784b88c5 | 16,348 |
import re
def case_mismatch(vm_type, param):
"""Return True if vm_type matches a portion of param in a case
insensitive search, but does not equal that portion;
return False otherwise.
The "portions" of param are delimited by "_".
"""
re_portion = re.compile(
"(^(%(x)s)_)|(_(%(x)s)_)|(... | e7fb565ac6e10fd15dd62a64fbf7f14a8bcfde6b | 16,349 |
def _async_os(cls):
""" Aliases for aiofiles.os"""
return aiofiles.os | ad37b21f22ed5203451ac8eb4b7a53f4572fec73 | 16,350 |
import torch
def corruption_function(x: torch.Tensor):
""" Applies the Gsaussian blur to x """
return torchdrift.data.functional.gaussian_blur(x, severity=5) | 54b98c6bddb187689c0e70fc2dbf0f3c56e25ad1 | 16,351 |
def filter_by_filename(conn, im_ids, imported_filename):
"""Filter list of image ids by originalFile name
Sometimes we know the filename of an image that has been imported into
OMERO but not necessarily the image ID. This is frequently the case when
we want to annotate a recently imported image. This f... | bf9625c06929a80f21a4683b1da687535f296e59 | 16,352 |
def get_count():
"""
:return: 计数的值
"""
counter = Counters.query.filter(Counters.id == 1).first()
return make_succ_response(0) if counter is None else make_succ_response(counter.count) | be0ab2773e661b8e5e34f685b59f16cfdee6b26d | 16,353 |
import math
def perm(x, y=None):
"""Return the number of ways to choose k items from n items without repetition and with order."""
if not isinstance(x, int) or (not isinstance(y, int) and y is not None):
raise ValueError(f"Expected integers. Received [{type(x)}] {x} and [{type(y)}] {y}")
return ma... | c9ad65c6ce3cc3e5ba488c5f2ddd1aabbdc7da6a | 16,354 |
from typing import Union
def ui(candles: np.ndarray, period: int = 14, scalar: float = 100, source_type: str = "close", sequential: bool = False) -> Union[float, np.ndarray]:
"""
Ulcer Index (UI)
:param candles: np.ndarray
:param period: int - default: 14
:param scalar: float - default: 100
... | 1f99a6ee849094f3a695812e37035a13f36e8c49 | 16,357 |
def _padwithzeros(vector, pad_width, iaxis, kwargs):
"""Pad with zeros"""
vector[: pad_width[0]] = 0
vector[-pad_width[1] :] = 0
return vector | 1a3a9fc4fd3b0fc17a905fa9ecd283d60310655d | 16,358 |
def fill_from_sparse_coo(t,elems):
"""
:param elems: non-zero elements defined in COO format (tuple(indices),value)
:type elems: list[tuple(tuple(int),value)]
"""
for e in elems:
t[e[0]]=e[1]
return t | 73c6892464d7d7cf34f40fe1dde9973950cdef79 | 16,359 |
def download_responses(survey_id):
"""Download survey responses."""
if request.method == 'GET':
csv = survey_service.download_responses(survey_id)
return Response(
csv,
mimetype='text/csv',
headers={'Content-disposition': 'attachment; filename=surveydata.csv'}) | 8513caf582b87bf0cd5db80622c530d1ec1c3ef2 | 16,360 |
from collections import deque
from typing import Iterable
from typing import Deque
def array_shift(data: Iterable, shift: int) -> Deque:
"""
left(-) or right(+) shift of array
>>> arr = range(10)
>>> array_shift(arr, -3)
deque([3, 4, 5, 6, 7, 8, 9, 0, 1, 2])
>>> array_shift(arr, 3)
deque(... | c14e115808592808bc9b0cf20fa8bc3d5ece7768 | 16,361 |
def convert_to_timetable(trains):
"""
列車データを時刻表データに変換する関数
Args:
trains (list of list of `Section`): 列車データ
Returns:
timetable (list): 時刻表データ
timetable[from_station][to_station][dep_time] = (from_time, to_time)
-> 現在時刻が dep_time の時に from_station から to_station まで直近... | 042238b090af1b4b4e4a8cf469f9bbcd49edc9af | 16,362 |
import math
def parents(level, idx):
"""
Return all the (grand-)parents of the Healpix pixel idx at level (in nested format)
:param level: Resolution level
:param idx: Pixel index
:return: All the parents of the pixel
"""
assert idx < 12 * 2 ** (2 * level)
plpairs = []
for ind in ... | 355c3acffa07065de10049059ef064abefdd7ca0 | 16,363 |
def precise_inst_ht(vert_list, spacing, offset):
"""
Uses a set of Vertical Angle Observations taken to a
levelling staff at regular intervals to determine the
height of the instrument above a reference mark
:param vert_list: List of Vertical (Zenith) Angle Observations (minimum of 3) in Decimal Deg... | d88cf0dc289f2ef96d4b60dabf17c6e4bd04e549 | 16,364 |
def _parse_transform_set(transform_dict, imputer_string, n_images=None):
"""Parse a dictionary read from yaml into a TransformSet object
Parameters
----------
transform_dict : dictionary
The dictionary as read from the yaml config file containing config
key-value pairs
imputer_strin... | 47e3bf72c9e70bff22bebee7e73a14c349761116 | 16,365 |
import json
import random
def initialize_train_test_dataset(dataset):
""" Create train and test dataset by random sampling.
pct: percentage of training
"""
pct = 0.80
if dataset in ['reddit', 'gab']:
dataset_fname = './data/A-Benchmark-Dataset-for-Learning-to-Intervene-in-Online-Hate-S... | bac5876be313a85213badcce667af550e8f3f65a | 16,366 |
def load_raw_data_xlsx(files):
"""
Load data from an xlsx file
After loading, the date column in the raw data is converted to a UTC datetime
Parameters
----------
files : list
A list of files to read. See the Notes section for more information
Returns
-------
list
... | a2aebdb4d972ef7f46970b3e8fc14ef40ae42bb8 | 16,367 |
def filter_production_hosts(nr):
"""
Filter the hosts inventory, which match the production
attribute.
:param nr: An initialised Nornir inventory, used for processing.
:return target_hosts: The targeted nornir hosts after being
processed through nornir filtering.
"""
# Execute filter ba... | 006524e7b014d3f908955fb81d9f928ac7df25d8 | 16,368 |
import random
def get_lightmap(map_name="random"):
"""
Fetches the right lightmap given command line argument.
"""
assert map_name in ["default", "random"] + list(CONSTANTS.ALL_LIGHTMAPS.keys()), f"Unknown lightmap {map_name}..."
if map_name == "random":
map_name = random.choice(list(CONS... | 04ea7e901bbde8ba900469d8ed87b1b3c158809a | 16,369 |
def kill_instance(cook_url, instance, assert_response=True, expected_status_code=204):
"""Kill an instance"""
params = {'instance': [instance]}
response = session.delete(f'{cook_url}/rawscheduler', params=params)
if assert_response:
assert expected_status_code == response.status_code, response.t... | 3daa954579b15deedc5a66e77a2178a5682bd1a3 | 16,370 |
def _get_n_batch_from_dataloader(dataloader: DataLoader) -> int:
"""Get a batch number in dataloader.
Args:
dataloader: torch dataloader
Returns:
A batch number in dataloader
"""
n_data = _get_n_data_from_dataloader(dataloader)
n_batch = dataloader.batch_size if dataloader.batc... | 182e5566c6b9c83d3dabc3c99f32aedf1e3c21e7 | 16,371 |
def get_hidden() -> list:
"""
Returns places that should NOT be shown in the addressbook
"""
return __hidden_places__ | 8d201c25dd3272b2a3b2292ef3d8fa5293a97967 | 16,372 |
def wait_for_unit_state(reactor, docker_client, unit_name,
expected_activation_states):
"""
Wait until a unit is in the requested state.
:param IReactorTime reactor: The reactor implementation to use to delay.
:param docker_client: A ``DockerClient`` instance.
:param unicode... | 73278f8762a9b0c5d78ea4d5e098bb7a41b97072 | 16,373 |
def get_list_primitives():
"""Get list of primitive words."""
return g_primitives | 2429b646fbe2fbcc344e08ddffb64ccf2a2d853d | 16,374 |
def make_graph(edge_list, threshold=0.0, max_connections=10):
"""Return 2 way graph from edge_list based on threshold"""
graph = defaultdict(list)
edge_list.sort(reverse=True, key=lambda x: x[1])
for nodes, weight in edge_list:
a, b = nodes
if weight > threshold:
if len(graph... | c9414a0b8df8b9de46ad444b376c5316f1960cd0 | 16,375 |
def ping(request):
"""Ping view."""
checked = {}
for service in services_to_check:
checked[service.name] = service().check()
if all(item[0] for item in checked.values()):
return HttpResponse(
PINGDOM_TEMPLATE.format(status='OK'),
content_type='text/xml',
... | 09b3bd76c59e4d69678a6ce9c3018f638248ff88 | 16,376 |
import numbers
def _num_samples(x):
"""Return number of samples in array-like x."""
message = 'Expected sequence or array-like, got %s' % type(x)
if hasattr(x, 'fit') and callable(x.fit):
# Don't get num_samples from an ensembles length!
raise TypeError(message)
if not hasattr(x, '__l... | 18133457621ec7c79add6d0ff9ab8b1b0c17d524 | 16,377 |
def inf_compress_idb(*args):
"""
inf_compress_idb() -> bool
"""
return _ida_ida.inf_compress_idb(*args) | fd4ef3c50b9fef7213d9f37a0326f5e9f06b9822 | 16,378 |
def tokens_history(corpus_id):
""" History of changes in the corpus
:param corpus_id: ID of the corpus
"""
corpus = Corpus.query.get_or_404(corpus_id)
tokens = corpus.get_history(page=int_or(request.args.get("page"), 1), limit=int_or(request.args.get("limit"), 20))
return render_template_with_n... | d87e4486cb2141b3c59e86a3483f4c445476ca20 | 16,379 |
def Hidden(request):
"""
Hidden Field with a visible friend..
"""
schema = schemaish.Structure()
schema.add('Visible', schemaish.String())
schema.add('Hidden', schemaish.String())
form = formish.Form(schema, 'form')
form['Hidden'].widget = formish.Hidden()
return form | 3f5d96339c39c7cf186d4d45d837b0e95402d328 | 16,381 |
def train_and_eval(trial: optuna.Trial, study_dir: str, seed: int):
"""
Objective function for the Optuna `Study` to maximize.
.. note::
Optuna expects only the `trial` argument, thus we use `functools.partial` to sneak in custom arguments.
:param trial: Optuna Trial object for hyper-parameter... | 07e1cff3ab9954172ce4c09f673881109df6f08c | 16,382 |
def random_active_qubits(nqubits, nmin=None, nactive=None):
"""Generates random list of target and control qubits."""
all_qubits = np.arange(nqubits)
np.random.shuffle(all_qubits)
if nactive is None:
nactive = np.random.randint(nmin + 1, nqubits)
return list(all_qubits[:nactive]) | c9bab4d02a0afc569907c6ec838d0020878a345a | 16,383 |
import re
import requests
import random
import hashlib
from bs4 import BeautifulSoup
def main(host: str, username: str, password: str):
"""メイン.
Args:
host: ホスト名又はIPアドレス
username: ユーザ名
password: パスワード
"""
url: str = f"http://{host}/"
rlogintoken: re.Pattern = re.compile(r"c... | 36efbd8dc18b891934f690091ef8709e0eddb3ce | 16,384 |
from typing import List
import requests
def create_label(project_id: int, label_name: str, templates: list, session=konfuzio_session()) -> List[dict]:
"""
Create a Label and associate it with templates.
If no templates are specified, the label is associated with the first default template of the project.... | 4dda5f7ac6473be76212c03deb6beb7980b44105 | 16,385 |
def home():
""" Home page """
return render_template("index.html") | 0ac607593cc98871d97c111fc2ca89aa980af83f | 16,386 |
def get_from_parameterdata_or_dict(params,key,**kwargs):
"""
Get the value corresponding to a key from an object that can be either
a ParameterData or a dictionary.
:param params: a dict or a ParameterData object
:param key: a key
:param default: a default value. If not present, and if key is no... | 864936e9b43c18e4a8dfd7d88c1cedda28fdb23d | 16,388 |
import torch
def test_input_type(temp_files, fsdp_config, input_cls):
"""Test FSDP with input being a list or a dict, only single GPU."""
if torch_version() < (1, 7, 0):
# This test runs multiple test cases in a single process. On 1.6.0 it
# throw an error like this:
# RuntimeErro... | 6bf7d03f51088518e85d3e6ea8f59bcc86e4a0b4 | 16,389 |
def get_heroesplayed_players(matchs_data, team_longname):
"""Returns a dict linking each player to
- the heroes he/she played
- if it was a win (1) or a loss (0)
"""
picks = get_picks(matchs_data, team_longname)
players = get_players(picks)
results = get_results(matchs_data, team_longname)
... | 53dc68642a4cca7b80ede7b2d54098eb9274b1af | 16,390 |
def autofmt(filename, validfmts, defaultfmt=None):
"""Infer the format of a file from its filename. As a convention all the
format to be forced with prefix followed by a colon (e.g. "fmt:filename").
`validfmts` is a list of acceptable file formats
`defaultfmt` is the format to use if the extension is ... | 3e39325f43f8b4a87074a38f7d576d17669151fb | 16,391 |
def get_or_add_dukaan():
""" Add a new business """
if request.method == "POST":
payload = request.json
# payload = change_case(payload, "lower")
business = db.dukaans.find_one({"name": payload["name"]})
if business is not None:
return (
jsonify(
... | e522ac8394b7b70949e2854e10251f3bc51279ae | 16,392 |
def nearest(a, num):
"""
Finds the array's nearest value to a given num.
Args:
a (ndarray): An array.
num (float): The value to find the nearest to.
Returns:
float. The normalized array.
"""
a = np.array(a, dtype=float)
return a.flat[np.abs(a - num).argmin()] | cadbad68add910ced502a6802592d1c043f1c914 | 16,393 |
def hex_string(data):
"""Return a hex dump of a string as a string.
The output produced is in the standard 16 characters per line hex +
ascii format:
00000000: 40 00 00 00 00 00 00 00 40 00 00 00 01 00 04 80 @....... @.......
00000010: 01 01 00 00 00 00 00 01 00 00 00 00 ........ .... | 7f827b4f8049b43e86d35bd972f5b6aaa2190869 | 16,394 |
def extract_ego_time_point(history: SimulationHistory) -> npt.NDArray[int]:
"""
Extract time point in simulation history.
:param history: Simulation history.
:return An array of time in micro seconds.
"""
time_point = np.array(
[sample.ego_state.time_point.time_us for sample in history.... | 4860b2c7032ea232ace2680c704e4a59051b6c5c | 16,396 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.