content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def print_melhor_time(funcao_atual_ou_futuro):
"""Função que imprirmi o melhor time.
Parameters
----------
funcao_atual_ou_futuro : list
Lista contendo um time de jogadores
Returns
-------
str
Texto organizando o time por posição
"""
gol, zag1, zag2, l... | 62,400 |
def run():
"""Requirements for Task 1D """
# Build station list
stations = build_station_list()
# Build river list
rivers = rivers_with_station(stations)
# First deliverable
print(len(rivers))
print(sorted(list(rivers))[:10])
# Build dictionary
river_station_dict = stations_by_r... | 62,401 |
def info_from_giphy(info, url):
"""Populate info object with info from *.giphy.com url."""
log("--- Detected giphy")
url = url.replace("media.giphy.com", "i.giphy.com")
url = url.replace("media1.giphy.com", "i.giphy.com")
url = url.replace("media2.giphy.com", "i.giphy.com")
url = url.replace("gi... | 62,402 |
def gcf():
"""获取当前Axis"""
global g_figure
return g_figure | 62,403 |
def set_buzzer(state):
"""set buzzer state
Phenox buzzer has only 2 states(ON of OFF).
if bool(state) == True, buzzer turns on, else turns off.
"""
pxlib.pxset_buzzer(int(bool(state))) | 62,404 |
def postrefine_frames(i_iter, frames, frame_files, iparams, pres_set, miller_array_ref, avg_mode):
"""postrefine given frames and previous postrefinement results"""
miller_array_ref = miller_array_ref.generate_bijvoet_mates()
txt_merge_postref = 'Post-refinement cycle '+str(i_iter+1)+' ('+avg_mode+')\n'
txt_mer... | 62,405 |
def calc_and_plot_trap(trap: abstract_trap.AbstractTrap, trap_params: TrapVisParams, ipv, expanded=True):
"""creates 3D visualization in jupyter notebook"""
e_types_colors = trap._voltages.EXCITATION.colors_for_3d()
# what to visulize
if expanded:
trap.pa = PA(file=f"{trap.pa_filename}_expa... | 62,406 |
def backend2(threescale, backend_usages):
"""
Second bound backend
Should deliver slight performance improvement
"""
return threescale.backends.read(backend_usages[1]["backend_id"]) | 62,407 |
def gen_cr_from_active_set(program: MPQP_Program, active_set: List[int], check_full_dim=True) -> Optional[
CriticalRegion]:
"""
Builds the critical region of the given mpqp from the active set.
:param program: the MQMP_Program to be solved
:param active_set: the active set combination to build this... | 62,408 |
def test_expire_action(friends):
"""
Want to observe the scheduling move from deferred state to ready state.
"""
dispatcher, scheduler, action = friends()
dispatcher.add_action("foo", action)
dispatcher.add_scheduler("bar", scheduler)
assert 0 == dispatcher.get_expiring_action_count()
a... | 62,409 |
def get():
"""Get peaks dataset.
"""
# Get hosp. capacity data
data = capacidad_hospitalaria.get()
# Do not consider rows with UCI status.
data = data[~data['estatus_capacidad_uci'].isnull()]
# Find peaks and its statistics
peaks = []
for hospital, hospital_data in data.groupby('n... | 62,410 |
def extract_group_to_individual_class(df, parts_group, df_body_parts):
"""
Extract multiple keys from dataframe and combine them in a trackedgroup
Inputs:
_______
df : dataframe
parts_group : string
df_body_parts: list of strings
"""
parts_group_label = list(filter(lambda x: re.match... | 62,411 |
def without_apply_rng(f: TransformedT) -> TransformedT:
"""Removes the rng argument from the apply function.
This is a convenience wrapper that makes the ``rng`` argument to
``f.apply`` default to ``None``. This is useful when ``f`` doesn't actually
use random numbers as part of its computation, such that the ... | 62,412 |
def has_events(doc, include_negatives=False):
"""
Parameters
----------
doc: Document
include_negatives: Count document as having events when at least one trigger is not an abstain
Returns
-------
Whether the document contains any (positive) events
"""
if "events" in doc and doc... | 62,413 |
def update_named_ports(mig, named_ports):
"""
Set the named ports on a Managed Instance Group.
Sort the existing named ports and new. If different, update.
This also implicitly allows for the removal of named_por
:param mig: Managed Instance Group Object from libcloud.
:type mig: :class: `GC... | 62,414 |
def get_allowable_kernels() -> List[str]:
"""Get all allowable kernel families.
:return:
"""
return list(KERNEL_DICT.keys()) | 62,415 |
def fooo(request, user):
"""
# Assert statements
"""
assert user.is_admin
# secure code...
| 62,416 |
def lrCostFunction(theta, X, y, lambda_):
"""Compute cost and gradient for logistic regression with regularization
J = lrCostFunction(theta, X, y, lambda) computes the cost of using
theta as the parameter for regularized logistic regression and the
gradient of the cost w.r.t. to the parameters.
:pa... | 62,417 |
def coe2rv(coe, mu):
""" Convert from Keplerian to Cartesian.
Ref:
Vallado 4th Ed. pg 118
Args:
coe (numpy.array): 6x1 array with Keplerian orbital elements
1: semimajor axis (LU)
2: eccentricity
3: inclination (radia... | 62,418 |
def add_motifclust_arguments(parser):
"""Parsing arguments using argparse
Returns
-------
ArgumentParser
an object containing all parameters given.
"""
parser.formatter_class = lambda prog: argparse.RawDescriptionHelpFormatter(prog, max_help_position=40, width=90)
description = "Cluster motifs based on simil... | 62,419 |
def out_line(name, attributes, value, formatter, join_char=";"):
"""Returns a single field correctly formatted and encoded (including trailing newline)
@param name: The field name
@param attributes: A list of string attributes (eg "TYPE=intl,post" ). Usually
empty except for TEL and ADR... | 62,420 |
def adjacency(dist, idx):
"""Return the adjacency matrix of a kNN graph."""
M, k = dist.shape
assert M, k == idx.shape
assert dist.min() >= 0
# Weights.
sigma_list = []
for i in range(len(dist)):
pos = 0
while dist[i, pos + 1] != np.inf:
pos += 1
if p... | 62,421 |
def run_test(heat_template, validate):
"""call validate for each fixed_ips
"""
heat = Heat(filepath=heat_template)
if not heat.resources:
pytest.skip("No resources found")
contrail_resources = heat.contrail_resources
if not contrail_resources:
pytest.skip("No Contrail resources ... | 62,422 |
def discover_webmention_endpoint(target: str) -> WebmentionDiscoveryResponse:
"""
Return the webmention endpoint for the given target.
:param target: The target to discover the webmention endpoint for.
:type target: str
:return: The discovered webmention endpoint.
:rtype: str
.. code-block... | 62,423 |
def create_tokens():
"""Creates a token from posted JSON request"""
new_token = EmailToken.from_json(request.get_json(force=True))
existing_token = EmailToken.query.filter_by(
token=new_token.token,
token_type=new_token.token_type,
).first()
print(
'Received token with valu... | 62,424 |
def get_fts_endpoint(endpoint_str, key=None):
"""
Make a request to the FTS API for the given endpoint_str, and optionally takes a key for additional json filtering.
Return the normalized json response as a pandas dataframe if successful, or None if not.
Example: endpoint_str = '/public/fts/flow?year=20... | 62,425 |
def get_dataset(inputs, args):
"""get dataset"""
dataset = fluid.DatasetFactory().create_dataset()
dataset.set_use_var(inputs)
dataset.set_pipe_command("python ./dataset_generator.py")
dataset.set_batch_size(args.batch_size)
dataset.set_thread(int(args.cpu_num))
file_list = [
str(arg... | 62,426 |
def highest_paying_jobs(fse_client, plane_type, distance_limit=None, minimum_pay=0, top_n=5,
desired_trip_type=fse.TripTypes.TRIP_ONLY):
"""
For a type of aircraft find the top N which are rentable and have best $/NM jobs (accounting for capacity)
:param desired_trip_type: Set the t... | 62,427 |
def load_raf_db():
"""
load RAF-Db dataset
:param batch_size:
:return:
"""
print('loading RAF-Db dataset...')
train_dataset = RafFaceDataset(train=True, type='basic',
transform=transforms.Compose([
transforms.Resize(22... | 62,428 |
def compute_tuple(lat, lon, resolution, slice):
"""Computes the tuple Geobox for a coordinate with a resolution and slice."""
decimal.getcontext().prec = resolution + 3
lat = decimal.Decimal(str(lat))
lon = decimal.Decimal(str(lon))
slice = decimal.Decimal(str(1.0 * slice * 10 ** -resolution))
adjusted_l... | 62,429 |
def test_modification(func):
"""Test that bn.xxx gives the same output as np.xxx."""
name = func.__name__
if name == "replace":
return
msg = "\nInput array modified by %s.\n\n"
msg += "input array before:\n%s\nafter:\n%s\n"
for i, a in enumerate(arrays(DTYPES)):
axes = list(range... | 62,430 |
def cast_as_int(input_val):
"""
Args:
input_val: A value of unknown type
Returns:
Int of the value, defaults to 0 if the value cannot be cast as an int.
Examples:
>>> cast_as_int('3')
3
>>> cast_as_int(3.55)
3
>>> cast_as_int('Three')
0
... | 62,431 |
def get_encoder(layer, in_features, hidden_size, bidirectional=True):
"""Returns the requested layer."""
if layer == "lstm":
return LSTMEncoder(in_features, hidden_size,
bidirectional=bidirectional)
elif layer == "rcnn":
return RCNNEncoder(in_features, hidden_size,... | 62,432 |
def touchInstanceInitFile():
"""
function: touch upgrade init file for every primary and standby instance
input: NA
output: NA
"""
g_logger.log("Touch init file.")
try:
InstanceList = []
# find all DB instances need to touch
if len(g_dbNode.datanodes) != 0:
... | 62,433 |
def train_and_evaluate(model, train_dataloader, val_dataloader, optimizer,
loss_fn, metrics, params, model_dir, restore_file=None):
"""Train the model and evaluate every epoch.
Args:
model: (torch.nn.Module) the neural network
params: (Params) hyperparameters
mode... | 62,434 |
def stdin_to_csv(delimiter=',', quotechar='"'):
""" Parse stdin and return output in a CSV format """
# Open CSV
with open_tempfile() as file_:
writer = get_writer(file_, delimiter=delimiter, quotechar=quotechar)
# Parse lines and add to file
separator = None
for line in sy... | 62,435 |
def create_user(session: DatabaseSession, name, comment: str = None) -> None:
"""
Create the user *name*, described by an optional *comment*.
"""
with session.cursor() as cursor:
LOG.info(f"Creating user «{name}»")
cursor.execute(
sqlf("create user {}", Identifier(name)))
... | 62,436 |
def make_input_fn(hparams, mode):
"""Construct a input function for training."""
def _input_fn(params):
"""Input function."""
if mode == contrib_learn.ModeKeys.TRAIN:
src_file = "%s.%s" % (hparams.train_prefix, hparams.src)
tgt_file = "%s.%s" % (hparams.train_prefix, hparams.tgt)
else:
... | 62,437 |
def sim_seird_decay(
s: float, e:float, i: float, r: float, d: float, beta: float, gamma: float, alpha: float, n_days: int,
decay1:float, decay2:float, decay3: float, decay4: float, end_delta: int, fatal: float
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Simulate the SIR model forward... | 62,438 |
def cnv2nc(data, filename):
""" Save a CNV() object into filename as a NetCDF
To save the CTD.cnv into a NetCDF, just run:
profile = cnv.fCNV("CTD.cnv")
cnv2nc(profile, "CTD.nc")
"""
print("Saving netcdf output file: %s" % filename)
nc = netCDF4.Dataset(filename, 'w', format='... | 62,439 |
def toR3(Q):
"""
Transformation from Dual Quaternion to Euclidian Space Coordinates
Q: Symbolic Matrix (two - dimensional)
"""
z = np.array([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0... | 62,440 |
def vpn_server(phrase: str):
"""Enables or disables VPN server.
Args:
phrase: Takes the phrase spoken as an argument.
"""
phrase = phrase.lower()
if vpn_server_check():
say(text='An operation for VPN Server is already in progress sir! Please wait and retry.')
elif 'start' in phr... | 62,441 |
def discharge(da_x, da_y, feats, key='name', reverse=False):
"""
Wrapper function to compute discharge over line segments in a geopackage (opened with fiona)
:param da_x: DataArray - containing x-directional flow
:param da_y: DataArray - containing x-directional flow
:param feats: fiona features - ... | 62,442 |
def render_email_template(template, context):
"""
Renders an email template with this format:
{% if subject %}Subject{% endif %}
{% if message %}Email body{% endif %}
context must be a dict
"""
if not 'site' in context:
from orchestra import settings
url = urlparse(s... | 62,443 |
def FF_Normal(inferred, ground_truth):
"""Compute the fitness for an individual.
Takes in two images and compares
them according to the equation (p + 2)^log(|m - n| + 2), where p is the pixel
error, m is the number of segments in the inferred mask, and n is the number
of segments in the ground trut... | 62,444 |
def run(argv=None):
"""Pipeline for reading data from a Cloud Storage bucket and writing the results to BigQuery"""
parser = argparse.ArgumentParser()
parser.add_argument('--input',
dest='input',
help='File to read in.')
parser.add_argument('--output',
... | 62,445 |
def parse_BIO_tag(tag):
"""Parse given string as BIO tag.
The expected format is "[BIO]-TYPE", where TYPE is any non-empty
nonspace string, and the "-TYPE" part is optional.
Args:
tag (string): tag to parse.
Returns:
string pair: tag ("B", "I" or "O") and TYPE.
"""
m = re.... | 62,446 |
def test_decode_roi_with_priors():
"""Acceptance test of ROI-based decoding with topic priors.
"""
model_file = join(get_test_data_path(), 'gclda_model.pkl')
roi_file = join(get_test_data_path(), 'roi.nii.gz')
model = Model.load(model_file)
_, priors = decode_roi(model, roi_file)
decoded_df,... | 62,447 |
def create_schema(
events: Sequence[Mapping[str, Any]],
links: Sequence[Mapping[str, str]],
tracking: Sequence[Mapping[str, Any]],
schema_id: str,
schema_name: str,
schema_dscpt: str,
) -> Schema:
"""Takes the events and links lists from the applications and creates a schema for it.
Arg... | 62,448 |
def test_backend_get_button_state():
"""Test that we can get the button state."""
device = MockUSBPowerBoardDevice("SERIAL0")
backend = SRV4PowerBoardHardwareBackend(device)
assert not backend.get_button_state(MockBoard(), 0)
with pytest.raises(ValueError):
backend.get_button_state(MockBoa... | 62,449 |
def dadda_4to2_reduction(previous_bit_heap):
""" BitHeap Wallace reduction using 4:2 compressors """
next_bit_heap = BitHeap()
carry_bit_heap = BitHeap()
max_count = previous_bit_heap.max_count()
new_count = int(math.ceil(max_count / 2.0))
# each step reduce the height of the bit heap at at most... | 62,450 |
def vrep_print(client_id, message):
"""Print a message in both the python command line and on the V-REP Statusbar.
The Statusbar is the white command line output on the bottom of the V-REP GUI window.
"""
vrep.simxAddStatusbarMessage(client_id, message, vrep.simx_opmode_oneshot)
print(message) | 62,451 |
def assert_equal(expected, actual):
"""
:param:
- `expected`: The expected Value
- `actual`: The actual value
"""
assert expected==actual, \
"Expected: {e}=={a}, Actual: {e} != {a}".format(e=expected,a=actual)
return | 62,452 |
def modification_oeuvre(identifier):
"""
Route gérant la modification d'une oeuvre
:param id_publ: identifiant de l'oeuvre
:return : affichage du template modifier_oeuvre.html ou redirection
"""
# On renvoie sur la page html les éléments de l'objet oeuvre correspondant à l'identifiant de la route
if request.meth... | 62,453 |
def query_list(L, query):
""" 支持类似 mongodb的 $or $in $nin $gt $gte $lt $lte $ne
"""
for d in L:
flag = False
for k, v in query.iteritems():
if k == '$or':
op_or = query['$or']
rr = []
for dd in op_or:
for kk, vv i... | 62,454 |
def AppendNodeAnnotation(node, annotation, value):
"""Appends an annotation value to a list of annotations on the node.
Arguments:
node: the node.
annotation: annotation name - a string.
value: annotation value to set.
"""
attr = GetNodeAnnotation(node, annotation, set())
attr.add(value)
SetNod... | 62,455 |
def test_appveyor_update_new_compiler_jobs():
""" Try to update an AppVeyor file, new compiler jobs should be added
"""
path_old, path_expected = _prepare_old_file("appveyor_2", ".yml")
args = ['--appveyorfile', path_old]
command = Command()
command.run(args)
assert _compare_file(path_old... | 62,456 |
def ibufs_append_iostandard_params(top):
""" Appends IOSTANDARD parameter to all IBUFs in the design. """
for site in top.sites:
if not site.is_input():
continue
if not site.bels:
continue
append_ibuf_iostandard_params(top, site) | 62,457 |
def VisualizeAll3D(pts3D,ax,dataset_name, xlim, ylim, zlim):
"""
this function visualizes all 3D skeletons from one image
the form if pts3D is 4 by n numpy array, rows 0,1,2 are x,y,z, row3 is always 1
"""
bright_orange_cv2 = (255/255,79/255,0)
bright_blue_cv2 = (0, 229/255, 238/255)
... | 62,458 |
def co2_mol_to_C_mass_flux( df, n_seconds ) :
"""
Convert molar CO2 flux to mass C flux ( umolCO2/m^2/s to gC/m^2 )
and sum (integrate) for each period in the timeseries for each column
in data frame
Args:
df: a pandas dataframe
n_seconds: number of seconds to integrate in the conve... | 62,459 |
def _contourf(darray,
x='lon',
y='lat',
transform=None,
# Facetgrids arguments
figsize=None,
size=None,
aspect=None,
ax=None,
row=None,
col=None,
col_wrap=None,
... | 62,460 |
def generate_token(email, token_expire_date):
"""
It generates user token
:param email: user email
:param token_expire_date: time taken for token to expire
:return: token
"""
token = jwt.encode({'email': email,
'exp': token_expire_date},
os.gete... | 62,461 |
def chunk_textgrid_parser(textgrid_obj):
""" Parsses the Textgrid of One Chunk and Returns a List
Parameters
----------
textgrid_obj : praatio.Textgrid()
One Chunk's Textgrid Object imported using praatio
Returns
-------
textgrid_dict : dict
Dictionary of all of the Tiers f... | 62,462 |
def _set_values(loop_data):
"""Find rows corresponding to values in data
This is a private function, not meant for general use.
Input: dataframe
Output: dataframe
"""
# These are the indexes of all the data that are unassigned
value_indexes = loop_data.ix[(loop_data.loop==0)&... | 62,463 |
def abs(x):
"""Element-wise absolute value.
# Arguments
x: input tensor.
# Returns
A tensor.
"""
return KerasSymbol(mx.sym.abs(data=x.symbol)) | 62,464 |
def persistence2stats(rev_docs, min_persisted=5, min_visible=1209600,
include=None, exclude=None, verbose=False):
"""
Processes a sorted and page-partitioned sequence of revision documents into
and adds statistics to the 'persistence' field each token "added" in the
revision persis... | 62,465 |
def test_atomic_any_uri_enumeration_nistxml_sv_iv_atomic_any_uri_enumeration_1_1(mode, save_output, output_format):
"""
Type atomic/anyURI is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/anyURI/Schema+Instance/NISTSchema-SV-IV-atomic-anyURI-enumeration-1.xsd",
... | 62,466 |
def createDataset_detection(outputPath, imagePathList, box_x_list, box_y_list,
labelList, region_mask_list, pixel_mask_list):
"""
Create LMDB dataset for CRNN training.
ARGS:
outputPath : LMDB output path
imagePathList : list of image path
labelList : l... | 62,467 |
def build_module(
mod,
target,
params=None,
enable_acl=True,
tvm_ops=0,
acl_partitions=1,
disabled_ops=["concatenate"],
):
"""Build module with option to build for ACL."""
if isinstance(mod, tvm.relay.expr.Call):
mod = tvm.IRModule.from_expr(mod)
with tvm.transform.PassCo... | 62,468 |
def plus_frequente_occurence(vecteur, valeur_par_defaut=None):
"""Wrapper de la méthode first_valid_index d'un Pandas.Series.
Arguments d'entrée:
vecteur (pandas.Series)
valeur_par_defaut
Arguments de sortie:
(Python Object)
"""
return vecteur.value_counts(ascending=Fals... | 62,469 |
def szsh_cjmx(date):
"""刷新指定日期的股票成交明细"""
if date is None:
today = pd.Timestamp('today')
if today.hour <= 18:
input_date = pd.Timestamp('today')-pd.Timedelta(days=1)
else:
input_date = today
else:
input_date = date
cjmx.wy_refresh_cjmx(input_date) | 62,470 |
def _get_git_version():
"""Return version of git we use (might be bundled)"""
return __get_git_version(_git_runner) | 62,471 |
def create_cde_graph(restrict_to=None):
"""Create an RDFLIB graph with the FSL CDEs
Any CDE that has a mapping will be mapped
"""
import rdflib as rl
from nidm.core import Constants
with open(cde_file, "r") as fp:
fsl_cde = json.load(fp)
fsl = Constants.FSL
nidm = Constants.NI... | 62,472 |
def test_init_(self):
"""
Test to if check the initialization/creation of user instances is properly done.
"""
self.assertEqual(self.new_user.first_name, "Anthony")
self.assertEqual(self.new_user.last_name, "Mu\tu\ku")
self.assertEqual(self.new_use... | 62,473 |
def test_2010tcdbng(caplog):
"""Card-level parenthesised commends (common)"""
TWDA = twda._TWDA()
with open(os.path.join(os.path.dirname(__file__), "2010tcdbng.html")) as f:
TWDA.load_html(f)
assert len(TWDA) == 1
assert TWDA["2010tcdbng"].to_json() == {
"id": "2010tcdbng",
"... | 62,474 |
def train_and_test_model(number_of_captchas=10, model_path=None):
"""
:param number_of_captchas int: Number of captcha we want to for the train
:param model_path string: Path of the model if it exist
:return None: Print test result
"""
number_of_classes = len(CHAR_POSSIBILITIES)
captchas = l... | 62,475 |
def trajectory(ddir, file_prefix):
""" generate trajectory DataFile
"""
name = autofile.name.trajectory(file_prefix)
writer_ = autofile.write.trajectory
reader_ = _not_implemented
return factory.DataFile(ddir=ddir, name=name,
writer_=writer_, reader_=reader_) | 62,476 |
def _decode_base64(data, altchars=b'+/'):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data) # normalize
missing_padding = len(data) % 4
if missing_paddi... | 62,477 |
def compute_condition(t, dt):
"""
Inputs are normalized times.
`t` is the position of one dirac and `dt` is the distance between the two
diracs.
"""
u0 = np.exp(-1j*2*np.pi*t)
u1 = u0*np.exp(-1j*2*np.pi*dt)
# eigenvalues from quadratic formula
a = 1
b = -1*(1+u1)
c = -1*(u... | 62,478 |
def dot_general(lhs: np.ndarray,
rhs: np.ndarray,
contracting_dims: Axes,
batch_dims: Axes,
precision=None) -> np.ndarray:
"""`jax.lax.dot_general` with preserved dims order and shared lhs / rhs dims.
Precisely, returns `jax.lax.dot_general(lhs, rhs, ... | 62,479 |
def DbSession(filename):
"""Context manage a session with a database connection.
Ensures that tables have been initialized.
"""
if filename != ':memory:':
parent_dir = os.path.dirname(filename)
if not os.path.exists(parent_dir):
os.makedirs(parent_dir)
con = sqlite3.connect(filename)
try:
... | 62,480 |
def read_current_user_shops(
current_user: usermodels.User = Depends(get_current_active_user),
):
"""
Retrieve a list of shops assigned to the currently logged in user.
"""
return current_user.shops | 62,481 |
def check_sim_params(params={}):
"""
Checks simulation parameter dictionary for various keywords and sets to
default values if not present
Parameters
----------
params: dict, optional
dictionary containing initial key/value pairs for simulation of catalog
Returns
-------
pa... | 62,482 |
def post_error():
"""Sends error message in Slack to alert the user
about the incorrect date argument
"""
payload = {
"attachments": [
{
"title": "Error",
"text": ("Date entered must be in the future. "
"\n Go to the <https... | 62,483 |
def visualize_colormap():
""" """
label_img = np.random.randint(0, 80, size=(100, 100))
id_to_class_name_map = {i: str(i) for i in range(80)}
form_contained_classes_color_guide(
label_img=label_img,
id_to_class_name_map=id_to_class_name_map,
fname_stem="fb_colormap",
save... | 62,484 |
def points_on_circle(radius, points):
"""
returns a set of uniform points around a circle
:param radius: radius of the circle
:param points: number of points on the circle
:return:
"""
angle = np.linspace(0, 2*np.pi, points)
x_coord = np.cos(angle)*radius
y_coord = np.sin(angle)*radi... | 62,485 |
def validate(data_loader):
"""
:return: validation accuracy, validation loss
"""
num_iteration = 0
deep_punctuation.eval()
correct = 0
total = 0
val_loss = 0
with torch.no_grad():
for x, y, att, y_mask in tqdm(data_loader, desc='eval'):
x, y, att, y_mask = (
... | 62,486 |
def show_secret(item):
"""
Show a secret for X seconds and erase it from the screen
"""
try:
print("* The password will be hidden after %s seconds." %
(global_scope['conf'].hideSecretTTL))
print('* The password is: %s' % (item.password), end="\r")
time.sleep(i... | 62,487 |
def analyze_data(fitsfn, observables_dir="", affine2d=None,
psf_offset_find_rotation = (0.0,0.0),
psf_offset_ff = None,
rotsearch_d=None,
set_pistons=None):
"""
returns: affine2d (measured or input),
... | 62,488 |
def exclude_glance_partition(role_mapping, node):
"""In case images_ceph used as glance image storage
no need to create partition /var/lib/glance
"""
if node.cluster.attributes.editable['storage'].get('images_ceph'):
images_ceph = (node.cluster.attributes['editable']['storage']
... | 62,489 |
def value_at_offset(obj_node, offset, dst_type):
"""
Perform (dst_type) (((char *) my_object) + offset)
"""
offset = ConstNode(offset, Py_ssize_t)
pointer = PointerFromObject(obj_node)
pointer = CoercionNode(pointer, char.pointer())
pointer = pointer_add(pointer, offset)
value_at_offset ... | 62,490 |
def step_id(value):
"""return the test id from the test step object"""
return f"{value.comment} {value.user_input}" | 62,491 |
def _attributes_equal(new_attributes, old_attributes):
"""
Compare attributes (dict) by value to determine if a state is changed
:param new_attributes: dict containing attributes
:param old_attributes: dict containing attributes
:return bool: result of the comparison between new_attributes and
... | 62,492 |
def test_ap_wps_upnp_web_oom(dev, apdev, params):
"""hostapd WPS UPnP web OOM"""
ap_uuid = "27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"
hapd = add_ssdp_ap(apdev[0], ap_uuid)
location = ssdp_get_location(ap_uuid)
url = urlparse(location)
urls = upnp_get_urls(location)
eventurl = urlparse(urls['eve... | 62,493 |
def get_pass_times(
start_time: datetime,
end_time: datetime,
pass_times_filename: PathLike = PASS_TIMES_FILENAME,
):
"""
Retreive array of datetimes of VIIRS passes within the given time interval, given initial period durations.
:param start_time: beginning of time interval (in UTC)
:param... | 62,494 |
def decode_utf8(text: str) -> str:
"""Eliminates encoded UTF-8 symbols in a text
Example: 2020%2D03%2D25 16%3A25%3A17%3A%2E0 --> 2020-03-25 16:25:17.0
Args:
text (str): Input text
Returns:
str: Decoded text
"""
with open(os.path.join(os.path.dirname(__file__), "decode_utf8", "l... | 62,495 |
def read_cmd_args():
"""Read command line arguments."""
if len(sys.argv) != 12:
print("[ERR] Invalid number of command line arguments!")
_usage()
sys.exit(1)
# fcst_syr
try:
fcst_syr = int(sys.argv[1])
except ValueError:
print(f"[ERR] Invalid argument for fc... | 62,496 |
def _recover_bin_edges(wave):
"""Recover the edges of a set of wavelength bins given the bin centers.
This function is designed to work for standard linear binning along with
other more exotic forms of binning such as logarithmic bins. We do a second
order correction to try to get the bin widths as acc... | 62,497 |
def structured(inputSchema, outputSchema, schema_store=None,
ignore_body=False):
"""
Decorate a Klein-style endpoint method so that the request body is
automatically decoded and the response body is automatically encoded.
Items in the object encoded in the request body will be passed to
... | 62,498 |
def run_check_dist_check(grouped_files, dist_dir):
"""
check if all dist files created and if all means are appropriate
:param grouped_files: (list) list of protein, target, start groups
:param dist_dir: (string) directiory to place distances
:return:
"""
if len(os.listdir(dist_dir)) != len(... | 62,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.