content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def help_text():
"""
Retreive human-readable description of all added craftable items
:return: description of all added craftable items
:rtype: str
"""
ret = []
for name in craftables:
items, item = craftables[name]
item_names = utils.list_to_english([str(x) for x in items])... | ce8ffb7ed681ad875242317b8ae426ca13ffb9dc | 36,190 |
def _load_image(path):
"""
Reads image image from the given path and returns an numpy array.
"""
image = np.load(path)
assert image.dtype == np.uint8
assert image.shape == (64, 64, 3)
return image | 0950925b484dbe75bb578df781c6ee09c1e80634 | 36,191 |
def nb(model, ref):
"""
Normalzied bias.
model = nuemrical solution of shape M by N
ref = analytical solution or observation of shape M by N
returns nb
"""
e = model - ref
mean_e = nanmean(e)
mean_abs_ref = nanmean(abs(ref))
nb = mean_e / mean_abs_ref
return nb | d021af55091f161e6621222d3be9ed5f85541cc7 | 36,192 |
def annotate_heatmap(im, data=None, valfmt="{x:.2f}", textcolors=["black", "white"], threshold=None, **textkw):
"""
A function to annotate a heatmap.
Parameters
----------
im
The AxesImage to be labeled.
data
Data used to annotate. If None, the image's data is used. Optional.
... | 9b75485cf6b9f33b1feccbdd552fe7c68378fb40 | 36,193 |
def sigmoid(x):
"""
Sigmoid activation function
@param x: input array
@return:
out: output array
"""
return 1 / (1 + np.exp(-x)) | a1b23861287b50c7f78537e026b2da9bd2b664bd | 36,194 |
def _flagword(obj):
"""Internal use only"""
#create the flags word for an objective
_f = B_DISC #everything's discoverable
if obj.neg:
_f |= B_NEG
if obj.synch:
_f |= B_SYNCH
if obj.dry:
_f |= B_DRY
return _f | eb34deececffdbd8a69c600d437d4cd0965b49dd | 36,195 |
def create_model(conditioning_dim, flags):
"""Define model, and initialize classifiers."""
model = VAEBasic(flags.height, flags.width, latent_dim=flags.latent_dim, conditioning_dim=conditioning_dim,
start_filters=flags.start_filters, name='VAE')
return model | 8903edadfafbb60183d740855fb6f1733ff4d0f3 | 36,196 |
def palette(name):
"""Palette decorator"""
def wrapper(cls):
palette_providers[name] = cls
return cls
return wrapper | 27e8dffd4eb9eeb7df2e31812f5c2f6e64c98ea0 | 36,197 |
import copy
def remove_one_path(path_graph, dest=None, preserv_cov=False):
"""
Removes one path from the path set in a way that
the vertices covered by the set of paths does not
decrease.
"""
complete = False
ix = 0
if dest is None:
dest = max(list(path_graph.keys())) + 1
w... | e8bf21429937e36190c530a1fd69a2a83007ca9b | 36,198 |
import types
import inspect
def spec_builtin(obj):
""" Describe a builtin function """
# Built-in functions cannot be inspected by
# inspect.getargspec. We have to try and parse
# the __doc__ attribute of the function.
docstr = obj.__doc__
args = ''
if not docstr:
if isinstance(obj,types.... | b892bc8268e7394e87de63e00154698084fba302 | 36,199 |
def get_nb_skl_base_estimators(obj, fitted=True):
"""
Returns the number of :epkg:`scikit-learn` *BaseEstimator*
including in a pipeline. The function assumes the pipeline
is not recursive.
@param obj object to walk through
@param fitted count the number of fitted object
... | 4462b7c4e897beff4cbea9ded3d369aace74821c | 36,200 |
def interval_velocity_time(vp, pars):
"""
Output the interval velocity in time
@params:
vp (numpy.ndarray) : A 1D array containing the Vp profile in depth
pars (ModelParameter): Parameters used to generate the model
@returns:
vint (numpy.ndarray) : The interval velocity in time
"""
... | 576c28c5aad293da1403eb495f619776a9b7c6b3 | 36,201 |
import io
import json
import warnings
def read_analysis_settings(analysis_settings_fp, il_files_exist=False,
ri_files_exist=False):
"""Read the analysis settings file"""
# Load analysis_settings file
try:
# Load as a json
with io.open(analysis_settings_fp, 'r',... | 3a83e27f031b71616197e03ea24467055af47913 | 36,202 |
from typing import Any
def encode_current(value: Any) -> bytes:
"""Encode current value to raw (2 bytes) payload"""
return int.to_bytes(int(value * 10), length=2, byteorder="big", signed=True) | 96dcc6d14bc9a0e0519fb5157f468b0d02afd3c5 | 36,204 |
def assessments_view():
"""The clutter-free list of all Person's Assessments"""
return flask.render_template("assessments_view/index.haml") | a63666a5d025bc97129e595be8205e108ed011cd | 36,205 |
def run_charm_authorize(token):
"""Authorize charm to perfom certain actions.
Run vault charm action to authorize the charm to perform a limited
set of calls against the vault API.
:param token: Token to authorize action against vault.
:type token: str
:returns: Action object
:rtype: juju.... | 0acfb5a1056078e7dcf10eb999ba96e8d1c3e401 | 36,206 |
def get_odds_labels(nfunc, adfam=False):
"""Labels used for odds in results_df."""
if adfam:
col_names = [r'$P(T={},N={})$'.format(1, i + 1)
for i in range(nfunc)]
col_names += [r'$P(T={},N={})$'.format(2, i + 1)
for i in range(nfunc)]
col_names... | ca874d9da52dfe49625305cde62ef7489439eb00 | 36,208 |
def subsetphaseheads(repo, subset):
"""Finds the phase heads for a subset of a history
Returns a list indexed by phase number where each item is a list of phase
head nodes.
"""
cl = repo.changelog
headsbyphase = {i: [] for i in allphases}
# No need to keep track of secret phase; any heads ... | 85a9d7c92b81d192de493ff8cced2cd44bd57573 | 36,209 |
from typing import Union
from typing import List
def mimic_3_demo(encoded: bool = False, mudata: bool = False) -> Union[MuData, List[AnnData]]: # pragma: no cover
"""Loads the MIMIC-III demo dataset
Args:
encoded: Whether to return an already encoded object
mudata: Whether to return a MuData... | cdb9d5b47649079e48316f96baa264aff7e959b5 | 36,210 |
def get_validation_context(self):
"""
Retrieves the validation context.
:rtype: String
:return: The validation context.
"""
return self.validation_context | b025b742a6fd5a537752f897eb8ed88ed56e5a21 | 36,212 |
def _iprompt(repo, mynode, orig, fcd, fco, fca, toolconf):
"""Asks the user which of the local or the other version to keep as
the merged version."""
ui = repo.ui
fd = fcd.path()
if ui.promptchoice(_(" no tool found to merge %s\n"
"keep (l)ocal or take (o)ther?"
... | be65996080ccde703be7db6320b76dd39a9b38e3 | 36,213 |
def floating_ip_bulk_destroy(context, ips):
"""Destroy a lot of floating ips from the values dictionary."""
return IMPL.floating_ip_bulk_destroy(context, ips) | d060861d500bbef6614a4422071de704ad077304 | 36,214 |
def prepare_save_data(ts, conf):
"""
Given a time stepper configuration, return a list of time steps when the
state should be saved.
"""
try:
save_steps = conf.options.save_steps
except:
save_steps = -1
if save_steps == -1:
save_steps = ts.n_step
is_save = nm.li... | e632911286be64bc2d229a974092b92021f9ac14 | 36,215 |
def _add_attr(caller, attr_string, **kwargs):
"""
Add new attribute, parsing input.
Args:
caller (Object): Caller of menu.
attr_string (str): Input from user
attr is entered on these forms
attr = value
attr;category = value
attr;ca... | cbc7eca9ff194911728dca2253ec006ffd99fb0c | 36,216 |
import copy
def route_multiple(world, robots, mode="random", number_of_runs=1):
"""
Routes the world demand and matches it with the robots like in the route method but multiple times to evaluate
quantities such as mean, etc. Particularly useful for the random method.
Parameters
----------
wor... | 27783fcef81a3cac214b754ae407922ccf7c083e | 36,217 |
import psutil
def disk_total_write():
"""
Returns the total amount of data written for the startup disk in a readeable format (> string)
"""
return get_scaled_size(psutil.disk_io_counters().write_bytes) | a502f4011b9512afbd8109f08a94d9e78c10d914 | 36,218 |
def identify_principle_axis(C, sI_N=100):
"""
Using 2nd-order cumulant identify principle axis of correlation in 2D.
`sI_N` denotes window over which to look for maximum correlation
"""
if C.dims == ("x", "y"):
Nx, Ny = C.shape
else:
Ny, Nx = C.shape
x_ = C.coords["x"]
y... | 31640a026e2debdd85fbf8a973068e64ffa7d79e | 36,219 |
def _jupyter_nbextension_paths():
"""Called by Jupyter Notebook Server to detect if it is a valid nbextension and
to install the widget
Returns
=======
section: The section of the Jupyter Notebook Server to change.
Must be 'notebook' for widget extensions
src: Source directory name to c... | 36443750811019e41d5dd74417d3049bc8af24ac | 36,220 |
from datetime import datetime
def ssl_valid_time_remaining(hostname: str) -> datetime.timedelta:
"""Get the number of days left in a cert's lifetime."""
expires = ssl_expiry_datetime(hostname)
return expires - datetime.datetime.utcnow() | 40c2d9c800e6703dd40e6f76d548895a7ae461f0 | 36,221 |
def absolute_import_try(space, modulename, baselevel, fromlist_w):
""" Only look up sys.modules, not actually try to load anything
"""
w_path = None
last_dot = 0
if '.' not in modulename:
w_mod = check_sys_modules_w(space, modulename)
first = w_mod
if fromlist_w is not None a... | fae9d7accef009f81b28a8da221da5ebdd16b9e1 | 36,222 |
def get_engine():
"""Return engine singleton"""
global _engine
if _engine is None:
_engine = create_engine(_connection_string)
return _engine | 16981b51a62257d45793b3201213ee7597e20849 | 36,223 |
def CreateTestAdUnit(client, server, version):
"""Create a test ad unit.
Args:
client: DfpClient used for service creation.
server: str the API server.
version: str the API version.
Returns:
The ID of the ad unit.
"""
inventory_service = client.GetService('InventoryService', server, version)... | 76bc6cde3a1c9ed06f19f38d7d6e9a8834e8c5b0 | 36,224 |
def _cache_deserialize(func):
"""Simple caching decorator"""
def cache_decorator(self, *args, **kwargs):
if self._deserialization_done:
return self._deserialization_result
self._deserialization_result = func(self, *args, **kwargs)
self._deserialization_done = ... | 787e4cc382f08bffc00c6811cae8272d8d759b0f | 36,225 |
def correct_directory_path(directory_path):
"""
Attempts to convert the directory path to a proper one by removing
any double slashes next to one another.
Args:
directory_path:
String of a potential directory path.
Returns:
Returns the fixed path.
"""
l... | b403ebaa93765a7df4e6033f5bc5f924f2fe312a | 36,226 |
def fused_laplacian_pyramid(gauss_pyramid_mod1, gauss_pyramid_mod2, lap_pyramid_mod1, lap_pyramid_mod2):
"""
A funtion that builds a fused Laplacian pyramid of two modalities of the same image
:param gauss_pyramid_mod1: The Gaussian pyramid of modality 1, a list of grayscale images, the first one in highes... | 59f600de9a56587146efe46692754d4f757e3645 | 36,227 |
def ascend(x):
"""True if vector x is monotonically ascendent, false otherwise
Recommended usage:
if not ascend(x): sort(x)
"""
return alltrue(greater_equal(x[1:],x[0:-1])) | ae7e8cbe1f889da56a6c228586d43b4bfbd713bd | 36,229 |
def read_cdf_forecast_group(forecast_id):
"""Read CDF Group Forecast metadata.
Parameters
----------
forecast_id: String
UUID of the forecast to retrieve.
Returns
-------
dict
The CDF Forecast's metadata or None if the Forecast
does not exist.
"""
forecast =... | 16763337eb828d255d3e036d0cf926ab5478bdf2 | 36,230 |
from typing import Callable
from typing import Tuple
def integrate(t_0: TimeSpan,
x_0: Matrix,
h: TimeSpan,
dynamics_func: Callable[[TimeSpan, Matrix], Matrix]
) -> Tuple[TimeSpan, Matrix, TimeSpan]:
""" Function utilizes a 4th-order Runge-Kutta integration ... | 1fa8e20b7658e73bb3786f0c5eb1922593a5c604 | 36,231 |
def increase(value):
"""Test template tag that returns an increased value."""
return value + 1 | 41e4a7efd8541bcadf1f2e4224cb3dc170dfb50b | 36,232 |
import cpuinfo
def get_processor():
"""Docstring.
Returns:
TYPE: Description
"""
try:
info = cpuinfo.get_cpu_info()
data = {
"bits": get_value(info, 'bits'),
"count": get_value(info, 'count'),
"brand": get_value(info, 'brand'),
"... | 38386d04174858227a8a4583b396f58d9b9a52a7 | 36,233 |
def get_module_registry_dependencies(
pkg_names, registry_key='calmjs.module', working_set=None):
"""
For the given packages 'pkg_names' and the registry identified by
'registry_key', resolve the exported location for just the package.
"""
working_set = working_set or default_working_set
... | e2f3f86f138dded55bd9cc8a6b7c75de10abf8f9 | 36,234 |
def get_contour(rad,thresh):
"""
Find the edge in the input radiograph.
Parameters:
rad (numpy.ndarray): Radiograph of a sharp edge sample
thresh (float): The value at which a iso-valued contour (contour is the edge) is drawn
Returns:
numpy.ndarray: Coordinates along the longes... | 1a306e1941c0e60cf4231dcc451f33ce5653ee6b | 36,235 |
from typing import Type
def _mp_message_dialog(
monkeypatch: MonkeyPatch,
method: str = "warning",
return_value: QMessageBox.StandardButton | None = None,
mock_class: Type[QMessageBox] = QMessageBox,
) -> CallList:
"""Mock a QMessageDialog and return a list with the call's arguments."""
return... | 37b228375d96aeea365b27b566c2d5eb3b333756 | 36,236 |
def dominant_wavelength(xy, xy_n, cmfs=None, inverse=False):
"""
Returns the *dominant wavelength* :math:`\\lambda_d` for given colour
stimulus :math:`xy` and the related :math:`xy_wl` first and :math:`xy_{cw}`
second intersection coordinates with the spectral locus.
In the eventuality where the :m... | fdb723b3ea835bf8e237e82249d93083340963e5 | 36,237 |
def getIconAsQPixmap(name: str, scale: int = None) -> QtGui.QPixmap:
"""Retrive a icon image as a QPixmap
:param name: the icon filename
:type name: str
:param scale: the desired size to apply to the icon (squared size), defaults to None
:type scale: int, optional
:return: the icon as a QPixmap
:rtype: QtGui.QP... | 0030426e304c90059492c1348e3752230aad5ec5 | 36,238 |
from typing import Any
from typing import Tuple
from typing import Dict
def validate_arguments(selected_args: params.SelectedAnalysisOptions, validate_extra_args_func: Any = None) -> Tuple[params.SelectedAnalysisOptions, Dict[str, Any]]:
""" Validate arguments passed to the analysis task. Converts str and float t... | b719e1da3abe312d880fbc5e8dafd36d5aa0abd5 | 36,241 |
def post_processing(results, bar_boxes, cluster_idx):
"""Post process identified barcode regions, combine overlapping or adjacent areas."""
combined = combine_overlapping_areas(results, cluster_idx)
filtered = []
for rect in combined:
# Barcode should be a horizontal series of bars, not a a ver... | 8c363a4a2aa79f6e464f0517ca6597e5ff5741db | 36,242 |
def kl_with_logits(p_logits, q_logits, scope=None,
loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES):
"""Helper function to compute kl-divergence KL(p || q)
"""
with tf.name_scope(scope, "kl_divergence") as name:
p = tf.nn.softmax(p_logits)
p_log = tf.nn.log_softmax(p_logits)
q_lo... | 5a7c7f7761e9215e48d7dee56a098d24285a013c | 36,243 |
import numpy
def _total_exposure_op(habitat_arr, *num_denom_list):
"""Calculate the exposure score for a habitat layer from all stressors.
Add up all the numerators and denominators respectively, then divide
the total numerator by the total denominator on habitat pixels, to get
the final exposure or ... | d00be0ad20aebb213d67a2fb4e0d529dca063ea9 | 36,244 |
def _check_axis_valid(axes, ndim):
"""
Checks axes are valid given ndim, and returns axes that can be passed
to the built-in operator (non-negative, int or tuple)
"""
if axes is None:
axes = F.make_range(ndim)
return axes
if isinstance(axes, (tuple, list)):
axes = tuple(m... | 2dc4df51ffca9b1f1c2194ad0a390fd42d0c95d1 | 36,245 |
def _create_cigale_in(photom_cat:Table, zmin:float = 0.01, zmax:float=0.35, n_z:int = 35, cigale_input:str = "cigin_minz_zfrb.fits")->Table:
"""
Take the photometry table and
create a new table with redshifts.
For each galaxy, create multiple entries
with different redshifts from 0 to 2.
These r... | ba5fec9a702aae3f9791f4fa571cbad08acdc0eb | 36,247 |
def get_corrections(time_from=None, time_to=None, source=None):
"""
:return:
"""
corrections = session.query(Correction).filter(Correction.rolled_back == False)
if time_from is not None:
corrections.filter(Correction.date > time_from)
if time_to is not None:
corrections.filter(C... | e7f42a78a24943814c96acdcd91bcba0591b3940 | 36,248 |
def regression_loss(predicty, ylabel, weight_map=None):
"""
Distance regression loss
:param predicty: prediction results
:param ylabel: ground truth
:return: regression loss
"""
loss = l2_loss(predicty, ylabel, weight_map)
return loss | 4e76acf1405ae80eb4e80ebec202ab936fe2ff14 | 36,249 |
def get_required_distance(W, sigma_det, wav):
"""
Calculate the propagation distance required to satisfy sampling conditions.
:param W: approximate feature size [m]
:param sigma_det: propagated plane (detector) pixel size [m]
:param wav: source wavelength [m]
:returns zreq: required distance ... | 400dfe3279a4d2a16be8494e5404b25d1d42ef56 | 36,250 |
def add_user_to_license(
requesting_user: User, license_object: License, user: User
) -> LicenseUser:
"""
Adds a user to the provided license.
:param requesting_user: The user on whose behalf the user is added to the license.
:param license_object: The license that the user must be added to.
:p... | 97a5c211ac93d84b2d5e55c3ebf3b314f2fde8c8 | 36,251 |
def subfolders_in(whole_path):
"""
Returns all subfolders in a path, in order
>>> subfolders_in('/')
['/']
>>> subfolders_in('/this/is/a/path')
['/this', '/this/is', '/this/is/a', '/this/is/a/path']
>>> subfolders_in('this/is/a/path')
['this', 'this/is', 'this/is/a', 'this/is/a/path']... | a7389811a8acacea87abd55ba47892203e0b95e5 | 36,252 |
def getall(current_user):
""" endpoint to fetch all meetups """
all_meetups = MEETUPS.getall_meetups()
if all_meetups:
return make_response(jsonify({
"message": "Success",
"meetups": all_meetups
}), 200)
return make_response(jsonify({'message': 'Meetup not found'... | 9852ba431031a87409f1a34d1ec0e27e19697da5 | 36,253 |
import random
def initSetGenotype(possible_values: list):
"""
Function to initialise the genotype of individuals represented as a Set from a list of possible
values.
Parameters
----------
possible_values: list
List of possible values to insert into the individual.
Returns
---... | 2500ccb0a33925d65805379804a1d307475118d7 | 36,256 |
def logout(request):
"""
Logout request
:param request:
:return:
"""
auth.logout(request)
return render_to_response("logout.html") | bfeb1c8b38bef3b72bcffb920f9329328ff5f4b3 | 36,257 |
from typing import Mapping
def get_actual(db: Connection) -> Mapping[str, Event]:
"""
Get actual channel values.
"""
return {key: Event(**value) for key, value in db[ACTUAL_KEY].items()} | bf044c83c4a1591a846d5002424d0e7e06e5dedd | 36,259 |
def get_filter_set_field_tuples(filter_set):
"""Return a list of tuples of filter set filter names and values.
This is used together with above `join_filter_set_field_values` to create
a table of filters used in an analysis view.
NOTE:
- This function and `join_filter_set_field_values` are kept se... | 928b313227972ed855aa6944f72f333fde10862a | 36,260 |
def getInnerText(node):
"""
Get all the inner text of a DOM node (recursively).
"""
# inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html
inner_text = []
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NO... | a3d83fe008339e61d213b6b8d78b0882ff7cec05 | 36,261 |
def solve(s, minint=-20, maxint=20, threads=8, options=()):
"""
Return the (optimal) models/assignments of the program in the given string.
"""
solver = Solver(minint, maxint, threads, options)
ret = _solve(solver, s)
has_minimize = solver.prp.has_minimize
for conf in CONF_GLOBAL:
... | aa67249e308994324f27d38ec5b505be1bca8542 | 36,263 |
from typing import DefaultDict
def create_report(result: DefaultDict) -> str:
"""
Creates the report
:param result: results instance
:param output: output string
:return:
"""
fpoint = 10
report = f"""
Analyse-Report Version 0.1
\n{"-" * 60}\n"""
if "combined" in result.keys... | fd377cad5d959fa904004660256487b0c9914c26 | 36,265 |
def np_masked_softmax(logits, legal_actions_mask):
"""Returns the softmax over the valid actions defined by `legal_actions_mask`.
Args:
logits: A tensor [..., num_actions] (e.g. [num_actions] or [B, num_actions])
representing the logits to mask.
legal_actions_mask: The legal action mask, same shape a... | 40635ac5d34984d7e11c71afc26ec3a603aaf19a | 36,267 |
def get_example1_pandas():
"""First example with no missing values, A and D are declared categoricals,
while B is also categorical but not declared as such, one which is
obviously categorical and two continuous
"""
df = pd.DataFrame(
{
"A": [0, 1, 1, 1, 0, 0, 0, 0, 1],
... | e635f3bf7afd65df95774442a58c21e279e55c2b | 36,268 |
def wpet_unit(out):
"""wpe * tの単位変換器を生成する.
以下のコードを実行することで、データのt軸をwpe*tで規格化できる.
>>> Emout.name2unit['t'] = wpet_unit
Parameters
----------
out : Emout
Emoutオブジェクト
Returns
-------
UnitTranslator
wpe * tの単位変換器
"""
return UnitTranslator(
out.inp.wp[0] ... | 57545c94c859f5ad0177fbd4d8cd9365862cae57 | 36,269 |
def buttons_click(dx, dy, key):
"""Проверяет, какая клавиша была нажата.
При нажатии опредленных клавиш меняются скорость, а также ращрешение, какую кнопку нажать
dx, dy -- изменение координат змейки
key -- параметр запускающий метод pygame для читания нажатых клавиш
return: измененные в соотвеств... | 5996b45576177a8b4ab6d3c0e9665fdfae8bdbed | 36,270 |
def listing(output_lines):
"""Return list of dicts with basic item info parsed from cli output."""
items = []
table_ = multi_line_row_table(output_lines)
for row in table_['values']:
item = {}
for col_idx, col_key in enumerate(table_['headers']):
item[col_key] = row[col_idx]... | f5bc061a2de174bfedfaef7b0020dabe614f96c3 | 36,272 |
def extract_network_from_shapefile(edge_shapefile_df, node_shapefile_df):
"""
Extracts network data into DataFrames for pipes and nodes in the network
:param edge_shapefile_df: DataFrame containing all data imported from the edge shapefile
:param node_shapefile_df: DataFrame containing all data importe... | fbe05d89e50f5352dd9531b485c519e66ec5e1b1 | 36,273 |
from typing import Dict
from typing import Union
def MPC_SetupFindFieldStrength(expected_voltage: float) \
-> Dict[str, Union[float, int]]:
"""Reaches Vov by adjusting RF field strength
Parameters
----------
expected_voltage : float
Vdc value to reach in V
Returns
-------
... | e253a9ae14c6458535f25637af4a927edd15a6d5 | 36,274 |
def classifier_sklearn(X_train, X_test, y, classifier_name, params):
"""
:param X_train:
:param X_test:
:param y:
:param classifier_name: class must be imported at top of the file, for config use class name only
:param params:
:return:
"""
n_classes = np.unique(y).shape[0]
class... | 0cb1635a608a4fadec5fdb860fb57fdc82249adb | 36,275 |
import string
import random
def string_generator(size=6, chars=string.ascii_letters):
"""Generator string based on the parameters passed.
@param size: Size limit of string. Default: 6
@param chars: string.ascii_letters Default: 200 - Use the constant string class
"""
return ''.join(random.choice(... | 696d6b9219f41dbdda7226d6571f2b89b344774b | 36,276 |
def compileFinalNgramCounts(final_ngrams,compiled_final_station_ngrams,station_ngrams):
"""Join the final_ngrams in station_ngrams to compiled_final_station_ngrams"""
for (station, ngrams) in station_ngrams.viewitems():
thisstation_finalngrams = \
compiled_final_station_ngrams.get(station,(d... | e0caddef19d007d8b96fa04de3898a998a7b8c05 | 36,277 |
def inference(model, X):
""" Run model inferences and return the predictions.
Inputs
------
model : catboost.CatBoostClassifier
Trained machine learning model.
X : np.array
Data used for prediction.
Returns
-------
preds : np.array
Predictions from the model.
... | cbcfc6c6c7088162b4798194e4a2759f0d52ac13 | 36,278 |
def readPars(fileName, var_Ze="Ze", var_time="time", var_vmean="vmean", var_dmean="dmean", var_rr="rr", **kwargs):
""" This function reads the parsivel netCDF files and
extracts the desired variables.
Arguments
---------
fileName of the .nc parsivel data file
var_Ze: va... | a7adf91108f83c4335260e5f0e0d9918d39c7f7a | 36,280 |
def fib_iter(n):
"""[summary]
Works iterative approximate O(n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be positive integer'
fib_1 = 0
fib_2 = 1
res = 0
if n <= 1:
return n
... | 1b6529eee7461ff16cedde1ab4c8bde2653ea2ee | 36,281 |
from typing import Sequence
from typing import Tuple
from typing import Any
def split(values: Sequence[TItem], split_count: int) -> Tuple[Any, ...]:
"""
Returns the split ``values`` in ``split_count`` pieces in protocol.
Spec: https://github.com/ethereum/eth2.0-specs/blob/70cef14a08de70e7bd0455d75cf380eb6... | 83777c7025a1d55964a40ccaa56f7bc4b7f4c463 | 36,282 |
def BalanceOf(account):
"""
Method to return the current balance of an address
:param account: the account address to retrieve the balance for
:type account: bytearray
:return: the current balance of an address
:rtype: int
"""
context = GetContext()
balance = Get(context, account)... | f011f757c44f196e12707a538167cfd19e5af4b2 | 36,283 |
def all_downloadable_sfs_files(session):
"""
Gets all files managed in Snapchat FS for a specific user; returns
them as a list of Snap objects, whose IDs can be used to download
all or some of the files from Snapchat's DB.
@session An SfsSession object that has been logged in.
@return List ... | 3f1c9863c4aa6cc7d18a54d5a6255b29e0c72142 | 36,284 |
def overlaps_graph(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
"""
# 1. Tile boxes2 and repeat boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
# TF doesn't have an equivalent to np.repeat() so si... | a8ac2ba8c86f5948a40bf24e8f732c6b57c28a4e | 36,285 |
def friendly_number(num):
""" Convert a base 10 number to a base X string.
Charcters from VALID_CHARS are chosen, to convert the number
to eg base 24, if there are 24 characters to choose from.
Use valid chars to choose characters that are friendly, avoiding
ones that could be confu... | 815731df20009d5fb3c71e8e5de3307ece801941 | 36,286 |
import time
def create_c2_opt(optimizer_config, eval_func_path):
"""
Create a C2 Calibration object. Can be used to simulate the calibration process, if
the eval_func_path contains a ''real'' experiment.
Parameters
----------
optimizer_config : str
File path to a hjson configuration f... | d0ad6ebdb5df8461ffcefb50347c4d8bb3195b9a | 36,288 |
def pick_model(data):
"""Picks the models depending on the provided configuration flags."""
# Create model classification.
if FLAGS.model_cls == 'mlp':
hidden_classif = (parse_layers_string(FLAGS.hidden_cls)
if FLAGS.hidden_cls is not None else [])
model_cls = MLP(
output_dim... | 867d02fe1eb3b9b9447465ea76c8785f2d22d897 | 36,289 |
def pytest_funcarg__tracker_config(request):
"""
The tracker configuration as ``TrackerConfig`` object, or ``None``, if
there is no tracker configuration.
Tracker configuration is taken from the class this test is defined in. If
there is a ``testname`` for this test, the tracker config is taken fr... | 8591a59b4f825ba7f7a034959a8c4ffe7a241013 | 36,290 |
def send_verify_code(phone_num):
"""发送验证码逻辑
:params phone_num: 手机号码
:return:
"""
code = utils.gen_rendom_code(6)
#生成验证码
sms.send_verify_code(phone_num, code)
#发送验证码
return True | 94027f52bce7987eac24a1084e2d3e5b2f5a8e27 | 36,291 |
def api_index():
"""List available endpoints
"""
url_rules = [r.rule for r in current_app.url_map.iter_rules()]
return ApiResponse({'endpoints': sorted(list(set(url_rules)))}) | fd0217357effd563fd0813a4b38d6661f1fe3bd5 | 36,292 |
def get_available_formats():
"""List the formats you can use in self.getFormat in a comma separated list (string)"""
ret = ""
for formats in IRC_FORMATTING_DICT:
ret += formats + ", "
return ret[:-2] | 00b18147f81905e0f9c884039bed23bc1dee3a9e | 36,293 |
def min_os_level(release):
"""
Usage::
class Tests (unittest.TestCase):
@min_os_level('10.6')
def testSnowLeopardCode(self):
pass
"""
return onlyIf(
os_level_key(os_release()) >= os_level_key(release),
f"Requires OSX {release} or later",
... | fe453776e844fa3b1507b53778f33c653a5b7ab1 | 36,294 |
from keras.models import Model
from keras.layers import Input
from keras.layers import Conv2D, MaxPool2D
from keras.layers import UpSampling2D, Reshape, concatenate
def UNet(dim=512, num_classes=12):
"""
Standard U-Net architecture for segmentation
"""
input = Input(shape=(None, None, 3))
# Do... | 4bdfb486371def10886125b25b46b23bf77097f6 | 36,295 |
import logging
def _PreprocessExactUsers(
cnxn, cond, user_service, id_fields, is_member):
"""Preprocess a foo=emails cond into foo_id=IDs, if exact user match.
This preprocesing step converts string conditions to int ID conditions.
E.g., [owner=email] to [owner_id=ID]. It only does it in cases
where (a... | 87246ca8aa1b1d2fafa385000c08f93f64586833 | 36,296 |
from datetime import datetime
from operator import le
def UploadForecastFromExcel():
"""Interface Package Description"""
interface = {
"FileName" : str,
"SheetName" : str,
"ForecastName" : str,
"ForecastYear" : str,
"GFO" : bool,
"InterpolationMethod" : ['MonthlyVolumes', 'MonthlyRates... | aa480d6437f9e61d65f4e0a715a815b4c2c98c18 | 36,298 |
import random
def random_matrix(width: int, height: int, a: int, b: int) -> Matrix:
"""
returns a random matrix WxH with integer components
between 'a' and 'b'
"""
random.seed(None)
matrix: list[list[float]] = [
[random.randint(a, b) for _ in range(width)] for _ in range(height)
]
... | 6653ddf88b3c88ff656584ca25e6c4ee87548c2f | 36,299 |
import json
def show_quick_pick(items: list, options: QuickPickOptions = None) -> QuickPickItem:
"""
Shows a selection list allowing multiple selections.
Returns either the selected items or undefined.
"""
data = []
for item in items:
if isinstance(item, QuickPickItem):
da... | d30c376ea97c35b23ae43fd03ad2fb26eb7a4c9b | 36,300 |
def merge(nums1, m: int, nums2, n) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
if len(nums1) >= m + n:
for num in nums2:
nums1[m] = num
m += 1
nums1.sort()
return nums1 | 2c2e372e05b71981cab4796f62116e72e278c352 | 36,301 |
def create_sample_user(**params):
"""Creates sample user"""
return get_user_model().objects.create_user(**params) | 7e9ce097d699b1eb7b94916998d628c10f943935 | 36,302 |
from typing import Optional
from typing import Tuple
import torch
def subset_model(
model: Model,
objective_weights: Tensor,
outcome_constraints: Optional[Tuple[Tensor, Tensor]] = None,
objective_thresholds: Optional[Tensor] = None,
) -> SubsetModelData:
"""Subset a botorch model to the outputs us... | cd220d39282f89b2abdca87a5b0b8e3a9ea08c8e | 36,303 |
def relu_derivative(dA, Z):
"""
Implement the backward propagation for a single RELU unit.
Arguments:
dA -- post-activation gradient, of any shape
cache -- 'Z' where we store for computing backward propagation efficiently
Returns:
dZ -- Gradient of the cost with respect to Z
"""
... | 8102fda6fbf03c01ff1ba2692faa7f8d918f011c | 36,304 |
def compute_coupled_cell(f1,f2) :
"""
Computes the full-sky angular power spectra of two masked fields (f1 and f2) without aiming to deconvolve the mode-coupling matrix. Effectively, this is equivalent to calling the usual HEALPix anafast routine on the masked and contaminant-cleaned maps.
:param NmtField ... | 4ea78e0f2f330a42cd1e47f6684901ce87c3ac1c | 36,305 |
def get_dates(time):
"""Obtain pandas datetime objects from date objects.
Sometimes there are problems with 360 days calendars and cftime
units in pandas. This function uses `dates_from_360cal` to
circumvent this problem when pandas can't be used directly to
generate a DatetimeIndex.
Param... | ab20f97b835edfb3e49196646529f6ebe80025d5 | 36,306 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.