content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging import tokenizers import sys import gc def get_bm25_index(args, db, db_opts): """Form a sparse word to document count matrix (inverted index). M[i, j] = # times word i appears in document j. """ # Map doc_ids to indexes global DOC2IDX db_class = retriever.get_class(db) log...
fc6f29099683cb7fc88a3b5079f290d1229e80bc
3,638,600
import torch def get_bernoulli_sample(probs): """Conduct Bernoulli sampling according to a specific probability distribution. Args: prob: (torch.Tensor) A tensor in which each element denotes a probability of 1 in a Bernoulli distribution. Returns: A Tensor of binary samp...
14c45741d47f5eaff24893471425ddd4de7e2e4b
3,638,601
def angle_load(root, ext='.angle'): """ Load information from the :ref:`Output_angle` file previously created by :func:`.angle_save`. Args: root (str): root name for the file to be loaded ext (str, optional): default ".angle" - extension for the file to be loaded: name = root + ext Ret...
f1218dc2dc1a6c5ef1c56689111086137b04a786
3,638,602
import subprocess import locale def parse_env_file(filename, pattern): """Source a shell script and extract variables from it.""" # Use the shell to parse this so we can also read substitutions # like $() for example. env = {} command = 'source {}; set | grep -E "{}"'.format(filename, pattern) ...
d7a3a14bc163066f0232bf7811c397fbb594b45c
3,638,603
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to you...
e7803d2ad62feb59619c212cb720e0b25fd29a57
3,638,604
import pickle def load_newsdata_and_labels(): """ Read newsdata, return list of documents, each line in list is one document as string. And list of labels, each line in list is one-hot-encoded class """ # read newsdata which is pickled def read_pickle_one_by_one(pickle_file): with ope...
3838cbd42e5bab898fc969ebe9b4f326c736c773
3,638,605
def CollectUniqueByOrderOfAppearance(dataset:list): """ This method collect all unique in order of appearance and return it as list. :param dataset:list: dataset list """ try: seen = set() seen_add = seen.add return [x for x in dataset if not (x in seen or seen_add(x))] ...
e252d064bf0c525ec1c1781ca6dc915dbc9d46f0
3,638,606
async def list_slot_set_actions(current_user: User = Depends(Authentication.get_current_user_and_bot)): """ Returns list of slot set actions for bot. """ actions = mongo_processor.list_slot_set_actions(current_user.get_bot()) return Response(data=actions)
f52f1e996b2be38a0e175ca6bfcbfd694dc79240
3,638,607
from PyQt5 import QtGui, QtWidgets, QtCore def openfile_dialog(file_types="All files (*)", multiple_files=False, file_path='.', caption="Select a file..."): """ Opens a File dialog which is used in open_file() function This function uses pyQt5. Parameters ---------- file_t...
b96112c5af25350b49bc086820bcea32c228d3c8
3,638,608
def getBlocks(bal: "BKAlignedLayout"): """ Finds all blocks of a given layout. :param bal The layout of which the blocks shall be found :return: The blocks of the given layout """ blocks = defaultdict(list) for layer in bal.layeredGraph.layers: for node in layer: root =...
6f40dc209b72747f6960d474d54e1ffedd2fa9a1
3,638,609
def read_mcmc(path_to_file): """ Reads mcmc chain from file Parameters ---------- path_to_file: string Path to mcmc chain file Returns --------- emcee_table: pandas dataframe Dataframe of mcmc chain values with NANs removed """ colnames = ['mhalo_c','mstellar_c'...
f8d0cdd5ea5a7274e81992722db4df29d7664e43
3,638,610
def rotzV(x, theta): """Roate a coordinate in the local z frame""" M = [[np.cos(theta), -np.sin(theta), 0], \ [np.sin(theta), np.cos(theta), 0], [0, 0, 1]] return np.dot(M, x)
43e4f7a8f93fb2b237da1f6ac3f699bf41e38e0a
3,638,611
import fcntl def has_flock(fd): """ Checks if fd has flock over it True if it is, False otherwise :param fd: :return: :rtype: bool """ try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: return True else: return False
9ae997d06a12d73a659958bc2f0467ebdf0142b7
3,638,612
def ExtractCodeBySystem( codable_concept, system): """Extract code in codable_concept.""" for coding in codable_concept.coding: if (coding.HasField('system') and coding.HasField('code') and coding.system.value == system): return coding.code.value return None
e672cb3d2c1d8d65e49d00539cdecf6ee03d1143
3,638,613
def add_item(data, type): """ Add an item to the data in ranked order This function handles the process of adding an item to the list. It first requests the item from the console. Items are nothing more than a line of text typed in. Next, this kicks off a type of binary search to find the proper l...
0662fb19725e0985043d7ea75bad4c5fa55d921f
3,638,614
from typing import List def _all_steps_multiples_of_min_step(rows: np.ndarray) -> bool: """ Are all steps integer multiples of the smallest step? This is used in determining whether the setpoints correspond to a regular grid Args: rows: the output of _rows_from_datapoints Returns: ...
73c4d63cdfa96610ce21e18424663c01fd395e27
3,638,615
import subprocess import os import configparser def black_config( config: c2cciutils.configuration.ChecksBlackConfigurationConfig, full_config: c2cciutils.configuration.Configuration, args: Namespace, ) -> bool: """ Check the black configuration. config is like: properties: # dictiona...
7cee55e29ec18656abbe785fc63dae69354024a8
3,638,616
def get_full_test_names(testargs, machine, compiler): ############################################################################### """ Return full test names in the form: TESTCASE.GRID.COMPSET.MACHINE_COMPILER.TESTMODS Testmods are optional Testargs can be categories or test names and support th...
05fd19a412172195c2365b0c002c442ceabf7946
3,638,617
def record_or_not(record_mode, line, start_block, end_block): """ """ if not record_mode: if start_block in line: record_mode = True elif end_block in line: record_mode = False return record_mode
2b3952ab7fa3aa23ccbd712dee0aa06083b7b5f5
3,638,618
def compute_angle_stats(vec_mat, unit='deg'): """ Get mean of angles the successif vectors used in the reconstruction. return mean an variance of the angles. """ angles = [] for i in range(vec_mat.shape[1] - 1): aux = 0 dot_prod = np.dot(vec_mat[i] / np.linalg.norm(vec_mat[i]...
d1701a3eca12e41b05a38433a7561f811aceb02c
3,638,619
def id_test_data(value): """generate id""" return f"action={value.action_name} return={value.return_code}"
47649b7302ef2f3ad046fc1c7b3fc18da2687921
3,638,620
def kneeJointCenter(frame, hip_JC, delta, vsk=None): """Calculate the knee joint center and axis. Takes in a dictionary of marker names to x, y, z positions, the hip axis and pelvis axis. Calculates the knee joint axis and returns the knee origin and axis. Markers used: RTHI, LTHI, RKNE, LKNE, hip...
1f4ab38ef90c79c964587551e05ce32ccf482e53
3,638,621
def uniform(low: float = 0.0, high: float = 1.0, size: tp.Optional[SIZE_TYPE] = None): """ Draw samples from a uniform distribution. """ if high < low: raise ValueError("high must not be less than low") u = _draw_and_reshape(size, rand) return u * (high - low) +...
da79a086a9c129a88e45c11407ca0d3993104f1a
3,638,622
import math def toInt(): """This built-in function casts the current value to Int and returns the result. """ def transform_function(current_value: object, record: dict, complete_transform_schema: dict, custom_variables: dict): value_to_return = None if current...
0f58cb6c85ca4015696c7fef2d9378c0466c2422
3,638,623
import json def public_upload(request): """Public form to upload missing images :param request: current user request :type request: django.http.request :return: rendered response :rtype: HttpResponse """ upload_success = False if request.method == "POST": document = Document.o...
857b558566a52dc2b192efc3b1441a0da11a649c
3,638,624
import pathlib import re def load_classes(fstem): """Load all classes from a python file.""" all_classes = [] header = [] forward_refs = [] class_text = None done_header = False fname = pathlib.Path('trestle/oscal/tmp') / (fstem + '.py') with open(fname, 'r', encoding='utf8') as inf...
da4baaed8d849b90c51200b778bdde9a47d58cc4
3,638,625
def findAllSubstrings(string, substring): """ Returns a list of all substring starting positions in string or an empty list if substring is not present in string. :param string: a template string :param substring: a string, which is looked for in the ``string`` parameter. :returns: a list of subst...
d9af07047c9ac6572dff430e07117220b0587847
3,638,626
def build_optimizer(name, lr=0.001, **kwargs): """Get an optimizer for TensorFlow high-level API Estimator. Args: name (str): Optimizer name. Note, to use 'Momentum', should specify lr (float): Learning rate. kwargs (dictionary): Optimizer arguments. Returns: tf.train.Optim...
c04c9348f26fdf25951f362a693cb70765133756
3,638,627
import yaml def generate_pruning_config(model_name, sparsity, begin_step=0, end_step=-1, schedule='ConstantSparsity', granularity='BlockSparsity', res...
42f566ce574b53d6effafcec18984c201fba7f92
3,638,628
def collect_FR_dev(stim_array,stim_dt,sim_dt,spikemon,n,return_spikes=False): """ get all firing rates for a given spikemon stim_array: array of stimulation time/strengths, e.g., [0,0,0,0,1,0,0,0,1,0,0] stim_dt: time interval of stimulation sim_dt: time interval of simulation spikemon_t: ti...
05914a68085112e0b1b4353dbd6434fb3e59c7c8
3,638,629
import json def assertDict(s): """ Assert that the input is a dictionary. """ if isinstance(s,str): try: s = json.loads(s) except: raise AssertionError('String "{}" cannot be json-decoded.'.format(s)) if not isinstance(s,dict): raise AssertionError('Variable "{}" is not a dictionary.'.forma...
302defb4e1eecc9a6171cda0401947e3251be585
3,638,630
import math def _consolidate_subdivide_geometry(geometry, max_query_area_size): """ Consolidate and subdivide some geometry. Consolidate a geometry into a convex hull, then subdivide it into smaller sub-polygons if its area exceeds max size (in geometry's units). Parameters ---------- ge...
32fbafcf3066cc73c022fc1482030d35387107c2
3,638,631
import logging def deleteAllPatientes(): """Delete all patient record Raises: HTTPException: raises if there is any error in underlying CRUD operation. Returns: null: success response if all the records are successfully deleted """ logging.debug("Router: /patient/all") ...
95eea9cd316c19dd6e73e560e45187ca6b96d06e
3,638,632
import ast from typing import Tuple from typing import List from typing import Any def get_function_args(node: ast.FunctionDef) -> Tuple[List[Any], List[Any]]: """ This functon will process function definition and will extract all arguments used by a given function and return all optional and non-optional...
a4fe9dccedd5684050a7d5e7949e384dd4021035
3,638,633
def svn_client_copy3(*args): """ svn_client_copy3(svn_commit_info_t commit_info_p, char src_path, svn_opt_revision_t src_revision, char dst_path, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return apply(_client.svn_client_copy3, args)
336aaec7d6c2a44f22d6b1164316f16b4fd5f53f
3,638,634
import json import copy def delete(server = None, keys = None): """ Marks an entity or entities as deleted on the server. Until an entity is permanently deleted (an administrative operation, not available through the RESTful API), it can still be accessed, but will not turn up in search results. ...
b3662ba85b1aacfca6034da5d5e198a5ffada2fa
3,638,635
import collections import csv def ParseMemCsv(f): """Compute summary stats for memory. vm5_peak_kib -> max(vm_peak_kib) # over 5 second intervals. Since it uses the kernel, it's accurate except for takes that spike in their last 4 seconds. vm5_mean_kib -> mean(vm_size_kib) # over 5 second intervals "...
5d10a0d0ac5ab3d3e99ff5fd4c9ca6cd0b74656b
3,638,636
def index_containing_substring(list_str, substring): """For a given list of strings finds the index of the element that contains the substring. Parameters ---------- list_str: list of strings substring: substring Returns ------- index: containing the substring or -1 """ ...
2816899bc56f6b2c305192b23685d3e803b420df
3,638,637
import pycountry import gettext import six def _localized_country_list_inner(locale): """ Inner function supporting :func:`localized_country_list`. """ if locale == 'en': countries = [(country.name, country.alpha_2) for country in pycountry.countries] else: pycountry_locale = gette...
c67b107d10b8bc2426de39f11c30e886b5fc2894
3,638,638
def ingest_questions(questions: dict, assignment: Assignment): """ questions: [ { sequence: int questions: [ { q: str // what is 2*2 a: str // 4 }, ] }, ... ] response = { rejected: [ ... ] ignored: [ ... ...
d72370bcaa5cf1f5017eda827cca6dd011ac36d0
3,638,639
from datetime import datetime def render_book_template(book_id): """ Find a specific book in the database. Locate the associated reviews (sorted by score and date). Create the purchase url. Check whether the user has saved the book to their wishlist. """ # Find the book document in the dat...
d30b30b79b102b1c08404bc00c69b1f22ccebc6a
3,638,640
def iatan2(y,x): """One coordinate must be zero""" if x == 0: return 90 if y > 0 else -90 else: return 0 if x > 0 else 180
a0b18b61d7ffadf864a94299bc4a3a0aacd7c65a
3,638,641
import torch def fuse_bn_sequential(model): """ This function takes a sequential block and fuses the batch normalization with convolution :param model: nn.Sequential. Source resnet model :return: nn.Sequential. Converted block """ if not isinstance(model, torch.nn.Sequential): return m...
6d31cd2cd73e8dc91098b7f9cc7f70ce3b81a3b9
3,638,642
def get_baseconf_settings( baseconf_settings_filename = None ): """ Returns the basic configuration settings as a parameter structure. :param baseconf_settings_filename: loads the settings from the specified filename, otherwise from the default filename or in the absence of such a file creates default sett...
0b0b829f4923072431b8e73c7fd70e732f17dc30
3,638,643
from blog import blog, user, api,auth import os def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) app.logger.debug('app.instance_path = %s', app.instance_path) app.config.from_mapping( SECRET_...
1f4ca85eccf4a5ab226d84470d90ccd0569d16aa
3,638,644
def subtract_background(image, background_image): """Subtracts background image from a specified image. Returns ------- bs_image : np.ndarray of type np.int | shape = [image.shape] Background-subtracted image. """ image = image.copy().astype(np.int) background = background_image.cop...
c136f78c1f355c2031ef60ca17fb0bd6fc63c94e
3,638,645
import math def batch_genomes(genomes, num_batches, order): """ Populates 2D numpy array with len(rows)==num_batches in {order} major order. Using col is for when you know you are using X number of nodes, and want- to evenly distribute genomes across each node Use row when you want to fill each no...
00fea150ea20ae886fd72f099a1c0bd4216ba987
3,638,646
def single_gate_params(gate, params=None): """Apply a single qubit gate to the qubit. Args: gate(str): the single qubit gate name params(list): the operation parameters op['params'] Returns: a tuple of U gate parameters (theta, phi, lam) """ if gate == 'U' or gate == 'u3': ...
153459403639103cdfa9502a26797e9c536ba112
3,638,647
def check_copr_build(build_id: int) -> bool: """ Check the copr_build with given id and refresh the status if needed. Used in the babysit task. :param build_id: id of the copr_build (CoprBuildModel.build.id) :return: True if in case of successful run, False when we need to retry """ logger...
792b25d6a15d25d0bae3ccdb942d95512139b70b
3,638,648
import sys def net_to_graph(net): """ Convert Net object from parse_net_file to graph represented (as per dijkstra.py) as dict of dicts where G[v][w] for any v,w is cost of edge from v to w. Here v and w are just integers (node numbers). Parameters: net (in/OUT) - Net object as returned by...
3f27a53eb0a0c49deddb5d88af4e1bdb999ca716
3,638,649
import time def runTests(data, targets, pipeline, parameters): """ Perform grid search with specified pipeline and parameters on data training set with targets as labels Evaluate performance based on precision and print parameters for best estimator grid search o...
122d1330444dd72aa064cd263cb7f405bf2bf9ba
3,638,650
def isMultipleTagsInput(item): """ Returns True if the argument datatype is not a column or a table, and if it allows lists and if it has no permitted value. This function is used to check whether the argument values have to be delimited by the null character (returns True) or not. :param item: Tab...
f7710902e27962fc8df55bc75be2d5d404144aeb
3,638,651
def imagenet_vgg_compression(compression_config, var_config, overall_model, muVes, strategy, optimizer, verbose=True): """ :param compression_config: :param var_config: :param overall_model: :param muVes: :param strategy: :param optimizer: :param verbose: :return: """ cc = c...
27d52928046af28f4243e667887958e679e8655d
3,638,652
def remove_url(url: str = Form(...)): """ Remove url from the url json file :param url: api url in the format: http://ip:port/ :return: ApiResponse """ try: payload = helpers.parse_json(url_config_path) except Exception as e: return ApiResponse(success=False, ...
c7c218926c2992df19b3988987fca8cf2bbff3d1
3,638,653
def load_CSVdata(messages_filepath, categories_filepath): """ Load and merge datasets messages and categories Inputs: Path to the CSV file containing messages Path to the CSV file containing categories Output: dataframe with merged data containing messages and categories ...
e216c09ca403545fbc1152a25e966efeb4baeefc
3,638,654
def accept_invite(payload, user): """ Accepts an invite args: payload, user ret: response """ try: invite = Invites.get(payload['invite'])[0] except: return Message( Codes.NOT_FOUND, { 'message': 'There isn\'t any active invite with the given id.' } ...
bff423eeec7f7f527771934de0f32ede0f528948
3,638,655
from typing import Tuple from typing import Dict from typing import List import re def clean_status_output( input: str, ) -> Tuple[bool, Dict[str, str], List[Dict[str, str]]]: # example input """ # Health check: # - dns: rename /etc/resolv.conf /etc/resolv.pre-tailscale-backup.conf: device or ...
bbf100514373595948b0691dff857deb5772f019
3,638,656
def test_tensor_method_mul(): """test_tensor_method_mul""" class Net(Cell): def __init__(self): super(Net, self).__init__() self.sub = P.Sub() def construct(self, x, y): out = x * (-y) return out.transpose() net = Net() x = ms.Tensor(np...
89866ebd9311e0bac0e3324b01545507b986751f
3,638,657
def _get_top_artists(session: Session, limit=100): """Gets the top artists by follows of all of Audius""" top_artists = ( session.query(User) .select_from(AggregateUser) .join(User, User.user_id == AggregateUser.user_id) .filter(AggregateUser.track_count > 0, User.is_current) ...
ae6a45e7190995fc35daf62236e73c4bd5c6235f
3,638,658
import os def get_imagenet_lmdb(train_transform, val_transform, test_transform, CONFIG): """ Load lmdb imagenet dataset https://github.com/Fangyh09/Image2LMDB """ train_path = os.path.join(CONFIG.dataset_dir, "train_lmdb", "train.lmdb") val_path = os.path.join(CONFIG.dataset_dir, "val_lmdb", "...
8d3b66f9436db2d072e097d98cb44693c3bf001b
3,638,659
def _get_other_locations(): """Returns all locations except convention venues.""" if 'all' not in location_cache.keys(): conv_venue = LocationType.objects.get(name='Convention venue') location_cache['all'] = Location.objects.exclude(loc_type=conv_venue) return location_cache['all']
a34bf432529a31bc013988c394230e55b01ac21b
3,638,660
import torch def _check_cuda_version(): """ Make sure that CUDA versions match between the pytorch install and torchvision install """ if not _HAS_OPS: return -1 _version = torch.ops.torchvision._cuda_version() if _version != -1 and torch.version.cuda is not None: tv_version = ...
d86e209d10514060f0c15bff9ea28df6b2054480
3,638,661
def largest(layer,field): """largest(layer,field) Returns the largest area significant class in the study area. """ theitems = [] rows = arcpy.SearchCursor(layer) for row in rows: theitems.append(row.getValue(field)) del rows theitems.sort() max1= theitems[-1] return ma...
ff6433a5fef48550e902317384dec746136063dc
3,638,662
import asyncio import random async def double_up(ctx): """ 「ダブルアップチャンス!」を開始します。 """ depth = 1 # 現在の階層 HOLE = "\N{HOLE}\N{VARIATION SELECTOR-16}" LEFT_ARROW = "\N{LEFTWARDS BLACK ARROW}\N{VARIATION SELECTOR-16}" RIGHT_ARROW = "\N{BLACK RIGHTWARDS ARROW}\N{VARIATION SELECTOR-16}" TOP_AR...
3ec1394d681fcb0e626e98b11bd815dddbe64254
3,638,663
def read_version(file_contents): """Read the project setting from pyproject.toml.""" data = tomlkit.loads(file_contents) details = data["tool"]["poetry"] return details["version"]
7255c199463437765d21658f792a54049bbb45ee
3,638,664
from datetime import datetime def schedule_time(check_start_time, check_end_time, time_duaration=7) -> dict: """ Returns dictionary of earliest available time within the next week """ all_busy_events = get_busy_events() for d in range(1,time_duaration): # Increment by one day throughout the week ...
858387e8d07634df7a143b3ee500e648ed54abd6
3,638,665
import array def _to_array(value): """When `value` is a plain Python sequence, return it as a NumPy array.""" if not hasattr(value, 'shape') and hasattr(value, '__len__'): return array(value) else: return value
3bf185f34c51dc2042bdb05138b0febd9e89b421
3,638,666
def dict_pix_to_deg(input_dict, changeN): """Convert pix to deg for a given dictionary format, changeN is 1 or 2, to let the function works for the first or both elements of the tuple""" dict_deg = {} for key, values in input_dict.items(): new_display = [] for display in values: ...
03c49e113c8805c4d675899f3c61e3ae00bd7681
3,638,667
def remove_container_name_from_blob_path(blob_path, container_name): """ Get the bit of the filepath after the container name. """ # container name will often be part of filepath - we want # the blob name to be the bit after that if not container_name in blob_path: return blob_path b...
e02807abebdf3a193efcabee1dda3f733a780dd5
3,638,668
from typing import Dict from typing import List def _complex_ar_from_dict(dic: Dict[str, List]) -> np.ndarray: """Construct complex array from dictionary of real and imaginary parts""" out = np.array(dic["real"], dtype=complex) out.imag = np.array(dic["imag"], dtype=float) return out
a3938619f84c2dcbec5c9ac90c0064ea380346c4
3,638,669
def endpoint(url_pattern, method="GET"): """ :param url_pattern: :param method: :param item: :return: """ def wrapped_func(f): @wraps(f) def inner_func(self, *args, **kwargs): """ :param self: :param args: :param kwargs: ...
23b68a1440e96eac27926f2a37d96cb74a568734
3,638,670
def elastic_transform( image, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, random_state=None, approximate=False, ): """Elastic deformation of images as described in [Simard2003]_ (with modifications). Based on https://gist.github...
e60754cc898d83051164180b1d07ac0e4c688946
3,638,671
import re from orangecontrib.xoppy.util.xoppy_xraylib_util import f0_xop def crystal_atnum(list_AtomicName, unique_AtomicName, unique_Zatom,list_fraction, f0coeffs): """ To get the atom and fractional factor in diffierent sites list_AtomicName: list of all atoms in the crystal unique_AtomicName: lis...
f9805890971e1c2e6696084fad5f8b9071999046
3,638,672
def integrate(name, var): """ given filename and var, generate profile """ d = vtk.vtkExodusIIReader() d.SetFileName(name) d.UpdateInformation() d.SetPointResultArrayStatus(var,1) d.Update() blocks = d.GetOutput().GetNumberOfBlocks() data = d.GetOutput() # range...
116993d18c4430f6ce0e7dacba8b73ef3a03f689
3,638,673
def mediate(timer: TimerBase, decimals: int | None) -> int: """If the start function doesn't have decimals defined, then use the decimals value defined when the Timer() was initiated.""" return timer.decimals if decimals is None else validate_and_normalise(decimals)
030ec62071bc4c2bc41ae30c5eb8212b36e0359a
3,638,674
def calculate_n_inputs(inputs, config_dict): """ Calculate the number of inputs for a particular model. """ input_size = 0 for input_name in inputs: if input_name == 'action': input_size += config_dict['prior_args']['n_variables'] elif input_name == 'state': i...
78d750ff4744d872d696dcb454933c868b0ba41e
3,638,675
from typing import Sequence from typing import Tuple def clustering( adata: ad.AnnData, resolutions: Sequence[float], clustering_method: str = "leiden", cell_type_col: str = "cell_types", batch_col: str = "batch_indices" ) -> Tuple[str, float, float]: """Clusters the data and calculate agreeme...
c94efe865ca2ee52c7dfeeef40e46bc20786e284
3,638,676
from datetime import datetime async def login_swagger(form_data: OAuth2PasswordRequestForm, db: AsyncIOMotorClient) -> LoginUserReplyModel: """ Login route, returns Bearer Token. SWAGGER FRIENDLY. Due to the swagger Api not letting me add otp as a required parameter the otp needs t...
b6452d28570ebbd3b09c52690da34ea6b7d5d1a6
3,638,677
def coords(lat: float, lon: float, alt: float = None ) -> str: """Turn longitude, latitude into a printable string.""" txt = "%2.4f%s" % (abs(lat), "N" if lat>0 else "S") txt += " %2.4f%s" % (abs(lon), "E" if lon>0 else "W") if alt: txt += " %2.0fm" % alt return txt
c5768e03c55d5f567695056d78108812014b9ef4
3,638,678
def chromosome_to_smiles(): """Wrapper function for simplicity.""" def sc2smi(chromosome): """Generate a SMILES string from a list of SMILES characters. To be customized.""" silyl = "([Si]([C])([C])([C]))" core = chromosome[0] phosphine_1 = ( "(P(" + chromosome[1] + ...
793995484c46295977f1d312c4fa11f69bca6c84
3,638,679
def softmax_edges(graph, feat): """Apply batch-wise graph-level softmax over all the values of edge field :attr:`feat` in :attr:`graph`. Parameters ---------- graph : DGLGraph The graph. feat : str The feature field. Returns ------- tensor The tensor obtaine...
f5dafccca3c487756deeb37f534ef178cf1de75f
3,638,680
def command_result_processor_parameter_required(command_line_parameter): """ Command result message processor if a parameter stays unsatisfied. Parameters ---------- command_line_parameter : ``CommandLineParameter`` Respective command parameter. Returns ------- message ...
fed1b7af60018cb5638e021365ae754477b7a241
3,638,681
def randdirichlet(a): """ Python implementation of randdirichlet.m using randomgamma fucnction :param a: vector of weights (shape parameters to the gamma distribution) """ try: x = rand.randomgamma(a) except ValueError: a[a == 0] += 1e-16 x = rand.randomgamma(a) x /= x...
c825fb81c07337231f49437a2bea7ddd5a40234f
3,638,682
def home(request): """ This is the home page request """ return render(request, 'generator/home.html')
ad8b69871d484c16583752d029fec2970084e698
3,638,683
def print_insn_mnem(ea): """ Get instruction mnemonics @param ea: linear address of instruction @return: "" - no instruction at the specified location @note: this function may not return exactly the same mnemonics as you see on the screen. """ res = ida_ua.ua_mnem(ea) if not res:...
4c60e853356217c2fbfdd21047429c729b57f10f
3,638,684
def setdim(P, dim=None): """ Adjust the dimensions of a polynomial. Output the results into Poly object Args: P (Poly) : Input polynomial dim (int) : The dimensions of the output polynomial. If omitted, increase polynomial with one dimension. If the new dim is ...
610138c1d1a13112d35583d758cac43c1e296d18
3,638,685
def extract_file_from_zip(zipfile, filename): """ Returns the compressed file `filename` from `zipfile`. """ raise NotImplementedError() return None
dc7b1e5a196a019d1fd2274155e0404b03b09702
3,638,686
def reframe_box_masks_to_image_masks(box_masks, boxes, image_height, image_width): """Transforms the box masks back to full image masks. Embeds masks in bounding boxes of larger masks whose shapes correspond to image shape. Args: box_masks: A tf.float32 tensor of size [n...
b8fb1d255b01bfbd8f89dbf1a31c797342279e0f
3,638,687
import torch def multi_classes_nms(cls_scores, box_preds, nms_config, score_thresh=None): """ Args: cls_scores: (N, num_class) box_preds: (N, 7 + C) nms_config: score_thresh: Returns: """ pred_scores, pred_labels, pred_boxes = [], [], [] for k in range(cls_sco...
a0451c3769b4415e7e7d184d43f6b8f121b651b1
3,638,688
def check_str_length(str_to_check, limit=MAX_LENGTH): """Check the length of a string. If exceeds limit, then truncate it. :type str_to_check: str :param str_to_check: String to check. :type limit: int :param limit: The upper limit of the length. :rtype: tuple :returns: The string it self...
73ae59241a18c5398c041c2c332c932831a39c55
3,638,689
async def create_or_update( hub, ctx, name, resource_group, prefix_length, sku="standard", public_ip_address_version="IPv4", zones=None, **kwargs, ): """ .. versionadded:: 4.0.0 Creates or updates a static or dynamic public IP prefix. :param name: The name of the pu...
08fb4db3f585ec8844e28e5fa90867f588cdb91a
3,638,690
def _get_job_name(job_label: str = None) -> str: """Returns Beam runner job name. Args: job_label: A user defined string that helps define the job. Returns: A job name compatible with apache beam runners, including a time stamp to insure uniqueness. """ job_name = 'tfrecorder-' + common.get_t...
3786c532109c880ec9255b82a6a2442cf8414780
3,638,691
def all_not_none(*args): """Shorthand function for ``all(x is not None for x in args)``. Returns True if all `*args` are not None, otherwise False.""" return all(x is not None for x in args)
2d063f39e253a78b28be6857df08d8f386d8eb4a
3,638,692
def weighted_photon_spec(eng): """ Returns the weighted photon spectrum from positronium annihilation. This assumes 3/4 ortho- and 1/4 para-, normalized to a single annihilation. Parameters ---------- eng : ndarray The energy abscissa. Returns ------- Spectrum T...
39b5301d5e49f070d1128d678f4f0672b32c275d
3,638,693
def get_for_tag(app_name): """ Retorna a tag for customizada para listar registros no template list.html :param app_name: Nome do app que está sendo criado :type app_name: str """ return "{% for " + app_name + " in " + app_name + "s %}"
12399a148262893047bf21c20e784bfb33373c29
3,638,694
def _reloadFn(*args): """Placeholder callback function for :func:`_handleSIGHUP`.""" return True
261a54f52e4e448671b8625dae4fbc67116bd546
3,638,695
def interpolation_lagrange_matrix(old_grid, new_grid): """ Evaluate lagrange matrix to interpolate state and control values from the solved grid onto the new grid. Parameters ---------- old_grid : <GridData> GridData object representing the grid on which the problem has been solved. new...
ce219dbfa65842ad275fe22f1122474b865fcfb0
3,638,696
def optimize_shim(coils, unshimmed, mask, mask_origin=(0, 0, 0), bounds=None): """ Optimize unshimmed volume by varying current to each channel Args: coils (numpy.ndarray): X, Y, Z, N coil map unshimmed (numpy.ndarray): 3D B0 map mask (numpy.ndarray): 3D inte...
f9e5d88e4a54222c841b3a2a66254675218207c4
3,638,697
def _log(x1): """closure of log for zero arguments, sign-protected""" with np.errstate(divide="ignore", invalid="ignore"): x1 = np.where(np.abs(x1) > 0.001, x1, 1) return np.where(x1 < -1, np.log(np.abs(x1)) * np.sign(x1), np.log(np.abs(x1)))
bcc782434b1e38749096d56e6b78df287a14eeb2
3,638,698
def whats_the_meaning_of_life(n_cores=23): """Answers the question about the meaning of life. You don't even have to ask the question, it will figure it out for you. Don't use more cores than available to mankind. Parameters ---------- n_cores: int [default: 23] The number of CPU cores...
9b42257161ad3063bd7d8faddb6e385aa5586bf0
3,638,699