content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _filter_unlabeled_sentences(
characterwise_predicted_label_names_per_sentence, words_per_sentence,
unlabeled_sentence_filter):
"""Filters sentences without any predicted labels. Keeps every nth entry."""
sentences_without_label = 0
filtered_characterwise_predicted_label_names_per_sentenc... | 5,309,900 |
def highest_mag(slide):
"""Returns the highest magnification for the slide
"""
return int(slide.properties['aperio.AppMag']) | 5,309,901 |
def is_crud(crud):
"""Check if item is subclass of <GQL>"""
its_crud = False
try:
if not crud == GQL:
its_crud = issubclass(crud, GQL)
except TypeError:
pass
return its_crud | 5,309,902 |
def matrixProfile(ts: Matrix,
**kwargs: Dict[str, VALID_INPUT_TYPES]):
"""
Builtin function that computes the MatrixProfile of a time series efficiently
using the SCRIMP++ algorithm.
.. code-block:: txt
References:
Yan Zhu et al.. 2018.
Matrix Profil... | 5,309,903 |
def job(ctx, id):
"""Create new harvest job and runs it (puts it on the gather queue).
"""
flask_app = ctx.meta["flask_app"]
with flask_app.test_request_context():
try:
result = utils.create_job(id)
except HarvestJobExists as e:
tk.error_shout(e)
ctx.... | 5,309,904 |
def test_SubtractPDF(logging_mixin: Any, simple_test_functions: Any, skip_prefixes: List[str],
expected_co_varnames: List[str]) -> None:
""" Test for subtracting multiple functions with ``SubtractPDF``.
Note:
This is effectively an integration test for most of the ``SubtractPDF`` f... | 5,309,905 |
def verify_divide_edge(G, u, v, key, data, node_creation_counter, max_edge_length):
"""
Verify if edge(u,v)[key] length is higher than a certain threshold
In this case, divide edge(u,v) in two edges of equal length
Assign negative values to the edges new osm id
Call recursively to continue dividing each of the lin... | 5,309,906 |
def create_evaluations(model_or_ensemble_ids, datasets, evaluation_args,
args, api=None,
path=None, session_file=None, log=None,
existing_evaluations=0):
"""Create evaluations for a list of models
``model_or_ensemble_ids``: list of model o... | 5,309,907 |
def pegar_por_href(navegador, link):
"""Encontrar o elemento `a` com o link `link`.
Argumentos:
- browser = Instancia do browser [firefox, chrome, ...]
- link = link (ou parte dele) que será procurado em toda as tags `a`
"""
elementos = chrome.find_elements_by_tag_name('a')
for e... | 5,309,908 |
def import_txt(file_name, two_dimensional=False, **kwargs):
""" Reads control points from a text file and generates a 1-dimensional list of control points.
The following code examples illustrate importing different types of text files for curves and surfaces:
.. code-block:: python
:linenos:
... | 5,309,909 |
def sizeAbove(resource, value):
"""
Check if the contentSize attribute of the <contentInstance> resource is
equal to or greater than the specified value.
:param resource:
:type resource:
:param value:
:type value:
:return:
:rtype:
"""
try:
return resource.contentSize ... | 5,309,910 |
def decode_delegate_call_trace(trace: Dict[str, any], next_trace: Dict[str, any]) -> DecodedCallTrace:
"""
Takes a trace and decodes it. It needs next trace for return value
Structure for CALL and CALLCODE:
gas | addr | argsOffset | argsLength | retOffset | retLength
"""
# TODO Check stack is pr... | 5,309,911 |
def enumerate_destination_file_name(destination_file_name):
"""
Append a * to the end of the provided destination file name.
Only used when query output is too big and Google returns an error
requesting multiple file names.
"""
if re.search(r'\.', destination_file_name):
destination_file... | 5,309,912 |
def Flux_Quad(wpert, thetapert):
"""
Separates fluxes into quadrants
Arguments:
wpert -- array of w perturbations
thetapert -- array of theta perturbations
Returns:
[up_warm, down_warm, up_cold, down_cold] -- arrays, np.nans are fillers
"""
[rows, columnsx, columnsy] = ... | 5,309,913 |
def demistoVersion():
"""Retrieves server version and build number
Returns:
dict: Objects contains server version and build number
"""
return {
'version': '5.5.0',
'buildNumber': '12345'
} | 5,309,914 |
def classification_metric(all_real, all_pred, all_prob):
""" Metric used for experiments
Args:
all_real (list): real labels (ground truth) with n values
all_pred (list): predictions for n predictions
all_prob (list or np.array): probabilities (confidence).
If it is ... | 5,309,915 |
def camel_to_human(s, lower=True):
"""
Converts camel case to 'human' case
Arguments:
----------
lower: bool (default: False)
Convert output to lower
"""
ret = start_of_camel.sub(r" \1", s).strip()
if lower:
ret = ret.lower()
return ret | 5,309,916 |
def dice_game ():
"""
Function for manage all the game.
@rtype: None
@return: Return None when the game is ended
"""
scores = { TypeOfPlayers.PLAYER: 0, TypeOfPlayers.COMPUTER: 0 }
who_play = TypeOfPlayers.COMPUTER
while not game_is_ended(scores):
print('----------------------------------... | 5,309,917 |
def on_message(message):
"""
这是消息回调函数,所有的返回消息都在这里接收,建议异步处理,防止阻塞
:param message: 发送/接收的消息详情
:return: null
"""
print(message)
# 收到群聊消息且有@
if auto_reply and message['type'] == 'msg::chatroom' and message['data']['send_or_recv'][0] == '0' \
and message['data']['data_type'] == '1'... | 5,309,918 |
def create_work_name(name):
""" Remove ".nzb" and ".par(2)" """
strip_ext = ['.nzb', '.par', '.par2']
name = name.strip()
if name.find('://') < 0:
name_base, ext = os.path.splitext(name)
# In case it was one of these, there might be more
while ext.lower() in strip_ext:
... | 5,309,919 |
def edit_affiliations(request, affiliation_formset):
"""
Edit affiliation information
Helper function for `project_authors`.
"""
if affiliation_formset.is_valid():
affiliation_formset.save()
messages.success(request, 'Your author affiliations have been updated')
return True
... | 5,309,920 |
def tojson(x):
"""
python2/3 compatible conversion to json string
"""
return tobytes(json.dumps(x)) | 5,309,921 |
def prob_remap_bcg(upid, host_halo_mass,
mhalo_table=(13.5, 13.75, 14, 15), prob_table=(0, 0.1, 0.5, 1)):
"""
"""
ngals = len(upid)
prob_remap = np.interp(np.log10(host_halo_mass), mhalo_table, prob_table)
uran = np.random.rand(ngals)
uran[upid != -1] = 1.0
return uran < prob_re... | 5,309,922 |
def rsf_score(year, flu_space, sections, section_neighbors, buildings,
access_variables):
"""
Scores/weights for single family development.
"""
# get projects
projs = flu_space.to_frame(['building_type', 'project_type',
'total_units', 'built_units', 'p... | 5,309,923 |
def retrieve_all_plans() -> List[str]:
"""Return the names of all plans stored in the plan engine."""
url = _plan()
response = requests.get(url=url)
_raise_for_status(response)
plans: List[str] = json.loads(response.text)
return plans | 5,309,924 |
def test_compound_ops_and_return_vals(classname, method, children_and_retvals,
expected, derive_compound_exporter_class,
derive_child_exporter_class, new_exporter,
mocker):
"""
The `export_records` ... | 5,309,925 |
def test_fetch_pybullet_robot():
"""Tests for FetchPyBulletRobot()."""
utils.reset_config({"pybullet_control_mode": "not a real control mode"})
physics_client_id = p.connect(p.DIRECT)
ee_home_pose = (1.35, 0.75, 0.75)
ee_orn = p.getQuaternionFromEuler([0.0, np.pi / 2, -np.pi])
robot = FetchPyBu... | 5,309,926 |
def load_task_names(path: str) -> List[str]:
"""
Loads the task names a model was trained with.
:param path: Path where model checkpoint is saved.
:return: A list of the task names that the model was trained with.
"""
return load_args(path).task_names | 5,309,927 |
def sample_seq2seq(news_config: LMConfig, initial_context, eos_token, ignore_ids=None, p_for_topp=0.95,
do_topk=False, max_len=1025):
"""
Sample multiple outputs for a model in a seq2seq way.
:param news_config: Configuration used to construct the model
:param initial_context: [batch... | 5,309,928 |
def unquote_plus(s):
"""unquote('%7e/abc+def') -> '~/abc def'"""
s = s.replace('+', ' ')
return unquote(s) | 5,309,929 |
def log_debug(text):
"""
Adds a record at the DEBUG level.
Useful to write in the config file and on the stdout when debug mode is enabled.
"""
get_cr_logger().debug(text) | 5,309,930 |
def _rankf(x):
""" Return an integer valuation of float32 x """
shift = int32(31)
mask = int32((1 << 31) - 1)
i32 = x.view(int32)
value = i32 >> shift
value &= mask
value ^= i32
return value | 5,309,931 |
def main(digits, length):
""" Print the largest product for contiguous substring of n digits """
print(largest_product(digits, length)) | 5,309,932 |
def extract_package_to_dir(package_url):
"""
Extracts a pip package to a temporary directory.
:param package_url: the URL to the package source.
:return: the directory the package was extracted to.
"""
# 1) Plugin installation during deployment creation occurs not in the main
# thread, bu... | 5,309,933 |
def update_or_set_community_schema(community, json_file):
"""Updates or sets the schema for a community.
The complete schema of a community contains a copy of the root metadata
schema and a set of community-specific metadata block schemas. Currently
we assume there's only one allowed metadata block sch... | 5,309,934 |
def reorder_tables(openapi_yaml: sy.YAML) -> List[sy.Str]:
"""Orders the tables so no table references another table that might be defined after.
Parameters
----------
openapi_yaml
Contains the openapi format describing the database schema
Returns
-------
tables_in_order
A l... | 5,309,935 |
def test_find_maximum_value():
"""Test to find the max value with a small tree."""
tree = BST([9, 5, 15, 7])
assert tree.find_maximum_value() == 15 | 5,309,936 |
def video_feed():
"""
Video streaming route. Put this in the src attribute of an
img tag.
"""
txt = 'multipart/x-mixed-replace; boundary=frame'
# WS added passing a message to the Camera class
return Response(gen(Camera(message=msg)), mimetype=txt) | 5,309,937 |
def bias_act(x, b=None, dim=1, gain=None, clamp=None):
"""Slow reference implementation of `bias_act()`
"""
# spec = activation_funcs[act]
# alpha = float(alpha if alpha is not None else 0)
gain = float(gain if gain is not None else 1)
clamp = float(clamp if clamp is not None else -1)
# Add... | 5,309,938 |
def init():
"""Return top level command handler."""
ctx = {}
@click.group()
@click.option('--cell', required=True,
envvar='TREADMILL_CELL',
callback=cli.handle_context_opt,
expose_value=False)
@click.option('--api', required=False, help='API ur... | 5,309,939 |
def process_json_file(file_name, grounding_ns=None, extract_filter=None,
grounding_mode=default_grounding_mode):
"""Return an EidosProcessor by processing the given Eidos JSON-LD file.
This function is useful if the output from Eidos is saved as a file and
needs to be processed.
... | 5,309,940 |
def accumulate_ip_for_certificate(value):
"""
A convenience function that wraps the results of 'search_ip_for_certificate' into a Python list.
:param value: The certificate value for which to search
:return: The list of IP addresses
:raises LookupException: If there was an error performing the look... | 5,309,941 |
def combine_envs(*envs):
"""Combine zero or more dictionaries containing environment variables.
Environment variables later from dictionaries later in the list take
priority over those earlier in the list. For variables ending with
``PATH``, we prepend (and add a colon) rather than overwriting.
If... | 5,309,942 |
def get_request_data() -> dict:
"""
Get keys & values from request.
(Note that this method parse requests with
content type "application/x-www-form-urlencoded")
"""
data = dict(request.values)
logging.info(f"received request: {data}")
return data | 5,309,943 |
def test_curve_ascend():
"""
Feature: Test image curve.
Description: Transform an image with curve.
Expectation: success.
"""
context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
image = np.random.random((32, 32, 3))
trans = Curve(curves=1.5, depth=1.5, mode='horizontal')... | 5,309,944 |
def generate_square_subsequent_mask(sz):
"""
Generate attention mask using triu (triangle) attention
"""
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = (
mask.float()
.masked_fill(mask == 0, float("-inf"))
.masked_fill(mask == 1, float(0.0))
)
ret... | 5,309,945 |
def load_settings(*signal_args):
"""Call to stop running, may be called with a signum and frame
parameter if called as a signal handler."""
if _debug: load_settings._debug("load_settings %r", signal_args)
global args, settings
if signal_args:
sys.stderr.write("===== HUP Signal, %s\n" % time... | 5,309,946 |
def tree_graph(data, attrs=_attrs):
"""Return graph from tree data format.
Parameters
----------
data : dict
Tree formatted graph data
Returns
-------
G : NetworkX OrderedDiGraph
attrs : dict
A dictionary that contains two keys 'id' and 'children'. The
correspo... | 5,309,947 |
def retry_on_mysql_lock_fail(metric=None, metric_tags=None):
"""Function decorator to backoff and retry on MySQL lock failures.
This handles these MySQL errors:
* (1205) Lock wait timeout exceeded
* (1213) Deadlock when trying to get lock
In both cases, restarting the transaction may work.
It... | 5,309,948 |
def test_modules_environment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""
Check that the environment variables set by a module are being propagated correctly.
Do so by by running `env` as the tool and parsing its output.
"""
monkeypatch.setenv(
"MODULEPATH", os.path.join(o... | 5,309,949 |
def eot(date: datetime.date, offset: int = 0) -> datetime.date:
"""
Returns the end of the calendar trimester, i.e. one of
30 April, 31 August or 31 December, then optionally offsets it
by :code:`offset` trimesters
Parameters
----------
date : datetime.date
the date from which to ... | 5,309,950 |
def generate_activation_url(token_name: str, token_value: str) -> str:
"""
Generates url with token_name=token_value embedded in it.
:param token_name:
:param token_value:
:return:
"""
return Config.FRONT_END_URL + "?" + f"{token_name}={token_value}" | 5,309,951 |
def native_type_range(fmt):
"""Return range of a native type."""
if fmt == 'c':
lh = (0, 256)
elif fmt == '?':
lh = (0, 2)
elif fmt == 'f':
lh = (-(1<<63), 1<<63)
elif fmt == 'd':
lh = (-(1<<1023), 1<<1023)
else:
for exp in (128, 127, 64, 63, 32, 31, 16, 1... | 5,309,952 |
def get_action(affordance_map, epsilon, open_scales):
"""Get action based on affordance_map.
Args:
affordance_map: [S, K, W, H]
epsilon: random aciton based on prob VS choose best aciton. If epsilon < 0: get action with best score
open_scales: list of open_scales [S]
Returns:
... | 5,309,953 |
def drop_shadow(image, offset=(5, 5), background=0xffffff, shadow=0x444444,
border=8, iterations=5):
"""
Add a gaussian blur drop shadow to an image.
image - The image to overlay on top of the shadow.
offset - Offset of the shadow from the image as an (x,y) tuple. Can be
... | 5,309,954 |
def get_tickers(percent):
"""Keep the top percent market-cap companies."""
assert isinstance(percent, int)
output = []
for exchange in ["NASDAQ", "NYSE", "AMEX"]:
url = "http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange="
repeat_times = 10 # repeat downloading in case ... | 5,309,955 |
def get_s_test(z_test_grad, z_losses, params, damp=0.01, scale=25.0, recursion_depth=20000, threshold=1e-8):
"""s_test can be precomputed for each test point of interest, and then
multiplied with grad_z to get the desired value for each training point.
Here, strochastic estimation is used to calculate s_tes... | 5,309,956 |
def test_default_platform_precision():
"""Test that the precision for platform is set to mixed by default."""
available_platforms = [openmm.Platform.getPlatform(i).getName()
for i in range(openmm.Platform.getNumPlatforms())]
# Determine whether this device OpenCL platform support... | 5,309,957 |
def main(token_file=None, save_token_file=False):
"""
Starts the Antistasi Discord Bot 'AntiPetros'.
creates the bot, loads the extensions and starts the bot with the Token.
"""
os.environ['INFO_RUN'] = "0"
if token_file is not None and save_token_file is True:
store_token_file(token_fi... | 5,309,958 |
def to_fft_image(fft_mat, is_shift=False):
"""Convert frequency matrix to visual image"""
if is_shift:
fft_mat = np.fft.fftshift(fft_mat)
log_mat = 20*np.log(np.abs(fft_mat))
return np.uint8(np.around(log_mat)) | 5,309,959 |
def np_normal(shape, random_state, scale=0.01):
"""
Builds a numpy variable filled with normal random values
Parameters
----------
shape, tuple of ints or tuple of tuples
shape of values to initialize
tuple of ints should be single shape
tuple of tuples is primarily for conv... | 5,309,960 |
def head(
path: str, /, *, name: Optional[str] = None, include_in_schema: bool = True
) -> Callable[[Callable[[Request], Awaitable[Response]]], Route]:
"""decorator to create a Starlette Route for HEAD requests from an endpoint"""
return route(path, methods=["HEAD"], name=name, include_in_schema=include_in_... | 5,309,961 |
def api_hash_key(*args, **kwargs):
"""参考cachetools hashkey实现,对WSGIRequest参数对象进行特殊处理"""
new_args, _ = deal_request_args(False, *args)
return hashkey(*new_args, **kwargs) | 5,309,962 |
def len_column(table):
"""
Add length column containing the length of the original entry in the seq column.
Insert a number column with numbered entries for each row.
"""
for pos, i in enumerate(table):
i.insert(0, pos)
i.append(len(i[1]))
return table | 5,309,963 |
def _binary_roc_auc_score(y_true, y_score, sample_weight=None, max_fpr=None):
"""Binary roc auc score"""
if len(np.unique(y_true)) != 2:
raise ValueError("Only one class present in y_true. ROC AUC score "
"is not defined in that case.")
fpr, tpr, _ = roc_curve(y_true, y_sco... | 5,309,964 |
def build_service_set(gtfs_data):
"""Based on the calendar, figure out which service IDs should run for
each date"""
# The master dict of days
# Keys are the dates, the values are a list of service IDs that run for
# that day
service_days = {}
# Loop through each service ID
for service_... | 5,309,965 |
def manage_org_users(request):
"""
View to manage the users of an organisation
Should only be accessed by admin users of the organisation
"""
if request.user.is_org_admin:
context_dict = {}
context_dict['organisation_users'] = request.user.organisation.get_users()
context_dic... | 5,309,966 |
def open_python_doc():
"""
Open Python documentation
(Windows: open .chm documentation if found)
"""
python_doc = get_python_doc_path()
if os.name == 'nt':
os.startfile(python_doc)
else:
webbrowser.open(python_doc) | 5,309,967 |
def get_confusion_noise_robson19(f, t_obs=4 * u.yr):
"""Calculate the confusion noise using the model from Robson+19 Eq. 14 and Table 1
Also note that this fit is designed based on LISA sensitivity and so it is likely not sensible to apply
it to TianQin or other missions.
Parameters
----------
... | 5,309,968 |
def default():
"""
Simply calls :func:`get` for the default endpoint.
"""
return get() | 5,309,969 |
def direct_1d(x, x_s, dx, dt, c, f):
"""Use the 1D Green's function to determine the wavefield at a given
location due to the given source.
"""
r = torch.abs(x - x_s).item()
t_shift = (r / c) / dt
u = dx * dt * c / 2 * torch.Tensor(np.cumsum(shift(f, t_shift)))
return u | 5,309,970 |
def test_basic_state_transition(circuit):
"""Test the basic FSM function."""
class B123(edzed.FSM):
STATES = 'S1 S2 S3'.split()
EVENTS = [
('step', ['S1'], 'S2'),
['step', None, 'S3'], # default rule has lower precedence
('step', 'S3', 'S1') # single stat... | 5,309,971 |
def home():
""" Home Page """
print("### Home Page Loaded ###")
return render_template('index.html', page="Home") | 5,309,972 |
def group_conv(N, H, W, CI, CO, group, KH, KW, PAD_H, PAD_W, SH, SW, cutH, cutCo, cutM, cutK, cutN, block_size, use_bias=False, kernel_name='conv'):
"""
split channels of FeatureMap to some groups,every group has its filter-kernel
Args:
args1:a list,the size is 3 if use_bias else the size is 2;
... | 5,309,973 |
def tests(session):
"""Enforce code-style with appropriately configured linters."""
session.install(".[sphinx,testing]")
session.run("pytest", *session.posargs) | 5,309,974 |
def read_alignment(
filename, format=None, *, max_taxa=math.inf, max_characters=math.inf
):
"""
Reads a single alignment file to a torch tensor of probabilites.
:param str filename: Name of input file.
:param str format: Optional input format, e.g. "nexus" or "fasta".
:param int max_taxa: Optio... | 5,309,975 |
def auto_load_processed(path):
"""Load processed BEEP .json files regardless of their class.
Enables loadfn capability for legacy BEEP files, since calling
loadfn on legacy files will return dictionaries instead of objects
or will outright fail.
Examples:
auto_load_processed("maccor_file_... | 5,309,976 |
def grating_linear_dispersion(
spec_inclusion_angle,
spec_focal_length,
spec_focal_length_tilt,
spec_grooves_per_mm,
spec_central_wavelength,
spec_order,
number_of_pixels,
pixel_width,
calibration_pixel,
):
"""
Parameters
----------
spec_inclusion_angle : float
... | 5,309,977 |
def test_write_source_space():
"""Test reading and writing of source spaces
"""
tempdir = _TempDir()
src0 = read_source_spaces(fname, add_geom=False)
write_source_spaces(op.join(tempdir, 'tmp-src.fif'), src0)
src1 = read_source_spaces(op.join(tempdir, 'tmp-src.fif'), add_geom=False)
_compare... | 5,309,978 |
def __read_picture_data(_filelist):
""" READ picture exif data, put it in dictionary __PIC_DICT"""
for orig_filepath in _filelist:
# ensure we only fetch jpg and jpeg and JPG and JPEG ...
_, extension = splitext_last(orig_filepath)
if not extension in get_jpg_input_extensions():
... | 5,309,979 |
def merge_columns_starting_positions(starting_positions, strict=True):
"""merging all lines starting positions"""
starting_positions = tuple(set(starting_positions))
# If only one is provided, or all equals, return it
if len(starting_positions) == 1:
return starting_positions[0]
# If more t... | 5,309,980 |
def fin_FoM_optbd(n,d,bc,a,b,cini=None,imprecision=10**-2,bdlmax=100,alwaysbdlmax=False,lherm=True):
"""
Optimization of FoM over SLD MPO and also check of convergence in bond dimension. Function for finite size systems.
Parameters:
n: number of sites in TN
d: dimension of local Hilbert spa... | 5,309,981 |
def create_cylinder(position, radius, height, orientation=(0,0,0), color=None, texture=None, mass=1, friction=0.1, client=0, isCollision=True):
"""
create cylinder in physical scene.
----------------------
position[3-element tuple]: Center position of the cylinder
orientation[3-element tuple]: Euler... | 5,309,982 |
def read_maze(file_name):
"""
Reads a maze stored in a text file and returns a 2d list containing the maze representation.
"""
try:
with open(file_name) as fh:
maze = [[char for char in line.strip("\n")] for line in fh]
num_cols_top_row = len(maze[0])
for row ... | 5,309,983 |
def main():
""" main entry point for module execution
"""
argument_spec = dict(
src=dict(type='path'),
lines=dict(aliases=['commands'], type='list'),
parents=dict(type='list'),
before=dict(type='list'),
after=dict(type='list'),
match=dict(default='line', ch... | 5,309,984 |
def replace(
sources: ListOfPathsOrStrs, before: str, after: str, flags: int = re.MULTILINE
):
"""Replaces occurrences of before with after in all the given sources."""
expr = re.compile(before, flags=flags or 0)
paths = _filter_files(_expand_paths(sources, "."))
if not paths:
log.warning(f... | 5,309,985 |
def tokenize_batch_question_answering(pre_baskets, tokenizer, indices):
"""
Tokenizes text data for question answering tasks. Tokenization means splitting words into subwords, depending on the
tokenizer's vocabulary.
- We first tokenize all documents in batch mode. (When using FastTokenizers Rust multi... | 5,309,986 |
def neg3d(v: np.ndarray) -> None:
"""
v = -v
Parameters
----------
v 三维矢量
Returns None
-------
"""
f(drv.InOut(v), block=(1, 1, 1), grid=(1, 1)) | 5,309,987 |
def test_invalid_events():
"""
The HillasReconstructor is supposed to fail
in these cases:
- less than two teleskopes
- any width is NaN
- any width is 0
This test uses the same sample simtel file as
test_reconstruction(). As there are no invalid events in this
file, multiple hilla... | 5,309,988 |
def fwdimg():
"""Show next observation."""
i = min(vi + 1, data.shape[3] - 1)
changeimg(i) | 5,309,989 |
def format(number):
"""Reformat the number to the standard presentation format."""
number = compact(number)
return (number[:-7] + '.' + number[-7:-4] + '.' +
number[-4:-1] + '-' + number[-1]) | 5,309,990 |
def config_init():
"""Initialize config.json with default values"""
# Defaults
init_conf = {}
init_conf["registry"] = "docker.io"
init_conf["username"] = ""
init_conf["repository"] = "helperpod"
init_conf["tag"] = "vanilla"
with open(configfile_path, "w", encoding="utf-8") as init_conf... | 5,309,991 |
def user_register(**kwargs):
"""
swagger_from_file: Swagger/user/register.yml
"""
data = kwargs['data']
data['password'] = UserInfo.generate_hash(data['password'])
try:
obj = dynamic_modify(UserInfo(), data).create()
except Exception as e:
return response(ResponseEnum.INVALID... | 5,309,992 |
def _check(sample, data):
"""Get input sample for each chip bam file."""
if dd.get_chip_method(sample).lower() == "atac":
return [sample]
if dd.get_phenotype(sample) == "input":
return None
for origin in data:
if dd.get_batch(sample) in dd.get_batch(origin[0]) and dd.get_phenotyp... | 5,309,993 |
def step_update(x, P, a, b, sd):
"""
Apply 'observation' of form
a'x = b + N(0, sd^2)
to obtain new x, P, useful for building priors
:param x: n_k, n
:param P: n_k, n, n
:param a: n
:param b: n_k,
:param sd:
:return:
"""
PCt = P @ a # n_k, n
CPC_Q = PCt @ a + sd ** 2... | 5,309,994 |
def validate_single_message(schema, input_file, verbose):
"""Validate single message stored in input file."""
processed = 0
valid = 0
invalid = 0
error = 0
try:
payload = load_json_from_file(input_file, verbose)
processed = 1
validate(schema, payload, verbose)
va... | 5,309,995 |
def sns_certificate(*args):
""" Mock requests to retrieve the SNS signing certificate """
with open('tests/files/certificate.pem') as cert_file:
cert = cert_file.read()
return cert | 5,309,996 |
def kldivergence(x, y):
"""Compute the Kullback-Leibler divergence between two multivariate samples.
Parameters
----------
x : 2D array (n,d)
Samples from distribution P, which typically represents the true
distribution.
y : 2D array (m,d)
Samples from distribution Q, which typicall... | 5,309,997 |
def test_product():
"""Setup & Teardown an product for this api"""
product = ApigeeApiProducts()
loop = asyncio.new_event_loop()
loop.run_until_complete(product.create_new_product())
yield product
loop.run_until_complete(product.destroy_product()) | 5,309,998 |
def hashphraseviews_autodiscover():
"""
Auto-discover INSTALLED_APPS hashphraseviews.py modules and fail silently when
not present. NOTE: dajaxice_autodiscover was inspired/copied from
django.contrib.admin autodiscover
"""
global LOADING_HASHPHRASE
if LOADING_HASHPHRASE:
return
L... | 5,309,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.