content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def fixture_mock_aircon_api_instances(mock_aircon1_api, mock_aircon2_api):
"""Set up air conditioner API fixture."""
with mock.patch(
"homeassistant.components.whirlpool.climate.Aircon"
) as mock_aircon_api:
mock_aircon_api.side_effect = [mock_aircon1_api, mock_aircon2_api]
yield moc... | 5,320,700 |
def test_names_are_not_abbreviated(client):
"""
Based on https://github.com/EuroPython/epcon/issues/778
"""
conference = Conference.objects.create(
code=settings.CONFERENCE_CONFERENCE,
name=settings.CONFERENCE_CONFERENCE
)
user = auth_factories.UserFactory(email='joedoe@example... | 5,320,701 |
def once(f):
"""
Return a function that will be called only once, and it's result cached.
"""
cached = None
@wraps(f)
def wraped():
nonlocal cached
if cached is None:
cached = Some(f())
return cached.val
return wraped | 5,320,702 |
def from_greatfet_error(error_number):
"""
Returns the error class appropriate for the given GreatFET error.
"""
error_class = GREATFET_ERRORS.get(error_number, GreatFETError)
message = "Error {}".format(error_number)
return error_class(message) | 5,320,703 |
def compute_all_distances_to_nucleus_centroid3d(heightmap: np.ndarray, nucleus_centroid: np.ndarray,
image_width=None, image_height=None) -> np.ndarray:
"""
Compute distances within the cytoplasm between all points and nucleus_centroid in a
IMAGE_WIDTH x IMAGE... | 5,320,704 |
def strip_md_links(md):
"""strip markdown links from markdown text md
Args:
md: str, markdown text
Returns:
str with markdown links removed
Note: This uses a very basic regex that likely fails on all sorts of edge cases
but works for the links in the osxphotos docs
""... | 5,320,705 |
def tf_distort_color(image):
""" Distorts color. """
image = image / 255.0
image = image[:, :, ::-1]
brightness_max_delta = 16. / 255.
color_ordering = tf.random.uniform([], maxval=5, dtype=tf.int32)
if tf.equal(color_ordering, 0):
image = tf.image.random_brightness(image, max_delta=b... | 5,320,706 |
def run_and_read_cplex(n, problem_fn, solution_fn, solver_logfile,
solver_options, warmstart=None, store_basis=True):
"""
Solving function. Reads the linear problem file and passes it to the cplex
solver. If the solution is successful it returns variable solutions and
constraint ... | 5,320,707 |
def deharmonize(audio_data, sfreq, shift, high=False,
audio_min_freq=200.0, decompose="none"):
"""Deharmonize audio data using full signal FFT
Args:
audio_data(numpy.ndarray): Audio data in a NumPy array
sfreq(float): Sampling frequency in Hz
shift(float): Linear shift i... | 5,320,708 |
def get_max_sushi(m, features, combs, rank_dict):
"""
Specifically for DTS
:param model: gpflow model
:param features: sushi features
:param rank_dict: dictionary from sushi idx to place in ranking
:return: tuple (index of max sushi, rank)
"""
y_vals = m.predict_y(combs)[0]
num_discr... | 5,320,709 |
def get_multi_media(shelter_id=0, category_id=2, section = 'Identification'):
"""
Get pictures for the shelter sent by Dropzone via a POST
request.
"""
first = True
ImageFile.LOAD_TRUNCATED_IMAGES = True
imgwidth = 1280
shelter = Shelter.query.filter(Shelter.id==shelter_id).fi... | 5,320,710 |
def is_watchman_supported():
""" Return ``True`` if watchman is available."""
if WIN:
# for now we aren't bothering with windows sockets
return False
try:
sockpath = get_watchman_sockpath()
return bool(sockpath)
except Exception:
return False | 5,320,711 |
def geolocation(data_base, year, latitude, longitude, geofunc):
"""
Function for geolocating points from database and calculating distance from them to
the given user point.
>>> 33.5 <= geolocation(pd.DataFrame([["Film1", 2020, "Some info",\
"Los Angeles California USA"]], columns \
= ["name",... | 5,320,712 |
async def test_state_update(hass):
"""Test all sensors are updated accordingly to data."""
assert await _setup(hass)
assert len(hass.states.async_entity_ids()) == 3
assert hass.states.is_state('sensor.vaillant_boiler_pressure', '1.4')
assert hass.states.is_state('sensor.vaillant_boiler_temperature'... | 5,320,713 |
def get_clip_details(file_path: str) -> (int, float, int, int):
"""
Gets a clip's duration, frame rate and dimensions (width, height).
:param file_path: The absolute path to a clip.
:return: Duration in seconds, frame rate in FPS and width and height in pixels.
This is given in the form of... | 5,320,714 |
def notebook(live_mock_server, test_dir):
"""This launches a live server, configures a notebook to use it, and enables
devs to execute arbitrary cells. See tests/test_notebooks.py
"""
@contextmanager
def notebook_loader(nb_path, kernel_name="wandb_python", save_code=True, **kwargs):
with o... | 5,320,715 |
def read_dig_polhemus_isotrak(fname, ch_names=None, unit='m'):
"""Read Polhemus digitizer data from a file.
Parameters
----------
fname : str
The filepath of Polhemus ISOTrak formatted file.
File extension is expected to be '.hsp', '.elp' or '.eeg'.
ch_names : None | list of str
... | 5,320,716 |
def gt_comparison_plot(data, mu=None, sig=None, k=3.3e11, x_c = None):
"""
Generate the comparison Zipf plot for the data.
Parameters
----------
data : array_like
Size of each firm, where size is measured by sales, value added,
number of employees or some other variable.
k : f... | 5,320,717 |
def make_cache_key(instance):
"""Construct a cache key for the instance."""
prefix = '{}:{}:{}'.format(
instance._meta.app_label,
instance._meta.model_name,
instance.pk
)
return '{}:{}'.format(prefix, str(uuid4())) | 5,320,718 |
def load_model(filename: str, model_dir=config.MODEL_DIR) -> nn.Module:
"""
Load the model from a pickle.
:param filename: name of the file
:param model_dir: directory in which the file is located
:return:
"""
with open(os.path.join(model_dir, filename), 'rb') as f:
return pickle.loa... | 5,320,719 |
def phase_comparison(phase_ref, phases, step,cmap = None, set_limit = False, facecolor='r'):
"""
..py::function::
This function calculates difference of the phases trajectories in relation to
a reference phase trajectory.
:param phase_ref: Phase trajectory reference
:type phase_ref: nump... | 5,320,720 |
def CalculateMediationPEEffect(PointEstimate2, PointEstimate3):
"""Calculate derived effects from simple mediation model.
Given parameter estimates from a simple mediation model,
calculate the indirect effect, the total effect and the indirect effects
Parameters
----------
PointEstimate2 : ... | 5,320,721 |
def get_engine(db_dir_name, echo=False, path_str=None):
"""数据库引擎"""
if path_str:
path = path_str
else:
path = db_path(db_dir_name)
engine = create_engine('sqlite:///' + path, echo=echo)
return engine | 5,320,722 |
def init_websauna(config_uri: str, sanity_check: bool=False, console_app=False, extra_options=None) -> Request:
"""Initialize Websauna WSGI application for a command line oriented script.
:param config_uri: Path to config INI file
:param sanity_check: Perform database sanity check on start
:param con... | 5,320,723 |
def ts_glm_ridge_pipeline():
"""
Return pipeline with the following structure:
glm \
-> ridge -> final forecast
lagged - ridge /
Where glm - Generalized linear model
"""
node_glm = PrimaryNode("glm")
node_lagged = PrimaryNode("lagged")
node_ridge_1 = S... | 5,320,724 |
def remove(obj):
"""Remove a GraphicObject from the document"""
if (obj.parent):
obj.parent.children.remove(obj) | 5,320,725 |
def read_validation_annotations(validation_dir):
"""Reads validation data annotations."""
return read_tiny_imagenet_annotations(
os.path.join(validation_dir, 'val_annotations.txt'),
os.path.join(validation_dir, 'images')) | 5,320,726 |
def add_section(data, label, icon, items):
"""Adds a section to the module data."""
if not items: return
data.append({
"label": label,
"icon": icon,
"items": items
}) | 5,320,727 |
def ListBlob(bucket, blob):
"""Lists all buckets."""
credentials = service_account.Credentials.from_service_account_file(
'./digitalcore-poc-67645bca1a2a.json')
storage_client = storage.Client()
buckets = storage_client.list_buckets()
for bucket in buckets:
print(bucket.name)
b... | 5,320,728 |
def norm1to1(operator, n_samples=10000, mxBasis="gm", return_list=False):
"""
Returns the Hermitian 1-to-1 norm of a superoperator represented in
the standard basis, calculated via Monte-Carlo sampling. Definition
of Hermitian 1-to-1 norm can be found in arxiv:1109.6887.
"""
if mxBasis == 'gm':
... | 5,320,729 |
def test_ordinance_company_wrapper(current_test_orgs):
"""Test setting ordinance data for a company network."""
OFFICER_0_ID = "kk4hteZw_nx0lRsy5-qJAra1OlU"
for organisation in current_test_orgs:
if organisation.company_id != PUNCHDRUNK_COMPANY_ID:
organisation._skip_company = True
c... | 5,320,730 |
def _load_image_gdal(image_path, value_scale=1.0):
""" using gdal to read image, especially for remote sensing multi-spectral images
:param image_path: string, image path
:param value_scale: float, default 1.0. the data array will divided by the 'value_scale'
:return: array of shape (height, width, ban... | 5,320,731 |
def my_keyword(self):
"""Does nothing."""
pass | 5,320,732 |
def f1_chantler(element, energy, _larch=None, **kws):
"""returns real part of anomalous x-ray scattering factor for
a selected element and input energy (or array of energies) in eV.
Data is from the Chantler tables.
Values returned are in units of electrons
arguments
---------
element: at... | 5,320,733 |
def rgb_to_hex(red_component=None, green_component=None, blue_component=None):
"""Return color as #rrggbb for the given color tuple or component
values. Can be called as
TUPLE VERSION:
rgb_to_hex(COLORS['white']) or rgb_to_hex((128, 63, 96))
COMPONENT VERSION
rgb_to_hex(64, 183, 22)
... | 5,320,734 |
def test_beps_solver_bloch_ground_state(freq: float):
"""Verify solver results when we use Bloch states."""
hamiltonian = HTHamiltonian(
freq=freq, interaction_strength=INTERACTION_STRENGTH
)
trap_size = hamiltonian.trap_size
mesh = Mesh(
lower_bound=-8 * trap_size, upper_bound=8 * t... | 5,320,735 |
def draw_bbox_inplace(image, bbox, label, color):
"""
----------
Author: Damon Gwinn (gwinndr)
----------
- Draws the given bbox on the image in_place (image is not copied first)
- bbox should be an integer list-like in the format (x1 y1 x2 y2)
- See BBOX DRAWING in constants.py for tweaking... | 5,320,736 |
def main(argv):
"""This is a template that includes OptionParser-style arguments."""
description = """This is a template that includes
argparse.ArgumentParser-style arguments in all their various forms."""
formatter = lambda prog: \
argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position... | 5,320,737 |
def check_array_indexer(
array: geopandas.array.GeometryArray,
indexer: pandas.core.arrays.boolean.BooleanArray,
):
"""
usage.geopandas: 2
"""
... | 5,320,738 |
def remove(predicate, seq):
""" Return those items of sequence for which predicate(item) is False
>>> def iseven(x):
... return x % 2 == 0
>>> list(remove(iseven, [1, 2, 3, 4]))
[1, 3]
"""
return filterfalse(predicate, seq) | 5,320,739 |
def test_sync_canary(scenario):
"""
The purpose of this test is to run the tap with all streams
selected to naively exercise all code and any changes to those
streams.
This is certainly not comprehensive, and assumes that all
streams have data, but is generally enough to provide some
value.... | 5,320,740 |
def average_coords(coords_list):
"""Calculate average coords
Parameters
----------
coords_list : list[skrobot.coordinates.Coordinates]
Returns
-------
coords_average : skrobot.coordinates.Coordinates
"""
q_list = [c.quaternion for c in coords_list]
q_average = averageQuaternion... | 5,320,741 |
def plotPanelScreenshot(panel, filename):
"""Capture a screenshot of the contents of the given :class:`.PlotPanel`
or :class:`.PlotPanel`, saving it to the given ``filename``.
"""
if isinstance(panel, plotpanel.PlotPanel):
figure = panel.canvas.figure
elif isinstance(panel, plotcanvas.PlotCa... | 5,320,742 |
def lowpassfilter(input_vect, width=101):
"""
Computes a low-pass filter of an input vector.
This is done while properly handling NaN values, but at the same time
being reasonably fast.
Algorithm:
provide an input vector of an arbitrary length and compute a running NaN
median over a box o... | 5,320,743 |
def test_check_conda_installation_pacakge_no_installed():
"""
Test check conda instllation function correclty identifies that a data pacakges is not installed by conda
"""
pytest_enable_socket()
recipe = "Fake-hg19-gaps"
version = "1"
assert install.check_conda_installation(recipe,version)... | 5,320,744 |
def n_keywords(data):
"""Return the number of keywords.
Arguments
---------
data: asreview.data.ASReviewData
An ASReviewData object with the records.
Return
------
int:
The statistic
"""
if data.keywords is None:
return None
return np.average([len(keywor... | 5,320,745 |
def flatten_reshape(variable, name=''):
"""Reshapes high-dimension input to a vector.
[batch_size, mask_row, mask_col, n_mask] ---> [batch_size, mask_row * mask_col * n_mask]
Parameters
----------
variable : a tensorflow variable
name : a string or None
An optional name to attach to thi... | 5,320,746 |
def global_install() -> None:
"""Install mathlib user-wide."""
proj = LeanProject.user_wide(cache_url, force_download)
proj.add_mathlib() | 5,320,747 |
def register_command(data):
"""Remote command registration service.
This has to be enabled by liquer.commands.enable_remote_registration()
WARNING: Remote command registration allows to deploy arbitrary python code on LiQuer server,
therefore it is a HUGE SECURITY RISK and it only should be used if oth... | 5,320,748 |
def add_noise(dgen_list, noise):
"""Add noise decorators to the DataGenerators from `dgen_list` list.
Parameters
----------
dgen_list : list of IDataGenerator
A list of DataGenerators to be decorated.
noise : list of dict or dict or None
Noise configuration.
If dict then `no... | 5,320,749 |
def index():
"""
Web app index page. It renders two pictures about the data. One bar chart and word cloud.
"""
# extract data needed for visuals
# TODO: Below is an example - modify to extract data for your own visuals
genre_counts = df.groupby('genre').count()['message']
genre_nam... | 5,320,750 |
def infer_dtype_from_object(dtype: Literal["byte"]):
"""
usage.koalas: 1
"""
... | 5,320,751 |
def open(table_file: str, table_map_file: str = None) -> pd.DataFrame:
"""
Opens a dynamo table file, returning a DynamoTable object
:param table_file:
:return: dataframe
"""
# Read into dataframe
df = pd.read_csv(table_file, header=None, delim_whitespace=True)
n_cols = df.shape[1]
i... | 5,320,752 |
def _evaluate_tags(pcluster_config, preferred_tags=None):
"""
Merge given tags to the ones defined in the configuration file and convert them into the Key/Value format.
:param pcluster_config: PclusterConfig, it can contain tags
:param preferred_tags: tags that must take the precedence before the confi... | 5,320,753 |
def test_schaffer2():
"""
Schaffer function N.2 benchmark
"""
options = {
"points" : 100,
"tol" : 2e-2,
"seedval" : 4815162342,
}
f = lambda x: 0.5 + (np.sin(x[0]**2 + x[1]**2)**2 - 0.5)\
/ (1 + 0.001*(x[0]**2 + x[1]**2)... | 5,320,754 |
def dict_view(request):
"""
字典管理
"""
return render_mako_context(request, '/system_permission/dictmgr.html') | 5,320,755 |
def rot_ETA(eta: float) -> np.ndarray:
"""Return rotation matrix corresponding to eta axis.
Parameters
----------
eta: float
eta axis angle
Returns
-------
np.ndarray
Rotation matrix as a NumPy array.
"""
return z_rotation(-eta) | 5,320,756 |
def show_lists(chat_id):
"""
It shows all the lists of the given user
:param chat_id:
:return:
"""
lists = notelistmodel.find_all_lists(mongodb, chat_id)
return {"text": monkeyview.lists_view(lists), "parse_mode": "Markdown"} | 5,320,757 |
def test_params_from_fw_spec(tempdir, files, dtool_config,
default_create_dataset_task_spec,
default_freeze_dataset_task_spec):
"""Will create dataset with some task parameters pulled from fw_spec."""
logger = logging.getLogger(__name__)
t_spec = {
... | 5,320,758 |
def import_string(path: str) -> T.Any:
"""
Import a dotted Python path to a class or other module attribute.
``import_string('foo.bar.MyClass')`` will return the class ``MyClass`` from
the package ``foo.bar``.
"""
name, attr = path.rsplit('.', 1)
return getattr(import_module(name), attr) | 5,320,759 |
def _CheckCmdName(name_or_alias):
"""Only allow strings for command names and aliases (TODO(chandler37): why did they reject unicode as well?).
Args:
name_or_alias: properly formatted string name or alias.
Raises:
AppCommandsError: If name is already registered OR name is not a string OR
... | 5,320,760 |
def inbox():
"""
RESTful CRUD controller for the Inbox
- all Inbound Messages are visible here
"""
if not auth.s3_logged_in():
session.error = T("Requires Login!")
redirect(URL(c="default", f="user",
args = "login",
))
table = s... | 5,320,761 |
def main(args, outs):
""" Fails if args.sentinel is non-empty and refers to a file that exists. """
sentinel = ""
if args.should_fail:
sentinel = martian.make_path("sentinel")
with open(sentinel, "w") as sentinel_file:
sentinel_file.write("fail this attempt")
outs.should_fail... | 5,320,762 |
def set_network_host_project_id(self):
"""Get the host project."""
if not self.config.vpc_host_project_id:
self.config.vpc_host_project_id, _, _ = get_gcloud_info()
print('VPC Host Project %s' % self.config.vpc_host_project_id) | 5,320,763 |
def pipe_remove_props(stream, props, summary=None, comp_id="pipe_remove_props"):
"""Remove properties from the stream.
props can be a single property name or a list of property names."""
if not isinstance(props, list):
props = [props]
rec_counter = 0
for rec_counter, rec in enumerate(strea... | 5,320,764 |
def glorot_uniform_sigm(shape):
"""
Glorot style weight initializer for sigmoid activations.
Like keras.initializations.glorot_uniform(), but with uniform random interval like in
Deeplearning.net tutorials.
They claim that the initialization random interval should be
+/- sqrt(6 / (fan_in... | 5,320,765 |
def test_atomic_negative_integer_min_inclusive_nistxml_sv_iv_atomic_negative_integer_min_inclusive_1_4(mode, save_output, output_format):
"""
Type atomic/negativeInteger is restricted by facet minInclusive with
value -999999999999999999.
"""
assert_bindings(
schema="nistData/atomic/negativeI... | 5,320,766 |
def pytest_report_header(config):
"""Display cachedir with --cache-show and if non-default."""
if config.option.verbose > 0 or config.getini("cache_dir") != ".pytest_cache":
cachedir = config.cache._cachedir
# TODO: evaluate generating upward relative paths
# starting with .., ../.. if s... | 5,320,767 |
def params(kernels, time, target, target_frame, observer, corr):
"""Input parameters from WGC API example."""
return {
'kernels': kernels,
'times': time,
'target': target,
'target_frame': target_frame,
'observer': observer,
'aberration_correction': corr,
} | 5,320,768 |
def extract_thresholds_of_intensity_criteria(data_path, sub_ses_test, patch_side, new_spacing, out_folder, n_parallel_jobs, overlapping, prints=True):
"""This function computes the threshold to use for the extraction of the vessel-like negative patches (i.e. the
negative patches that roughly have the same avera... | 5,320,769 |
def group_activity_list(
group_id: str,
limit: int,
offset: int,
include_hidden_activity: bool = False,
) -> list[Activity]:
"""Return the given group's public activity stream.
Returns activities where the given group or one of its datasets is the
object of the activity, e.g.:
"{USER}... | 5,320,770 |
def on_(period: str):
"""stats for given date"""
since, until = convert_to_range(period)
print(f"# Log items for {period.capitalize()} ({since} to {until})")
main(since=since, until=until) | 5,320,771 |
def rotMatrixfromXYZ(station, mode='LBA'):
"""Return a rotation matrix which will rotate a station to (0,0,1)"""
loc = station.antField.location[mode]
longRotMat = rotationMatrix(0., 0., -1.*np.arctan(loc[1]/loc[0]))
loc0 = np.dot(longRotMat, loc)
latRotMat = rotationMatrix(0., np.arctan(loc0[0,2]/l... | 5,320,772 |
def geo_info_for_geo_name(
geo_name: str, username: str = CONFIG["geonames_username"]
) -> GeoInfo:
"""Get geo information (latitude and longitude) for given region name."""
logging.info("Decoding latitude and longitude of '{}'...".format(geo_name))
gn = geocoders.GeoNames(username=username, timeout=10)... | 5,320,773 |
def char_accuracy(predictions, targets, rej_char, streaming=False):
"""Computes character level accuracy.
Both predictions and targets should have the same shape
[batch_size x seq_length].
Args:
predictions: predicted characters ids.
targets: ground truth character ids.
rej_char: the character id use... | 5,320,774 |
def read_cities_db(fname="world-cities_json.json"):
"""Read a database file containing names of cities from different countries.
Source: https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json
"""
with open(fname) as f:
world_... | 5,320,775 |
async def async_setup_platform(
hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None
):
"""Set up MQTT switch through configuration.yaml."""
await _async_setup_entity(config, async_add_entities, discovery_info) | 5,320,776 |
def update_operands_values(trace, gpr):
""" ensure operands have been updated """
for op in operands_list:
exec("if trace.%0s in gpr: trace.%0s_val = gpr[trace.%0s]" % (op, op, op)) | 5,320,777 |
def generateBinary(ostream, nbytes):
"""Generate Binary with Random Bytes
Generates a binary file with the 8*floor(nbytes/8) bytes of data to the
specified file stream.
Parameters:
ostream - Output file stream that the random binary information will
be written to.
... | 5,320,778 |
def ConcatWith(x, dim, tensor):
"""
A wrapper around `tf.concat` to support `LinearWrap`
:param x: the input tensor
:param dim: the dimension along which to concatenate
:param tensor: a tensor or list of tensor to concatenate with x. x will be
at the beginning
:return: tf.concat(dim, [x]... | 5,320,779 |
def strip_df(data: pd.DataFrame) -> np.ndarray:
"""Strip dataframe from all index levels to only contain values.
Parameters
----------
data : :class:`~pandas.DataFrame`
input dataframe
Returns
-------
:class:`~numpy.ndarray`
array of stripped dataframe without index
""... | 5,320,780 |
def isRef(obj):
""" """
if isinstance(obj, dict) == True and '_REF' in obj:
return obj['_REF']
else:
return False | 5,320,781 |
def collect_genes_with_confidence(
query: str,
*,
cache_file: Path = None,
client: Neo4jClient,
) -> Dict[Tuple[str, str], Dict[str, Tuple[float, int]]]:
"""Collect gene sets based on the given query.
Parameters
----------
query:
A cypher query
client :
The Neo4j cli... | 5,320,782 |
def intervals_disjoint(intvs):
"""
Given a list of complex intervals, check whether they are pairwise
disjoint.
EXAMPLES::
sage: from sage.rings.polynomial.complex_roots import intervals_disjoint
sage: a = CIF(RIF(0, 3), 0)
sage: b = CIF(0, RIF(1, 3))
sage: c = CIF(RIF(... | 5,320,783 |
def _get_registered_typelibs(match='HEC River Analysis System'):
"""
adapted from pywin32
# Copyright (c) 1996-2008, Greg Stein and Mark Hammond.
"""
# Explicit lookup in the registry.
result = []
key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib")
try:
num = 0
... | 5,320,784 |
def head(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", transla... | 5,320,785 |
def standardize(dataset, verbose=True):
""" remove all source-specific columns, keeping only those that occur in all repo sources.
also adds extra columns with default values """
found = False
for source, extra_features in EXTRA_FEATURES.items():
if all(feat in dataset.features for feat in extr... | 5,320,786 |
def mark(tv,stars=None,rad=3,auto=False,color='m',new=False,exit=False):
""" Interactive mark stars on TV, or recenter current list
Args :
tv : TV instance from which user will mark stars
stars = : existing star table
auto= (bool) : if True, recentroid from existing posit... | 5,320,787 |
def result_summary_info(request,object_id):
"""Present a result summary"""
object = get_object_or_404(Results.ResultSummaryList, pk=object_id)
protocolfields={}
for (fieldname, text, cond) in [("version_intolerant", "Version Intolerant", Results.ResultCondition.RESULTC_VERSION_INTOLERANT),
("extension... | 5,320,788 |
def stackplot(data, add, xlabel='', ylabel='', cmap='Spectral',
figsize=(3, 4.5), lw=1, plot=True):
"""
Plots a stack plot of selected spectras.
:type data: list[float]
:param data: Data to in the plot.
:type add: float
:param add: displacement, or difference, between each curve... | 5,320,789 |
def batch_detect(net, img_batch, device):
"""
Inputs:
- img_batch: a numpy array of shape (Batch size, Channels, Height, Width)
"""
B, C, H, W = img_batch.shape
orig_size = min(H, W)
# BB, HH, WW = img_batch.shape
# if img_batch
if isinstance(img_batch, torch.Tensor):
... | 5,320,790 |
def int_to_binary(x, n):
"""Convert an integer into its binary representation
Args:
x (int): input integer
n (int): number of leading zeros to display
Returns:
(str) binary representation
"""
if type(x) != int:
raise ValueError('x must be an integer.')
return f... | 5,320,791 |
def ndtype_validator(validator, value, instance, schema):
""" validators for n-dimensional data dtype
Parameters
----------
validator
value
instance
schema
Returns
-------
"""
try:
np.asarray(instance, dtype=value)
except (ValueError, TypeError):
yield ... | 5,320,792 |
def TestClusterRename():
"""gnt-cluster rename"""
cmd = ["gnt-cluster", "rename", "-f"]
original_name = qa_config.get("name")
rename_target = qa_config.get("rename", None)
if rename_target is None:
print qa_logging.FormatError('"rename" entry is missing')
return
for data in [
cmd + [rename_tar... | 5,320,793 |
def read_requirements():
"""Parse requirements from requirements.txt."""
requirements_path = os.path.join('.', 'requirements.txt')
with open(requirements_path, 'r') as f:
requirements = [line.rstrip() for line in f]
return requirements | 5,320,794 |
def convert_examples_to_features(examples,
tokenizer,
max_seq_length,
max_program_length,
is_training,
op_list,
op_list_si... | 5,320,795 |
def show(dir_path: str, use_pager: bool) -> None:
"""
show history
Args:
dir_path (str): path of cache directory.
use_pager (bool): Whether to use pager.
"""
core.show(dir_path, use_pager) | 5,320,796 |
def negative_mean_successiness(c):
"""Negative mean successiness over the course of the trial."""
if c.needed_control_arm_events.size > 1:
center = float(c.needed_control_arm_events.mean())
width = float(c.needed_control_arm_events.std())
else:
center = float(c.needed_control_arm_events)
width = c... | 5,320,797 |
def determina_putere(n):
"""
Determina ce putere a lui 2 este prima cea mai mare
decat n
:param (int) n: numarul de IP-uri necesare
citit de la tastatura
:return (int) putere: puterea lui 2 potrivita
"""
putere = 1
while 2**putere < n+2:
putere += 1
... | 5,320,798 |
def process_project(self, processing_request: Dict[str, Any]) -> None:
"""Check if packages in given project may be updated."""
log.debug("Starting task 'process_project'.")
worker = Worker(update_celery_state_method=self.update_state, logger=log)
log.debug("Attempting to deserialize project request.")... | 5,320,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.