content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def delete_resource_group(credentials, subscription_id, resource_group):
"""
Delete a resource group
:param credentials: msrestazure.azure_active_directory.AdalAuthentication
:param subscription_id: str
:param resource_group: str
"""
resource_client = ResourceManagementClient... | 5,300,200 |
def heapsort(alist):
"""Sorting an array using heapsort algorithm."""
if len(alist) > 1:
build_heap(alist)
for i in range(len(alist)-1, 0, -1):
if alist[0] > alist[i]:
alist[0], alist[i] = alist[i], alist[0]
heapify(alist, 0, i - 1)
# retur... | 5,300,201 |
def compute_heuristic_conn_4(init_pos, coord):
"""Returns Manhattan heuristic for distance from coord to init_pos
init_pos - coordinate of position of goal configuration
coord - coordinate of configuration for which heursitic is
being computed
Returns the heuristic distance to goal t... | 5,300,202 |
def hpat_pandas_series_floordiv(self, other, level=None, fill_value=None, axis=0):
"""
Pandas Series method :meth:`pandas.Series.floordiv` implementation.
.. only:: developer
Test: python -m hpat.runtests hpat.tests.test_series.TestSeries.test_series_op5
Parameters
----------
... | 5,300,203 |
def initdb_command():
"""Initializes the database."""
init_db()
print('Database initialized.') | 5,300,204 |
def subs_si(expr: Expr) -> Expr:
"""Substitute any ConstantSymbols in an Expression with their value in a SI units
Args:
expr:
Expr, the sympy expression in which to substitute constant symbols for values
Returns:
Expr, the substituted expression
"""
return _subs_const_... | 5,300,205 |
def close():
"""
Close the masternode.
"""
try:
node_private_key = NodePrivateKey().get()
except (NotSupportedOsToGetNodePrivateKeyError, FileNotFoundError) as error:
print_errors(errors=str(error))
sys.exit(FAILED_EXIT_FROM_COMMAND_CODE)
remme = Remme(
account_... | 5,300,206 |
def generateGenericCell(nBuildings, pAgents, pPHHagents,
pAgriculture, pDHN, pPVplants,
pHeatpumps, pCHP, pBTypes,
nSepBSLAgents, pAgricultureBSLsep,
region, hist=0):
""" Create a cell of a generic energy system
The... | 5,300,207 |
def test_heap_instaniated_with_bool():
"""If heap is instantiated with a bool, type error should be raised."""
from binary_heap import BinaryHeap
with pytest.raises(TypeError):
BinaryHeap(False) | 5,300,208 |
def source_cli():
"""Manage sources"""
pass | 5,300,209 |
def cancel_and_stop_intent_handler(handler_input):
"""Single handler for Cancel and Stop Intent."""
speech_text = "OK Mate calm down."
attr = handler_input.attributes_manager.session_attributes
attr['readShows'] = False
attr['readMovies'] = False
attr['readBoth'] = False
attr['active_reques... | 5,300,210 |
async def test_explicit_color_mode_templated(hass, mqtt_mock_entry_with_yaml_config):
"""Test templated explicit color mode over mqtt."""
config = {
light.DOMAIN: {
"platform": "mqtt",
"name": "test",
"state_topic": "test_light_rgb/status",
"command_topic"... | 5,300,211 |
def get_excluded_apps_and_models(excludes):
"""
:param excludes: list of app labels ("app_label.model_name" or "app_label") to exclude
:return: Tuple containing two sets: Set of AppConfigs to exclude, Set of model classes to excluded.
"""
excluded_apps = set()
excluded_models = set()
for exc... | 5,300,212 |
def subprocess_run(args, **kwargs):
"""
Emulate Python 3 "subprocess.run"
Don't help the caller remember to say: stdin=subprocess.PIPE
"""
# Trust the library, if available
if hasattr(subprocess, "run"):
run = subprocess.run(args, **kwargs) # pylint: disable=subprocess-run-check
... | 5,300,213 |
def frequency(text, char):
""" Counts frequency of a character in a string. """
count = 0
for c in text:
if c == char:
count += 1
return count | 5,300,214 |
def Interpolate(a,h,image,BP,sig_data=1,K=Squared_Expo,width=9):
"""
Interpolate(a,h,image,BP,sig_data=1,K=Squared_Expo,width=9)
Correcting the values of bad pixels by interpolation.
Parameters
----------
a: float
Same as in GPR_Kernel.
h: float or shape (2,) ar... | 5,300,215 |
def run_train():
"""train function"""
print('device id:', get_device_id())
print('device num:', get_device_num())
print('rank id:', get_rank_id())
print('job id:', get_job_id())
device_target = config.device_target
context.set_context(mode=context.GRAPH_MODE,
device_... | 5,300,216 |
def test_extend_works():
"""Test simple extend works."""
sl = setlist(range(1))
sl.extend([1, 2])
assert sl == setlist(range(3))
assert sl.index(0) == 0
assert sl.index(1) == 1
assert sl.index(2) == 2 | 5,300,217 |
def ripser(
X,
maxdim=1,
thresh=np.inf,
coeff=2,
distance_matrix=False,
do_cocycles=False,
metric="euclidean",
):
"""Compute persistence diagrams for X data array. If X is not a distance matrix, it will be converted to a distance matrix using the chosen metric.
Parameters
------... | 5,300,218 |
def slice_spec_from_stats( # pylint: disable=invalid-name
statistics: statistics_pb2.DatasetFeatureStatisticsList,
categorical_uniques_threshold: int = 100,
max_cross_size: int = 2) -> List[slicer.SingleSliceSpec]:
"""Generates slicing spec from statistics.
Args:
statistics: Data statistics.
c... | 5,300,219 |
def is_benchmark_supported(benchmark : Benchmark):
"""returns True if the provided benchmark is supported by the tool and if the given benchmark should appear on the generated benchmark list"""
# Check for unsupported input languages: everything but PRISM currently
if benchmark.is_prism():
# Tempor... | 5,300,220 |
def get_regional_map_file(
atlas_id: str,
parcellation_id: str,
region_id: str,
space_id: Optional[str] = None):
"""
Returns a regional map for given region name.
"""
roi, space_of_interest = parse_region_selection(
atlas_id, parcellation_id, region_id, space_id)
... | 5,300,221 |
def export_xrefs(clans_file: str, proteins_file: str, matches_file: str,
proteomes_file: str, domorgs_file: str,
structureinfo_file: str, structures_file: str, output: str):
"""Export PDBe structures cross-references, that is:
- proteins
- taxa
- proteomes
... | 5,300,222 |
def main():
"""
NAME
ani_depthplot.py
DESCRIPTION
plots tau, V3_inc, V1_dec, P and chi versus core_depth
SYNTAX
ani_depthplot.py [command line optins]
# or, for Anaconda users:
ani_depthplot_anaconda [command line options]
OPTIONS
-h prints help me... | 5,300,223 |
def ListContainerImageTags(request, callback, customData = None, extraHeaders = None):
"""
Lists the tags for a custom container image.
https://docs.microsoft.com/rest/api/playfab/multiplayer/multiplayerserver/listcontainerimagetags
"""
if not PlayFabSettings._internalSettings.EntityToken:
r... | 5,300,224 |
def test_evolution_models():
"""
Test to make sure the different evolution models work
"""
from popstar import evolution
# Age ranges to test
age_young_arr = [6.7, 7.9]
age_all_arr = [6.7, 8.0, 9.7]
# Metallicity ranges to test (if applicable)
metal_range = [-2.5, 0, 0.4]
metal... | 5,300,225 |
def get_parent_execution(execution_db):
"""Get the action execution for the parent workflow
Useful for finding the parent workflow. Pass in any ActionExecutionDB instance,
and this function will return the action execution of the parent workflow.
:param execution_db: The ActionExecutionDB instance for... | 5,300,226 |
def counts(short_question, course_code):
"""Return number of comments by star for a given course code, question,
and fiscal year.
"""
course_code = course_code.upper()
# Unpack arguments
fiscal_year = request.args.get('fiscal_year', '')
# Run query; return dict of 0s in case of invalid arguments
try:
counts... | 5,300,227 |
def get_route_geometry(locs_or_traj):
"""
Computes a map-matched geometry for a list of locations or TrajDataFrame
Parameters
----------
locs_or_traj : list | TrajDataFrame
Either a list of coordinates in the form of [[x,y], ...] or a TrajDataFrame to map-match
Returns
-------
... | 5,300,228 |
def build_index(root, base_url):
"""
Create a new data.xml index file, by combining the xml description
files for various packages and collections. ``root`` should be the
path to a directory containing the package xml and zip files; and
the collection xml files. The ``root`` directory is expected to
have ... | 5,300,229 |
async def read_scoreframe(data: bytearray) -> Tuple[ScoreFrame, int]:
""" Read an osu! scoreframe from `data`. """
offset = 29
s = ScoreFrame(*struct.unpack('<iBHHHHHHiHH?BB?', data[:offset]))
if s.score_v2:
s.combo_portion, s.bonus_portion = struct.unpack('<ff', data[offset:offset+8])
... | 5,300,230 |
def status_log_for_each_instrument():
"""Get a dictionary containing the most recent log entry for each instrument with log entries.
Returns
-------
Dictionary with the instrument ids for each log as the key and a dictionary for the log's 'author', 'status code',
and 'contents' as the value. 'conte... | 5,300,231 |
def experimental_jit_scope(compile_ops=True):
"""Enable or disable JIT compilation of operators within the scope.
NOTE: This is an experimental feature.
The compilation is a hint and only supported on a best-effort basis.
Example usage:
with tf.contrib.framework.experimental_jit_scope():
c = tf.mat... | 5,300,232 |
def test_searchparameter_7(base_settings):
"""No. 7 tests collection for SearchParameter.
Test File: organization-extensions-Organization-alias.json
"""
filename = (
base_settings["unittest_data_dir"]
/ "organization-extensions-Organization-alias.json"
)
inst = searchparameter.Se... | 5,300,233 |
def test_data_installation():
"""the `data` directory was installed properly with the package"""
package_root_dir = discoursegraphs.PACKAGE_ROOT_DIR
assert len(package_root_dir) != 2
# if we can't find the documents, this will be 0
assert len(discoursegraphs.corpora.pcc) == 176 | 5,300,234 |
def test_cleanup_after_install_from_local_directory():
"""
Test clean up after installing from a local directory.
"""
env = reset_env()
to_install = abspath(join(here, 'packages', 'FSPkg'))
run_pip('install', to_install, expect_error=False)
build = env.venv_path/'build'
src = env.venv_p... | 5,300,235 |
def update_blog(title):
"""This defines the creation of a new form
"""
blog = Blog.query.filter_by(title = title).first()
form = BlogForm()
if form.validate_on_submit():
blog.title = form.title.data
blog.meta_title = form.meta_title.data
blog.body = form.blog.data
bl... | 5,300,236 |
def softmax_pooler_output(nr_class, *, exclusive_classes=True, **cfg):
"""Select features from the pooler output, (if necessary) mean-pool them
to produce one vector per item, and then softmax them.
The gradients of the class vectors are incremented in the backward pass,
to allow fine-tuning.
"""
... | 5,300,237 |
def name_option(args, run):
"""Set the name for this run."""
run.experiment_info["name"] = args
run.run_logger = run.root_logger.getChild(args) | 5,300,238 |
def get_latest_tle_from_restapi(number):
"""
:param number: get the latest TLE from Restful API
:return: a TLE
"""
return "see restful_client.py" | 5,300,239 |
def test_objects_equality():
""" it should return true if objects are equal """
obj_a = {
"test": [1],
"hello": "world",
}
obj_b = {
"test": [1],
"hello": "world",
}
assert isjsonequal(obj_a, obj_b)
assert isjsonequal(obj_b, obj_a) | 5,300,240 |
def mroz2(path):
"""mroz
Data loads lazily. Type data(mroz) into the console.
A data.frame with 753 rows and 22 variables:
- inlf. =1 if in lab frce, 1975
- hours. hours worked, 1975
- kidslt6. # kids < 6 years
- kidsge6. # kids 6-18
- age. woman's age in yrs
- educ. years of schooling
... | 5,300,241 |
def measure_command(func, kwargs):
""" Measures the execution time of a function
:param func: function
:param kwargs: dict
keyword arguments
:return: float, result
(time, result of fucntion)
"""
time_start = time.time()
r = func(**kwargs)
dt = time.time() - time_start
... | 5,300,242 |
def get_soup_object(response_content: str) -> BeautifulSoup:
"""
Note: possible to get page even if content is not desired
"""
# TODO: error handling here if empty string
return BeautifulSoup(response_content, "lxml") | 5,300,243 |
def heapsort(array):
"""Implements heapsort in-place using heap.Heap. Insert all
the values in (via heapify in O(n) ) and the read them
out in max order, inserting into the correct place in the
orig list.
This uses an additional O(n) space since we create another copy in the
Heap. We could do... | 5,300,244 |
def p_numero(production):
"""numero : NUM_INTEIRO
| NUM_PONTO_FLUTUANTE
| NUM_NOTACAO_CIENTIFICA
"""
rtype = ''
if re.match(inteiro, production[1]):
rtype = 'inteiro'
elif re.match(notacao_cientifica, production[1]):
rtype = 'flutuante'
if re.match(f... | 5,300,245 |
def in_pyz():
""" Determine if running in pyz archive """
pyz_file = os.path.abspath(os.path.dirname(__file__))
if zipfile.is_zipfile(pyz_file):
return True
else:
return False | 5,300,246 |
def generator(input_dim=2,activation_function='linear',bias=True):
"""
Purpose:
-------
This is a network that can used to represent element in a given presentation. The choice is the one made in the paper.
Arguments:
---------
dim : i... | 5,300,247 |
def _build_train_mindrecord_dataset(
csv_path, clean_csv_path, image_dir, generate_train_validation_splits, validation_split_size, seed):
"""Build a MindRecord dataset for the train split.
Args:
csv_path: path to the train Google-landmark Dataset csv Data Sources files.
clean_csv_... | 5,300,248 |
def unload_module(module):
"""
Reset import so one can mock global constants.
Args:
module (module, object or str): The module will
be removed so it will have to be imported again. If given
an object, the module in which that object sits will be unloaded. A string
... | 5,300,249 |
def _test_dt(code):
"""判断股票上市时间是否晚于指定时间"""
try:
return datetime.datetime(2005, 1, 1) >= get_ipo_date(code)
except:
return False | 5,300,250 |
def edit_equipment_type(
client: SymphonyClient,
name: str,
new_positions_list: List[str],
new_port_definitions: List[EquipmentPortDefinition],
new_properties: Optional[Mapping[str, PropertyValue]] = None,
) -> EquipmentType:
"""Edit existing equipment type.
:param name: Equipment type name... | 5,300,251 |
def get_color(pred_class, labels):
"""
Function to color the barplots. Defaults to blue, but it colors
the prediction green/red if it's correct/incorrect
:param pred_class:
:param labels:
:return:
"""
num_classes = 10 # Hard coded for the 10 MNIST labels
target_class = np.argmax(lab... | 5,300,252 |
def add_member(client_session, esg_name, pool_name, member_name, member_ip, port=None, monitor_port=None, weight=None,
max_conn=None, min_conn=None):
"""
This function creates a Member inside a Server Pool on an ESG
:type client_session: nsxramlclient.client.NsxClient
:param client_sessi... | 5,300,253 |
def check_auth_shared_secret(auth = True,
):
"""
Authentication via HMAC signatures, nonces, and a local keypair DB.
"""
def decorator(func):
def proxyfunc(self, *args, **kw):
user_key = dict(self.request.headers).get("Key", False)
... | 5,300,254 |
def remove_indiv_files(path):
"""Used to delete .nc or .zarr files"""
if isinstance(path, FSMap):
path.fs.delete(path.root, recursive=True)
else:
fname, ext = os.path.splitext(path)
if ext == ".zarr":
shutil.rmtree(path)
else:
os.remove(path) | 5,300,255 |
def _find_new_wire(wires: Wires) -> int:
"""Finds a new wire label that is not in ``wires``."""
ctr = 0
while ctr in wires:
ctr += 1
return ctr | 5,300,256 |
def init_syslog(level, process_ident, address='/dev/log', facility=LOG_DAEMON):
"""
Set the root logger to be directed to syslog from the given level
and with given ident string (which will get prepended to every message).
"""
logging.root.setLevel(level)
if len(logging.root.handlers) == 0:
... | 5,300,257 |
def is_linux_ready(path):
"""
linux下的文件是否已经准备好
:param path:
:return:
"""
for proc in psutil.process_iter():
try:
for item in proc.open_files():
if path == item.path:
return False
except Exception:
pass
... | 5,300,258 |
def evaluate_model(
model, eval_loader, device, k=1, split_name="VAL", log_file="log.txt"
):
"""
Evaluate model (nn.Module) on data loaded by eval_loader (torch.utils.data.DataLoader)
Check top `k` (default: 1) predictions for each class while evaluating class accuracies
Returns:
`img_acc`: ... | 5,300,259 |
def cli_handle_exception(exception_handler, exception_classes):
"""
deal with exception stack info, and then just throw the wrapper exception by cli
>>> def cli_handler1(ex):
... assert False, 'Need root permission'
>>> @cli_handle_exception(cli_handler1, ZeroDivisionError)
... def... | 5,300,260 |
def getMonthlyReportList(userId, year, month):
"""選択された月の1ヶ月分の月報データを取得するMapperを呼び出す
:param userId: 登録ユーザID
:param year: 登録年
:param month: 登録月
"""
dto = __getList(userId, year, month)
return dto | 5,300,261 |
def render_path(**data) -> None:
"""Draws an AgentPath.
Args
- context: A SimulationContext instance.
Context Details
- cell_size
- path
- cell_center_x_offset
- cell_center_y_offset
"""
logger.info('Renderer: render_path')
context: SimulationContext = data['context']
path: Age... | 5,300,262 |
def test_automl_max_iterations(
parallel_engine_type,
pool_type,
X_y_binary_cls,
cluster,
thread_pool,
process_pool,
sequential_engine,
):
"""Making sure that the max_iterations parameter limits the number of pipelines run."""
X, y = X_y_binary_cls
resources, client_class, engin... | 5,300,263 |
def _setup_cached_extents_hints(stage, root_path, meshes, times):
"""Add bounding box information to the a UsdSkelRoot Prim.
Adding an extentsHint onto the root skeleton is an optional part of
exporting a USD skeleton. But if USD has these values pre-cached,
it can be used to cull out-of-frame meshes w... | 5,300,264 |
def frequency_sort(items):
"""
Return rating by frequency
"""
if sorted(items) == list(set(items)):
return items
elif len(set([items.count(x) for x in items])) == 1:
return sorted(items)
else:
return sorted(
sorted(items, reverse=True), key=lambda k: (item... | 5,300,265 |
def read_ts_guess_atomic_numbers(content):
"""Read structure from xtbscan.log file """
atom_symbols = []
number_of_atoms = int(content.split('\n')[0].strip())
ts_guess_energy, ts_index = read_ts_guess_energy(content)
ts_index = int(ts_index)
i = 0
for line in content.split('\n'):
i... | 5,300,266 |
def templatepartsmap(spec, t, partnames):
"""Create a mapping of {part: ref}"""
partsmap = {spec.ref: spec.ref} # initial ref must exist in t
if spec.mapfile:
partsmap.update((p, p) for p in partnames if p in t)
elif spec.ref:
for part in partnames:
ref = '%s:%s' % (spec.ref... | 5,300,267 |
def _gen_chamnet_v2(depth_multiplier, num_classes=1000, **kwargs):
""" Generate Chameleon Network (ChamNet)
Paper: https://arxiv.org/abs/1812.08934
Ref Impl: https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/modeling/backbone/fbnet_modeldef.py
FIXME: this a bit of a... | 5,300,268 |
def two_p(name, space="nm", index_key=None):
"""
Return expression representing a 1-boson operator
name (str): Name of operator
space (str): Name of boson space
"""
x = Idx(0, space, fermion=False)
y = Idx(1, space, fermion=False)
t1 = Term(
1, [Sigma(x), Sigma(y)], [Tensor([x, ... | 5,300,269 |
def create_sig_selectors(width, bandwidth, scheme):
"""Generate indices for LSH band selectors
:param width:
:type width: int
:param bandwidth:
:type bandwidth: int
:param scheme:
:type scheme: str
:return:
:rtype: tuple
"""
split_res = re.split(r'\b([a-zA-Z]+)(?=\d+\b)', s... | 5,300,270 |
def run_training(
# pylint: disable=too-many-arguments, too-many-locals
learnsteps,
train_freq,
batch_size,
exploration_fraction,
early_exit_factor,
num_processing_steps,
latent_size,
num_layers,
seedgen,
rl_seed,
experiment_name,
prioritized,
prioritized_replay_a... | 5,300,271 |
def non_nan_values_per_image(input_data):
"""Create boolean mask to index nans in original data,
assuming all samples in the dataset have nans at the same position"""
boolean_nan_idx = numpy.isnan(input_data[:, 0, 0])
count = numpy.count_nonzero(numpy.isnan(input_data[:, 0, 0]))
non_nan_values = int... | 5,300,272 |
def fit_pipeline(j_dataset, j_model, df):
"""
fit the model with data provided in the dataframe df, and information on the dataset in json format
:param j_dataset: dataset info in json format
:param j_model: model as a json
:param df: data as dataframe (including x and y columns and columns not use... | 5,300,273 |
def test_simulate(xes: fd.ERSource):
"""Test the simulator with and without fix_truth"""
n_ev = int(1e3)
# Test simulate with number of events
simd = xes.simulate(n_ev)
assert len(simd) <= n_ev
# Test n_events etc. have not been changed
assert xes.n_events == 2
assert len(xes.data) == ... | 5,300,274 |
def _find_sub_prog():
"""
Returns the first job submission command found on the system.
Currently, only qsub and sbatch are supported
"""
possible_sub_prog_list = ['sbatch', 'qsub']
for prog in possible_sub_prog_list:
if popen('command -v ' + prog).read() != '':
return prog
... | 5,300,275 |
def processed_json_filename(path):
"""Take the path to a raw json asset and return the filename of the binary asset."""
return os.path.basename(processed_json_path(path)) | 5,300,276 |
def create_tesseract_trainFile(language, font, shell_type, outdir=os.curdir):
"""
shell type cmd | bash
:param shell_type:
:return:
"""
common_shell_str1 = ['# create box file',
'tesseract '
'-psm 8 '
'{l}.{font}.ex... | 5,300,277 |
async def cmd_line_detection_on(
bot: CameraBot, message: Message, cam: HikvisionCam
) -> None:
"""Enable camera's Line Crossing Detection."""
event = DetectionConfEvent(
cam=cam,
event=Event.CONFIGURE_DETECTION,
type=Detection.LINE,
message=message,
switch=True,
... | 5,300,278 |
def split_chunks(shape, chunks):
"""
Yield a set of ndindex indices for chunks over shape
If the shape is not a multiple of the chunk size, some chunks will be
truncated.
For example, if a has shape (10, 19) and is chunked into chunks
of shape (5, 5):
>>> from versioned_hdf5.slicetools im... | 5,300,279 |
def generate_evaluation_table(
evaluation_directory: str,
) -> Tuple[Dict[str, Any], List[Dict[str, Any]], str]:
"""
Generate a table from the currently selected results.json summary file.
Parameters
----------
evaluation_directory : str
directory of the mcts evaluation (containing all ... | 5,300,280 |
async def test_update_permissions(error, spawn_client, no_permissions, resp_is):
"""
Test that a valid request results in permission changes.
"""
client = await spawn_client(authorize=True, administrator=True)
if not error:
await client.db.groups.insert_one(
{"_id": "test", "pe... | 5,300,281 |
def recommendation(request):
"""
Get:
Returns a list of recommendations
Input:
{
from: optional(str),
to: optional(str),
}
Output:
[
Recommendations
]
===
Input:
{
feedback_id: int,
feedback: str,
}
Output:
Empty Bo... | 5,300,282 |
def get_active_days_in_range(
range_start, range_end, ad_delivery_start_time_series, last_active_date_series):
"""Calculate the days an ad was active in a given range.
Args:
range_start: datetime.date Start of period of interest
range_end: datetime.date End of period of interest
... | 5,300,283 |
def _f1_score(guess, answers):
"""Return the max F1 score between the guess and *any* answer."""
if guess is None or answers is None:
return 0
g_tokens = normalize_answer(guess).split()
scores = [
_prec_recall_f1_score(g_tokens, normalize_answer(a).split())for a in answers
]
retu... | 5,300,284 |
def semi_train(task_name,sed_model_name,at_model_name,augmentation):
""""
Training with semi-supervised learning (Guiding learning)
Args:
task_name: string
the name of the task
sed_model_name: string
the name of the the PS-model
at_model_name: string
the name of the the PT-model
... | 5,300,285 |
def handle_post_sleep_notification(msg):
"""Process an internal pre sleep notification message."""
if not msg.gateway.is_sensor(msg.node_id):
return None
handle_smartsleep(msg)
handle_wakeup(msg)
return None | 5,300,286 |
def pozice_od_hrace():
"""Fuknce pozice od hrace se zeptá uživatele kam chce umístít svůj znak,
ověří, že se jedná o číslo a pozici vrátí"""
while True:
try:
cisloPolickaHrace = int(input("Na kolikáté místo v herním poli chceš umístit tvůj znak \"x\"? "))-1
except ValueErro... | 5,300,287 |
def plaintext(msg):
""" Parse a SNS message and relay it on to pusher.com """
return msg | 5,300,288 |
def multihead_attention(
queries,
keys,
num_units=None,
num_heads=8,
dropout_rate=0,
is_training=True,
causality=False,
scope="multihead_attention",
reuse=None,
with_qk=False,
):
"""Applies multihead attention.
Args:
queries: A 3d tensor with shape of [N, T_q, C_q]... | 5,300,289 |
def test_lint_wrong_fixture(fixture_path, all_violations):
"""Checks that `lint` command works for wrong files."""
process = subprocess.Popen(
[
'dotenv-linter',
fixture_path('.env.incorrect'),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
uni... | 5,300,290 |
def conn_record_to_message_repr(conn: ConnectionRecord) -> Dict[str, Any]:
"""Map ConnectionRecord onto Connection."""
def _state_map(state: str) -> str:
if state in ('active', 'response'):
return 'active'
if state == 'error':
return 'error'
return 'pending'
... | 5,300,291 |
def test_list_id_enumeration_1_nistxml_sv_iv_list_id_enumeration_2_5(mode, save_output, output_format):
"""
Type list/ID is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/ID/Schema+Instance/NISTSchema-SV-IV-list-ID-enumeration-2.xsd",
instance="nistData/list/... | 5,300,292 |
def strategy_connected_sequential_bfs(G, colors):
"""Returns an iterable over nodes in ``G`` in the order given by a
breadth-first traversal.
The generated sequence has the property that for each node except
the first, at least one neighbor appeared earlier in the sequence.
``G`` is a NetworkX gra... | 5,300,293 |
def provider_borad(request):
"""show the provider board"""
page_index = request.POST.get('page_index')
page_size = request.POST.get('page_size')
sort_type = request.POST.get('sort_type')
page_size = interface.handle_page(page_size, 5)
page_index = interface.handle_page(page_index, 1)
msg_dat... | 5,300,294 |
def generate_common_invalid_structure_schemas():
"""
Generate schemas that make schema request cannot be submitted to ledger.
:return: schema and ids.
"""
data = list()
ids = list()
ids.append("schema_build_schema_req_fails_with_missing_schema_version")
data.append({'data': schema()})... | 5,300,295 |
def auto_log(logger_name):
"""
A decorator that wraps the passed in function, logs entering and exiting the function,
and logs exceptions should one occur. Exceptions are reraised.
Tag each method or function with @auto_log(__name__) to automatically log calls.
Logs these calls at DEBUG level.
... | 5,300,296 |
def _is_extern_seg(seg):
"""Returns `True` if `seg` refers to a segment with external variable or
function declarations."""
if not seg:
return False
seg_type = idc.get_segm_attr(seg.start_ea, idc.SEGATTR_TYPE)
return seg_type == idc.SEG_XTRN | 5,300,297 |
def _fixpath(p):
"""Apply tilde expansion and absolutization to a path."""
return os.path.abspath(os.path.expanduser(p)) | 5,300,298 |
def get_indices_remain_type_zero(p: np.ndarray) -> List[int]:
"""p is assumed to be a probability distribution with type-0."""
indices = list(range(len(p)))
indices_removed = get_indices_removed_type_zero(p)
for i in indices_removed:
indices.remove(i)
return indices | 5,300,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.