content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from .model_store import download_state_dict import os def get_shufflenet(groups, width_scale, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create ShuffleNet mod...
c181e0f7fcf907a7b44015da289959e35b403216
3,608,700
def dims_for_qty(data): """Return the list of dimensions for *data*. If *data* is a :class:`pandas.DataFrame`, its columns are processed; otherwise it must be a list. genno.RENAME_DIMS is used to rename dimensions. """ if isinstance(data, pd.DataFrame): # List of the dimensions ...
aa05712be2d23765cf50728b6482eb7bcf20335a
3,608,701
from shlex import split def split(s,separator=None): """'this is "a test"' -> ['this', 'is', 'a test']""" if separator is None: return split(s) else: return s.split(separator)
a28bfd53d38afe8492c6fecc47c72bf0fcd5cd4c
3,608,702
def view_event(user, event): """ Check whether a user may view a specified event. :param User user: :param Event event: :return: bool """ if event is None: return None return user.has_perm("booking.view_hidden_events") or event.visible is True
0aca52c9a60449ab0711a2291c5f12f42c8b3f96
3,608,703
def is_serial_synchronised(database_handler: DatabaseHandler, source: str, settings_only=False) -> bool: """ Determine whether a source should use / is using serial synchronisation from the NRTM mirror source. If settings_only is set, only look at whether serial synchronisation should be enabled bas...
dbc540b67f143117d7848d7f7fb03d03b339c7e5
3,608,704
def micro_fmeasure(y_true, y_pred): """This metric return a micro-averaged F-score""" precision_value = micro_precision(y_true, y_pred) recall_value = micro_recall(y_true, y_pred) return ((Beta ** 2 + 1) * precision_value * recall_value) / (Beta ** 2 * precision_value + recall_value)
99eabd636a3934c95d0ad3035241ff10fdbe7001
3,608,705
def setProjParameter(self, name, value): """ Set an individual paramater for a projection """ checkName(self, name, value) param = self.parameters ok = proj_ok_parameters for nm in list(ok.keys()): vals = ok[nm] oktypes = vals[0] position = vals[1] nms = vals[2] ...
ea8f1a809713e8d1b86d33b26d376474b0dd647a
3,608,706
def parse_filename(fname, return_ext=True, verbose=False): """ Parses `fname` (in BIDS-inspired format) and returns dictionary Parameters ---------- fname : str os os.PathLike Filename to parse return_ext : bool, optional Whether to return extension of `fname` in addition to key...
1512b50fa6d07a0bcbb69831418a935f28abe2d8
3,608,707
def split_to_patch(arr, target_shape=(8, 8)): """ shape: (t, 112, 112, 1) -> (-1, t, 8, 8, 1) """ hs, ws, _ = arr.shape ht, wt = target_shape hp = hs // ht wp = ws // wt patch = [] for w in range(wp): for h in range(hp): patch.append(arr[(ht*h):(ht*(h+1)), (wt*w)...
4d7f609d02807e8a3eee5e21dfdbc713ae3ebe7e
3,608,708
import numpy def inverse_time_decay(learning_rate, global_step, decay_steps, decay_rate, decay_delay=0, decay_power=1, staircase=False): """Applies inverse time decay to the learning rate. decayed_learning_rate = learning_rate / (1 + decay_rate * t) learning_rate: A Python number. ...
a62b0d8ecdb0e422483489b33a1e8eb1af557734
3,608,709
def input_fn(path): """ Function to load the LIBSVM Data from the path & tranform the feas into a dictionary [0] and the response [relevance of the current option] into a tf.Tensor [1] Response: Size: - as many rows as we have BATCH_SIZE - as many cols as we have LIST_SIZE Val...
fd2dc408d7738652faf59a1568c8abbd5bc50d11
3,608,710
def not_found(error): """404 page""" return render_template('errors/404_notfound.html', error=error), 404
6efb3f92ebb87b534ae8deaa5d3bd19189869ba9
3,608,711
def get_ls(omega_list): """Return the array of the Solar longitude of each OMEGA/MEx observation in omega_list. Parameters ========== omega_list : array of OMEGAdata The input array of OMEGA observations. Returns ======= ls : ndarray The array of the omega_list Ls. ...
c8be1927a55ff9aac0134d52691b3b2bdd049724
3,608,712
import requests import json def altitude(place: str): """標高を表示する""" def ret(client: BaseClient): user = client.get_send_user_name() logger.debug("%s called 'hato altitude '", user) coordinates = None place_name = None place_list = split_command(place, 2) if le...
2b3d7c043be083fe9598eed69914669d0cc5bbac
3,608,713
def np_mean(a): """ Returns the mean from the array, NaN if length is 0. :param a: the array to use for the calculation :type a: np.array :return: the mean or NaN if failed to calculate :rtype: float """ if len(a) == 0: return float("NaN") try: return float(np.mean(a...
8b2739b2205d24158871a777395ed6acd34d26a0
3,608,714
def run_intcode(memory, noun, verb): """Assign noun and verb then run intcode program on memory.""" memory[1] = noun memory[2] = verb pointer = 0 while True: opcode = memory[pointer] if opcode == 99: return memory[0] param_one = memory[pointer + 1] param_...
b4f0c6762a9a27021ce1cabd03b950fb8fabcd48
3,608,715
def update_city(city_id: int, data) -> City: """ Update a city record in the database. :param city_id: The city record identifier. :type city_id: int :param data: Updated JSON data for an existing City object. :return: City """ city = City.query.filter(City.id == city_id).one() city...
72e88ac2c9d0568b4cb61c96e97db964f5f49355
3,608,716
import re def read_memory_graph(target_file): """Reads memory percentages from the memory graph.""" percentage_expression_string = r'\d{1,3}\.\d\%' mem_used_search = re.search(percentage_expression_string, target_file.readline()) if mem_used_search is None: mem_used = "0.0%" else: ...
5c838ff8b3ff1bb5902472879594ac014b18b0c5
3,608,717
def weights(shape): """Create a weight variable. """ input_size = shape[0] var = tf.Variable(tf.truncated_normal( shape, stddev=tf.sqrt(2.0 / input_size) )) return var
1c5eecaa0884403643a9a86708c64dc14ec753ef
3,608,718
def regression_tree(input_dict): """ Creates a Decision tree classifier """ criterion = input_dict['criterion'] splitter = input_dict['splitter'] max_depth = input_dict['max_depth'] min_samples_leaf = input_dict['min_samples_leaf'] max_depth = max_depth.strip() if max_depth == '': ...
6b697a2afab08ea96b54a818471b8fd4541566a7
3,608,719
def sample_name(data): """Return `name` of `Sample` that given `Data` object belongs to.""" return get_sample_attr(data, 'name')
7400e22cccf72b8f23f7a06df442e3494a6087a5
3,608,720
import functools import tqdm import time def extract_knn(data_shape, index_builder=AnnoyKnnMatrix.load, verbose=1, **kwargs): """Starts multiple processes to retrieve nearest neighbours from a built index in parallel. :param tuple data_shape: The shape of the data that the index was built on. :param inde...
ff2e15ed03a36b86baf1719c4ae79e3c764d785c
3,608,721
def adjust_scale_prediction(y_pred, cell_grid, ANCHORS): """ Adjust prediction == input == y_pred : takes any real values tensor of shape = (N batch, NGrid h, NGrid w, NAnchor, 4 + 1 + N class) ANCHORS : list containing width and height...
84bf66304bb05fa0ec85538fb37def319c4c0e9f
3,608,722
def getTweeningMethod(method): """Get the tweening method from a string, if the function doesn't exists None will be returned. :return: Tweening function :rtype: func/None """ _dict = getTweeningMethods() return _dict[method] or None
a312f0154c83ba32af1aa84d0bf80acc68dbfbd1
3,608,723
import os import sys def gads_invoker(request): """Triggers the upload of a chunk of conversions. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask...
92dbd956609f017890f8a79a7dcf54ee4e746d15
3,608,724
def mesh_offset(mesh, distance=1.0): """Offset a mesh. Parameters ---------- mesh : :class:`compas.datastructures.Mesh` A Mesh to offset. distance : float, optional The offset distance. Returns ------- :class:`compas.datastructures.Mesh` The offset mesh. No...
151c39c36c868f110d1a39b631d73c8d3ab042cf
3,608,725
def extract_java(fpath: str): """ Extract regexes from java file :param fpath: A path to a file :return: A list of FoundExpressions """ # find import statement f = open(fpath, "r") # get lines in file lines = f.readlines() expressions = [] # list of FoundExpressions im...
9f27b55ac541f1f14499d153f74f79acb5f9ef8a
3,608,726
import torch def _evaluate_iou(target, pred): """ Evaluate intersection over union (IOU) for target from dataset and output prediction from model """ if pred["boxes"].shape[0] == 0: # no box detected return torch.tensor(0.0, device=pred["boxes"].device) return box_iou(target["b...
8442abbb0442bb65f1a5fa38ddc1acc488e9d395
3,608,727
def partial_product_generation(bit_list, exp_prime): """Generate partial-products.""" pp_list = [] while bit_list: pp = PartialProduct(exp_prime) tmp_bit_list = [] for bit in bit_list: check = pp.add_bit(bit) if check is False: tmp_bit_list.app...
17f7077486839cb1ee74072c8b977d8d4d46b408
3,608,728
import psutil def restore_from_mysql_full( stream, dst_dir, config, redo_only=False, xtrabackup_binary=XTRABACKUP_BINARY, xbstream_binary=XBSTREAM_BINARY, ): """ Restore MySQL datadir from a backup copy :param stream: Generator that provides backup copy :param dst_dir: Path to...
197fa8249cebd171446dc4d4ff77461b88f1fad9
3,608,729
import concurrent def validate_keys_multi( w3, operators: t.List[t.Dict], lido_address: str, lido_abi_path: str, ) -> t.List[t.Dict]: """ Main multi-process validation function. Modifies the input! Adds "valid_signature" field to every key item. It will spawn an appropriate process poo...
e0cf457ad3d70b36c584ff63d55a9e56217b2d92
3,608,730
def upvLayoutObjects(upv_layout_objects, bounds): """ Layout Objects So far only seen vias in this """ count = 0 vias = {} for layout_object in upv_layout_objects: count += 1 #Error handling for future improvement #Only handling vias right now ...
5876038d0aca24d9f4a782a3b37d71dde56f4489
3,608,731
def paginationpageurl(context, page, url_name, page_id, qs): """ Enhanced version of wagtails own 'routablepageurl' that adds handling for the routing of page 1 and :param context: page context :param page: Page: The root page with the child pages :param url_name: sting: the url named pattern f...
04689eebe1de43b82ef5d971e5a3874c77706ae6
3,608,732
def _connect_mongo(host, port, username, password, db): """ A util for making a connection to mongo """ if username and password: mongo_uri = 'mongodb://{}:{}@{}:{}/{}'.format(username, password, host, port, db) conn = MongoClient(mongo_uri) else: conn = MongoClient(host, port) ...
945509455084ecf33ec488b4d239dc92a5bc1c6c
3,608,733
def client(): """ A test client that has the Authorization header """ app_test.testing = True app = app_test.test_client() return app
c777d1f0eb4e1218be24c6be9f15597d19ffb875
3,608,734
def fix_term_scope(term): """ 对term的scope进行硬处理 :param term: :return: """ scope = 'realtime' left = term.left if left and left.type == 'func' and left.subtype == 'getvariable' and 'profile' in left.variable[1]: scope = 'profile' # hard code if left and left.subtype == ...
bf67f5839a402281c2ef943983e857e10d5da627
3,608,735
def gf_add_const(f, a, p): """Returns f + a where f in GF(p)[x] and a in GF(p). """ if not f: a = a % p else: a = (f[-1] + a) % p if len(f) > 1: return f[:-1] + [a] if not a: return [] else: return [a]
8c728467213a6a83a1e98ddec68f8145697d15dc
3,608,736
from typing import Optional async def delete_item(identifier: Optional[str] = None, item_name: Optional[str] = None, city_name: str = None, current_user: AdminModel = Depends(get_current_user)): """ Delete an item by item and city name: - **current user** should be admin - **ite...
e5b58076cc29e656880ca96aecafbf47915df79b
3,608,737
from typing import Callable from typing import Awaitable async def async_bind_async_future( function: Callable[[_ValueType], Awaitable['Future[_NewValueType]']], inner_value: Awaitable[Result[_ValueType, _ErrorType]], ) -> Result[_NewValueType, _ErrorType]: """Async binds a container returning ``IO`` over...
22b50c829732e273f75e33e57c163e5d99c8a4bb
3,608,738
def pyramid_lucas_kanade( img1, img2, keypoints, window_size=9, num_iters=7, level=2, scale=2 ): """Pyramidal Lucas Kanade method Args: img1 - same as lucas_kanade img2 - same as lucas_kanade keypoints - same as lucas_kanade window_size - same as lucas_kanade num_...
a677512eddf39557ea878e4da9d1db397969fc07
3,608,739
import pkg_resources def version(): """ Returns the current version of the CySCS Python wrapper. """ return pkg_resources.get_distribution("cyscs").version
b530c798702dfb62a041a6a9c1fb8ff1dc1e6365
3,608,740
def get_parameter_name_by_parameter_stream(stream_parameter_name, stream): """ Get parameter display name using stream rest api to get english name and units. (Used in plotting.py where plot_layout == 'stacked') """ display_name = None try: # Check input parameters. if not stream or ...
ddfeb2cf4d9433e1adebcea166290bed2ffb67b7
3,608,741
def check_code(): """Run pylint on code and get output :return: JSON object of pylint errors { { "code":..., "error": ..., "message": ..., "line": ..., "error_info": ..., ...
e94cb01d63354c5c7f497a130151deed86e017c4
3,608,742
def gcd(f, g, *gens, **args): """Returns polynomial GCD of `f` and `g`. """ gens = _analyze_gens(gens) try: F, G = _polify_basic(f, g, *gens, **args) except CoercionFailed, (f, g): try: return f.gcd(g) except (AttributeError, TypeError): # pragma: no cover ...
10f33ffe6211ed81d80378960d7dec3c57682d2e
3,608,743
def get_compilation_failure(messages): """ Reads the json formatted 'messages' and checks for compilation errors. If there is a genuine compilation error then there should be a new message containing a severity field = Error and an accompanying message with the compile error text. Any othe...
650868350a7e11a877290c88e1e0038c1beb3fff
3,608,744
import types def _generic_ode_solve(r, rho0, tlist, e_ops, opt, progress_bar): """ Internal function for solving ME. Solve an ODE which solver parameters already setup (r). Calculate the required expectation values or invoke callback function at each time step. """ # # prepare output arra...
ba8c111ebd0a8abf29e2ba63af4440a6c8e119ff
3,608,745
from datetime import datetime import json def change_state(request, name, option=None): """Change state of charter, notifying parties as necessary and logging the change as a comment.""" charter = get_object_or_404(Document, type="charter", name=name) group = charter.group if not can_manage_group...
68c34e6f49da209f9a89cd115e1767834bf470c5
3,608,746
def register_done(request): """ Shows registration complete message. """ return render(request, 'blog/register_done.html')
ee984e34035d2c345db740ffa781a87ffeb8cc42
3,608,747
import torch from typing import List def validate_on_data( model: SignModel, data: Dataset, batch_size: int, use_cuda: bool, sgn_dim: int, do_recognition: bool, recognition_loss_function: torch.nn.Module, recognition_loss_weight: int, do_translation: bool, translation_loss_func...
bed81c156c2c5393a8d8ce228a2c67d31985ba8d
3,608,748
import random def miller_rabin_primality_testing(n): """Calculates whether n is composite (which is always correct) or prime (which theoretically is incorrect with error probability 4**-k), by applying Miller-Rabin primality testing. For reference and implementation example, see: https://en.wikip...
6f7263f261bf20b851aa40e0c616a68e9936f16d
3,608,749
def draw_tab(_image, _width, _height, _key_background): """draws enter arrow""" im = ImageDraw.Draw(_image) # white = (255,255,255,255) # black = (0,0,0,255) fill = pick_fill(_key_background) scalex = _width / 52.0 scaley = _height / 40.0 poly = [(int(x * scalex), int(y * scaley)) for x,...
a26b3ebd69b611a39a5454aaf04f62caffa0d000
3,608,750
import json def identity(): """ Generates a response with the name of this node. Returns: Response : Name of node """ return Response( json.dumps({RESPONSE_MSG.SUCCESS: True, "identity": local_worker.id}), status=200, mimetype="application/json", )
3d18e2bd04dc3c43fcced48bfbd704199d533b58
3,608,751
import functools from datetime import datetime def busy_try(delay_secs: int, ExceptionType=Exception): """ A decorator that repeatedly attempts the function until the timeout specified has been reached. This is different from timeout-related functions, where the decorated function is called only *onc...
0d005935ffa8b7f594da692edfa39ec4342ed4e1
3,608,752
def net_debt_to_ebitda(asset: Asset, period: str, period_direction: FundamentalMetricPeriodDirection, *, source: str = None, real_time: bool = False) -> Series: """ Net Debt to EBITDA of the single stock or the asset-weighted average value of ...
5dcd94a2ac7adb58315174479ef7c34663ccd257
3,608,753
def apply_to_tuple(*funcs, **kwargs): """ Applies several functions to one ``item`` and returns tuple of results. :param list func: The list of functions we need to apply. :param dict kwargs: Keyword arguments with only one mandatory argument, ``item``. Functions would be appli...
ecd24cc472cdb61c006e8f377041f7e5167e8df6
3,608,754
import os def cloneRepositories(repositories, TCVersion, patches): """ Checkout each git repository for TCVersion in directory repositories.""" assert isinstance(repositories, str), "Expecting a string for the directory name." assert isinstance(TCVersion, LLVMBMTC), "Expecting an LLVMBMTC object." if ...
ed242279f2c211d59d1a81134aeb966adcf51bb7
3,608,755
def MakeDeclarationString(params): """Given a list of (name, type, vectorSize) parameters, make a C-style parameter declaration string. Ex return: 'GLuint index, GLfloat x, GLfloat y, GLfloat z'. """ n = len(params) if n == 0: return 'void' else: result = '' i = 1 for (name, type, vecSize) in params: ...
1b009bce0d6c25b25e4830b3a021dda877519ea3
3,608,756
from datetime import datetime def get_value_from_view(context, field): """ Responsible for deriving the displayed value for the passed in 'field'. This first checks for a particular method on the ListView, then looks for a method on the object, then finally treats it as an attribute. """ view...
b28215907a82d9548067ad8283e5391383028599
3,608,757
from pypykatz.registry.offline_parser import OffineRegistry def decrypt_hive(loot_id): """Decrypt the registry hive and store result in DB""" loot = get_loot_entry(loot_id) o = OffineRegistry() try: o = o.from_files( loot.system_file, security_path=loot.security_file...
7c2ea9a85240ec3ee757d95e8e144e5a9686a911
3,608,758
from typing import Tuple from typing import Union def min_avg(arr: list, k: int) -> Tuple[list, Union[float, int]]: """ Time Complexity: O(n) space complexity: O(1) """ avg: Union[int, float] = sum(arr[:k]) / k start: int = 0 end: int = k - 1 cur_avg = avg for index in range(k, le...
1a2cdafd54eda4ed1078fe72f369fb8750634b84
3,608,759
def user_delete(request): """ --Delete a User instance (make inactive)-- ========================================================================================================== 1) Checks wether this delete is confirmed. If False returns 400. 2) Checks to make sure there is a refresh token string ...
c66711be8ef83404449a33075cf6810c61c16525
3,608,760
import os def load_specdataset(): """Load SpecDset but skip test if matplotlib is not installed.""" pytest.importorskip("matplotlib") dset = read_swan(os.path.join(FILES_DIR, "swanfile.spec"), as_site=True) return dset
4832275b08b861d357470102f0c081e3b4de682a
3,608,761
import os def add_content_set(content_dir=None, service_id=None, **kwargs): """Adds content to the given MRS service Args: content_dir (str): The path to the content directory service_id (int): The id of the service the schema should be added to **kwargs: Additional options Keywo...
a14f5e508447d84099cd2437a48d7c0ecca876ba
3,608,762
import networkx import subprocess def network_create(G, docs, config): """ Create the final .gexf file needed form visualizing the network Args: - G : generated graph - docs: list of strings, one for each node(concatenated) - config: config file """ log...
783f56783c9ff397b07be9fb6b9491668833392f
3,608,763
from BigDFT.Fragments import Fragment def system_from_log(log, fragmentation=None): """ This function returns a :class:`~BigDFT.Fragment.System` class out of a logfile. If the logfile contains information about fragmentation and atomic multipoles, then the system is created accordingly. Otherwise,...
2cf9514c31d3046f699f2ec81c06f124afdf378c
3,608,764
def _ComputeLeafChildCacheKey(node): """Computes a key that uniquely identifies the node, or None if no key.""" if not _NodeHasAllLeafChildren(node): # We do not compute cache keys for nodes that have children, since # there is a low hitrate for such duplicates and since the cache # keys would be substa...
6a5e3a6915749a8767ef20f753a57b9ba29075fc
3,608,765
import click def update_crs_cmd(epsg): """ Reproject the CityJSON to a new EPSG. The current file must have an EPSG defined (do it with function update_epsg()). """ def processor(cm): print_cmd_status('Reproject to EPSG:%d' % epsg) if (cm.get_epsg() == None): click.echo...
39323e2184212d03a40c8b9c548ad3f2e43f587b
3,608,766
def get_gs(urldata): """ 训练二分类器,用于后期特异度判断 :param urldata: :return: """ tmp = host_count(urldata) urldata = pd.merge(urldata, tmp, on='original_host') low = urldata['ip_dst_nunique'].describe()[4] mid = urldata['ip_dst_nunique'].describe()[5] high = urldata['ip_dst_nunique'].descr...
735d5bd6fd9454ed87be3b98cf9779154a3d2f5f
3,608,767
def db_connect(rdb): """ Connect to specified database Keyword arguments: db: database key """ LOGGER.info("Connecting to %s on %s", rdb['name'], rdb['host']) try: conn = MySQLdb.connect(host=rdb['host'], user=rdb['user'], passwd=rdb['password'], db...
39d9dd1c76fd1d04f8c74d17cd9f4d29d2aa866e
3,608,768
import numpy as np def rand_jitter(arr, sensib = 0.01, lowerLimit=None, upperLimit=None): """ Creation of jittering in a one-D data array arr sensibility can be adjust with parameter sensib. In case of an array only made of a same value, you can use the lowerlimit and upperlimit parameters """...
1e7e6f67a660508effedb1b68cb4034acaa5e0c2
3,608,769
def make_text_list(postings_dict, first_n_postings=100): """ Extract the texts from postings_dict into a list of strings Parameters: postings_dict: first_n_postings: Returns: text_list: list of job posting texts """ text_list = [] for i in rang...
0d2a4e0f2d904b246942508e03cfd97cf5d43ea0
3,608,770
def SegNet(input_shape, num_classes): """ 论文中介绍的SegNet网络 :param input_shape: 模型输入shape :param num_classes: 分类数量 :return: model """ inputs = layers.Input(shape=input_shape) # encoder x = layers.Conv2D(64, (3, 3), padding='same', kernel_initializer='he_uniform')(inputs) x = layers...
3aed89a84c91a32fb7a8ab76af7b053328faa527
3,608,771
from pathlib import Path from typing import Dict from typing import Tuple from typing import List def get_tensorboard_hooks( config: dict, experiment_root_directory: Path, train_metrics: Dict[str, Metric], test_metrics: Dict[str, Metric] ) -> Tuple[List, List]: """ Get TensorBoard hooks for visualizin...
03f2fed5aee9aac3c234d0456b579ffdf47f63c3
3,608,772
import os def get_entity_dataloader( args, tasks, entity_symbols, tokenizer, ): """Get the dataloaders. Args: args: main args tasks: task names entity_symbols: entity symbols Returns: list of dataloaders """ task_to_label_dict = {t: None for t in tasks} ...
c0c7e3a6a2d977859526d05bf8a4cfca259fc80b
3,608,773
import yaml def db_read_benchmark(db_name=cfg.FILES.DB_BENCHMARK): """ Read benchmark data from file.""" with open(cfg.FILES.DB_BENCHMARK,'r') as f: db_benchmark = edict(yaml.load(f.read())) if cfg.EVAL_SET == 'paper': db_benchmark['techniques'] = filter( lambda technique: technique.eval_set=='paper',d...
49e27079945dc62a98e5da9b96a9d5718037cc55
3,608,774
def create_widgets(root, model): """Create the window and its widgets. Arguments: root: the root window. model (str): keyboard model Returns: A SimpleNamespace of widgets """ # Set the font. default_font = nametofont("TkDefaultFont") default_font.configure(size=12)...
927a6c186f3cdf75eaa7957fabd55a4b4ac04376
3,608,775
def nonoverlap(a, i, omega, R): """No overlap constraint. This function receives a 1D array which is the row of a matrix. Each element is a vector. i is which row we are passing. """ nonzeroi = np.nonzero(omega[i])[0] x = a n1, n2 = a[nonzeroi] vec = n1 - n2 norm = np.linalg.norm(vec...
aca025b81b001e6af91731fdd2d87b6e8f0168ff
3,608,776
def update_addon_download_totals(): """Update add-on total and average downloads.""" if not waffle.switch_is_active('local-statistics-processing'): return False qs = ( Addon.objects .annotate(sum_download_count=Sum('downloadcount__count')) .values_list('id', 'sum_d...
8e3846ed071ac2b63a4acfbe525072815ea94ba9
3,608,777
import json def get_file(projectCode, branch, filepath): """ :projectCode: идентификатор проекта :branch: необходимая ветка :folderPath: GET параметр путь к папке, получить через request.args.get('filePath') **Response:** ``` { "name": "myfile.md", "full_path": "/folder/my...
1765c422e2f9ced254775f1da354f424071b7763
3,608,778
def parse_input_shape(input_shape): """ Function Description: parse input shape Parameter: input_shape:the input shape,this format like:tensor_name1:dim1,dim2;tensor_name2:dim1,dim2 Return Value: the map type of input_shapes """ input_shapes = {} if input_shape == '':...
793810607751c5866dfd35a0aaf9632ff8593004
3,608,779
import re import tempfile import pipes import sys import os def _run_bam_to_fastx(program_name, fastx_reader, fastx_writer, input_file_name, output_file_name, tmp_dir=None, seqid_prefix=None, subreads_in=None): """ Converts a dataset to a set of fastx file, possibly...
a6ab9b2d5888d9c64c0deb36daadeebf37efa10a
3,608,780
def app_add_developers(app_name_or_id, alias=None, input_params={}, always_retry=True, **kwargs): """ Invokes the /app-xxxx/addDevelopers API method. For more info, see: https://documentation.dnanexus.com/developer/api/running-analyses/apps#api-method-app-xxxx-yyyy-adddevelopers """ fully_qualified...
2108709599993fc695e60038a6523f7276922f8a
3,608,781
def wave_exist_2d_trunc_v2(b=.8): """ plot zeros of -nu1 + G(nu1,nu2) and -nu2 + G(nu2,nu1) as a function of g """ plane1_z = 0.55 plane2_z = 0.889 g = np.linspace(0+.0*1j,2+0.*1j,1000) # nu1 branches L1 = Sqrt(-1 + 1.8*g) L2 = Sqrt(-5 + (4 + b)*g + Sqrt(9 + 6*(-4 + b)*g + (4...
d845fca19de9007549dd1cf0e9f96f099e57f635
3,608,782
def _get_test_unconnected_page(site): """Get unconnected page from site for tests.""" gen = pagegenerators.NewpagesPageGenerator(site=site, total=10, namespaces=[1, ]) for page in gen: if not page.properties().get('wikibase_item'): return pa...
172fdb8770d7864eed7f1a94908a94e5ed4e05dd
3,608,783
def not_contains_non_russian_cyrillic_letters(text: str) -> bool: """Checks if a text contains any non-russian but cyrillic letter.""" return all(letter not in NON_RUSSIAN_CYRILLIC_LETTERS for letter in text)
1aa732e83f63438c1b45f85aef412acbc829d926
3,608,784
def evaluation_rect(box,image,range,cur_state,thresh,k_thresh,min_thresh,max_thresh,k_select): """ :param box: 外包矩形四个顶点 :param image: 图片 :param min_thresh max_thresh 对于该斜率范围直线,保持原本斜率会过于大,直接加减又不合适,更新为k_select :param k_thresh :param k_thresh:代表确定斜率无穷大的阈值 :param thresh: 白色像素百分比阈值,大于此阈值,为1 ...
fce9a8e78667feade7ae679dca5f4fa7edae68f7
3,608,785
import uuid import json def test_blank_index_upload_authz( app, client, auth_client, encoded_creds_jwt, user_client ): """ Same test as above, except request a specific "authz" for the new record """ class MockResponse(object): def __init__(self, data, status_code=200): self.d...
b78abbf76cdb0f9a121b4f6df743b2d8e40ff524
3,608,786
def get_blocked_mlp(class_or_reg, num_blocks, num_layers_per_block=None, num_units_in_each_layer=None): """ Creates a blocked MLP. """ # Create rectifiers and sigmoids rectifiers = ['relu', 'elu', 'crelu', 'leaky-relu', 'softplus'] sigmoids = ['logistic', 'tanh'] obtl_label = 'linear' if c...
5a539d4bd54a1af374f528c5f4cc41f110a5ffe2
3,608,787
def auto_review_task(study, task): """ Reviews a Task machine-wise. Based on the regulations on http://fetc-gw.wp.hum.uu.nl/reglement-algemene-kamer/. """ reasons = [] for registration in task.registrations.all(): if registration.requires_review: if registration.age_min:...
121d2fbf861283c8eccd7c447ad5474e25b80d62
3,608,788
def make_Anndata(input_data, mtx_name='bmat', feature_names=None, metadata_name='metaData', jaccard=True, jaccard_key='jmat', save_all_rds=False, save=None, copy=True): """ Cu...
cd06ac717a73d81fec7f4807fce54b5bd4737e08
3,608,789
def _ensure_year(yr, isyr2): """ Ensure 4-digit year Years are supposed to be 4-digit years. If they have only 1 or 2 digits, then every year that is above the current year of the century will be taken as being in 1900, i.e. 90 will be taken as 1990, while all other years are taken in the 21st ...
1fdc894da9165aa494a842f96b35ba62111f2c10
3,608,790
def calculate_iou(confusion_matrix): """ https://github.com/ternaus/robot-surgery-segmentation/blob/master/validation.py """ confusion_matrix = confusion_matrix.astype(float) ious = [] for index in range(confusion_matrix.shape[0]): true_positives = confusion_matrix[index, index] ...
7f8eb6f957b031c808bb4ef0f921de26a2c855eb
3,608,791
def word_db_embed_attention_decoder(all_embeddings, decoder_inputs, initial_state, attention_states, cell, num_symbols, num_heads=1, output_size=None, output_projection=None, feed_previous=F...
3f8642f234f46b0fe86d6c1368b52e54f7835967
3,608,792
def create_manager(notifiers=None, **kwargs): """ Create manager. If notifiers is given and is a tuple (a, b), it generates a authorized notifiers and b non-authorized notifiers in the same state. """ state = kwargs.setdefault("state", random_state()) kwargs = { "email": "manager@manager...
f9d463dc303a8e0e6b5765b4ab977c9bd85aeeab
3,608,793
def tokenise(string): """ Tokenise an ASJP string into a list of tokens. Raise ValueError if it cannot be unambiguously tokenised and raise TypeError if it is not a string. The input may consist of several words, i.e. whitespace-separated sub-strings. Usage: >>> tokenise('nova zEmy~a') ['n', 'o', 'v', 'a', 'z',...
4d3ee3faa9912b463cbe984605352b8823b708b9
3,608,794
def cards_db(db): """Empty the CardsDB object after each function""" db.delete_all() return db
1f62dc919e860b9d4db31f611a8109356c1c6c1b
3,608,795
def dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" if type(labels_dense) != np.ndarray: labels_dense = np.asarray(labels_dense) num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np...
a7068c22d272cf155e059d46b1d6bb6054da7da0
3,608,796
def viewmesh(): """ mesh / glacier view """ mapform = get_map_form(session) extractform = get_form(ExtractForm(), session) meshform = get_form(MeshForm(), session) return render_template('mesh.html', form=mapform, extractform=extractform, meshform=meshform)
be35ffb7db9c76c98313a5b6ebb7dd5f288a8417
3,608,797
def cellres(lat, xres=1.0, yres=1.0): """Return the cell (x, y) resolution [m] based on cell center latitude and its resolution measured in degrees.""" m1 = 111132.92 # latitude calculation term 1 m2 = -559.82 # latitude calculation term 2 m3 = 1.175 # latitude calculation term 3 m4 = -0.0023...
b05104ae2f8e5b4365091cd30c22d40f727faa77
3,608,798
from typing import Callable from typing import Any def commands_dict( funcs, *, mk_command: Callable[[Callable, tuple, dict], Any] = Command, what_to_do_with_remainding='ignore', **kwargs, ): """ :param funcs: :param mk_command: :param kwargs: :return: >>> def add(a, b: f...
e489eda57c5bc7a81472d5e5b53f72d1fa09d8e4
3,608,799