content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def moeda(n=0):
"""
-> Formata um número como moeda
:param n: número
:return: número formatado
"""
return f'R$ {n:.2f}' | 3727a2257afe8746d6ef2b3c8ee088842c46c5ce | 3,627,800 |
from PIL import Image
import aggdraw
def _draw_subpath(subpath_list, width, height, brush, pen):
"""
Rasterize Bezier curves.
TODO: Replace aggdraw implementation with skimage.draw.
"""
mask = Image.new('L', (width, height), 0)
draw = aggdraw.Draw(mask)
pen = aggdraw.Pen(**pen) if pen els... | dc8762c537fc316e23ac920232da2726bc124068 | 3,627,801 |
def parse_devices(metadata, parser):
"""
Iterate device ``metadata`` to use ``parser`` to create and return a
list of network device objects.
:param metadata:
A collection of key/value pairs (Generally returned from
`~trigger.rancid.parse_rancid_file`)
:param parser:
A call... | de45f8d7564d13ddf56257407c857a473ed869a1 | 3,627,802 |
def preprocess_chunk(raw_chunk, subtract_mean=True, convert_to_milivolt=False):
"""
Preprocesses a chunk of data.
Parameters
----------
raw_chunk : array_like
Chunk of raw_data to preprocess
subtract_mean : bool, optional
Subtract mean over all other channels, by default True
... | 333eabb21efb40bef8e2eecbe7d93381d067df26 | 3,627,803 |
def generate_presigned_url(s3_client, client_method, method_parameters, expires_in):
"""
Generating a presigned Amazon S3 URL that can be used to perform an action.
"""
try:
url = s3_client.generate_presigned_url(
ClientMethod=client_method,
Params=method_parameters,
... | b19ff1019efacb4af5b11b7c46c6b7483346f169 | 3,627,804 |
def update_topic(zkurl, topic, partitions, replica=None, kafka_env=None):
"""Alter a topic in Kafka instances from zkurl list"""
return _exec_topic_cmd(TOPIC_CLASS, 'alter', zkurl, topic,
partitions, replica=replica, kafka_env=kafka_env) | 8dd270dff30f6e66c67d0cfa52c199b8176c352a | 3,627,805 |
def get_list_peaks(matrix, image_size):
"""Return a list of class Peak form H5
gets a matrix with data for all peas given
file h5
Returns
-------
peaks : list
List of class Peak object.
"""
try:
# array[:,] next rows
peaks = [Peak(posx=(row[0] + image_size[1]/2.0... | 7f9bd83fea592a6e55016011e5f67e90966591c6 | 3,627,806 |
from datetime import datetime
async def add_report_history(
id: int,
search_id: str,
search_start: datetime,
search_end: datetime,
search_type: str,
session: str):
"""Add report history
Adds reports to the history.
Args:
id: the user_id
... | aea938dbc26ac973c9d61371dfed8da6c223fb92 | 3,627,807 |
def get_latest_featuregroup_version(featuregroup, featurestore=None):
"""
Utility method to get the latest version of a particular featuregroup
Example usage:
>>> featurestore.get_latest_featuregroup_version("teams_features_spanish")
Args:
:featuregroup: the featuregroup to get the latest... | d670c8e8ec2ba08e5e5248f613702a46445592bd | 3,627,808 |
def guardian(badger: BadgerSystem, startBlock, endBlock, pastRewards, test=False):
"""
Guardian Role
- Check if there is a new proposed root
- If there is, run the rewards script at the same block height to verify the results
- If there is a discrepency, notify admin
(In case of a one-off failur... | 00100d17b64cbfbd9ff309374c20bc8ff39be803 | 3,627,809 |
def cutMapById(data, subcatchmap, id, x, y, FillVal):
"""
:param data: 2d numpy array to cut
:param subcatchmap: 2d numpy array with subcatch
:param id: id (value in the array) to cut by
:param x: array with x values
:param y: array with y values
:return: x,y, data
"""
if len(data... | d8183f4a46e553885e0ab1e9b9257249b6e3a5ba | 3,627,810 |
def train_step(input_image, target):
"""Run a single training step and return losses."""
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
gen_output = GENERATOR(input_image, training=True)
disc_real_output = DISCRIMINATOR([input_image, target], training=True)
disc_gen... | e77f4f3bef6f953183436e417b05e926a5441701 | 3,627,811 |
from functools import wraps
def flow(flow):
"""Decorator:
decorator = flow(flow)
The decorator then transforms a method:
method = decorator(method)
so that the "flow" kwarg is set the argument to the decorator.
A nonsense value of "flow" will raise and Exception in
Componenet.__select_f... | 24292de3d0f63ca6eafc9785db4c5bfa5519852f | 3,627,812 |
def do_tags_for_model(parser, token):
"""
Retrieves a list of ``Tag`` objects associated with a given model
and stores them in a context variable.
The model is specified in ``[appname].[modelname]`` format.
If specified - by providing extra ``with counts`` arguments - adds
a ``count`` attribut... | 44c371d97b75bf609d437bc2cabf5fbd03bf40be | 3,627,813 |
def use(alpha, beta):
"""Sum 2 things."""
return functions.func(alpha, beta) | 3ba6d89218ae9f6ff87288e3580c3d42e097513b | 3,627,814 |
def controller_enabled_provisioned(hostname):
""" check if host is enabled """
try:
with openstack.OpenStack() as client:
hosts = get_hosts(client.admin_token,
client.conf['region_name'])
for host in hosts:
if (hostname == host.name a... | a6ade2fbd6131a51e868c6d8abcfaa0e74221d20 | 3,627,815 |
from covid19sim.human import Human
def get_humans_with_age(city, age_histogram, conf, rng):
"""
Creats human objects corresponding to the numbers in `age_histogram`.
Args:
city (covid19sim.location.City): simulator's city object
age_histogram (dict): a dictionary with keys as age bins (a ... | 6971deb609f5b7376c2d269dd42c81469119fc0e | 3,627,816 |
from typing import Union
from typing import Optional
from typing import Generator
from typing import Tuple
from typing import List
import logging
def place_ontop_obj_pos(
env: "BehaviorEnv",
obj: Union["URDFObject", "RoomFloor"],
place_rel_pos: Array,
rng: Optional[Generator] = None,
) -> Optional[Tup... | 149e55421b8393ba1d81dfbf5bf75d07be5d2977 | 3,627,817 |
def make_htc_proxy_X(X: np.ndarray):
"""
Makes HTC proxy values from data series.
The value of the HTC proxy is sum(gas) / mean(in_temp - out_temp).
"""
return np.array([[np.sum(x[:,2]) / np.sum(x[:,0] - x[:,1])] for x in X]) | 8b052c9a50faf9e4a47d3a7ea3247cf78f3d7606 | 3,627,818 |
def recovery_invalid_token(
) -> str:
"""Return a valid auth token"""
return 'wrong' | 38ff965ffa7b579965e479ca1d676a4b40978772 | 3,627,819 |
def squeeze(input_vector):
"""Ensure vector only has one axis of dimensionality."""
if input_vector.ndim > 1:
return np.squeeze(input_vector)
else:
return input_vector | 97a80a73c0061dbfe0d6a9f3ab579c4163e00c36 | 3,627,820 |
import warnings
def summarize_darshan_perf(darshan_logs):
"""
Given a list of Darshan log file paths, calculate the performance observed
from each file and identify OSTs over which each file was striped. Return
this summary of file performances and stripes.
"""
results = {
'file_paths... | 7275454355f85045ff8d65baea748c75cb7939bc | 3,627,821 |
from django.contrib.auth import login
from django.contrib.auth import authenticate
from django.contrib.auth import login
def login(request, template_name="lfs/customer/login.html"):
"""Custom view to login or register/login a user.
The reason to use a custom login method are:
* validate checkout type
... | d7bc83bc3a63913bbf5a3e8f34ca6afd72ac3320 | 3,627,822 |
def is_string(var):
"""Check if `var` is a string (or unicode)."""
target = (str, unicode) if python2 else str
return isinstance(var, target) | 6141524b4c98e700199f8376aa923e9b347fdeaf | 3,627,823 |
def get_parameter_name(argument):
"""Return the name of the parameter without the leading prefix."""
if argument[0] not in {'$', '%'}:
raise AssertionError(u'Unexpectedly received an unprefixed parameter name, unable to '
u'determine whether it is a runtime or tagged paramet... | 54b51cd5e3239fbfaaccaad123975df0e84374fc | 3,627,824 |
def find_distance(a1, num_atoms, canon_adj_list, max_distance=7):
"""
Calculate graph distance between atom a1 with the remaining atoms using BFS
"""
distance = np.zeros((num_atoms, max_distance))
radial = 0
# atoms `radial` bonds away from `a1`
adj_list = set(canon_adj_list[a1])
# atoms less than `radi... | 8576cda6d975549fd55ad707b1cd146648517314 | 3,627,825 |
def _get_pixel_coords(plot_params):
"""A helper method to define coordinates for a plotting window.
This routine builds a coordinate surface map for the plotting window defined
for by the user. If no window was defined, then this routine uses the outer
bounding box around the geometry as the plotting w... | 9967381d54d2eb5841d3fe702cc15183cce14819 | 3,627,826 |
import requests
import itertools
def parse_nasa_catalog(mission, product, version, from_date=None, to_date=None, min_max=False):
"""
Function to parse the NASA Hyrax dap server via the catalog xml.
Parameters
----------
missions : str, list of str, or None
The missions to parse. None will... | b621adf204e013e6c235245bd59a4be91955b716 | 3,627,827 |
def open_pdb(f_loc):
"""
This function reads in a .pdb file and returns the atom names and coordinates.
Parameters
----------
f_loc : str
File path to .pdb file
Returns
-------
symbols, coordinates : np.ndarray
Numpy arrays of the atomic symbols (str) and coordinates (f... | e944a37834b77ca86ab70e6294657ed51ec5b8b3 | 3,627,828 |
def update_name(name, mapping):
"""Makes an improvement in the address (name) according to the dictionary (mapping)"""
m = street_type_re.search(name)
not_good_type = m.group()
try:
name = name.replace(not_good_type, mapping[not_good_type])
return name
except:
return False | 6f2d26091663888ac602854968e29981f66b1be7 | 3,627,829 |
def print_list_text(img_src, str_list, origin = (0, 0), color = (0, 255, 255), thickness = 2, fontScale = 0.45, y_space = 20):
""" prints text list in cool way
Args:
img_src: `cv2.math` input image to draw text
str_list: `list` list with text for each row
origin: `tuple` (X, Y) coordi... | de53fd31146b63c3f29f335d235919263a2e29f3 | 3,627,830 |
def get_extension_modules(config):
"""Handle extension modules"""
EXTENSION_FIELDS = ("sources",
"include_dirs",
"define_macros",
"undef_macros",
"library_dirs",
"libraries",
... | 0d21ac1e04879d90577debfc8ae04761af1d16e2 | 3,627,831 |
def configure_ibgp_vrrp_vxlan(module):
"""
Method to configure iBGP, VRRP and Vxlan for DCI.
:param module: The Ansible module to fetch input parameters.
:return: String describing details of all configurations.
"""
global CHANGED_FLAG
output = ''
cluster_dict_info = find_clustered_switc... | 43dc1d5adf4c93106e6d5ed5341b215b7e4685d9 | 3,627,832 |
def part_has_modifier(data, part, modifier):
"""Returns true if the modifier is in the given subject/object part
:param dict data: A PyBEL edge data dictionary
:param str part: either :data:`pybel.constants.SUBJECT` or :data:`pybel.constants.OBJECT`
:param modifier: The modifier to look for
:rtype:... | cd7596b792fd8803ea5eb62573b0ba5efeae5c93 | 3,627,833 |
def unbox_unchecked_bool(stage: ImportStage, value: ir.Value) -> ir.Value:
"""Unboxes an object value to a bool, not checking for success."""
return d.UnboxOp(d.ExceptionResultType.get(), d.BoolType.get(),
value).primitive | 36977ea10532b57290ee7c24e1459a284dd67387 | 3,627,834 |
def step4_pfg(data_input, col, g_list, nfrag):
"""
Parallel FP-Growth
"""
g_list = g_list[0]
result = [[] for _ in range(nfrag)]
df = read_stage_file(data_input, col)
for transaction in df[col].to_numpy():
# group_list has already been pruned, but item_set hasn't
item_set =... | b3b3e8b44de3245494206649a882a49162e074db | 3,627,835 |
def camera_to_points_world(camera,robot,points_format='numpy',color_format='channels'):
"""Same as :meth:`camera_to_points`, but converts to the world coordinate
system given the robot to which the camera is attached.
Points that have no reading are stripped out.
"""
assert isinstance(camera,SimR... | 4a576452a9fe96fa0267644c2d682d29fc886461 | 3,627,836 |
def array_size(arr):
""" Return size of an numpy.ndarray in bytes """
return np.prod(arr.shape) * arr.dtype.itemsize | 27b1862dc02d3e404fe63495d3b683b08cdffa5a | 3,627,837 |
def is_deprecated(image_array, blank_rate):
"""whether to deprecate the patches with blank ratio greater than max_blank_ratio"""
blank_num = np.sum(image_array == (255, 255, 255)) / 3
height, width = image_array.shape[:2]
if blank_num / (height * width) >= blank_rate:
return True
else:
... | 2f7fc0f1c14b505c33d7f93e7fbded3b6b9498e9 | 3,627,838 |
def get_one_hot_labels(labels, n_classes):
"""
Function for creating one-hot vectors for the labels, returns a tensor of shape (?, num_classes).
Parameters:
labels: tensor of labels from the dataloader, size (?)
n_classes: the total number of classes in the dataset, an integer scalar
"""... | afcd20c26c776d71574c5f48f37a816f98f1d38a | 3,627,839 |
import hashlib
def cmpHash(file1, file2):
"""Compare the hash of two files."""
hash1 = hashlib.md5()
with open(file1, 'rb') as f:
hash1.update(f.read())
hash1 = hash1.hexdigest()
hash2 = hashlib.md5()
with open(file2, 'rb') as f:
hash2.update(f.read())
hash2 = hash2... | 891b71188de42fb9c30a6559cd22b39685b6fc13 | 3,627,840 |
def gsfLoadDepthScaleFactorAutoOffset(
p_mb_ping,
subrecord_id: c_int,
reset: c_int,
min_depth: c_double,
max_depth: c_double,
last_corrector,
p_c_flag,
precision: c_double,
) -> int:
"""
:param p_mb_ping: POINTER(gsfpy3_09.gsfSwathBathyPing.c_gsfSwathBathyPing)
:param subrec... | 295560ed85df1ef5ec7fb03e7ebf9f4a1f9b14ed | 3,627,841 |
def preprocess_onnx(img: Image, width: int, height: int, data_type, scale: float, mean: list,
stddev: list):
"""Preprocessing function for ONNX imagenet models based on:
https://github.com/onnx/models/blob/master/vision/classification/imagenet_inference.ipynb
Args:
img (PIL.Imag... | 1c7d29ea33e400c085b8924189a594826ef3ca5d | 3,627,842 |
import numpy
def boxerFrameStack(framestackpath, parttree, outstack, boxsize,framelist):
"""
boxes the particles and returns them as a list of numpy arrays
"""
start_frame = framelist[0]
nframe = len(framelist)
apDisplay.printMsg("boxing %d particles from sum of total %d frames starting from frame %d using mmap... | 271ee7ad606e603b802161532352df337cb89d8e | 3,627,843 |
def validate_optional_prompt(val, error_msg=None):
"""Dummy validation function for optional prompts. Just returns val"""
# TODO Should there just be an option in prompt()? If input is non-blank you'll probably still wanna validate it
return val | 8020dcc7547a32f4d1e0abc81faaf2de834833f4 | 3,627,844 |
def acorr_grouped_df(
df,
col = None,
by = 'date',
nfft = 'pad',
func = lambda x: x,
subtract_mean = 'total',
norm = 'total',
return_df = True,
debias = True,
**kwargs
):
... | d5af7fc9e12084e21d3f65666997b7fc46e13387 | 3,627,845 |
import pyte
def normalize_pyte(raw_result: str) -> str:
"""ta metoda normalizacji używa emulatora terminala
do wyrenderowania finalnej planszy
wymaga zainstalowania paczki `pyte` z pip
pyte nie wspiera następujących ansi escape codes:
Esc[s -- save cursor position
Esc[u -- restore cursor posi... | 1c76a3f7e6c82667e576fc513d97db1c8a851808 | 3,627,846 |
def delete(isamAppliance, id, check_mode=False, force=False):
"""
Deleting a Password Strength
"""
if force is True or _check(isamAppliance, id) is True:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isamAppliance.invo... | f9c916b0be3123dd0ad1ff8bad9a704d3cf69ab5 | 3,627,847 |
def register(style, func=None):
"""注册一个拼音风格实现
::
@register('echo')
def echo(pinyin, **kwargs):
return pinyin
# or
register('echo', echo)
"""
if func is not None:
_registry[style] = func
return
def decorator(func):
_registry[styl... | c581df1459ec4e022d0f071a5e2e837b17652c3f | 3,627,848 |
def pickoff_image(ap_obs, v2_obj, v3_obj, flux_obj, oversample=1):
"""
Create an unconvolved image of filled pixel values that have
been shifted via bilinear interpolation. The image will then
be convolved with a PSF to create the a focal plane image that
is the size of the NIRCam pick-off mirror. ... | d14055d322bdba079e91895c31c320cc78e807ed | 3,627,849 |
def kms_encrypt(value, key, aws_config=None):
"""Encrypt and value with KMS key.
Args:
value (str): value to encrypt
key (str): key id or alias
aws_config (optional[dict]): aws credentials
dict of arguments passed into boto3 session
example:
aws_c... | f2e70c8ee6caa6c8f2069485eada953a5f031e0b | 3,627,850 |
def pd_expand_json_column(df, json_column):
"""
https://stackoverflow.com/a/25512372
"""
df = pd.concat(
[df, json_column.apply(lambda content: pd.Series(list(content.values()), index=list(content.keys())))],
axis=1
)
return df.drop(columns=['data']) | be9808e9b80e8fbe2de79ac4839b28d9b5705662 | 3,627,851 |
def correct_spellings(text):
"""
converts incorrectly spelled words into correct spelling
"""
corrected_text = []
misspelled_words = spell.unknown(text.split())
for word in text.split():
if word in misspelled_words:
corrected_text.append(spell.correction(word))
else... | 7d75f5cffbec29c6707e627183d4b57165951928 | 3,627,852 |
def xception_module(inputs,
depth_list,
skip_connection_type,
stride,
unit_rate_list=None,
rate=1,
activation_fn_in_separable_conv=False,
regularize_depthwise=False,
... | 1b6137392e027c3cb55fa43edf7828ddd108117c | 3,627,853 |
def greatest_common_divisor(a: int, b: int) -> int:
"""
Euclid's Lemma : d divides a and b, if and only if d divides a-b and b
Euclid's Algorithm
>>> greatest_common_divisor(7,5)
1
Note : In number theory, two integers a and b are said to be relatively prime,
mutually prime, or co-pri... | b481c0162c233e1e5e8a717e4b469118e6fa9eea | 3,627,854 |
def bfmt(num, size=8):
""" Returns the printable string version of a binary number <num> that's length <size> """
if num > 2**size:
return format((num >> size) & (2**size - 1), 'b').zfill(size)
try:
return format(num, 'b').zfill(size)
except ValueError:
return num | 8aadc9671643b48c7c05032473b05fd872475bb0 | 3,627,855 |
from datetime import datetime
def text_to_NAF(text,
nlp,
dct,
layers,
title=None,
uri=None,
language='en',
layer_to_attributes_to_ignore=dict(),
naf_version='v3',
cdata=True,... | 016e4662f40ca411b924b9b7dda103033215aae5 | 3,627,856 |
from typing import Optional
def getContextRect(
context: Context,
obj: Optional[TextContainerObject] = None
) -> Optional[locationHelper.RectLTRB]:
"""Gets a rectangle for the specified context."""
if context == Context.FOCUS:
return getObjectRect(obj or api.getFocusObject())
elif context == Context.NAVIGATO... | 8638c4f9ed2b569b95ae0549a6ed61ba973fe02e | 3,627,857 |
def spans_to_binary(spans, length=None):
"""
Converts spans to a binary array indicating whether each character is in the span.
Args: spans (list of lists of two ints): Spans.
Returns: np array [length]: Binarized spans.
"""
length = np.max(spans) if length is None else length
binary = np.ze... | fea51009dd8a33208e6e29db88d1385ef8f0bb98 | 3,627,858 |
def check_dataset_access_permission(view_func):
"""
Decorator ensuring that the user has access to dataset.
Arg: 'dataset'.
Return: the dataset or raise an exception
Notice: its gets an id in input and returns the full object in output (not an id).
"""
def decorate(request, *args, **kwargs):
dataset... | d30a496bdff110cfefa711e6b84dcb8f30f1c1f9 | 3,627,859 |
def check_barcode_is_off(alignment, tags, log=None):
"""
See if the barcode was recognised with soft clipping.
if so, it returns True and can be counted in the optional log
:param alignment: the read
:param tags: alignment tags as dict
:return:
"""
if 'RG' in tags:
if tags['bm']... | 7adcbb8eae797750b3e543c52db41341d82f0937 | 3,627,860 |
def flatten_all_lists_in_dict(obj):
"""
>>> flatten_all_lists_in_dict({1: [[2], [3, {5: [5, 6]}]]})
{1: [2, 3, {5: [5, 6]}]}
"""
if isinstance(obj, dict):
for key, value in obj.items():
obj[key] = flatten_all_lists_in_dict(value)
return obj
elif isinstance(obj, list):... | 85afdb04337ee8e942073c4193c8b027981c5429 | 3,627,861 |
def already_visited(string):
"""
Helper method used to identify if a subroutine call or definition has
already been visited by the script in another instance
:param string: The call or definition of a subroutine/function
:return: a boolean indicating if it has been visited already or not
"""
... | 7a9d84b6e04cdf7edb27bb7cf49cf1021130ab07 | 3,627,862 |
def series_to_dict(ts, cat=None, dynamic_feat=None):
"""Given a pandas.Series object, returns a dictionary encoding the time series.
ts -- a pands.Series object with the target time series
cat -- an integer indicating the time series category
Return value: a dictionary
"""
obj = {"start": str(... | be2c5a22f6b57d446e58b73ae966fbc7b0fdf9ef | 3,627,863 |
def expected_loss_t(u_m, lgd, ead, new):
""" Total expected loss.
Shape (K,)"""
el = np.sum(expected_loss_g_i_t(u_m, lgd, ead, new), axis=0)
el = np.sum(el, axis=0)
return el | ce81dcac5fb58dc66e174bcce9c89b528fa8b4dc | 3,627,864 |
def tool_pred_class_label(log_likelyhood, cutoff=0):
"""
Infer class label based on log-likelyhood
Args:
log_likelyhood:
Returns:
"""
if log_likelyhood > cutoff + EPSLONG:
return 1
return 0 | dd80e7ba95005f561d3e121b7d60dcd896cc917f | 3,627,865 |
from typing import Sequence
import itertools
def select_polymorph(polymorphs, args):
"""Determine the polymorphic signature that will match a given argument list.
This is the mechanism used to reconcile Java's strict-typing polymorphism with
Python's unique-name, weak typing polymorphism. When invoking a ... | bf2811989ce9af4cd433df9d9a3841777f47bc4d | 3,627,866 |
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/main") | 88696b0e642389ede52cac6504b10e3a0f890c3b | 3,627,867 |
import pathlib
def get_stem_name(file_name: pathlib.Path | str | None) -> str:
"""Get the stem name from a file name.
Args:
file_name (pathlib.Path | str | None): File name or file path.
Returns:
str: Stem name.
"""
if file_name is None:
return ""
if isinstance(file_... | 01bab045f2c54aedf848922550ae241c9ddf8bce | 3,627,868 |
def getSingleIndexedParamValue(request, param_name, values=()):
"""Returns a value indexed by a query parameter in the HTTP request.
Args:
request: the Django HTTP request object
param_name: name of the query parameter in the HTTP request
values: list (or tuple) of ordered values; one of which is
... | c8a1a552d1ad9435e21243bf05226b373257d163 | 3,627,869 |
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
#if the state is a terminal state, then there is no possible action
if terminal(board):
return "game over"
else:
#traverse through the board and add the location of empty cells to the p... | e3daa821650b665a5119bfa206b7dc42b941d8c9 | 3,627,870 |
def requestLanguage(request, try_user=True):
"""
Return the user interface language for this request.
The user interface language is taken from the user preferences for
registered users, or request environment, or the default language of
the wiki, or English.
This should be called once per req... | 58cc57acc55f6e34f44bc6c932b123642e7f1c09 | 3,627,871 |
import IPython
import IPython.display
from typing import Type
def register_json_formatter(cls: Type, to_dict_method_name: str = 'to_dict'):
"""
TODO
:param cls:
:param to_dict_method_name:
:return:
"""
if not hasattr(cls, to_dict_method_name) or not callable(getattr(cls, to_dict_method_nam... | 76394307a2d549e735a9a4bd7323290188358755 | 3,627,872 |
def get_best_muscle_hits(subject_seq, query_aln,threshold,use_shorter=True):
"""Returns subset of query_aln with alignment scores above threshold.
- subject_seq is sequence aligned against query_aln seqs.
- query_aln is dict or Alignment object with candidate seqs to be
aligned with sub... | 980930d7bf98635de4f4efb9bb4affbbaff0c053 | 3,627,873 |
def _hrf_d_basis(d, t_r, n_times_atom):
""" Private helper to define the double gamma HRF 2/3 basis function.
Parameters
----------
d : int, the number of atoms in the HRF basis, possible values are 2 or 3
t_r : float, Time of Repetition, fMRI acquisition parameter, the temporal
resolution
... | 3736c4bdc852d118901789fb24b450e5d3666d84 | 3,627,874 |
from lhrhost.messaging.transport.ascii import transport_loop
from lhrhost.messaging.transport.firmata import transport_loop
def parse_argparser_transport_selector(args):
"""Return a transport loop as specified from the argparse args."""
if args.transport == 'ascii':
elif args.transport == 'firmata':
e... | 01bda845fa368cf3212d46e14c557a2749889f3c | 3,627,875 |
from typing import Optional
import os
def gsea_results_to_filtered_df(
dataset,
kegg_manager: Optional[bio2bel_kegg.Manager] = None,
reactome_manager: Optional[bio2bel_reactome.Manager] = None,
wikipathways_manager: Optional[bio2bel_wikipathways.Manager] = None,
p_value: Option... | a625c7bd3b9187ba66c8e0332d23e8fda6c3a480 | 3,627,876 |
def create_network(request, id_vlan="0", sf_number='0', sf_name='0', sf_environment='0', sf_nettype='0', sf_subnet='0', sf_ipversion='0', sf_network='0', sf_iexact='0', sf_acl='0'):
""" Set column 'active = 1' in tables """
try:
if request.method == 'POST':
form = CreateForm(request.POST)
... | 017b3f8bf765e7f5a4aeea8c24c28dd3cd37f539 | 3,627,877 |
from typing import List
from typing import Union
import copy
def _order_fun(term: List[List[int]], weight: Union[float, complex] = 1.0):
"""
Return a normal ordered single term of the fermion operator.
Normal ordering corresponds to placing the operator acting on the
highest index on the left and lowe... | c4e5d5fc748633aa601effb137b9c74d4a6252a4 | 3,627,878 |
def validate(number):
"""Check if the number provided is a valid RNC."""
number = compact(number)
if not number.isdigit():
raise InvalidFormat()
if number in whitelist:
return number
if len(number) != 9:
raise InvalidLength()
if calc_check_digit(number[:-1]) != number[-1]... | 2bb71bdf15a6e69cebab5af0f65bf32fe6922cea | 3,627,879 |
def bindwith(*mappings, **kwargs):
"""Bind variables to a function's outer scope, but don't yet call the function.
>>> @bindwith(cheez='cheddar')
... def makez_cheezburger():
... bun = ...
... patty = ...
... cheezburger = [bun, patty, cheez, bun]
>>> makez_cheezburger.outer_sc... | d4dd4dd747035b10415631b362472db2f5220454 | 3,627,880 |
def _call(calls):
"""Make final call"""
final_call = ''
if calls['is_hiv'] == 'No':
final_call = 'NonHIV'
return final_call
if calls['deletion'] == 'Yes':
final_call = 'Large Deletion'
if calls['inversion'] == 'Yes':
final_call += ' with Internal Inversion'
... | c5e293255911cfdb16a73a026a13b7a394ae71cc | 3,627,881 |
from typing import OrderedDict
def load_madminer_settings(file_name: str, include_nuisance_benchmarks: bool) -> tuple:
"""
Loads the complete set of Madminer settings from a HDF5 data file
Parameters
----------
file_name: str
HDF5 file name to load the settings from
include_nuisance_b... | da283ad14a8b570bca366dee7adcadb95ccf7757 | 3,627,882 |
def namespace2dict(namespace):
"""
Converts recursively namespace to dictionary. Does not work if there is a namespace whose
parent is not a namespace.
"""
d = dict(**namespace)
for k, v in d.items():
if isinstance(v, NamespaceMap):
d[k] = namespace2dict(v)
return d | 0a8ed70b03e5a8a5c348fe3a619a8f46d1ff46b8 | 3,627,883 |
def editGenre(genre_id):
""" Edits the genre
"""
editedGenre = session.query(Genre).filter_by(id=genre_id).one()
if editedGenre.user_id != login_session['user_id']:
return """<script>(function() {alert("not authorized");})();</script>"""
if request.method == 'POST':
if request.form['... | f8c1400d13bb00e474bc52334ca319238e676db0 | 3,627,884 |
def potential_fn(scale, coefs, preds, x):
"""Linear regression"""
y = jnp.dot(x, coefs)
logpdf = stats.norm.logpdf(preds, y, scale)
return -jnp.sum(logpdf) | ccd1c9767be5ae9523839694a62d5960f926ae2b | 3,627,885 |
def van32(**kwargs):
"""Constructs a 32 layers vanilla model.
"""
model = Vanilla(*make_layers(32), **kwargs)
return model | 6eb8bea96c120c1d8c64b31940c1b45548db4552 | 3,627,886 |
import collections
def indices(record):
"""
Generalization of Mapping.keys().
@type: record: Record[Any, Any]
@rtype: Iterator[Any]
@raises: TypeError
"""
if isinstance(record, collections.Mapping):
if hasattr(record, 'keys'):
return iter(record.keys())
else:
... | 4b204d2e8a82a3bf996d2c994e8bafdd1ea320f6 | 3,627,887 |
def my_request_classifier(environ):
""" Returns one of the classifiers 'dav', 'xmlpost', or 'browser',
depending on the imperative logic below"""
request_method = REQUEST_METHOD(environ)
if request_method in _DAV_METHODS:
return "dav"
useragent = USER_AGENT(environ)
if useragent:
... | 0797e408c516e6ecf07fc8d7d13896ef4b990b9a | 3,627,888 |
def bisection_solve(x, power, epsilon, low, high):
"""x, epsilon, low, high are floats
epsilon > 0
low <= high and there is an ans between low and high s.t.
ans**power is within epsilon of x
returns ans s.t. ans**power within epsilon of x"""
ans = (high + low)/2
while abs... | 64df81073237499e0e05f2daef6cd3dcafe85f0f | 3,627,889 |
def get_distinct_rotations(structure, symprec=0.1, atol=1e-6):
"""
Get distinct rotations from structure spacegroup operations
Args:
structure (Structure): structure object to analyze and
get corresponding rotations for
symprec (float): symprec for SpacegroupAnalyzer
ato... | 26fd948e3091d21bb3343fc231545ef106a8db2e | 3,627,890 |
import math
def get_sierpinski_carpet_set(width, height):
"""
获得谢尔宾斯基地毯点集
:param width:
:param height:
:return: 谢尔宾斯基地毯点集
"""
def get_sierpinski_carpet_points(left, top, right, bottom):
"""
递归获取谢尔宾斯基地毯的点
:param left:
:param top:
:param right:
... | b66bbe0dd25b47d81089b35d21a255b3b56c1f1e | 3,627,891 |
def find_target_node(ctx, stmt, is_instance_allowed = False):
"""Find the target node for the 'refine' or 'augment' statements"""
parent = stmt.parent
if stmt.arg == '.':
return parent
# parse the path into a list of two-tuples of (prefix,identifier)
pstr = '/' + stmt.arg
path = [(m[1], ... | cb44f81c7bf23dee5fadbf8d451aaa0714fbbe52 | 3,627,892 |
def destroy_asteroids(angles):
"""Destroy asteroids, start with laser pointing up and rotate clockwise."""
destroy_list = []
sorted_angles = sorted(angles)
while sorted_angles:
for angle in sorted_angles:
if not angles[angle]:
sorted_angles.remove(angle)
e... | 166fbd4e87152748b1d6527315fb87a91b617b7a | 3,627,893 |
def zoom(image, zoom_scale):
"""
TODO: Check that this works for odd, even zoom_scale
TODO: write tests
Zooms in on center of image, with a representative zoom_scale.
Inputs:
:image: (numpy array) image to be zoomed in on.
:zoom_scale: (int) length of side of box of zoomed image, i... | 364d317506f5a7c96964d9c540c9e878eaf9363a | 3,627,894 |
def _get_multipart_param(param_name: str, count: int, ssm) -> str:
"""You must pass the count returned from _get_num_multiparts"""
param_value = ""
i = 0
for i in range(count):
param_value += ssm.get_parameter(Name=_get_multipart_param_part_name(param_name, i))[
"Parameter"
]... | ce4840be7d74d80067608561ac3177fb3f22eda0 | 3,627,895 |
from typing import Optional
def get_lrs(lr:slice, count:Optional[int]=None):
"""
Exponentially increasing lr from
slice.start to slice.stop.
if `count is None` then count = int(stop/start)
"""
lr1 = lr.start
lr2 = lr.stop
if count is None:
count = int(lr2/lr1)
inc... | 2df40e7716f579b84f631af2eaaa2d4848b5eb74 | 3,627,896 |
def install_softcurrent_turn():
"""
turn to current 10 day's line chart of yesterday soft install top 10
:return:
"""
return render_template("cb_soft_install_crnt_line_show.html") | 488c0628b26522a20d089e2d5331f8aa62fdcb56 | 3,627,897 |
import json
def add_filename(json_):
"""
Args:
string: json path
Returns:
dict: annotion label
"""
with open(json_) as f:
imgs_anns = json.load(f)
img_extension = json_.split('/')[-1].split('.')[0]+'.jpg'
imgs_anns['filename'] = img_extension
return img... | 3710a1d6f177b36c6786797f9af5c58cd527f354 | 3,627,898 |
import unittest
def test():
""" Function to execute unitest.
"""
suite = unittest.TestLoader().loadTestsFromTestCase(TestMemory)
runtime = unittest.TextTestRunner(verbosity=2).run(suite)
return runtime.wasSuccessful() | 4013ee35937307f01899129a46884fb8a6113452 | 3,627,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.