content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def delete_user(user_id: int):
"""删除"""
user = User.query.filter(
User.user_id == user_id
).first()
if not user:
return dbu.inner_error("该不存在或已被删除")
db.session.delete(user)
try:
db.session.commit()
except Exception as e:
current_app.logger.warning(e)
... | 5,324,400 |
def _combine_odds(odds):
"""Combine odds of different targets."""
combined_odds = 1 / (1 / odds).sum(axis=1)
return combined_odds | 5,324,401 |
def db(port, dirpath):
"""Run HTTP api/database server"""
env = environ.copy()
if port is not None:
env["MLRUN_httpdb__port"] = str(port)
if dirpath is not None:
env["MLRUN_httpdb__dirpath"] = dirpath
cmd = [executable, "-m", "mlrun.api.main"]
child = Popen(cmd, env=env)
ret... | 5,324,402 |
def deleteAndMove(dir, files='*.fits'):
"""
:param dir:
:param files:
:return:
"""
if not os.path.exists(dir):
os.makedirs(dir)
else:
for f in glob.glob(dir + '/' + files):
os.remove(f)
for f in glob.glob(files):
shutil.move(f, './'+dir+'/'+f) | 5,324,403 |
def decrypt(pp, skx, cty, max_innerprod=100):
"""
Performs the decrypt algorithm for IPE on a secret key skx and ciphertext cty.
The output is the inner product <x,y>, so long as it is in the range
[0,max_innerprod].
"""
(k1, k2) = skx
(c1, c2) = cty
d1 = pair(k1, c1)
d2 = innerpro... | 5,324,404 |
def alpha_blend_colors(colors, additional_alpha=1.0):
"""
Given a sequence of colors, return the alpha blended color.
This assumes the last color is the one in front.
"""
srcr, srcg, srcb, srca = COLOR_CONVERTER.to_rgba(colors[0])
srca *= additional_alpha
for color in colors[1:]:
... | 5,324,405 |
def ruled(nrb1, nrb2):
"""
Construct a ruled surface/volume
between two NURBS curves/surfaces.
Parameters
----------
nrb1, nrb2 : NURBS
"""
assert nrb1.dim == nrb2.dim
assert nrb1.dim <= 2
assert nrb2.dim <= 2
nrb1, nrb2 = compat(nrb1, nrb2)
Cw = np.zeros(nrb1.shape+(2,... | 5,324,406 |
async def db_head_state():
"""Status/health check."""
sql = ("SELECT num, created_at, extract(epoch from created_at) ts "
"FROM hive_blocks ORDER BY num DESC LIMIT 1")
row = DB.query_row(sql)
return dict(db_head_block=row['num'],
db_head_time=str(row['created_at']),
... | 5,324,407 |
def d_d_theta_inv(y, alpha):
"""
xi'(y) = 1/theta''(xi(y)) > 0
= alpha / (1 - |y|)^2
Nikolova et al 2014, table 1, theta_2 and eq 5.
"""
assert -1 < y < 1 and alpha > 0
denom = 1 - abs(y)
return alpha / (denom*denom) | 5,324,408 |
async def add_item(
item: ItemEditableFields,
db_session: Session = Depends(get_db_session)
):
"""This handler adds item to the DB.
Args:
item: ItemEditableFields. The data of item to be added to the DB.
db_session: Session. The database session used to interact with the DB.
... | 5,324,409 |
def center_crop(img, crop_height, crop_width):
""" Crop the central part of an image.
Args:
img (ndarray): image to be cropped.
crop_height (int): height of the crop.
crop_width (int): width of the crop.
Return:
(ndarray): the cropped image.
"""
def get_center_crop_... | 5,324,410 |
def p_py_atom_1(p):
"""py_atom : ID
| ICONST
| FCONST
| SCONST_D
| SCONST_S"""
p[0] = p[1] | 5,324,411 |
def list_medical_transcription_jobs(Status=None, JobNameContains=None, NextToken=None, MaxResults=None):
"""
Lists medical transcription jobs with a specified status or substring that matches their names.
See also: AWS API Documentation
Exceptions
:example: response = client.list_medical_t... | 5,324,412 |
def membOutDet(input_slc, cell_mask=10, outer_mask=30, det_cutoff=0.75):
""" Detection of mYFP maxima in the line of interest.
Algorithm is going from outside to inside cell
and finding first outer maxima of the membrane.
"cell_mask" - option for hiding inner cell region
for ignoring possible cytop... | 5,324,413 |
def cmk_arn_value(variable_name):
"""Retrieve target CMK ARN from environment variable."""
arn = os.environ.get(variable_name, None)
if arn is None:
raise ValueError(
'Environment variable "{}" must be set to a valid KMS CMK ARN for examples to run'.format(
variable_name
... | 5,324,414 |
def qaoa_ansatz(gammas, betas):
"""
Function that returns a QAOA ansatz program for a list of angles betas and gammas. len(betas) ==
len(gammas) == P for a QAOA program of order P.
:param list(float) gammas: Angles over which to parameterize the cost Hamiltonian.
:param list(float) betas: Angles ov... | 5,324,415 |
def test_atomic_any_uri_length_2_nistxml_sv_iv_atomic_any_uri_length_3_5(mode, save_output, output_format):
"""
Type atomic/anyURI is restricted by facet length with value 34.
"""
assert_bindings(
schema="nistData/atomic/anyURI/Schema+Instance/NISTSchema-SV-IV-atomic-anyURI-length-3.xsd",
... | 5,324,416 |
def print_header(procs_status, num_procs):
"""Print system-related info, above the process list."""
def get_dashes(perc):
dashes = "|" * int((float(perc) / 10 * 4))
empty_dashes = " " * (40 - len(dashes))
return dashes, empty_dashes
# cpu usage
percs = psutil.cpu_percent(interv... | 5,324,417 |
def approximated_atmo_spectrum(energy):
"""Gives an approximated atmospheric neutrino spectrum.
Can be used for comparing expected true energy distribution to recorded
energy proxy distributions. It is normalised such that the weight for an
energy of 1 is equal to 1. (It is agnostic to energy units)
... | 5,324,418 |
def test_delete_token():
"""Delete Token"""
soup = TexSoup(r"""
\section{one}
text
\section{two}
delete me""")
assert 'delete me' in str(soup)
for node in soup.all:
if 'delete me' in node:
node.delete()
assert 'delete me' not in str(soup) | 5,324,419 |
def to_csv(logbook, filename, output=False):
"""
Write a logbook to a CSV file.
The output file is readable using an ordinary CSV reader, e.g. ``pandas.read_csv``.
Alternatively you may read it back into a logbook format using ``gt.ops.from_csv``.
"""
logs = []
for unique_trip_id in log... | 5,324,420 |
def flatten_dict(d, parent_key="", sep="_"):
"""
Flatten a dictionnary
"""
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if v and isinstance(v, collections.MutableMapping):
items.extend(flatten_dict(v, new_key, sep=sep).items())
... | 5,324,421 |
def request_mxnet_inference(ip_address="127.0.0.1", port="80", connection=None, model="squeezenet"):
"""
Send request to container to test inference on kitten.jpg
:param ip_address:
:param port:
:connection: ec2_connection object to run the commands remotely over ssh
:return: <bool> True/False b... | 5,324,422 |
def flatten(iterable):
""" Flattens an iterable, where strings and dicts
are not considered iterable.
:param iterable: The iterable to flatten.
:returns: The iterable flattened as a flat list.
>>> from dautils import collect
>>> collect.flatten([[1, 2]])
[1, 2]
"""
logger = log_ap... | 5,324,423 |
def get_ts_pid(pidfile):
"""Read a pidfile, return a PID."""
try:
with open(pidfile) as f:
pid = f.readline()
except EnvironmentError:
LOG.warning("Unable to read pidfile; process metrics will fail!")
pid = None
return pid | 5,324,424 |
def conjg(a):
"""
Find the complex conjugate values of the input.
Parameters
----------
a : af.Array
Multi dimensional arrayfire array.
Returns
--------
out : af.Array
array containing copmplex conjugate values from `a`.
"""
return _arith_unary_func(a, backend.... | 5,324,425 |
def obj_size_avg_residual(coeffs, avg_size, class_id):
"""
:param coeffs: object sizes
:param size_template: dictionary that saves the mean size of each category
:param class_id: nyu class id.
:return: size residual ground truth normalized by the average size
"""
size_residual = (coeffs - av... | 5,324,426 |
def search_content(obj):
"""Get the excerpt in which the searched term matches the content."""
indexable_text = []
if hasattr(obj, 'excerpt'):
if obj.excerpt:
indexable_text.append(obj.excerpt)
if not hasattr(obj, 'content_editor'):
return ' '.join(indexable_text)
conte... | 5,324,427 |
def get_total_num_activities():
"""Query the IATI registry and return a faceted list of activity counts and their frequencies.
The total number of activities is then calculated as the sum of the product of a count and a frequency.
E.g. if "30" is the count and the frequency is 2, then the total number of a... | 5,324,428 |
def _get_chromosome_dirs(input_directory):
"""Collect chromosome directories"""
dirs = []
for d in input_directory.iterdir():
if not d.is_dir():
continue
# Just in case user re-runs and
# does not delete output files
elif d.name == 'logs':
continue
... | 5,324,429 |
def calculateCumTimeDiff(df):
"""
Calculates the cumulative of the time difference
between points for each track of 'dfTrack'.
"""
warnings.warn("The calculateCumTimeDiff function is deprecated and "
"will be removed in version 2.0.0. "
"Use the calculate_cum_time... | 5,324,430 |
def optimalPriceFast(z_list, V_list, U, s_radius, max_iter = 1e4):
""" Returns tuple of optimal prices p^* chosen in hindsight, and revenue achieved
if we know z_t (list of 1-D arrays) V_t (list of 2-D arrays),
and U (2-D array) is Orthogonal!
Performs optimization over low-dimensional acti... | 5,324,431 |
def push(repo: Repository, remote, branch):
"""Upload local BRANCH commit history / data to REMOTE server.
"""
commit_hash = repo.remote.push(remote=remote, branch=branch)
click.echo(f'Push data for commit hash: {commit_hash}') | 5,324,432 |
def extract_seqIdList_from_cluster(cluster_name, cluster_dic, extract_id, allSeqDf, idName, match_method="contains"):
"""
For all sequences in a cluster, find corresponding sequences in the dataframe.
The extract_id function is used to extract a id that will be used to
find the matching entry in th... | 5,324,433 |
def format_imports(import_statements):
"""
-----
examples:
@need
from fastest.constants import TestBodies
@end
@let
import_input = TestBodies.TEST_STACK_IMPORTS_INPUT
output = TestBodies.TEST_STACK_IMPORTS_OUTPUT
@end
1) format_imports(import_input) -> output
-----
:... | 5,324,434 |
def parse_modmap(lines):
"""Parse a modmap file."""
re_range = re.compile(r'KeyCodes range from (\d+) to')
lower_bound = 8
re_line = re.compile(r'^\s+(\d+)\s+0x[\dA-Fa-f]+\s+(.*)')
re_remainder = re.compile(r'\((.+?)\)')
ret = ModMapper()
for line in lines.split('\n'):
if not line:
... | 5,324,435 |
def ParseFastq(pathstofastqs):
"""
:param pathstofastqs: list of list of fastq.
Given a list [] of fastq directories (uncompressed, gzip compressed or bz2 compressed), extract sequence ID, Sequence(s) and qualityscore(s) from it.
"""
for i in range(len(pathstofastqs)):
if pathstofastqs[i][0]... | 5,324,436 |
def read_evoked(fname, setno=None, baseline=None, kind='average', proj=True):
"""Read an evoked dataset
Parameters
----------
fname : string
The file name.
setno : int or str | list of int or str | None
The index or list of indices of the evoked dataset to read. FIF files
ca... | 5,324,437 |
def construct_lexically_addressed_lambda_tree(lambda_tree, surrounding_scope=None):
"""
Out of a "bare" LambdaTree constructs a LexicallyAddressedLambdaTree, i.e. a tree of lambdas where the nodes are
decorated with a dict like so:
{symbol: scopes_up_count}
It does this by going down the tree, cal... | 5,324,438 |
def integrate_vec(vec, time_dep=False, method='ss', **kwargs):
"""
Integrate (stationary of time-dependent) vector field (N-D Tensor) in tensorflow
Aside from directly using tensorflow's numerical integration odeint(), also implements
"scaling and squaring", and quadrature. Note that the diff. equatio... | 5,324,439 |
def get_all_news(num_page, limit):
"""Get all users"""
news = News.objects.paginate(page=num_page, per_page=limit)
response_object = {
'status': 'success',
'data': news.items,
}
return jsonify(response_object), 200 | 5,324,440 |
def correlations(X, y=None):
"""
given a pandas DataFrame returns correlation matrix and figure representing the correlations
:param y: [pandas Series] target column
:param X: [pandas DataFrame] predictor columns
:param size: matplotlib figure size
:return: correlation matrix and figure represen... | 5,324,441 |
def build_stream(subdir):
"""generate the stream templates"""
stream_types = ["uniform grid",
"amr grids",
"particles",
"octree",
"hexahedral mesh",
"unstructured mesh"]
if subdir is None:
subdir = ... | 5,324,442 |
def consensus():
"""
Resolve the blockchain based on consensus algorthim when multiple nodes are conencted
"""
replaced = blockchain.resolve_conflicts()
if replaced:
response = {
'message': 'Our chain was replaced',
'new_chain': blockchain.chain
}
else:
... | 5,324,443 |
def create_idletomography_report(results, filename, title="auto",
ws=None, auto_open=False, link_to=None,
brevity=0, advancedOptions=None, verbosity=1):
"""
Creates an Idle Tomography report, summarizing the results of running
idle tomography... | 5,324,444 |
def sha256_secrethash(secret: Secret) -> SecretHash:
"""Compute the secret hash using sha256."""
return SecretHash(sha256(secret).digest()) | 5,324,445 |
def make_http_request(method, url, check_response=None, *args, **kwargs):
"""
Make an HTTP request with the global session.
:return: The response object.
:raises: WebserviceException
"""
session = get_requests_session()
response = ClientBase._execute_func(lambda *args, **kwargs: ses... | 5,324,446 |
def get_pages_matches_no_prep(title, edition, archive, filename, text, keysentences):
"""
Get pages within a document that include one or more keywords.
For each page that includes a specific keyword, add a tuple of
form:
(<TITLE>, <EDITION>, <ARCHIVE>, <FILENAME>, <TEXT>, <KEYWORD>)
If a ... | 5,324,447 |
def sf(k, r, p):
"""
Survival function of the negative binomial distribution.
Parameters
----------
r : int
Number of failures until the experiment is stopped.
p : float
Probability of success.
"""
with mpmath.extradps(5):
k = mpmath.mpf(k)
r = mpmath.mpf... | 5,324,448 |
def _loglevel_signal_handler(loggers):
"""
Handle SIGUSR1 and SIGUSR2. Sets log level to INFO on SIGUSR1 and DEBUG on SIGUSR2.
After setting level, it calls the previous SIGUSRx handler unless it was set to SIG_DFL.
"""
usr_signals = {
signal.SIGUSR1: logging.INFO,
signal.SIGUSR2: l... | 5,324,449 |
def process_menu(menu: Menu, perms: PermWrapper) -> MenuGroup:
"""Enable a menu item if view permissions exist for the user."""
for group in menu.groups:
for item in group.items:
# Parse the URL template tag to a permission string.
app, scope = item.url.split(":")
obj... | 5,324,450 |
def _grid_in_property(field_name, docstring, read_only=False,
closed_only=False):
"""Create a GridIn property."""
def getter(self):
if closed_only and not self._closed:
raise AttributeError("can only get %r on a closed file" %
field_name... | 5,324,451 |
def Run(benchmark_spec):
"""Runs memtier against memcached and gathers the results.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
Returns:
A list of sample.Sample instances.
"""
client = benchmark_spec.vm_groups['client'][0]
ser... | 5,324,452 |
async def test_connection_error(
hass: HomeAssistant, mock_pvoutput_config_flow: MagicMock
) -> None:
"""Test API connection error."""
mock_pvoutput_config_flow.status.side_effect = PVOutputConnectionError
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SO... | 5,324,453 |
def query_leave(account_id, __, ___):
"""
This function deals with the problems related to leave query.
:param account_id: user account id.
"""
status, __, type, message = get_user_status(account_id)
if status == "wait_in":
set_user_status(account_id, status="none")
fmt = _("Here a... | 5,324,454 |
def get_trainer_class_from_model(parameter):
"""
>>> from IPython.lib.pretty import pprint
>>> from pb_bss.distribution.cacgmm import (
... ComplexAngularCentralGaussian,
... )
>>> get_trainer_class_from_model(ComplexAngularCentralGaussian).__name__
'ComplexAngularCentralGaussianTrainer'... | 5,324,455 |
def is_fractional_it(input_str, short_scale=False):
"""
This function takes the given text and checks if it is a fraction.
Updated to italian from en version 18.8.9
Args:
input_str (str): the string to check if fractional
short_scale (bool): use short scale if True, long scale if False
... | 5,324,456 |
def qchem2molgraph(logfile, return_qobj=False, return_none_on_err=False, **kwargs):
"""
Convert a Q-Chem logfile to a MolGraph object. Return the QChem
object in addition to the MolGraph if return_qobj is True. Catch
QChemError if return_none_on_err is True and return None. Options
in kwargs are pas... | 5,324,457 |
def extract_signals(data, fs, segmentation_times):
"""
Signal that given the set of segmentation times, extract the signal from the raw trace.
Args:
data : Numpy
The input seismic data containing both, start and end times of the seismic data.
fs : float
The sampling f... | 5,324,458 |
def main(results_path, network_config: dict, learningrate: int = 1e-3, weight_decay: float = 1e-5,
n_updates: int = int(1e5), device: torch.device = torch.device("cuda:0")):
"""Main function that takes hyperparameters and performs training and evaluation of model"""
# Prepare a path to plot to
os.m... | 5,324,459 |
def get_dataset(
file_pattern,
n_classes,
batch_size,
volume_shape,
plane,
n_slices=24,
block_shape=None,
n_epochs=None,
mapping=None,
shuffle_buffer_size=None,
num_parallel_calls=AUTOTUNE,
mode="train",
):
"""Returns tf.data.Dataset after preprocessing from
tfre... | 5,324,460 |
def cos_d(x:int)->float:
"""
This function takes in input in radians and returns the
computed derivaive of cos which is -sin.
"""
return -math.sin(x) | 5,324,461 |
def rhist(ax, data, **kwargs):
"""
Create a hist plot with default style parameters to look like ggplot2.
kwargs can be passed to changed other parameters.
"""
defaults = {'facecolor': '0.3',
'edgecolor': '0.36',
'linewidth': 1,
'rwidth': 1}
for ... | 5,324,462 |
def follow(request, username_to_follow):
"""View that is used to let the login user to follow another user"""
try:
# If the user is not all ready begin follwed
if not request.user.following.filter(username=username_to_follow).exists():
user_to_follow = get_object_or_404(User, usernam... | 5,324,463 |
def Neq(left: Expr, right: Expr) -> BinaryExpr:
"""Difference expression.
Checks if left != right.
Args:
left: A value to check.
right: The other value to check. Must evaluate to the same type as left.
"""
return BinaryExpr(Op.neq, right.type_of(), TealType.uint64, left, right) | 5,324,464 |
def load_core_settings():
"""Load core settings.
This function must be manually called (see :file:`urls.py`) in
order to load base settings.
"""
from django.utils.translation import ugettext_lazy
from modoboa.lib import parameters, events
from .app_settings import GeneralParametersForm
... | 5,324,465 |
def create_simplex_matrix(
dimensions: int,
distance: float) -> np.ndarray:
"""
Create centered normalized N-dimensional simplex structure
The structure is described by N+1, N-dimensional points that have the
same distance between them
:param dimensions: The number of dimensions of t... | 5,324,466 |
def asymmetric_lorentz_gauss_sum(x, mu, fwhm_l, fwhm_g, alpha=1.0, beta=1.5):
"""
asymmetric Lorentzian with Gauss convoluted
"""
ygaus = np.array(gauss_one(x, fwhm_g, mu))
ylorentz = np.array(asymmetric_lorentz(x, fwhm_l, mu, alpha=alpha, beta=beta))
ydata = ylorentz + ygaus
return ydata | 5,324,467 |
def main():
"""
Main entry point for module execution
"""
argument_spec = dict(
netbox_url=dict(type="str", required=True),
netbox_token=dict(type="str", required=True, no_log=True),
data=dict(type="dict", required=True),
state=dict(required=False, default="present", choi... | 5,324,468 |
def manage_delegations(d_spec, args, log, deployed, auth_spec):
"""
Create and manage cross account access delegations based on
delegation specifications. Manages delegation roles in
trusting accounts and group policies in Auth (trusted) account.
"""
log.debug('considering %s' % d_spec['RoleN... | 5,324,469 |
def access(path, mode):
"""Use the real uid/gid to test for access to path.
:type path: bytes | unicode
:type mode: int
:rtype: bool
"""
return False | 5,324,470 |
def _is_punctuation(char: str) -> bool:
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, for
#... | 5,324,471 |
def get_imports(filename, source=None):
"""
Returns a list of #ImportInfo tuples for all module imports in the specified
Python source file or the *source* string. Note that `from X import Y`
imports could also refer to a member of the module X named Y and not the
module X.Y.
"""
def _find_nodes(ast_node... | 5,324,472 |
def follow_card(card, deck_size, shuffles, shuffler):
"""Follow position of the card in deck of deck_size during shuffles."""
position = card
for shuffle, parameter in shuffles:
shuffling = shuffler(shuffle)
position = shuffling(deck_size, position, parameter)
return position | 5,324,473 |
def get_secure_directory():
"""get a temporary secure sub directory"""
temp_dir = tempfile.mkdtemp(suffix='',prefix='')
return temp_dir | 5,324,474 |
def area(shape):
"""Multimethod dispatch key"""
return shape.get('type') | 5,324,475 |
def get_trie_properties(trie, offsets, values):
"""Obtain the length of every trigger in the trie."""
anchor_length = np.zeros(len(values), dtype=np.int32)
start, end = 0, 0
for idx, key in enumerate(trie.iterkeys()):
end = offsets[idx]
anchor_length[start:end] = len(key)
start =... | 5,324,476 |
def _register_when_ui_available():
"""Register a function emits the SceneEvents.WhenUIAvailable event.
This will be emitted when the UI is first brought up and the event
loop begins running.
:return:
"""
# Import here in case UI is not available.
import hdefereval
# Emit the event af... | 5,324,477 |
def get_available_qmix_configs(configs_dir=None):
"""
Create a list of available qmix configurations
Parameters
----------
configs_dir : string or None
The parent directory containing the Qmix configurations.
If ``None``, assume the default directory used by
Qmix Elements, i... | 5,324,478 |
def besseli(X, order=0, Nk=64):
""" Approximates the modified Bessel function of the first kind,
of either order zero or one.
OBS: Inputing float32 can lead to numerical issues.
Args:
X (torch.tensor): Input (N, 1).
order (int, optional): 0 or 1, defaults to 0.
Nk (int,... | 5,324,479 |
def proxy_py_subprocess(request: Any) -> Generator[int, None, None]:
"""Instantiate proxy.py in a subprocess for testing.
NOTE: Doesn't waits for the proxy to startup.
Ensure instance check in your tests.
After the testing is over, tear it down.
"""
run_id = str(int(time.time())) + '-' + str(i... | 5,324,480 |
def laplacian_total_variation_kernel(x, y, sigma=1.0, **kwargs):
"""Geodesic Laplacian kernel based on total variation distance."""
dist = np.abs(x - y).sum() / 2.0
return np.exp(-sigma * dist) | 5,324,481 |
def print_mimic(mimic_dict, word):
"""Given mimic dict and start word, prints 200 random words."""
line, text = '', ''
# Iterating 200 time to pick up random keys and values
for count in range(0, 200):
key = random.choice(list(mimic_dict.keys()))
val = mimic_dict.get(key)
line +... | 5,324,482 |
def get_dataset(
dataset_name: str,
path: Path = default_dataset_path,
regenerate: bool = False,
) -> TrainDatasets:
"""
Get a repository dataset.
The datasets that can be obtained through this function have been used
with different processing over time by several papers (e.g., [SFG17]_,
... | 5,324,483 |
def create_queue_from_filter_selector():
"""Create queue for a GPU device or,
if it is not available, for a CPU device.
Create in-order queue with profilign enabled.
"""
q = dpctl.SyclQueue("gpu,cpu", property=("in_order", "enable_profiling"))
print("Queue {} is in order: {}".format(q, q.is_in_... | 5,324,484 |
def test_view(regression_id):
"""
Show a single regression test.
:param regression_id: id of the regression test
:type regression_id: int
:return: Regression test
:rtype: dict
"""
test = RegressionTest.query.filter(RegressionTest.id == regression_id).first()
if test is None:
... | 5,324,485 |
def test44():
"""
test44: like test43, but get the task host from a StaticServer in the
infra model
"""
cap = Capture()
class Infra(InfraModel):
setup_server = StaticServer("setup_helper", "127.0.0.1")
infra = Infra("helper")
class NS(NamespaceModel):
task_performe... | 5,324,486 |
def data_context_path_computation_context_path_comp_serviceuuid_objective_function_post(uuid, tapi_path_computation_path_objective_function=None): # noqa: E501
"""data_context_path_computation_context_path_comp_serviceuuid_objective_function_post
creates tapi.path.computation.PathObjectiveFunction # noqa: E50... | 5,324,487 |
def tbl_2_nparray(in_tbl, flds):
"""Form the TableToNumPyArray to account for nulls for various dtypes.
This is essentially a shortcut to `arcpy.da.TableToNumPyArray`
Requires
--------
`in_tbl` :
table, or featureclass table name
`flds` :
list of field names
`skip_... | 5,324,488 |
def _get_paper_page(url: str) -> object: # pragma: no cover
"""
Get a paper page element from a provided URL
Parameters
----------
url : str
The paper URL
Returns
-------
Object
A HTML element representing the paper given by the provided URL
"""
response = com... | 5,324,489 |
def check_grid_side(ctx, param, value: int) -> int:
"""
check the size of the grid
:type value: int
"""
if value < 5:
raise ValueError("all sides of grid must be at least 5")
return value | 5,324,490 |
def distributed_transformer_model(input_tensor,
attention_mask=None,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=gelu,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
initializer_range=0.02,
... | 5,324,491 |
def cli(version=False):
"""
A simple AbemaTV and other we(e)bsite video downloader
"""
if version:
print('yuu v{} - Created by NoAiOne'.format(__version__))
exit(0) | 5,324,492 |
def create(ctx, message, test=False):
""" Invoke alembic to generate new migration from the existing db
and service' models.
"""
get_env(test)
app = create_app()
with app.app_context():
import alembic.config
alembic.config.main(argv=[
'-c',
'migration... | 5,324,493 |
def sgrank(doc, kp_count, window=1500, idf=None):
"""
Extracts keyphrases from a text using SGRank algorithm.
Args:
doc: a spacy.Doc object
kp_count: number of keyphrases
window: word co-occurrence window length
idf: a dictionary (string, float) of inverse document frequenci... | 5,324,494 |
def save_quantitative_results(quantitative_results: List[Tuple[int, List[float]]], metric_names: List[str], output_file: str):
"""
Saves the quantitative results into an output file.
The quantitative results are passed as a list of entries, where each entry consists
of the entry id, as well as a lis... | 5,324,495 |
def interpret(parsed, source_url, base_href=None, item=None,
use_rel_syndication=True, want_json=False, fetch_mf2_func=None):
"""Interpret a permalink of unknown type. Finds the first interesting
h-* element, and delegates to :func:`interpret_entry` if it is an
h-entry or :func:`interpret_even... | 5,324,496 |
def display_img(i, x, style, is_val=False):
"""
Display image.
"""
# Currently generated image
img = x
if is_val:
#img = ndimage.median_filter(img, 3)
fname = f"images/output/{style}_{i}_val.png"
else:
fname = f"images/output/{style}_{i}.png"
# Save image
... | 5,324,497 |
def generate(*drf_globs: DRF_list) -> List[str]:
"""
Generates a list of valid requests from a DRF glob.
:param drf_globs: A list of DRF globs.
:return: A list of valid requests.
"""
results = []
def parse_globs(drf_globs):
for drf_glob in drf_globs:
# Parse nested list... | 5,324,498 |
def MoveItemToUserFromCharacter(request, callback, customData = None, extraHeaders = None):
"""
Moves an item from a character's inventory into the owning user's inventory.
https://docs.microsoft.com/rest/api/playfab/server/player-item-management/moveitemtouserfromcharacter
"""
if not PlayFabSetting... | 5,324,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.