content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def home():
"""Return the home page."""
response = flask.render_template(
'index.html',
metrics=SUPPORTED_METRICS.keys())
return response, 200 | 36,900 |
def data_to_segments_uniform(x, n_segments, segment_ranges=True):
""" Split data into segments of equal size (number of observations)."""
return split_equal_bins(x, n_segments) | 36,901 |
def create_waf_sensor(data, name, comment):
"""Create waf sensor."""
data.id_or_name = name
data.comment = comment | 36,902 |
def load_all_sheets(file_name):
"""
Load from a xls(x) file all its sheets to a pandas.DataFrame as values to sheet_names as keys in a dictionary
Parameters
----------
file_name : str, Path
file_name to load from
Returns
-------
dict
dictionary containing the sheet_names... | 36,903 |
def rate_limit(limit=1000, interval=60):
"""Rate limit for API endpoints.
If the user has exceeded the limit, then return the response 429.
"""
def rate_limit_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
key: str = f"Limit::{request.remote_addr}:{datetime.date... | 36,904 |
def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def auth_filter(filteredapp):
return AuthProtocol(filteredapp, conf)
return auth_filter | 36,905 |
def parse(stylesheet):
"""Parse a stylesheet using tinycss2 and return a StyleSheet instance.
:param stylesheet: A string of an existing stylesheet.
"""
parsed_stylesheet = tinycss2.parse_stylesheet(
stylesheet, skip_comments=True, skip_whitespace=True
)
css = qstylizer.style.StyleShee... | 36,906 |
def test_suite():
"""Returns a test suite of all the tests in this module."""
test_classes = [TestNetCDFPointUtilsConstructor,
TestNetCDFPointUtilsFunctions1,
TestNetCDFPointUtilsGridFunctions
]
suite_list = map(unittest.defaultTestLoader.loadTes... | 36,907 |
def compute_max_cut(n: int, nodes: List[int]) -> int:
"""Compute (inefficiently) the max cut, exhaustively."""
max_cut = -1000
for bits in helper.bitprod(n):
# Collect in/out sets.
iset = []
oset = []
for idx, val in enumerate(bits):
iset.append(idx) if val == 0 ... | 36,908 |
def get_capacity_potential_from_enspreso(tech: str) -> pd.Series:
"""
Return capacity potential (in GW) per NUTS2 region for a given technology, based on the ENSPRESO dataset.
Parameters
----------
tech : str
Technology name among 'wind_onshore', 'wind_offshore', 'wind_floating', 'pv_utilit... | 36,909 |
def use_nearby_search(url, next_page=False, request_count=0):
"""Call nearby search API request.
Parameters
----------
url: str
URL to use to send a Nearby Search Request in Google Maps Place Search API
next_page: boolean, optional(default=False)
whether or not the URL is to request... | 36,910 |
def _GetGoogleAuthtoken(account_type, user, password, service, source):
"""This function authenticates the user in the specified service using
the provided authentication data.
Args:
account_type: Type of the account to login, could be GOOGLE or any other
string if the account is external.
user: ... | 36,911 |
def trim_filters(response):
"""Trim the leading and trailing zeros from a 1-D array or sequence, leaving
one zero on each side. This is a modified version of numpy.trim_zeros.
Parameters
----------
response : 1-D array or sequence
Input array.
Returns
-------
first : int
... | 36,912 |
def main():
"""
Does the database exist? Create if not, then
continue the script by calling check_booking()
"""
if os.path.isfile(database):
pass
else:
create_db()
conn = connect_db(database)
logger.info('Beginning run...')
with conn:
is_bookable(conn)
... | 36,913 |
def print_metrics(met_dict):
"""
Given a metrics dictionary, print the values for:
- Loss
- Accuracy
- Precision
- Recall
- F1
"""
print("Loss: {:.3f}".format(met_dict['Loss']))
print("Accuracy: {:.3f} %".format(met_dict['Accuracy'] * 100))
print("Precisi... | 36,914 |
def is_spanning(graph, subgraph):
"""
Return True or False by passing graph and subgraph through function V
to check if the subgraph uses all verticies of the original graph
Parameters
----------
graph = A networkx graph.
subgraph = A networkx subgraph of 'graph'.
... | 36,915 |
def get_commit_msg() -> str:
"""
Return the last commit message.
"""
result = subprocess.run(
'git show -s --format=%s'.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
if result.stderr: # no commit yet
return '\n'
return ... | 36,916 |
def get_class_membership(alpaca, class_id, membership):
"""Given a class ID, return a set of IDs of all classes of which that
class is a member.
"""
class_ast = find_class_defn(alpaca, class_id)
get_membership(alpaca, class_ast.classes, membership) | 36,917 |
def relative_paths(root: Path, paths: list) -> List[str]:
"""
Normalises paths from incoming configuration and ensures
they are all strings relative to root
"""
result = []
for path in paths:
# more hacks for exclusions I'm not happy about
# maybe we should subclass Path to make ... | 36,918 |
def domain_loss_roi(pred, domain_label):
"""
ROI-level domain adversarial loss
"""
if DEBUG:
print('\tDA-ROI loss')
device_id = pred.get_device()
target_label = Variable(
torch.FloatTensor(pred.data.size()).fill_(float(domain_label))
).cuda(de... | 36,919 |
def qm9():
"""configuration for the QM9 dataset"""
dbpath = './data/qm9.db'
dataset = 'QM9'
property_mapping = {Properties.energy: QM9.U0,
Properties.dipole_moment: QM9.mu,
Properties.iso_polarizability: QM9.alpha} | 36,920 |
def clean_text(text):
"""
A function to pre-process text
Parameters
----------
text : string
the string to be processed
Returns
-------
text : string
a clean string
"""
tok = WordPunctTokenizer()
pat1 = r'@[A-Za-z0-9]+'
pat2 = r'https?://[A-Za-z0-9./]+'
... | 36,921 |
def train_one_epoch(dataloader, model, optimizer, device, writer, epoch, cfg):
""" Trains the model for one epoch. """
model.train()
optimizer.zero_grad()
metrics = []
n_batches = len(dataloader)
progress = tqdm(dataloader, desc='TRAIN', leave=False)
for i, sample in enumerate(progress):
... | 36,922 |
def test_alias_function():
"""Test 4: Generate markup based on an element using an (alias w/function) parameter to explicitly correlate data and elements"""
template = get_template('contacts-alias')
def alias_name(p, e, k, v):
eq_(k, 'name')
return 'foo'
weld(template('.contact')[0], d... | 36,923 |
def baseurl(request):
"""
Return a BASE_URL template context for the current request.
"""
if request.is_secure():
scheme = 'https://'
else:
scheme = 'http://'
return {'BASE_URL': scheme + request.get_host(), } | 36,924 |
def geolocate(address, bounds=None, country=None, administrative_area=None, sensor=False):
"""
Resolves address using Google Maps API, and performs some massaging to the output result.
Provided for convenience, as Uber relies on this heavily, and the desire to give a simple 'batteries included' experience.
... | 36,925 |
def _cmdy_hook_class(cls):
"""Put hooks into the original class for extending"""
# store the functions with the same name
# that defined by different plugins
# Note that current (most recently added) is not in the stack
cls._plugin_stacks = {}
def _original(self, fname):
"""Get the orig... | 36,926 |
def pair_verify(
credentials: HapCredentials, connection: HttpConnection
) -> PairVerifyProcedure:
"""Return procedure object used for Pair-Verify."""
_LOGGER.debug(
"Setting up new AirPlay Pair-Verify procedure with type %s", credentials.type
)
if credentials.type == AuthenticationType.Nul... | 36,927 |
def get_file_type_and_ext(filename):
"""
Return file type and extension if the file can be previewd online,
otherwise, return unknown type.
"""
fileExt = os.path.splitext(filename)[1][1:].lower()
if fileExt in get_conf_text_ext():
return (TEXT, fileExt)
filetype = FILEEXT_TYPE_MAP.g... | 36,928 |
def load_data(
datapath=None,
minstorms=3,
minbmps=3,
combine_nox=True,
combine_WB_RP=True,
remove_grabs=True,
grab_ok_bmps="default",
balanced_only=True,
fix_PFCs=True,
excluded_bmps=None,
excluded_params=None,
as_dataframe=False,
**dc_kwargs
):
""... | 36,929 |
def sign(request):
"""
Returns a signed URL (for file upload) and an OTP
"""
credentials, project_id = auth.default()
if credentials.token is None:
# Perform a refresh request to populate the access token of the
# current credentials.
credentials.refresh(requests.Requ... | 36,930 |
def _parse_squeue_state(squeue_out, job_id):
"""Parse "state" column from squeue output for given job_id
Returns state for the *first* job matching job_id. Returns 'u' if
`squeue` output is empty or job_id is not found.
"""
invalid_job_str = "Invalid job id specified"
if invalid_job_str in sq... | 36,931 |
def test_parse_url_opaque_path_state(caplog):
"""Validation error in opaque path state."""
caplog.set_level(logging.INFO)
urlstring = "sc:\\../%GH"
base = "about:blank"
_ = parse_url(urlstring, base)
assert len(caplog.record_tuples) > 0
assert caplog.record_tuples[-1][0].startswith(_MODULE_... | 36,932 |
def parser_IBP_Descriptor(data,i,length,end):
"""\
parser_IBP_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "IBP", "contents" : unparsed_descriptor_contents }
(Defined in ISO 13818-1 specif... | 36,933 |
def test_next_turn():
"""Test a boards `next_turn` function.
Check if the functions's behavoir is correct.
To do so initialize an instance of the Board class
and assert the functions output with different setups.
"""
board = Board()
assert_obj_attr(board, "player", "white")
assert_obj_... | 36,934 |
def build_county_list(state):
"""
Build the and return the fips list
"""
state_obj = us.states.lookup(state)
logging.info(f"Get fips list for state {state_obj.name}")
df_whitelist = load_data.load_whitelist()
df_whitelist = df_whitelist[df_whitelist["inference_ok"] == True]
all_fips = d... | 36,935 |
def vw_train(data_file,
l2=None,
l1=None,
keep=None,
ignore=None,
quadratic=None,
passes=None,
model_file=None,
learn_rate=0.1,
holdout=False,
other=None):
"""
Function programmatica... | 36,936 |
def num_materials_per_bin(config_path, database_path, generation=None, output_path="-"):
"""outputs materials per bin for cover visualization script in blender"""
config = load_config_file(config_path)
prop1range = config['prop1range']
prop2range = config['prop2range']
num_bins = config['number_of_... | 36,937 |
def is_comment(obj):
"""Is comment."""
import bs4
return isinstance(obj, bs4.Comment) | 36,938 |
def insert_user(username: str) -> Tuple[int, str]:
"""
Inserts a new user. If the desired username is already taken,
appends integers incrementally until an open name is found.
:param username: The desired username for the new user.
:return A tuple containing the id and name of the new user.
... | 36,939 |
def test_tanium_simulate_bad_input_file(tmp_path):
"""Test simulate with bad input file call."""
config = configparser.ConfigParser()
config_path = pathlib.Path('tests/data/tasks/tanium/demo-tanium-to-oscal.config')
config.read(config_path)
config.remove_option('task.tanium-to-oscal', 'input-dir')
... | 36,940 |
def gather(tensor, tensor_list=None, root=0, group=None):
"""
Sends tensor to root process, which store it in tensor_list.
"""
rank = distributed.get_rank()
if group is None:
group = distributed.group.WORLD
if rank == root:
assert(tensor_list is not None)
distribut... | 36,941 |
def main():
"""Lists as piles
"""
# Create a stack
my_stack = [1, 2, 3, 4]
print("my_stack", my_stack)
# Push values on the stack
my_stack.append(5)
my_stack.append(6)
my_stack.append(7)
print("my_stack", my_stack)
# Pop values from the stack
print("Poped value", my_st... | 36,942 |
def get_gateway(ctx, name):
"""Get the sdk's gateway resource.
It will restore sessions if expired. It will read the client and vdc
from context and make get_gateway call to VDC for gateway object.
"""
restore_session(ctx, vdc_required=True)
client = ctx.obj['client']
vdc_href = ctx.obj['pr... | 36,943 |
def fn_getdatetime(fn):
"""Extract datetime from input filename
"""
dt_list = fn_getdatetime_list(fn)
if dt_list:
return dt_list[0]
else:
return None | 36,944 |
def ai_check_mate(board, checkmate_moves, enemy_color, computer_turn):
"""in the case that ai does not have any move that gives it material advantage, it attempts to check mate by
choosing moves that leave the enemy king with as few possible moves as possible
:param board: the logical board
:param compu... | 36,945 |
def test_monitoring_after_ocp_upgrade(pre_upgrade_monitoring_pvc):
"""
After ocp upgrade validate all monitoring pods are up and running,
its health is OK and also confirm no new monitoring
pvc created instead using previous one.
"""
pod_obj_list = pod.get_all_pods(namespace=defaults.OCS_MONITO... | 36,946 |
def greenplum_kill_process(process_id):
"""
:param process_id: int
:return: None
"""
query = """
select pg_cancel_backend({0});
select pg_terminate_backend({0});
""".format(process_id)
return greenplum_read(query) | 36,947 |
def test_signature():
"""check svs_search"""
tp = product.TextProduct(get_test_file("TOR.txt"))
assert tp.get_signature() == "CBD" | 36,948 |
async def rauch_lancet_de_novos(result, limiter):
""" get de novo data for Rauch et al. intellectual disability exome study
De novo mutation data sourced from supplementary tables 2 and 3 from
Rauch et al. (2012) Lancet 380:1674-1682
doi: 10.1016/S0140-6736(12)61480-9
Returns:
d... | 36,949 |
def check_app_auth(headers):
"""Authenticate an application from Authorization HTTP header"""
import base64
try:
auth_header = headers["Authorization"]
except KeyError:
return False
# Only handle HTTP Basic authentication
m = re.match("Basic (\w+==)", auth_header)
if not m:... | 36,950 |
def print_title(title_text):
"""Print inputted text between a series of dashes to mark important text.
Used for outputting information to the user while the program is scraping data
Keyword argument:
title_text -- the text to be printed in a title format
"""
print "\n------------... | 36,951 |
def setupConnection():
"""
Create connection to database, to be shared by table classes. The file
will be created if it does not exist.
"""
dbPath = conf.get('db', 'path')
conn = builder()(dbPath)
return conn | 36,952 |
def max_pool(ip):
"""does a 2x2 max pool, crops off ends if not divisible by 2
ip is DxHxW
op is DxH/2xW/2
"""
height = ip.shape[1] - ip.shape[1]%2
width = ip.shape[2] - ip.shape[2]%2
h_max = np.maximum(ip[:,:height:2,:], ip[:,1:height:2,:])
op = np.maximum(h_max[:,:,:width:2], h_max[:,... | 36,953 |
def test_wrong_cli_type(runner: Runner) -> None:
"""Loading command with a cli attribute that is not a click command raises an error"""
result = runner.invoke(['wrong_cli_type'])
assert isinstance(result.exception, AssertionError)
assert str(result.exception) == (
'Expected command module attrib... | 36,954 |
def register(linter):
"""Register the reporter classes with the linter."""
linter.register_reporter(JSONReporter) | 36,955 |
def get_bin_vals(global_config):
"""
Creates bin values for grasping widths according to bounds defined in config
Arguments:
global_config {dict} -- config
Returns:
tf.constant -- bin value tensor
"""
bins_bounds = np.array(global_config['DATA']['labels']['offset_bins'])
if... | 36,956 |
def dphi_dop(t, profile, r0_vec, v_vec, d_hat, use_form=False, form_fun=None,
interp_table=None):
"""
Returns the phase shift due to the Doppler delay for subhalos of mass, mass
TODO: add use_closest option
"""
v_mag = np.linalg.norm(v_vec, axis=1)
r0_v = np.einsum("ij, ij -> i... | 36,957 |
def calculate_Hubble_flow_velocity_from_cMpc(cMpc, cosmology="Planck15"):
"""
Calculates the Hubble flow recession velocity from comoving distance
Parameters
----------
cMpc : array-like, shape (N, )
The distance in units of comoving megaparsecs. Must be 1D or scalar.
cosmology : strin... | 36,958 |
def CollapseDictionary(mapping):
"""
Takes a dictionary mapping prefixes to URIs
and removes prefix mappings that begin with _ and
there is already a map to their value
>>> from rdflib import URIRef
>>> a = {'ex': URIRef('http://example.com/')}
>>> a['_1'] = a['ex']
>>> len(a)
2
... | 36,959 |
def do_pre_context(PreContextSmToBeReversedList, PreContextSmIdList, dial_db):
"""Pre-context detecting state machine (backward).
---------------------------------------------------------------------------
Micro actions are: pre-context fullfilled_f
DropOut --> Begin of 'main' state machine... | 36,960 |
async def check_user_cooldown(ctx: Context, config: Config, cooldown: dict):
"""Check if command is on cooldown."""
command = ctx.command.qualified_name
last = cooldown[command]["last"]
rate = cooldown[command]["rate"]
per = cooldown[command]["per"]
uses = cooldown[command]["uses"]
now = ... | 36,961 |
def apply_keymaps(window):
"""
Given a window, check it to see if it it contains a project, and if so
activate any key bindings present in it.
This will remove the key bindings for a project that used to have them
if it no longer does, which could happen if the project is changed by
some extern... | 36,962 |
def round_robin(units, sets=None):
""" Generates a schedule of "fair" pairings from a list of units """
if len(units) % 2:
units.append(None)
count = len(units)
sets = sets or (count - 1)
half = count / 2
schedule = []
for turn in range(sets):
pairings = []
... | 36,963 |
def test_pipeline_load(testbed: SparkETLTests):
"""Test pipeline.load method using the mocked spark session and introspect the calling pattern\
to make sure spark methods were called with intended arguments
.. seealso:: :class:`SparkETLTests`
"""
# calling the extract method with mocked spark and t... | 36,964 |
def filter_df(p_df:pd.DataFrame, col_name:str, value, keep:bool=True, period=None):
"""
Filter a dataframe based on a specific date
Parameters :
p_df : pandas.DataFrame
The original dataframe
col_name : str
The dataframe column name where the ... | 36,965 |
def _VerifyOptions(options):
"""Verify the passed-in options.
Args:
options: The parsed options to verify.
Returns:
Boolean, True if verification passes, False otherwise.
"""
if options.endpoints_service and not options.openapi_template:
logging.error('Please specify openAPI template with --open... | 36,966 |
def program_cancel(app, view:View, context):
"""Exit the program"""
app.msg_info("exit")
sys.exit(0) | 36,967 |
def force_delegate(func: _F) -> _F:
"""
A decorator to allow delegation for the specified method even if cls.delegate = False
"""
func._force_delegate = True # type: ignore[attr-defined]
return func | 36,968 |
def add_dataframe_to_bq_as_str_values(frame, dataset, table_name,
column_types=None, col_modes=None,
project=None, overwrite=True):
"""Adds (either overwrites or appends) the provided DataFrame to the table
specified by `dataset.tabl... | 36,969 |
def create_signature(key_dict, data):
"""
<Purpose>
Return a signature dictionary of the form:
{'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...',
'sig': '...'}.
The signing process will use the private key in
key_dict['keyval']['private'] and 'data' to generate the signature.
The fol... | 36,970 |
def test_laplacian(deriv_1d_data):
"""Test laplacian with simple 1D data."""
laplac = laplacian(deriv_1d_data.values, coordinates=(deriv_1d_data.x,))
# Worked by hand
truth = np.ones_like(deriv_1d_data.values) * 0.2133333 * units('delta_degC/cm**2')
assert_array_almost_equal(laplac, truth, 5) | 36,971 |
def parse_line(line):
""" Parse a queue trace line into a dict
"""
line = line.split()
result = {}
if len(line) < 12:
return result
result["event"] = line[0]
result["time"] = float(line[1])
result["from"] = int(line[2])
result["to"] = int(line[3])
result["type"] = line[4]... | 36,972 |
def gaussian_linear_combination(distributions_and_weights: Dict):
""" Computes the PDF of the weighted average of two Gaussian variables. """
assert isinstance(distributions_and_weights, dict)
assert all(
isinstance(dist, MultivariateNormal)
for dist in distributions_and_weights.keys()
)... | 36,973 |
def open():
"""Open the HTML documentation in a browser"""
index_path = cwd/'_build/html/index.html'
webbrowser.open(index_path.absolute().as_uri()) | 36,974 |
def check_pattern_startswith_slash(pattern):
"""
Check that the pattern does not begin with a forward slash.
"""
regex_pattern = pattern.regex.pattern
if regex_pattern.startswith('/') or regex_pattern.startswith('^/'):
warning = Warning(
"Your URL pattern {} has a regex beginning... | 36,975 |
def attack_images(cores, prob_cutoff):
"""
:param cores: how many cores to use for multiprocessing
:param prob_cutoff: user's image belongs to a certain category if the output of the last FC layer of the resnet model for the category > prob_cutoff
:return:
"""
mediaFile = "target_media"
... | 36,976 |
def ht(x):
"""ht(x)
Evaluates the heaviside function
Args:
x: Domain points
Returns:
ht(x): Heaviside function evaluated over the domain x
"""
g = np.ones_like(x)
for i in range(np.size(x)-1):
if x[i] < 0:
g[i] = 0
elif x[i] > 0:
g[i] =... | 36,977 |
def Scan(client, table, callback):
"""Scans an entire table.
"""
found_entries = {}
for prefix in options.options.hash_key_prefixes:
found_entries[prefix] = 0
deleted = 0
last_key = None
count = 0
while True:
result = yield gen.Task(client.Scan, table.name, attributes=None, limit=50, excl_start_... | 36,978 |
def xoGkuXokhXpZ():
"""Package link to class."""
pkg = Package("pkg")
return pkg.circles.simple_class.Foo | 36,979 |
def create_all_pts_within_observation_window(observation_window_hours) -> str:
"""
create a view of all patients within observation window
return the view name
"""
view_name = f"default.all_pts_{observation_window_hours}_hours"
query = f"""
CREATE OR REPLACE VIEW {view_name} AS
... | 36,980 |
def get_signature(data, raw_labels):
"""
Should return a 4 x z* matrix, where z* is the number of classes in the
labels matrix.
"""
labels = raw_labels.reset_index()
pca = decomposition.PCA(n_components=2)
lle = manifold.LocallyLinearEmbedding(n_components=2)
X_pca = pd.DataFr... | 36,981 |
def get_xyz_where(Z, Cond):
"""
Z and Cond are MxN matrices. Z are data and Cond is a boolean
matrix where some condition is satisfied. Return value is x,y,z
where x and y are the indices into Z and z are the values of Z at
those indices. x,y,z are 1D arrays
"""
X,Y = np.indices(Z.shape)
... | 36,982 |
def retrieve_seq_length(data):
"""compute the length of a sequence. 0 are masked.
Args:
data: input sequence
Returns:
a `int`, length of the sequence
"""
with tf.name_scope('GetLength'):
used = tf.sign(tf.reduce_max(tf.abs(data), axis=2))
length = tf.reduce_sum(used, axis=1)
length = ... | 36,983 |
def get_census_params(variable_ids, county_level=False):
"""Gets census url params to make an API call.
variable_ids: The ids of the variables to request. Automatically includes
NAME.
county_level: Whether to request at the county level, or the state level."""
keys = variable_ids.copy()
key... | 36,984 |
def lookupName(n, names):
"""Check if name is in list of names
Parameters
----------
n : str
Name to check
names : list
List of names to check in
Returns
-------
bool
Flag denoting if name has been found in list (True) or not (False)
"""
if n in names:... | 36,985 |
def calculate_appointments(new_set, old_set):
"""
Calculate different appointment types.
Used for making useful distinctions in the email message.
new_set will be the fresh set of all available appointments at a given interval
old_set will the previous appointments variable getting passed i... | 36,986 |
def SystemPropertiesDir(dirname = 'system-properties'):
"""
SystemProperty
Creates configuration for a system-properties dir.
"""
print data.system_properties_dir.format(domain={'system-properties-dir': dirname}) | 36,987 |
def clean():
"""Deletes generated JavaScript files, the build folder and clears all caches."""
session.clean()
profile = Profile.Profile(session)
fm = profile.getFileManager()
fm.removeDir("build")
fm.removeDir("source/script") | 36,988 |
def log(func: Callable[..., RT]) -> Callable[..., RT]:
"""logs entering and exiting functions for debugging."""
logger = logging.getLogger(func.__module__)
@wraps(func)
def wrapper(*args, **kwargs) -> RT:
logger.debug("Entering: %s", func.__name__)
result = func(*args, **kwargs)
... | 36,989 |
def chunks(l, n):
""" Yield successive `n`-sized chunks from list `l`. """
for i in range(0, len(l), n):
yield l[i : i + n] | 36,990 |
def transaksi_hari_ini():
"""
used in: app_kasir/statistik.html
"""
return Transaksi.objects.filter(
tanggal_transaksi__year=timezone.now().year,
tanggal_transaksi__month=timezone.now().month,
tanggal_transaksi__day=timezone.now().day
).count() | 36,991 |
def save_files(assembly_dict: Dict[str, bytes], output_dir: str):
"""
Saves the assemblies on assembly_dict to output_dir
:param assembly_dict: a dictionary that maps an assembly name to its contents
:param output_dir: output directory
:return: None
"""
os.makedirs(output_dir, exist_ok=True)... | 36,992 |
def extractWindows(signal, window_size=10, return_window_indices=False):
""" Reshape a signal into a series of non-overlapping windows.
Parameters
----------
signal : numpy array, shape (num_samples,)
window_size : int, optional
return_window_indices : bool, optional
Returns
-------
... | 36,993 |
def add(left: int, right: int):
"""
add up two numbers.
"""
print(left + right)
return 0 | 36,994 |
def parse_args():
"""
Parse command-line arguments
"""
parser = argparse.ArgumentParser(description='Move retrieval to a '
'different directory.')
parser.add_argument('retrieval_id', help='the id of the retrieval '
'to move', type=int)
par... | 36,995 |
def rand_x_digit_num(x):
"""Return an X digit number, leading_zeroes returns a string, otherwise int."""
return '{0:0{x}d}'.format(random.randint(0, 10**x-1), x=x) | 36,996 |
def gen_workflow_steps(step_list):
"""Generates a table of steps for a workflow
Assumes step_list is a list of dictionaries with 'task_id' and 'state'
"""
steps = format_utils.table_factory(field_names=['Steps', 'State'])
if step_list:
for step in step_list:
steps.add_row([step.... | 36,997 |
def commonprefix(items):
"""Get common prefix for completions
Return the longest common prefix of a list of strings, but with special
treatment of escape characters that might precede commands in IPython,
such as %magic functions. Used in tab completion.
For a more general function, see os.path.co... | 36,998 |
def sround(x: Union[np.ndarray, float, list, tuple], digits: int=1) -> Any:
""" 'smart' round to largest `digits` + 1
Args
x (float, list, tuple, ndarray)
digits (int [1]) number of digits beyond highest
Examples
>>> sround(0.0212343, 2) # result 0.0212
"""
if isinstance(... | 36,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.