content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def space_list(line: str) -> list:
""""Given a string, return a list of index positions where a blank space occurs.
>>> space_list(" abc ")
[0, 1, 2, 3, 7]
"""
spaces = []
for idx, car in enumerate(list(line)):
if car == " ":
spaces.append(idx)
return spaces | 968fbd2a4cacbd8fda110855677ba10d6bdacd00 | 636,967 |
def pre_process_request_data(request_data):
"""
Pro process request database.
"""
if request_data is None:
request_data = dict()
return request_data | ee3f09e6d0a3f5d6d844201b3a9846f949883992 | 636,968 |
import itertools
def _get_coord_mapping(
dims,
output,
out_indices,
numblocks,
argpairs,
concatenate,
):
"""Calculate coordinate mapping for graph construction.
This function handles the high-level logic behind Blockwise graph
construction. The output is a tuple containing: The ma... | 6cfa507b4bb2ebb50053d71c6947553196114f9a | 636,969 |
import optparse
def ParseOptions():
"""Parse command line options.
Returns:
A pair of (options data, remaining args)
"""
parser = optparse.OptionParser()
parser.add_option("--build_dir", dest="build_dir")
parser.add_option("--volname", dest="volname", default="GoogleJapaneseInput")
parser.add_optio... | 211816279f29bfe8244db0cf86a40ecdfe8a7aa4 | 636,970 |
import functools
import itertools
def boto_all(func, *args, **kwargs):
"""
Iterate through all boto next_token's
"""
ret = [func(*args, **kwargs)]
while ret[-1].next_token:
kwargs['next_token'] = ret[-1].next_token
ret.append(func(*args, **kwargs))
# flatten it by 1 level
... | 7c4bda01a56b396411e9e806d83fd0a347e2fdc4 | 636,971 |
from typing import Callable
import time
import sys
import requests
def wait_for_tensorboard(max_seconds: float, url: str, still_alive_fn: Callable[[], bool]) -> bool:
"""Return True if the process successfully comes up before a deadline."""
deadline = time.time() + max_seconds
while True:
if tim... | 9069fc0302a95b1c6923f52a7704925c045d8c84 | 636,972 |
def xr_average_across_days_of_year(da):
"""
Collapses an array across days of each year.
Parameters
----------
da: xr.DataArray
with 'time' dimension
Returns
-------
xr.DataArray with a 'year' dimension instead of 'time'
"""
return da.groupby("time.year").mean() | 15f4aa6cab514bf2a609f46f06a7b4d406fbdbfd | 636,973 |
import numpy
def linear(yin, xin, xout, method='linear'):
"""
Interpolate the curve defined by (xin, yin) at points xout. The array
xin must be monotonically increasing. The output has the same data type as
the input yin.
:param yin: y values of input curve
:param xin: x values of input curve... | 26f99170ea5dc3ab6cfd768ef2a668ffebfc2af4 | 636,974 |
def update_record_count(count_a, count_b):
"""Updates the running number of records processed.
Given previous running total and current batch size, return new running total.
Args:
count_a: tf.int64 scalar tensor of previous running total of records.
count_b: tf.int64 scalar tensor of current batch size.... | 8f2ecd121815e7dcb30c7ef04311147cb104dbed | 636,975 |
def prompt_for_yes_no(msg):
"""returns a bool based on whether the user presses y/n."""
choice = None
while not choice or choice.lower() not in ['y', 'n', 'yes', 'no']:
choice = input('%s (y/n) ' % msg).lower()
return choice.lower() in ['y', 'yes'] | b6c31055be5accdb62a4dcd6ecc5234955b43845 | 636,976 |
def divide(x, y):
""" Idiomatic / Pythonic recursive division with remainder """
if x == 0:
return (0,0)
q, r = divide(x / 2, y)
q *= 2
r *= 2
if x & 1:
r += 1
if r >= y:
r -= y
q += 1
return (q,r) | e056e7749b5a8661e966b8723b8f667605b92de3 | 636,978 |
def evaluate_mva(df, mva):
"""
Evaluate the response of a trained classifier.
Parameters
----------
df : DataFrame, shape= [n_training_samples, n_features]
DataFrame containing features.
mva
Trained classifier.
Returns
-------
Series or array
Classifier resp... | 94432f3d374ba2d34e0cb120cba70b62c33ea464 | 636,979 |
import os
def create_directory(directory_path):
"""
This function validate that exist a directory, if not, then try to create
:param directory_path:
:return:
"""
if not os.path.exists(directory_path) or not os.path.isdir(directory_path):
os.makedirs(directory_path)
return True | 5e2305178de2d8e22beb2e53070685dcdb7b9429 | 636,980 |
import sys
def accept_status(status: bytes) -> bool:
"""
Check if the server status is OK
"""
if status == b'MSG-OK-DONE':
return True
if not status:
raise InterruptedError('Server closed unexpectedly')
if not status.startswith(b'MSG-'):
print(f'Unexpected response st... | f9872aa9a36559735ba8ea29246f5ceebe6e30d9 | 636,981 |
def _get_naive_return(x, annualize=False, ann_tday=253):
"""Get Naive Return
Most basic way of calculating return ... doesn't account holding duration
Args:
x (DataFrame): DataFrame with 'date' index, columns for
'end_value_t' (see M_T in _get_hpr()) and 'txn_value' (shares * price)
... | 7e66e9118d3abdb905e3f0459efd2cd35ea9c6f3 | 636,982 |
def add_50(x):
"""
Adds 50 to the input value x.
"""
return x + 50 | 26a36e12ad38617efc904359729313c430a017c1 | 636,983 |
def reindex_frame(target_df, index_mapper):
"""
Parameters
----------
target_df :
index_mapper :
Returns
-------
"""
return target_df.rename(index=index_mapper) | 6e986d3b6270db4ec8f768e316607bd1fa0d41d2 | 636,984 |
def sum_mult_nums(x: int, y: int, z: int) -> str:
"""
005
Ask the user to enter three numbers. Add together the first two numbers and then multiply this total
by the third. Display the answer as 'The answer is <answer>.
"""
result = (x + y) * z
return f"The answer is {result}." | e5593a5f2a48247b392cfa08cf4e6eff06ebe79a | 636,985 |
def is_descriptor_schema(data):
"""Return ``True`` if passed object is DescriptorSchema and ``False`` otherwise."""
return type(data).__name__ == 'DescriptorSchema' | 46337d0837f86ff9c6500d6e101844f968e724a3 | 636,986 |
def serialize_curve(fcurve):
"""Returns a list of dictionaries representing each of the keys in the given FCurve."""
key_data_list = []
for key in fcurve.Keys:
key_data = {
'time': key.Time.Get(),
'value': key.Value,
'interpolation': int(key.Interpolation),
... | 1af5aea6ca0aa8c9ae309ba9b178fa1ecce19493 | 636,987 |
def valid_year(year):
"""Check if number is a valid year"""
return 1920 <= year < 2030 | 3f060ee33de3fd29b89d958386142f6717327524 | 636,988 |
def split_paths(data):
"""
splits the data in train and test collections
by default the data is divided in 3 : 1 proportion
:return train and test collections:
"""
test, train = {}, {}
for id, paths in data.items():
train[id] = paths[:3*len(paths)//4]
test[id] = paths[3*len(p... | c590ffe391cb0e57b64f50fee45ebd9bcb1385fb | 636,989 |
from pathlib import Path
import json
import requests
import warnings
def get_countries_data():
"""Pull countries example GeoJSON from the net or a locally cached file.
If this is not locally cached, yet, it will be after the first call,
unless the file cannot be saved, in which case it will be re-downloa... | c5abb23dbfbdf5eedc1fb4cfea07f6ce803dd3d1 | 636,990 |
def add_reprompt(response):
"""
Adds a response message to tell the user to ask their question again.
"""
response['response']['reprompt'] = {
"outputSpeech": {
"type": "PlainText",
"text": "Please ask your crypto price question"
}
}
return response | 64fa9f057e84d7332a7c3273a6d1940bcbe03d36 | 636,991 |
from typing import OrderedDict
def ohem(second_stage):
"""Add OHEM to second stage head"""
if second_stage is None:
print('there is not second stage for this detector, OHEM can not be used')
return False
ohem = OrderedDict({'batch_size': 512})
sampler = OrderedDict({'type': 'keep_all'}... | 9a2c6148937a9f0c67cc1ef55b17c715802404b1 | 636,992 |
import argparse
def parse_arguments():
"""
Parse the command line arguments
"""
ap = argparse.ArgumentParser()
ap.add_argument(
"-m",
"--models",
required=False,
default="mdef_detr",
help=
"The models to be used for performing inference. Available op... | 2629cb9e4eb170fd58a16f489c9eab16ca8179d4 | 636,993 |
import math
def rotation_matrix_to_euler_angle(R):
"""
Converts a rotation matrix to [yaw, pitch, roll]
"""
yaw = math.atan2(R[1, 0], R[0, 0])
pitch = math.atan2(-R[2, 0], math.sqrt(R[2, 1] ** 2 + R[2, 2] ** 2))
roll = math.atan2(R[2, 1], R[2, 2])
return yaw, pitch, roll | 8e1f7c77496fabbb0478454940c6cb336d19a0ce | 636,994 |
import torch
def calculate_cm_torch(output, target, num_classes):
"""Calculate confussion matrix"""
with torch.no_grad():
confusion = torch.zeros(num_classes, num_classes)
_, preds = torch.max(output, 1)
for t, p in zip(target.view(-1), preds.view(-1)):
confusion[t.long... | f78dbb4a62bbfd707de90fb218ac505555ff8c68 | 636,995 |
def arc(equity_array, scale=252):
"""
Annualized Return Ratio
:param equity_array: equity line
:param scale: number of days required for normalization. By default in a year there are 252 trading days.
:return: ARC as percentage
"""
return (equity_array[-1] / equity_array[0]) ** (scale / len(... | d7f9ea620d91b8833570cb7bdb9e60b7af49a143 | 636,996 |
import os
def fixpath(path):
"""Uniformly format a path."""
return os.path.normpath(os.path.realpath(path)) | 976d4d231d54cfd23712d13de9a9030cefd353d9 | 636,997 |
def drop_paragraphs(paragraphs, list_to_drop):
"""function to allow the user to remove paragraphs they feel are unimportant"""
for i in sorted(list_to_drop, reverse=True):
del paragraphs[i - 1]
return paragraphs | 91f1d9a666043bbd37e4ff0ffb8d6cd82b273767 | 636,998 |
import os
def check_empty(path):
"""检查相应位置的空文档, 计数, 并输出空文档名, 便于调整"""
empty_list = []
for filename in os.listdir(path):
with open(os.path.join(path, filename), 'r', encoding='utf8') as txt_fr:
txt_file = txt_fr.read()
if len(txt_file) == 0:
empty_list.append(filename... | 2b4fa13db111ee88588a6839615605f56bc5fa1a | 636,999 |
def _get_id2upper(id2upper, item_id, item_obj):
"""Add the parent item IDs for one item object and their upper."""
if item_id in id2upper:
return id2upper[item_id]
upper_ids = set()
for upper_obj in item_obj.get_goterms_upper():
upper_id = upper_obj.item_id
upper_ids.add(upper_id... | e2f39eda3fe250a8cc1eb344e7e157e408e3c8ca | 637,000 |
def wrap_as_envelope(data=None, error=None, as_null=True):
"""
as_null: if True, keys for null values are created and assigned to None
"""
payload = {}
if data or as_null:
payload['data'] = data
if error or as_null:
payload['error'] = error
return payload | 8107a3810cc7cd8e074c71d0a3fa4729c875be28 | 637,001 |
import re
def normalize_directors(s: str) -> str:
"""Restore proper first-last name order and use a uniform separator between multiple names."""
flip = lambda name: ' '.join(reversed(name.split(', ')))
return ' & '.join(map(flip, re.split(' & |/', s))) | 1dcb31f0475bb2c307ca790f0a8b25da79393ede | 637,002 |
def string_to_number(s):
"""Input stringified number and return integer."""
return int(s) | ed74783348d85d06cd8afe72feda5d9872398705 | 637,003 |
import typing
def offers() -> dict[str, dict[str, typing.Any]]:
"""Offres à définir. Modifier cette fonction pour modifier les offres.
L'argument `active` signifie que l'offre peut être utilisée pour créer
de nouveaux abonnements.
L'argument `visible` signifie que l'offre apparaît dans la liste d... | 77288bfe924733b2e43ea20aa1b1c0e34d2ddb44 | 637,004 |
def sparrow_url_helper(*, build_url, config, **_):
"""
This helper function uses the "build_url" input from flowbyactivity.py,
which is a base url for data imports that requires parts of the url text
string to be replaced with info specific to the data year. This function
does not parse the data, on... | 02aedd2e2755da86f714b5de3ea5ad625831bae2 | 637,005 |
def translated_geometry(assets):
"""Returns the translated geometry assets folder."""
return assets / "translated_geometry" | a2b87ad86ee276b57594afc1db6f3ed217fd7526 | 637,006 |
def sort_array(arr):
"""
Sorts only the odd numbers leaving the even numbers in place
:param: arr Array of numbers
:return sorted numbers with only the odds sorted by value and evens retain their place
:rtype: list
"""
odds = sorted([x for x in arr if x % 2], reverse=True)
return [x if x... | e42fc82132d37c4a8c0d6d37a746537148e63295 | 637,007 |
def _get_divergence_point(trace, dependency_chain):
"""get divergence point between trace and dependency chain"""
for depid, _ in enumerate(dependency_chain):
dependency_node = dependency_chain[depid]
closest = []
dist = float("inf")
for traceid, _ in enumerate(trace):
... | 567a5bbe0801be0985baa4ee4943febb5ba5808a | 637,008 |
import numpy
def from_iter_to_array(iterator, continuous, block_size=1, verbose=0):
"""Extracts the data of an iterator into a single numpy array
continous: indicates whether the data was saved in continous mode or not
if it continuous is True, an element is skipped to avoid repetitions
... | e32fdc4b7bd29a9ef8d3cfb4e4f5f7b099a739c4 | 637,009 |
import tempfile
import sys
def maketemp(*args, **kwargs):
"""Wrapper around default tempfile.mktemp to fix an osx issue"""
tdir = tempfile.mktemp(*args, **kwargs)
if sys.platform == 'darwin':
tdir = '/private' + tdir
return tdir | e1b2e14eaf010649fcdc83d2919d266566699c0b | 637,010 |
def valida_input(msg, respostas_validas, erro):
"""
Cria um laço de repetição "while True" que só é encerrado quando o usuário fornece uma resposta válida.
enquanto isso não acontece, uma mensagem de "erro" é mostrada na tela.
param msg(str): mensagem mostrada ao úsuario no input
param respostas_va... | b6bae9d077a77aa0c74432ea69cbc1de27b0d7b3 | 637,011 |
def _str_to_str(value: str) -> str:
"""Convert ``str`` to ``str``"""
return value | 3237651c783cb7e2223ea2f78cd2a13ff554d7ea | 637,012 |
import re
def replace_str(before_string, pattern, translate_dict):
"""
根据pattern和translate_dict同时替换字符
:return:
"""
after_string = pattern.sub(lambda m: translate_dict[re.escape(m.group(0))], before_string)
return after_string | 785672a0027e5d803afb3515791cb9b5651a3b1b | 637,013 |
import string
def sanitise_string_for_stream_id(unsafe_string):
"""
Removes any unhelpful characters (e.g. #,/,<space>,%) from a string.
We pass:
-Letters ([A-Za-z])
-digits ([0-9]),
-hyphens ("-"),underscores ("_"), colons (":"), and periods (".")
-Plus symbol ('+')
... | 7d70534682259e583bdaacd84f9b94ecebcdbf87 | 637,014 |
import unicodedata
def normalize_string(string):
"""Normalize string for tokenization and matching.
Characters can come in composed or decomposed varieties.
We normalize to decomposed characters in order to allow
fine-grained control of accent patterns. The string is
converted to lowercase.
... | 1159b54d4893dfdd6346c628398eeaad9496f6cb | 637,015 |
def add_if_not_none(a, b):
"""Returns a/b is one of them is None, or their sum if both are not None."""
if a is None:
return b
if b is None:
return a
return a + b | 87b71dce3aefddf1affa716547b836855405d3a4 | 637,016 |
def _database_delete_all_data_function_name(dataset):
"""Returns the name of the function to delete all data from the dataset's database"""
return '{}_database_delete_all_data'.format(dataset.name) | ff06ec21a81ef46070e6cd7be592a465baf95e27 | 637,017 |
def removeLocations(lmA, prefix):
"""Removes locations with a given prefix
Keyword arguments:
lmA -- Location map to delete location from
prefix -- Key or part of key in location map dictionary
Creates a copy of provided location map lmA
Copy contains all key-value pairs from l... | ed83a14db23264cf49df81b44b6ce48a9f300c04 | 637,018 |
def create_list_tuples_span_tag(list_span, tag):
""" takes a list of span and returns a list of tuples of the form
[((start_index, end_index), tag), ..., (start_index, end_index), tag)]"""
list_tuples = [(x, tag) for x in list_span]
return list_tuples | f226ce2fca77b8140b58ce9ac64578b21f0e5c64 | 637,021 |
def outliers_z_score(serie, window, treshold):
"""
Find outliers on a serie based on z-scores.
Parameters
----------
:serie: array_like
Input array or object that can be converted to an array.
:windows: int
:treshold: number of standard deviations to filter
Retu... | 4cd730e3912651916a331a22f2f3366bbb327f33 | 637,022 |
import numpy
def stefcal(r, m, niter=100):
"""
Compute solution to the quadratic matrix equation using the StefCal
algorithm [stefs]_.
Returns a solution, up to a phase factor, to the equation
.. math:: g r g^H = m
where g is a column vector and r, m are Hermitian matrices.
Parameters
... | 6efecaf09025cc8340fe48d57aa77cb56aa41363 | 637,024 |
def check_bw_unit(bw_unit: str) -> str:
"""Check if the bandwidth unit is one of "gbit" and "mbit".
Parameters
----------
bw_unit : str
The bandwidth unit.
Returns
-------
str
The bandwidth unit changing to lowercase letters and removing extra spaces.
Raises
------... | df7fd27887bd2efb3c9ea5c44c55292fe11d91ae | 637,025 |
import re
def to_snake_case(name):
"""Convert the name from camel-style to snake-style."""
intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name)
insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower()
if insecure[0] != '_':
return insecure
return insecure[2:] | a99bb1267465fe392bd5699f3ee28b0bc18afee3 | 637,026 |
def field(name, transform=None):
""" Convenience function to explicitly return a "field" specification for
a Bokeh :class:`~bokeh.core.properties.DataSpec` property.
Args:
name (str) : name of a data source field to reference for a
``DataSpec`` property.
transform (Transform, o... | bc391f991fcebad956464c1f0cc741505d3d4028 | 637,027 |
def regulate_column_names(df, test_type):
"""
Regulate column names for flu_ag test data since Quidel changed their column names multiple times.
We want to finalize the column name list to be:
['SofiaSerNum', 'TestDate', 'Facility',
'Zip', 'FluA', 'FluB', 'StorageDate']
"""
# No reg... | 2439bf64e1efcfefa5bcb93c0f68bfed539cb175 | 637,028 |
def get_one_arg(args, argv):
"""
Hacked together parser to get just one value
:param args: Name of arg to retrieve. If multiple specified, return first found.
:type args: ```Tuple[str]```
:param argv: Argument list
:type argv: ```List[str]```
:return: First matching arg value
:rtype: ... | 428c094ee26090053724a7f0f4d4909da4c3b70d | 637,030 |
def createPatterns(line):
"""
Función que, dada una línea de un archivo de texto con expresiones s, regresa un string
de la forma -> [identificador]: [expresión regular de la librería re de python]
Las expresiones s recibidas deben estar estructuradas con la notación especificada
en el reporte an... | 0250baa40541f622ffd19cc5c8f6c42ca51b3730 | 637,031 |
def orm_coerce_row(row, extra_columns, result_type):
"""Trim off the extra columns."""
# orm_get_page might have added some extra columns to the query in order
# to get the keys for the bookmark. Here, we split the rows back to the
# requested data and the ordering keys.
N = len(row) - len(extra_col... | 1ad90840d9966f1ada31f93fff5c038d4f66ea5d | 637,032 |
def chunk(lines):
"""Return groups of lines separated by whitespace or comments
[(int, str)] -> [[(int, str)]]
"""
chunks = []
chunk = []
for lineno, line in lines:
stripped = line.strip()
if not stripped or stripped[0] == '#':
if chunk:
chunks.append... | c2b372248983e723e7c06d3fa652c9863442df77 | 637,033 |
def _user_lookup(key, users):
"""Given a user id and a list of users, search list for user with
matching id. If found, return user name, else return string 'Not Found'
Args:
key (str): User id to match on
users (list of obj): List of users objects (students)
Return:
(str): U... | 2b02d9b4b3898497f163abefafb23f4afaa17f44 | 637,035 |
def payload():
"""Test payload to reuse."""
return {
'tool': 'pytest',
'version': 'python3',
'opinion': ['redis', 'rocks'],
'none': None,
'empty': []
} | 21ca0f8fd082d80c0542d1b74541aaad8e91e295 | 637,037 |
def post_process_response(token_ids, reader, merge=True):
"""Post-process the decoded sequence.
Truncate from the first <eos> and remove the <bos> and <eos> tokens.
Convert token_ids to words(merge=True) or tokens(merge=False)
Args:
token_ids: Token id sequence.
merge: If true, merge s... | 669ca779442a66a23fb10c053fd1c8c62bd519a6 | 637,038 |
def retreive_details(input_dict,keys_to_extract):
"""
Retreive specific keys from a dictionary object
This function searches through a dictionary, and
retreives keys that match keys from a list. This function
will find matching keys in every level of the dictionary heirarchy.
Inputs:
... | f80c4bac321227a09a9cdf8bac3b1b4e0b16ff5d | 637,039 |
import json
def make_iam_policy(statements):
"""Turn a list of statements into an IAM policy.
"""
return json.dumps({'Version': '2012-10-17', 'Statement': list(statements)}) | b2453e972bc897e433d8ecb8aed3cf417d8e0022 | 637,040 |
import re
def match(reportBody: str, reportWeakness: str) -> bool:
""" Returns whether or not the given report body or report weakness are about an XSS vulnerability """
return (re.findall("xss", reportBody.lower()) != [] or
"xss" in reportBody.lower() or
re.findall("cross[\s\S]site[\s... | fa12945fd14247f09ff219370c8e7bb6d81c02ff | 637,041 |
def _get_bbox_feature(image_size, feature_map, x_min, x_max, y_min, y_max):
"""Get bounding box features.
The feature is the center pixel of a bounding box.
Args:
image_size (tuple): Size of an image in [x, y].
feature_map (numpy.ndarray(numpy.float)): Feature map of size [x, y, n_features... | a5e61183686661015ee6c401b7661ee6c39d7d5e | 637,042 |
def _sane_version_list(version):
"""Ensure the major and minor are int.
Parameters
----------
version : list
Version components
Returns
-------
version : list
List of components where first two components has been sanitised
"""
v0 = str(version[0])
if v0:
... | 5532b9feffa42026abe02cd5087f79de5975e9b6 | 637,043 |
def transpose_table(table):
"""
Transpose any table of values stored as list of lists.
Table must be rectangular.
Returns: Transposed list of lists.
"""
n_table = []
while len(n_table) != len(table[0]):
n_table += [[]]
for col_ind in range(0, len(table[0])):
for row_in... | f6edb065df5b609c482ff85c0126dbd0301ef27f | 637,044 |
import argparse
def parse_arguments(arguments):
""" Parse command line arguments """
# Create an argument parser, and pop the optional arguments section
parser = argparse.ArgumentParser(description="word_embedder - train sets of word embeddings (vector space representations of words)")
optional = par... | c9e059299e7d20eff1e84e67b6efd421fd1f44e2 | 637,045 |
def _matches2str(matches):
"""
Get matches into a multi-line string
:param matches: matches to convert
:return: multi-line string containing matches
"""
output_text = ''
for match in matches:
output_text += f"{match[0]} - {match[1]}\n"
return output_text | 61eef45b59a9143cc6fbdf0701c38cf4135df558 | 637,046 |
def parse_list(value):
"""
Parse a string to extract a simple list of string values.
"""
if value.startswith('[') and value.endswith(']'):
value = value[1:len(value)-1].strip()
elif not value.strip():
return []
return list(value.split(',')) | 933dbb5af1f662bc3d4782d547c70d75ea02d6c1 | 637,047 |
def mk_int(s):
"""Convert to a int, if it can't, return 0"""
s = s.strip().replace(",", "")
return int(s) if s else 0 | 6f7ee17125fa9add84d624f9e3cad610cfc3be0f | 637,048 |
def fit_fullcube(fitter, adr_params, psf_params, store_data=True, get_filename=True,
nb_process=1, **kwargs):
""" """
cubemodel = fitter.evaluate_model_cube(parameters={**adr_params, **psf_params},
nb_process=nb_process, **kwargs)
cubemodel... | 63d55826407fcd0e1bd481303a43cec08e815472 | 637,049 |
def generate_regular_graph_param_test_data():
"""
Generate required R and N combination for test data
:return:
"""
graph_params = []
# Generate even N regular graph
for n in range(4, 18, 2):
# Generate even R degree
for r in range(2, n, 2):
graph_params.append([... | ddd2f939ceb2e32f2e9e876b06945fa4137bd5f0 | 637,050 |
def get_connection():
"""Temporary connection used for local development
:return: (*str*) -- connection string for postgres db
"""
return "dbname=psd host=localhost user=postgres password=example" | 04c7e2c6605a62b01a997667ce741f4a0da61063 | 637,051 |
import os
def work_dir_file(relfile, release_dir, working_dir):
"""Constructs path to working directory for a release file."""
path = os.path.relpath(relfile, release_dir)
dest_file = os.path.join(working_dir, path)
return dest_file | f3acb7894fc8dee6b3686adcab3f3f63613b3f90 | 637,052 |
def solution1(inp):
"""Solves the first part of the challenge"""
rules, _, nearby = inp.strip().split("\n\n")
rules = rules.split("\n")
nearby = nearby.split("\n")[1:]
rrules = []
for rule in rules:
a, b = rule.split(" or ")
r1 = a.strip().split(" ")[-1]
r2 = b.strip()
... | d1f5412c80cf82026f280345a60b0aec9bfd8f94 | 637,053 |
def load_metaparameters(param_dict=None):
"""
Parameters for bayesian optimizer. Default dictionary listed and updated by param_dict.
The default contains some redundancy dependent on the architecture.
If the generic architecture is used, the 'dense_X' values are ignored.
If not, the values of 'den... | 684d2cf181e5f51a1bbc476ff684a75859b8542f | 637,054 |
def _apply_filters(filters, fn):
"""
Parameters
----------
filters: a filter bank
fn: a function to apply on the parameters
Returns
-------
filters: the filters modified
"""
for k in range(len(filters)):
filters[k] = fn(filters[k])
return ... | e29e9f767914b7b915d49d99e429981f1ada2748 | 637,055 |
def bytes_to_int(d):
"""Convert a list of bytes to an int
Bytes are in LSB first.
>>> hex(bytes_to_int([0, 1]))
'0x100'
>>> hex(bytes_to_int([1, 2]))
'0x201'
"""
v = 0
for i,d in enumerate(d):
v |= d << (i*8)
return v | feeb6a4bfaf248f68ca5aacaafc73134dcf57dd3 | 637,056 |
import os
import sys
import subprocess
def main():
"""
Change to doc directory and call mkdocs
Args:
None
Returns:
int: exit code
Raises:
None
"""
# determine the repository root dir
root_dir = os.path.abspath(
'{}/..'.format(os.path.dirname(os.path.a... | 5ddf7f6d56fbeab6de9ddf8ecb5b254f6a2eaad0 | 637,057 |
import pkg_resources
def _check_presence(dependencies):
"""Check if all dependencies are present. Return missing dependencies."""
missing = []
for dependency in dependencies:
requirement = dependency.name + dependency.constraint
try:
pkg_resources.require(requirement)
e... | 75d98b914829fd6acd44a84db9b27b88a0b07c83 | 637,058 |
import secrets
def spoiler(help_text: str, button_text="🕵️ Show Hint") -> str:
"""
HTML boilerplate for spoiler element in challenge descriptions.
"""
div_id = secrets.token_hex(5)
return f"""
<div>
<div id="{div_id}-help" class="d-none">
<hr/>
... | d93a93c7c19b33007b999430eff603b9033275b4 | 637,059 |
def arrays_as_dataset(states, actions, rewards, next_states, absorbings, lasts):
"""
Creates a dataset of transitions from the provided arrays.
Args:
states (np.ndarray): array of states;
actions (np.ndarray): array of actions;
rewards (np.ndarray): array of rewards;
next_st... | ac6a5cc1d63c6508e8e181f86aae6d7d46d6d513 | 637,061 |
def is_utf8_encoded(bstring):
"""
Return ``True`` if the given byte string can be decoded
into a Unicode string using the UTF-8 decoder.
:param bytes bstring: the string to test
:rtype: bool
"""
try:
bstring.decode("utf-8")
return True
except UnicodeDecodeError:
... | 845f79d725b95adc8ba75feabda2c9e68214aa98 | 637,062 |
def find_val_or_next_smaller_iter(bst, x, d=None):
"""Get the greatest value <= x in a binary search tree.
Returns None if no such value can be found.
"""
while True:
if bst is None:
return d
elif bst.val == x:
return x
elif bst.val > x:
(bst, ... | 16b018345f4be498c644868a4661eee7e7a8b499 | 637,063 |
import logging
def set_logger_verbose(verbose: bool):
"""
Set up logging verbose at runtime. The implementation is contingent on
static LOGGING setting in "stave_config.py". This can only be called after
the server starts.
"""
root_logger = logging.getLogger()
root_handlers = root_logger.... | 6878684d95583b7516ea04e159fa412108ba5fe3 | 637,064 |
def _validate_name(name):
"""
Validates the given name.
Parameters
----------
name : `None` or `str`
A command's respective name.
Returns
-------
name : `None` or `str`
The validated name.
Raises
------
TypeError
If `name` is not given a... | e629f0bbc82d421441344a958554df1082b7fdae | 637,065 |
import re
def cleanup(s: str, remove_non_alphabet: bool = True) -> str:
"""Remove all *bad* characters in text"""
if remove_non_alphabet:
s = re.sub("\W", "", s)
s = re.sub("[\n\t]+", " ", s)
s = re.sub("\s+", " ", s)
return s | 4e7f5f189469ab6cf0d5ed5a96951409dfcea1e2 | 637,066 |
def groupbyTime(images, function, time):
"""
function to group images by their acquisition time difference
:param images: a list of image names
:param function: a function to derive the time from the image names
:param time: a time difference in seconds by which to group the images
:return: a l... | 44e048b405bae765ca00fe3bbbdf4e38d8eb3801 | 637,067 |
def get_accuracy(Y, Y_pred):
"""
Calcualtes accuracy.
:param Y: int(N, )
Correct labels.
:param Y_pred: int(N, ) | double(N, C)
Predicted labels of shape(N, ) or (N, C) in case of one-hot vector.
:return: double
Accuracy.
"""
return (Y == Y_pred).mean()
# return ... | c3c16a8e4a96dd8eb80f249377d2cfa3f0b01e98 | 637,068 |
import uuid
def generate_id():
"""
Generate short id for games.
https://stackoverflow.com/questions/13484726/safe-enough-8-character-short-unique-random-string
"""
return str(uuid.uuid4())[:8] | 63a308d8a1a1f2743c102cab7267681c2e424c21 | 637,069 |
def fib(n):
"""
Compute the n'th Fibonacci number.
:param n: target Fibonacci number
:return: the appropriate number
"""
if n <=2:
return 1
else:
return fib(n-1) + fib(n-2) | 02c86ec003868c61f6198edf7647973d936654c2 | 637,070 |
def get_all_playable_cardnames(r):
"""Gets all cards that can be played now"""
return [str(r.progress[suit] + 1) + suit for suit in r.suits if r.progress[suit] < 5] | 7f0ecd59cb04e9fef162700dd74f570fbeb949a3 | 637,071 |
def python_link_doc(m, o=None, format="rst"):
"""
Returns a url about :epkg:`Python` documentation.
.. runpython::
:showcode:
from pyquickhelper.sphinxext import python_link_doc
print(python_link_doc("io"))
@param m Python module
@param o func... | 2c9444b7a307f03a0dc192d4842c0f414b59f0bc | 637,072 |
import subprocess
def start_rabbitmq_consumer():
"""
Start rabbitmq-consumer systemd service.
:return:
"""
try:
subprocess.check_call("sudo service rabbitmq-consumer start".split())
return True
except subprocess.CalledProcessError:
return False | 2c4a856b64cf10d06823b37a2ab5cddd27a72eca | 637,073 |
def parse_results(results):
""" parses the results file into a dictionary of names and tuples """
# hold the results in a dictionary
results_dict = {}
# loop over each line (result)
for result in results:
# split the string based on spaces
parts = result.split()
# there shoul... | 6ed1868697c043a603470d41bb3e62a6946ea342 | 637,074 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.