content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def bad_request(message):
"""Responde em forma de json o erro not found"""
print("Teste")
response = jsonify({'error':'bad request' , 'message' : message})
response.status_code = 400 | 22,600 |
def get_valid_identifier(prop, replacement_character='', allow_unicode=False):
"""Given a string property, generate a valid Python identifier
Parameters
----------
replacement_character: string, default ''
The character to replace invalid characters with.
allow_unicode: boolean, default Fal... | 22,601 |
def main() -> None:
"""
direct program entry point
"""
argp = argparse.ArgumentParser(
description="use regular expressions to rename files",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
argp.add_argument(
"-d",
"--debug",
action="store_true",... | 22,602 |
def temporal_padding(x, paddings=(1, 0), pad_value=0):
"""Pad the middle dimension of a 3D tensor
with `padding[0]` values left and `padding[1]` values right.
Modified from keras.backend.temporal_padding
https://github.com/fchollet/keras/blob/3bf913d/keras/backend/theano_backend.py#L590
... | 22,603 |
def install_dmm_test(node):
"""Prepare the DMM test envrionment.
Raise errors when failed.
:param node: Dictionary created from topology.
:type node: dict
:returns: nothing.
:raises RuntimeError: If install dmm failed.
"""
arch = Topology.get_node_arch(node)
logger.console('Install... | 22,604 |
def get_args_and_hdf5_file(cfg):
"""
Assembles the command line arguments for training and the filename for the hdf5-file
with the results
:return: args, filename
"""
common_parameters = [
"--train:mode", "world",
"--train:samples", "256**3",
"--train:batchsize... | 22,605 |
def click_monitoring(e):
"""
monitoring click event
@input: event body
@output: None
"""
global click_count
global prev_dot_x
global prev_dot_y
dot = GOval(SIZE, SIZE, x=e.x - SIZE/2, y=e.y-SIZE/2)
dot.filled = True
dot.fill_color = "#00FFFF"
if click_coun... | 22,606 |
def make_hidden_file(file_path: pathlib.Path) -> None:
"""Make hidden file."""
if not file_path.name.startswith('.') and not is_windows():
file_path = file_path.parent / ('.' + file_path.name)
file_path.touch()
if is_windows():
atts = win32api.GetFileAttributes(str(file_path))
w... | 22,607 |
def get_orientation(y, num_classes=8, encoding='one_hot'):
"""
Args:
y: [B, T, H, W]
"""
# [H, 1]
idx_y = np.arange(y.shape[2]).reshape([-1, 1])
# [1, W]
idx_x = np.arange(y.shape[3]).reshape([1, -1])
# [H, W, 2]
idx_map = np.zeros([y.shape[2], y.shape[3], 2])
idx_map[:, ... | 22,608 |
def plot_tempo_curve(f_tempo, t_beat, ax=None, figsize=(8, 2), color='k', logscale=False,
xlabel='Time (beats)', ylabel='Temp (BPM)', xlim=None, ylim=None,
label='', measure_pos=[]):
"""Plot a tempo curve
Notebook: C3/C3S3_MusicAppTempoCurve.ipynb
Args:
f_... | 22,609 |
def not_pathology(data):
"""Return false if the node is a pathology.
:param dict data: A PyBEL data dictionary
:rtype: bool
"""
return data[FUNCTION] != PATHOLOGY | 22,610 |
def remove_index_fastqs(fastqs,fastq_attrs=IlluminaFastqAttrs):
"""
Remove index (I1/I2) Fastqs from list
Arguments:
fastqs (list): list of paths to Fastq files
fastq_attrs (BaseFastqAttrs): class to use for
extracting attributes from Fastq names
(defaults to IlluminaFastqAttrs)... | 22,611 |
def max(name: "Union[str, List[Expr]]") -> "Expr":
"""
Get maximum value
"""
if isinstance(name, list):
def max_(acc: Series, val: Series) -> Series:
mask = acc < val
return acc.zip_with(mask, val)
return fold(lit(0), max_, name).alias("max")
return col(name... | 22,612 |
def initialize(Lx, Ly,
solutes, restart_folder,
field_to_subspace,
concentration_init, rad,
enable_NS, enable_EC,
dx,
surface_charge,
permittivity,
**namespace):
""" Create the initial state. """
... | 22,613 |
def main() -> None:
"""Watch files for changes and rebuild."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
add_parser_arguments(parser)
args = parser.parse_args()
path_to_log, event_handler, exclude_list = watch_setup(... | 22,614 |
def _get_sentry_sdk():
"""Creates raven.Client instance configured to work with cron jobs."""
# NOTE: this function uses settings and therefore it shouldn't be called
# at module level.
try:
sentry_sdk = __import__("sentry_sdk")
DjangoIntegration = __import__(
"sentry_s... | 22,615 |
def handle_network() -> None:
"""
Helper for handling network events on all backends
"""
for backend in dict(BACKENDS).values():
backend.handle_network() | 22,616 |
def get_memos():
"""
Returns all memos in the database, in a form that
can be inserted directly in the 'session' object.
"""
records = [ ]
for record in collection.find( { "type": "dated_memo" } ):
record['date'] = arrow.get(record['date']).isoformat()
del record['_id']
r... | 22,617 |
def filepath(folder, *args, ext='pkl'):
"""Returns the full path of the file with the calculated results
for the given dataset, descriptor, descriptor of the given dataset
Parameters
----------
folder : string
Full path of the folder where results are saved.
args : list or tuple... | 22,618 |
def assert_type(name: str, val: Any, cls: Any):
"""
Raise an informative error if the passed value isn't of the given type.
Args:
name: User-friendly name of the value to be printed in an exception if raised.
val: The value to check type of.
cls: The type to compare the value's type again... | 22,619 |
def run_vacuum_tasks_table():
"""Run vacuum to reclaim storage."""
logger.info("Start vacuum on tasks table.")
p_con = auth.postgresDB()
# isolation_level 0 will move you out of a transaction block
old_isolation_level = p_con._db_connection.isolation_level
p_con._db_connection.set_isolation_leve... | 22,620 |
def psplit(df, idx, label):
"""
Split the participants with a positive label in df into two sets, similarly for participants with a negative label. Return two numpy arrays of participant ids, each array are the chosen id's to be removed from two dataframes to ensure no overlap of participants between the two se... | 22,621 |
def se_block(inputs, out_node, scope=None):
# TODO: check feature shape and dimension
"""SENet"""
with tf.variable_scope(scope, "se_block", reuse=tf.AUTO_REUSE):
channel = inputs.get_shape().as_list()[3]
net = tf.reduce_mean(inputs, [1,2], keep_dims=False)
net = fc_layer(net, [channel, out_node]... | 22,622 |
def deri_cie_ionfrac(Zlist, condifile='adia.exp_phy.info', \
condi_index=False, appfile=False, outfilename=False, rootpath=False):
"""
Derive the CIE ionic fraction based on the physical conditions in
an ASCII file. The only input parameter is the index (array) of
the elements.
Parameters
----------
Z... | 22,623 |
def get_numpy_include_dirs(sconscript_path):
"""Return include dirs for numpy.
The paths are relatively to the setup.py script path."""
from numscons import get_scons_build_dir
scdir = pjoin(get_scons_build_dir(), pdirname(sconscript_path))
n = scdir.count(os.sep)
dirs = _incdir()
rdirs = ... | 22,624 |
def invU(U):
"""
Calculate inverse of U Cell.
"""
nr, nc = U.getCellsShape()
mshape = U.getMatrixShape()
assert (nr == nc), "U Cell must be square!"
nmat = nr
u_tmp = admmMath.copyCell(U)
u_inv = admmMath.Cells(nmat, nmat)
for i in range(nmat):
for j in range(nmat):... | 22,625 |
def liq_g(drvt,drvp,temp,pres):
"""Calculate liquid water Gibbs energy using F03.
Calculate the specific Gibbs free energy of liquid water or its
derivatives with respect to temperature and pressure using the
Feistel (2003) polynomial formulation.
:arg int drvt: Number of temperature deriv... | 22,626 |
def read(fname):
"""
Utility function to read the README file.
Used for the long_description. It's nice, because now 1) we have a top
level README file and 2) it's easier to type in the README file than to put
a raw string in below ...
"""
with open(os.path.join(os.path.dirname(__file__), f... | 22,627 |
def get_tcp_client(tcp_server_address: str, tcp_server_port: int, session_handler: SessionHandler):
"""Returns the TCP client used in the 15118 communication.
:param tcp_server_address: The TCP server address.
:param tcp_server_port: The TCP server port.
:param session_handler: The session handler that... | 22,628 |
def extract_dates(obj):
"""extract ISO8601 dates from unpacked JSON"""
if isinstance(obj, dict):
new_obj = {} # don't clobber
for k,v in iteritems(obj):
new_obj[k] = extract_dates(v)
obj = new_obj
elif isinstance(obj, (list, tuple)):
obj = [ extract_dates(o) for o... | 22,629 |
def construct_covariates(states, model_spec):
"""Construct a matrix of all the covariates
that depend only on the state space.
Parameters
---------
states : np.ndarray
Array with shape (num_states, 8) containing period, years of schooling,
the lagged choice, the years of experience ... | 22,630 |
def clone(pkgbase):
"""Clone or update a git repo.
.. versionadded:: 4.0.0
"""
if os.path.exists('./{0}/'.format(pkgbase)):
if os.path.exists('./{0}/.git'.format(pkgbase)):
# git repo, pull
try:
os.chdir(pkgbase)
subprocess.check_call(['gi... | 22,631 |
def target_ok(target_file, *source_list):
"""Was the target file created after all the source files?
If so, this is OK.
If there's no target, or the target is out-of-date,
it's not OK.
"""
try:
mtime_target = datetime.datetime.fromtimestamp(
target_file.stat().st_mtime)
e... | 22,632 |
def check_oblique_montante(grille, x, y):
"""Alignements diagonaux montants (/) : allant du coin bas gauche au coin haut droit"""
symbole = grille.grid[y][x]
# Alignement diagonal montant de la forme XXX., le noeud (x,y) étant le plus bas et à gauche
if grille.is_far_from_top(y) and grille.is_far_from_r... | 22,633 |
def main(argv, name):
"""wrapper to mkmasks"""
ntasks = -1
ncores = -1
groupsize = -1
htcores = False
readable = False
try:
opts, _ = getopt.getopt(argv, "ht:c:g:xv")
except getopt.GetoptError:
print_help(name)
sys.exit(2)
for opt, arg in opts:
if opt... | 22,634 |
def _rotate_the_grid(lon, lat, rot_1, rot_2, rot_3):
"""Rotate the horizontal grid at lon, lat, via rotation matrices rot_1/2/3
Parameters
----------
lon, lat : xarray DataArray
giving longitude, latitude in degrees of LLC horizontal grid
rot_1, rot_2, rot_3 : np.ndarray
rotation ma... | 22,635 |
def dict_mapper(data):
"""Mapper from `TypeValueMap` to :class`dict`"""
out = {}
for k, v in data.items():
if v.type in (iceint.TypedValueType.TypeDoubleComplex,
iceint.TypedValueType.TypeFloatComplex):
out[k] = complex(v.value.real, v.value.imag)
elif v.typ... | 22,636 |
def predict_walkthrough_actions():
""" Given the observation, predict the next action from the walkthrough. """
action_predictor = lambda obs: choice(['n','s','e','w'])
rom = '/home/matthew/workspace/text_agents/roms/zork1.z5'
bindings = load_bindings(rom)
env = FrotzEnv(rom, seed=bindings['seed'])... | 22,637 |
def parse_prophage_tbl(phispydir):
"""
Parse the prophage table and return a dict of objects
:param phispydir: The phispy directory to find the results
:return: dict
"""
if not os.path.exists(os.path.join(phispydir, "prophage.tbl")):
sys.stderr.write("FATAL: The file prophage.tbl does n... | 22,638 |
async def get_odds(database, params):
"""Get odds based on parameters."""
LOGGER.info("generating odds")
start_time = time.time()
players = [dict(
civilization_id=data['civilization_id'],
user_id=data['user_id'],
winner=data['winner'],
team_id=data['team_id']
) for d... | 22,639 |
def split_by_normal(cpy):
"""split curved faces into one face per triangle (aka split by
normal, planarize). in place"""
for name, faces in cpy.iteritems():
new_faces = []
for points, triangles in faces:
x = points[triangles, :]
normals = np.cross(x[:, 1]-x[:, 0], x[:... | 22,640 |
def generate_index_distribution_from_blocks(numTrain, numTest, numValidation, params):
""" Generates a vector of indices to partition the data for training.
NO CHECKING IS DONE: it is assumed that the data could be partitioned
in the specified block quantities and that the block quantities describe ... | 22,641 |
def sct2e(sc, sclkdp):
"""sct2e(SpiceInt sc, SpiceDouble sclkdp)"""
return _cspyce0.sct2e(sc, sclkdp) | 22,642 |
def test_check_flow_data17():
""" input flow out of flow index"""
with pytest.raises(AssertionError) as err_info:
PyDampCheck.check_flow_data(flow_fail_17)
assert str(err_info.value) == 'component 3 function 2 input in not in range of the flow index' | 22,643 |
def test_main(monkeypatch, test_dict: FullTestDict):
"""
- GIVEN a list of words
- WHEN the accent dict is generated
- THEN check all the jisho info is correct and complete
"""
word_list = convert_list_of_str_to_kaki(test_dict['input'])
sections = test_dict['jisho']['expected_sections']
... | 22,644 |
def main():
""" Create object and call apply """
ntp_obj = NetAppOntapNTPServer()
ntp_obj.apply() | 22,645 |
def normalizeFilename(filename):
"""Take a given filename and return the normalized version of it.
Where ~/ is expanded to the full OS specific home directory and all
relative path elements are resolved.
"""
result = os.path.expanduser(filename)
result = os.path.abspath(result)
return result | 22,646 |
def do_plugin_create(cc, args):
"""Register a new plugin with the Iotronic service."""
field_list = ['name', 'code', 'callable', 'public', 'extra']
fields = dict((k, v) for (k, v) in vars(args).items()
if k in field_list and not (v is None))
fields = utils.args_array_to_dict(fields,... | 22,647 |
def get_tn(tp, fp, fn, _all):
"""
Args:
tp (Set[T]):
fp (Set[T]):
fn (Set[T]):
_all (Iterable[T]):
Returns:
Set[T]
"""
return set(_all) - tp - fp - fn | 22,648 |
def test_posdef_symmetric3():
""" The test return 0 if the matrix has 0 eigenvalue.
Is this correct?
"""
data = np.array([[1.,1],[1,1]], dtype = theano.config.floatX)
assert mv.posdef(data) ==0 | 22,649 |
def download_cow_head():
"""Download cow head dataset."""
return _download_and_read('cowHead.vtp') | 22,650 |
def select_tests(blocks, match_string_list, do_test):
"""Remove or keep tests from list in WarpX-tests.ini according to do_test variable"""
if do_test not in [True, False]:
raise ValueError("do_test must be True or False")
if (do_test == False):
for match_string in match_string_list:
... | 22,651 |
def get_last_ds_for_site(session, idescr: ImportDescription, col: ImportColumn, siteid: int):
"""
Returns the newest dataset for a site with instrument, valuetype and level fitting to the ImportDescription's column
To be used by lab imports where a site is encoded into the sample name.
"""
q = sess... | 22,652 |
def main():
""" Main Program """
pygame.init()
# Set the height and width of the screen
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Dino")
# Create all the levels
level_list = []
level_list.append(Level(VIEW_RECT, TILE_WI... | 22,653 |
def test_eq_issue62_last_component_not_va():
"""
VA is not last when components are sorted alphabetically.
"""
test_tdb = """
ELEMENT VA VACUUM 0.0000E+00 0.0000E+00 0.0000E+00!
ELEMENT AL FCC_A1 2.6982E+01 4.5773E+03 2.8322E+01!
ELEMENT CO HCP... | 22,654 |
def get_cart_from_request(request, cart_queryset=Cart.objects.all()):
"""Get cart from database or return unsaved Cart
:type cart_queryset: saleor.cart.models.CartQueryset
:type request: django.http.HttpRequest
:rtype: Cart
"""
if request.user.is_authenticated():
cart = get_user_cart(req... | 22,655 |
def _is_ge(series, value):
""" Returns the index of rows from series where series >= value.
Parameters
----------
series : pandas.Series
The data to be queried
value : list-like
The values to be tested
Returns
-------
index : pandas.index
The index of series fo... | 22,656 |
def preprocess_image(image, image_size, is_training=False, test_crop=True):
"""Preprocesses the given image.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: Size of output image.
is_training: `bool` for whether the preprocessing is for training.
test_crop: whether or not ... | 22,657 |
async def wait_for_reaction(self, message):
""" Assert that ``message`` is reacted to with any reaction.
:param discord.Message message: The message to test with
:returns: The reaction object.
:rtype: discord.Reaction
:raises NoReactionError:
"""
def check_reaction(reaction, user):
... | 22,658 |
def test_get_active_invalid_key():
"""
gets the value of given key which is unavailable from
active section of given config store.
it should raise an error.
"""
with pytest.raises(ConfigurationStoreKeyNotFoundError):
config_services.get_active('environment', 'missing_key') | 22,659 |
def test_isclose(func_interface):
"""Tests for numpoly.isclose."""
poly1 = numpoly.polynomial([1e10*X, 1e-7])
poly2 = numpoly.polynomial([1.00001e10*X, 1e-8])
assert_equal(func_interface.isclose(poly1, poly2), [True, False])
poly1 = numpoly.polynomial([1e10*X, 1e-8])
poly2 = numpoly.polynomial([... | 22,660 |
def _multivariate_normal_log_likelihood(X, means=None, covariance=None):
"""Calculate log-likelihood assuming normally distributed data."""
X = check_array(X)
n_samples, n_features = X.shape
if means is None:
means = np.zeros_like(X)
else:
means = check_array(means)
asser... | 22,661 |
def show_hdf5_structure(filename, filepath=''):
"""
Show madrigal hdf5 file structure in console.
Example:
fn = "/home/leicai/01_work/00_data/madrigal/DMSP/20151102/dms_20151102_16s1.001.hdf5"
show_structure(fn)
"""
with h5py.File(os.path.join(filepath, filename), 'r') as fh5:
... | 22,662 |
def morethan(kt,n):
"""
Arguments:
- `n`:
"""
total = 0
temp = 0
r = 0
for (word,k) in kt:
total += k
if k > n:
r += 1
temp += k
print "出现频率大于%s的词共有%s个"%(n,r)
print "占总的标记百分比%s"%(1.0*temp/total)
print 20*"=" | 22,663 |
def lemmatize(text):
"""
tokenize and lemmatize english messages
Parameters
----------
text: str
text messages to be lemmatized
Returns
-------
list
list with lemmatized forms of words
"""
def get_wordnet_pos(treebank_tag):
if treebank_tag.startswith('J'... | 22,664 |
def prune_non_overlapping_boxes(boxes1, boxes2, min_overlap):
"""Prunes the boxes in boxes1 that overlap less than thresh with boxes2.
For each box in boxes1, we want its IOA to be more than min_overlap with
at least one of the boxes in boxes2. If it does not, we remove it.
Arguments:
boxes1: a... | 22,665 |
def get_namespace_from_node(node):
"""Get the namespace from the given node
Args:
node (str): name of the node
Returns:
namespace (str)
"""
parts = node.rsplit("|", 1)[-1].rsplit(":", 1)
return parts[0] if len(parts) > 1 else u":" | 22,666 |
def PricingStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | 22,667 |
def test_to_string():
"""test if a credit card outputs the right to str value"""
credit_card = CreditCard(
number = '4111111111111111',
exp_mo = '02',
exp_yr = '2012',
first_name = 'John',
last_name = 'Doe',
cvv = '911',
strict ... | 22,668 |
def get_structures(defect_name: str,
output_path: str,
bdm_increment: float=0.1,
bdm_distortions: list = None,
bdm_type="BDM",
):
"""Imports all the structures found with BDM and stores them in a dictionary matching BDM... | 22,669 |
def create_whimsy_value_at_clients(number_of_clients: int = 3):
"""Returns a Python value and federated type at clients."""
value = [float(x) for x in range(10, number_of_clients + 10)]
type_signature = computation_types.at_clients(tf.float32)
return value, type_signature | 22,670 |
def format_task_numbers_with_links(tasks):
"""Returns formatting for the tasks section of asana."""
project_id = data.get('asana-project', None)
def _task_format(task_id):
if project_id:
asana_url = tool.ToolApp.make_asana_url(project_id, task_id)
return "[#%d](%s)" % (task... | 22,671 |
def get_tick_indices(tickmode, numticks, coords):
"""
Ticks on the axis are a subset of the axis coordinates
This function returns the indices of y coordinates on which a tick should be displayed
:param tickmode: should be 'auto' (automatically generated) or 'all'
:param numticks: minimum number of ... | 22,672 |
def fpIsNormal(a, ctx=None):
"""Create a Z3 floating-point isNormal expression.
"""
return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx) | 22,673 |
def test_bench():
"""Runs benchmarks before and after and compares the results."""
os.chdir(get_repo_root_path())
# Get numbers for current HEAD.
return_code, stdout, stderr = _run_cargo_bench(PR_BENCH_RESULTS_FILE)
# Even if it is the first time this test is run, the benchmark tests should pass.
... | 22,674 |
def test_extract_command():
"""
Test the command-line script extract feature
"""
with mock.patch('uflash.extract') as mock_extract:
uflash.main(argv=['-e', 'hex.hex', 'foo.py'])
mock_extract.assert_called_once_with('hex.hex', ['foo.py']) | 22,675 |
def existingFile(filename):
""" 'type' for argparse - check that filename exists """
if not os.path.exists(filename):
raise argparse.ArgumentTypeError("{0} does not exist".format(filename))
return filename | 22,676 |
def test_get_by_id() -> None:
"""Tests fetching a match by ID."""
match = Match()
assert Match.get_by_id(match.id) is None
match.put_in_pool()
assert Match.get_by_id(match.id) is match | 22,677 |
def app():
"""
Setup our flask test app, this only gets executed once.
:return: Flask app
"""
_app = create_app("testing")
# Establish an application context before running the tests.
ctx = _app.app_context()
ctx.push()
yield _app
ctx.pop() | 22,678 |
def siqs_find_next_poly(n, factor_base, i, g, B):
"""Compute the (i+1)-th polynomials for the Self-Initialising
Quadratic Sieve, given that g is the i-th polynomial.
"""
v = lowest_set_bit(i) + 1
z = -1 if math.ceil(i / (2 ** v)) % 2 == 1 else 1
b = (g.b + 2 * z * B[v - 1]) % g.a
a = g.a
... | 22,679 |
def get_column(value):
"""Convert column number on command line to Python index."""
if value.startswith("c"):
# Ignore c prefix, e.g. "c1" for "1"
value = value[1:]
try:
col = int(value)
except:
stop_err("Expected an integer column number, not %r" % value)
if col < 1:... | 22,680 |
def sdi(ts_split, mean=False, keys=None):
"""
Compute the Structural Decoupling Index (SDI).
i.e. the ratio between the norms of the "high" and the norm of the "low"
"graph-filtered" timeseries.
If the given dictionary does not contain the keywords "high" and "low",
the SDI is computed as the ... | 22,681 |
def Class_Property (getter) :
"""Return a descriptor for a property that is accessible via the class
and via the instance.
::
>>> from _TFL._Meta.Property import *
>>> from _TFL._Meta.Once_Property import Once_Property
>>> class Foo (object) :
... @Class_Property
... | 22,682 |
def initialize_third_party():
"""Load common dependencies."""
spdlog()
catch2()
fmt() | 22,683 |
def naive_act_norm_initialize(x, axis):
"""Compute the act_norm initial `scale` and `bias` for `x`."""
x = np.asarray(x)
axis = list(sorted(set([a + len(x.shape) if a < 0 else a for a in axis])))
min_axis = np.min(axis)
reduce_axis = tuple(a for a in range(len(x.shape)) if a not in axis)
var_sha... | 22,684 |
def cmpTensors(t1, t2, atol=1e-5, rtol=1e-5, useLayout=None):
"""Compare Tensor list data"""
assert (len(t1) == len(t2))
for i in range(len(t2)):
if (useLayout is None):
assert(t1[i].layout == t2[i].layout)
dt1 = t1[i].dataAs(useLayout)
dt2 = t2[i].dataAs(useLayout)
... | 22,685 |
def auth(body): # noqa: E501
"""Authenticate endpoint
Return a bearer token to authenticate and authorize subsequent calls for resources # noqa: E501
:param body: Request body to perform authentication
:type body: dict | bytes
:rtype: Auth
"""
db = get_db()
cust = db['Customer'].find... | 22,686 |
def make_feature(func, *argfuncs):
"""Return a customized feature function that adapts to different input representations.
Args:
func: feature function (callable)
argfuncs: argument adaptor functions (callable, take `ctx` as input)
"""
assert callable(func)
for argfunc in argfuncs:
... | 22,687 |
def from_numpy(np_array: np.ndarray):
"""Convert a numpy array to another type of dlpack compatible array.
Parameters
----------
np_array : np.ndarray
The source numpy array that will be converted.
Returns
-------
pycapsule : PyCapsule
A pycapsule containing a DLManagedTens... | 22,688 |
def rename(bot, msg):
"""Rename a shorturl."""
old_slug = msg.match.group(1)
new_slug = msg.match.group(2)
with shorturl_db(user='ocfircbot', password=bot.mysql_password) as ctx:
rename_shorturl(ctx, old_slug, new_slug)
msg.respond(f'shorturl `{old_slug}` has been renamed to `{new_slug... | 22,689 |
def lmsSubstringsAreEqual(string, typemap, offsetA, offsetB):
"""
Return True if LMS substrings at offsetA and offsetB are equal.
"""
# No other substring is equal to the empty suffix.
if offsetA == len(string) or offsetB == len(string):
return False
i = 0
while True:
aIsLMS... | 22,690 |
def validate_config(*, config: Any) -> None:
"""
Validate a config.
Args:
config: the config.
Raises:
InvalidConfig: when the config isn't valid.
"""
default_schema = schema.Schema(
{
"static_url": str,
schema.Optional("favicon_ico"): schema.Or(N... | 22,691 |
def synthesize_photometry(lbda, flux, filter_lbda, filter_trans,
normed=True):
""" Get Photometry from the given spectral information through the given filter.
This function converts the flux into photons since the transmission provides the
fraction of photons that goes though.
... | 22,692 |
def get_A_dash_floor_bath(house_insulation_type, floor_bath_insulation):
"""浴室の床の面積 (m2)
Args:
house_insulation_type(str): 床断熱住戸'または'基礎断熱住戸'
floor_bath_insulation(str): 床断熱住戸'または'基礎断熱住戸'または'浴室の床及び基礎が外気等に面していない'
Returns:
float: 浴室の床の面積 (m2)
"""
return get_table_3(15, house_insula... | 22,693 |
def cancel_task_async(hostname, task_id):
"""Cancels a swarming task."""
return _call_api_async(
None, hostname, 'task/%s/cancel' % task_id, method='POST') | 22,694 |
def generate_two_files_both_stress_strain():
"""Generates two files that have both stress and strain in each file"""
fname = {'stress': 'resources/double_stress.json',
'strain': 'resources/double_strain.json'}
expected = [ # makes an array of two pif systems
pif.System(
pro... | 22,695 |
async def test_template_with_delay_on_based_on_input(hass):
"""Test binary sensor template with template delay on based on input number."""
config = {
"binary_sensor": {
"platform": "template",
"sensors": {
"test": {
"friendly_name": "virtual t... | 22,696 |
def run_cli(entry_point, *arguments, **options):
"""
Test a command line entry point.
:param entry_point: The function that implements the command line interface
(a callable).
:param arguments: Any positional arguments (strings) become the command
line argu... | 22,697 |
def recipe_edit(username, pk):
"""Page showing the possibility to edit the recipe."""
recipe_manager = RecipeManager(api_token=g.user_token)
response = recipe_manager.get_recipe_response(pk)
recipe = response.json()
# shows 404 if there is no recipe, response status code is 404 or user is not the au... | 22,698 |
def test_document_request_get_issuer():
"""Test the `DocumentRequest.get_issuer()` method"""
document_request = factories.DocumentRequestFactory(
issuer="marion.issuers.DummyDocument",
context_query={"fullname": "Richie Cunningham"},
)
assert isinstance(document_request.get_issuer(), i... | 22,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.