content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def GetHomeFunctorViaPose():
""" Deprecated.
Returns a function that will move the robot to the home position when called.
"""
js_home = GetPlanToHomeService()
req = ServoToPoseRequest()
pose_home = GetHomePoseKDL()
req.target = pm.toMsg(pose_home)
open_gripper = GetOpenGripperService()... | 5,352,600 |
def getAveragePlatPrice(item_name):
"""
Get the current average price of the item on the Warframe marketplace.
Args:
item_name (str): The name of the item.
Returns:
float: the average platinum market price of the item.
"""
avg_price = -1
item_name = clean(item_name)
it... | 5,352,601 |
def mode_strength(n, kr, sphere_type='rigid'):
"""Mode strength b_n(kr) for an incident plane wave on sphere.
Parameters
----------
n : int
Degree.
kr : array_like
kr vector, product of wavenumber k and radius r_0.
sphere_type : 'rigid' or 'open'
Returns
-------
b_n... | 5,352,602 |
def data_dir(test_dir: Path) -> Path:
"""
Create a directory for storing the mock data set.
"""
_data_dir = test_dir / 'data'
_data_dir.mkdir(exist_ok=True)
return _data_dir | 5,352,603 |
def get_runtime_brief():
""" A digest version of get_runtime to be used more frequently """
return {"cpu_count": multiprocessing.cpu_count()} | 5,352,604 |
def test_get_tasks_n():
"""Test get a list of tasks percluster and instance."""
cluster_name = "test-cluster"
cluster = initialize_ecs_cluster(cluster_name)
num_services = 5
num_instances = 10
num_tasks = 3
infraestructure = initialize_ecs_infrastructure(
cluster,
num_service... | 5,352,605 |
def dict_compare(d1, d2):
"""
compares all differences between 2x dicts.
returns sub-dicts: "added", "removed", "modified", "same"
"""
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
added = d1_keys - d2_keys
removed = d2_keys - d1_ke... | 5,352,606 |
def toLocalTime(seconds, microseconds=0):
"""toLocalTime(seconds, microseconds=0) -> datetime
Converts the given number of seconds since the GPS Epoch (midnight
on January 6th, 1980) to this computer's local time. Returns a
Python datetime object.
Examples:
>>> toLocalTime(0)
datetime.da... | 5,352,607 |
def get_part_01_answer():
"""
Static method that will return the answer to Day01.01
:return: The product result
:rtype: float
"""
return prod(summation_equals(puzzle_inputs, 2020, 2)) | 5,352,608 |
def eig_of_series(matrices):
"""Returns the eigenvalues and eigenvectors for a series of matrices.
Parameters
----------
matrices : array_like, shape(n,m,m)
A series of square matrices.
Returns
-------
eigenvalues : ndarray, shape(n,m)
The eigenvalues of the matrices.
e... | 5,352,609 |
def config():
"""List and modify configuration parameters"""
pass | 5,352,610 |
def injectable(
cls: T = None,
*,
qualifier: str = None,
primary: bool = False,
namespace: str = None,
group: str = None,
singleton: bool = False,
) -> T:
"""
Class decorator to mark it as an injectable dependency.
This decorator accepts customization parameters but can be invok... | 5,352,611 |
def build_graph(defined_routes):
"""
build the graph form route definitions
"""
G = {}
for row in defined_routes:
t_fk_oid = int(row["t_fk_oid"])
t_pk_oid = int(row["t_pk_oid"])
if not t_fk_oid in G:
G[t_fk_oid] = {}
if not t_pk_oid in G:
G[t_p... | 5,352,612 |
def grando_transform_gauss_batch(batch_of_images, mean, variance):
"""Input: batch of images; type: ndarray: size: (batch, 784)
Output: batch of images with gaussian nois; we use clip function
to be assured that numbers in matrixs belong to interval (0,1);
type: ndarray; size: (batch, 784);
"""
... | 5,352,613 |
def get_poetry_project_version() -> VersionInfo:
"""Run poetry version and get the project version"""
command = ["poetry", "version"]
poetry_version_output = subprocess.check_output(command, text=True)
return version_string_to_version_info(poetry_version_output.split(" ")[1]) | 5,352,614 |
def LF_DG_DISTANCE_SHORT(c):
"""
This LF is designed to make sure that the disease mention
and the gene mention aren't right next to each other.
"""
return -1 if len(list(get_between_tokens(c))) <= 2 else 0 | 5,352,615 |
def populate_user_flags(conf, args):
"""Populate a dictionary of configuration flag parameters, "conf", from
values supplied on the command line in the structure, "args"."""
if args.cflags:
conf['cflags'] = args.cflags.split(sep=' ')
if args.ldflags:
conf['ldflags'] = args.ldflags.sp... | 5,352,616 |
def set_up():
"""
"""
reset_config()
config['env']['exchanges'][exchanges.SANDBOX]['fee'] = 0
config['env']['exchanges'][exchanges.SANDBOX]['starting_balance'] = 1000
config['app']['trading_mode'] = 'backtest'
config['app']['considering_exchanges'] = ['Sandbox']
router.set_routes([(exch... | 5,352,617 |
def test_base_dense_head_get_bboxes__ncnn():
"""Test get_bboxes rewrite of base dense head."""
backend_type = Backend.NCNN
check_backend(backend_type)
anchor_head = get_anchor_head_model()
anchor_head.cpu().eval()
s = 128
img_metas = [{
'scale_factor': np.ones(4),
'pad_shape'... | 5,352,618 |
def combine_raytrace(input_list):
"""
Produce a combined output from a list of raytrace outputs.
"""
profiler.start('combine_raytrace')
output = dict()
output['config'] = input_list[0]['config']
output['total'] = dict()
output['total']['meta'] = dict()
output['total']['image'] = dic... | 5,352,619 |
def blank_line_split(seq):
"""
Group subseqences of the given string sequence, split by blank lines.
"""
group = []
for line in seq:
if len(line) == 0:
# Ignore consecutive blank lines (empty group)
if len(group):
yield group
group = []... | 5,352,620 |
def is_dict():
"""Expects any dictionary"""
return TypeMatcher(dict) | 5,352,621 |
def init_dmriprep_wf():
"""
Build *dMRIPrep*'s pipeline.
This workflow organizes the execution of *dMRIPrep*, with a sub-workflow for
each subject. If FreeSurfer's recon-all is to be run, a FreeSurfer derivatives folder is
created and populated with any needed template subjects.
Workflow Graph... | 5,352,622 |
def test_external_query_pure(bq, gcs_data, gcs_external_config, dest_dataset,
dest_table, mock_env):
"""tests the basic external query ingrestion mechanics
with bq_transform.sql and external.json
"""
if not gcs_data.exists():
raise google.cloud.exceptions.NotFound("t... | 5,352,623 |
def get_list_from_comma_separated_string(comma_separated_list):
"""
get a python list of resource names from comma separated list
:param str comma_separated_list:
:return:
"""
import re
# remove all extra whitespace after commas and before/after string but NOT in between resource names
r... | 5,352,624 |
def _set_eeg_montage(cfg, raw, subject, session, run) -> None:
"""Set an EEG template montage if requested.
Modifies ``raw`` in-place.
"""
montage = cfg.eeg_template_montage
is_mne_montage = isinstance(montage,
mne.channels.montage.DigMontage)
montage_name = 'cus... | 5,352,625 |
def cci(series, window=14):
"""
compute commodity channel index
"""
price = typical_price(series)
typical_mean = rolling_mean(price, window)
res = (price - typical_mean) / (.015 * np.std(typical_mean))
return pd.Series(index=series.index, data=res) | 5,352,626 |
def load_definition_from_string(qualified_module, cache=True):
"""Load a definition based on a fully qualified string.
Returns:
None or the loaded object
Example:
.. code-block:: python
definition = load_definition_from_string('watson.http.messages.Request')
request = definit... | 5,352,627 |
def get_session(auth_mechanism, username, password, host):
"""Takes a username, password and authentication mechanism, logs into ICAT
and returns a session ID"""
# The ICAT Rest API does not accept json in the body of the HTTP request.
# Instead it takes the form parameter 'json' with a string value - ... | 5,352,628 |
def _create_all_aux_operators(num_modals: List[int]) -> List[VibrationalOp]:
"""Generates the common auxiliary operators out of the given WatsonHamiltonian.
Args:
num_modals: the number of modals per mode.
Returns:
A list of VibrationalOps. For each mode the number of occupied modals will ... | 5,352,629 |
def security(session: Session) -> None:
"""Check security safety."""
args = session.posargs or []
session.install("safety")
session.run("safety", "check", "-r", "workflow/envs/security.txt", *args) | 5,352,630 |
def add_conv(X: tf.Tensor, filters: List[int], kernel_sizes: List[int],
output_n_filters: int) -> tf.Tensor:
"""
Builds a single convolutional layer.
:param X: input layer.
:param filters: number of output filters in the convolution.
:param kernel_sizes: list of lengths of the 1D convo... | 5,352,631 |
def show_toast(view, message, timeout=DEFAULT_TIMEOUT, style=DEFAULT_STYLE):
# type: (sublime.View, str, int, Dict[str, str]) -> Callable[[], None]
"""Show a toast popup at the bottom of the view.
A timeout of -1 makes a "sticky" toast.
"""
messages_by_line = escape_text(message).splitlines()
c... | 5,352,632 |
def flip_metropolised_gibbs_numba_classic(p, z):
"""
Given the *probability* of z=1
flip z according to metropolised Gibbs
"""
if z == 1:
if p <= .5:
return -z
# alpha = 1 # TODO, can return -x here
else:
alpha = (1 - p) / p
else:
if p ... | 5,352,633 |
def get_default_interpreter():
"""Returns an instance of the default interpreter class."""
return __default_interpreter.get() | 5,352,634 |
def fx_ugoira_frames():
"""frames data."""
return {
'000000.jpg': 1000,
'000001.jpg': 2000,
'000002.jpg': 3000,
} | 5,352,635 |
def handle_tododone(bot, ievent):
""" t-done <listofnrs> .. remove todo items """
if len(ievent.args) == 0: ievent.missing('<list of nrs>') ; return
try:
nrs = []
for i in ievent.args: nrs.append(int(i))
except ValueError: ievent.reply('%s is not an integer' % i) ; return
name = getu... | 5,352,636 |
def coherent_tmm(pol, n_list, d_list, th_0, lam_vac):
"""
This is my slightly modified version of byrnes's "coh_tmm"
I've rearranged the calculations in a way that is more intuitive to me
Example inputs:
For angle dependence, be careful to include air first, otherwise the angle will be wrong
... | 5,352,637 |
def direct_pm25(ds):
"""
Add to dataset the calculated pm2.5 direclty fromWRFchem outputs variables.
Calculation for sum follows the calculation in WRF-Chem
module_mosaic_sumpm.F subroutine sum_pm_mosaic_vbs4.
:param ds: WRF-chem output.
:type ds: xarray DataSet.
:return: Dataset with a... | 5,352,638 |
def base_info():
"""
基本资料的展示和修改
1、尝试获取用户信息
2、如果是get请求,返回用户信息给模板
如果是post请求:
1、获取参数,nick_name,signature,gender[MAN,WOMAN]
2、检查参数的完整性
3、检查gender性别必须在范围内
4、保存用户信息
5、提交数据
6、修改redis缓存中的nick_name
注册:session['nick_name'] = mobile
登录:session['nick_name'] = user.nick_name
修... | 5,352,639 |
def build_mode(arg_namespace):
"""Check command line arguments and run build function."""
custom_temps = arg_namespace.template or []
temp_paths = [rel_to_cwd("templates", temp) for temp in custom_temps]
try:
result = builder.build(
templates=temp_paths,
schemes=arg_name... | 5,352,640 |
def to_list(obj):
""" """
if isinstance(obj, np.ndarray):
return obj.tolist()
raise TypeError('Not serializable') | 5,352,641 |
def symbolic_expression(x):
"""
Create a symbolic expression or vector of symbolic expressions from x.
INPUT:
- ``x`` - an object
OUTPUT:
- a symbolic expression.
EXAMPLES::
sage: a = symbolic_expression(3/2); a
3/2
sage: type(a)
<type 'sage.symbolic.exp... | 5,352,642 |
def seq_hyphentation(words):
"""
Converts words in a list of strings into lists of syllables
:param words: a list of words (strings)
:return: a list of lists containing word syllables
"""
return [hyphenation(w) for w in words] | 5,352,643 |
def to_ufo_background_image(self, ufo_glyph, layer):
"""Copy the backgound image from the GSLayer to the UFO Glyph."""
image = layer.backgroundImage
if image is None:
return
ufo_image = ufo_glyph.image
ufo_image.fileName = image.path
ufo_image.transformation = image.transform
ufo_gly... | 5,352,644 |
def angle(A, B, dim=1):
"""
Computes the angle in radians between the inputs along the specified dimension
Parameters
----------
A : Tensor
first input tensor
B : Tensor
second input tensor
dim : int (optional)
dimension along the angle is computed (default is 1)
... | 5,352,645 |
def _run_lint_helper(
*, fail_on_missing_sub_src, exclude_lint, warn_lint, site_name=None):
"""Helper for executing lint on specific site or all sites in repo."""
if site_name:
func = functools.partial(engine.lint.site, site_name=site_name)
else:
func = engine.lint.full
warns = f... | 5,352,646 |
def simulate_from_orders_nb(target_shape: tp.Shape,
group_lens: tp.Array1d,
init_cash: tp.Array1d,
call_seq: tp.Array2d,
size: tp.ArrayLike = np.asarray(np.inf),
price: tp.ArrayLik... | 5,352,647 |
def get_data_value(k: int, data: bytes) -> bytes:
"""Extracts the kth value from data.
data should be in the format value0:value1:value2:...:valueN. This last representation
is merely for understanding the logic. In practice, data will be a sequence of bytes,
with each value preceded by the length of s... | 5,352,648 |
def exp_map_individual(network, variable, max_degree):
"""Summary measure calculate for the non-parametric mapping approach described in Sofrygin & van der Laan (2017).
This approach works best for networks with uniform degree distributions. This summary measure generates a number
of columns (a total of ``m... | 5,352,649 |
def test_dpp_tcp_pkex_auto_connect_2_status_fail(dev, apdev, params):
"""DPP/PKEXv2 over TCP and automatic connection status for failure"""
run_dpp_tcp_pkex_auto_connect_2(dev, apdev, params, True, start_ap=False) | 5,352,650 |
def bridge_meshes(Xs, Ys, Zs, Cs):
"""
Concatenate multiple meshes, with hidden transparent bridges, to a single mesh, so that plt.plot_surface
uses correct drawing order between meshes (as it really should)
:param list Xs: list of x-coordinates for each mesh
:param list Ys: list of y-coordinates fo... | 5,352,651 |
def get_groups():
"""
Get the list of label groups.
@return: the list of label groups.
"""
labels_dict = load_yaml_from_file("labels")
groups = []
for group_info in labels_dict["groups"]:
group = Group(**group_info)
label_names = group_info.pop("labels", [])
groups.a... | 5,352,652 |
def create_workspace(db_workspace):
"""
:param workspace:
:return:
"""
sql_create_workspace = ''' INSERT OR IGNORE INTO workspace(name,output_dir)
VALUES(?,?) '''
CUR.execute(sql_create_workspace,db_workspace)
CONNECTION.commit() | 5,352,653 |
def print_table(table, headers='keys', highlight_strs=None, **echo_args):
"""
Print a tabular collection.
Outputs to the system pager, with colored unicode formatting
Args:
table: A nested dict or list of dicts, with keys representing columns
headers (str): Header type to be used with :... | 5,352,654 |
def diffractometer_rotation(phi=0, chi=0, eta=0, mu=0):
"""
Generate the 6-axis diffracometer rotation matrix
R = M * E * X * P
Also called Z in H. You, J. Appl. Cryst 32 (1999), 614-623
:param phi: float angle in degrees
:param chi: float angle in degrees
:param eta: float angle in degree... | 5,352,655 |
def supports_build_in_container(config):
"""
Given a workflow config, this method provides a boolean on whether the workflow can run within a container or not.
Parameters
----------
config namedtuple(Capability)
Config specifying the particular build workflow
Returns
-------
tu... | 5,352,656 |
def get_img_array_mhd(img_file):
"""Image array in zyx convention with dtype = int16."""
itk_img = sitk.ReadImage(img_file)
img_array_zyx = sitk.GetArrayFromImage(itk_img) # indices are z, y, x
origin = itk_img.GetOrigin() # x, y, z world coordinates (mm)
origin_zyx = [origin[2], origin[1], origin... | 5,352,657 |
def registration(request):
"""Render the registration page."""
if request.user.is_authenticated:
return redirect(reverse('index'))
if request.method == 'POST':
registration_form = UserRegistrationForm(request.POST)
if registration_form.is_valid():
r... | 5,352,658 |
def _get_arc2height(arcs):
"""
Parameters
----------
arcs: list[(int, int)]
Returns
-------
dict[(int, int), int]
"""
# arc2height = {(b,e): np.abs(b - e) for b, e in arcs}
n_arcs = len(arcs)
arcs_sorted = sorted(arcs, key=lambda x: np.abs(x[0] - x[1]))
arc2height = {ar... | 5,352,659 |
def init_ycm(path):
"""
Generate a ycm_extra_conf.py file in the given path dir to specify
compilation flags for a project. This is necessary to get
semantic analysis for c-family languages.
Check ycmd docs for more details.
"""
conf = join(path, '.ycm_extra_conf.py')
if exists(conf):... | 5,352,660 |
def get_aggregate_stats_flows_single_appliance(
self,
ne_pk: str,
start_time: int,
end_time: int,
granularity: str,
traffic_class: int = None,
flow: str = None,
ip: str = None,
data_format: str = None
) -> dict:
"""Get aggregate flow stats data for a single appliance filter by
... | 5,352,661 |
def save_confusion_matrix_from_tensor(confusion_matrix, labels,
current_epoch, save_dir):
"""Receive a confusion matrix from tensor, generate a image
with seaborn and save as .png in mlflow experiment
Args:
confusion_matrix (torch.Tensor): Tensor of confusion ... | 5,352,662 |
def load_user(userid):
"""Callback to load user from db, called by Flask-Login"""
db = get_db()
user = db.execute("SELECT id FROM users WHERE id = ?", [userid]).fetchone()
if user is not None:
return User(user[0])
return None | 5,352,663 |
def run_global_bears(message_queue,
timeout,
global_bear_queue,
global_bear_list,
global_result_dict,
control_queue):
"""
Run all global bears.
:param message_queue: A queue that contains messages ... | 5,352,664 |
def get_partial_outputs_with_prophecies(prophecies, loader, model, my_device,
corpus, seq2seq):
"""
Parameters
----------
prophecies : dict
Dictionary mapping from sequence index to a list of prophecies, one
for each prefix in the sequence.
... | 5,352,665 |
def _generate_deserialize_impl(
symbol_table: intermediate.SymbolTable,
spec_impls: specific_implementations.SpecificImplementations,
) -> Tuple[Optional[Stripped], Optional[List[Error]]]:
"""Generate the implementation for deserialization functions."""
blocks = [
_generate_skip_whitespace_and_c... | 5,352,666 |
def verif_snap_availability(dc, host):
"""Verify the ZFS snapshot name already exists.
accepts: data center, host
returns: ZFS snapshot / clone name exists.
"""
logger.info('Validating configuration request.')
zfssrcfslist.append("ifxdb-do_" + "v-" + str(db_version))
zfssrcfslist.append("app... | 5,352,667 |
def timestep_to_transition_idx(snapshot_years, transitions, timestep):
"""Convert timestep to transition index.
Args:
snapshot_years (list): a list of years corresponding to the provided
rasters
transitions (int): the number of transitions in the scenario
timestep (int): the... | 5,352,668 |
def _make_abs_path(path, cwd=None, default=None):
"""convert 'path' to absolute if necessary (could be already absolute)
if not defined (empty, or None), will return 'default' one or 'cwd'
"""
cwd = cwd or get_cwd()
if not path:
abs_path = default or cwd
elif os.path.isabs(path):
... | 5,352,669 |
def resolve_checks(names, all_checks):
"""Returns a set of resolved check names.
Resolving a check name expands tag references (e.g., "@tag") to all the
checks that contain the given tag. OpenShiftCheckException is raised if
names contains an unknown check or tag name.
names should be a sequence o... | 5,352,670 |
def swish(
data: NodeInput,
beta: Optional[NodeInput] = None,
name: Optional[str] = None,
) -> Node:
"""Return a node which performing Swish activation function Swish(x, beta=1.0) = x * sigmoid(x * beta)).
:param data: Tensor with input data floating point type.
:return: The new node which perf... | 5,352,671 |
def cut_out_interval(data, interval, with_gaps=False):
"""
Cuts out data from input array.
Interval is the start-stop time pair.
If with_gaps flag is True, then one NaN value will be added
between the remaining two pieces of data.
Returns modified data array.
:param data: 2-dimensional arr... | 5,352,672 |
def _abbreviations_to_word(text: str):
"""
对句子中的压缩次进行扩展成单词
:param text: 单个句子文本
:return: 转换后的句子文本
"""
abbreviations = [
(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
('mrs', 'misess'),
('mr', 'mister'),
('dr', 'doctor'),
('... | 5,352,673 |
def _prev(message=None):
"""
Handler for mycroft.audio.service.prev. Starts playing the previous
track.
Args:
message: message bus message, not used but required
"""
global current
if current:
current.prev() | 5,352,674 |
def resnet56(num_classes=100):
"""Constructs a ResNet-56 model for CIFAR-10 (by default)
Args:
num_classes (uint): number of classes
"""
model = CifarResNet(ResNetBasicblock, 56, num_classes)
return model | 5,352,675 |
def _fetch_latest_from_memcache(app_version):
"""Get the latest configuration data for this app-version from memcache.
Args:
app_version: the major version you want configuration data for.
Returns:
A Config class instance for most recently set options or None if none
could be found in memcache.
""... | 5,352,676 |
def check_settings(generate_module, build_to_run):
"""
Check the validity of locally configured settings.
"""
add_check_settings_steps(generate_module, build_to_run)
build_to_run.run() | 5,352,677 |
async def async_setup_entry(
hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities
):
"""Set up CAME light devices dynamically through discovery."""
async def async_discover_sensor(dev_ids):
"""Discover and add a discovered CAME light devices."""
if not dev_ids:
ret... | 5,352,678 |
def validate_train_id(relative_path):
"""
Check if train_id is valid.
Args:
relative_path (str): Train ID of a summary directory, e.g. './log1'.
Returns:
bool, if train id is valid, return True.
"""
if not relative_path.startswith('./'):
log.warning("The relative_path ... | 5,352,679 |
def test_atx_headings_extra_4():
"""
Test case extra 4: ATX headings string starting with a code span.
"""
# Arrange
source_markdown = """## ``this`` is a fun day"""
expected_tokens = [
"[atx(1,1):2:0:]",
"[text(1,4)::\a \a\x03\a]",
"[icode-span(1,4):this:``::]",
... | 5,352,680 |
def pad_set_room(request):
"""
pad修改关联会议室
:param request:
:return:
"""
dbs = request.dbsession
user_id = request.POST.get('user_id', '')
room_id = request.POST.get('room_id', '')
pad_code = request.POST.get('pad_code', '')
if not user_id:
error_msg = '用户ID不能为空!'
elif ... | 5,352,681 |
def airffromrh_wmo(rh_wmo,temp,pres,asat=None,dhsat=None,chkvals=False,
chktol=_CHKTOL,asat0=None,dhsat0=None,chkbnd=False,mathargs=None):
"""Calculate dry fraction from WMO RH.
Calculate the dry air mass fraction from the relative humidity. The
relative humidity used here is defined by the WMO as:... | 5,352,682 |
def sqs_queue_encryption_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:
"""[SQS.2] SQS queues should use Server Side encryption"""
response = list_queues(cache)
iso8601Time = datetime.datetime.now(datetime.timezone.utc).isoformat()
if 'QueueUrls' in response:
f... | 5,352,683 |
def test_model_not_recommend_the_last_eaten_menu(model, ten_people_data):
"""
Test model not recommend the last eaten menu
"""
model.add_data(ten_people_data)
print(model.preferences('Jason'))
assert model.recommend('Jason') != 'pasta' | 5,352,684 |
def player_vs_bot():
"""
For playing against a bot.
it's created to keep the main class clean.
"""
die_player1 = dice.Dice()
die_computer = dice.Dice()
game = bot_levels.BotDifficulty()
while True:
try:
choose_difficulty = int(input("""select difficulty.
... | 5,352,685 |
def download_file(filename, url):
"""
Download an URL to a file
"""
print("downloading {0}".format(url))
with open(filename, "wb") as fout:
response = requests.get(url, stream=True, verify=False)
response.raise_for_status()
# Write response data to file
iblock = 0
... | 5,352,686 |
def resolve_If(node: ast.If, tree: ast.Module, context: Context) -> WorkflowStep:
"""
Make the resolved condition string and body into a workflow step.
TODO: support assignments, not just calls
TODO: support multi-statement bodies
"""
if len(node.body) > 1:
raise NotImplementedError("Ca... | 5,352,687 |
def inflate(data: str) -> str:
"""
reverses the compression used by draw.io
see: https://drawio-app.com/extracting-the-xml-from-mxfiles/
see: https://stackoverflow.com/questions/1089662/python-inflate-and-deflate-implementations
:param data: base64 encoded string
:return: "plain text" version ... | 5,352,688 |
def error_mixin():
"""
@apiDefine ErrorMixin
@apiError content 错误信息
@apiError message 错误消息
@apiErrorExample 400 Bad Request
参数错误
{
content="missed keys set(['city'])",
message="ArgsParseFailed"
}
查询获取单个数... | 5,352,689 |
def get_tree(data_path,sep,root,cutoff,layer_max,up=True):
"""
This function takes the path of a data file of edge list with numeric
weights and returns a tree (DiGraph object). The parameters include:
data_path: The path of a data file of edge list with numeric weights.
sep: The delimiter of the d... | 5,352,690 |
def delete_functions(lambda_client, function_list) -> list:
"""Deletes all instances in the instances parameter.
Args:
lambda_client: A lambda boto3 client
function_list: A list of instances you want deleted.
Returns:
A count of deleted instances
"""
terminated_functions = ... | 5,352,691 |
def run():
"""
Run the main loop.
After the window has been set up, and the event hooks are in place, this is usually one of the last
commands on the main program.
"""
pyglet.app.run() | 5,352,692 |
def make_random_shares(seed, minimum, n_shares, share_strength=256):
"""
Generates a random shamir pool for a given seed phrase.
Returns share points as seeds phrases (word list).
"""
if minimum > n_shares:
raise ValueError(
"More shares needed (%d) to recover the seed phrase tha... | 5,352,693 |
def confusion_matrix(
probs: Optional[Sequence[Sequence]] = None,
y_true: Optional[Sequence] = None,
preds: Optional[Sequence] = None,
class_names: Optional[Sequence[str]] = None,
title: Optional[str] = None,
):
"""
Computes a multi-run confusion matrix.
Arguments:
probs (2-d ar... | 5,352,694 |
def get_monitor_details():
"""Render the index page."""
monitor_id = paranoid_clean(request.args.get('id'))
monitors = mongo.db[app.config['MONITORS_COLLECTION']]
monitor = monitors.find_one({'hashed': monitor_id}, {'_id': 0})
if not monitor:
return jsonify({'success': False, 'error': 'Monit... | 5,352,695 |
def _simplify(obj: object) -> object:
"""
This function takes an object as input and returns a simple
Python object which is supported by the chosen serialization
method (such as JSON or msgpack). The reason we have this function
is that some objects are either NOT supported by high level (fast)
... | 5,352,696 |
def test_property_bindings(rdfs_graph: Graph) -> None:
"""
The ``bindings`` property of a `rdflib.query.Result` result works as expected.
"""
result = rdfs_graph.query(
"""
SELECT ?class ?label WHERE {
?class rdf:type rdfs:Class.
?class rdfs:label ?lab... | 5,352,697 |
def match_v2v3(aperture_1, aperture_2, verbose=False):
"""Use the V2V3 from aperture_1 in aperture_2 modifying X[Y]DetRef,X[Y]SciRef to match.
Also shift the polynomial coefficients to reflect the new reference point origin
and for NIRCam recalculate angles.
Parameters
----------
aperture_1 : ... | 5,352,698 |
def PlatformPager() -> PagerCommand:
"""
Return the default pager command for the current platform.
"""
if sys.platform.startswith('aix'):
return More()
if sys.platform.startswith('win32'):
return More()
return Less() | 5,352,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.