content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def listify(x):
"""If x is already a list, do nothing. Otherwise, wrap x in a list."""
if isinstance(x, list):
return x
else:
return [x] | 751d518c64f19f9a6640717ddd8cd0949edf4d37 | 677,889 |
def remove_empty_values(metric_epoch, num_tasks, num_epochs):
"""
Remove empty values from 'metric_epoch', where there are zeros at some epochs (because of early stopping).
:param metric_epoch: array of size (num_runs, num_tasks * num_epochs) with 0 values where early stopping occured
:param num_tasks:... | 06ab035b9328956e5bbcf6dbc5a1e6b599fe08cb | 677,890 |
def em_complete(job):
"""Verify that energy minimization has completed"""
return job.isfile('em.gro') | b96ef1eebac69b426ee44eae72847bb8dd661a2f | 677,891 |
import os
import glob
import re
import torch
def load_saved_model(saved_path, model):
"""
Load saved model if exiseted
:param saved_path: model saved path, str
:param model: model object
:return:
"""
if not os.path.exists(saved_path):
raise ValueError('{} not found'.format(saved_... | ead7f780b7c736921353308b4faf2bde3cb909c4 | 677,892 |
def world_to_index(x, y, origin, resolution, width):
""" Convert World coordinates to index """
x = (x - origin[0]) / resolution
y = (y - origin[1]) / resolution
return y * width + x | 23c8a769236afd1bc92f8bb00db44d97a5227a86 | 677,893 |
def size_in_stock(item,size_str):
"""
Example: has_size(item, '32x36')
"""
for unit in item['units']:
if unit['size'] == size_str and unit['stock'] > 0:
return True
return False | 82e2ba8f79ee7e926ca38c174753c0b715efa647 | 677,894 |
def wait_for_button_press(button):
"""
Wait for a button to be pressed and released.
Parameter:
- `button` (Button): an instance of the EV3 Button() class
return the Button name that was pressed.
"""
pressed = None
while True:
allpressed = button.buttons_pressed
if bool(a... | 2b119fb637580104fa79f43f8c72ec76182f31fa | 677,895 |
def determine_inception(model_type):
"""
Determines if the model type is Inception v3.
:param model_type: Model type.
:return: A boolean indicating if the model is Inception v3.
"""
return True if model_type == 'inception_v3' else False | 124d6c6121b0ab3835196a2077ab1b14111e8057 | 677,896 |
def Transform(obj, x=0., y=0., z=0.):
"""
Transformation between raster and model space using a model transformation
matrix applied to raster coordinates plus altitude.
```python
>>> mps = ifd.GeoKeyModel["ModelPixelScaleTag"]
>>> mtt = ifd.GeoKeyModel["ModelTiepointTag"]
>>> Sx, Sy, Sz = m... | 139d2964152ae32c2c0ffa3f45b62e1cb7536b4f | 677,897 |
import re
def compile_flags():
"""(?F): Activate compile flags. F in 'aiLmsux'."""
# Flags
# a --> re.A, re.ASCII: matches ASCII only
# i --> re.I, re.IGNORECASE: ignore character case
# L --> re.L, re.LOCALE: locale dependent
# m --> re.M, re.MULTILINE: multi-line matching
# s --> re.S, ... | 35e78ee80ba12ef8b63b6475a2b8753e9356b331 | 677,898 |
def _write_logic(tx, operation, networks, edges):
"""
Accesses database to return edge list of intersection of networks.
:param tx: Neo4j transaction
:param operation: Type of logic operation
:param networks: List of network names
:param edges: List of edges returned by logic operation
:retu... | ee5d37691130512425a13fb1a1eb1b2d9f2fe4b6 | 677,899 |
def is_valid_field_content(s: str) -> bool:
"""
Returns True if string s can be stored in a SubStation field.
Fields are written in CSV-like manner, thus commas and/or newlines
are not acceptable in the string.
"""
return "\n" not in s and "," not in s | 6de29796766d672cdb27044135378167564f1c76 | 677,900 |
def patchData(data1, data2, xmin=55, xmax=74, ymin=53, ymax=72):
"""
Copies data from data2 to data1 within the defined patch region
(often used for processing DIV files)
**Inputs**
data1 (sans2d): measurement to be patched
data2 (sans2d): measurement to get the patch from
xmin (int): le... | de43540f0d61498ca086315d389ef5c1e2a41493 | 677,902 |
from typing import Counter
def aggregate_event_cat(event_list):
"""
Return a dictionary-like list of eventCategory frequency counts.
:param event_list: list of event tuples (eventCategory,eventAction)
:return: dict-like list of frequencies [(eventCat1, freq_1),(eventCat2, freq_2),...]
"""
retu... | 666eb7732fdfbef236b934b549ef827edad8ea6c | 677,903 |
def reclassify_experience(experience, get_block, num_blocks):
"""
Classify experience into state-action blocks.
:param experience: List of experienced transitions.
:param get_block: Get state-action block function.
:param num_blocks: Number of state-action blocks.
:return:
""... | 9fbe9db050308231bf6bdbb060fd76e3ffb8950e | 677,904 |
import builtins
def is_a_builtin(word) -> bool:
"""
Returns True if a word is a builtin python object
Args:
word: word to check
Returns: True if word is builtin python object
"""
return str(word) in dir(builtins) | 5dd2eed08273d8fc5a4bba1e67cc681f3a2488ca | 677,906 |
def build_loss_function_from_dict(loss_function_ref):
"""
Builds loss function
"""
# Getting the details of the loss_function using get_loss_function method
loss_function_details = loss_function_ref.get_loss_function()
# Storing the loss_function details
loss_function_func = loss_functi... | 44988ab80942864f157106b3d77192cd45083198 | 677,907 |
def invalidate_cols(platemap, cols, valid=False):
"""Returns updated plate map with specified columns invalidated.
:param platemap: Plate map to use
:type platemap: pandas dataframe
:param wells: Columns to invalidate, e.g. [1, 2, 3]
:type wells: int or list of ints
:param valid: Sets the s... | 114a15fd452a49f2c5e3a23421a6181ce2d142d6 | 677,908 |
import getpass
def get_current_user() -> str:
"""Return the name of the current user"""
return getpass.getuser() | cc21a6aafd5cbbd8a02b0b6e62f8318311a6ed59 | 677,910 |
import copy
def substitute_variable_name(v_dict, old_name, new_name):
"""Exchanges values in a dictionary.
Parameters
----------
v_dict : Dictionary
old_name : string, Value to change
new_name : string, new value
Returns
-------
v_dict : Dictionary with changed names
"""
... | be0056e0de3c7ccc0f2d2f7669d394ad4245ae2d | 677,912 |
def concat_lyrics(lyrics, threshold):
"""
# Accepts two arguments, a list of lists of strings
# and an integer. Joins the lists if the word count would
# remain below the given threshold and returns the joined
# lists.
>>> print(concat_lyrics([["We’re", "so", "young,", "boy"],\
["We", "ain’... | 51bca5f18b48489cd75c2878f2062a39c037399b | 677,914 |
import re
def filterSection(section, filter):
"""filters section according to regexp terms in filter and outputs a list
of all matched entries """
ret = []
for sec in section:
secret = []
for line in sec:
line = line.lstrip()
if re.match(filter, line, re.I):
... | 291b182767d8b61593b44b67a07e216a6cd7401e | 677,915 |
def increase_threshold(thresh, thresh_inc):
"""
Increase the threshold based on a string
Inputs: - thresh Initial threshold
- thresh_inc How the threshold should be increased.
"xN": multiply by N
"+N": increase by N
... | c5d7281acb85e27a6ada104b336bb6a05ed1b24c | 677,916 |
import pandas
def read_in_data(address_path):
"""
Reads in the address data, separates the address information from the patient data, and
uniquifies the addresses while creating a column of list of original indexes that will later be used to map address
data and patient data.
:param address_path:... | 439571240662f47bdc9b54816a7d69103279d42b | 677,917 |
import math
def hd(inc, sd):
"""
Calculate horizontal distance.
:param inc: (float) inclination angle in degrees
:param sd: (float) slope distance in any units
"""
return sd * math.cos(math.radians(inc)) | 76de48925810c399632d80fa799d4bbf94ff0069 | 677,918 |
def get_symbol_name(*args):
"""Return fully-qualified symbol name given path args.
Example usage:
>>> get_symbol_name('ZenPacks.example.Name')
'ZenPacks.example.Name'
>>> get_symbol_name('ZenPacks.example.Name', 'schema')
'ZenPacks.example.Name.schema'
>>> get_symbol_... | b0c97157f8121e5bb6f32f8bb9253b5a723cfde8 | 677,919 |
import random
def getId() -> str:
"""
Generate an 8 base29-encoded character string
11 base58 characters are enough for youtube so 8 base29 characters should
be good enough for me
I landed on 29 characters that are difficult to build words out of as a
natural filter (hopefully) against inapp... | 37ea456ef80a32f8e16974542d594a5c60b12cf5 | 677,920 |
from typing import Set
import re
def solidity_unresolved_symbols(hex_code: str) -> Set[str]:
""" Return the unresolved symbols contained in the `hex_code`.
Note:
The binary representation should not be provided since this function
relies on the fact that the '_' is invalid in hex encoding.
... | 496f120c0dc6c49b45eedd4a6004e773d5a3e88e | 677,921 |
def socket_get_status():
""" Alias of stream_get_meta_data"""
return NotImplementedError() | 7d682d3e27bbbeaf0dc0ad4ca2015d8541c09533 | 677,922 |
def get_ssh_command(public_ip, user=None, proxyjump=None, flag=None):
""" Return SSH command """
command = ['ssh']
if proxyjump:
command.extend(['-J %s' % (proxyjump.strip())])
if flag:
command.extend([flag.strip()])
if user:
command.extend(['%s@%s' % (user, public_ip)])... | fffce7122346880f632fa00865f3e1e0491f8cba | 677,923 |
import numpy as np
def sigmoid(z):
"""used to compute the sigmoid function"""
s = 1/(1+np.exp(-z))
### END CODE HERE ###
return s | cdf25e9b6a376425b51090049242992161f8a888 | 677,924 |
def remove_comment(content):
"""Remove comment from the content."""
lines = content.split('\n')
return '\n'.join([line for line in lines if not line.startswith('#')]).strip() | 6efb3ae4376eb16cc14c3c1a8f210420e807a250 | 677,925 |
def person(request):
"""
A dummy fixture, parametrized so that it has two instances
"""
if request.param == 0:
return "world"
elif request.param == 1:
return "self" | 5c34b2a87c2db01d93d4f2e32e07c80cb2a06459 | 677,926 |
import sys
import argparse
def parse_args(args=sys.argv[1:]):
"""Parse arguments."""
parser = argparse.ArgumentParser(
description="Monitor the uptime of the Internet connection and record any downtime",
prog='python -m monitor_internet_connection')
parser.add_argument("-n", "--no-logfil... | 04fe940918c23f6f696b26bf70d804f2d24dad76 | 677,927 |
def list_of_dicts_to_dict(l, major_key, other_keys):
"""
Args:
l (list) - list of dictionaries
major_key (tuple, str, float, int) - key to orient output dictionary on
other_keys (list) - list of keys (tuple, str, float, int) to include in output dictionary
Returns:
dicti... | 81679c7c99b6a535181fd2a1ce8092e7dd46132a | 677,928 |
import itertools
def aggregate_frame_ranges(frame_ids):
"""
Compresses a list of frames to ranges
:param frame_ids: assumes either a list of frame_ids or a list of lists [frame_id, duration]
:return: list of frame ranges
"""
frame_ids_updated = []
if isinstance(frame_ids[0], list) or isin... | 0f39dded65205d89fa3017ae5267fccac80ce96d | 677,929 |
import re
def clean_tag(tag, allow_none=False, mytype='string', default=None, max_len=254):
""" Clean the given `tag` instance depending of its `mytype`."""
if default is None and allow_none is False:
if mytype == 'string':
default = 'unknown'
elif mytype == 'integer':
... | 69416f4c1f4230434eac17e983fb460df371b125 | 677,930 |
import mpmath
def mpmath_normal_cdf2(x, y, r):
"""
This function produces correct results for inputs currently present in /test/Tests/Data/SpecialFunctionsValues.
Other inputs may fall into areas where currently present algorithms produce incorrect results and may require modifying this function.
"""
... | 9c692c8122f0330c090967b2cfa3ffd9a18428d1 | 677,931 |
def calculate_square(num):
"""
Returns the square of a given number
"""
return num * num | 5bac73090aaf92cd97659343a64513470f81e8c2 | 677,932 |
def fmt_color(text: str, color: str) -> str:
"""Format a string in a certain color (`<span>`).
Args:
text: The text to format.
color: Any valid CSS color.
Returns:
A `<span>` that contains the colored text.
"""
return u'<span style="color:{color}">{text}</span>'.format(
... | 2bb3a83fa278e5a48335e43d048fdda6029c9afb | 677,933 |
def RIGHT(text, n):
"""Slices string(s) a specified number of characters from right.
Parameters
----------
text : list or string
string(s) to be sliced from right.
n : integer
number of characters to slice from right. Must be greater than zero.
Returns
-------
list or s... | d5a31641754213a41da74114bd09010a9ea23e62 | 677,934 |
def UMinus(a):
""" Create an SMT unary negation.
Deprecated. Kept for compatiblity with Z3. See "Neg".
See also the __neg__ overload (unary - operator) for arithmetic SMT expressions.
>>> x = Int('x')
>>> UMinus(x)
-x
"""
return -a | 2b7c3131c38f0c365340aed30f6c68057c644d48 | 677,936 |
import os
def _path(unix_path):
"""Convert a unix-path into a platform-dependent path."""
return unix_path.replace("/", os.path.sep) | 73bdaae8573242d0b304048af9d4e6f4ca2e0f6d | 677,937 |
def alembic_config():
"""Override this fixture to configure the exact alembic context setup required."""
return {} | 0dffbd7b97c0c27201e374b71fb5bd89a5d124c1 | 677,938 |
def e_pest(model, n):
"""
It's a monkey patch
Without this simply expression there is a error in solver.solve
ValueError: Unsupported expression type
(<class 'pyomo.core.expr.numeric_expr.LinearExpression'>)
in _print_nonlinear_terms_NL
Parameters
----------
... | 1a60918e3b69d88c2bbe7558a68e9c585d372c58 | 677,939 |
def _stringify_int(integer):
"""Convert an integer into a string formatted with thousand separators.
Parameters
----------
integer : int
The integer.
Returns
-------
str
The integer turned into a string.
"""
return "{:,}".format(integer) | 8f797819ef166a3cb726565f9d329d154ebb44dc | 677,940 |
import json
def get_stored_username():
"""Get stored username if available."""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username | 49f18b3ca37437529a6ae93b4447123dca9efc03 | 677,941 |
def resolve_from_parameter(node):
""" Resolve 'from_parameter' dependencies.
Converts e.g. {'from_parameter': 'data'} to {'data': 'dc_0'}
"""
in_nodes = {}
# Resolve 'from_parameter' if field exists in node arguments
for argument in node.arguments:
# Check if current argument is iter... | 07389dc41921ed5533adc4d8a32bbdd14f11a61a | 677,942 |
import codecs
import logging
import re
def ReadUnknownEncodedFile(file_path, logging_text=None):
"""Read a file of unknown encoding (UTF-8 or latin) by trying in sequence.
Args:
file_path: what to read.
logging_text: what to display for logging depending on file read.
Returns:
File content, possib... | c33d93037e974dfcbe9203279cf556b5777a2a9c | 677,943 |
def calc_percent(per, cent):
"""Takes the parameters "per" and "cent"
and returns the calculated percent."""
return (per / cent) * 100 | aeb7cf4a5ba243847ccd638bd8c89dbfa3b5195f | 677,944 |
def plus5(num):
"""assumes num is a numeric
returns a numeric, num + 5"""
return num + 5 | f37cb25bd4a88787418a3fc4d271abf68823c491 | 677,945 |
import collections
def empty_defaultdict():
"""Returns a defaultdict with an empty defaultdict as default value."""
return collections.defaultdict(empty_defaultdict) | 12961b76b44c7969be7ba7fae023f9bdfa7e974e | 677,946 |
import posix
def OsType():
# type: () -> str
""" Compute $OSTYPE variable """
return posix.uname()[0].lower() | d22fd793f1659e79f0e70e353dbc87b9a22b82f7 | 677,947 |
from typing import Union
from typing import List
from typing import Tuple
def edge_has_empty_node(
edge: Union[List[str], Tuple[str, str]], node_ids_with_labels
) -> bool:
"""Check if edge contains an empty node."""
return not str(node_ids_with_labels[edge[0]]) or not str(
node_ids_with_labels[edg... | 18fd4784484403aaa7859f249b61776da95cb9a7 | 677,948 |
def reverse_dict(d):
"""
Flip keys and values
"""
r_d = {}
for k, v in d.items():
if v not in r_d:
r_d[v] = [k]
else:
r_d[v].append(k)
return r_d | debc1492f0c23b7ddd3009bfd06217a76e424b9f | 677,949 |
import collections
def removeDuplicatedLetters(s):
"""
To remove consecutive same letters
Arguments:
s : original string
Returns:
newStr : a string that does not contains consecutive same letters
"""
conseq_dupls = collections.Counter()
newStr = ""
... | 7fc5e8bf8311353902314f7ef2ebc012f091dda9 | 677,950 |
import os
def get_img_path_type(parent_folder):
"""
Args: Parent_folder: Root path
Returns: Two lists with paths and correspond types
"""
list_paths = []
list_types = []
for root, dirs, files in os.walk(parent_folder):
for each_file in files:
if '.jpg' in each_file:
... | af963862b5c979777c55b253225a6502e3dd794f | 677,951 |
import random
def genEtu(n):
"""
"""
res = []
c = list(range(0, 9))
for i in range(n):
res.append(random.sample(c, 9))
res[i].insert(0, i)
return res | 64a7763ce6f5acec9584d22e3a7ef1a1f6098376 | 677,952 |
import argparse
def parse_args():
""" Parse input arguments """
parser = argparse.ArgumentParser(description='Feature extraction for RCC algorithm')
parser.add_argument('--dataset', default=None, type=str,
help='The entered dataset file must be in the Data folder')
parser.add_... | e4925500f345e3347f24ddaa8cdf117cbc00d477 | 677,953 |
import os
def get_gdf_header(gdf_file, gdf2a_bin=os.path.expandvars('$GDF2A_BIN')):
"""Reads the header (column names) of gdf_file and returns them"""
assert os.path.exists(gdf2a_bin), f'The gdf2a binary "{gdf2a_bin}" does not exist.'
assert os.path.exists(gdf_file), f'The gdf file "{gdf_file}" does not... | a14de17260b5e1a007e84ec0d7e0bfd9434ffde7 | 677,954 |
import torch
def mpjpe_by_action_p1(predicted, target, action, action_error_sum):
"""
Mean per-joint position error (i.e. mean Euclidean distance),
often referred to as "Protocol #1" in many papers.
"""
assert predicted.shape == target.shape
num = predicted.size(0)
dist = torch.mean(torch.... | babc210bd41282ab6084c3460395060449b62e0f | 677,955 |
def time_analyze(time):
"""
Time documentation
7:00 - 7:05 = 0
7:05 - 7:10 = 1
7:10 - 7:15 = 2
7:15 - 7:20 = 3
7:20 - 7:25 = 4
.
.
.
23:55 - 00:00 = 203
"""
if time == "00:00":
return 204
hour = int(time[0:2])
hour = (hour - 7) * 12
minutes = int(time[-2:]) // 5
return hour + minutes | 26384429d415309ea59844c9d6005655a293c58b | 677,956 |
import os
def get_env(key: str) -> str:
"""Get the environment value for a given key
Args:
key (str): The name of the environment variable
Returns:
str: Its value
"""
return os.environ[key] | d1c01ed6265a04634ae1c49876269ee2b9e62149 | 677,957 |
def get_image_type(fileName):
"""
Get image type.
:param fileName:
:return:
"""
if fileName.endswith(".jpg"):
return "image/jpeg"
elif fileName.endswith(".png"):
return "image/png" | d2e82829fd365093cfcd0a1089ee0ecd65a8a0dd | 677,958 |
def cli(ctx, state="", history_id="", invocation_id="", tool_id="", workflow_id="", user_id="", date_range_min="", date_range_max="", limit=500, offset=0, user_details=False):
"""Get all jobs, or select a subset by specifying optional arguments for filtering (e.g. a state).
Output:
Summary information for eac... | cf6702581a7f4870c105aab763a8b5b5a89a1bc6 | 677,959 |
def build_table(x,
perceiver,
cache,
cache_emb,
topk,
return_images=False,
index_dir=None):
"""
Maps each image to a linearized row in a table. Each entry in a row
is delimited by "|". Each entry comes from the t... | 5822dbe6f54a0d582bc19785cf9b1d49a4ac5eda | 677,960 |
def Check_NOT(promotor, Output_P, Gates):
"""Check the whole list and returns the delay of the gate matching with inputs"""
for i in Gates:
if i[0] == promotor and i[1] == Output_P:
return i[2]
return 0 | f148e44be910c2afb9364ee4da50d21d12496703 | 677,961 |
from pathlib import Path
import os
def cachedir() -> Path:
"""Return the path of the cache directory."""
if os.environ.get("TEST_TMPDIR"):
return Path(os.environ["TEST_TMPDIR"])
else:
return Path("~/.cache/programl").expanduser() | c3bdc126d3d7a56c6c2fea0bf876e88f697f281f | 677,962 |
def get_or_create_vcf_output_dir(alignment_group):
"""Ensures root directory for vcf files exists and returns the full path.
Root directory looks like:
/projects/<project_uid>/alignment_groups/vcf/
And per-tool vcf files will go in directory:
/projects/<project_uid>/alignment_groups/vcf/<v... | 845959b358620be3ab8ab7426ea70d8d63570d23 | 677,963 |
def commonName(names):
"""return common name from list of names"""
name = names[0]
for n in names[1:]:
while not name in n:
name = name[:-1]
# strip common endings
for s in [' ','(','.','/','\\','_']:
name = name.strip(s)
return name | 9632fa99df415102784153e238ed92dd876a31b6 | 677,964 |
def match_pattern(resource: bytes, pattern: bytes, mask: bytes, ignored: bytes):
"""
Implementation of algorithm in:x
https://mimesniff.spec.whatwg.org/#matching-a-mime-type-pattern
True if pattern matches the resource. False otherwise.
"""
resource = bytearray(resource)
pattern = bytearray(... | 8e6652c2593317d6c75e2f30eaedb25377504962 | 677,966 |
import random
def randomSnack(rows,item):
"""
create random snack cubes:
we must be sure we dont put a snack on top of the snake
"""
#global rows
positions = item.body
while True:
x = random.randrange(rows)
y = random.randrange(rows)
#we get a list of filtered list and check if and of the positions
#a... | 26f4574c1a0b007c4343ce9fb24ca3eb8c17c247 | 677,967 |
import torch
def mse(target, predicted):
"""Mean Squared Error"""
return torch.mean((target - predicted)**2) | 27b60d509f4cddac3e06f8cb76ee3221f60e8d0b | 677,968 |
def min_scalar_type(a):
"""
min_scalar_type(a)
For scalar ``a``, returns the data type with the smallest size
and smallest scalar kind which can hold its value. For non-scalar
array ``a``, returns the vector's dtype unmodified.
Floating point values are not demoted to integers,
and comple... | d9a69b900c2b7ab8e600447fa42058bb17a574fc | 677,969 |
from typing import Any
def force_list(value: Any) -> list:
"""
Convert `value` to list or return `value` if it is already a list.
:param value: Value to convert to list.
"""
return list(value) if isinstance(value, (list, tuple)) else [value] | 2151eefef55a280c6c7cc0a5a7520a774750ecb2 | 677,970 |
def override_key(key) -> str:
"""Handles the fn key for macs"""
if str(key) == "<179>" or str(key) == "<63>":
return "Key.fn"
if str(key) == "'\\\\'":
return "'\\'"
return str(key) | 852ecc1281ecbfc8882835f99f7a92ef95be085c | 677,971 |
def readCoNLL(inputPath, cols, commentSymbol=None):
"""
Reads in a CoNLL file and returns a list with sentences (each sentence is a list of tokens)
"""
sentences = []
sentenceTemplate = {name: [] for name in cols.values()}
sentence = {name: [] for name in sentenceTemplate.keys()}
... | 8b9167a73450a06f29d272c0f817f450a315157e | 677,973 |
def get_frameshift_lengths(num_bins):
"""Simple function that returns the lengths for each frameshift category
if `num_bins` number of frameshift categories are requested.
"""
fs_len = []
i = 1
tmp_bins = 0
while(tmp_bins<num_bins):
if i%3:
fs_len.append(i)
tm... | dde6f0d2264754727384c82792e56dacaadb84c9 | 677,974 |
def set_appliance_discovery_emails(
self,
email_list: list[str],
) -> bool:
"""Update email addresses configured to be notified for discovery of
new appliances.
.. warning::
Replaces the current configured list with the new list. To
add an email, first retrieve the current emails an... | 62872b47ebdd2c9129c379348ea763666262f17e | 677,975 |
def _check_not_none(value, name):
"""Checks that value is not None."""
if value is None:
raise ValueError(f"`{name}` must be specified.")
return value | bfded56ca8e86463d3d20ceebe252605bfe6319b | 677,976 |
def check_drange(drange, pdate1, pdate2):
"""
drange : list of two datetimes
pdate1 : datetime
pdate2 : datetime
Returns
savedata : boolean
returns True if drange is between pdate1 and pdate2
"""
savedata = True
testf = True
# if pdate1 is within drange then save the data.... | 1280c05c0973e9ea43def1644993424200d2158f | 677,977 |
import heapq
import functools
import itertools
def nlargest_heapreplace2(n, iterable):
"""Return the n largest items in the given iterable."""
# Uses the heapq.heapify structure for the list of largest numbers, to
# replace the search for the minimal number at every turn. The search is
# replaced by m... | d8f358738e6dbbe1a274cd232f57200d6908abe0 | 677,978 |
def fill_point(x, y, z, _):
"""
Returns a string defining a set of minecraft fill coordinates relative to the actor.
In minecraft, the y axis denotes the vertical (non-intuitively).
"""
return f'~{int(x)} ~{int(z)} ~{int(y)}' | 25cdf38627ea6f2dc612484f9ffb2c54e0d08d64 | 677,979 |
import os
def is_exe(fpath):
"""Returns true if fpath is an executable."""
return os.path.isfile(fpath) and os.access(fpath, os.X_OK) | b86e361473f8860cf8d002f196e2f9f5ea891d0a | 677,980 |
import operator
def advance_permutation(a, increasing=True, forward=True):
"""
Advance a list of unique, ordered elements in-place, lexicographically
increasing or backward, by rightmost or leftmost digit.
Returns False if the permutation wrapped around - i.e. went from
lexicographically greatest... | d5d2740e9b173c3277843411f1b5c05427d785ce | 677,981 |
def clearzero(df):
"""Remove STN rows which have 0% robustness across all runs."""
unique_stns = df.drop_duplicates(subset="stn_path")
to_remove = []
for _, row in unique_stns.iterrows():
stn_path = row["stn_path"]
runs = df.loc[df["stn_path"] == stn_path]
all_zero = True
... | ead11497b4bce7015d26eb72c00b406a4224f405 | 677,982 |
def locate_block_by_hash(chain, prev_hash):
"""
在区块链中定位区块
:param chain: 区块链
:param prev_hash: 前一区块的哈希
:return: 区块的高度
"""
for height, block in enumerate(chain):
if block.hash == prev_hash:
return height + 1
return -1 | e2ee94d8d1d6f5d27a561555706dee0c0bbfab16 | 677,983 |
def wait4localstack_object():
"""Wait4Localstack object."""
return {} | 8bdd64b6dc728256dcd4664636b3ec68afcfe25b | 677,984 |
def _empty_network(create_using, default):
"""Return an empty network.
See Also
--------
empty_hypergraph
empty_simplicial_complex
"""
if create_using is None:
H = default()
elif hasattr(create_using, "_node"):
# create_using is a Hypergraph object
create_using.... | 9001afc2d38af4034fdc9f139a75cfda123f2752 | 677,985 |
def prompt(msg):
"""Prompt the user for input."""
value = ""
while not value:
value = input(msg+" ").strip()
return value | edf2fa00d99b96d8ad25e9af40c1020eb39c6fe6 | 677,986 |
import math
def p_sequence(expected_value, days_a_week, upper_bound, step):
"""Calcualtes the capacity values to test."""
lower_p = math.ceil(days_a_week*expected_value/0.99)
# PSEQ per week, pseq per day
PSEQ = sorted(list(set([int(lower_p + step*i) for i in range(upper_bound)])))
pseq = [round(i... | c3122ec315aa190f9ad7ca3c53c9c02c380cb634 | 677,987 |
import torch
def jitter(X, ox, oy):
"""
Helper function to randomly jitter an image.
Inputs
- X: PyTorch Tensor of shape (N, C, H, W)
- ox, oy: Integers giving number of pixels to jitter along W and H axes
Returns: A new PyTorch Tensor of shape (N, C, H, W)
"""
if ox != 0:
left = X[:, :, :, ... | 6807ff6b7010d2684c4a737568e475a1695dcbf1 | 677,988 |
import sys
def make_input_pipeline_from_def(def_dict, mode, **kwargs):
"""Creates an InputPipeline object from a dictionary definition.
Args:
def_dict: A dictionary defining the input pipeline.
It must have "class" and "params" that correspond to the class
name and constructor parameters of an In... | bb080a8f87309d68c95dcb17052b28e76a3d55b6 | 677,989 |
import time
def add_timer(func_name):
"""Decorator to add timing to run commands
"""
def decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
line_len = 88
print("")
print... | 63e330fda8146c14613ba60feab7cde8daf6a4b9 | 677,990 |
def recall_at_n(asins: list, predicted_asins: list) -> float:
"""
Args:
asins ([list]):
predicted_asins ([list]):
"""
# number of relevant items
set_actual = set(asins)
set_preds = set(predicted_asins)
num_relevant = len(set_actual.intersection(set_preds))
# calculating... | 126043d4a1ff854584c671268d3ee129851d13c5 | 677,991 |
def volmesh_halfface_pinch(volmesh, hfkey, xyz):
"""
"""
x, y, z = xyz
w = volmesh.add_vertex(x=x, y=y, z=z)
hf_vkeys = volmesh.halfface_vertices(hfkey)
cell_halffaces = [hf_vkeys[::-1]]
halfedges = volmesh.halfface_halfedges(hfkey)
for u, v in halfedges:
cell_halffaces.append(... | d1f88aff44feaca312d49385e2677820c64f1de5 | 677,992 |
from numpy import array, arctan2, sqrt, shape
def vec_to_angles(vec):
"""
converts vector (x,y,z) to (magnitude, theta, phi)
"""
magnitude, theta, phi = [], [], []
if len(vec)==3 and len(shape(vec))<2:
vec = array([vec])
multiple_entries = False
else:
multiple_entries =... | 74096f0816b81f89a77d68f435697cdbe2a04153 | 677,993 |
import re
def to_slug(value):
""" Convert a string to a URL slug. """
value = value.lower()
# Space to dashes
value = re.sub(r'[\s_]+', '-', value)
# Special characters
value = re.sub(r'[^a-z0-9\-]+', '', value, flags=re.I)
# Extra dashes
value = re.sub(r'\-{2,}', '-', value)
va... | 27a1524f94324c83bd5fe763133bd2b2f65c5984 | 677,995 |
def get_digits_by_length(patterns, length):
"""Find all digits of a given length."""
return [pattern for pattern in patterns if len(pattern) == length] | d35b73c4ba9710a2a7d4f681ed02a7cfaac7d234 | 677,996 |
def calculate_fantasy_points(player) -> float:
"""
Calculate the fantasy points this player earned from the formula
Kill = 0.3
Death = -0.3
Assist = 0.15
Last Hit = 0.003
Gold per minute = 0.002
EXP per minute = 0.002
Seconds of enemy stuns = 0.07
Every 1000 allied healing done ... | a2a0c91a69720904a81fee58d5a5ecf236f32bdc | 677,997 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.