content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_case_insensitive_dict_upper_get_not_existent(key):
"""
Test case insensitive lookup (non existent keys) in CaseInsensitiveDict with upper() as normalizing function
"""
from masci_tools.util.case_insensitive_dict import CaseInsensitiveDict
d = CaseInsensitiveDict(TEST_DICT, upper=True)
a... | 13,100 |
def _GenerateElementInfo(impl_path, names):
"""Generates the data a group needs to load sub elements.
Args:
impl_path: The file path to the command implementation for this group.
names: [str], The names of the sub groups or commands found in the group.
Raises:
LayoutException: if there is a command ... | 13,101 |
def locate_dir(instrument, mode=None):
"""Locate the instrument specific directory for a reference file.
The mode=None test case is disabled because it mysteriously causes these tests to
fail when running the runtests script:
ERROR: test_throughput_lookup_generation (crds.tests.test_synphot_lookup_... | 13,102 |
def auto_grad():
"""
对函数 y=2x**2 求关于列向量 x 的梯度 4x
:return:
"""
x = nd.arange(4).reshape((4, 1))
logger.info("autograd 数组:")
logger.info(x)
# 调用attach_grad函数来申请存储梯度所需要的内存
x.attach_grad()
logger.info("autograd.is_training():")
logger.info(autograd.is_training())
# 调用re... | 13,103 |
def test_odl_rsp_retrieval_no_rsp(capfd, classifier, rsp_name):
"""
Test if classifier raises RuntimeError for RSP non-existing in ODL
Pass: if `RuntimeError` is raised
if 'operation-failed' string is in captured error log
Fail: if the above conditions fails
"""
with pytest.raises(Ru... | 13,104 |
def pas(al, ap, bl,bp):
""" Postion-angle from spherical coordinates.
:param al: longitude of point A in radians.
:type al: float
:param ap: latitude of point A in radians.
:type ap: float
:param bl: longitude of point B in radians.
:type bl: float
:param bp: latitude of point B in r... | 13,105 |
def get_messy_items_for_training(mod_factor=5):
"""
Fetch a subset of `FacilityListItem` objects that have been parsed and are
not in an error state.
Arguments:
mod_factor -- Used to partition a subset of `FacilityListItem` records. The
larger the value, the fewer records will be ... | 13,106 |
def test_roc_curve_display_plotting(
pyplot,
response_method,
data_binary,
with_sample_weight,
drop_intermediate,
with_strings,
constructor_name,
default_name,
):
"""Check the overall plotting behaviour."""
X, y = data_binary
pos_label = None
if with_strings:
y =... | 13,107 |
def tanh_squared(x: np.ndarray, margin: float, loss_at_margin: float = 0.95):
"""Returns a sigmoidal shaping loss based on Hafner & Reidmiller (2011).
Args:
x: A numpy array representing the error.
margin: Margin parameter, a positive `float`.
loss_at_margin: The loss when `l2_norm(x) == margin`. A `fl... | 13,108 |
def test_fill(machine_tiny):
"""
Проверка заполнения машины
"""
with patch('trivial_tools.storage.caching_instance.datetime') as fake:
fake.now.return_value = datetime(2019, 10, 31, 18, 6, 0)
assert machine_tiny.total() == 0
machine_tiny.set('key_1', 'value')
assert mach... | 13,109 |
def _inv_Jacobian_2D(J, detJ):
""" manually invert 2x2 jacobians J in place """
tmp = J[:, 1, 1, :] / detJ
J[:, 0, 1, :] = -J[:, 0, 1, :] / detJ
J[:, 1, 0, :] = -J[:, 1, 0, :] / detJ
J[:, 1, 1, :] = J[:, 0, 0, :] / detJ
J[:, 0, 0, :] = tmp
return J | 13,110 |
def ratio_error_acc(y_true, y_pred, epsilon, threshold):
"""
Calculate the ratio error accuracy with the threshold.
:param y_true:
:param y_pred:
:param epsilon:
:param threshold:
:return:
"""
ratio_1 = keras.layers.Lambda(lambda x: (x[0] + x[2]) / (x[1] + x[2]))([y_true, y_... | 13,111 |
def error_embed(ctx: context.ApplicationContext, title: str, description: str, author: bool = True) -> discord.Embed:
"""Make a basic error message embed."""
return make_embed(
ctx=ctx,
title=title if title else "Error:",
description=description,
color=discord.Color.red(),
... | 13,112 |
def load_configuration() -> Dict[str, Any]:
"""
Return dict from TOML formatted string or file.
Returns:
The dict configuration.
"""
default_config = """
[key_bindings]
AUTOCLEAR = "c"
CANCEL = "esc"
ENTER = "enter"
FILTER = ["F4", "\\... | 13,113 |
def test_angle_wrapping():
"""
ensure angle wrapping works properly
"""
data = survey.get_scale_height_data(track = 'CrF', wrap_at_180 = True)
data2 = survey.get_scale_height_data(track = 'CrF', wrap_at_180 = False)
assert np.allclose(data["INTEN"], data2["INTEN"], equal_nan = True) | 13,114 |
def type_weapon(stage, bin, data=None):
"""Weapon"""
if data == None:
return 1
if stage == 1:
return (str(data),'')
try:
v = int(data)
if 0 > v or v > 255:
raise
except:
raise PyMSError('Parameter',"Invalid Weapon value '%s', it must be 1 for ground attack or not 1 for air attack." % data)
... | 13,115 |
def show_home_menu_edit_msg(update, context):
"""
Edit current message with the home menu
"""
keyboard = get_home_menu_buttons()
text = 'I am your Terra Node Bot. 🤖\nClick *MY NODES* to get information about the Terra Nodes you monitor!'
query = update.callback_query
query.edit_message_tex... | 13,116 |
def to_square_feet(square_metres):
"""Convert metres^2 to ft^2"""
return square_metres * 10.7639 | 13,117 |
def middle_name_handler(update: Update, context: CallbackContext) -> str:
"""Get and save patronymic of user. Send hello with full name."""
u = User.get_user(update, context)
name = (f'{context.user_data[LAST_NAME]} {context.user_data[FIRST_NAME]} '
f'{context.user_data[MIDDLE_NAME]}')
cont... | 13,118 |
def import_dynamic_data(database_path, dynamic_data):
"""
Import dynamic . Currently designed for use with parsed dicitonary of dynamic data with station number and timestamp as key
:return:
"""
#Connect to database
conn = lite.connect(database_path)
with conn:
cur = conn.cur... | 13,119 |
def load_enzyme_reaction_relation():
"""
Gets all reaction and respective catalyzing enzymes and creates populates the table enzyme_reaction_organism for
E. coli.
Returns:
None
"""
data_df = pd.read_csv(ENZYME_GENES_DATA_FILE, sep=',')
organism = Organism.query.filter_by(name='E. ... | 13,120 |
def test_skipgram():
""" Test skip-gram with naiveSoftmaxLossAndGradient """
dataset, dummy_vectors, dummy_tokens = getDummyObjects()
print("==== Gradient check for skip-gram with naiveSoftmaxLossAndGradient ====")
gradcheck_naive(lambda vec: word2vec_sgd_wrapper(
skipgram, dummy_tokens, vec, d... | 13,121 |
def submit_barcodes(barcodes):
"""
Submits a set of {release1: barcode1, release2:barcode2}
Must call auth(user, pass) first
"""
query = mbxml.make_barcode_request(barcodes)
return _do_mb_post("release", query) | 13,122 |
def get_idf_dict(arr, tokenizer, nthreads=4):
"""
Returns mapping from word piece index to its inverse document frequency.
Args:
- :param: `arr` (list of str) : sentences to process.
- :param: `tokenizer` : a BERT tokenizer corresponds to `model`.
- :param: `nthreads` (int) : numbe... | 13,123 |
def load_id_json_file(json_path):
"""
load the JSON file and get the data inside
all this function does is to call json.load(f)
inside a with statement
Args:
json_path (str): where the target JSON file is
Return:
ID list (list): all the data found in t... | 13,124 |
def check_github_scopes(exc: ResponseError) -> str:
"""
Parse github3 ResponseError headers for the correct scopes and return a
warning if the user is missing.
@param exc: The exception to process
@returns: The formatted exception string
"""
user_warning = ""
has_wrong_status_code = e... | 13,125 |
def _add_threat_intel_subparser(subparsers):
"""Add Threat Intel subparser: manage.py threat-intel [subcommand]"""
usage = 'manage.py threat-intel [subcommand]'
description = """
StreamAlertCLI v{}
Enable, configure StreamAlert Threat Intelligence feature.
Available Subcommands:
manage.py threat-intel... | 13,126 |
def user_login():
"""
# 显示页面的设置
:return: 接收前端的session信息来显示不同的页面
"""
# 获取参数
name = session.get("name")
if name is not None:
return jsonify(errno=RET.OK, errmsg="True", data={"name": name})
else:
return jsonify(errno=RET.SESSIONERR, errmsg="用户未登入") | 13,127 |
def sample_conditional(node: gtsam.GaussianConditional, N: int, parents: list = [], sample: dict = {}):
"""Sample from conditional """
# every node ~ exp(0.5*|R x + S p - d|^2)
# calculate mean as inv(R)*(d - S p)
d = node.d()
n = len(d)
rhs = d.reshape(n, 1)
if len(parents) > 0:
rhs... | 13,128 |
def _liftover_data_path(data_type: str, version: str) -> str:
"""
Paths to liftover gnomAD Table.
:param data_type: One of `exomes` or `genomes`
:param version: One of the release versions of gnomAD on GRCh37
:return: Path to chosen Table
"""
return f"gs://gnomad-public-requester-pays/relea... | 13,129 |
def valueinfo_to_tensor(vi):
"""Creates an all-zeroes numpy tensor from a ValueInfoProto."""
dims = [x.dim_value for x in vi.type.tensor_type.shape.dim]
return np.zeros(
dims, dtype=onnx.mapping.TENSOR_TYPE_TO_NP_TYPE[vi.type.tensor_type.elem_type]
) | 13,130 |
def signup_email():
"""Create a new account using data encoded in the POST body.
Expects the following form data:
first_name: E.g. 'Taylor'
last_name: E.g. 'Swift'
email: E.g. 'tswift@gmail.com'
password: E.g. 'iknewyouweretrouble'
Responds with the session cookie via the `... | 13,131 |
def calculate_multi_rmse(regressor, n_task):
"""
Method which calculate root mean squared error value for trained model
Using regressor attributes
Return RMSE metrics as dict for train and test datasets
:param regressor: trained regression model object
:param n_task:
:type regressor: Traine... | 13,132 |
def detr_predict(model, image, thresh=0.95):
"""
Function used to preprocess the image, feed it into the detr model, and prepare the output draw bounding boxes.
Outputs are thresholded.
Related functions: detr_load, draw_boxes in coco.py
Args:
model -- the detr model from detr_load()
... | 13,133 |
def extract_colors_from_static_themes(ids, **kw):
"""Extract and store colors from existing static themes."""
log.info('Extracting static themes colors %d-%d [%d].', ids[0], ids[-1],
len(ids))
addons = Addon.objects.filter(id__in=ids)
extracted = []
for addon in addons:
first_pr... | 13,134 |
def docker() -> DockerAPI:
"""Mock DockerAPI."""
images = [MagicMock(tags=["ghcr.io/home-assistant/amd64-hassio-supervisor:latest"])]
with patch("docker.DockerClient", return_value=MagicMock()), patch(
"supervisor.docker.DockerAPI.images", return_value=MagicMock()
), patch("supervisor.docker.Do... | 13,135 |
def comp_fill_factor(self):
"""Compute the fill factor of the winding"""
if self.winding is None:
return 0
else:
(Nrad, Ntan) = self.winding.get_dim_wind()
S_slot_wind = self.slot.comp_surface_wind()
S_wind_act = (
self.winding.conductor.comp_surface_active()
... | 13,136 |
def idewpt(vp):
"""
Calculate the dew point given the vapor pressure
Args:
vp - array of vapor pressure values in [Pa]
Returns:
dewpt - array same size as vp of the calculated
dew point temperature [C] (see Dingman 2002).
"""
# ensure that vp is a numpy array
... | 13,137 |
def _hexify(num):
"""
Converts and formats to hexadecimal
"""
num = "%x" % num
if len(num) % 2:
num = '0'+num
return num.decode('hex') | 13,138 |
def syn_ucbpe(num_workers, gp, acq_optimiser, anc_data):
""" Returns a recommendation via UCB-PE in the synchronous setting. """
# Define some internal functions.
beta_th = _get_ucb_beta_th(gp.input_dim, anc_data.t)
# 1. An LCB for the function
def _ucbpe_lcb(x):
""" An LCB for GP-UCB-PE. """
mu, sigm... | 13,139 |
def get_reward(intervention, state, time):
"""Compute the reward based on the observed state and choosen intervention."""
A_1, A_2, A_3 = 60, 500, 60
C_1, C_2, C_3, C_4 = 25, 20, 30, 40
discount = 4.0 / 365
cost = (
A_1 * state.asymptomatic_humans
+ A_2 * state.symptomatic_humans
... | 13,140 |
def array_of_floats(f):
"""Read an entire file of text as a list of floating-point numbers."""
words = f.read().split()
return [builtin_float(x) for x in words] | 13,141 |
def add_to_command_file(properties_path, command):
"""
This method writes the commands to a text file in the output folder
"""
commands_path = os.path.dirname(properties_path) + '/commands_' + timestamp + '.txt'
with open(commands_path, 'a+') as commands:
commands.write(command + '\n') | 13,142 |
def change_currency():
""" Change user's currency """
form = CurrencyForm()
if form.validate_on_submit():
currency = form.rate.data
redirected = redirect(url_for('cashtrack.overview'))
redirected.set_cookie('filter', currency)
symbol = rates[currency]['symbol']
flash(... | 13,143 |
def get_host_checks():
"""
Returns lxc configuration checks.
"""
import lxc
out = subprocess.check_output('lxc-checkconfig', shell=True)
response = []
if out:
for line in out.splitlines():
response.append(line.decode('utf-8'))
info = {
'checks': response,
... | 13,144 |
def remplissage_contenu(engine, article) -> None:
"""
Permet de remplir le texte des articles la base de données.
:param article : instance de la classe Surlignage.
:param engine : instance de connexion à la base de donnée.
"""
pbar = tqdm(range(len(article.url_surlignage)), colour='green', des... | 13,145 |
def test_4():
"""
Detect the date columns in naukri_com.csv
Example date present - '2019-07-06 09:20:22 +0000'
"""
table = pandas.read_csv('data_for_tests/naukri_com.csv')
result = date_detection.detect(table)
print(result)
expected_result = '''{'Crawl Timestamp': {'type': <ColumnTypes.C... | 13,146 |
def q2_1(df: pd.DataFrame) -> int:
"""
Finds # of entries in df
"""
return df.size[0] | 13,147 |
def is_shell(command: str) -> bool:
"""Check if command is shell."""
return command.startswith(get_shell()) | 13,148 |
def parse_args():
"""set and check parameters."""
parser = argparse.ArgumentParser(description="bert process")
parser.add_argument("--pipeline_path", type=str, default="./config/fat_deepffm.pipeline", help="SDK infer pipeline")
parser.add_argument("--data_dir", type=str, default="../data/input/Criteo_bi... | 13,149 |
def board_init():
"""
Initializes board with all available values 1-9 for each cell
"""
board = [[[i for i in range(1,n+1)] for j in range(n)] for k in range(n)]
return board | 13,150 |
def gen_int_lists(num):
"""
Generate num list strategies of integers
"""
return [
s.lists(s.integers(), max_size=100)
for _ in range(num)
] | 13,151 |
def is_blob(bucket: str, file:str):
""" checking if it's a blob """
client = storage.Client()
blob = client.get_bucket(bucket).get_blob(file)
return hasattr(blob, 'exists') and callable(getattr(blob, 'exists')) | 13,152 |
def _validate_train_test_split(X_train, X_test, y_train, y_test):
"""Check that data shapes are consistent with proper split."""
assert X_train.shape[0] == y_train.shape[0]
assert X_test.shape[0] == y_test.shape[0]
if X_train.ndim > 1:
assert X_train.shape[1] == X_test.shape[1]
if y_train.nd... | 13,153 |
def rotate(q, p):
"""
Rotation of vectors in p by quaternions in q
Format: The last dimension contains the quaternion components which
are ordered as (i,j,k,w), i.e. real component last.
The other dimensions follow the default broadcasting rules.
"""
iw = 3
ii = 0
i... | 13,154 |
def _is_whitelisted(name: str, doc_obj: Union['Module', 'Class']):
"""
Returns `True` if `name` (relative or absolute refname) is
contained in some module's __pdoc__ with a truish value.
"""
refname = doc_obj.refname + '.' + name
module = doc_obj.module
while module:
qualname = refna... | 13,155 |
def permute_bond_indices(atomtype_vector):
"""
Permutes the set of bond indices of a molecule according to the complete set of valid molecular permutation cycles
atomtype_vector: array-like
A vector of the number of each atoms, the length is the total number of atoms.
An A3B8C system would b... | 13,156 |
def get_cell_integer_param(device_resources,
cell_data,
name,
force_format=None):
"""
Retrieves definition and decodes value of an integer cell parameter. The
function can optionally force a specific encoding format if needed.
... | 13,157 |
def remove(config, device_ids: tuple):
""" Removes USB devices from the config """
uev = config.uev
uev.remove_devices(device_ids=device_ids) | 13,158 |
def get_md5(filename):
""" Calculates the MD5 sum of the passed file
Args:
filename (str): File to hash
Returns:
str: MD5 hash of file
"""
import hashlib
# Size of buffer in bytes
BUF_SIZE = 65536
md5 = hashlib.md5()
# Read the file in 64 kB blocks... | 13,159 |
def get_py_path(pem_path):
"""Returns the .py filepath used to generate the given .pem path, which may
or may not exist.
Some test files (notably those in verify_certificate_chain_unittest/ have a
"generate-XXX.py" script that builds the "XXX.pem" file. Build the path to
the corresponding "generate-XXX.py" (... | 13,160 |
def is_recurrent(sequence):
"""
Returns true if the given sequence is recurrent (elements can exist more than once), otherwise returns false.
Example
---------
>>> sequence = [1,2,3,4,5]
>>> ps.is_recurrent(sequence)
False
>>> sequence = [1,1,2,2,3]
>>> ps.is_recurrent(sequence)
True
"""
element_counts... | 13,161 |
def flex_stack(items, dim=0):
"""
"""
if len(items) < 1:
raise ValueError("items is empty")
if len(set([type(item) for item in items])) != 1:
raise TypeError("items are not of the same type")
if isinstance(items[0], list):
return items
elif isinstance(items[0], torch.T... | 13,162 |
def download_image_data(gpx_file,
padding,
square,
min_lat,
min_long,
max_lat,
max_long,
cache_dir):
"""
Download sa... | 13,163 |
def find_nearest_values(array, value):
"""Find indexes of the two nearest values of an array to a given value
Parameters
----------
array (numpy.ndarray) : array
value (float) : value
Returns
-------
idx1 (int) : index of nearest value in the array
idx2 (int) : index of s... | 13,164 |
def channel_info(channel_id):
"""
Get Slack channel info
"""
channel_info = slack_client.api_call("channels.info", channel=channel_id)
if channel_info:
return channel_info['channel']
return None | 13,165 |
def uninstall_trap(dut, feature_name, trap_id):
"""
Uninstall trap by disabling feature and set always_enable to false
Args:
dut (SonicHost): The target device
feature_name (str): feature name corresponding to the trap
trap_id (str): trap id
"""
disable_feature_entry(dut, fe... | 13,166 |
def gen_pdf(outfile, asset_ids, width, prefix):
"""Generate a PDF with sheets of QR codes.
Args:
outfile: absolute filepath to write the PDF to.
asset_ids: list of lists of asset IDs. Each sublist forms a single page, and
should contain exactly enough codes to fill the page.
width: width to pad t... | 13,167 |
def log(message: str) -> Callable:
"""Returns a decorator to log info a message before function call.
Parameters
----------
message : str
message to log before function call
"""
def decorator(function: Callable) -> Callable:
@wraps(function)
def wrapper(*args: Any, **kw... | 13,168 |
def client(identity: PrivateIdentity) -> Client:
"""Client for easy access to iov42 platform."""
return Client(PLATFORM_URL, identity) | 13,169 |
def init_weights(module, init='orthogonal'):
"""Initialize all the weights and biases of a model.
:param module: any nn.Module or nn.Sequential
:param init: type of initialize, see dict below.
:returns: same module with initialized weights
:rtype: type(module)
"""
if init is None: # Base ... | 13,170 |
def run_security_tests(*, image: str):
"""Run the security tests"""
temp_dir = CWD
if os.environ.get("GITHUB_ACTIONS") == "true":
if os.environ.get("RUNNER_TEMP"):
# Update the temp_dir if a temporary directory is indicated by the
# environment
temp_dir = Path(st... | 13,171 |
def run(puzzle_class, start_position=None, output_stream=sys.stdout,
settings=None):
"""Given a `Puzzle` subclass instance, find all solutions."""
if settings is None:
settings = Settings(start_position=start_position)
elif start_position:
settings.start_position = start_position
... | 13,172 |
def main(argv: Optional[Sequence[str]] = None) -> None:
"""Run VROOM command line interface."""
_main(sys.argv if argv is None else argv) | 13,173 |
def getsoundchanges(reflex, root): # requires two ipastrings as input
"""
Takes a modern-day L1 word and its reconstructed form and returns \
a table of sound changes.
:param reflex: a modern-day L1-word
:type reflex: str
:param root: a reconstructed proto-L1 word
:type root: str
:re... | 13,174 |
def compute_normals(filename, datatype='cell'):
"""
Given a file, this method computes the surface normals of the mesh stored
in the file. It allows to compute the normals of the cells or of the points.
The normal computed in a point is the interpolation of the cell normals of
the cells adiacent to ... | 13,175 |
def distribution_of_feature_box_plot(dfData,
tplFigSize = (10,5),
intFontSize = 22,
strName = "Test",
boolSave = False):
"""
Parameters
#---------
dfData ... | 13,176 |
def bounce():
"""
The ball has VX as x velocity and 0 as y velocity. Each bounce reduces
y velocity to REDUCE of itself.
"""
vertical_velocity = 0
while ball.x <= window.width:
ball.move(VX, vertical_velocity)
vertical_velocity += GRAVITY
if ball.y >= window.heig... | 13,177 |
def build_layers_url(
layers: List[str], *, size: Optional[LayerImageSize] = None
) -> str:
"""Convenience method to make the server-side-rendering URL of the provided layer URLs.
Parameters
-----------
layers: List[:class:`str`]
The image urls, in ascending order of Zone ID's
size: Opt... | 13,178 |
def SyncBatchNorm(*args, **kwargs):
"""In cpu environment nn.SyncBatchNorm does not have kernel so use nn.BatchNorm2D instead"""
if paddle.get_device() == 'cpu':
return nn.BatchNorm2D(*args, **kwargs)
else:
return nn.SyncBatchNorm(*args, **kwargs) | 13,179 |
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_burst_size_get(uuid, local_id): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_capacity_bandwidth_profile_peak_burst_size_get
returns tapi.common.Capac... | 13,180 |
def test_color():
"""
Text-buttons colors
"""
vq_button = vq.Button.text("foo") | 13,181 |
def parse_path_length(path):
"""
parse path length
"""
matched_tmp = re.findall(r"(S\d+)", path)
return len(matched_tmp) | 13,182 |
def check_permisions(request, allowed_groups):
""" Return permissions."""
try:
profile = request.user.id
print('User', profile, allowed_groups)
is_allowed = True
except Exception:
return False
else:
return is_allowed | 13,183 |
def find_planets_around_stars(stars_df, campaign_no, max_planets=None,
provenance=["EVEREST", "K2SFF", "K2"],
log_file='summary_log.csv', interactive=False):
"""
Find one or more planet transits given input time, raw flux and corrected
flux series.... | 13,184 |
def kanji2digit(s):
"""
1から99までの漢数字をアラビア数字に変換する
"""
k2d = lambda m, i: _kanjitable[m.group(i)]
s = _re_kanjijiu1.sub(lambda m: k2d(m,1) + k2d(m,2), s)
s = _re_kanjijiu2.sub(lambda m: u'1' + k2d(m,1), s)
s = _re_kanji.sub(lambda m: k2d(m,1), s)
s = s.replace(u'十', u'10')
return s | 13,185 |
def type_right(wait=0):
"""
Press Right key
Args:
wait (int, optional): Wait interval (ms) after task
"""
kb.send('right')
delay = max(0, wait or config.DEFAULT_SLEEP_AFTER_ACTION)
sleep(delay) | 13,186 |
def calc_rdm_segment(t, c, segment_id_beg, segment_id_end, segment_id, ph_index_beg, segment_ph_cnt, debug=0):
"""
Function to calculate radiometry (rdm)
Input:
t - time or delta_time of ATL03, for a given gt num
c - classification of ATL03 for a given gt num
ensure that no nan... | 13,187 |
def load_featurizer(pretrained_local_path):
"""Load pretrained model."""
return CNN_tf("vgg", pretrained_local_path) | 13,188 |
def create_zipfile(dir_to_zip, savepath=''):
"""Create a zip file from all the files under 'dir_to_zip'.
The output zip file will be saved to savepath.
If savepath ends with '.zip', then the output zip file will be
saved AS 'savepath'. Necessary tree subdirectories are created automatically.
Else, ... | 13,189 |
def make_cmdclass(basecmd):
"""Decorate setuptools commands."""
base_run = basecmd.run
def new_run(self):
from templateflow.conf import setup_home
setup_home()
base_run(self)
basecmd.run = new_run
return basecmd | 13,190 |
def rmse(predictions, targets):
"""Compute root mean squared error"""
rmse = np.sqrt(((predictions - targets) ** 2).mean())
return rmse | 13,191 |
def format_timedelta(value, time_format=None):
""" formats a datetime.timedelta with the given format.
Code copied from Django as explained in
http://stackoverflow.com/a/30339105/932593
"""
if time_format is None:
time_format = "{days} days, {hours2}:{minutes2}:{seconds2}"
if hasa... | 13,192 |
def categorical_log_likelihood(probs: chex.Array, labels: chex.Array):
"""Computes joint log likelihood based on probs and labels."""
num_data, unused_num_classes = probs.shape
assert len(labels) == num_data
assigned_probs = probs[jnp.arange(num_data), jnp.squeeze(labels)]
return jnp.sum(jnp.log(ass... | 13,193 |
def ask_name(question: str = "What is your name?") -> str:
"""Ask for the users name."""
return input(question) | 13,194 |
def p_path_primary_2(p):
"""
path_primary : bracketed_path
"""
# | not_path_negated_property_set # not implemented atm
p[0] = p[1] | 13,195 |
def _maxcut(g: Graph, values: Sequence[int]) -> float:
"""
cut by given values $$\pm 1$$ on each vertex as a list
:param g:
:param values:
:return:
"""
cost = 0
for e in g.edges:
cost += g[e[0]][e[1]].get("weight", 1.0) / 2 * (1 - values[e[0]] * values[e[1]])
return cost | 13,196 |
def main():
"""Execute main."""
cli.add_command(deploy)
cli.add_command(configure)
cli() | 13,197 |
def cp_als(X, rank, random_state=None, init='randn', **options):
"""Fits CP Decomposition using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be compute... | 13,198 |
def load_station_enu(
station_name,
start_date=None,
end_date=None,
download_if_missing=True,
force_download=False,
zero_by="mean",
to_cm=True,
):
"""Loads one gps station's ENU data since start_date until end_date as a dataframe
Args:
station_name (str): 4 Letter name of GP... | 13,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.