content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_story(): # type: () -> Story """Get Story in session.""" return session[STORY_KEY]
d47b20ee0daca77240f92c94e227354f52f3fe8b
3,622,400
def align_vector_to_another(a=np.array([0, 0, 1]), b=np.array([1, 0, 0])): """Aligns vector a to vector b with axis angle rotation""" if np.array_equal(a, b): return None, None axis_ = np.cross(a, b) axis_ = axis_ / np.linalg.norm(axis_) angle = np.arccos(np.dot(a, b)) return axis_, ang...
4596d30b125f3a4d1bb1f7b06fcbb46368faf5ec
3,622,401
from typing import Sequence def rand_seq(alphabet, size, p=None): """Generate a random :class:`Sequence` of the given length from the given :class:`Alphabet`. Keyword Args: alphabet (Alphabet) size (int): The length of the randomly generated sequence. p (list): The discrete probab...
c8dd4b1a738489dd7a77918a6044a2eec56ff204
3,622,402
from pymantic.primitives import Literal def en(value): """Returns an RDF literal from the en language for the given value.""" return Literal(value, language='en')
4e3ff4a1a6a2965fd8a5acc81ed866e4b1aea9c7
3,622,403
import tempfile def minimal_sphinx_app(configuration=None, sourcedir=None): """Create a minimal Sphinx environment; loading sphinx roles, directives, etc. """ class MockSphinx(Sphinx): """Minimal sphinx init to load roles and directives.""" def __init__(self, confoverrides=None, srcdir=N...
5ad03e7def4958ee47e1ed083f9087be10fcd8e5
3,622,404
def add_sppc_args(parser): """Add args of SPP Container to app.""" parser.add_argument( '--dist-name', type=str, default='ubuntu', help="Name of Linux distribution") parser.add_argument( '--dist-ver', type=str, default='latest', help="Version ...
9458603e0ce6717858c2d844db85b159bff8714e
3,622,405
from typing import Iterable import re def rank4_naming(proteins_available: Iterable[str], best_match_protein_name: str) -> str: """ Given a list of proteins available as well as the best match name the function returns predicted name In this example the function extracts the first three letter patter...
ed3fe9f2563aa6cc808a8d4196c628872c2a1369
3,622,406
def init_infected_symptomatic_20(): """ Real Name: b'init Infected symptomatic 20' Original Eqn: b'0' Units: b'person' Limits: (None, None) Type: constant b'' """ return 0
c0cd99a5ce5180302946c54daef2d5bcb735cca2
3,622,407
def improve_p(time, b, I): """ calculate solution of Kolmogorov equation """ ret = odeint(deriv_improve_kolmog, [1, 0, 0], time, args=(b, I)) P_S, P_I, P_R = ret.T return P_S, P_I, P_R
b1bb905f1f00411aa344a87378b1b0a689674bc4
3,622,408
def has_singularity(order): """ Tests order for a 'Singularity', or a common reduction error resulting in huge counts""" order = order[4:-4] order_c = np.convolve(np.abs(order), [1, 1]) big = np.where(order_c > 500)[0] zero_crossings = np.where(np.diff(np.sign(order)))[0] return True if np.inter...
e9c66f7e29aa53dd7cf63775d4d5e61fe6ff2a95
3,622,409
import math def get_exact_angle(pt1, pt2): """ Given two cardinal points, returns the corresponding angle in *radians*. Args: * **pt1** (tuple): Point 1 * **pt2** (tuple): Point 2 Returns: float Angle (in radians) Example:: import picwriter.toolkit as tk ...
fea71b45bfdb2935caa619390959aa0dc1be917d
3,622,410
def _perceptive_hash(file_path, hash_size = 8): """Calculates a hash-value from an image Conversion uses a resized, grayscaled pixel-array of the image, converting the pixel-array to a number-array (differences between neighboring pixels) and finally converting these values to a hex-string of length ha...
be2363f084d3bdb5b360f849315a7b266e4aafee
3,622,411
def embed(x, vsz, dsz, initializer, finetune=True, scope="LUT"): """Perform a lookup table operation while freezing the PAD vector. Use the initializer to set the weights :param x: The input to this operation :param vsz: The size of the input vocabulary :param dsz: The output size or embedding dimensi...
b599db31526c851c370f12fd39e99d8a3899781d
3,622,412
def make_drf_request(request: HttpRequest = None, headers: dict = None): """ The request object made by APIRequestFactory is `WSGIRequest` which doesn't have `.query_params` or `.data` method as recommended by DRF. It only gets "upgraded" to DRF `Request` class after passing through the `APIView`, ...
31743159d452ce0e1cf8aa76182555a25f308c2c
3,622,413
def is_quit_event(event): """ Returns True if provided event is a quit event. :param event: Any pygame event. :return: True if QUIT signal is given, or ESC is pressed, or CMD + Q is pressed, or ALT + F4 is pressed. """ if event.type == pygame.QUIT: return True elif event.type == ...
57f4f884b43f6aa2a45e730f581269895f46a45e
3,622,414
def split_data(x, y, ratio, seed=1): """split the dataset based on the split ratio.""" # set seed np.random.seed(seed) # generate random indices num_row = len(y) indices = np.random.permutation(num_row) index_split = int(np.floor(ratio * num_row)) index_tr = indices[: index_split] in...
a1c51bebc53646459542047710cc547673a02c68
3,622,415
def trace_downstream( input_layer, split_distance=None, split_units="Kilometers", max_distance=None, max_distance_units="Kilometers", bounding_polygon_layer=None, source_database=None, generalize=True, output_name=None, context=None, ...
da0945b734c81b0f53fc9acf204db866eb9e4c82
3,622,416
from typing import Any from pathlib import Path def get_object_filepath(object: Any) -> str: """ Get object's filepath. """ path = Path(object.__code__.co_filename).absolute() try: filepath = "./" + path.relative_to(Path.cwd()).as_posix() except ValueError: filepath = path.as_p...
de30939b8699e812e712b4e5eea32cf6fe80eb4d
3,622,417
def linear_timeseries(start_value: float = 0, end_value: float = 1, length: int = 10, freq: str = 'D', start_ts: pd.Timestamp = pd.Timestamp('2000-01-01')) -> TimeSeries: """ Creates a TimeSeries with a starting value of `st...
4f41cb5dbba21cff1cb9496b6c8dda072a6a8ab3
3,622,418
import requests def get_blog_html(url: str) -> str: """ get the raw html of the blog post """ try: response = requests.get(url) if response.ok: return response.text else: return None except Exception as e: print(f"[!] Failed to get blog html: {str(e)...
8a155967919757db8f12dfabeee050ede2a04cfa
3,622,419
import math def calculate_mwp_mag(peak, epicentral_distance): """ Calculate Mwp magnitude. .. seealso:: [Tsuboi1999]_ and [Tsuboi1995]_ :type peak: float :param peak: Peak value of integral of displacement seismogram. :type epicentral_distance: float :param epicentral_distance: Great-cir...
5a12d8284fd0f133cd0cc03f42662f43eef95d0b
3,622,420
from unittest.mock import call def get_all_services(resource_root, cluster_name="default", view=None): """ Get all services @param resource_root: The root Resource object. @param cluster_name: Cluster name @return: A list of ApiService objects. """ return call(resource_root.get, SERVICES_PATH % (c...
781274c296c2c203dfa28e38b46492913cd7faa1
3,622,421
def _depgrep_rel_disjunction_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node from the disjunction of several other such lambda functions. """ # filter out the pipe tokens = [x for x in tokens if x != "|"] # print 'relation disjunction tokens: ', t...
1daad27c573ff7e36083d422aacd9d232ecef32c
3,622,422
import re def bibtexToCoNLL(bibpath, writeToDisk = False, outpath = None, encoding = "latex", mapping = None, seqStruct = None): """ The function transforms a bibtex file in a simil-CoNLL dataset. In detail, it parses a bibtex file and returns lists similar to those returned b...
0824fd592f897c9b4a7f60eaae467fa875909ee7
3,622,423
def get_buff(status): """获取人物指定的BUFF""" dm.use_dict(2) result = dm.find_str(142, 11, 1419, 48, status, color='C1E2DA-3B1D23|E4E0D7-1B1F28', sim=0.8) if result[0] > -1: return True
1bbda18e36de3eb39ad11b57ad9e6d4e1caf94b1
3,622,424
import struct def get_header_data(header_data_map: dict = {}, ecat_file: str = '', byte_offset: int = 0): """ Collects the header data from an ecat file, by default starts at byte position 0 (aka byte offset) for any header that is not the main header this offset will need to be provided :param header...
22af6780a9dd4197232ec80d42ceec729f1de107
3,622,425
import socket def _find_unused_port(): """ Finds a port that's available. Unfortunately, this port may not be available by the time the subprocess uses it, but this generally works. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.bind(('127.0.0.1', 0)) sock.listen(socket.SOMAXCONN...
f715335d7e2bbc2a4a12cfb233e9d7a18fb6fdcf
3,622,426
def merge(batch, results): """ Merge clumped results files together """ merger = batch.new_job(name='merge-results') merger.image('ubuntu:18.04') if results: merger.command(f''' head -n 1 {results[0]} > {merger.ofile} for result in {" ".join(results)} do tail -n +2 "$result" >> {merg...
92037b34ff8db44381789f15518b5f44949b26a2
3,622,427
def model_with_buckets(encoder_inputs, decoder_inputs, targets, weights, buckets, seq2seq, softmax_loss_function=None, per_example_loss=False, name=None): """Create a sequence-to-sequence model with support for bucketing. The seq2seq argument is a function that defines ...
51455d3956f0117c23e50dad1250ba5727f779b9
3,622,428
import torch from typing import OrderedDict def torch_load_state_dict_without_module(ckp_file): """ this function using for load a model without module """ checkpoint = torch.load(ckp_file) state_dict =checkpoint['state_dict'] new_state_dict = OrderedDict() for k, v in state_dict.items():...
72f265b2087bd40d328d8760cc9668c9e6ccacf6
3,622,429
def resnet50c(config, norm_layer=nn.BatchNorm2D): """resnet50c implement The ResNet-50 [Heet al., 2016] with dilation convolution at last stage, ResNet-50 model Ref, https://arxiv.org/pdf/1512.03385.pdf Args: config (dict): configuration of network norm_layer: normalization layer t...
77864a3db2d50dc173564a69acb5e81d0cdab0a0
3,622,430
import json def set_parameters_in_cookie(response: Response) -> Response: """Set request parameters in the cookie, to use as future defaults.""" if response.status_code == status.HTTP_200_OK: data = {param: request.args[param] for param in PARAMS_TO_PERSIST if param in request.args} ...
ea186dc878a055f2c40143f1526af5c6200b71aa
3,622,431
def code_list_lengthener(code_list, parameter): """Ensures that code_list is long enough to accept an item in its parameter-th location""" while len(code_list) < parameter+1: code_list.append(0) return code_list
fd9a2d498ca1c679f44b0937a902bd95a7a882c8
3,622,432
import os import shutil def download_lua(args, download_dir): """Download the Lua tarball to the specified directory.""" full_version = CONFIG["specific_versions"][args.lua_version] if args.lua_version.startswith("luajit"): LOG.info("Downloading LuaJIT %s into `%s`...", full_version, download_dir...
dfad557122ee9618ecf8d8c7cf5c9e15a381f8c0
3,622,433
import json def invoice(request): """Returns all invoices""" auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT, ) client = QuickBooks( auth_client=auth_client, refresh_token=request.sessi...
59763a3bbe56fdef7f2372a3bdddfbb61af71b4a
3,622,434
def delete_user_account(): """ remove all character blueprint for current user """ if request.is_xhr: char_id = current_user.character_id try: delete_account(current_user) flash("Your account have been deleted.", 'info') return json_response('success', '', 200...
1867cfe34829f1f051d5008311c43de9fb8e0d1f
3,622,435
import unicodedata import re def unaccented_letters(s: str) -> str: """Return the letters of `s` with accents removed.""" s = unicodedata.normalize('NFKD', s) s = re.sub(r'[^\w -]', '', s) return s
e75b8929f8bd800ad4c79ae5688dea1067c351c5
3,622,436
import os import re from collections import defaultdict def load_ud_english(fpath): """Load a file from the UD English corpus Parameters ---------- fpath : str Path to UD corpus file ending in .conllu Output: Returns a list equal to length of total num of docs with ea...
b2e6d83a3e1a5cbb806c30915287cd2717510019
3,622,437
def smooth_imgs(env: aneurysm_utils.Environment, mr_imgs: list, fwhm=1) -> list: """Smooth images.""" niimg_likes = get_nift_like(env, mr_imgs) smoothed = [] for img in niimg_likes: smoothed.append( nilearn.image.smooth_img(img, fwhm=fwhm).get_data().astype("<f4") ) retu...
8f8d781494779b45135e72f710bf081f0e60f958
3,622,438
import ast def run_averecmd(ssh_client, node_ip, password, method, user='admin', args='', timeout=60): """Run averecmd on the vFXT controller connected via ssh_client.""" cmd = "averecmd --raw --no-check-certificate " + \ "--user {0} --password '{1}' --server {2} {3} {4}".format( ...
bc2fa37ed3197d1015bf48c026778486d6d355dd
3,622,439
def create_bout_ds_list( prefix, lengths=(6, 2, 4, 7), nxpe=4, nype=2, nt=1, guards={}, topology="core", syn_data_type="random", squashed=False, bout_v5=False, metric_3D=False, ): """ Mocks up a set of BOUT-like datasets. Structured as though they were produced b...
f24c93eb1e7c3910aeb824694aeea20305eed0a1
3,622,440
def parse_mapping_file(fp): """ """ ensp_to_hgnc = {} with open(fp, "r") as fh: for line in fh: line = line.rstrip() words = line.split() if(len(words) >= 4): ensp_to_hgnc[words[3]] = words[0] return ensp_to_hgnc
e3c47d9a73cf19eddd9efc8b4fb7840f5bda156b
3,622,441
def sort_group(indx, column1, column2): """ Parameters ---------- indx : integer column1 : list data type (contains strings of SOC NAMES / WORK STATES which need to be ordered.) column2 : list data type (contains integers which denote numbers of of certified applications.) Returns ------- sort_group : l...
6bc153d78be6c40a1c3b7324784f45fb9f01fbd4
3,622,442
import logging def rate_limit(auth, limit, period): """Rate limit main function""" if rate_request(auth, limit, timedelta(seconds=period)): raise exception.too_many_rquests() logging.info('✅ Request is allowed') return True
777fdbd8bf2e39e6c546aa52d2e17bb81320519d
3,622,443
def unflag_output_id(output_id: str) -> bool: """Sets the flag property of an IOPointer to false.""" store = Store(_db_uri) return store.set_io_pointer_flag(output_id, False)
9a9e7071335e5fc52e8b0aa51d78691e56f3f49c
3,622,444
import argparse def make_argument_parser() -> argparse.ArgumentParser: """Generic experiment parser. Generic parser takes the experiment yaml as the main argument, but has some options for reloading, etc. This parser can be easily extended using a wrapper method. Returns: argparse.parser ...
2b532e06bf86e827fc52838b33fe350aaa0aaeeb
3,622,445
def get_indicator_representation(row): """Convert binary indicator to list of assigned labels Parameters: ----------- row : List[{0,1}] binary indicator list whether i-th label is assigned or not Returns ------- np.array[int] list of assigned labels """ return np.w...
07a1fc42f748bc5ca964ed93db57d6a93112b764
3,622,446
def Uniform(*opts): """Uniform distribution over a finite list of options. Implemented as an instance of :obj:`Options` when the set of options is known statically, and an instance of `UniformDistribution` otherwise. """ if any(isinstance(opt, StarredDistribution) for opt in opts): return UniformDistribution(op...
386d2f701254e596f4aa1f50af456b6f31dda6c9
3,622,447
def TWM_p(pfreq, pmag, f0c): """ Two-way mismatch algorithm for f0 detection (by Beauchamp&Maher) [better to use the C version of this function: UF_C.twm] pfreq, pmag: peak frequencies in Hz and magnitudes, f0c: frequencies of f0 candidates returns f0, f0Error: fundamental frequency detected and...
50969163558a53021ea748550bda2fd6c2b167d7
3,622,448
def iter_items(rows): """ """ member_load = {} for row in rows: try: member_load[row[0]].extend(list(row[2:])) except KeyError: member_load[row[0]] = list(row[2:]) return member_load
16ee5bca38a66dd9c2ba8b3428f169d2c624af85
3,622,449
import os def get_training_strategy(): """ :return: A training strategy. It could be TPUStrategy if we are running the code in TPUs, DistributionStrategy if the code is distributed or MirroredStrategy if the code is running in one machine with more than one GPU. This code expects all the machines to h...
2fcf3ab125299f935f99aaa63c37e489bb8f1b7f
3,622,450
def get_file_name(api_token, data_series_list, initial_date, final_date, api_host=DEFAULT_API_HOST): """Combines region, items, and dates to return a string""" client = GroClient(api_host, api_token) logger = client.get_logger() key_words = [client.lookup('regions', data_series_list[0]...
a08a8f1847f355f425b7c7a77f0b562538f2bec8
3,622,451
def from_transform(msg): """ Convert a `geometry_msgs/Transform` ROS message into a numpy array (4x4 homogeneous transformation). Parameters ---------- msg: geometry_msgs/Transform The ROS message to be converted Returns ------- array: np.array The resulting numpy array...
cbd0c8a8547b2bb2da242fedeedeb9665367d193
3,622,452
def _read_character_at(source, pointer): """Reads a code point or a backslash-u-escaped code point.""" while pointer < len(source) and source[pointer] == " ": pointer += 1 if pointer >= len(source): raise IndexError("pointer %d out of range 0-%d" % (pointer, len(source))) if source[poi...
529c7319f5f90d6df4aba97ba5fc40d526b94dde
3,622,453
def get_list_of_data(filepath, col_name, geoid=None): """Pull a column data from a shape or CSV file. :filepath: The path to where your data is located. :col_name: A list of the columns of data you want to grab. :returns: A list of the data you have specified. """ # Checks if you have inputed ...
b505501f33e2223a5eb983eb59adde2f2314fe34
3,622,454
def waber(lumin, lambdaValue): """ Weber's law nspired by Physhilogy experiment. """ # lambdaValue normally select 0.6 w = lumin**lambdaValue #w = (255*np.clip(w,0,1)).astype('uint8') return(w)
d9c495dd656161a67120f1e15e447021617180ab
3,622,455
import os def valid_engine_path(path): """ Check if the engine path is valid """ path = os.path.normcase(path) # Check that path is actually there if not os.path.exists(path): return False # Check that is has an engine folder if not os.path.exists(os.path.join(path,'engine'))...
3a722675f244f2a88fdf33d7223e5dceccfeea54
3,622,456
def children(nodes): """ Search and list all the nodes childs. :param nodes: a list with tree nodes :return: a list with nodes childs """ child = [] for node in nodes: if node.left: child.append(node.left) if node.right: child.append(node.right) r...
19e60bbdceb60f85ffa9806e5ff61fd00030b368
3,622,457
def run(ceph_cluster, **kw): """ Prepares the cluster to run rados tests. Actions Performed: 1. Create a Replicated and Erasure coded pools and write Objects into pools 2. Setup email alerts for sending errors/warnings on the cluster. Verifies Bugs: https://bugzilla.redhat.com/show_b...
e27c4861fb36b7b9f9ea42f88ed3d81c67fa6c90
3,622,458
def process_long_strings(lexicon: lex_or_string) -> lex_or_string: """Process long strings in the main lexicon. Strings marked for concatenation are indicated with a leading pipe. """ if isinstance(lexicon, str): if lexicon.startswith("|"): lexicon = ( # Remove the p...
f3e8f88dec9731c3d192ce54607223759de2bdef
3,622,459
import os def component(name, prefix='', folder_name=COMPONENT_DIR, file_type=FILE_TYPE): """Get the image for the component of a given name. prefix- the name of the component's feature (leg, segment, wing) name- the feature's value folder_name- the enclosing folder for component images file_type-...
8aa5b7d29595f70164f11409f4c0a8e5964f03e9
3,622,460
import click def init(): """Admin Cell CLI module""" @click.group( cls=cli.make_commands( __name__ + '.' + context.GLOBAL.get_profile_name() ) ) @click.option( '--cell', required=True, envvar='TREADMILL_CELL', is_eager=True, callback=cli.handle_cont...
de93dc1caaadaa41e912ff0ad10bf45ea47725a3
3,622,461
def tensor_prod(a, b): """ Returns the tensor product using lists """ product = [] # loop through first tensor/vector for a_ in a: row = [] # multiply with each element of second tensor and add to row list for b_ in b: row.append(a_ * b_) # add row lis...
c13ec6e0d3292d1124c567420d2b50b8d3a5501a
3,622,462
from typing import OrderedDict def xblock_view_handler(request, usage_key_string, view_name): """ The restful handler for requests for rendered xblock views. Returns a json object containing two keys: html: The rendered html of the view resources: A list of tuples where the first element ...
25c0b7bf925b130edbaf34327f47e725923fe53b
3,622,463
from operator import mod def invoke(request): """Where the magic happens...""" transformed_request = _transform_request(request) with monitor(labels=_labels, name="invoke"): data_iter = mx.io.NDArrayIter(transformed_request, None, 1) response = mod.predict(data_iter) return _transform...
fd817fc70e469b1947c6b0f67ab751cd5c088415
3,622,464
def get_location(stmt): """Return the grounded geo-location context associated with a Statement.""" if not has_location(stmt): loc = None else: loc = stmt.context.geo_location.db_refs['GEOID'] return loc
71d53954cc5de55f3eea4844c2bbc8f8d7aacc08
3,622,465
def _convert_version(value): """Extract 3 version numbers from 2 bytes""" # subversion bits 0.3, versin bits 4-7, type bits 8-15 type_ = value // 256 value = value % 256 version = value // 16 subversion = value % 16 return '{}.{}.{}'.format(type_, version, subversion)
2850b4729da445f2ee7007c469aaa91c2370e4dd
3,622,466
def var_gaussian(r, levels=5, modified=False): """ Returns the Parametric Gaussian VaR of a Series or DataFrame If modified is True, then the modified VaR is returned using Cornish-Fisher modifications """ # compute the Z score assuming the distribution is Gaussian z = norm.ppf(levels / 100...
22d7c8e55230beb2a95d031d53b0a49faa5e5b34
3,622,467
import math def taylor_green_vortex(x, y, z): """ Calculates Taylor Green vortex flow velocities. """ A = 0.14 B = A C = -2 * A a = 1 b = 1 c = 1 # Position translated to ensure boundary flow is tangential and continuous. x_p = x + (math.pi / (a * 2)) y_p = y + (math.pi / (a ...
c7810d3c059f0325c9d29ec88fbd4d8a87f1dea5
3,622,468
def breadcrumbs_list(links): """Returns a list of links to render as breadcrumbs inside a <ul> element in a HTML template. ``links`` should be a iterable of tuples (URL, text). """ crumbs = "" li_str = '<li class="breadcrumb-item"><a href="{}">{}</a></li>' li_str_active = '<li class="breadcrumb-...
736f6685cc3f58b50d2e67758c239ab7970cc9f2
3,622,469
def setup(args: Arguments): """ Create configs and perform basic setups. """ cfg = get_cfg() add_config(args, cfg) cfg.merge_from_file(str(args.config_file)) # cfg.merge_from_list(args.opts) cfg.merge_from_list(switch_extract_mode(args.extract_mode)) cfg.merge_from_list(set_min_max_b...
b660209d3bcbf5efc867d4235b4ac581d4ed596d
3,622,470
import argparse def parse_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser('Extract user sessions from log.') parser.add_argument('input', help='an input file') parser.add_argument('output', help='an output file') parser.add_argument('-p', '--protocol', defaul...
b07bc1fc60a73ac4f2089d12ae8ad34e106c1360
3,622,471
import glob def get_lists_in_dir(dir_path): """ Function to obtain a list of .jpg files in a directory. Parameters: - dir_path: directory for the training images (from camera output) """ image_list = [] for filename in glob.glob(dir_path + '/*.jpg'): image_list.append(filename...
c59701c5c8327569a5efe68c2751b0568de0498e
3,622,472
from io import StringIO from os import environ def get_help_string(unit, brief=False, width=None): """ Retrieves the help string from a given refinery unit. """ if brief: return terminalfit(documentation(unit), width=width) else: try: environ['REFINERY_TERMSIZE'] = str(...
f3a00b8a29c926a3613d4fa0016acce71e51e590
3,622,473
from typing import Iterable from typing import Dict import os def get_files_for_package( dir: str, allow_git: bool = True, ignore_patterns: Iterable[str] = (), ) -> Dict[str, PackageFileInfo]: """ Get files to package for ad-hoc packaging from the file system. :param dir: The source directory...
e22fd47f037f767f600b983e9aaa524b4c8f2af3
3,622,474
from typing import Union def suppress_red_green_blue(error: Union[Red, Green, Blue]) -> bool: """Suppress Red, Green, and Blue exceptions.""" return True
2febf662644c94bea579c3ad12c24429a91b1bb7
3,622,475
def exists(env): """Check if we're okay to load this builder""" return MkdocsCommon.detect(env)
60066ac1da3a0762694505ef89a5eda40ff36871
3,622,476
def walk_links_for_node(node, callback, direction, obj=None): """ Walks the each link from the given node. Raising a StopIteration will terminate the traversal. :type node: treestruct.Node :type callback: (treestruct.Node, treestruct.Node, object) -> () :type direction: int :type obj: Any ...
a92cb831945a537c55ff4c014eedcb17b26ddd96
3,622,477
from openeye import oechem, oedepict from typing import List import copy def _create_openeye_pdf(molecules: List[Molecule], file_name: str, columns: int): """Make the pdf of the molecules using OpenEye.""" itf = oechem.OEInterface() suppress_h = True rows = 10 cols = columns ropts = oedepict...
3ba260ef2899a6ba1b233637be39ec77c807e8f4
3,622,478
def check_match(template, meme, debug=False): """ This calculates how similar template is to meme :param template: File path :param meme: File path :param debug: Debug :return: [-1, Exception] if error, [0, confidence] if all ok """ original = cv2.imread(template) image_to_compare = ...
be57e1e767884454068edd092bd74c64904d4b30
3,622,479
def dialog_create_repository(request): """fills the create repository dialog """ # nothing is needed return { 'mode': 'CREATE', 'has_permission': PermissionChecker(request) }
f69590ecff28a6694e07d5ec0bb81bb5f72dcdaf
3,622,480
def external_load_new_pool(request, form_acess, client): """ Method to call shared_load_new_pool when use by external way """ return facade.shared_load_new_pool(request, client, form_acess, external=True)
7d3423bf1f02038cdfc3f7e651ff0cc2658b0640
3,622,481
import configparser def get_config_parser(filepath): """Create parser for config file. :param filepath: Config file path :type filepath: str :return: configparser.ConfigParser instance """ config_parser = configparser.ConfigParser(interpolation=None) # use read_file() instead of read() to...
224f524c60161bc45b1324b26eeb6d4715c43054
3,622,482
def num_concavities(prop, **kwargs): """Return the number of concavities for a cell Args: prop (skimage.measure.regionprops): The property information for a cell returned by regionprops **kwargs: Arbitrary keyword arguments Returns: int: The numb...
f83cc3206b22b0cbfb7dc264cbbb2f051925dd21
3,622,483
def add_street_network_to_city(city_object, name_list, pos_list, edge_list): """ Add street network to city object. Based on street network functions of uesgraphs. Parameters ---------- city_object : object City object of pycity_calc name_list : list List of street node name...
e73723001ccc9709da71efb6191457bbc111e483
3,622,484
def admin_login_req(f): """ 登录装饰器 """ @wraps(f) def decorated_function(*args, **kwargs): if "admin" not in session: return redirect(url_for("admin.login", next=request.url)) return f(*args, **kwargs) return decorated_function
ef25213a2aed99aa0836624cfa426b1898f302cb
3,622,485
def vec2d(x,y): """A vector in 2D vector space""" return jnp.array([x+0.,y])
559ff6a524a05ab74d63508c11e0ae5aab3ebda8
3,622,486
def preview_page_version(request, revision_id): """ Returns GET response for specified page preview. :param request: the request instance. :param reversion_pk: the page revision ID. :rtype: django.http.HttpResponse. """ revision = get_object_or_404(PageRevision, pk=revision_id) if not ...
3d53848c7d7f5d1146f59b0535aa8906d9e116fd
3,622,487
def load_id_map(id_file): """ Load a ids file in to a barcode -> coordinate dictionary. """ id_map = {} with open(id_file, "r") as fh: for line in fh: bc, x, y = line.split("\t") id_map[bc] = (int(x), int(y)) return id_map
cd2c0635496209c3e19597fa45ae4f486779ceac
3,622,488
def map_page(): """ Global strain map shows the locations of all wild isolates within the SQLite database. """ VARS = {'title': "Global Strain Map", 'strain_listing': dump_json(get_strains(known_origin=True))} return render_template('strain/global_strain_map.html', **VARS)
fe7a078c314d78e0c3ac01115482b80a3072fcf6
3,622,489
def database_is_empty_or_contains_kombu_tables(db_url): """ Database is empty or contains 2 tables: kombu_message, kombu_queue. (ref: https://github.com/galaxyproject/galaxy/issues/13689) """ with disposing_engine(db_url) as engine: with engine.connect() as conn: metadata = MetaD...
99c7870aa7e20702fd94fa69edf1458ab1df3740
3,622,490
from datetime import datetime from pathlib import Path import ftplib def download(startend: tuple[datetime, datetime], site: str, odir: Path, host: str = None, wavelen: str = None) -> list[Path]: """ startend: tuple of datetime """ if not host: host = HOST assert len(startend) == 2 s...
ffcb66a704442febfe73803a310e0e8b671723d2
3,622,491
def get_static_mini_dataset() -> Dataset: """Return a collection of 10 documents and their target subjects of 4 different subjects. Returns ------- Dataset the static dataset consisting of 10 documents and 4 subjects """ documents = [ Document(uri="uri://test_document1", title="...
80521e3ceb5a9798ee4abac5b54ae0b6a89f6def
3,622,492
def popular_environment_shared(request, client_api): """ Method to return environment vip list by finality and client Param: finality Param: client """ lists = dict() status_code = None lists['environments'] = '' try: finality = get_param_in_request(request, 'finality') ...
4a8ab75a4565fa05883467385a8234bb2867a25a
3,622,493
def save_name(): """Change a users details, most importantly his name.""" user = request.json store_user(user) return "I'll try to remember your name, {}!".format(user.get("name"))
51c9ab4d37624af49a58413979a6af91014d7738
3,622,494
import os def favicon(): """Return favicon resource.""" return send_from_directory( os.path.join(app.root_path, 'static'), 'icon.png', mimetype = 'image/png')
113c94887b819c0c1abf2b4b607327b11364bfae
3,622,495
from typing import Union from typing import Callable from typing import Optional def add_l2_weight_decay(loss_fn: base.LossFn, scale: Union[float, Callable[[hk.Params], hk.Params]], predicate: Optional[PredicateFn] = None) -> base.LossFn: """Adds scale * l2 weight dec...
c8450dad029799d5b8149782001ba5d72a0a36d6
3,622,496
def create_resnet101() -> tf.keras.Model: """Create ResNet101 """ resnet_base = tf.keras.applications.ResNet101( input_shape=(32,32,3), weights='imagenet', pooling='avg', include_top=False) # Downloading data from # https://storage.googleapis.com/tensorflow/keras-app...
e4bebdab84feb2a01c37679e8fd3f0d5daecabd1
3,622,497
def spatial_join_facilities(left, right, lid_property, rid_property, lsimilarity_properties, rsimilarity_properties, similarity_weights=None, ...
d1e9315af0329db22060c3a25b9e1513db121c63
3,622,498
from textwrap import dedent def handle_description(update, context): """Добавление определенного кол-ва товара в корзину""" query = update.callback_query if '/back' == query.data: return start(update, context) purchase_id = str(query.data) purchase_quantity = 1 chat_id = update.eff...
28c9632cf3f6cecf492f97f51b4607f7dc6f5460
3,622,499