content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from salt.cloud.exceptions import SaltCloudException
def avail_images(call=None):
"""
REturns available upcloud templates
"""
if call == 'action':
raise SaltCloudException(
'The avail_locations function must be called with -f or --function.'
)
manager = _get_manager()... | 8adf233a1c1bfeef23b94689c0ccb4230fc2b5b5 | 27,200 |
def batch_dataset(x, batch_size):
"""
partitions dataset x into args.batch_size batches
TODO: ensure that x.shape[0] is divisible by batch_size so no leftovers
"""
size_modulo = len(x) % batch_size # hack to ensure data is batches successfully
if size_modulo != 0:
x = x[:-size_modulo]
partitioned = np.split(x... | ed2ce6edeafd1213b1465b0d3c1438809b259483 | 27,201 |
import requests
def _verify_email_upload(transfer_id: str, session: requests.Session) -> str:
"""Given a transfer_id, read the code from standard input.
Return the parsed JSON response.
"""
code = input('Code:')
j = {
"code": code,
"expire_in": WETRANSFER_EXPIRE_IN,
}
r ... | d46610f4dc7582df68fc82654de167a43729d8af | 27,202 |
from .error import RunFailed, DownloadFailed, Terminated, error_json
from .task import run_local_task
from .. import parse_document, values_from_json, values_to_json, Walker
import logging
import os
import traceback
def run(cfg: config.Loader, logger: logging.Logger, uri: str, **kwargs) -> str:
"""
Download t... | 5d5ac767f8076aef453e4ef52512ddbf63396d90 | 27,203 |
def envelope_generic(pshape, *args, **kwargs):
"""
Envelope for a given pulse shape at a given time or times.
Parameters
----------
pshape : str or function object
Pulse shape type or user-provided function.
Allowed string values are 'square', 'gauss', 'cos',
'flattop_gauss'... | 6e6d007a6602c90c1d39b4749442b910d90f9cf1 | 27,204 |
def sdb_longitude(longitude):
"""Return an 8 character, zero padded string version of the
longitude parameter.
**Arguments:**
* *longitude* -- Longitude.
"""
adjusted = (180 + float(longitude)) * 100000
return str(int(adjusted)).zfill(8) | b7b82819952d30ea58dc9dc08e0c4ab63d92743e | 27,205 |
import os
def run_qemu(kernel, machine='lm3s811evb', dump_file=None, dump_range=None):
""" Runs qemu on a given kernel file """
if not has_qemu():
return ''
# Check bin file exists:
assert os.path.isfile(kernel)
logger.debug('Running qemu with machine=%s and image %s', machine, kernel)
... | c22d22caaa6c077bbcc1bbc0cd25a886828ad8c5 | 27,206 |
def is_allowed_location(location, allowed_location):
""""
Returns true if the location is allowed_location
Args:
location: location id
allowed_location: allowed_location
Returns:
is_allowed(bool): Is location allowed.
"""
if allowed_location == 1:
return True
... | e16b8bb15827b34c65b3ee6aa36f710ad2aaeea5 | 27,207 |
def gsl_isinf(*args, **kwargs):
"""gsl_isinf(double x) -> int"""
return _gslwrap.gsl_isinf(*args, **kwargs) | 71b1a114cdb581721eaafc442a038b8183a056d1 | 27,208 |
def abstract_clone(__call__, self, x, *args):
"""Clone an abstract value."""
def proceed():
if isinstance(x, AbstractValue) and x in cache:
return cache[x]
result = __call__(self, x, *args)
if not isinstance(result, GeneratorType):
return result
cls = resu... | 4c5f85a710d29f751adb7b2a5cd37ca33136e227 | 27,209 |
from typing import Union
from typing import Dict
from typing import Any
import typing
def Layout(
align_baseline: bool = None,
align_center: bool = None,
align_content_center: bool = None,
align_content_end: bool = None,
align_content_space_around: bool = None,
align_content_space_between: boo... | b20157e22d69e32fc89d5abda243b5e967d1eefe | 27,210 |
def paint_hull(inputfile, hull={}):
"""Launches the emergency hull painting robot with the specified Intcode source file
Parameters
----------
inputfile: str
Path/Filename of Intcode source code
hull : dict<(int,int): int>
Initial state of the hull
"""
robot_pos = (0, 0)
... | a781aca8f946cc6931b310848064df93ce888012 | 27,211 |
from typing import Tuple
from datetime import datetime
def get_token_expiration(parser: ConfigParser, profile: str) -> Tuple[str, str]:
"""Return token expiration date and whether it is expired.
Parameters
----------
parser : ConfigParser
Parser with all configuration files.
profile : str... | 0ec467b5c1455784f28b1529e82116e1dbc0dde6 | 27,212 |
def ensure_format(s: str, n_chars: int = None) -> str:
"""
Removes spaces within a string and ensures proper format
------
PARAMS
------
1. 's' -> input string
2. 'n_chars' -> Num characters the string should consist of. Defaults to None.
"""
assert isinstance(s, str), "Input... | 646faf1f155fdd2023ea711adfe62d6e13dd0954 | 27,213 |
def gamma_boundary_condition(gamma=-3):
"""
Defines boundary condition parameterized by either a scalar or list/iterable.
In the latter case, piecewise-interpolation on an equispaced grid over
the interior of (0, 1). In the former, the scalar defines the minimum displacement
value of the boundary co... | acdfe4e311361c27ef0cec4dbebb2fb51d180683 | 27,214 |
def toggleDateSyncButton(click):
"""Change the color of on/off date syncing button - for css."""
if not click:
click = 0
if click % 2 == 0:
children = "Date Syncing: On"
style = {**on_button_style, **{"margin-right": "15px"}}
else:
children = "Date Syncing: Off"
... | f8d74feb690044c96d41d83802f791f54f3f6ab8 | 27,215 |
import os
import inspect
def _find_path(image):
"""Searches for the given filename and returns the full path.
Searches in the directory of the script that called (for example)
detect_match, then in the directory of that script's caller, etc.
"""
if os.path.isabs(image):
return image
... | 402a4ee96229db6a94ce77bfca73749509fbd714 | 27,216 |
def pacf(x, nlags=40, method='ywunbiased', alpha=None):
"""
Partial autocorrelation estimated
Parameters
----------
x : 1d array
observations of time series for which pacf is calculated
nlags : int
largest lag for which the pacf is returned
method : str
specifies whi... | 0f4ac3ca1802f6564a84375d78a85b63ab1b0cf8 | 27,217 |
def _opt(spc_info, mod_thy_info, geo, run_fs,
script_str, opt_cart=True, **kwargs):
""" Run an optimization
"""
# Optimize displaced geometry
geom = geo if opt_cart else automol.geom.zmatrix(geo)
success, ret = es_runner.execute_job(
job=elstruct.Job.OPTIMIZATION,
script_st... | b06a97dd33d66a3bc6dc755f48e010f03eb96832 | 27,218 |
def fi(x, y, z, i):
"""The f1, f2, f3, f4, and f5 functions from the specification."""
if i == 0:
return x ^ y ^ z
elif i == 1:
return (x & y) | (~x & z)
elif i == 2:
return (x | ~y) ^ z
elif i == 3:
return (x & z) | (y & ~z)
elif i == 4:
return x ^ (y | ~... | af30fff4cfc2036eb2b7d3e6b33d365b8d64404a | 27,219 |
import torch
def th_accuracy(pad_outputs, pad_targets, ignore_label):
"""Calculate accuracy.
Args:
pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
pad_targets (LongTensor): Target label tensors (B, Lmax, D).
ignore_label (int): Ignore label id.
Returns:
float: Acc... | 31b89a949a6c2cfa7e9dd2dddc8e0f25d148d5e9 | 27,220 |
def staff_level():
""" Staff Levels Controller """
mode = session.s3.hrm.mode
def prep(r):
if mode is not None:
auth.permission.fail()
return True
s3.prep = prep
output = s3_rest_controller()
return output | f665c822c002a9b27e2f8132213c7c2b8841611d | 27,221 |
def aa_status_string (status):
"""usage: str return = aa_status_string(int status)"""
if not AA_LIBRARY_LOADED: return AA_INCOMPATIBLE_LIBRARY
# Call API function
return api.py_aa_status_string(status) | eabe0b6016b269a749e86e88e3eb5aab8e844215 | 27,222 |
def echo(context, args):
""" echo text
Echo back the following text."""
info(args)
return context | 887e49ce9ff95c7eabf0499756e1cfce418ccd59 | 27,223 |
import time
def wait_for_visibility(element, wait_time=1):
"""Wait until an element is visible before scrolling.
Args:
element (ElementAPI): The splinter element to be waited on.
wait_time (int): The time in seconds to wait.
"""
end_time = time.time() + wait_time
while time.time... | b3e4ed391098131bc62bad4277f8ef163e129d20 | 27,224 |
import asyncio
async def meta(request):
"""Return ffprobe metadata"""
async def stream_fn(response):
async with sem:
cmd = ['ffprobe',
'-v',
'quiet',
'-i',
request.args.get('url'),
'-print_format... | 65bbedf428196ac8317716287550ee868bb6b99e | 27,225 |
from typing import Tuple
import ctypes
def tpictr(
sample: str, lenout: int = _default_len_out, lenerr: int = _default_len_out
) -> Tuple[str, int, str]:
"""
Given a sample time string, create a time format picture
suitable for use by the routine timout.
https://naif.jpl.nasa.gov/pub/naif/toolkit... | 73f098aa71b796d1a586f9e8666e4277339b7c0d | 27,226 |
def survey_page(request):
"""View extracts the data that a volunteer fills out from the monthly survey
and updates the data on app side accordingly"""
if request.method == 'GET':
request.session['vol_id'] = request.GET.get('id')
request.session['vol_email'] = request.GET.get('email')
... | fa9ac1a31782c0a5639d0d20d98cc41772b1ce09 | 27,227 |
def chebyu(n, monic=0):
"""Return nth order Chebyshev polynomial of second kind, Un(x). Orthogonal
over [-1,1] with weight function (1-x**2)**(1/2).
"""
base = jacobi(n,0.5,0.5,monic=monic)
if monic:
return base
factor = sqrt(pi)/2.0*_gam(n+2) / _gam(n+1.5)
base._scale(factor)
r... | b71c947e8f988fe3500339a10bd783ed8561da77 | 27,228 |
def spm(name, path, size, bos= -1, eos= -1, unk= 0, coverage= 0.9995):
"""-> SentencePieceProcessor
trains a sentence piece model of `size` from text file on `path`
and saves with `name`.
"""
SentencePieceTrainer.train(
"--model_prefix={name} \
--input={path} \
--vocab_size... | df22367462839192bcd55093ddf8a2c5b15085f6 | 27,229 |
def list_reshape_bywindow(longlist, windowlen, step=1):
"""
A function to use window intercept long list into several component
A list could like below,
[a, b, c, d, e]
Output could be
[[a,b], [c,d]]
where windowlen as 2,
step as 2
Parameters:
------------
longlist: ... | ee501b49c34656f4c0a1353d36f542b231b3a925 | 27,230 |
def generate_test_repo() -> Repository:
""" gets you a test repo """
test_requester = Requester(
login_or_token="",
retry=False,
password=None,
jwt=None,
base_url="https://github.com/yaleman/github_linter/",
timeout=30,
pool_size=10,
per_page=100,
... | 56ed5de055e0437bb00630f4cdb71e4547868e64 | 27,231 |
from ucsmsdk.mometa.comm.CommSyslogConsole import \
def syslog_local_console_exists(handle, **kwargs):
"""
Checks if the syslog local console already exists
Args:
handle (UcsHandle)
**kwargs: key-value pair of managed object(MO) property and value, Use
'print(ucscoreutil... | f4f0b1c50dd29fdf8d574ff4bd5b3f4b33b522f5 | 27,232 |
import numpy
def filter_inputs(inputlist, minimum_members, number_of_families):
"""
Removes functions that have fewer than minimum_members different hashes,
and returns a subset (number_of_families) different ones.
"""
temp = defaultdict(list)
for i in inputlist:
temp[i[1]].append((i[0], i[2]))
... | a92d37a20964b543bbd89dd86b0a93166ffe0130 | 27,233 |
import sys
def get_dataloader_workers():
"""在非Windows的平台上,使用4个进程来读取的数据。"""
return 0 if sys.platform.startswith('win') else 4 | 92c81010c6e1a81ae3b19a232a243c68ecbfe2fa | 27,234 |
def is_phone_in_call_video_tx_enabled(log, ad):
"""Return if phone in tx_enabled video call.
Args:
log: log object.
ad: android device object
Returns:
True if phone in tx_enabled video call.
"""
return is_phone_in_call_video_tx_enabled_for_subscription(
log, ad, get... | ec51a84c43a808b1e5f750eddf1eedcc4f050158 | 27,235 |
from typing import Sequence
def fit_t1_results(times: Sequence[float], z_expectations: Sequence[float],
z_std_errs: Sequence[float] = None, param_guesses: tuple = (1.0, 15, 0.0)) \
-> ModelResult:
"""
Wrapper for fitting the results of a T1 experiment for a single qubit; simply extr... | 63b8aeb8fa3823ea9857ede3ed07d52076e6d691 | 27,236 |
def find_mapping_net_assn(context, network_id, host_id):
"""
Takes in a network id and the host id to return an SEA that creates that
mapping. If there's no association found, a None is returned
:context: The context used to call the dom API
:network_id: The neutron network id.
:host_id: The Ho... | 543516722a3011d7d859f8f46ae62fd2823989e0 | 27,237 |
import os
def get_emergency_passphrase():
"""Returns emergency passphrase provided in environment variable"""
passphrase = os.environ.get(EMERGENCY_PASSPHRASE_VARIABLE)
if passphrase is None:
raise MissingVariableError(EMERGENCY_PASSPHRASE_VARIABLE)
return passphrase | 6404ef99dfaedf2baf9ee5ccabff12a76fcc8ae0 | 27,238 |
def bubble_sort(seq):
"""Inefficiently sort the mutable sequence (list) in place.
seq MUST BE A MUTABLE SEQUENCE.
As with list.sort() and random.shuffle this does NOT return
"""
changed = True
while changed:
changed = False
for i in xrange(len(seq) - 1):
if seq... | be8c8b4dea93fb91f0ed9397dcd3a9fb9c5d4703 | 27,239 |
def numba_cuda_DeviceNDArray(xd_arr):
"""Return cupy.ndarray view of a xnd.xnd in CUDA device.
"""
cbuf = pyarrow_cuda_buffer(xd_arr)
# DERIVED
return pyarrow_cuda_buffer_as.numba_cuda_DeviceNDArray(cbuf) | 80f820ac589434f407a1e05954cb59c308882540 | 27,240 |
def deg2rad(dd):
"""Convertit un angle "degrés décimaux" en "radians"
"""
return dd/180*pi | cba29769452ed971a9934cae4f072724caf9a8d8 | 27,241 |
def createView(database, view_name, map_func):
"""
Creates and returns a Cloudant view.
"""
my_design_document = design_document.DesignDocument(database, "_design/names")
my_design_document.add_view(view_name, map_func)
return view.View(my_design_document, view_name, map_func) | 77b8fbcbe33c8ae08605f4dff8dc7379dd686329 | 27,242 |
def find_modifiable_states(state_data):
""" Find indices into the state_data array,
Args:
state_data (ndarray): States array, in the form returned by cmd_states.get_cmd_states.fetch_states
Returns:
(ndarray): Numeric index of states that represent dwells with modifiable chip counts
... | 61dc59766deb0b6b2c238fe4ce20fe819ef8c7d3 | 27,243 |
import urllib
def get_tool_def( trans, hda ):
""" Returns definition of an interactive tool for an HDA. """
job = get_dataset_job( hda )
# TODO: could use this assertion to provide more information.
# assert job is not None, 'Requested job has not been loaded.'
if not job:
return None... | 4f1ae068945bc23ee2d870820888aa088bec9f7a | 27,244 |
import os
import hashlib
def create_multi_file_info(directory,
files,
piece_length):
"""
Return dictionary with the following keys:
- pieces: concatenated 20-byte-sha1-hashes
- name: basename of the directory (default name of all torrents)
... | 07964794728aa5a6af3672093de04cb7b5ef990e | 27,245 |
def get_datasource_bounding_box(datasource_uri):
"""Get datasource bounding box where coordinates are in projected units.
Args:
dataset_uri (string): a uri to a GDAL dataset
Returns:
bounding_box (list):
[upper_left_x, upper_left_y, lower_right_x, lower_right_y] in
... | 0d262eafb535807c9f6ce38ca3485f731cc95c97 | 27,246 |
def instance_id(instance):
"""
Return id of instance in hex form.
Helps in logs/debugs/development troubleshooting.
"""
instance_id = hex(id(instance))[2:] # remove leading 0x
return instance_id | fd755c01f4a2031cff072b629fdbc1a596097342 | 27,247 |
def distributions_to_lower_upper_bounds(model, negative_allowed=[], ppf=(0.05,0.95), save_to_model=False):
"""
Converts distributions to uniform distributions by taking specified ppf
Args:
model: The model object
negative_allowed: list of params which are allowed to be negative
ppf:... | c86b53802e34ec71a9a72d498278900a36420f37 | 27,248 |
def refresh_database(engine, server, jobs, source_obj, container_obj):
"""
This function actually performs the refresh
engine:
server: Engine object
jobs: list containing running jobs
source_obj: source object used to refresh from snapshot or timeflow
container_obj: VDB container
"""
... | 99ec18df995ee8ce61a75e8c5448bd40a7ca2f1d | 27,249 |
def create_feature_indices(header):
"""
Function to return unique features along with respective column indices
for each feature in the final numpy array
Args:
header (list[str]): description of each feature's possible values
Returns:
feature_indices (dict): unique feature names as... | a29d8c4c8f3a31ad516216756b7eba7eb4110946 | 27,250 |
def lower(word):
"""Sets all characters in a word to their lowercase value"""
return word.lower() | f96b1470b3ab1e31cd1875ad9cbf9ed017aa0158 | 27,251 |
def band_pass(data, scale_one, scale_two):
"""
Band pass filter
Difference of two gaussians
G(data, s1) - G(data, s2)
"""
bp = gaussian(data, scale=scale_one) - gaussian(data, scale=scale_two)
return bp | 140074b49dc589641380a830b1cce8edb6445a45 | 27,252 |
def _in_dir(obj, attr):
"""Simpler hasattr() function without side effects."""
return attr in dir(obj) | f95e265d278e3014e8e683a872cd3b70ef6133c9 | 27,253 |
import os
def file_exists(work_dir, path):
"""
goal: check if file exists
type: (string, string) -> bool
"""
prev_dir = os.getcwd()
try:
os.chdir(work_dir)
if os.path.exists(path) and os.path.isfile(path):
return True
else:
return False
... | 7bb2e3a4d245908054014cf9210769bf89a7b693 | 27,254 |
import wave
def save_speech(data, p):
""" Saves mic data to temporary WAV file. Returns filename of saved
file """
filename = 'output'
# writes data to WAV file
data = ''.join(data)
wf = wave.open(filename + '.wav', 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudi... | 113a2d808bc5352e8faec5597d47befa37e07e9c | 27,255 |
def load_stat_features_others_windows(patient_list, data_path="statistic_features.csv",
statistics_list=["std_x", "std_y", "std_z"], n_others_windows=40):
"""
Returns:
X_all_data - ndarray of shape(n_records, n_new_features), feature-vector consist of features of curre... | 71de81b25740479f6fc1bc270cff35f33a70b357 | 27,256 |
def map_format(value, pattern):
"""
Apply python string formatting on an object:
.. sourcecode:: jinja
{{ "%s - %s"|format("Hello?", "Foo!") }}
-> Hello? - Foo!
"""
return soft_unicode(pattern) % (value) | 53273dd29d7d0a0e11981fc7de948e930e966fc4 | 27,257 |
def Cadzow(Xk, K, N, tol_ratio=10000, max_iter=10):
"""
Implement Cadzow denoising
Parameters
----------
Xk : signal to denoise
K : number of most significant members to take
N : number of samples in the signal
tol_ratio : min ratio of (K+1)th singular value / Kth singular value
... | 3dfffcf4eeb0b9765059f327b327375378007825 | 27,258 |
def toposortGroup(candidateIrefs):
"""Given a set of IRefs, returns a list of irefs toposorted based on the include graph."""
graph = {}
for iRef in candidateIrefs:
graph[iRef] = set(includePaths(iRef))
candidateSet = set(candidateIrefs)
output = []
for group in toposort.toposort(graph):... | 48166f439a5a9c4ad6ef8abd5c9b9e8dd6559888 | 27,259 |
def make_template(template):
"""Given an OpenSearch template, return a Template instance for it.
>>> template = make_template('http://localhost/search?q={term}')
>>> template.substitute(term='opensearch syntax')
'http://localhost/search?q=opensearch+syntax'
>>>
"""
terms = decompose_templat... | ad6729cf5c4c2d9cf2198781e4566809d2a8f2b9 | 27,260 |
def search(T, dist, w, i=0):
"""Searches for w[i:] in trie T with distance at most dist
"""
if i == len(w):
if T is not None and T.is_word and dist == 0:
return ""
else:
return None
if T is None:
return None
f = search(T.s[w[i]], dist, w, i + 1) ... | 926a0c3e50d38ed1ad7b6e66e8e0a85e24716d89 | 27,261 |
def get_weighted_embeddings(embeddings, weights):
"""Multiply a sequence of word embeddings with their weights
:param embeddings: a sequence of word embeddings got from
embedding_lookup, size of [batch_size, seq_len, embed_dim]
:param weights: a sequence of weights for each word, size of [batch_size,... | 741d68036cc7df4060403f3bf9f2acd08b16466c | 27,262 |
def _adjust_values(females, males):
"""
Adjusting the values as the man moves in with the woman
"""
females = females.copy()
males = males.copy()
males.loc[:,"hid"] = females["hid"].tolist()
males.loc[:,"east"] = females["east"].tolist()
males.loc[:,"hhweight"] = females["hhweight"].tol... | d139869b73e06fb917f843e86d135d1d9db3f4e3 | 27,263 |
def create_other_features(data):
"""Create columns for each other feature extracted."""
# Features list
features_list = ['Fibra_ottica', 'Cancello_elettrico', 'Cantina',
'Impianto_di_allarme', 'Mansarda', 'Taverna',
'Cablato', 'Idromassaggio', 'Piscina']
# Crea... | 20d2f7e71c06952f2604004224fa113ab9ec88bb | 27,264 |
def handler_good():
"""Return True for a good event handler."""
return True | 302ea021276cb9be2d5e98c2a09776f4ee53cc97 | 27,265 |
def form_gov():
"""
Collects the data from the government form and
redirects them to the appropriate results page to report
the final results
"""
collected_data = []
form_gov = InputData_gov()
if request.method == "POST":
try:
collected_data.append("Government")
... | 483a3ae4746a555bf1ab80252659606bca1b5447 | 27,266 |
from io import StringIO
def convert_to_grayscale(buffer):
"""Converts the image in the given StringIO object to grayscale.
Args:
buffer (StringIO): The original image to convert. Must be in RGB mode.
Returns:
StringIO: The grayscale version of the original image.
Raises:
ValueError: If the prov... | 8aa632768da7c49e82923074c3057cffe3ed4d51 | 27,267 |
def line_visible(plaza_geometry, line, delta_m):
""" check if the line is "visible", i.e. unobstructed through the plaza"""
intersection_line = plaza_geometry.intersection(line)
# a line is visible if the intersection has the same length as the line itself, within a given delta
delta = meters_to_degree... | aadc340eddb5f4036af1e8131ced244aa081c75d | 27,268 |
def bad_gateway(message="Bad gateway"):
"""
A shortcut for creating a :class:`~aiohttp.web.Response` object with a ``502`` status and the JSON body
``{"message": "Bad gateway"}``.
:param message: text to send instead of 'Bad gateway'
:type message: str
:return: the response
:rtype: :class:... | 9f9592b53b4e08b5c089ed2ad32754b95b8dcdb9 | 27,269 |
def chromatic_induction_factors(n: FloatingOrArrayLike) -> NDArray:
"""
Return the chromatic induction factors :math:`N_{bb}` and :math:`N_{cb}`.
Parameters
----------
n
Function of the luminance factor of the background :math:`n`.
Returns
-------
:class:`numpy.ndarray`
... | 14f43cbc64aa1904eb38fa2442b33c840aad7275 | 27,270 |
def get_correctly_labeled_entries(all_entries):
"""Get entries that are labeled and evaluated as correct."""
return [
entry for entry in all_entries if convert_to_bool(entry[9]) and convert_to_bool(entry[10])
] | a61251165629c9bfff3d412c8f4be10eb5b8a5ac | 27,271 |
def data_context_connectivity_context_connectivity_serviceuuid_latency_characteristictraffic_property_name_delete(uuid, traffic_property_name): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_latency_characteristictraffic_property_name_delete
removes tapi.topology.LatencyCharacteris... | f8409c09d84ac223f8b3081e4396bc9af86c31c0 | 27,272 |
def tag_state_quantities(blocks, attributes, labels, exception=False):
""" Take a stream states dictionary, and return a tag dictionary for stream
quantities. This takes a dictionary (blk) that has state block labels as
keys and state blocks as values. The attributes are a list of attributes to
tag. ... | 74df558808c1db1e59f27ebe320e8931c291eb28 | 27,273 |
import argparse
def optional_list():
"""Return an OptionalList action."""
class OptionalList(argparse.Action):
"""An action that supports an optional list of arguments.
This is a list equivalent to supplying a const value with nargs='?'. Which itself only allows a single optional
val... | 8e6f84e75c75893862dfbbb93d2d9c75ce229c68 | 27,274 |
import os
def test_exercise_2():
"""Solution for exercise 2."""
dirname = os.path.dirname(os.path.realpath(__file__))
df = pd.read_pickle(f"{dirname}/material/data-consumption-function.pkl")
def construct_predicted_values(income, alpha, beta, gamma):
return alpha + beta * income ** gamma
... | 1b56bba8140fb7e0614e9b1d96edd8e41e5e5837 | 27,275 |
def instancesUserLookup(query=None, query_type=None):
"""
Return a list of sites to which the requested user belongs
Display on /search
"""
if query_type == 'username':
kwargs = {'$or': [{'users.username.site_owner': {'$regex': query, '$options': 'i'}}, {'users.username.site_editor': {'$re... | 27b778fb1d199497c5529754bf0cbbe99357ddcb | 27,276 |
def volume_kerucut_melingkar(radius: float, tinggi: float) -> float:
"""
referensi dari kerucut melingkar
https://en.wikipedia.org/wiki/Cone
>>> volume_kerucut_melingkar(2, 3)
12.566370614359172
"""
return pi * pow(radius, 2) * tinggi / 3.0 | 2f0ddb7b1bd75ec1ee637135f4d5741fda8af328 | 27,277 |
def vgg19(pretrained=False, **kwargs):
"""VGG 19-layer model (configuration "E")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['E']), **kwargs)
if pretrained:
model.... | 2ff08d30dc82297d5d497f55894e62766dd35019 | 27,278 |
def xmprv_from_seed(seed: Octets, version: Octets, decode: bool = True) -> bytes:
"""derive the master extended private key from the seed"""
if isinstance(version, str): # hex string
version = bytes.fromhex(version)
if version not in PRV:
m = f"invalid private version ({version})"
... | f7fb2a06d3e812e24b18453304c9a10476bda31d | 27,279 |
def load_empty_config_setup() -> DictConfig:
"""Return a dictionary containing all the MLOQ setup config values set to None."""
return OmegaConf.load(setup_yml.src) | e862fb753737990a23975659f7c026ca0a2e7132 | 27,280 |
from typing import Dict
from typing import Tuple
def apply_dfg(dfg: Dict[Tuple[str, str], int], start_activities: Dict[str, int], end_activities: Dict[str, int], activities: Dict[str, int], parameters=None, variant=DEFAULT_VARIANT_DFG) -> Tuple[PetriNet, Marking, Marking]:
"""
Apply the chosen IM algorithm to... | 644b871c17bcf983067754588be54aecf20c5c40 | 27,281 |
def make_extrap_log_func(func, extrap_x_l=None):
"""
Generate a version of func that extrapolates to infinitely many gridpoints.
Note that extrapolation here is done on the *log* of the function result,
so this will fail if any returned values are < 0. It does seem to be better
behaved for SFS calc... | 1ddac8d607b18cb3f392ac9a06ccfcc2608617d4 | 27,282 |
def get_logger(name):
"""每次调用,都是一个新的
"""
return LogCollector(name) | 81cb8ad13bbf54ada444cc624b7fc521b2cb8943 | 27,283 |
from re import T
def ShowString(name, msg):
"""Return a html page listing a file and a 'back' button"""
return """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>%s</title>
</head>
<body>
<FORM><INPUT TYPE="BUTTON" VALUE="%s" ONCLICK="history.go(-1)"></FORM>
... | 4f1c837989c18180991dcfb6ecb93025d8a6c27d | 27,284 |
def game_loop(screen, buttons, items, music, sound, g_settings, particles=None, percentthing=None):
"""Manage events, return a gamestate change if it happens, and update the screen"""
while True:
# Check and manage event queue
gs_change = gf.check_events(buttons, music, sound, g_settings)
... | 0fcd40402859bca8671a2856a9872bcd7fb6008e | 27,285 |
def fake_request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Requ... | a2a1cd19fc657d2e0cece37954735d9c66e877c5 | 27,286 |
from typing import List
from typing import Dict
from typing import Any
from typing import OrderedDict
def assert_step_match(
step: Step,
expected_step_func: str,
expected_step_arguments: List[Dict[str, Any]],
step_registry: StepRegistry,
):
"""Assert that the Step correctly matches in the Registry... | 0b156e6f7a1bf39b6fcc7805f0dcb9da30768e58 | 27,287 |
from typing import List
from typing import Dict
import requests
def get_grafana_dashboards_url(admin: bool) -> List[Dict]:
"""
Get a list of dashboard available to the tenant.
:admin (bool) A boolean representing admin status.
Return a list of dashboards dictionaries.
"""
urls = []
req =... | 0b28b9ef1333c633a001297f9c038fd5496952a8 | 27,288 |
def validate_comma_separated_list(argument):
"""Convert argument to a list."""
if not isinstance(argument, list):
argument = [argument]
last = argument.pop()
items = [i.strip(u' \t\n') for i in last.split(u',') if i.strip(u' \t\n')]
argument.extend(items)
return argument | bdf68db95d6070be4ffb5a74a646f5c730c726b4 | 27,289 |
def get_view(brain):
"""Setup for view persistence test"""
fig = brain._figures[0][0]
if mlab.options.backend == 'test':
return
fig.scene.camera.parallel_scale = 50
assert fig.scene.camera.parallel_scale == 50
view, roll = brain.show_view()
return fig.scene.camera.parallel_scale, vie... | 72295348921668e309aed5ac7c281dae7dea292a | 27,290 |
def model_description(formula):
"""Interpret model formula and obtain a model description.
This function receives a string with a formula describing a statistical
model and returns an object of class ModelTerms that describes the
model interpreted from the formula.
Parameters
----------
fo... | fad391e86b31108694c3a784101ad8686f8b3292 | 27,291 |
import argparse
def setup():
"""
Parse command line arguments
Returns parsed arguments
"""
parser = argparse.ArgumentParser(description='Search Reddit Thing')
parser.add_argument(
'subreddit',
help="Enter the name of the subreddit to search.")
parser.add_argument(
... | 49748a64532fcedf3fcc96c8a56de224e6daac43 | 27,292 |
def eintragen_kaeufe(kliste, id_zu_objekt, id_zu_profil):
""" bekommt eine Liste von dicts mit dem Inhalt von je einer Zeile der
registration-Tabelle der alten db. Außerdem ein mapping der produkt_id
der alten db zu model-Instanzen der neuen. Trägt entsprechende Käufe ein
und gibt dict produkt_id -> mo... | 68da4934335fefd64ffbfb9200afa81976037332 | 27,293 |
from datetime import datetime
def update_status(payload: Something, context: EventContext) -> Something:
"""
Updates status of payload to PROCESSED and puts previous status in history.
:param payload: Something, object
:param context: EventContext
"""
logger.info(context, "updating something ... | 7dbcec5930e657dfc3e654c4d1c8c970e9947906 | 27,294 |
def get_holdout_set(train, target_column):
"""This is a sample callable to demonstrate how the Environment's `holdout_dataset` is evaluated. If you do provide a
callable, it should expect two inputs: the train_dataset (pandas.DataFrame), and the target_column name (string). You should
return two DataFrames:... | ba2ea647c287f11f37bc4557ef389ed288b0bb02 | 27,295 |
def field_type(value):
"""Return the type of the field, using the Ref object"""
if isinstance(value, Ref):
return "RefValue"
else:
return "StringValue" | f3165d87ecef0f13214e98856a10851061aea4f6 | 27,296 |
import torch
def test_read_covars_manual_input(tmp_observe_class,
covar_details_mapped_covar_mapped_names_tmp_observe_class,
additional_text, monkeypatch):
"""
test reading of covars from manual input by user. Monkeypatches reliance on functi... | 46c62f0350edbecd001040b5c431862377b9afe8 | 27,297 |
def remove_overlapping_squares_v2(squares_dict, array_type):
"""
removes squares with min_x and min_y that are both within 40 pixels of each other
:param squares_dict: dict with overlapping squares
:param array_type: "Air_100" is the only one currently supported
:return: dict of squares and datafram... | 5f13cda913ece68c0402e5c5aa003bffed50b0cd | 27,298 |
def depth_to_space(x, scale, use_default=False):
"""Depth to space function."""
if use_default:
out = tf.depth_to_space(x, scale)
else:
b, h, w, c = list(map(int, x.shape))
out = tf.reshape(x, [b, h, w, scale, scale, -1])
out = tf.transpose(out, [0, 1, 3, 2, 4, 5])
ou... | 1c6f8c55fd9f7371ca7e69d91db44b86ffb81d45 | 27,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.