content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import random def generator_order_code(sex=None): """ 生成顺序码 :param sex: :return: """ order_code = random.randint(101, 1000) if sex == 1: order_code = order_code - 1 if order_code % 2 == 0 else order_code if sex == 0: order_code = order_code if order_code % 2 == 0 else o...
52be4dd5d9a40d261511adbe57271824a09592bf
3,627,300
def fasta_reader(fa, q, *filters): # TO DO # Check packing/unpacking # Should this be just a list, even if it's empty? """ Reader worker for the fa file in the specified q(ueue) Applies a filter on the sequence length > 1. This is there to parse out (a) empty sequence strings (b) se...
dde75f77b33d7dc65c4c37087bd4e04eb7b0c8c3
3,627,301
def test(model, test_inputs, test_labels): """ Runs through one epoch - all testing examples :returns: accuracy """ num_predict_corrections = 0 num_times_we_guessed_zero = 0 num_batches = len(test_labels) for batch_no in range(num_batches): test_input = test_inputs[batch_no] ...
c84b705ce321d60fe294de10ded6f6c474b79dae
3,627,302
def mirantis(cred): """ :returns: list [{'region': str, 'timestamp': int, 'nodes': list}] """ return _openstack(Provider.OPENSTACK, cred)
d5ad35b8cdb6bc48d4d75d4d8d72715fe0cfb566
3,627,303
def load(path, encoding="utf-8"): """ 从文件夹加载 CDTB 格式文档 :param path: 文档文件夹路径 :param encoding: 文档编码 :return structure.tree.Discourse 生成器 """ return CDTB.load(path, encoding=encoding)
8993d79e112ff97ced08c6315523433e0d20b85d
3,627,304
import os def load_spikes(filename, recording_number): """ Loads spike data, using memory mapping to improve performance The returned data is not memory mapped Input: ===== filename - string path to the data file (.spikes, .events, or .continuous) recording_inde...
c411c2ffdb0459b3beed0e9d86660a1e1e8fcf59
3,627,305
import io def _get_exchange_info() -> pd.DataFrame: """ Returns a dataframe of exchange listings for initializing the Universe class Called upon initialization of the Universe class, updates the stock listings that are available by default when gathering stock data from the internet Returns: ...
7384879bb4009851bd761093c04d00c60aee2feb
3,627,306
import os def create_pie_chart(data, rngs, colors=['#244268', '#426084', '#67809F', '#95A9C1', '#C6D2E0'], unit_scale=1.0, measure_quantity='m^3', figsize=(33, 15), legend_loc=(0.383, -0.25), zebra_color=(False, 3), legend_fontsize=50, chart_fontsize=60, ...
6a83bb0a80d988655cf7159bad1158530f87eabb
3,627,307
import pathlib def read_xr_and_concat(fname: pathlib.Path): """Reads the given filename and concatenates it into a single file. Assumes that the filename is an xarray file which was made by parsing many calcium analysis results. """ data = xr.open_dataset(fname).dff return np.vstack(data)
2b23bffcbbae0ed9e9d4cfeaaecc72107ba8cdc6
3,627,308
import os def ee_dask_deploy(config, pb_id, image, n_workers=1, buffers=[]): """Deploy Dask execution engine. :param config: configuration DB handle :param pb_id: processing block ID :param image: Docker image to deploy :param n_workers: number of Dask workers :param buffers: list of buffers ...
738d5d1245927915c5d916aeca8544c233b4bec6
3,627,309
def _filterProviders(providers, item, cfgData, dataCache): """ Take a list of providers and filter/reorder according to the environment variables """ eligible = [] preferred_versions = {} sortpkg_pn = {} # The order of providers depends on the order of the files on the disk # up to ...
cc108fd5a15c524a1c32bd37d3b4111d92a5ae67
3,627,310
def is_win(record): """ Test for specific domains :param record: line to analyse :return: True if is specific for Windows, False otherwise """ return win_reg1.search(record) or win_reg2.search(record) or win_reg3.search(record) \ or win_reg4.search(record) or win_reg5.search(record) o...
3c2f3af4a6c203d16e22341d2545f4cfe262d7c0
3,627,311
import logging def initialize_nose_logger() -> logging.Logger: """Configures the logger to be used by the "nose" package. """ print("initialize_nose_logger()") logger_config = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { ...
715fe7378999841a2bb8c46205fb508917f175be
3,627,312
def sq_sums(a_gpu, b_gpu, GSZ=GSZ): """ Compute squared summations of rows from GPUArrays and then their pairwise summations. Parameters ---------- A : GPUArray B : GPUArray GSZ : int, optional Grid size for CUDA kernel invocation Returns ------- out : GPUArray ...
4de45c202abcb665ca3b33aee504c646727ba486
3,627,313
def timealize_img(experiment, image, label): """ Transforms an image to an image with timesteps to be fed into a SNN. Copies the image timesteps times and stacks them together. Equivalent of feeding the SNN a raw input current, not feeding it spikes. :param experiment: :param image: :param l...
acefe04bc5de1fcc5a6cdf6fd400bb69ebe0e224
3,627,314
def simpleClosedPath(listPts): """Returns the closed path of the given points""" points = listPts[:] # making a compy of the listPts y_min_index = getBottomRight(listPts) y_min_point = points.pop(y_min_index) closed_path = [(y_min_point, 0)] for point in points: angle = theta(y_min_p...
151967973bd1c777a4aa0ff65c1516ffa6d50016
3,627,315
def home(): """ Route for displaying the homepage. """ return render_template("home.html", home=True)
e7426ac8cd8f2e2792ec0940ae8555444b47e962
3,627,316
def timefunc(func, msg, *args, **kwargs): """Benchmark *func* and print out its runtime. Args: msg (str): func: *args: **kwargs: Returns: object: """ # Make sure the function is compiled before we start the benchmark res = func(*args, **kwargs) # T...
67c2c1b8abe0f8dc05020d88b45154619fd49012
3,627,317
def button(where=None, x=0, y=0, label="", width=0, height=30, idle=None, over=None, down=None, color=(50,50,50)): """Display a button whose graphics are images (np.ndarray). The button accepts three images to describe its states, which are idle (no mouse interaction), over (mouse is over the button) and down (mouse c...
ced0cb82fca6a8af9913a899a6714ea9cc0f8c4d
3,627,318
def action_checker(target_name): """ Checks in on targets.json and determines what actions are available for the requesting target. Parameters ---------- target_name: str Returns ------- A list of available actions for the target. """ target_json = get_target_data(target_name) ...
4168219285f0c884d6640103eb2e9b95d94bf6c9
3,627,319
def get_licence(html): """ Searches the HTML content for a mention of a CC licence. """ if "creative-commons" in html or "Creative Commons" in html: licence = "CC" else: licence = "N/A" return licence
07dcd2439455fd23b034e11204d2a474c9502cdf
3,627,320
def get_selected_ctrl(): """ the joints from current selection. :return: <tuple> array of joints from selection. """ selected_obj = object_utils.get_selected_node() if selected_obj and object_utils.is_shape_curve(selected_obj): return selected_obj
60f935377302c4a6ebb6ddc3afed161306666e6d
3,627,321
def sum_temp(s, n): """ :param s: int, sum of total value of temperature :param n: int, latest information to add up :return: s + n """ s += n return s
4dc7da032fd91da86d73bf545fdf527497c12cd5
3,627,322
def foreground_rainbow(ncolors=20, background_color=BLACK): """ A rainbow gradient of `ncolors` ColorPairs with a given background color. """ return [ ColorPair(*foreground_color, *background_color) for foreground_color in _rainbow_gradient(ncolors) ]
44a934ea8ee4a95b46ad3559e91e6044c0f0494b
3,627,323
import re def get_method_parameter_values(code, line, full_sig): """ Returns a List of parameter values for the method at a given line """ param_list = [] offset = int((get_offset(code, line, "catch(") - 3)) line += (1 + int(offset / 2)) for i in range(int(offset / 2)): param_pattern = re...
0c4803710daaffcb015361665dcd3604d0b9960b
3,627,324
def mrc_to_dask(fname: Pathlike, chunks: tuple): """ Generate a dask array backed by a memory-mapped .mrc file """ with access_mrc(fname, mode="r") as mem: shape, dtype = mrc_shape_dtype_inference(mem) chunks_ = normalize_chunks(chunks, shape) def chunk_loader(fname, block_info=None): ...
10da8a3a8d9abf13fafbd98be3e3f1f4b2bc7264
3,627,325
import os def get_local_path_kind(pathname): """Determine if there is a path in the filesystem and if the path is a directory or non-directory.""" try: os.stat(pathname) if os.path.isdir(pathname): status = LOCAL_PATH_DIR else: status = LOCAL_PATH_NON_DIR ...
787683925a8f01441f5f7d7cd5b0563755c70283
3,627,326
def mock_random_choice(seq): """Always returns first element from the sequence.""" # We could try to mock a particular |seq| to be a list with a single element, # but it does not work well, as random_choice returns a 'mock.mock.MagicMock' # object that behaves differently from the actual type of |seq[0]|. ret...
a889c7ca32b6d494493000134c1d9d26fe5e97c3
3,627,327
from typing import Tuple from typing import Callable import sys def mount_remote_volumes( runner: Runner, remote_info: RemoteInfo, ssh: SSH, allow_all_users: bool ) -> Tuple[str, Callable]: """ sshfs is used to mount the remote system locally. Allowing all users may require root, so we use sudo in th...
5522e4f25a2d3755d5b5013e3d356af91af98fa0
3,627,328
def find_entries_without_field(path_or_db, field): """Return entries without field.""" _, db = _load_or_use(path_or_db) lacking_entries = [] for entry in db.entries: if field not in entry: lacking_entries += [entry] return lacking_entries
308aab183bb1a8977f7c7404515911076eb0450d
3,627,329
import numpy def valley_width_transform(valleys): """Calculate the approximate distributed valley width `from bluegeo.water import valley_width_transform;test = valley_width_transform('/Users/devin/Desktop/valley.tif')` Arguments: valleys {[type]} -- [description] """ valleys = Raster(va...
2f76a3484264ca1c509ad6c7e07839c6655a47af
3,627,330
def add_contents_entry(section, page_variable, feature, parent): """ Adds a new row to the table of contents table. <p> The table should be called 'report_contents' and be structured with a 'section' and a 'page' column. No detailed checks are made to confirm this structure is in place. </p><p>...
9e50715bd40bad8f94c560ada09833a270e7d512
3,627,331
def V_6_3_3(b, h0, ft): """ 不配置箍筋和弯起钢筋的一般板类受弯构件斜截面承载力 """ if h0<800: beta_h = 1 elif h0<2000: beta_h = (800/h0)**0.25 else: beta_h = (800/2000)**0.25 return 0.7*beta_h*ft*b*h0
79e9d97fcc755ed163cedb5f775d07abb6c26595
3,627,332
import ast def make_cond_block(): """ if flor.skip_stack.peek().should_execute(not flor.SKIP): pass TODO: Extend to accept predicate """ previous_arg = ast.UnaryOp( op=ast.Not(), operand=ast.Attribute( value=ast.Name('flor', ast.Load()),...
5b2d2a61c295d765f192f9d24950799f46f34ef0
3,627,333
def removeInteger(string): """ Remove an integer from a string. Args: string: write your description """ _checkSequenceError(string=string, start=bytesHexB, expected="02") length, lengthLen = _readLength(string[1:]) numberBytes = string[1 + lengthLen:1 + lengthLen + length] res...
54e2905bf9f68224ba35b3c9e2d5c94bf81bdfd0
3,627,334
import select def get_urls(): """The get_urls function fetches 16 urls from the database that need to be scraped by the bee. The Url which are set with a priority in the database will be retrieved first. """ return select(u for u in Url if u.date_scraped is None).order_by(desc(Url.priority_scrape))[:8...
2e181424ae6795838f2a468cd3e59a6153cd3d5c
3,627,335
import json def convert_input_to_userid(input_id): """ Take user input from app (Steam user ID or vanity URL) and output Steam user ID for further API calls ] """ req = Request('http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=%s&vanityurl=%s'%(api_key, input_id)) try: data_raw = urlopen(re...
7f18e720dca48c33c892b7ad3e1970c057d4e6b8
3,627,336
def create_citydist(create_environment, create_building): """ Pytest fixture function to generate city district with three res. buildings (with demands) on positions (0, 0), (0, 10), (10, 10) Parameters ---------- create_environment : object Environment object (as fixture of pytest) ...
116cc1974b295198aade37b9bc0ee49a5e141a2b
3,627,337
def read_log(log_file, skip_log_rows=None, skip_log_conditions=None): """Reads the behavioral log file with information about each EEG trial.""" # Check if data are already in a DataFrame if isinstance(log_file, pd.DataFrame): log = log_file else: # Detect file encoding with op...
b52a852092b9e0d56cbe264301b5000d2df777f8
3,627,338
import hashlib def sha1_base32(buf: bytes, n: int = None): """ Return a base32 representation of the first n bytes of SHA1(buf). If n = None, the entire buffer will be encoded. """ return base32(hashlib.sha1(buf).digest()[slice(0, n)])
f5cae574c2dfaf6e2a031203858145239289e41e
3,627,339
def get_lsf_grid_name(fibre_number): """ Return the appropriate LSF name (a, b, c, or d) to use, given a mean fiber number. :param fiber_number: The mean fiber number of observations. :returns: A one-length string describing which LSF grid to use ('a', 'b', 'c', or 'd'). """ ...
009b20027f895e19c5b6cabb4476cf41a222e465
3,627,340
from typing import List def get_named_layers_and_params_by_regex( module: Module, param_names: List[str], params_strict: bool = False, ) -> List[NamedLayerParam]: """ :param module: the module to get the matching layers and params from :param param_names: a list of names or regex patterns to m...
6f6e2a42158e2dbe7762bcc13d9991279967d3e0
3,627,341
def draw_box(to_draw, xmin, xmax, ymin, ymax, cname, cindex, class_colors, conf=None, extratext=""): """ Draws a box on top of an image. The image is then returned. Arguments: to_draw -- image to draw on xmin, xmax, ymin, ymax -- coordinates of the box cname ...
db60a02cfe0e3cb438f078cabba3be1b445ea060
3,627,342
def _get_node(pending_set, pre_sel=[], opts={}): """ Next node preferably in pre-selected nodes """ shuffle(pre_sel) for node in pre_sel: if node in pending_set: pending_set.remove(node) return node # Random if not return pending_set.pop()
2dfcfd96479ec19c074cd52129dee9fd018243b0
3,627,343
import functools def callCounter(func): """function call counter""" @functools.wraps(func) def helper(*args, **kwargs): helper.calls += 1 return func(*args, **kwargs) helper.calls = 0 return helper
a999210fd0f553ccc5d00ffc4c61ccc09deba4b9
3,627,344
def deprecated(func): """Print a deprecation warning once on first use of the function. >>> @deprecated # doctest: +SKIP ... def f(): ... pass >>> f() # doctest: +SKIP f is deprecated """ count = [0] def wrapper(*args, **kwargs)...
882b26592fa620be65eb7e1306abdf1d138ca022
3,627,345
import numpy def eigsh(a, k=6, *, which='LM', ncv=None, maxiter=None, tol=0, return_eigenvectors=True): """Finds ``k`` eigenvalues and eigenvectors of the real symmetric matrix. Solves ``Ax = wx``, the standard eigenvalue problem for ``w`` eigenvalues with corresponding eigenvectors ``x``. ...
5486b984e47b0e1702c57c077a55519371117c09
3,627,346
def calc_t_frame(n_col, n_row, n_amp, ins): """Calculates the frame time for a given ins/readmode/subarray. Parameters ---------- n_col : int Number of columns. n_row : int Number of rows. n_amp : int Amplifiers reading data. ins : str The instrument key. ...
3f26f0e29a3522c1a3ccf6fdc35635ac11e1648e
3,627,347
def verify_bytesio(enc_message, verify_key_hex, signature): """ Verify asymmetrically signed bytesreams. :param bytes enc_message: encrypted data :param bytes verify_key_hex: serialized verification key :param bytes signature: signature """ verify_key = nacl.signing.VerifyKey(verify_key_hex, en...
b98a9c9c9c4a14dc52e91ea5764143a2c2f36ab2
3,627,348
import logging import json def rest_error_message(error, jid): """Returns exception error message as valid JSON string to caller :param error: Exception, error message :param jid: string, job ID :return: JSON string """ logging.exception(error) e = str(error) return json.dumps({'user_i...
7422c77be37ed473ed15acc5fdfae9e85ff90812
3,627,349
def typedefn_from_root_element(el: UxsdElement) -> str: """Generate a C++ class declaration of a root element, which inherits its content type and adds load and write functions. """ out = "" out += "/** Generated from:\n" out += utils.to_comment_body(el.source) out += "\n*/\n" out += "class %s : public %s {\n" ...
63ecabd9b8e778ef7ccd4d6516ba0f60ef450990
3,627,350
def store(url, date, content): """Store article in database.""" if type(date) is str: date = iso2ts(date) return crawldb.add(url, content, version=date)
0114dbdfebdf76b70378f32c9cb4698e99359df4
3,627,351
def Dict(val): """ Build a dict for key/value pairs. """ return dict(val)
47864a91183070a7f8ce285e330d1278828b8352
3,627,352
def get_distracting_answer_by_visual7w_generation(qa_id, correct_answer, candidate_dict, res_cnt=3): """ Args: qa_id: int correct_answer: str candidate_dict: dict of (id, candidate), generated by visual7w baseline model """ res = [] if qa_id not in candidate_dict: pri...
f114a0da2b0598f48326a701c5d2e7fa1bc34023
3,627,353
def diag(req, resp): """ Data about the state of the database """ return { 'driver': engine.driver, 'tables': engine.table_names() }
d141aba9c726775505ed98c8ea80ca277b1acc95
3,627,354
import os import pathlib def as_path(path: PathLike) -> ReadWritePath: """Create a generic `pathlib.Path`-like abstraction. This function Args: path: Pathlike object. Returns: path: The `pathlib.Path`-like abstraction. """ if isinstance(path, str): if os.name == 'nt' and not path.startswith...
85157a165ba23c6f523154f53d94b46ee86936a9
3,627,355
def dc_loss(embedding, label): """ Deep clustering loss function. Args: embedding: (T,D)-shaped activation values label: (T,C)-shaped labels return: (1,)-shaped squared flobenius norm of the difference between embedding and label affinity matrices """ xp = cuda.get_array...
8f1fb8a9307dc6af465f43e8236dee45b19fea86
3,627,356
import urllib import json import time def ScrapeAdMetadataByKeyword(CurrentSession, Seed, NumAds = 2000): """ Returns a list of dictionaries that includes metadata of the Ad and also includes it's performance details. Our program crawls 5000 ads in the first iteration and then 500 ads in the subsequ...
e9446fb44d28c984bb3b252183d522d7438d9fab
3,627,357
from typing import Optional import os def get_all_slots_metadata(player_id: str, page_size: int, consistent_read: bool, start_key: Optional[str]): """Get metadata for all save slots, or an empty list if no metadata is found.""" gamesaves_table = ddb.get_table(table_name=os.environ.get('GAMESAVES_TABLE_NAME'))...
2de88ba9fd04fd7f471f66c7339a00a6dbc155a3
3,627,358
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities): """Set up the platform from config_entry.""" # We should scan options for alert configs and then if at least 1 listener is enabled subscribe for the stream hik_client = hass.data[const.DOMAIN][config_entry.entry...
907de6fbb5245fc98b0de2cbac8387bdf147dee6
3,627,359
def image_pil2cv(img): """Convert a PIL image to an opencv image. Args: img (PIL image): A PIL image of uint8 between 0 and 255 using RGB channels. Returns: np.array: A numpy image loaded with opencv of uint8 between 0 and 255 using BGR channels. Examples: >>> img ...
a3e44b1f290dd412afd4af62e8ee8fcd138c1aba
3,627,360
def _ww3_ounf_contents(run_date, run_type): """ :param run_date: :py:class:`arrow.Arrow` :param str run_type: :return: ww3_ounf.inp file contents :rtype: str """ start_date = ( run_date.format("YYYYMMDD") if run_type == "nowcast" else run_date.shift(days=+1).format("...
62618639265e419b5ad1ff9c7364e6d83aeca1c0
3,627,361
from typing import Tuple def _search(matrix: np.ndarray, tour: np.ndarray, x: int, y: int, z: int) -> Tuple[int, float]: """ Поиск лучшей замены, среди всех возможных замен matrix: Матрица весов tour: Список городов x, y, z: Города, для которых пробуем найти изменение тура return: Тип переворота, ...
0bd0468c2b1f206f27020ee3d9c5029606e1a8e8
3,627,362
from typing import Iterable from typing import List import logging from typing import Callable from typing import Optional def __build_transfer_paths( requests_with_sources: "Iterable[RequestWithSources]", multihop_rses: "List[str]", schemes: "List[str]", failover_schemes: "List[str]",...
294c1b97f9465b77429ff8c6d52c57fdb2a72794
3,627,363
import itertools def new_min_max(_builtin_func, *args, **kwargs): """ To support the argument "default" introduced in python 3.4 for min and max :param _builtin_func: builtin min or builtin max :param args: :param kwargs: :return: returns the min or max based on the arguments passed """ ...
4aae098143c4c96b53ec6b5fa9b240de936b9ecc
3,627,364
from typing import Optional import os def get_database_config(parsed: ConfigParser, manager: ConfigManager) -> dict: """ Generate a populated configuration dictionary. TODO: This should be shared with dbManager.py. :param parsed: ConfigParser :param manager: ConfigManager :return: Dic...
217dd99e5f1c0d40f184c82b7ac36d6a642b008c
3,627,365
def eigenvector_centrality( G, max_iter=100, tol=1.0e-6, normalized=True ): """ Compute the eigenvector centrality for a graph G. Eigenvector centrality computes the centrality for a node based on the centrality of its neighbors. The eigenvector centrality for node i is the i-th element of the ...
b6e710f9955b86eb661bc955f6e5287033b7f552
3,627,366
def article(word, function=INDEFINITE, gender=MALE, role=SUBJECT): """ Returns the indefinite (ein) or definite (der/die/das/die) article for the given word. """ return function == DEFINITE \ and definite_article(word, gender, role) \ or indefinite_article(word, gender, role)
fe21fdc34253c1736bcc17dae25f14d502ce301e
3,627,367
import requests def get_workbooks(server, auth_token, user_id, site_id): """ Queries all existing workbooks on the current site. 'server' specified server address 'auth_token' authentication token that grants user access to API calls 'user_id' ID of user with access to...
4a91fe94e5f71e6599689e3430f75239e8efd4aa
3,627,368
def dirty_image_generate(dirty_image_uv, mask = None, baseline_threshold = 0, normalization = None, resize = None, width_smooth = None, degpix = None, not_real = False, image_filter_fn = 'filter_uv_uniform', pad_uv_image = None, filter = None, v...
679afb90fd45c8c30805ad84f0ea08103b18d398
3,627,369
from datetime import datetime from typing import MutableMapping from typing import Any def get_significant_states_with_session( hass: HomeAssistant, session: Session, start_time: datetime, end_time: datetime | None = None, entity_ids: list[str] | None = None, filters: Filters | None = None, ...
2e2767d07e3b9a2bfa75acb4664a2a93c5d10472
3,627,370
def vc_to_oct(solution): """Convert a VertexCover solution into an OCT solution. This is done by undoing the graph doubling done to reduce OCT to VC. The certificate is recovered as the vertes whose counterparts are both in the VC certificate. Parameters ---------- solution : Solution ...
e08425dbc31f89dc4e0d79c257f83c884efb0714
3,627,371
def class_of ( object ): """ Returns a string containing the class name of an object with the correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image', 'a PlotValue'). """ if isinstance( object, py3compat.string_types ): return add_article( object ) return add_article( ob...
4cfad61c30afd3ab726f52bcf5906a59dd711866
3,627,372
import jinja2 import shutil import subprocess import sys import traceback import platform def _create_issue_body(command: str) -> str: """Generate a Github issue body based on given exception and command. Args: command: The command causing the exception to get thrown, e.g. 'django-cloud-d...
ad6fff41d8b7660e5d054a137956963b2407e198
3,627,373
def saturated_vapour_pressure_inst(t_air_i): """Like :func:`saturated_vapour_pressure` but as an instantaneous value Parameters ---------- t_air_i : float instantaneous air temperature :math:`T_{a,i}` [C] Returns ------- svp_i : float instantaneous saturated...
f5b45c6c354dfedf6e16d12bebd9b9f499e413ee
3,627,374
from typing import Tuple from typing import Optional from datetime import datetime def format_timestamp_range( timestamp_range: Tuple[int, int], timestamp_unit: Optional[str], timestamp_format: Optional[str] ) -> str: """ Format a time range with unit. :param timestamp_range: rang...
f0cf3cf0465ec8ebaafa73fd9a60e7b589df3c19
3,627,375
def make_eeg_average_ref_proj(info, activate=True, verbose=None): """Create an EEG average reference SSP projection vector Parameters ---------- info : dict Measurement info. activate : bool If True projections are activated. verbose : bool, str, int, or None If not None...
125a9320d1e018de2bc709f1e777cbb34cf8f127
3,627,376
def generate_degree2_invariants_from_different(coeffs1, coeffs2): """ Generate degree 2 invariants from density projection coefficients. Parameters ---------- coeffs1 : array[num_envs, num_species, nmax1, (lmax+1)**2] Density projection coefficients. This could include the spherical ...
abdfa4806d32f4c5b34e6c8cccbc841b9cadbe19
3,627,377
def ts_css(text): """applies nice css to the type string""" return '<span class="ts">%s</span>' % text
a505f4ffc8359bc886f0011295fb5309529be5bf
3,627,378
import typing def noop(val: typing.Any, *_args, **_kwargs) -> typing.Any: """A function does nothing. >>> noop(1) 1 """ return val
99841c0b291a654d83741500e83441482f59d45a
3,627,379
def method_detect(method: str): """Detects which method to use and returns its object""" if method in POSTPROCESS_METHODS: if method == "rtb-bnb": return RemovingTooTransparentBordersHardAndBlurringHardBorders() elif method == "rtb-bnb2": return RemovingTooTransparentBord...
4d3a065b25ac25a15e24681a723b5aa9e2354bc9
3,627,380
def normalized_difference(): """ Returns class instance of `NormalizedDifference`. For more details, please have a look at the implementations inside `NormalizedDifference`. Returns ------- NormalizedDifference : Class instance implementing all 'normalized_difference' processes. ""...
e3325e48c1ea7d8b775d7d9613425c445cad4f57
3,627,381
def detect_event_no_plot(VLMuscle, VRMuscle, Time, Threshold): """ This function calculates the start, end and duration of swimming episode, as defined by a threshold. Does not plot the result :param VLMuscle: list or 1-D numpy array :param VRMuscle: list or 1-D numpy array :param Time: list or...
3a7eae3a3b7b8e16e6c4365f7390227084676dc9
3,627,382
import torch def build_dgl_graph_v15(nodes, edges, sent_nodes): """ Build DGL homogeneous graph based on New Graph structure. 1112: checked graph through visualisation 1116: qo_node feature: [-10, opt id] 1201: hotpotQA, store node separately and combine """ # split entity nodes and q_opt ...
6e8e5da0a3ff6d37006606a818a708998fa206e2
3,627,383
import os def get_large_rand_ary_tfrecord(n_samples=100000, n_features=2000, dtype=np.float32): """ Args: n_samples (int) n_features (int) Returns: str: tfrecord data folder for training str: tfrecord data path for prediction (finally generating embedding) dict: {} """ X = get_rand_ary(n_samples...
50cbb320b92ef32ef7869f8d10fe25286a06e5e3
3,627,384
def entropy_bubble(signal, delay=1, dimension=3, alpha=2, **kwargs): """**Bubble Entropy (BubblEn)** Introduced by Manis et al. (2017) with the goal of being independent of parameters such as *Tolerance* and *Dimension*. Bubble Entropy is based on :func:`permutation entropy <entropy_permutation>`, but ...
0574f271acc7922a85ef9f6d411386bd5e8d2ac4
3,627,385
from typing import ClassVar from typing import Sequence from typing import Optional def open_set(dataset_class: ClassVar, public_classes: Sequence[str], private_classes: Optional[Sequence[str]] = ()) -> ClassVar: """ Convert a dataset into its open-set version. In other words, those samples w...
6bb48c1f7b40ae88e30adeb9dbf5dff922ebe115
3,627,386
import string import random def generate_random_string(length, using_digits=False, using_ascii_letters=False, using_punctuation=False): """ Example: opting out for 50 symbol-long, [a-z][A-Z][0-9] string would yiel...
d1606c450911183bd72353f6e4793dbc8d997271
3,627,387
def get_blocking_times_of_all_states_using_direct_approach( lambda_1, mu, num_of_servers, threshold, system_capacity, buffer_capacity ): """Solve M*X = b using numpy.linalg.solve() where: M = The array containing the coefficients of all b(u,v) equations b = Vector of constants of equations ...
7fe8954e1f2f6e7cf3401557990d29e035292953
3,627,388
def create_read_only_text(title: str, example: str, value: str, layout: QLayout) -> QLineEdit: """ Creates and returns a read-only one-line text widget (QLineEdit) with the given title, example contents and value in the given layout. """ widget = create_text(title, example, value, layout) widget...
046ec074cc46ba3717f03be8febb7e0dd657c925
3,627,389
def find_lane_pixels_around_poly(binary_warped, left_fit, right_fit, margin = 100): """ Returns the pixel coordinates contained within a margin from left and right polynomial fits. Left and right fits shoud be from the previous frame. PARAMETER * margin: width around the polynomial fit """ #...
16e852fbf502424a44d80ff1c9177455a1a99151
3,627,390
def log_softmax_v2(logits, axis=None, name=None): """Computes log softmax activations. For each batch `i` and class `j` we have logsoftmax = logits - log(reduce_sum(exp(logits), axis)) Args: logits: A non-empty `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. axis...
549fb730f89790230b8422607dd39ba23471695c
3,627,391
def graphs_tuple_to_broadcasted_sharded_graphs_tuple( graphs_tuple: jraph.GraphsTuple, num_shards: int) -> ShardedEdgesGraphsTuple: """Converts a `GraphsTuple` to a `ShardedEdgesGraphsTuple` to use with `pmap`. For a given number of shards this will compute device-local edge and graph attributes, and add...
6ef661b440d5bc26b97ed352184b18496260c717
3,627,392
def apply_reflection(reflection_name, coordinate): """ Given a reflection type and a canonical coordinate, applies the reflection and describes a circuit which enacts the reflection + a global phase shift. """ reflection_scalars, reflection_phase_shift, source_reflection_gates = reflection_options[ ...
2ef16ecb01747d216717438413f30b7a2b4f9f22
3,627,393
import json def _get_vcpus_from_pricing_file(instance_type): """ Read pricing file and get number of vcpus for the given instance type. :param instance_type: the instance type to search for. :return: the number of vcpus or -1 if the instance type cannot be found """ with open(pricing_file) as...
43d83826ef9d59101ed6928567e921173e58cbda
3,627,394
def route_from_text(obj, route): """ Recursive function to look for the requested object :param obj: :param route: :return: """ _LOG.debug(f'Looking for {route} in {obj}') if len(route) > 1 and ':' in route[0]: _LOG.debug('Is a dictionary nested inside a list') res = [d f...
b502f3db20271879b6924e76131fc73090ecc460
3,627,395
def rot_mol(rot, struct, wrt="origin", degrees=True, seq="xyz"): """ Rotate molecule using rotation matrix. Arguments --------- rot: array Can be either a list of 3 euler angles in the given order or a 3,3 rotation matrix. wrt: str Rotation performed with respect...
19ae4c586a84f2130389456a527a960ae3a03afc
3,627,396
from typing import Dict import asyncio async def _send_multipart(data: Dict[str, str], boundary: str, headers: HeadersType, chunk_size: int = _CHUNK_SIZE) -> bytes: """Send multipart data by streaming.""" # TODO: precalculate body size and stream request, pr...
a6cc24034b5b684558770f40115c4efac07d8179
3,627,397
def fit_naive_bayes_model(matrix, labels): """Fit a naive bayes model. This function should fit a Naive Bayes model given a training matrix and labels. The function should return the state of that model. Feel free to use whatever datatype you wish for the state of the model. Args: matrix...
637a355434911b6cf25f12d704f6bc9680d5c548
3,627,398
from typing import Union from contextlib import suppress def get_checkBox_entry(checkBox: etree._Element) -> str: """Create text representation for a checkBox element. :param checkBox: a checkBox xml element :returns: 1. attempt to get ``checked.w:val`` and return "\u2610" or "\u2612" 2. ...
d71e7821ac5fb7bafe9d5db5b579def2fe369609
3,627,399