content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def svn_merge(rev_range, source, target, lines=None, elides=[],
text_conflicts=0, prop_conflicts=0, tree_conflicts=0,
text_resolved=0, prop_resolved=0, tree_resolved=0,
args=[]):
"""Merge a single change from path SOURCE to path TARGET and verify the
output and that there i... | 67,600 |
def create_namespace_with_name_from_yaml(v1: CoreV1Api, name, yaml_manifest) -> str:
"""
Create a namespace with a specific name based on a yaml manifest.
:param v1: CoreV1Api
:param name: name
:param yaml_manifest: an absolute path to file
:return: str
"""
print(f"Create a namespace wi... | 67,601 |
def convert_properties_obj_in_prop(properties, properties_class):
"""
Convert the internal properties of `properties_class` object in a dictionary.
:param properties: the properties of a `properties_class` object to convert
:param properties_class: if the internal properties of an object are instance o... | 67,602 |
def validate_inputs(scenario_id, subscenarios, subproblem, stage, conn):
"""
Get inputs from database and validate the inputs
:param subscenarios: SubScenarios object with all subscenario info
:param subproblem:
:param stage:
:param conn: database connection
:return:
"""
min_max_bui... | 67,603 |
def sd_generate_state(model, n_steps, n_targets, init_state, birth, death,
noise=True):
"""Generate synthetic data on target states
Provide with a model, number of steps to generate, number of targets,
initial state of each of the targets and the time of the birth and death
of eac... | 67,604 |
def get_all_image_size(dstdb, dstcurse):
"""
่ทๅๅๅพ็็ๅคงๅฐๅ้ฟๅฎฝ๏ผ่กฅๅ
ๅพ็็ๆฉๅฑๅ
ๅฎน
"""
IMAGE_FOLDER = '/home/miwoo/workspace/beeso/tools'
sql = 'select image,id from storage_image'
dstcurse.execute(sql)
images = dstcurse.fetchall()
for img in images:
filename = os.path.join(IMAGE_FOLDER, img[0][... | 67,605 |
def value_of_ace(card_one, card_two):
"""Calculate the most advantageous value for the ace card.
:param card_one, card_two: str - card dealt. See below for values.
:return: int - either 1 or 11 value of the upcoming ace card.
1. 'J', 'Q', or 'K' (otherwise known as "face cards") = 10
2. 'A' (ace... | 67,606 |
def drawK (t,w,h,s):
"""
draw the letter K using t as the turtle, w as the width, h as the height, and s as the spacing between letters
"""
#move the turtle up h and over 2s to make space between the L and the K
t.up ()
t.goto (t.pos()+(2*s,h))
t.down ()
#draw the vertical component of t... | 67,607 |
def allreduce_inplace(
tensor: torch.Tensor,
op: ReduceOp = ReduceOp.SUM,
comm: Optional[B.BaguaSingleCommunicatorPy] = None,
):
"""The in-place version of :func:`allreduce`."""
if _rank_not_in_comm(comm):
return
assert tensor.device != torch.device("cpu"), "input tensor must be CUDA a... | 67,608 |
def autoapi_skip_member(app: Sphinx, what: str, name: str, obj: PythonPythonMapper, would_skip: bool, options: Dict):
"""Project specific skip function for AutoAPI."""
if '__init__' in name:
return False
return would_skip | 67,609 |
async def post_settings(update: AdvancedSettingRequest) -> AdvancedSettingsResponse:
"""Update advanced setting (feature flag)"""
try:
await advanced_settings.set_adv_setting(update.id, update.value)
except ValueError as e:
raise LegacyErrorResponse(message=str(e)).as_error(status.HTTP_400_B... | 67,610 |
def printTable( field_width, entries):
"""Makes it easier to format output for evaluation metrics."""
cols = len(entries)
labelFormat = ''
for i in range(0,cols):
extra = ''
if type(entries[i]) is float:
labelFormat += '{0[' + str(i) + ']:>{width}.2f' + '}'
else:
labelFormat += '{0[' + str(i) + ']:>{wi... | 67,611 |
def safe_log10(data):
""" A safe function for LOG10 in cases of too small values (close or equal to 0 ) """
prob_tmp = np.where(data > 1.0e-10, data, 1.0e-10)
result = np.where(data > 1.0e-10, np.log10(prob_tmp), -10)
return result | 67,612 |
def offset(point, direction, distance=1):
"""Offsets a point in a given direction some distance,
E.g. (0, 0) offset 'R' by 2 => (2, 0)
Args:
point (Point): the point to use for the offset point
direction (str): a valid direction ('U', 'R', 'D' or 'L')
distance (Optional[int]): the d... | 67,613 |
def property_entropy(col, sim_matrix, bg_distr, seq_weights, gap_penalty=1):
"""Calculate the entropy of a column col relative to a partition of the
amino acids. Similar to Mirny '99. sim_matrix and bg_distr are ignored, but
could be used to define the sets. """
# Mirny and Shakn. '99
property_pa... | 67,614 |
def set_p_to_zero(pvect, i):
""" Provided utility function: given a symbolic vector of
probabilities and an index 'i', set the probability of the
i-th element to 0 and renormalize the probabilities so they
sum to 1.
"""
new_pvect = T.set_subtensor(pvect[i], 0.)
new_pvect = new_pvect / new_pv... | 67,615 |
def get_cards(session: requests.sessions.Session, dni: str) -> list:
"""Returns cards list and details using the session provided."""
endpoint = GET_CARDS_ENDPOINT
data = {
"dni": dni,
}
json_response = session_post(session, endpoint, data)
card_list = json_response["response"]["listCard... | 67,616 |
async def main():
"""Show example on controlling your WLED device."""
async with WLED("10.10.11.82") as led:
device = await led.update()
print(device.info.version)
# Turn strip on, full brightness
await led.master(on=False, brightness=255) | 67,617 |
def define_systems(cube, verbose=True, MinNSpax=0, return_first=False,
return_second=False):
"""
Args:
cube:
verbose:
MinNSpax:
Returns:
"""
#!..make sure that undefined variance pixels that are defined in the datacube have a dummy high value
#WHER... | 67,618 |
def configure_i18n(app):
""" ๅฝ้
ๅๆฏๆ. """
babel = Babel(app)
@babel.localeselector
def get_locale():
if has_request_context() and request:
# Request a locale and save to session
rl = request.args.get('_locale', None)
if rl:
accept_languages = ap... | 67,619 |
def process_articles_results(articles_results_list):
"""
Function that process the list of article from the request.
"""
articles_results = []
for individual_article in articles_results_list:
title = individual_article.get('title')
description = individual_article.get('description')
... | 67,620 |
def units_handler(validator, v_item):
"""
validate @units
:see: https://bitbucket.org/cfpython/cfunits-python
:see: https://pypi.python.org/pypi/cfunits/1.5.1
But, cfunits is not ready for Python3
Requires a python version from 2.6 up to, but not including, 3.0.
:see: https://github.com/S... | 67,621 |
def _compute_diagram_component(Primes, Update, Subspaces, EdgeData, Silent):
"""
Also computes the commitment diagram but without removing out-DAGs or considering connected components separately.
Not meant for general use. Use compute_diagram(..) instead.
"""
assert(Update in PyBoolNet.StateTransit... | 67,622 |
def translate_english_to_chinese(target_str):
""" translate English to Chinese
Args:
target_str (str): target string
"""
translator = Translator(to_lang="chinese")
result = translator.translate(target_str)
return result | 67,623 |
def export_to_csv(data_url_path):
"""
Reads the data from the url and exports it to a json file.
Args:
data_url_path (str):
Path to the data
"""
print("Exporting data results to CSV file...")
csv_file = open('report_results.csv', "w", encoding="utf8")
csv_file.write("g... | 67,624 |
def FakeGetNameInfo(sockaddr, flags):
"""Fake version of socket.getnameinfo."""
raise NotImplementedError() | 67,625 |
def div(a,b):
"""Elementwise division with another vector, or with a scalar."""
if hasattr(b,'__iter__'):
if len(a)!=len(b):
raise RuntimeError('Vector dimensions not equal')
return [ai/bi for ai,bi in zip(a,b)]
else:
return [ai/b for ai in a] | 67,626 |
def test_bulk_operations(site, client):
"""Test creating/updating multiple Devices at once."""
# URIs
attr_uri = site.list_uri('attribute')
dev_uri = site.list_uri('device')
# Successfully create a collection of Devices
collection = [
{'hostname': 'device1'},
{'hostname': 'devic... | 67,627 |
def part2(grid):
"""
A basin is all locations that eventually flow downward to a single low point.
Therefore, every low point has a basin
Locations of height 9 do not count as being in any basin
All other locations will always be part of exactly one basin.
The size of a basin is the number of lo... | 67,628 |
def test_impute_single_value(missingdata_df):
"""Check if constant value is imputed correctly."""
df = missingdata_df.impute("a", 5)
assert set(df["a"]) == set([1, 2, 5]) | 67,629 |
def normalize_twitter_hashtag(text):
"""hashtagใๅ
ฑ้ใฎๆๅญๅใซ็ฝฎใๆใใ๏ผๅซใใงใใใใจใ่กจใใใ๏ผ"""
return re.sub(r"#\w+", "#hashtag", text) | 67,630 |
def get_market_price_change_by_ticker(fromdate: str, todate: str, market: str="KOSPI", adjusted: bool=True) -> DataFrame:
"""์
๋ ฅ๋ ๊ธฐ๊ฐ๋์์ ์ ์ข
๋ชฉ ์์ต๋ฅ ๋ฐํ
Args:
fromdate (str ): ์กฐํ ์์ ์ผ์ (YYYYMMDD)
todate (str ): ์กฐํ ์ข
๋ฃ ์ผ์ (YYYYMMDD)
market (str , optional): ์กฐํ ์์ฅ (KOSPI/... | 67,631 |
def save_gammatone(list_audio, output_dir, fs):
"""
Save a list of chunks audio as gammagram
:param list_audio: list of audio chunks
:param output_dir: path of the output_dir
:param fs: sampling rate
:return:
"""
for i, f in enumerate(list_audio):
waveform = gtgram(f, fs, window... | 67,632 |
def deserialize_environment_from_cluster(cluster: Cluster,
path: Optional[
str] = None) -> Environment: # noqa, pylint: disable=line-too-long,bad-whitespace
"""Loads the environment from remote file.
See :func:`.pull_env... | 67,633 |
def filter(data, low=300, high=6000, rate=30000):
""" Filter the data with a 3-pole Butterworth bandpass filter.
This is used to remove LFP from the signal. Also reduces noise due
to the decreased bandwidth. You will typically filter the raw data,
then extract spikes.
**Ar... | 67,634 |
def load_config(filepath: str) -> ConfigFile:
"""Load configuration
Arguments:
filepath {str}
Returns:
{ConfigFile} -- query parameters
"""
config = ConfigFile.from_filename(filepath)
validate(config.content, config.version)
return config | 67,635 |
def szudzik_pair(pairs: np.ndarray) -> np.ndarray:
"""
Numpy implementation of a pairing function by Matthew Szudzik
Args:
pairs (np.ndarray): n x 2 integer array of pairs.
Returns:
hash_list (np.ndarray): n x 1 integer array of hashes.
"""
xy = np.array(pairs)
x = xy[..., ... | 67,636 |
def relu(x):
"""
Compute the relu of x
Arguments:
x -- A scalar or numpy array of any size.
Return:
s -- relu(x)
"""
s = np.maximum(0,x)
return s | 67,637 |
def SearchForExecutableOnPath(executable, path=None):
"""Tries to find all 'executable' in the directories listed in the PATH.
This is mostly copied from distutils.spawn.find_executable() but with a
few differences. It does not check the current directory for the
executable. We only want to find things that ... | 67,638 |
def test_metadata_parser_snapshot_outside_daterange(parallel_test_data):
"""Test for PlantCV."""
# Create config instance
config = WorkflowConfig()
config.input_dir = parallel_test_data.snapshot_imgdir
config.json = "output.json"
config.filename_metadata = ["imgtype", "camera", "frame", "zoom", ... | 67,639 |
def get_enumeration_sparql(rq, v, endpoint, auth=None):
"""
Returns a list of enumerated values for variable 'v' in query 'rq'
"""
glogger.info('Retrieving enumeration for variable {}'.format(v))
vcodes = []
# tpattern_matcher = re.compile(".*(FROM\s+)?(?P<gnames>.*)\s+WHERE.*[\.\{][\n\t\s]*(?P<... | 67,640 |
def get_instance_id(finding):
"""
Given a finding, go find and return the corresponding AWS Instance ID
:param finding:
:return:
"""
for kv in finding['attributes']:
if kv['key'] == 'INSTANCE_ID':
return kv['value']
return None | 67,641 |
def get_winning(process_id: int) -> Optional[list[Version]]:
"""Get a dict of the winning process versions per customer category.
Format of dict:
[{
'customer_category': str,
'winning_version': Version.A or Version.B
}]
:param process_id: specify process
:return: list with winni... | 67,642 |
def _create_pending_session_if_needed(request):
"""
return or create a session context for entering samples manually to create a sample set
"""
if "input_samples" not in request.session:
logger.debug("views_helper._create_pending_session_if_needed() going to CREATE new request.session")
... | 67,643 |
def BackwardFoldScaleAxis():
"""Backward fold axis scaling into weights of conv2d/dense.
Returns
-------
ret : tvm.relay.Pass
The registered pass to backward fold expressions.
Note
----
It is recommended to call backward_fold_scale_axis
before using forward_fold_scale_axis as b... | 67,644 |
def refresh(request):
"""Endpoint that'll use the database information to update running
process"""
ips_from_database = [x.ip for x in Machine.objects.all()]
database_machines_found = LocalNetworkScanner().refresh(ips_from_database, PORTS)
# if machine in database found on netowkr
ips_from_fou... | 67,645 |
def triple(subject, relation, obj):
"""Builds a simple triple in PyParsing that has a ``subject relation object`` format"""
return And([Group(subject)(SUBJECT), relation(RELATION), Group(obj)(OBJECT)]) | 67,646 |
def embedall(
face_extractor,
video,
h5fn,
from_skels,
start_frame,
skel_thresh_pool,
skel_thresh_val,
batch_size,
write_bboxes,
write_chip,
):
"""
Create a HDF5 face dump from a video using dlib.
"""
from skelshop.face.pipe import all_faces_from_skel_batched, ite... | 67,647 |
def _append_variable_index_level(df: Union[pd.DataFrame, pd.Series], field_name: FieldName) -> None:
"""Add level `VARIABLE` to df.index with constant value `field_name`, in-place"""
assert df.index.names == [CommonFields.LOCATION_ID]
# From https://stackoverflow.com/a/40636392
df.index = pd.MultiIndex.... | 67,648 |
def test_root_values_on_missing_file(request):
"""Test values on the root of the config file when it's missing."""
ProjectMock(request).style(
"""
["pre-commit-config.yaml"]
fail_fast = true
whatever = "1"
"""
).lint().assert_errors_contain(
"""
NIP331... | 67,649 |
def _module_repr_from_spec(spec):
"""Return the repr to use dla the module."""
# We mostly replicate _module_repr() using the spec attributes.
jeลผeli spec.name jest Nic:
name = '?'
inaczej:
name = spec.name
jeลผeli spec.origin jest Nic:
jeลผeli spec.loader jest Nic:
... | 67,650 |
def get_article_sentiment(article):
"""
Extracts sentiment analysis for article.
@param article: article dictionary (retrieved from the Data Lake)
@returns: (article_level_polarity, article_level_subjectivity)
"""
if language_dict[article['media']] == 'DE':
blob = TextBlobDE(article['tex... | 67,651 |
def frame_to_yaml_safe(frame):
"""
Convert a pandas DataFrame to a dictionary that will survive
YAML serialization and re-conversion back to a DataFrame.
Parameters
----------
frame : pandas.DataFrame
Returns
-------
safe : dict
"""
return {col: series_to_yaml_safe(series)... | 67,652 |
def hgcmd():
"""Return the command used to execute current hg
This is different from hgexecutable() because on Windows we want
to avoid things opening new shell windows like batch files, so we
get either the python call or current executable.
"""
if mainfrozen():
if getattr(sys, 'frozen... | 67,653 |
def receive_set(target, value, old, initiator): # old, initiator not being used but need to be here
"""
Updates the compute_remaining for a user when the jobs.completed
field is set for a job.
"""
### Added because started can be not set (only .created is defaulted)
### and you get a problem wi... | 67,654 |
def coach_or_competitor(username):
"""converts a string to bytes
Args:
username: the user whose should be checked
Returns:
renders the competiotr template if user is comeptitor or the coach one if coach
"""
if is_coach(username):
print "This user is a coach"
return... | 67,655 |
def taint_name(rawtxt):
"""check the interface arguments"""
tainted_input = str(rawtxt).lower()
for test_username in get_user_list():
if tainted_input in test_username:
return test_username
return None | 67,656 |
def cdlsticksandwich(opn, high, low, close):
"""Stick Sandwich๏ผ
A stick sandwich is a technical trading pattern in which three candlesticks form what appears
to resemble a sandwich on a trader's screen. Stick sandwiches will have the middle candlestick
oppositely colored of the candlesticks on either s... | 67,657 |
def find_typerefs(node, fileName):
""" Find all references to the type named 'typename'
"""
#if node.kind == clang.cindex.CursorKind.is_declaration
#if node.kind.is_definition():
#if node.is_definition():
#ref_node = clang.cindex.Cursor_ref(node)
#ref_node = node
#if node.kind ==... | 67,658 |
def sample_bounded_multicoal_tree(stree, n, T, leaf_counts=None, namefunc=None,
sroot=None, sleaves=None, stimes=None,
gene_counts=None):
"""
Returns a gene tree from a bounded multi-species coalescence process
stree -- species tree
... | 67,659 |
def check_packages_in_ecosystem(s3interface, csvReporter, ecosystem):
"""Check all packages in selected ecosystem."""
core_packages = s3interface.read_core_packages_for_ecosystem(ecosystem)
packages = s3interface.read_packages_for_ecosystem(ecosystem)
store_list("s3_core_packages.txt", core_packages)
... | 67,660 |
def collect_inventory_license_expression(location, scancode=False):
"""
Read the inventory file at location and return a list of ABOUT objects without
validation. The purpose of this is to speed up the process for `gen_license` command.
"""
abouts = []
if scancode:
inventory = gen.load_... | 67,661 |
def node_hist_fig(
node_color_distribution,
title="Graph Node Distribution",
width=400,
height=300,
top=60,
left=25,
bottom=60,
right=25,
bgcolor="rgb(240,240,240)",
y_gridcolor="white",
):
"""Define the plotly plot representing the node histogram
Parameter... | 67,662 |
def analytic_solution_modes(dx, p, nx, ny, x, y, c, t, n):
"""
Analytic solution for acoustic modes in 2D rectangular domains.
:param dx spatial step after discretization, scalar (m).
:param p numerical acoustic pressure used for the sizes, 2D-array (Pa).
:param nx mode nu... | 67,663 |
def encode_images(format_dict: Dict) -> Dict[str, str]:
"""b64-encodes images in a displaypub format dict
Perhaps this should be handled in json_clean itself?
Parameters
----------
format_dict : dict
A dictionary of display data keyed by mime-type
Returns
-------
format_dict... | 67,664 |
def initialise_fleet_data(fleet_file_path=None, reset=False):
"""
Uses the provided file path to load the fleet file csv file.
If no fleet file is found we return false.
Reset=True Remove all records and replace with this file.
Reset=False Add these fleet entries to the fleet table.
return T... | 67,665 |
def read_catl(path_to_file):
"""
Reads survey catalog from file
Parameters
----------
path_to_file: `string`
Path to survey catalog file
survey: `string`
Name of survey
Returns
---------
catl: `pandas.DataFrame`
Survey catalog with grpcz, abs rmag and stell... | 67,666 |
def deconv(in_planes, out_planes, upscale_factor=2):
"""2d deconv"""
kernel_size, stride, opad = get_deconv_params(upscale_factor)
# print("DECONV", kernel_size, stride, opad)
return nn.ConvTranspose2d(in_planes, out_planes,
kernel_size=kernel_size,
... | 67,667 |
def generate_file_rst(fname, target_dir, src_dir, plot_gallery):
""" Generate the rst file for a given example.
"""
base_image_name = os.path.splitext(fname)[0]
image_fname = '%s_%%s.png' % base_image_name
this_template = rst_template
last_dir = os.path.split(src_dir)[-1]
# to avoid leading... | 67,668 |
def OR(r1, r2):
"""Or/Union
Equates to union (both relations have same heading)
"""
if r1.heading() != r2.heading():
raise RelationInvalidOperationException(r1, "OR can only handle same reltypes so far: %s" % str(r2._heading))
#assert r1._heading == r2._heading, "OR can only handle ... | 67,669 |
def test_select_workflow_engines():
"""Tests for select_workflow_engines()."""
from reana.reana_dev.run import select_workflow_engines
for (input_value, output_expected) in (
# regular workflow engines:
(["cwl",], ["cwl",]),
(["serial",], ["serial",]),
(["cwl", "yadage",], [... | 67,670 |
def integrity_check_packet(received_data_path):
"""
This function will test the integrity of the data of a given file
It will open the actual file and verify the the Headers, ID, and
data integrity of all transmission recorded in the file
@params:
received_data_path - Required : path to the received data file (... | 67,671 |
def bernoulli_like(x, mean=0.5, seed=auto_select, name=''):
"""bernoulli_like(x, mean=0.5, seed=auto_select, name='')
Generates samples from the Bernoulli distribution with success probability `mean`.
Args:
x: cntk variable (input, output, parameter, or constant) from which to copy the shape, data ... | 67,672 |
def dVdc_calc(Vdc,Ppv,S,C):
"""Calculate derivative of Vdc"""
dVdc = (Ppv - S.real)/(Vdc*C)
return dVdc | 67,673 |
def register_last_index(index_path: Path):
"""Save the last index loaded as a symlink to use again later."""
if index_path == LAST_PATH:
return
for index, last in ((index_path, LAST_PATH),
(f'{index_path}.shelf', f'{LAST_PATH}.shelf')):
try:
os.remove(last... | 67,674 |
def percentile_spectrogram(spg, f_axis, rank_freqs=(8., 12.), pct=(0, 25, 50, 75), sum_log_power=True, show=True):
""" Compute percentile power spectra using the spectrogram, ranked by power within
a specific band. Essentially a different way of visualizing correlation between freqs.
Parameters
-------... | 67,675 |
def _get_cold_progression(age, rng, carefulness, preexisting_conditions, really_sick, extremely_sick):
"""
[summary]
Args:
age ([type]): [description]
rng ([type]): [description]
carefulness ([type]): [description]
preexisting_conditions ([type]): [description]
reall... | 67,676 |
def project_to_image_space(anchors, stereo_calib_p2, image_shape):
"""
Projects 3D anchors into image space
Args:
anchors: list of anchors in anchor format N x [x, y, z,
dim_x, dim_y, dim_z]
stereo_calib_p2: stereo camera calibration p2 matrix
image_shape: dimensions of ... | 67,677 |
def define_model(quant_features, qual_features):
"""Define model
Args:
quant_features (list of str): corresponding to column names of training data
qual_features (list of str): corresponding to column names of training data
Returns:
model (sklearn obj)
"""
# transf... | 67,678 |
def check_order(df, topcol, basecol, raise_error=True):
"""
Check that all rows are either depth ordered or elevation_ordered.
Returns 'elevation' or 'depth'.
"""
assert basecol in df.columns, f'`basecol` {basecol} not present in {df.columns}'
if (df[topcol] > df[basecol]).all():
return... | 67,679 |
def environment(request):
"""
A JavaScript snippet that initializes the environment
"""
# Capture all REACT_APP_ variables into a dictionary for context
environment = {
k: v
for k, v in os.environ.items()
if k.startswith('REACT_APP_')
}
# Add Environment variable, lo... | 67,680 |
def search(results_path, network_type, num_layers,
num_neurons, batch_size, num_epochs,
training_method, regularization):
"""Search relevant files.
based on input arguments and return a list of filename
Parameters
----------
results_path : string
Destination of resul... | 67,681 |
async def list_keys(hub, ctx, name, resource_group, **kwargs):
"""
.. versionadded:: 2.0.0
Retrieve a Redis cache's access keys. This operation requires write permission to the cache resource.
:param name: The name of the Redis cache.
:param resource_group: The name of the resource group.
CL... | 67,682 |
def new_simple_controller_config(
config: dict = None,
options: dict = None,
config_from_file=False,
serial_number="1111",
devices: Tuple[pv.VeraDevice, ...] = (),
scenes: Tuple[pv.VeraScene, ...] = (),
setup_callback: SetupCallback = None,
) -> ControllerConfig:
"""Create simple contorl... | 67,683 |
def test_cache_delete(cache):
"""Test that cache.delete() removes a cache key."""
key, value = ("key", "value")
cache.set(key, value)
assert cache.has(key)
cache.delete(key)
assert not cache.has(key)
cache.delete(key)
assert not cache.has(key) | 67,684 |
def online_mean_and_std(loader):
"""Compute the mean and sd in an online fashion
Var[x] = E[X^2] - E^2[X]
"""
cnt = 0
fst_moment = torch.empty(3)
snd_moment = torch.empty(3)
for x, y in loader:
b, c, h, w = x.shape
nb_pixels = b * h * w
sum_ = torch.sum(x, dim=... | 67,685 |
def GetDevice(serial=None):
"""Returns and ADBDevice given its serial.
The first connected device is returned if serial is None.
"""
devices = [d for d in ListDevices() if not serial or serial == d.serial]
return devices[0] if devices else None | 67,686 |
def coding_problem_39(cells):
"""
Conway's Game of Life takes place on an infinite two-dimensional board of square cells. Each cell is either dead or
alive, and at each tick, the following rules apply:
Any live cell with less than two live neighbours dies.
Any live cell with two or three li... | 67,687 |
def api_demo_data_project(): # noqa: F401
"""Get info on the article"""
subset = request.args.get('subset', None)
if subset == "plugin":
result_datasets = get_dataset_metadata(exclude="builtin")
elif subset == "test":
result_datasets = get_dataset_metadata(include="builtin")
else:... | 67,688 |
def bioactivity_mapping(
basket_path: Path,
output_dir: Path,
activity_path: Path,
configd: Dict,
include_web_output: bool,
) -> None:
"""Performs compound activity mapping on basketed features."""
logger.debug("Loading baskets and activity data")
activity_df = activity.load_activity_dat... | 67,689 |
def parse_args():
"""set and check parameters."""
parser = argparse.ArgumentParser()
parser.add_argument("--result_path", type=str, default="", help="root path of predicted images")
args_opt = parser.parse_args()
return args_opt | 67,690 |
def nonmax_supression(x):
"""Nonmaximum suppression finds crests of a signal.
All other non-maxima found from thresholding are suppressed.
Args:
x (1D numpy array): a signal which has been thresholded to only
contain maximum peaks.
Returns:
1D numpy array: an array indexes ... | 67,691 |
def pyth_backward_induction(num_periods, max_states_period, periods_draws_emax,
num_draws_emax, states_number_period, periods_payoffs_systematic,
edu_max, edu_start, mapping_state_idx, states_all, delta, is_debug,
is_interpolated, num_points_interp, shocks_cholesky):
""" Backward induction p... | 67,692 |
def test_put_deck_conjuration_in_deck(
client: TestClient, session: db.Session, user_token
):
"""Must not allow saving a deck with conjurations in the card list"""
user, token = user_token
valid_deck = _valid_deck_dict(session)
conjuration_stub = (
session.query(Card.stub)
.filter(Ca... | 67,693 |
def plot_settings_together(Data, config):
"""Plot the displacement and velocity of the end-effector, hammer and the magnets
Arguments:
Data {dataframe} -- [a pandas dataframe consisting of the optimal results for hammering]
config {yaml} -- [configurations provided in the config.ya... | 67,694 |
def basic_histogram():
"""
Here we plot a basic histogram showing the distribution of band gaps
in the matminer dielectric constant dataset, originally taken from Petousis
et al., 2017.
"""
df = load_dataset("dielectric_constant")
pf = PlotlyFig(title="Distribution of Band Gaps in the Dielec... | 67,695 |
def ipv4_subnet_details(addr, mask):
"""
Function that prints the subnet related details- Network, Broadcast, Host IP range and number of host addresses
:param addr: IP address
:param mask: subnet mask
:return: result dictionary containing the details
"""
network_address = []
broadcast_a... | 67,696 |
def test_children_invalid_zoom():
"""invalid zoom."""
tms = morecantile.tms.get("WebMercatorQuad")
with pytest.raises(InvalidZoomError):
tms.children(243, 166, 9, zoom=8)
with pytest.raises(InvalidZoomError):
tms.children((243, 166, 9), zoom=8) | 67,697 |
def _get_sdk_name(platform):
"""Returns the SDK name for the provided platform.
Args:
platform: The `apple_platform` value describing the target platform.
Returns:
A `string` value representing the SDK name.
"""
return platform.name_in_plist.lower() | 67,698 |
def myplus(a, b=0):
"""
Parameters
----------
a : float
the first number
b : float
the second number
defaults to zero
Returns
-------
a + b
"""
return a + b | 67,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.