content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def unreduced_coboundary(morse_complex, akq, cell_ix):
""" Helper """
return unreduced_cells(akq, morse_complex.get_coboundary(cell_ix)) | 31,100 |
def __align(obj: Union[Trace, EventLog], pt: ProcessTree, max_trace_length: int = 1,
max_process_tree_height: int = 1, parameters=None):
"""
this function approximates alignments for a given event log or trace and a process tree
:param obj: event log or single trace
:param pt: process tree
... | 31,101 |
def scanProgramTransfersCount(program, transfersCount=None, address=None, args={}):
"""
Scan pools by active program, sort by transfersCount
"""
return resource.scan(**{**{
'type': 'pool',
'index': 'activeProgram',
'indexValue': program,
'sort': 'transfersCount',
... | 31,102 |
def def_use_error(node, report=MAIN_REPORT):
"""
Checks if node is a name and has a def_use_error
Args:
node (str or AstNode or CaitNode): The Name node to look up.
report (Report): The report to attach data to. Defaults to MAIN_REPORT.
Returns:
True if the given name has a def_... | 31,103 |
def task_new_callback(data):
"""
On receiving a task:new event, add a task to an asset in the
Avalon mongodb.
"""
# Log in to API
gazu.client.set_host("{0}/api".format(os.environ["GAZU_URL"]))
gazu.log_in(os.environ["GAZU_USER"], os.environ["GAZU_PASSWD"])
task = gazu.task.get_task(dat... | 31,104 |
def get_ref_inst(ref):
"""
If value is part of a port on an instance, return that instance,
otherwise None.
"""
root = ref.root()
if not isinstance(root, InstRef):
return None
return root.inst | 31,105 |
def not_found(error):
"""
Renders 404 page
:returns: HTML
:rtype: flask.Response
"""
view_args["title"] = "Not found"
return render_template("404.html", args=view_args), 404 | 31,106 |
def xml_escape(x):
"""Paranoid XML escaping suitable for content and attributes."""
res = ''
for i in x:
o = ord(i)
if ((o >= ord('a')) and (o <= ord('z'))) or \
((o >= ord('A')) and (o <= ord('Z'))) or \
((o >= ord('0')) and (o <= ord('9'))) or \
... | 31,107 |
def read_tab(filename):
"""Read information from a TAB file and return a list.
Parameters
----------
filename : str
Full path and name for the tab file.
Returns
-------
list
"""
with open(filename) as my_file:
lines = my_file.readlines()
return lines | 31,108 |
def build_model(stage_id, batch_size, real_images, **kwargs):
"""Builds progressive GAN model.
Args:
stage_id: An integer of training stage index.
batch_size: Number of training images in each minibatch.
real_images: A 4D `Tensor` of NHWC format.
**kwargs: A dictionary of
'start_height': An... | 31,109 |
def reflect(engine):
"""
Reflects the database tables.
"""
metadata.reflect(bind=engine)
LOGGER.info("Reflected %d tables", len(metadata.tables)) | 31,110 |
def int2(c):
""" Parse a string as a binary number """
return int(c, 2) | 31,111 |
def info():
"""Shows info, a short summary of intro section."""
st.sidebar.markdown("""
---\n
[International University - VNU-HCM](https://hcmiu.edu.vn/en/)\n
[Streamlit](https://www.streamlit.io/)\n
[GitHub](https://github.com/minhlong94/SWE_IT076IU)\n
""") | 31,112 |
def from_serializer(
serializer: serializers.Serializer,
api_type: str,
*,
id_field: str = "",
**kwargs: Any,
) -> Type[ResourceObject]:
"""
Generate a schema from a DRF serializer.
:param serializer: The serializer instance.
:param api_type: The JSON API resource type.
:param i... | 31,113 |
def user_input():
"""Input prompt"""
# Printing statement to signal the user that we are waiting for input.
user_input = input("Please type in your name\n")
# Printing a message based on the input.
print(f"Welcome, {user_input}!") | 31,114 |
def test_discarded_duplicate_children():
"""Verify that duplicate children are not added twice"""
trials_history = TrialsHistory()
trials = [DummyTrial(i, []) for i in range(3)]
trials_history.update(trials)
assert trials_history.children == [0, 1, 2]
trials = [DummyTrial(i, [trials[i].id]) for... | 31,115 |
def print_safety_margin(local_map, divisions):
"""Prints the safety margin of the given local_map, where each cell is divided into divisions^2 components.
Args:
local_map (2D np.ndarray): the local map
divisions (int): each grid cell will have a safety_margin sample taken for divisions^2 times
... | 31,116 |
def inv_rotate_pixpts(pixpts_rot, angle):
"""
Inverse rotate rotated pixel points to their original positions.
Keyword arguments:
pixpts_rot -- namedtuple of numpy arrays of x,y pixel points rotated
angle -- rotation angle in degrees
Return value:
pixpts -- namedtuple of numpy arrays of pi... | 31,117 |
def logged(func=None, level=logging.DEBUG, name=None, msg=None):
"""Decorator to log the function, with the duration.
Args:
-----
func (function): the function to log
level (logging.OBJECT): INFO, DEBUG, WARNING ...
name (str): name of the logger
msg ... | 31,118 |
def properties(classes):
"""get all property (p-*, u-*, e-*, dt-*) classnames
"""
return [c.partition("-")[2] for c in classes if c.startswith("p-")
or c.startswith("u-") or c.startswith("e-") or c.startswith("dt-")] | 31,119 |
def test_main():
"""Mock to ensure program flow."""
with patch.object(base, "get_all_git_repos") as mock_parse:
with patch.object(base, "display_credit", return_value=(0, 1)) as disp:
base.main()
mock_parse.assert_called_once_with(sys.argv)
assert disp.called | 31,120 |
def adapt_p3_histogram(codon_usages, purge_unwanted=True):
"""Returns P3 from each set of codon usage for feeding to hist()."""
return [array([c.positionalGC(purge_unwanted=True)[3] for c in curr])\
for curr in codon_usages] | 31,121 |
def send_data_wrapper():
""" wrapper to send data """
logger.debug("--- Chunk creation time: %s seconds ---" % (time.time() - track['start_time']))
send_data_to_if(track['current_row'], track['mode'])
track['chunk_count'] += 1
reset_track() | 31,122 |
def handle_logout_response(response):
"""
Handles saml2 logout response.
:param response: Saml2 logout response
"""
if len(response) > 1:
# Currently only one source is supported
return HttpResponseServerError("Logout from several sources not supported")
for entityid, logout_inf... | 31,123 |
def get_value_beginning_of_year(idx, col, validate=False):
"""
Devuelve el valor de la serie determinada por df[col] del
primer día del año del índice de tiempo 'idx'.
"""
beggining_of_year_idx = date(year=idx.date().year, month=1, day=1)
return get_value(beggining_of_year_idx, col, validate) | 31,124 |
def doc2vec_embedder(corpus: List[str], size: int = 100, window: int = 5) -> List[float]:
"""
Given a corpus of texts, returns an embedding (representation
of such texts) using a fine-tuned Doc2Vec embedder.
ref: https://radimrehurek.com/gensim/models/doc2vec.html
"""
logger.info(f"Training Do... | 31,125 |
def PremIncome(t):
"""Premium income"""
return SizePremium(t) * PolsIF_Beg1(t) | 31,126 |
def _setter_name(getter_name):
""" Convert a getter name to a setter name.
"""
return 'set' + getter_name[0].upper() + getter_name[1:] | 31,127 |
def get_bel_node_by_pathway_name():
"""Get Reactome related eBEL nodes by pathway name."""
pathway_name = request.args.get('pathway_name')
sql = f'''SELECT
@rid.asString() as rid,
namespace,
name,
bel,
reactome_pathways
FROM
pro... | 31,128 |
def get_model(model_file, log=True):
"""Load a model from the specified model_file."""
model = load_model(model_file)
if log:
print('Model successfully loaded on rank ' + str(hvd.rank()))
return model | 31,129 |
def variable_op(shape, dtype, name="Variable", set_shape=True, container="",
shared_name=""):
"""Deprecated. Used variable_op_v2 instead."""
if not set_shape:
shape = tensor_shape.unknown_shape()
ret = gen_state_ops.variable(shape=shape, dtype=dtype, name=name,
c... | 31,130 |
def main():
""" Script with tools and setup configuration for Linux machines """
pass | 31,131 |
def schedule_delete_default_vpc(account_id, region, role):
"""Schedule a delete_default_vpc on a thread
:param account_id: The account ID to remove the VPC from
:param org_session: The Organization class instance
:param region: The name of the region the VPC is resided
"""
ec2_client = role.clie... | 31,132 |
def usage(rc):
"""
Print usage for this script to stdout.
Parameters
rc: Exit status (int)
"""
str = "\n"
str = str + "pdb2pqr (Version %s)\n" % __version__
str = str + "\n"
str = str + "This module takes a PDB file as input and performs\n"
str = str + "optimi... | 31,133 |
def main(opt):
"""
Tests SRVP.
Parameters
----------
opt : DotDict
Contains the testing configuration.
"""
##################################################################################################################
# Setup
#############################################... | 31,134 |
def _sample_weight(kappa, dim, num_samples):
"""Rejection sampling scheme for sampling distance from center on
surface of the sphere.
"""
dim = dim - 1 # since S^{n-1}
b = dim / (np.sqrt(4.0 * kappa ** 2 + dim ** 2) + 2 * kappa)
x = (1.0 - b) / (1.0 + b)
c = kappa * x + dim * np.log(1 - x *... | 31,135 |
def variable_time_collate_fn3(
batch,
args,
device=torch.device("cpu"),
data_type="train",
data_min=None,
data_max=None,
):
"""
Expects a batch of time series data in the form of (record_id, tt, vals, mask, labels) where
- record_id is a patient id
- tt is a 1-dimensional ten... | 31,136 |
def merge_action(args):
"""Entry point for the "merge" CLI command."""
complete_func(
print, args.elf, args.m4hex, args.m0hex
) | 31,137 |
def run_map_reduce(files, mapper, n):
"""Runner to execute a map-reduce reduction of cowrie log files using mapper and files
Args:
files (list of files): The cowrie log files to be used for map-reduce reduction.
mapper (MapReduce): The mapper processing the files using map_func and redu... | 31,138 |
def metadata_record_dictize(pkg, context):
"""
Based on ckan.lib.dictization.model_dictize.package_dictize
"""
model = context['model']
is_latest_revision = not(context.get('revision_id') or
context.get('revision_date'))
execute = _execute if is_latest_revision else ... | 31,139 |
def is_data_by_filename(fname):
"""
TODO
this is super adhoc. FIXME
"""
return "Run201" in fname | 31,140 |
async def 서버상태(ctx):
"""Show server's status
It shows
Server's CPU Usage
Server's RAM Usage
"""
embed = discord.Embed(title="현재 서버 상태")
cpu = str(psutil.cpu_percent())
ram = str(psutil.virtual_memory())
print(cpu + "\n" + ram)
embed.add_field(name="CPU Usage: ", value=cpu, ... | 31,141 |
def test_add_metrics_distributed() -> None:
"""Test add_metrics_distributed."""
# Prepare
history = History()
# Execute
history.add_metrics_distributed(rnd=0, metrics={"acc": 0.9})
# Assert
assert len(history.losses_distributed) == 0
assert len(history.losses_centralized) == 0
asse... | 31,142 |
def colorbar_set_label_parallel(cbar,label_list,hpos=1.2,vpos=-0.3,
ha='left',va='center',
force_position=None,
**kwargs):
"""
This is to set colorbar label besie the colorbar.
Parameters:
-----------
cb... | 31,143 |
def read_csv(file, tz):
"""
Reads the file into a pandas dataframe, cleans data and rename columns
:param file: file to be read
:param tz: timezone
:return: pandas dataframe
"""
ctc_columns = {1: 'unknown_1',
2: 'Tank upper', # temperature [deg C]
3: 'u... | 31,144 |
def get_tokenizer_from_saved_model(saved_model: SavedModel) -> SentencepieceTokenizer:
"""
Get tokenizer from tf SavedModel.
:param SavedModel saved_model: tf SavedModel.
:return: tokenizer.
:rtype: SentencepieceTokenizer
"""
# extract functions that contain SentencePiece somewhere in ther... | 31,145 |
def heapq_merge(*iters, **kwargs):
"""Drop-in replacement for heapq.merge with key support"""
if kwargs.get('key') is None:
return heapq.merge(*iters)
def wrap(x, key=kwargs.get('key')):
return key(x), x
def unwrap(x):
_, value = x
return value
iters = tuple((wrap... | 31,146 |
def parse_args():
""" parse CLI arguments
Parameters
----------
args : :class: `list`
A list of arguments; generally, this should be ``sys.argv``.
Resturns
----------
:class: `argpase.Namespace`
An object returned by ``argparse.parse_args``.
"""
parser = argparse.... | 31,147 |
def parse_archive_links(html):
"""Parse the HTML of an archive links page."""
parser = _ArchiveLinkHTMLParser()
parser.feed(html)
return parser.archive_links | 31,148 |
def processing_requests():
"""
Handles the request for what is in processing.
:return: JSON
"""
global processing
global processing_mutex
rc = []
response.content_type = "application/json"
with processing_mutex:
if processing:
rc.append(processing)
return j... | 31,149 |
def detect_feature(a, b=None):
"""
Detect the feature used in a relay program.
Parameters
----------
a : Union[tvm.relay.Expr, tvm.IRModule]
The input expression or module.
b : Optional[Union[tvm.relay.Expr, tvm.IRModule]]
The input expression or module.
The two arguments can... | 31,150 |
def get_urls_from_loaded_sitemapindex(sitemapindex):
"""Get all the webpage urls in a retrieved sitemap index XML"""
urls = set()
# for loc_elem in sitemapindex_elem.findall('/sitemap/loc'):
for loc_elem in sitemapindex.findall('//{http://www.sitemaps.org/schemas/sitemap/0.9}loc'):
urls.update(g... | 31,151 |
def genLinesegsnp(verts, colors = [], thickness = 2.0):
"""
gen objmnp
:param objpath:
:return:
"""
segs = LineSegs()
segs.setThickness(thickness)
if len(colors) == 0:
segs.setColor(Vec4(.2, .2, .2, 1))
else:
segs.setColor(colors[0], colors[1], colors[2], colors[3])... | 31,152 |
def ncores_traditional_recommendation_process(user_model_df, user_model_genres_distr_df, user_expected_items_df,
items_mapping_dict, user_blocked_items_df, recommender_label,
popularity_df, transaction_mean, control_count=None, ... | 31,153 |
def enhance_puncta(img, level=7):
"""
Removing low frequency wavelet signals to enhance puncta.
Dependent on image size, try level 6~8.
"""
if level == 0:
return img
wp = pywt.WaveletPacket2D(data=img, wavelet='haar', mode='sym')
back = resize(np.array(wp['d'*level].data), img.shape,... | 31,154 |
def thumbnail(img, size = (1000,1000)):
"""Converts Pillow images to a different size without modifying the original image
"""
img_thumbnail = img.copy()
img_thumbnail.thumbnail(size)
return img_thumbnail | 31,155 |
def test_cray_ims_deleted_base(cli_runner, rest_mock):
""" Test cray ims base command """
runner, cli, _ = cli_runner
result = runner.invoke(cli, ['ims', 'deleted'])
assert result.exit_code == 0
outputs = [
"public-keys",
"recipes",
"images",
]
compare_output(output... | 31,156 |
def _MapAnomaliesToMergeIntoBug(dest_issue, source_issue):
"""Maps anomalies from source bug to destination bug.
Args:
dest_issue: an IssueInfo with both the project and issue id.
source_issue: an IssueInfo with both the project and issue id.
"""
anomalies, _, _ = anomaly.Anomaly.QueryAsync(
bug_... | 31,157 |
def calculate_new_ratings(P1, P2, winner, type):
"""
calculate and return the new rating/rating_deviation for both songs
Args:
P1 (tuple or float): rating data for song 1
P2 (tuple or float): rating data for song 2
winner (str): left or right
type (str): elo or glicko
... | 31,158 |
def age(a):
"""age in yr - age(scale factor)"""
return _cosmocalc.age(a) | 31,159 |
def cli_parser() -> argparse.ArgumentParser:
"""Create parser with set arguments."""
parser = argparse.ArgumentParser(
# Also possible to add prog title to output,
# if ommitted the filename is used (e.g. cli-simple.py)
prog="CLI-COPERNICUS-DOWNLOAD",
description="A simple exampl... | 31,160 |
def test_get_policies_for_resource_for_non_existing_index():
""" Testing get_policies_for_resource
for non existing index 'not_index'.
"""
cluster = False
indices = ['not_index']
resource_policies = get_policies_for_resource(
cluster, indices, SAMPLE_POLICIES
)
expected_res... | 31,161 |
def run_tests():
# type: () -> None
"""Run all the tests."""
# my-py's typeshed does not have defaultTestLoader and TestLoader type information so suppresss
# my-py type information.
all_tests = unittest.defaultTestLoader.discover(start_dir="tests") # type: ignore
runner = XMLTestRunner(verbo... | 31,162 |
def _replace_ext_area_by_impedances_and_shunts(
net_eq, bus_lookups, impedance_params, shunt_params, net_internal,
return_internal, show_computing_time=False, calc_volt_angles=True, imp_threshold=1e-8):
"""
This function implements the parameters of the equivalent shunts and equivalent impedance... | 31,163 |
def _read_array(raster, band, bounds):
""" Read array from raster
"""
if bounds is None:
return raster._gdal_dataset.ReadAsArray()
else:
x_min, y_min, x_max, y_max = bounds
forward_transform = affine.Affine.from_gdal(*raster.geo_transform)
reverse_transform = ~forward_tr... | 31,164 |
def makePlayerInfo(pl_name):
""" Recupere toutes les infos d'un player
:param arg1: nom du joueur
:type arg1: chaine de caracteres
:return: infos du player : budget, profit & ventes (depuis le debut de la partie), boissons a vendre ce jour
:rtype: Json
"""
info = calculeMoneyInfo(pl_name, 0)
drinkInfo = ma... | 31,165 |
def _FinalizeHeaders(found_fields, headers, flags):
"""Helper to organize the final headers that show in the report.
The fields discovered in the user objects are kept separate from those
created in the flattening process in order to allow checking the found
fields against a list of those expected. Unexpected... | 31,166 |
def create_zip(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a ZIP archive with the zipfile Python module."""
try:
with zipfile.ZipFile(archive, 'w') as zfile:
for filename in filenames:
if os.path.isdir(filename):
write_director... | 31,167 |
def count_documents(project, commit_interval):
"""Calculate counts for documents.
Arguments:
project (Project): The ``Project`` to run counts for.
commit_interval (int): This method will commit the counts every this
many times.
"""
count = 0
logger = logging.getLogger(__... | 31,168 |
def test_create(random, tmpdir):
"""Test if new virtual environments can be created."""
path = str(tmpdir.join(random))
venv = api.VirtualEnvironment(path)
try:
venv.create()
except subprocess.CalledProcessError as exc:
assert False, exc.output
assert tmpdir.join(random).check() | 31,169 |
def get_outmost_points(contours):
"""Get the bounding rectangle of all the contours"""
all_points = np.concatenate(contours)
return get_bounding_rect(all_points) | 31,170 |
def dhcp_release_packet(eth_dst='ff:ff:ff:ff:ff:ff',
eth_src='00:01:02:03:04:05',
ip_src='0.0.0.0',
ip_dst='255.255.255.255',
src_port=68,
dst_port=67,
bootp_chaddr='00:01:02:03:04:05',
... | 31,171 |
def get_unique_dir(log_dir='', max_num=100, keep_original=False):
"""Get a unique dir name based on log_dir.
If keep_original is True, it checks the list
{log_dir, log_dir-0, log_dir-1, ..., log_dir-[max_num-1]}
and returns the first non-existing dir name. If keep_original is False
then log_dir is ... | 31,172 |
def dcfc_30_e_plus_360(start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:
"""
Computes the day count fraction for the "30E+/360" convention.
:param start: The start date of the period.
:param asof: The date which the day count fraction to be calculated as of.
:param end... | 31,173 |
def generate_meta_config(output_file='../data/meta_config.json'):
"""
Generate a meta configuration JSON file for the data generation pipeline.
This spits out a valid template of a meta configuration file as the one
required by the `WaveformConfigGenerator`. Just run this once to have a
valid templ... | 31,174 |
def get_current_func_info_by_traceback(self=None, logger=None) -> None:
"""
通过traceback获取函数执行信息并打印
use eg:
class A:
def a(self):
def cc():
def dd():
get_current_func_info_by_traceback(self=self)
dd()
... | 31,175 |
def augment_timeseries_shift(x: tf.Tensor, max_shift: int = 10) -> tf.Tensor:
"""Randomly shift the time series.
Parameters
----------
x : tf.Tensor (T, ...)
The tensor to be augmented.
max_shift : int
The maximum shift to be randomly applied to the tensor.
Returns
-------
... | 31,176 |
def main(argv):
"""
Main function.
"""
imageRawData = pre.imageprepare(argv)
imagevalue = prefictint(imageRawData)
print("识别结果是:", imagevalue) | 31,177 |
def test_sae_pk_sec_2(dev, apdev):
"""SAE-PK with Sec 2"""
check_sae_pk_capab(dev[0])
dev[0].set("sae_groups", "")
ssid = "SAE-PK test"
pw = "dwxm-zv66-p5ue"
m = "431ff8322f93b9dc50ded9f3d14ace22"
pk = "MHcCAQEEIAJIGlfnteonDb7rQyP/SGQjwzrZAnfrXIm4280VWajYoAoGCCqGSM49AwEHoUQDQgAEeRkstKQV+FSA... | 31,178 |
def endpoint(fun):
"""Decorator to denote a method which returns some result to the user"""
if not hasattr(fun, '_zweb_post'):
fun._zweb_post = []
fun._zweb = _LEAF_METHOD
fun._zweb_sig = _compile_signature(fun, partial=False)
return fun | 31,179 |
def show(path, file, counter):
"""Shows file where pattern was find."""
if counter > 0:
print(os.path.join(path, file), ": Nombre d'occurences :", counter) | 31,180 |
def test_query_album_1():
"""Test query --album"""
import json
import os
import os.path
import osxphotos
from osxphotos.cli import query
runner = CliRunner()
cwd = os.getcwd()
result = runner.invoke(
query,
[
"--json",
"--db",
os.... | 31,181 |
def focal_prob(attn, batch_size, queryL, sourceL):
"""
consider the confidence g(x) for each fragment as the sqrt
of their similarity probability to the query fragment
sigma_{j} (xi - xj)gj = sigma_{j} xi*gj - sigma_{j} xj*gj
attn: (batch, queryL, sourceL)
"""
# -> (batch, queryL, sourceL, ... | 31,182 |
def get_fibonacci_iterative(n: int) -> int:
"""
Calculate the fibonacci number at position 'n' in an iterative way
:param n: position number
:return: position n of Fibonacci series
"""
a = 0
b = 1
for i in range(n):
a, b = b, a + b
return a | 31,183 |
def get_sample_content(filename):
"""Return sample content form file."""
with open(
"tests/xml/{filename}".format(
filename=filename), encoding="utf-8") as file:
return file.read() | 31,184 |
def create_contrasts(task):
"""
Create a contrasts list
"""
contrasts = []
contrasts += [('Go', 'T', ['GO'], [1])]
contrasts += [('GoRT', 'T', ['GO_rt'], [1])]
contrasts += [('StopSuccess', 'T', ['STOP_SUCCESS'], [1])]
contrasts += [('StopUnsuccess', 'T', ['STOP_UNSUCCESS'], [1])]
c... | 31,185 |
def update_anomaly_pred_folder(pred_folder, save_path, brain_mask_folder, brain_as_nifti, data_path, print_progress=False, rot=True):
"""
Adjust Anomaly segmentation predictions on a folder organised as follow : pred folder contains sub-folder for each volume
prediction as slices in XX_anomalies.bmp and ano... | 31,186 |
def project(raster_path, boxes):
"""Project boxes into utm"""
with rasterio.open(raster_path) as dataset:
bounds = dataset.bounds
pixelSizeX, pixelSizeY = dataset.res
#subtract origin. Recall that numpy origin is top left! Not bottom left.
boxes["left"] = (boxes["xmin"] * pixelSizeX) +... | 31,187 |
def mean_relative_error(preds: Tensor, target: Tensor) -> Tensor:
"""
Computes mean relative error
Args:
preds: estimated labels
target: ground truth labels
Return:
Tensor with mean relative error
Example:
>>> from torchmetrics.functional import mean_relative_error... | 31,188 |
async def shutdown():
"""Cleanly prepare for, and then perform, shutdown of the bot.
This currently:
- expires all non-saveable reaction menus
- logs out of discord
- saves all savedata to file
"""
menus = list(bbGlobals.reactionMenusDB.values())
for menu in menus:
if not menu.s... | 31,189 |
def test_runs01():
"""runs"""
out = getoutput('{} -s 3 {}'.format(prg, const))
expected = open('test-outs/const.seed3.width70.len500').read()
assert out.rstrip() == expected.rstrip() | 31,190 |
def run():
""" Run the full script step-by-step"""
# Load data
df_sessions = read_sessions_data()
df_engagements = read_engagements_data()
print(df_sessions.head())
print(df_engagements.head())
# Transform data
df_engagements = filter_for_first_engagements(df_engagements)
df = merge_... | 31,191 |
def render_dendrogram(dend: Dict["str", Any], plot_width: int, plot_height: int) -> Figure:
"""
Render a missing dendrogram.
"""
# list of lists of dcoords and icoords from scipy.dendrogram
xs, ys, cols = dend["icoord"], dend["dcoord"], dend["ivl"]
# if the number of columns is greater than 20,... | 31,192 |
def sort_by_fullname(data: List[dict]) -> List[dict]:
""" sort data by full name
:param data:
:return:
"""
logging.info("Sorting data by fullname...")
try:
data.sort(key=lambda info: info["FULL_NAME"], reverse=False)
except Exception as exception:
logging.exception(exception... | 31,193 |
def cityscapes_txt(root, data_folder, split):
"""
:param root: str, root directory
:param data_folder: str, image(leftImg8bit) or label(gtFine_labelIds)
:param split: str, train, eval, test
:return: txt file of files paths
"""
im_dir: str = os.path.join(root, data_folder, split)
if not ... | 31,194 |
def get_vrf_interface(device, vrf):
""" Gets the subinterfaces for vrf
Args:
device ('obj'): device to run on
vrf ('str'): vrf to search under
Returns:
interfaces('list'): List of interfaces under specified vrf
None
Raises:
None
... | 31,195 |
def rsptext(rsp,subcode1=0,subcode2=0,erri='',cmd='',subcmd1='',subcmd2=''):
""" Adabas response code to text conversion """
global rspplugins
if rsp in rspplugins:
plugin = rspplugins[rsp] # get the plugin function
return plugin(rsp, subcode1=subcode1, subcode2=subcode2,
... | 31,196 |
def new_event_notification(producer_url):
"""Pull data from producer when notified"""
enqueued_method = 'frappe.event_streaming.doctype.event_producer.event_producer.pull_from_node'
jobs = get_jobs()
if not jobs or enqueued_method not in jobs[frappe.local.site]:
frappe.enqueue(enqueued_method, queue='default', **... | 31,197 |
def to_dataframe(data: xr.DataArray, *args, **kwargs) -> pd.DataFrame:
"""
Replacement for `xr.DataArray.to_dataframe` that adds the attrs for the given
DataArray into the resultant DataFrame.
Parameters
----------
data : xr.DataArray
the data to convert to DataFrame
Returns
--... | 31,198 |
def setup_logging(
default_path='logging.yaml',
default_level=logging.INFO,
env_key='LOG_CFG'
):
"""Setup logging configuration from a yaml file.
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with ... | 31,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.