content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def merge_image_data(dir_dict, output_image_file, logg):
"""
Merge image data in dir_dict.
Parameters
----------
base_dir : str base directory of dir_dict
dir_dict : dictionary containing pairs of directories and associated files
output_image_file : str output image file string
... | 77a090d08cdbfa2c4a5daf75f2393557d27105ec | 1,300 |
def case_mc2us(x):
""" mixed case to underscore notation """
return case_cw2us(x) | 13cd638311bea75699789a2f13b7a7d854f856bd | 1,301 |
import argparse
import sys
def _parse_arguments():
"""
Constructs and parses the command line arguments for eg. Returns an args
object as returned by parser.parse_args().
"""
parser = argparse.ArgumentParser(
description='eg provides examples of common command usage.'
)
parser.add... | 233dd4d9a61529aaba7c02b32d56839acc203799 | 1,302 |
def detail_url(reteta_id):
""""Return reteta detail URL"""
return reverse('reteta:reteta-detail', args=[reteta_id]) | 4b7219b5e0d7ae32656766a08c34f54a02d1634e | 1,303 |
def load_metadata_txt(file_path):
"""
Load distortion coefficients from a text file.
Parameters
----------
file_path : str
Path to a file.
Returns
-------
tuple of floats and list
Tuple of (xcenter, ycenter, list_fact).
"""
if ("\\" in file_path):
raise ... | 44e6319aec6d77910e15e8890bcd78ffcdca3aa4 | 1,304 |
import torch
def _output_gradient(f, loss_function, dataset, labels, out0, batch_indices, chunk):
"""
internal function
"""
x = _getitems(dataset, batch_indices)
y = _getitems(labels, batch_indices)
if out0 is not None:
out0 = out0[batch_indices]
out = []
grad = 0
loss_va... | 252f79065ce953eb99df17842d62786cebadee67 | 1,305 |
def __material_desc_dict(m, d):
""" Unpack positions 18-34 into material specific dict. """
return dict(zip(MD_FIELDS[m],
{"BK": __material_bk, "CF": __material_cf,
"MP": __material_mp, "MU": __material_mu,
"CR": __material_cr, "VM": __material_vm,
... | 9f87ce915bd5d226fa1d1ffd5991779c9a4fbdba | 1,306 |
def toint(x):
"""Try to convert x to an integer number without raising an exception."""
try: return int(x)
except: return x | bd1a675cb3f8f5c48e36f8f405a89dc637f3f558 | 1,307 |
def obtain_time_image(x, y, centroid_x, centroid_y, psi, time_gradient, time_intercept):
"""Create a pulse time image for a toymodel shower. Assumes the time development
occurs only along the longitudinal (major) axis of the shower, and scales
linearly with distance along the axis.
Parameters
-----... | 4a57399e041c0fd487fe039e5091986438d4b8b8 | 1,308 |
import re
def remove_comment(to_remove, infile):
"""Removes trailing block comments from the end of a string.
Parameters:
to_remove: The string to remove the comment from.
infile: The file being read from.
Returns:
The paramter string with the block comment removed (if comment wa... | 0172b295c9a023eb96fbad7a6c3a388874e106bc | 1,309 |
def generate_notification_header(obj):
"""
Generates notification header information based upon the object -- this is
used to preface the notification's context.
Could possibly be used for "Favorites" descriptions as well.
:param obj: The top-level object instantiated class.
:type obj: class w... | e02c2bdd9827077a49236ed7aa813458659f453c | 1,310 |
def promptyn(msg, default=None):
""" Display a blocking prompt until the user confirms """
while True:
yes = "Y" if default else "y"
if default or default is None:
no = "n"
else:
no = "N"
confirm = raw_input("%s [%s/%s]" % (msg, yes, no))
confirm =... | 1bec535462b8e859bac32c424e8500c432eb7751 | 1,311 |
def plan_launch_spec(state):
""" Read current job params, and prescribe the next training job to launch
"""
last_run_spec = state['run_spec']
last_warmup_rate = last_run_spec['warmup_learning_rate']
add_batch_norm = last_run_spec['add_batch_norm']
learning_rate = last_run_spec['learning_rate']... | 5fee797f24db05eccb49a5b10a9d88917987f905 | 1,312 |
def ssgenTxOut0():
"""
ssgenTxOut0 is the 0th position output in a valid SSGen tx used to test out the
IsSSGen function
"""
# fmt: off
return msgtx.TxOut(
value=0x00000000, # 0
version=0x0000,
pkScript=ByteArray(
[
0x6a, # OP... | 3bee03ef9bc3a326fff381b6d2594c3ea4c909e7 | 1,313 |
def sexag_to_dec(sexag_unit):
""" Converts Latitude and Longitude Coordinates from the Sexagesimal Notation
to the Decimal/Degree Notation"""
add_to_degree = (sexag_unit[1] + (sexag_unit[2]/60))/60
return sexag_unit[0]+add_to_degree | c9c4394920d2b483332eb4a81c0f0d9010179339 | 1,314 |
import apysc as ap
from typing import Any
from typing import Tuple
def is_immutable_type(value: Any) -> bool:
"""
Get a boolean value whether specified value is immutable
type or not.
Notes
-----
apysc's value types, such as the `Int`, are checked
as immutable since these js types are imm... | 79538477528df2e13eaf806231e2f43c756abacd | 1,315 |
def add_column_node_type(df: pd.DataFrame) -> pd.DataFrame:
"""Add column `node_type` indicating whether a post is a parent or a leaf node
Args:
df: The posts DataFrame with the columns `id_post` and `id_parent_post`.
Returns:
df: A copy of df, extended by `node_type`.
"""
if "node... | 3ad8a12f1a872d36a14257bdaa38229768714fa5 | 1,316 |
import random
def read_motifs(fmotif):
"""
create a random pool of motifs to choose from for the monte-carlo simulations
"""
motif_pool = []
for line in open(fmotif):
if not line.strip(): continue
if line[0] == "#": continue
motif, count = line.rstrip().split()
moti... | 168a7f82727917aa5ca1a30b9aa9df1699261585 | 1,317 |
from App import Proxys
import math
def createCone( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ):
"""
Create a rigid body for a cone with the specified attributes (axis is 0:x, 1:y, 2:z). Other rigid body parameters can be specified with keyword argume... | 43a7e0134627ed8069359c29bc53f354d70498d9 | 1,318 |
from typing import Union
def ef(candles: np.ndarray, lp_per: int = 10, hp_per: int = 30, f_type: str = "Ehlers", normalize: bool = False, source_type: str = "close", sequential: bool = False) -> Union[
float, np.ndarray]:
# added to definition : use_comp: bool = False, comp_intensity: float = 90.0,
"""
... | 6dd19e9a1cb5a8f293f4ec3eebef625e2b05bcfe | 1,319 |
from typing import Dict
def parse_displays(config: Dict) -> Dict[str, QueryDisplay]:
"""Parse display options from configuration."""
display_configs = config.get("displays")
if not display_configs:
return {}
displays = {}
for name, display_config in display_configs.items():
displa... | a7f3c32d3ceaf6c39ea16ee7e2f7ec843036487e | 1,320 |
async def update_result(user: dict, form: dict) -> str:
"""Extract form data and update one result and corresponding start event."""
informasjon = await create_finish_time_events(user, "finish_bib", form) # type: ignore
return informasjon | b9b97f3b08f08dc35a0744f38323d76ecb0c3fba | 1,321 |
from typing import List
import torch
import copy
def rasterize_polygons_within_box(
polygons: List[np.ndarray], box: np.ndarray, mask_size: int
) -> torch.Tensor:
"""
Rasterize the polygons into a mask image and
crop the mask content in the given box.
The cropped mask is resized to (mask_size, mas... | 98a35b477338f0f472d34b49f4be9f9cd0303654 | 1,322 |
def has_ao_num(trexio_file) -> bool:
"""Check that ao_num variable exists in the TREXIO file.
Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function.
Returns:
True if the variable exists, False otherwise
Raises:
- Exception from trexio.Error class if ... | 6a10204cc5d64a71e991fed1e43fd9ff81a250b9 | 1,323 |
def teapot(size=1.0):
"""
Z-axis aligned Utah teapot
Parameters
----------
size : float
Relative size of the teapot.
"""
vertices, indices = data.get("teapot.obj")
xmin = vertices["position"][:,0].min()
xmax = vertices["position"][:,0].max()
ymin = vertices["position"]... | 94cef5111384599f74bfe59fb97ba417c738ca50 | 1,324 |
def f30(x, rotations=None, shifts=None, shuffles=None):
"""
Composition Function 10 (N=3)
Args:
x (array): Input vector of dimension 2, 10, 20, 30, 50 or 100.
rotations (matrix): Optional rotation matrices (NxDxD). If None
(default), the official matrices from the benchmark suit... | d2bfe7a0bba501e1d7d5bcf29475ecc36f73913b | 1,325 |
def loadNode( collada, node, localscope ):
"""Generic scene node loading from a xml `node` and a `collada` object.
Knowing the supported nodes, create the appropiate class for the given node
and return it.
"""
if node.tag == tag('node'): return Node.load(collada, node, localscope)
elif node.ta... | 68083c4490e44e71f33d1221776837f2c1d59b69 | 1,326 |
def create_xla_tff_computation(xla_computation, type_spec):
"""Creates an XLA TFF computation.
Args:
xla_computation: An instance of `xla_client.XlaComputation`.
type_spec: The TFF type of the computation to be constructed.
Returns:
An instance of `pb.Computation`.
"""
py_typecheck.check_type(xl... | 5a02051913026029cab95d12199eb321fa511654 | 1,327 |
def render_contact_form(context):
"""
Renders the contact form which must be in the template context.
The most common use case for this template tag is to call it in the
template rendered by :class:`~envelope.views.ContactView`. The template
tag will then render a sub-template ``envelope/contact_fo... | e243502fadbf094ed7277ec5db770a3b209174e2 | 1,328 |
from typing import List
from typing import Dict
def get_basic_project(reviews: int = 0) -> List[Dict]:
"""Get basic project config with reviews."""
reviews = max(reviews, MIN_REVIEW)
reviews = min(reviews, MAX_REVIEW)
middle_stages, entry_point = _get_middle_stages(reviews, OUTPUT_NAME)
input_st... | 14c2252dec69ebbcec04fbd00de0fa5ac6d1cdf7 | 1,329 |
import re
def choose_quality(link, name=None, selected_link=None):
"""
choose quality for scraping
Keyword Arguments:
link -- Jenitem link with sublinks
name -- Name to display in dialog (default None)
"""
if name is None:
name = xbmc.getInfoLabel('listitem.label')
if link.sta... | a75214cd0acd1c0e3ede34241baeb07342aadb1b | 1,330 |
def picp_loss(target, predictions, total = True):
"""
Calculate 1 - PICP (see eval_metrics.picp for more details)
Parameters
----------
target : torch.Tensor
The true values of the target variable
predictions : list
- predictions[0] = y_pred_upper, predicted upper limit of the t... | a6d8d150241b1a2f8dda00c9c182ba7196c65585 | 1,331 |
import os
def find_files_to_upload(upload_dir):
"""
Find the files which are named correctly and have a .asc file
"""
files = []
for name in os.listdir(upload_dir):
asc_file = os.path.join(upload_dir, "{}.asc".format(name))
if valid_format(name) and os.path.isfile(asc_file):
... | f5647e7c30af16abe21ace1a9b488a947e4ecdb8 | 1,332 |
def index_wrap(data, index):
"""
Description: Select an index from an array data
:param data: array data
:param index: index (e.g. 1,2,3, account_data,..)
:return: Data inside the position index
"""
return data[index] | 42b53f1d9edf237b904f822c15ad1f1b930aa69c | 1,333 |
def import_operand_definition(
defdict, yaml, key, base_module,
regs, force=False
):
"""
:param defdict:
:param yaml:
:param key:
:param base_module:
:param regs:
"""
try:
entry = defdict[key]
except KeyError:
raise MicroprobeArchitectureDefinitionError(
... | 79acc3d03ec3758cfe03be0f3cf3cd0bc4679c25 | 1,334 |
def mzml_to_pandas_df(filename):
"""
Reads mzML file and returns a pandas.DataFrame.
"""
cols = ["retentionTime", "m/z array", "intensity array"]
slices = []
file = mzml.MzML(filename)
while True:
try:
data = file.next()
data["retentionTime"] = data["scanList"... | 2c6f1956d7c499c9f22bc85665bd6b5ce9ed51c3 | 1,335 |
def metadata_volumes(response: Response,
request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST),
sourcetype: str=Query(None, title=opasConfig.TITLE_SOURCETYPE, description=opasConfig.DESCRIPTION_PARAM_SOURCETYPE),
... | e8e4a686eaac21b20f2d758b8bc7de74d38571ab | 1,336 |
def do_step_right(pos: int, step: int, width: int) -> int:
"""Takes current position and do 3 steps to the
right. Be aware of overflow as the board limit
on the right is reached."""
new_pos = (pos + step) % width
return new_pos | 530f3760bab00a7b943314ca735c3a11343b87f5 | 1,337 |
def log_agm(x, prec):
"""
Fixed-point computation of -log(x) = log(1/x), suitable
for large precision. It is required that 0 < x < 1. The
algorithm used is the Sasaki-Kanada formula
-log(x) = pi/agm(theta2(x)^2,theta3(x)^2). [1]
For faster convergence in the theta functions, x should
b... | e873db3a45270eb077d9dc17f2951e2e791ad601 | 1,338 |
import unicodedata
def simplify_name(name):
"""Converts the `name` to lower-case ASCII for fuzzy comparisons."""
return unicodedata.normalize('NFKD',
name.lower()).encode('ascii', 'ignore') | a7c01471245e738fce8ab441e3a23cc0a67c71be | 1,339 |
async def parse_regex(opsdroid, skills, message):
"""Parse a message against all regex skills."""
matched_skills = []
for skill in skills:
for matcher in skill.matchers:
if "regex" in matcher:
opts = matcher["regex"]
matched_regex = await match_regex(messa... | aa3ad8ff48854b974ba90135b510074644e10028 | 1,340 |
def interpolate_minusones(y):
"""
Replace -1 in the array by the interpolation between their neighbor non zeros points
y is a [t] x [n] array
"""
x = np.arange(y.shape[0])
ynew = np.zeros(y.shape)
for ni in range(y.shape[1]):
idx = np.where(y[:,ni] != -1)[0]
if len(idx)>1:
... | db3e347ba75a39f40cd3ee90481efe8392ce08ed | 1,341 |
def precision(y, yhat, positive=True):
"""Returns the precision (higher is better).
:param y: true function values
:param yhat: predicted function values
:param positive: the positive label
:returns: number of true positive predictions / number of positive predictions
"""
table = continge... | f643631781565ddb049c1c4d22c6e5ea64ce4a22 | 1,342 |
def add_posibility_for_red_cross(svg):
"""add a symbol which represents a red cross in a white circle
Arguments:
svg {Svg} -- root element
"""
symbol = Svg(etree.SubElement(svg.root,
'symbol',
{'id': 'red_cross',
... | df621fb907187a36cb3f7387047a8cda6cb42992 | 1,343 |
import functools
import sys
def exceptions2exit(exception_list):
"""
Decorator to convert given exceptions to exit messages
This avoids displaying nasty stack traces to end-users
:param exception_list: list of exceptions to convert
"""
def exceptions2exit_decorator(func):
@functools.... | 8a73c334f03b81f8c96fd1d4e6691031f26c9896 | 1,344 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | 529cb8d6312eaa129a52f1679294d85c1d9bfbd0 | 1,345 |
import ctypes
def dasopw(fname):
"""
Open a DAS file for writing.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopw_c.html
:param fname: Name of a DAS file to be opened.
:type fname: str
:return: Handle assigned to the opened DAS file.
"""
fname = stypes.stringToCha... | 63f164ba82e6e135763969c8823d7eb46dd52c0e | 1,346 |
import re
def is_ncname(value):
"""
BNode identifiers must be valid NCNames.
From the `W3C RDF Syntax doc <http://www.w3.org/TR/REC-rdf-syntax/#section-blank-nodeid-event>`_
"The value is a function of the value of the ``identifier`` accessor.
The string value begins with "_:" and the entire val... | 78cbfe9209b9f39cd6bc90c0ed5c8e5291bc1562 | 1,347 |
from typing import Dict
def health_func() -> Dict[str, str]:
"""Give the user the API health."""
return "ok" | 5c14795d9d0560ddb34b193575917ac184dbe8a3 | 1,348 |
def queue_worker(decoy: Decoy) -> QueueWorker:
"""Get a mock QueueWorker."""
return decoy.mock(cls=QueueWorker) | aec88b037e393b195abd0c2704e8f2784e9a9f8d | 1,349 |
def astra_fp_3d(volume, proj_geom):
"""
:param proj_geom:
:param volume:
:return:3D sinogram
"""
detector_size = volume.shape[1]
slices_number = volume.shape[0]
rec_size = detector_size
vol_geom = build_volume_geometry_3d(rec_size, slices_number)
sinogram_id = astra.data3d.crea... | 7066bb61dc29fac331ffb13c6fe1432349eac185 | 1,350 |
def get_wf_neb_from_images(
parent,
images,
user_incar_settings,
additional_spec=None,
user_kpoints_settings=None,
additional_cust_args=None,
):
"""
Get a CI-NEB workflow from given images.
Workflow: NEB_1 -- NEB_2 - ... - NEB_n
Args:
parent (Structure): parent structure... | 15ed110d3685c9d8de216733e8d87f6c07580529 | 1,351 |
def categorize_folder_items(folder_items):
"""
Categorize submission items into three lists: CDM, PII, UNKNOWN
:param folder_items: list of filenames in a submission folder (name of folder excluded)
:return: a tuple with three separate lists - (cdm files, pii files, unknown files)
"""
found_cdm... | 14e840817cce4cc91ed50d6d9dcfa1c19a2bcbeb | 1,352 |
def _broadcast_all(indexArrays, cshape):
"""returns a list of views of 'indexArrays' broadcast to shape 'cshape'"""
result = []
for i in indexArrays:
if isinstance(i, NDArray) and i._strides is not None:
result.append(_broadcast(i, cshape))
else:
result.append(i)
... | b7b98245bc534074e408d5c9592bf68ae53f580e | 1,353 |
def _none_tozero_array(inarray, refarray):
"""Repair an array which is None with one which is not
by just buiding zeros
Attributes
inarray: numpy array
refarray: numpy array
"""
if inarray is None:
if _check_ifarrays([refarray]):
inarray = np.zeros_like(refarray)... | 9b0852655a13b572106acc809d842ca38d24e707 | 1,354 |
def dpuGetExceptionMode():
"""
Get the exception handling mode for runtime N2Cube
Returns: Current exception handing mode for N2Cube APIs.
Available values include:
- N2CUBE_EXCEPTION_MODE_PRINT_AND_EXIT
- N2CUBE_EXCEPTION_MODE_RET_ERR_CODE
"""
return pyc_l... | fd33aba868a05f3cc196c89e3c2d428b0cce108a | 1,355 |
import re
def clean_links(links, category):
"""
clean up query fields for display as category buttons to browse by
:param links: list of query outputs
:param category: category of search from route
:return: list of cleansed links
"""
cleansedlinks = []
for item in links:
# remo... | f43af81a8ef8e5520726e886dd74d991c999a32d | 1,356 |
from typing import Any
from typing import Optional
def as_bool(value: Any, schema: Optional[BooleanType] = None) -> bool:
"""Parses value as boolean"""
schema = schema or BooleanType()
value = value.decode() if isinstance(value, bytes) else value
if value:
value = str(value).lower()
v... | 7085b7bc7eccb2db95f5645b358e4940914f68f9 | 1,357 |
from typing import Dict
from typing import List
from typing import Tuple
def get_raw_feature(
column: Text, value: slicer_lib.FeatureValueType,
boundaries: Dict[Text, List[float]]
) -> Tuple[Text, slicer_lib.FeatureValueType]:
"""Get raw feature name and value.
Args:
column: Raw or transformed column... | 29323b8e1a7ef32f19ff94f31efca20567780aa4 | 1,358 |
from typing import Union
def ndmi(nir: Union[xr.DataArray, np.ndarray, float, int],
swir1: Union[xr.DataArray, np.ndarray, float, int]) -> \
Union[xr.DataArray, np.ndarray, float, int]:
"""
Normalized difference moisture index.
Sentinel-2: B8A, B11
Parameters
----------
nir ... | f66a68cd75d9c030c0257e1d543c2caf9efcf652 | 1,359 |
def _collect_data_and_enum_definitions(parsed_models: dict) -> dict[str, dict]:
"""
Collect all data and enum definitions that are referenced as interface messages or as a nested type within an interface message.
Args:
parsed_models: A dict containing models parsed from an AaC yaml file.
Retur... | 0d561003c8cdbe7d2eb7df2f03d5939f70d81467 | 1,360 |
def _list_goals(context, message):
"""Show all installed goals."""
context.log.error(message)
# Execute as if the user had run "./pants goals".
return Phase.execute(context, 'goals') | 5e823770528e97b4254e426a2d99113d119368b0 | 1,361 |
def values(df, varname):
"""Values and counts in index order.
df: DataFrame
varname: strign column name
returns: Series that maps from value to frequency
"""
return df[varname].value_counts().sort_index() | ea548afc8e0b030e441baa54abad32318c9c007f | 1,362 |
def get_or_none(l, n):
"""Get value or return 'None'"""
try:
return l[n]
except (TypeError, IndexError):
return 'None' | c46a0f4c8edc9286b0122f1643e24a04113a5bfc | 1,363 |
def pfam_clan_to_pdb(clan):
"""get a list of associated PDB ids for given pfam clan access key.
:param clan: pfam accession key of clan
:type clan: str
:return: List of associated PDB ids
:rettype:list"""
url='http://pfam.xfam.org/clan/'+clan+'/structures'
pattern='/structure/[A-Z, 0-9]... | 820e8a058edfeee256ab01281020c6e38e2d7c6d | 1,364 |
def fib(n):
"""Compute the nth Fibonacci number.
>>> fib(8)
21
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-2) + fib(n-1) | 0db631be60754376e1a9287a4486ceb5ad7e392f | 1,365 |
import os
def _is_cache_dir_appropriate(cache_dir, cache_file):
"""
Determine if a directory is acceptable for building.
A directory is suitable if any of the following are true:
- it doesn't exist
- it is empty
- it contains an existing build cache
"""
if os.path.exists(cache_d... | b7a94540b8e97c4628224c05bfff44b798e449c9 | 1,366 |
from typing import List
from typing import Union
def score_tours_absolute(problems: List[N_TSP], tours: List[Union[int, NDArray]]) -> NDArray:
"""Calculate tour lengths for a batch of tours.
Args:
problems (List[N_TSP]): list of TSPs
tours (List[Union[int, NDArray]]): list of tours (in either... | b13ad2df2bfaf58f2b6989f2f2e67d917475b5bb | 1,367 |
def has(pred: Pred, seq: Seq) -> bool:
"""
Return True if sequence has at least one item that satisfy the predicate.
"""
for x in seq:
if pred(x):
return True
return False | bc41ceb21804cd273d0c2a71327f63f2269763d9 | 1,368 |
from typing import Optional
from typing import Union
from typing import List
from typing import Dict
from typing import Any
import re
from datetime import datetime
def _get_dataset_domain(
dataset_folder: str,
is_periodic: bool,
spotlight_id: Optional[Union[str, List]] = None,
time_unit: Optional[str]... | bc230145eee3f60491b4c42453fcbf5145ac7761 | 1,369 |
def randomize_quaternion_along_z(
mujoco_simulation: RearrangeSimulationInterface, random_state: RandomState
):
""" Rotate goal along z axis and return the rotated quat of the goal """
quat = _random_quat_along_z(mujoco_simulation.num_objects, random_state)
return rotation.quat_mul(quat, mujoco_simulati... | 9bc29520ca8f00debf819bf4dee55cce43bb8483 | 1,370 |
from io import StringIO
import json
def init(model):
"""
Initialize the server. Loads pyfunc model from the path.
"""
app = flask.Flask(__name__)
@app.route("/ping", methods=["GET"])
def ping(): # pylint: disable=unused-variable
"""
Determine if the container is working and h... | 525ffd789be94c1e70d987c4b64c8876d9260d72 | 1,371 |
def sample_tag(user, name='Comedy'):
"""Creates a sample Tag"""
return Tag.objects.create(user=user, name=name) | 2288d8344fcf931a9e932b46db9a65275425b427 | 1,372 |
from typing import Tuple
def _middle_point(p1: np.ndarray, p2: np.ndarray) -> Tuple[int, int]:
"""Returns the middle point (x,y) between two points
Arguments:
p1 (np.ndarray): First point
p2 (np.ndarray): Second point
"""
return tuple((p1 + p2) // 2) | dcca1c1eeb0fea8c9adebfc9cccca94cb7ab7a43 | 1,373 |
def filter_with_prefixes(value, prefixes):
"""
Returns true if at least one of the prefixes exists in the value.
Arguments:
value -- string to validate
prefixes -- list of string prefixes to validate at the beginning of the value
"""
for prefix in prefixes:
if value.startswith(prefi... | 56b9bacedaa7aa06023e29d45809f6e9661ee483 | 1,374 |
import os
def get_idl_parser(*, allow_cache=True):
"""Get the global IdlParser object."""
# Singleton pattern
global _parser
if _parser and allow_cache:
return _parser
# Get source
with open(os.path.join(lib_dir, "resources", "webgpu.idl"), "rb") as f:
source = f.read().decod... | 345b1290d461ee064ae9aeb635f7f2ba902f2b1a | 1,375 |
def is_seq(x, step=1):
"""Checks if the elements in a list-like object are increasing by step
Parameters
----------
x: list-like
step
Returns
-------
True if elements increase by step, else false and the index at which the condition is violated.
"""
for i in range(1, len(x)):
... | 032e12b86aa7e50dfba2ddccd244475f58d70b29 | 1,376 |
def create_patient(record: dict) -> tuple:
""" Returns a FHIR Patient resource entry and reference. """
gender = map_sex(record["sex_new"] or record["sex"])
patient_id = generate_patient_hash(
names = participant_names(record),
gender = gender,
birth_date = record['birth... | cf211e9452b3a9f82ea1bd32bffeb9ba2146bc9e | 1,377 |
def delete_editor(userid):
"""
:param userid: a string representing the user's UW NetID
:return: True if request is successful, False otherwise.
raise DataFailureException or a corresponding TrumbaException
if the request failed or an error code has been returned.
"""
url = _make_del_account... | 494211289faa4b16206b9687d6f7f94a8adc992a | 1,378 |
def ecio_quality_rating(value, unit):
"""
ECIO (Ec/Io) - Energy to Interference Ratio (3G, CDMA/UMTS/EV-DO)
"""
if unit != "dBm":
raise ValueError("Unsupported unit '{:}'".format(unit))
rating = 0
if value > -2:
rating = 4
elif -2 >= value > -5:
rating = 3
elif ... | 4cc21012464b8476d026f9dfbc35b8b1ea3c2d85 | 1,379 |
def normalizeFilename(filename):
"""normalizeFilename(filename)
Replace characters that are illegal in the Window's environment"""
res = filename
rep = { "*":"_", "\"":"\'", "/":" per ", "\\":"_", ",":"_", "|":"_", ":":";" }
for frm, to in rep.iteritems():
res = res.replace(frm, to)
ret... | 84239d7d4fd982b27a4e0f5d20f615f3f288af85 | 1,380 |
def __virtual__():
"""
Check if macOS and PyObjC is available
"""
if not salt.utils.platform.is_darwin():
return (False, 'module: mac_wifi only available on macOS.')
if not PYOBJC:
return (False, 'PyObjC not available.')
return __virtualname__ | 46d21f3546234984890ff147a300ee8241b69ae6 | 1,381 |
def rearrange_kernel(kernel, data_shape=None):
"""Rearrange kernel
This method rearanges the input kernel elements for vector multiplication.
The input kernel is padded with zeroes to match the image size.
Parameters
----------
kernel : np.ndarray
Input kernel array
data_shape : tu... | a5117d56f520c3a8f79ba2baea68d0b4d516158c | 1,382 |
def exportTable(request_id, params):
"""Starts a table export task running.
This is a low-level method. The higher-level ee.batch.Export.table object
is generally preferred for initiating table exports.
Args:
request_id (string): A unique ID for the task, from newTaskId. If you are
using the cloud A... | e4dd22264c070315351bc3dd51061bc4948c9bda | 1,383 |
def add_parents_to_frame(qs):
"""
There seems to be bug in the django-pandas api that self-foreign keys are not returned properly
This is a workaround
:param qs:
:return:
"""
tn_parent_ids = qs.values_list("tn_parent_id", flat=True).all()
df = read_frame(qs.all(), fieldnames=get_standard... | cf3873822800620a6e52621846ed36dcfaee6d7b | 1,384 |
def template_check(value):
"""Check if a rendered template string equals true.
If value is not a string, return value as is.
"""
if isinstance(value, str):
return value.lower() == "true"
return value | 3733db5c107068e815bac079fdef1a450f7acdc9 | 1,385 |
def return_npc(mcc, mnc):
"""
Format MCC and MNC into a NPC.
:param mcc: Country code.
:type mcc: int
:param mnc: Network code.
:type mnc: int
"""
return "{0}{1}30".format(str(mcc).zfill(3), str(mnc).zfill(3)) | 0ae5952fd7b026c2c90c72046f63ca4d08dacf06 | 1,386 |
import math
def class_to_bps(bw_cls):
"""
Convert a SIBRA bandwidth class to bps (Bits Per Second). Class 0 is a
special case, and is mapped to 0bps.
:param float bw_cls: SIBRA bandwidth class.
:returns: Kbps of bandwidth class
:rtype: float
"""
if bw_cls == 0:
return 0
bw... | 02d0b4fbf5655318e6807bdd8c41fdfb59010ba4 | 1,387 |
def _get_capacity():
"""Return constant values for dam level capacities.
Storage capacity values are measured in million cubic metres
i.e. Megalitres or Ml.
Source: https://en.wikipedia.org/wiki/Western_Cape_Water_Supply_System
@return capacity: Dict object containing maximum capacities of Wester... | 01d1a5e7470d578296e285e2e00cd44eaf00d15c | 1,388 |
def login_required(f):
"""
Decorator to use if a view needs to be protected by a login.
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not 'username' in session:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function | d09069e65c64c06885708b10ca70f5f319389c7a | 1,389 |
def test_bare_except() -> None:
"""Bare `except` to handle any uncaught exceptions."""
def reciprocal_of(value: float) -> float:
try:
return 1 / value
except ZeroDivisionError:
raise
except:
raise
pytest.raises(TypeError, reciprocal_of, "a") | 8cce2efcd850ca546f092ec0988d69e8d576e500 | 1,390 |
def _get_image_blob(im):
"""Converts an image into a network input.
Arguments:
im (ndarray): a color image in BGR order
Returns:
blob (ndarray): a data blob holding an image pyramid
im_scale_factors (list): list of image scales (relative to im) used
in the image pyramid... | 61a10be02f258680b0c103398deee9d72870035b | 1,391 |
import sys
def check_args():
"""Checks the arguments passed by the command line
By passing one or more parameters, you can disable a single module source.
Actual parameters allowed are:
* `-no-instagram`: disables Instagram source
* `-no-youtube`: disables YouTube source
* `-no-spot... | 8458772b1a173bb5ca99fefd3d98ccd1aca32dc3 | 1,392 |
def toiter(x):
"""Convert to iterable. If input is iterable, returns it. Otherwise returns it in a list.
Useful when you want to iterate over something (like in a for loop),
and you don't want to have to do type checking or handle exceptions
when it isn't a sequence"""
if iterable(x):
return... | ef9716b65893ca614dd53cc6fa7ae17b6cce2a35 | 1,393 |
def ap_date(value):
"""
Converts a date string in m/d/yyyy format into AP style.
"""
if not value:
return ''
bits = unicode(value).split('/')
month, day, year = bits
output = AP_MONTHS[int(month) - 1]
output += ' ' + unicode(int(day))
output += ', ' + year
return outp... | 4ca1dab0775141f548946072e0208502d54bc784 | 1,394 |
def dump_sql(fp, query: str, encoding="utf8"):
"""
Write a given query into a file path.
"""
query = ljustify_sql(query)
for line in query:
fp.write(bytes(line, encoding=encoding))
return fp | b6a847dbfccb17c0cf7bd3590eee69783d83030c | 1,395 |
def make_design_matrix(stim, d=25):
"""Create time-lag design matrix from stimulus intensity vector.
Args:
stim (1D array): Stimulus intensity at each time point.
d (number): Number of time lags to use.
Returns
X (2D array): GLM design matrix with shape T, d
"""
padded_stim = np.concatenate([np... | 5b1759076b9e0f44ea338a4e72d2f1a76d3ccc3b | 1,396 |
def _fit_subpixel_2d(image, coord, radius, voxel_size_yx, psf_yx):
"""Fit a gaussian in a 2-d image.
Parameters
----------
image : np.ndarray
Image with shape (y, x).
coord : np.ndarray, np.int64
Coordinate of the spot detected, with shape (2,). One coordinate per
dimension ... | 6e05b395ae93319de599283fe041f681b5ee039c | 1,397 |
def density(sisal,temp,pres,salt=None,dliq=None,chkvals=False,
chktol=_CHKTOL,salt0=None,dliq0=None,chkbnd=False,useext=False,
mathargs=None):
"""Calculate sea-ice total density.
Calculate the total density of a sea-ice parcel.
:arg float sisal: Total sea-ice salinity in kg/kg.
:arg fl... | 40a365ea0d4c79813394790ef3df6c8eb21727b8 | 1,398 |
def prod_non_zero_diag(x):
"""Compute product of nonzero elements from matrix diagonal.
input:
x -- 2-d numpy array
output:
product -- integer number
Not vectorized implementation.
"""
n = len(x)
m = len(x[0])
res = 1
for i in range(min(n, m)):
if (x[i][i] != 0):
... | 13e9f6cc9ea22e7901d454b23297a2e9c5da3a3a | 1,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.