content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def erratic_leveling(target_level: int) -> int:
"""
Non-trivial calculation of experience to next level for an erratic leveling curve.
Args:
target_level (int): the level to reach.
Returns:
The amount of experience to reach this level from the ground up (from experience 0),
acc... | 0841aed503226932ebd49a66cdd42665eee265b2 | 31,200 |
import re
def get_puppetfile_tags(puppetfile):
"""
obtain tags from Puppetfile
:return: tuple(list, list)
"""
regex_vcs = re.compile(r"^:(git|svn)\s+=>\s+['\"](.+)['\"]\,", re.I)
regex_tag = re.compile(r"^:(ref|tag|commit|branch)\s+=>\s+['\"](.+)['\"]\,?", re.I)
vcss = []
tags = []
... | 6beec37d4c8a3a3b9a2c845cea0f5e12e18af620 | 31,201 |
def inf_is_wide_high_byte_first(*args):
"""
inf_is_wide_high_byte_first() -> bool
"""
return _ida_ida.inf_is_wide_high_byte_first(*args) | 13f30f49823e792ec83fb4b50266c72ceeed942c | 31,202 |
def rewrite_and_sanitize_link(link_header):
"""Sanitize and then rewrite a link header."""
return rewrite_links(sanitize_link(link_header)) | 907cc1492be7162611408200ad660e1a49dd5e14 | 31,203 |
def user_info():
"""
用户个人中心页面显示
:return:
"""
user = g.user
if not user:
return redirect("/")
data = {
"user": user.to_dict()
}
return render_template("news/user.html", data=data) | 2cbe80c6086bffbb5e147ee756b7b393b546da99 | 31,204 |
def cartesian2polar(state: CartesianState, state_goal : CartesianState) -> PolarState:
"""
rho is the distance between the robot and the goal position
: \sqrt((x*-x)^2 + (y*-y)^2)
alpha is the heading of the robot relative the angle to the goal
: theta - atan2((y*-y),(x*-x))
beta is the goal pos... | 92eea79a8ac8f7c83e78d9aaaff3d6af500b9876 | 31,205 |
def organize_array_by_rows(unformatted_array, num_cols):
"""Take unformatted array and make grid array"""
num_rows = int(len(unformatted_array) / num_cols)
array = []
for row in range(num_rows):
array.append(unformatted_array[row * num_cols:(row + 1) * num_cols])
return array | 8a7d74ea593bfcc5c4d3a92d1c192b2bf628f641 | 31,206 |
from typing import Union
from typing import Literal
from typing import Sequence
def group_abundance(
adata: AnnData,
groupby: str,
target_col: str = "has_ir",
*,
fraction: Union[None, str, bool] = None,
sort: Union[Literal["count", "alphabetical"], Sequence[str]] = "count",
) -> pd.DataFrame:
... | adfc5047349ec5fcffdc05de0ae2ecdfbf9b8b6c | 31,207 |
def infer(model, text_sequences, input_lengths):
"""
An inference hook for pretrained synthesizers
Arguments
---------
model: Tacotron2
the tacotron model
text_sequences: torch.Tensor
encoded text sequences
input_lengths: torch.Tensor
input lengths
Returns
-... | e7937395956e2dcd35dd86bc23599fbb63417c22 | 31,208 |
def build_info(image, spack_version):
"""Returns the name of the build image and its tag.
Args:
image (str): image to be used at run-time. Should be of the form
<image_name>:<image_tag> e.g. "ubuntu:18.04"
spack_version (str): version of Spack that we want to use to build
Retur... | bb09a530e2fdf50b78225647df1238ae08fe5b3d | 31,209 |
def _get_data_attr(data, attr):
"""Get data object field."""
if isinstance(data, dict):
# `Data` object's id is hydrated as `__id` in expression engine
data = data["__id"]
data_obj = Data.objects.get(id=data)
return getattr(data_obj, attr) | bdc90d01172655f77680f0c373ed609b4100e874 | 31,210 |
def get_user_project(user, dds_project_id):
"""
Get a single Duke DS Project for a user
:param user: User who has DukeDS credentials
:param dds_project_id: str: duke data service project id
:return: DDSProject: project details
"""
try:
remote_store = get_remote_store(user)
pr... | 71649da2b092954d8f7d65059edd75fc18a8e750 | 31,211 |
def _event_split(elist):
"""Split event list into dictionary of event keywords
"""
eventdict = dict()
dictkeys = (roxar.EventType.WLIMRATE,
roxar.EventType.WLIMPRES,
roxar.EventType.WLIMRATIO,
roxar.EventType.WHISTRATE,
roxar.EventType.WHIS... | 8097fdee8b36881b0c5a4851165ac57f70482415 | 31,212 |
import sys
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
... | 2dfc13a2ec812b0f0877ab936392961885099217 | 31,213 |
import random
import re
def generate_reply(utt, dais):
"""Generate a reply task for the given utterance and DAIs list."""
ret = DataLine(dat='reply', abstr_utt=utt, abstr_da='&'.join([unicode(dai) for dai in dais]))
utt, dais = deabstract(utt, dais)
# offer a ride (meeting the specifications in dai... | 9a9d1a7271b03e01e492be830e29725399f61387 | 31,214 |
def create_concept_graphs(example_indices, grakn_session):
"""
Builds an in-memory graph for each example, with an example_id as an anchor for each example subgraph.
Args:
example_indices: The values used to anchor the subgraph queries within the entire knowledge graph
grakn_session: Grakn S... | 66d5d13fad865e6d6437eb29d20e611e509ad7f7 | 31,215 |
def GetChange(host, change):
"""Queries a Gerrit server for information about a single change."""
path = 'changes/%s' % change
return _SendGerritJsonRequest(host, path) | 3f4c7c3554fdbba0cc6bc0c8c513823859d22d61 | 31,216 |
import os
import time
def train_net(logger, dims=20, deep=True, conv_channel=32, init="glorot_uniform", fast=False, num_iterations=20,
visual_name="", lr_start=1e-3, LR_decay=0.95, size=1600, input_name="new_eval", N_Cls=10,
bn=True, batch_size=32, input=None, use_sample_weights=False, min... | 70a97e9505b9fa7bf05fba786add8035c4e11391 | 31,217 |
def block_shape(f):
"""
find the block shape (nxb, nyb, nzb) given the hdf5 file f
returns
dimension, (nxb, nyb, nzb)
"""
if 'integer scalars' in f.root:
params = f.getNode(f.root, 'integer scalars').read()
p_dict = dict((name.rstrip(), val) for name, val in params)
... | ce7e3f58400185fa76855dc809f78867905915bc | 31,218 |
def model_init(rng_key, batch, encoder_sizes=(1000, 500, 250, 30)):
"""Initialize the standard autoencoder."""
x_size = batch.shape[-1]
decoder_sizes = encoder_sizes[len(encoder_sizes) - 2::-1]
sizes = (x_size,) + encoder_sizes + decoder_sizes + (x_size,)
keys = jax.random.split(rng_key, len(sizes) - 1)
par... | 937aa19a7bac1fd1e90e6ef7d7027dcb3822dcc8 | 31,219 |
def do2_SVU(calphase, temp, csv):
"""
Description:
Stern-Volmer-Uchida equation for calculating temperature
corrected dissolved oxygen concentration. OOI L1 data product.
Usage:
DO = do2_SVU(calphase, temp, csv)
where
DO = dissolved oxygen [micro-mole/L]
... | be3d3faee477749a2f7b2429759f4aff38b9a0ac | 31,220 |
def _make_rotation_matrix(vector_1,vector_2):
"""" Generates the rotation matrix from vector_1 to vector_2"""
# Use formula for rotation matrix: R = I + A + A^2 * b
# https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d
v = np.cross(vector_1,vecto... | 17c24c4c4e6c8378b65076686f4d80736d6ccf3e | 31,221 |
def get_models(models='all'):
"""
Returns model names as a list
Parameters
----------
models: str
OPTIONAL. Default value is 'all' in which case all keys in defaule_models are returned.
If 'mixed' is passed, only the MixedFluid model names are returned.
"""
if models == 'all':
return list(default_models.ke... | dcf0a00946f3146e5511825d875947bb5278be6a | 31,222 |
def other_language_code():
"""Language code used for testing, currently not set by user."""
return 'de-DE' | 2cbac23cd7a13e71991be6516a3a38dee19ae690 | 31,223 |
import numpy
def do_novelty_detection(
baseline_image_matrix, test_image_matrix, image_normalization_dict,
predictor_names, cnn_model_object, cnn_feature_layer_name,
ucn_model_object, num_novel_test_images,
percent_svd_variance_to_keep=97.5):
"""Does novelty detection.
Specifi... | 69181690b81a987b45dcdbea5b0febe8928b365b | 31,224 |
from datetime import datetime
def parse_last_timestamp(df):
"""
Parse last timestamp from dataframe.
Add one minute forward to prevent the script from fetching the same value.
The last timestamp already in database, so we need to fetch the weather data
one minute forward.
"""
if df.empty:... | 2fe7430344229e89aab33ef47af944735b79c169 | 31,225 |
def len_subword_features():
""" TODO: There is probably a better way to centralize this """
# Grapheme embedding (4), grapheme duration (1)
LEN_GRAPHEME_FEATURES = 5
return LEN_GRAPHEME_FEATURES | d9e0b3959b340a29d11817e9ac94e7f1078a7bc6 | 31,226 |
def NextLexem_OperatorPredicate(op_value):
""" construct a predicate: lexem_list -> boolean
which checks if the next lexem is an operator whose value macthes
@p op_value (do not consume it) """
def predicate(lexem_list):
if len(lexem_list) == 0:
return False
head_lexe... | caf2866e85a42bee2e7eab0355cad4568bde46de | 31,227 |
import torch
def optim_inits(objective, x_opt, inference_samples, partition_samples, edge_mat_samples, n_vertices,
acquisition_func=expected_improvement, reference=None):
"""
:param x_opt: 1D Tensor
:param inference_samples:
:param partition_samples:
:param edge_mat_samples:
:p... | f048fc3290d890bc687f3176f66e5ad86dfa5141 | 31,228 |
from sys import stderr
def suggest_max_coverage(alignment_file, y):
"""Estimate a max-coverage value for use with dysgu. Mean genome coverage is estimated from the index file, so
will only be useful for whole-genome alignment files"""
f = pysam.AlignmentFile(alignment_file)
cov, read_length = index_st... | 34b8c9327d3c4e7304845955bf82e7641435777e | 31,229 |
import torch
def stack(mems):
"""
Stack a list of tensors
Could use torch.stack here but torch.stack is much slower
than torch.cat + view
Submitted an issue for investigation:
https://github.com/pytorch/pytorch/issues/22462
FIXME: Remove this function after the issue above is resolved
... | e65cfe65d032dd42a7297f35092fa484bb7f4867 | 31,230 |
def _pushb2phases(pushop, bundler):
"""handle phase push through bundle2"""
if 'phases' in pushop.stepsdone:
return
b2caps = bundle2.bundle2caps(pushop.remote)
if not 'pushkey' in b2caps:
return
pushop.stepsdone.add('phases')
part2node = []
enc = pushkey.encode
for newrem... | ff8f5c839919c6593e2d7d5cb98c477f8b2bc735 | 31,231 |
def predict_all(model, all_data):
"""
Predict odor probabilities for all trials.
:param model: (keras) decoding model
:param all_data: (4d numpy array) data of format [trial, window, neuron, time]
:return: (3d numpy array) prediction of format [trial, time, odor]
"""
test = stack_data(all_d... | 5bc748f6eddc4e6791601b87ff73a000a72efa4c | 31,232 |
def normalize(X):
"""Normalize the given dataset X
Args:
X: ndarray, dataset
Returns:
(Xbar, mean, std): tuple of ndarray, Xbar is the normalized dataset
with mean 0 and standard deviation 1; mean and std are the
mean and standard deviation respectively.
Note:
... | 5db71253b148387663b8575cf4df086cd182fbff | 31,233 |
def get_lat_lon(exif_data):
"""Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above)"""
lat = None
lon = None
if "GPSInfo" in exif_data:
gps_info = exif_data["GPSInfo"]
gps_latitude = _get_if_exist(gps_info, "GP... | d653dd84cd47efb2063db724cf7a88fa3f2a7490 | 31,234 |
import requests
def get_rendered_original_stream(warc_filename, warc_offset, compressedendoffset, payload_only=True):
"""
Grabs a resource.
"""
# If not found, say so:
if warc_filename is None:
return None, None
# Grab the payload from the WARC and return it.
url = "%s%s?op=OPEN&u... | e3fce32a061445e6ec3f69bd80e7ef46cd2dedaf | 31,235 |
import argparse
def get_parser() -> argparse.ArgumentParser:
"""Create and return the argparser for concord flask/cheroot server"""
parser = argparse.ArgumentParser(
description="Start the concord flask/cheroot server",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.... | 8ffec895b722c975f79b2d7e7bd1ccae11f52347 | 31,236 |
def reduce_dimensions(df, reduce_cols=None, n_components=2):
"""
given a dataframe, columns to reduce and number of components for dimensionality reduction algorithm
returns a dictionary of reduction algorithm to it's name and reduced df.
dimensionality reduction or dimension reduction is the process o... | 39c5bf6257da93f449dc4081fde98ecd18465a0f | 31,237 |
import numpy
import math
def _dct_or_dst_type3(
x, n=None, axis=-1, norm=None, forward=True, dst=False, overwrite_x=False
):
"""Forward DCT/DST-III (or inverse DCT/DST-II) along a single axis.
Parameters
----------
x : cupy.ndarray
The data to transform.
n : int
The size of th... | 7e617e478c38ea47767a259df74581c960bfcaff | 31,238 |
def indi_events(person, tags=None):
"""Returns all events for a given individual.
Parameters
----------
person : `ged4py.model.Individual`
GEDCOM INDI record.
tags : `list` [ `str` ], optional
Set of tags to return, default is all event tags.
Returns
-------
events : `l... | 632a532ddcf6d187d1a9f8a5cf7b4451b3d73f37 | 31,239 |
def encrypt(key, plaintext):
"""Encrypt the string and return the ciphertext"""
return ''.join(key[l] for l in plaintext) | 0dc693fe1357756fdfee21cbc847fc6929dab2d1 | 31,240 |
from re import T
def rename_keys(
mapping: T.Dict[str, T.Any],
*,
prefix: T.Optional[str] = None,
suffix: T.Optional[str] = None
) -> T.Dict[str, T.Any]:
"""Renames every key in `mapping` with a `prefix` and/or `suffix`.
Args:
mapping (T.Dict): Mapping.
prefix (str, optional):... | fdfc335354e0ccf36c5416159927b7ffe8e5aec9 | 31,241 |
def any_root_path(path):
"""Rendering the React template."""
return render_template('index.html') | ba1069e4e52f2388b7a68129fa6ee7a4701ce31b | 31,242 |
def getChartdata():
"""
获取图表数据
params: request
return: response
"""
data = {'staff': {}}
data['staff']['is_worker'] = Staff.query.filter(Staff.is_leave==True).count()
data['staff']['not_worker'] = Staff.query.filter(Staff.is_leave==False).count()
data['staff']['total_worker'] = data[... | 70dcee23ca8e55ab8500e6ca56d44216aea69f95 | 31,243 |
def md_to_html(content):
""" Converts markdown content to HTML """
html = markdown.markdown(content)
return html | 16c67405d35b1119e2f52708aed26ad2f3f23244 | 31,244 |
import logging
def userdata_loader(s3_training_bucket='', trainer_script_name='trainer-script.sh'):
"""
Given the filepath for the trainer-script, load and return its contents as a str.
:param s3_training_bucket:
:param trainer_script_name:
:return:
"""
try:
# If the user didn't p... | 9ed6bf1c4cb252c855acf4ed943f3c8ce2a07952 | 31,245 |
def timer(string,i,f):
"""
Takes in:
i = starting time;
f = finishing time.
Returns: Time taken in full minutes and seconds.
"""
sec = f - i # Total time to run.
mins, sec= divmod(sec, 60.0)
time = string+' time: '+str(int(mins))+'min '+str(int(sec))+'s'
print(time)
... | cbb3c857160a4cbade7a02311455737b1e6e89ef | 31,246 |
def format_server_wrs(world_records, server_id):
"""Format the world records on the server browser to a table
world_records format: {server_id: [list of records]}
where every record is a tuple like {map_name, mode, date, time, player_name, steam_id, rank} accessible like sqlalchemy result"""
if ... | eef6be19b13694e8e7c7bf33d833c2f74960ad95 | 31,247 |
from pathlib import Path
def clean_file(path=Path('data') / 'Fangraphs Leaderboard.csv',
level='MLB', league='', season='', position=''):
"""Update names for querying and provide additional context.
Args:
level (str): the minor/major leave level selected. Default MLB.
league (s... | 4b01de07630f694c4b5a8010036b6394bed414ec | 31,248 |
def TextRangeCommandStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | dacf2fdb830f0fdfc5951288730963e3deb77741 | 31,249 |
import random
def ai_derp(gstate: TicTacToe, *args):
"""AI that randomly picks the next move"""
return random.choice(list(gstate.next_moves.keys())) | bfa1521c4bc2d4dad79a9f91b6bfed14b872f918 | 31,250 |
def get_logits_img(features, n_classes, mode, params):
"""Computes logits for provided features.
Args:
features: A dictionary of tensors that are the features
and whose first dimension is batch (as returned by input_fn).
n_classes: Number of classes from which to predict (i.e. the number
... | e4170d31949c531c54021b6a17c9cbd6306175eb | 31,251 |
def ccnv(pad=0):
"""Current canvas"""
global _cnvs
if pad == 0:
return _cnvs[-1]
_cnvs[-1].cd(pad)
return _cnvs[0].GetPad(pad) | 121f61661ea2a7d9ae941503c3bc2caa29f86dbd | 31,252 |
import functools
import unittest
def NetworkTest(reason='Skipping network test'):
"""Decorator for unit tests. Skip the test if --network is not specified."""
def Decorator(test_item):
@functools.wraps(test_item)
def NetworkWrapper(*args, **kwargs):
if GlobalTestConfig.NETWORK_TESTS_DISABLED:
... | f694902249d38be4d897ac20d47a23eb9ce10223 | 31,253 |
from typing import Dict
from typing import Any
def azure_firewall_network_rule_collection_update_command(client: AzureFirewallClient,
args: Dict[str, Any]) -> CommandResults:
"""
Update network rule collection in firewall or policy.
Args:
c... | 4d3d5ac09d345d661b2ef258ba2d6311c0f5b764 | 31,254 |
from typing import Optional
def get_stream(id: Optional[str] = None,
ledger_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStreamResult:
"""
Resource schema for AWS::QLDB::Stream.
"""
__args__ = dict()
__args__['id'] = id
_... | 244721f3424c8de4c923b8eb57c96429c028280d | 31,255 |
def _is_course_or_run_deleted(title):
"""
Returns True if '[delete]', 'delete ' (note the ending space character)
exists in a course's title or if the course title equals 'delete' for the
purpose of skipping the course
Args:
title (str): The course.title of the course
Returns:
... | c32c69e15fafbc899048b89ab8199f653d59e7a8 | 31,256 |
def copy_installer_dict(installer_dict, default_installer):
"""Copy installer dict.
The installer rules themselves are not deep-copied.
'default_installer' installer names are replaced according to
``default_installer``.
:param str default_installer: name of the default installer
"""
resu... | 1bae37f603b0ac36b80e433b44722245f5df0090 | 31,257 |
import numpy
def pbg_dispersion_1d_imre(
results,
wave="p",
size=(6,4), xlim=(-1, 1), ylim=(0, 1)
):
"""
Plots the photonic dispersion (Bloch wavevector) of a photonic crystal structure,
computed for a range of frequencies (wavelengths) and one angle of incidence.
... | d1c8605e1255669b31f9caf530f3c8669a2e03a6 | 31,258 |
from typing import OrderedDict
def map_constructor(loader, node):
"""
Constructs a map using OrderedDict.
:param loader: YAML loader
:param node: YAML node
:return: OrderedDictionary data
"""
loader.flatten_mapping(node)
return OrderedDict(loader.construct_pairs(node)) | 21bf92d0c3975758ae434026fae3f54736b7f21d | 31,259 |
def index():
"""首页"""
return redirect(url_for('site.hot')) | 816585c515c254929fdbd0f8e2c0af99c73f9f9d | 31,260 |
def tpr(df, label_column):
"""Measure the true positive rate."""
fp = sum((df['predictions'] >= 0.0) & (df[label_column] > 0.5))
ln = sum(df[label_column] > 0.5)
return float(fp) / float(ln) | 62cd3908f5e8490c507b2b320a8a453aa861f77d | 31,261 |
from typing import Optional
def get_pathway_names(
database: str,
pathway_df: pd.DataFrame,
kegg_manager: Optional[bio2bel_kegg.Manager] = None,
reactome_manager: Optional[bio2bel_reactome.Manager] = None,
wikipathways_manager: Optional[bio2bel_wikipathways.Manager] = None
):
... | 40397aa26fc90b06f21fe30605ef654b14a98662 | 31,262 |
from pathlib import Path
def gather_rgi_results(rgi_sample_list: [RGIResult], outdir: Path) -> tuple:
"""
Symlinks RGI result files to a single destination folder -- required for rgi heatmap command
:param rgi_sample_list: List containing RGIResult object instances
:param outdir: Destination directory... | 664172d0d6de5619c7f92ba74a5f3673726aedf9 | 31,263 |
from connio.rest.api.v3.account.propertyy import PropertyInstance
def retention(retention):
"""
Serialize a retention object to retention JSON
:param retention: PropertyInstance.Retention
:return: jsonified string represenation of obj
"""
if retention is values.unset or retention is None... | 38762297e80c434ce3e561731850b40137a16fdb | 31,264 |
def get_tool_path(loader, node):
""" yaml tag handler to access tools dict at load time """
py_str = loader.construct_python_str(node)
return py_str.format(**tools) | 22e2d82e428e376b31082b213a50d7ed33a5045f | 31,265 |
def _get_oath2_access_token(client_key, client_secret):
"""
Query the vistara API and get an access_token
"""
if not client_key and not client_secret:
log.error(
"client_key and client_secret have not been specified "
"and are required parameters."
)
retu... | 2be67e8305aac64f3cf39517e64efa7659100bf5 | 31,266 |
def sanity_check_dp(A_org, XW, U, L, delta_l, delta_g, check_symmetry=True, \
activation='linear'):
"""
Sanity approach for solving min_{A_G^{1+2+3}} F_c(A) + np.sum(A.*L)
param:
A_org: original adjacency matrix
XW: X... | 21f51523b21c2ca94feddf4724d7848317054279 | 31,267 |
def quadratic_bezier(t, p0, p1, p2):
"""
:return: Quadratic bezier formular according to https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B%C3%A9zier_curves
"""
return (1 - t) * ((1 - t) * p0 + t * p1) + t * ((1 - t) * p1 + t * p2) | ac9319683afb5b156ac40ba24865d9bc04531917 | 31,268 |
def add_musician_genres(musician, genre_list):
"""Add genres to a musician's profile"""
musician_genres = []
found_genres = Genre.query.filter(Genre.genre_name.in_(genre_list)).all()
for genre in found_genres:
musician_genre = MusicianGenre(genre_id=genre.genre_id,
... | 2557498853b8ecb634c282db5c27d0772ae066a1 | 31,269 |
def test_eat_exceptions_normal_case():
"""
If no exceptions, this wrapper should do nothing.
"""
@utils.eat_exceptions
def test_function(x):
return x
assert test_function(1) == 1 | ce16fff9511ac52b1e2ffb08305c839a1bb36b57 | 31,270 |
def delete_system_interface(api_client, interface_id, **kwargs): # noqa: E501
"""delete_system_interface # noqa: E501
Delete System Interface # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> response = awa... | a6c4db5d1c5ea1674146a7d723b8cea5725dcd51 | 31,271 |
def IsPlacementGroupCompatible(machine_type):
"""Returns True if VMs of 'machine_type' can be put in a placement group."""
prefix = machine_type.split('.')[0]
return prefix not in NON_PLACEMENT_GROUP_PREFIXES | 4c5cd10e2f2024d93b676df87a6e531fb866c228 | 31,272 |
import inspect
import os
import pathlib
def join_paths(new_Folder, file_Name=False):
"""
Requer uma string. Nome da pasta a ser criada.
Por padrão file_Name é False.
Quando file_Name é falso retorna o abspath da
pasta passada em folder.
Quando file_Name é verdadeiro junta o abspath da pasta
... | b709cd879f4c820517fc0a4ac044cb7ea3bce10e | 31,273 |
import binascii
def create_public_key_from_b64(b64Key: bytes) -> X25519PublicKey:
"""Derive X25519 Private key from b64 ascii string"""
public_bytes = binascii.a2b_base64(b64Key)
loaded_private_key = X25519PublicKey.from_public_bytes(public_bytes)
return loaded_private_key | 8cdac21431ed278fb82cfc4c76379baec401e518 | 31,274 |
from re import T
def im_detect_bbox(model, images, target_scale, target_max_size, device,
captions=None,
positive_map_label_to_token=None
):
"""
Performs bbox detection on the original image.
"""
if cfg.INPUT.FORMAT is not '':
input_form... | a20c4eb8fb8b5cf37bc5ee59901504e3a03a1307 | 31,275 |
import warnings
def jmap(g, H, ae0, be0, af0, bf0, max_iter=1000, tol=1e-4, rcond=None, observer=None):
"""Maximum a posteriori estimator for g = H @ f + e
p(g | f) = normal(H f, ve I)
p(ve) = inverse_gauss(ae0, be0)
p(f | vf) = normal(0, vf I)
p(vf) = inverse_gauss(af0, bf0)
JMAP: maximizes... | 82b1199dfbaf1ecc9811b0d3127d976304df576f | 31,276 |
def get_chats(im):
"""This function gets the chatting messages.
Arguments:
im (PIL.Image.Image): Image object
Return:
Image object list (PIL.Image.Image).
[0]: The most latest chatting message. e.g, The most below messages.
"""
return get_chat_msg(im) | b3d30ee36025866020e8b8ce4c1b1477c2950fa3 | 31,277 |
def state_field(value):
"""Fetch the pagination state field from flask.request.args.
:returns: list of the state(s)
"""
states = istate.States.all()
value = value.split(',')
invalid_states = [state for state in value if state not in states]
assert not invalid_states, \
_('State(s) "... | c7e3d31780994c46fc1e43fc3f4398a4e93e77f6 | 31,278 |
import torch
def cal_smoothness_orig(var1_orig, var2_orig, var3_orig, io, args):
"""
Input:
var1_orig, var2_orig, var3_orig: scalar tensors, original variances on the 3 principal orientations
Return: smoothness_orig: scalar, original smoothness of this region (linearity/planarity/scattering,
... | 4713aede2109c17deb917fb2f86f73142185a258 | 31,279 |
def format_size(size):
"""Format provided size in bytes in a human-friendly format
:param int size: size to format in bytes
:return: formatted size with an SI prefix ('k', 'M', 'G', 'T') and unit
('B')
:rtype: str
"""
if abs(size) < 1000:
return str(size) + 'B'
for unit in ... | 04d9099a99e7c4863ada898096829aed9f6d7fc1 | 31,280 |
def get_acl_permission(acl, complete_acl_list):
"""
This uses numpy's vectorized operations to quickly match the acl returned from the API, to
the complete list of acls to get the description.
"""
index = -1
where_arrays = np.where(acl == complete_acl_list[:,0])
try:
index = wher... | 55dc256c75be9dfcf897fffc6a5842cc19dbf1d8 | 31,281 |
import torch
def interface_script(mod_interface, nn_module):
"""
Makes a ScriptModule from an nn.Module, using the interface methods rule for
determining which methods to compile.
Args:
mod_interface: the interface type that the module have
nn_module: The original Python nn.Module th... | dcfe3b7710a353da53c3e3b3ee2d360a943b77dd | 31,282 |
def create_call_error(message: str) -> str:
"""Create CallError serialized representation based on serialize Call.
Raises ValueError if message is not type Call. CallResult and CallError
don't require response.
"""
call: Call = unpack(message)
if isinstance(call, Call):
call_error: Call... | c30a5c50c8d43805b554e4b2002bdc73be568918 | 31,283 |
def filter_boxes(min_score, boxes, scores, classes):
"""Return boxes with a confidence >= `min_score`"""
n = len(classes)
idxs = []
for i in range(n):
if scores[i] >= min_score:
idxs.append(i)
filtered_boxes = boxes[idxs, ...]
filtered_scores = scores[idxs, ...]
filtered_... | 596c9ecab145df0d6a3a7f1da44898da27566b72 | 31,284 |
def recenter_image(im):
"""
"""
n_height, n_width = im.shape
com = nd.center_of_mass(im)
if any(np.isnan(com)):
return im
im_center = im[(com[0]-n_height/2):(com[0]+n_height/2)]
offset = [(n_height-im_center.shape[0]),(n_width-im_center.shape[1])]
if offset[0]%2 > 0:
h_odd = 1
else:
h_odd = 0
if offse... | 64a180c8ea67a8105a08e7c326cc92c6cf281803 | 31,285 |
from typing import Counter
def cal_participate_num(course: Course) -> Counter:
"""
计算该课程对应组织所有成员的参与次数
return {Naturalperson.id:参与次数}
前端使用的时候直接读取字典的值就好了
"""
org = course.organization
activities = Activity.objects.activated().filter(
organization_id=org,
status=Activity.Statu... | c2dff0f9b956c819170070116f4fda858f616546 | 31,286 |
def plot(
self,
fig=None,
ax=None,
is_lam_only=False,
sym=1,
alpha=0,
delta=0,
is_edge_only=False,
edgecolor=None,
is_add_arrow=False,
is_display=True,
is_show_fig=True,
):
"""Plot the Lamination with empty Slots in a matplotlib fig
Parameters
----------
... | b317fe6518b20cd266f035bbb6a6ff3e4de94e10 | 31,287 |
def usage_percentage(usage, limit):
"""Usage percentage."""
if limit == 0:
return ""
return "({:.0%})".format(usage / limit) | 7caf98ddb37036c79c0e323fc854cbc550eaaa60 | 31,288 |
def all(numbered=False):
"""
Get all included stanzas.
Takes optional argument numbered.
Returns a dict if numbered=True, else returns a list.
"""
return dict(zip(range(1, 165 + 1), stanzas)) if numbered else stanzas | af61087223411f3d57ec2e35f048da9da41bf469 | 31,289 |
from tensorflow.python.ops import math_ops
from tensorflow.python.framework import ops
def cosine_decay(learning_rate, global_step, maximum_steps,
name=None):
"""
"""
if global_step is None:
raise ValueError("global_step is required for cosine_decay.")
with ops.name_scope(name, "CosineDe... | 6f4395bf5ca38beb483f142acec91455e2a77ced | 31,290 |
def parse_file_header_64(bytes):
"""Parse the ELF file header."""
e_ident = {}
e_ident['EI_CLASS'] = get_bytes(bytes, 4)
e_ident['EI_DATA'] = get_bytes(bytes, 5)
endian = get_byte_order(e_ident['EI_DATA'])
e_ident['EI_VERSION'] = get_bytes(bytes, 6)
e_ident['EI_OSABI'] = get_bytes(bytes, 7)
... | 1b4a5cbd8f9dad58dc8d8ad6bd6a87f65d7bad07 | 31,291 |
def _or (*args):
"""Helper function to return its parameters or-ed
together and bracketed, ready for a SQL statement.
eg,
_or ("x=1", _and ("a=2", "b=3")) => "(x=1 OR (a=2 AND b=3))"
"""
return " OR ".join (args) | 1162600b49acb57e3348e6281767ce2fb0118984 | 31,292 |
from typing import Dict
def strip_empty_values(values: Dict) -> Dict:
"""Remove any dict items with empty or ``None`` values."""
return {k: v for k, v in values.items() if v or v in [False, 0, 0.0]} | 982814edbd73961d9afa2e2389cbd970b2bc231e | 31,293 |
import torch
def dispnet(path=None, batch_norm=True):
"""dispNet model architecture.
Args:
path : where to load pretrained network. will create a new one if not set
"""
model = DispNet(batch_norm=batch_norm)
if path is not None:
data = torch.load(path)
if 'state_dict' in d... | 8229c4616148c771686edbb7d99217404c48e3f9 | 31,294 |
import os
def add_model_components(m, d, scenario_directory, subproblem, stage):
"""
The following Pyomo model components are defined in this module:
+-------------------------------------------------------------------------+
| Expressions |... | 99840966713dc49b9f1ff8906cd7ed23a10245a6 | 31,295 |
def apigw_required(view_func):
"""apigw装饰器
"""
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
request.jwt = JWTClient(request)
if not request.jwt.is_valid:
return jwt_invalid_view(request)
return view_func(request,... | c0bd9105df47297ae0f7db418ac3260c93272488 | 31,296 |
def text_analysis(string: str, *, nlp) -> str:
"""Return a text analysed string.
post-analysis sentences are separated by <sent> tags
e.g., 'a sentence<sent>a second sentence<sent>a third.
see https://spacy.io/usage/rule-based-matching#adding-patterns-attributes
"""
sents = []
doc = nlp(s... | 6bd16be281237bd2f2001755ce06d056a2cd8fda | 31,297 |
def wtr_tens(P, T):
"""Function to Calculate Gas-Water Interfacial Tension in dynes/cm"""
#P pressure, psia
#T temperature, °F
s74 = 75 - 1.108 * P ** 0.349
s280 = 53 - 0.1048 * P ** 0.637
if (T <= 74):
sw = s74
elif(T >= 280):
sw = s280
else:
sw... | acbf649a8dfe1302350b35f141afc09198470d8d | 31,298 |
from typing import List
def _decompose_move(event: MoveElements) -> List[MoveElements]:
"""
Decompose an event moving elements into a list of MoveElements events representing the
same action.
:param event: event to decompose
:return: list of events representing the same action
"""
return ... | c3572a2b183219280b4f352a8ddc98cbdfb7aa43 | 31,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.