content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import click def parse_rangelist(rli): """Parse a range list into a list of integers""" try: mylist = [] for nidrange in rli.split(","): startstr, sep, endstr = nidrange.partition("-") start = int(startstr, 0) if sep: end = int(endstr, 0) ...
321496a1170b81d02b8378d687d8ce6d6295bff6
32,020
def transcript_segments(location_descriptors, gene_descriptors): """Provide possible transcript_segment input.""" return [ { "transcript": "refseq:NM_152263.3", "exon_start": 1, "exon_start_offset": -9, "exon_end": 8, "exon_end_offset": 7, ...
3ca9041ff278dcd19432b6d314b9c01de6be1983
32,022
def perform_data_filtering_q2(data): """ Takes the original DataFrame. Returns the altered DataFrame necessary for Q2. """ # redoing the dataframe columns based on different values df = data diseased = df['num'] != 0 df['num'] = np.where(diseased, 'diseased', 'healthy') males = df['s...
2c8943bda66722b70a5dd25cb5a7c7473e40e67c
32,023
def player_with_name_and_value(source): """ source: pn.widgets.DiscretePlayer() target: consists of source player's name, value and player itself With pn.widgets.DiscretePlayer, we don't get name and value updates in textual form. This method is useful in case we want name and continuous value ...
e7d415d798f9c6aefb203f861b08c9477dde32d7
32,024
def _cached_diff(expression, var): """ Derive expression with respect to a single variable. :param expression: an expression to derive :type expression: :class:`~sympy.Expr` :param var: a variable :type var: :class:`~sympy.Symbol` :return: the derived expression :type: :class:`~sympy.Ex...
4a4206d327bee6f0c8168893e2bffbeaa23b9c14
32,025
def _get_mult_op_ ( klass1 , klass2 ) : """Get the proper multiplication operator """ t = klass1 , klass2 ops = _mult_ops_.get( t , None ) if ops : return ops ## RETURN ## try to load the operators try : ops = Ostap.Math.MultiplyOp ( klass1 , klass2 ) ...
f7a000f697d4739894e1671e9cfeb23099e1ce4f
32,026
def datetime_into_columns(df, column, weekday = False, hour_minutes = False, from_type = 'object'): """ The function converts a column with a date from either int64 or object type into separate columns with day - month - year user can choose to add weekday - hour - minutes columns Keyword argument...
e6178b33f113ef1430d0d8df3fe9b6c53d200e1e
32,027
def cis_codif_h1_moms(probe, starttime, endtime, sensitivity='high', try_download=True): """ Load H+ moments from CIS instrument. See https://caa.estec.esa.int/documents/UG/CAA_EST_UG_CIS_v35.pdf for more information on the CIS data. Parameters ---------- probe : stri...
e8f014196c2a634d406aaeb86a3130e6db59049f
32,028
def readlines(file_path): """ Read lines from fname, if the fname is loaded get the buffer.""" buffer = getbuffer(file_path) if buffer and int(vim.eval('bufloaded(%d)' % buffer.number)): return buffer try: with open(file_path, 'r') as fo: # we are not decoding: since we hav...
a4f367a00f90095a17f9eaf29eb150e7a5176045
32,029
def convert_range_image_to_point_cloud( frame, range_images, camera_projections, range_image_top_pose, ri_indexes=(0, 1) ): """Convert range images to point cloud. modified from https://github.com/waymo-research/waymo-open-dataset/blob/master/waymo_open_dataset/utils/range_image_utils.py#L612 Args: ...
af6a6af4cfcde6f3b600ffe0add8a3a0b0870067
32,031
from typing import Dict from typing import Tuple def get_counts(circ: MyCircuit, n_shots: int, seed: int) -> Dict[Tuple[int, ...], int]: """Helper method for tests to summarise the shot table from the simulator :param circ: The circuit to simulate :type circ: MyCircuit :param n_shots: The number of s...
e681fdc02e4cf7a637eac6f1e2096d9276b39cc6
32,032
def length( inputs: tf.Tensor, axis: int = -1, keepdims: bool = False, epsilon: float = 1e-10, name: str = None ) -> tf.Tensor: """ Computes the vector length (2-norm) along specified ´axis´ of given Tensor ´inputs´. Optionally an epsilon can be added to the squared n...
a548110ec2d8e3512e73805aea690f22c7d50fe3
32,033
def class_label_matrix(labels, img_sizes, num_classes): """ Computes the class label matrix of the training data. """ # Class label matrix Y = list() # Modeling the object detection problem as a binary classification problem (none, detection) if num_classes == 2: print('Modeling as a bin...
47efe5f8f76cac58d3afeaddb04d766ebdebf377
32,034
def default_lambda_consumer(env_id): """Create a default lambda consumer for the snapshot restore test.""" return st.consumer.LambdaConsumer( metadata_provider=DictMetadataProvider( CONFIG_DICT["measurements"], SnapRestoreBaselinesProvider(env_id) ), func=consume_...
ec7ec2ae6df4aaa7caf034537a5259b897755700
32,035
def thresholdPolyData(poly, attr, threshold, mode): """ Get the polydata after thresholding based on the input attribute Args: poly: vtk PolyData to apply threshold atrr: attribute of the cell array threshold: (min, max) Returns: output: resulted vtk PolyData """ ...
e4717b971c238d9c3a63a902db7eb91e2c630340
32,036
def TCh_GetNum(*args): """ TCh_GetNum(char const & Ch) -> int Parameters: Ch: char const & """ return _snap.TCh_GetNum(*args)
6caf9bcf71868604a6aedeceaba299a36a6bc62a
32,037
def writeFGSSPostageStampRequestById(outfile, requestName, results, xsize, ysize, psRequestType = 'byid', optionMask = 2049, imageType = 'warp', psJobType = 'stamp', skycell = 'null', email = 'qub2@qub.ac.uk', camera = 'gpc1', coordMask = 2): """writeFGSSPostageStampRequestById. Args: outfile: requ...
636284d46cbaced8d0609afe988148cbc3111d32
32,038
def reduce_sequence(sequence, desired_length): """Reduces a sequence to the desired length by removing some of its elements uniformly.""" if len(sequence) < desired_length: raise RuntimeError('Cannot reduce sequence to longer length.') indexes = N.arange(desired_length) * len(sequence) / desired_len...
25f104abc666e26821436a42f5cb71b99b41a86c
32,039
def encode_label(text): """Encode text escapes for the static control and button labels The ampersand (&) needs to be encoded as && for wx.StaticText and wx.Button in order to keep it from signifying an accelerator. """ return text.replace("&", "&&")
b4402604f87f19dab9dbda4273798374ee1a38d8
32,040
def dash_table_from_data_frame(df: pd.DataFrame, *, id, **kwargs): """Returns a dash_table.DataTable that will render `df` in a simple HTML table.""" df_all_columns = df.reset_index() return dash_table.DataTable( id=id, columns=[{"name": i, "id": i} for i in df_all_columns.columns], ...
813bf054f33a4dc15dfcff300414f60fd9cf2973
32,041
from warnings import filterwarnings def calcRSI(df): """ Calculates RSI indicator Read about RSI: https://www.investopedia.com/terms/r/rsi.asp Args: df : pandas.DataFrame() dataframe of historical ticker data Returns: pandas.DataFrame() dataframe of calcula...
4c2c76159473bf8b23e24cb02af00841977c7cd3
32,043
def test_c_py_compose_transforms_module(): """ Test combining Python and C++ transforms """ ds.config.set_seed(0) def test_config(arr, input_columns, output_cols, op_list): data = ds.NumpySlicesDataset(arr, column_names=input_columns, shuffle=False) data = data.map(operations=op_lis...
e51191a48cc79bcac8cfe41508dd9e539da4645c
32,046
import struct def add_header(input_array, codec, length, param): """Add the header to the appropriate array. :param the encoded array to add the header to :param the codec being used :param the length of the decoded array :param the parameter to add to the header :return the prepended encoded ...
228db86bb6eb9e3c7cc59cc48b67e443d46cc36d
32,047
import torch def jaccard_loss(logits, true, eps=1e-7): """Computes the Jaccard loss, a.k.a the IoU loss. Note that PyTorch optimizers minimize a loss. In this case, we would like to maximize the jaccard loss so we return the negated jaccard loss. Args: true: a tensor of shape [B, H, W] or ...
10e113294f67cbe88b61e90af51c6c6659ead805
32,048
def _get_positional_body(*args, **kwargs): """Verify args and kwargs are valid, and then return the positional body, if users passed it in.""" if len(args) > 1: raise TypeError("There can only be one positional argument, which is the POST body of this request.") if "options" in kwargs: raise...
c777296ab9c0e95d0f4d7f88dfd4ae292bfc558f
32,049
def resize_image_with_padding(im, new_dims, interp_order=1): """ Resize an image array with interpolation. Parameters ---------- im : (H x W x K) ndarray new_dims : (height, width) tuple of new dimensions. interp_order : interpolation order, default is linear. Returns ------- i...
d39195cdd20db2a7cd6750c7a81b419a62f820f9
32,050
from typing import List from typing import Dict def _get_run_stats(calc_docs: List[Calculation]) -> Dict[str, RunStatistics]: """Get summary of runtime statistics for each calculation in this task.""" run_stats = {} total = dict( average_memory=0.0, max_memory=0.0, elapsed_time=0.0...
fb83c559ced3ca44eaee767d6dabf8c183779f7f
32,051
def mvn_log_pdf(x, mean, covariance): """ This function calculates the log-likelihood of x for a multivariate normal distribution parameterised by the provided mean and covariance. :param x: The location(s) to evaluate the log-likelihood. Must be [B x D], where B is the batch size and D is the dimen...
dc2b019ace6760a040d97045b50b552e937706fd
32,053
def question_input (user_decision=None): """Obtains input from user on whether they want to scan barcodes or not. Parameters ---------- user_decision: default is None, if passed in, will not ask user for input. string type. Returns ------- True if user input was 'yes' False is...
afb7f3d4eef0795ad8c4ff7878e1469e07ec1875
32,054
def depth(d): """Check dictionary depth""" if isinstance(d, dict): return 1 + (max(map(depth, d.values())) if d else 0) return 0
6fd72b255a5fba193612cfa249bf4d242b315be1
32,055
import logging def validate_analysis_possible(f): """ Decorator that validates that the amount of information is sufficient for attractor analysis. :param f: function :return: decorated function """ def f_decorated(*args, **kwargs): db_conn, *_ = args if db_conn.root.n_agg...
9de0cbf2e18e47d14912ae3ebdff526a73f2c25d
32,056
def get_rel(href, method, rule): """Returns the `rel` of an endpoint (see `Returns` below). If the rule is a common rule as specified in the utils.py file, then that rel is returned. If the current url is the same as the href for the current route, `self` is returned. Args: href (str)...
e1e5af2baabec766f07460275d7525569439b40c
32,059
def is_exist(self, connectivity): """Check the existence of a cell defined by a connectivity (vector of points indices). The order of points indices does not matter. Parameters ---------- self : CellMat an CellMat object connectivity : ndarray an array of node tags Returns ...
59f111040ba158fa03e82400c1d3cb9dc1444601
32,060
from typing import Optional from typing import cast def get_current_identity_arn(boto3_session: Optional[boto3.Session] = None) -> str: """Get current user/role ARN. Parameters ---------- boto3_session : boto3.Session(), optional Boto3 Session. The default boto3 session will be used if boto3_...
892ffdd35d8a31849f4a53b0048a5bf87be624ce
32,061
def remove_whitespace(sentences): """ Clear out spaces and newlines from the list of list of strings. Arguments: ---------- sentences : list<list<str>> Returns: -------- list<list<str>> : same strings as input, without spaces or newlines. """ return [[w....
ed50124aec20feba037ea775490ede14457d6943
32,063
def generate_jwt(payload, expiry, secret=None): """ 生成jwt :param payload: dict 载荷 :param expiry: datetime 有效期 :param secret: 密钥 :return: jwt """ _payload = {'exp': expiry} _payload.update(payload) if not secret: secret = current_app.config['JWT_SECRET'] token = jwt....
aa4727b7d26a7f00b015cbaed9a977c5865eedca
32,064
import json import secrets def authentication(uuid): """Allow a client to request/recieve an authentication key.""" if request.method == "POST": with peewee_db.atomic(): if RestClient.get_or_none(RestClient.uuid == uuid): return json.jsonify({"msg": "UUID already exits."}),...
ec984b03c17917b12eb7ed6034c28b40f42aac63
32,065
def one_sided_ema(xolds, yolds, low=None, high=None, n=512, decay_steps=1., low_counts_threshold=1e-8): """From openai.baselines.common.plot_util.py perform one-sided (causal) EMA (exponential moving average) smoothing and resampling to an even grid with n points. Does not do extrapol...
17f14cd7a775c347366f375dfecef6285dc55af7
32,066
def settings_value(setting_name): """Return value for a given setting variable. {% settings_value "LANGUAGE_CODE" %} """ return getattr(settings, setting_name, "")
aab0b2f16f0fa66a1c4066382b0b96c6c2a15215
32,067
def mongo_stat(server, args_array, **kwargs): """Method: mongo_stat Description: Function stub holder for mongo_perf.mongo_stat. Arguments: (input) server (input) args_array (input) **kwargs class_cfg """ status = True if server and args_array and kwar...
45ae8fd66a1d0cae976959644837fae585d68e65
32,068
import pickle def train_new_TFIDF(docs, save_as=None): """ Trains a new TFIDF model.\n If a user abstract is given, it is used for the training. Parameters ---------- docs : `[String]`. Documents to train on\n save_as : `String`. Name to save model as. Returns ------- `TfidfV...
be520b62fa6f718eeb185e59fed5fe3edf8d7ea7
32,069
import math def generate_sphere_points(n): """ Returns list of coordinates on a sphere using the Golden- Section Spiral algorithm. """ points = [] inc = math.pi * (3 - math.sqrt(5)) offset = 2 / float(n) for k in range(int(n)): y = k * offset - 1 + (offset / 2) r = math.sqrt(1 - y*y) phi =...
6349f001709c2d2958cc2bcdd9bfe9c70a79b8f9
32,070
def get_options(): """ Purpose: Parse CLI arguments for script Args: N/A Return: N/A """ parser = ArgumentParser(description="Produce to Kafka Topic") required = parser.add_argument_group("Required Arguments") optional = parser.add_argument_group("Optional Argume...
a6168fb549fff9b2634f4c55cc625b7e3e387fa7
32,071
def _estimate_log_gaussian_prob(X, means, precisions_chol, covariance_type): """Estimate the log Gaussian probability. Parameters ---------- X : array-like of shape (n_samples, n_features) means : array-like of shape (n_components, n_features) precisions_chol : array-like Cholesky decomp...
c8d50ca609dfd877463ae20c572ec1ab60960b21
32,072
def descendants(region_id, allowed_ids, rm: RegionMeta): """Get all filtered descendant IDs of a given region ID. A descendant is only accepted if it's in ``allowed_ids`` or is a leaf region. This is mimicking Dimitri's algorithm, I'm not sure about why this must be that way. """ all_desce...
b0d1a5b57c00335343e52fbfe6e73b47bbccda42
32,073
import json def search_classification(request): """ Filters the classification by name. """ filters = json.loads(request.GET.get('filters', {})) fields = filters.get('fields', []) page = int_arg(request.GET.get('page', 1)) classifications = Classification.objects.get_queryset() if 'n...
fd1b78a9169c3496ee0b5d286d03d81cf75473c9
32,074
import click def get_zone_id(ctx, param, zone_name): """Return the id for a zone by name.""" del ctx #unused del param #unused cf = CloudFlare.CloudFlare() zones = cf.zones.get(params={'name': zone_name}) if len(zones) != 1: raise click.ClickException('Invalid zone name: {}'.format(zon...
07ebf939fe08b9f146ddb871af97e59c88e9484d
32,075
from typing import List def solve(letters: List[str], dictionary: trie.Node) -> List[str]: """Finds all words that can be made using the given letters. """ center_letter = letters[0] words = set() queue = deque([letter for letter in letters]) while queue: candidate = queue.popleft() ...
8a1773c6c388b88cc4b208ca24d5c0b8249722d0
32,076
from datetime import datetime def datetime_from_milliseconds_since_epoch(ms_since_epoch: int, timezone: datetime.timezone = None) -> datetime.datetime: """Converts milliseconds since epoch to a datetime object. Arguments: ---------- ms_since_epoch {int} -- Number of milliseconds since epoch. ...
95528da79c78ca9956d656067b5be623058b12e6
32,077
def input_file(path): """ Read common text file as a stream of (k, v) pairs where k is line number and v is line text :param path: path to the file to read :return: lazy seq of pairs """ return zip(count(), __input_file(path))
d1699863f790181bdbd5ea1abc08446e32909ffc
32,078
def lik_constant(vec, rho, t, root=1, survival=1, p1=p1): """ Calculates the likelihood of a constant-rate birth-death process, conditioned on the waiting times of a phylogenetic tree and degree of incomplete sampling. Based off of the R function `TreePar::LikConstant` written by Tanja Stadler. T....
bfb74866eec3c6eedbd6536522403f08340d39d7
32,079
def window_bounds( window: Window, affine: Affine, offset: str = 'center' ) -> tuple[float, float, float, float]: """Create bounds coordinates from a rasterio window Parameters: window: Window affine: Affine offset: str Returns: coordinate bounds (w, s, e, n) ...
6d6dca039213b4f5ea85d9168172b5cb32ff1a1e
32,080
import copy def get_k8s_model(model_type, model_dict): """ Returns an instance of type specified model_type from an model instance or represantative dictionary. """ model_dict = copy.deepcopy(model_dict) if isinstance(model_dict, model_type): return model_dict elif isinstance(mode...
217c517b53acb596eec51773f856ceaf15a93597
32,081
def merge_specs(specs_): """Merge TensorSpecs. Args: specs_: List of TensorSpecs to be merged. Returns: a TensorSpec: a merged TensorSpec. """ shape = specs_[0].shape dtype = specs_[0].dtype name = specs_[0].name for spec in specs_[1:]: assert shape[1:] == spec.shape[1:], "incompatible shap...
fb0c895847c477cc90eb3b495505fe436667fe1e
32,082
def makeMapItem(pl_id): """ Recupere les items d'un player sur la map (stand ou pub). Utilise les fonctions makeMapItemStand et Pub. :param arg1: id du joueur :type arg1: int :return: collection des objets appartenant au joueur, avec leur position :rtype: Collection d'objets Json """ mapItem = [] mapItem.a...
5bb5745dc161d74b2bd832a213c55906bc5f358c
32,083
def get_test_result_records(page_number, per_page, filters): """Get page with applied filters for uploaded test records. :param page_number: The number of page. :param per_page: The number of results for one page. :param filters: (Dict) Filters that will be applied for records. """ return IMPL....
89fc8b6d441ec8830cdb16fccfa142eed39f6c6a
32,084
def new_graph(**kwargs) -> Plot: """[summary] :return: [description] :rtype: Plot """ return GraphPlot(kwargs)
0bdbe97f6d86ba7dcfe802b5d41cb2e61fbb0ea7
32,085
def _average_path_length(n_samples_leaf): """ Taken from sklearn implementation of isolation forest: https://github.com/scikit-learn/scikit-learn/blob/fd237278e/sklearn/ensemble/_iforest.py#L480 For each given number of samples in the array n_samples_leaf, this calculates average path length of unsuccee...
d6434c4ed437e0f8bff9e5d9f25bfdc84ce8f82d
32,086
import pkg_resources def get_pkg_license(pkgname): """ Given a package reference (as from requirements.txt), return license listed in package metadata. NOTE: This function does no error checking and is for demonstration purposes only. """ pkgs = pkg_resources.require(pkgname) pkg = pkg...
238f2b3d33de6bf8ebfcca8f61609a58357e6da1
32,087
def parse(date): """ convert date from different input formats: Parameters ---------- date : STR FLOAT (unix timestamp) Python native datetime.date object pandas datetime object Returns ------- datetime.date """ out = False try...
e7de2f8198c177630dfd75980b25fe5e9a70e0a2
32,088
def check_table_exist(conn): """Check if a table exists. We do not use IF EXISTS in creating the table so as to we will not create hyper table twice when the table already exists. Args: conn (psycopg2.extensions.connection): The connection to PostgreSQL database. Returns: ...
0d9199464c0323f5258e4ca6638b5a5c6759b434
32,089
import traceback def get_err_str(exception, message, trace=True): """Return an error string containing a message and exception details. Args: exception (obj): the exception object caught. message (str): the base error message. trace (bool): whether the traceback is included (default=T...
0ede3de80fb1097b0537f90337cf11ffa1edecf7
32,090
def epoch_data(data, window_length = 2,overlap=0.5): """ Separates the data into equal sized windows Input: - data: data to seperate into windows - window_length: length of the window in seconds - overlap: overlap, float in [0,1), in percentage overlap of win...
ab15ea4927118ed36ccd9d161772de7457239374
32,091
def dailyUsagePer15minn(index_list, tank_data_list): """Process tank temperatures series to water usage series divided into 96 15 minutes intervals, where each interval has value in liters equal to used normalized hot water(37deg of c). :param index_list: list of indexes :param tank_data_list: list of ...
7699b4455376675312b2800896db4f75b37a1ada
32,092
def is_valid(number): """Check if the number provided is a valid CAS RN.""" try: return bool(validate(number)) except ValidationError: return False
7e05c8e05f779c6f06150d90ab34b18585dd4803
32,093
import torch def get_kernel(kernel_type, input_dim, on_gpu=True, **kwargs): """ Initializes one of the following gpytorch kernels: RBF, Matern Args: kernel_type (str): Kernel type ('RBF', Matern52', 'Spectral) input_dim (int): Number of input dimensions ...
f9660ba9ef16a816a2377ac90531e6d2705a0659
32,094
def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
685ff34e14c26fcc408e5d4f9219483118bfd3c0
32,095
def down_sample(source, freq_vocab, replacement='', threshold=1e-3, min_freq=0, seed=None, name=None): """Randomly down-sample high frequency tokens in `source` with `replacement` value. Args: source: string `Tensor` or `RaggedTensor` or `SparseTensor` of any shape, items to be sampled. freq_vo...
2209bcc48356f4d11c9151a80ab85069c8b6ad5b
32,096
import platform import pickle def load_pickle(f): """使用pickle加载文件""" version = platform.python_version_tuple() # 取python版本号 if version[0] == '2': return pickle.load(f) # pickle.load, 反序列化为python的数据类型 elif version[0] == '3': return pickle.load(f, encoding='latin1') raise ValueErro...
33db0ba6dbd8b1d2b3eba57e63d4069d91fbcb0b
32,097
def extract_hashtags(text_list): """Return a summary dictionary about hashtags in :attr:`text_list` Get a summary of the number of hashtags, their frequency, the top ones, and more. :param list text_list: A list of text strings. :returns summary: A dictionary with various stats about hashtags ...
688824fbef72c961b48a6bdb001983c25b1e0cee
32,098
def skipif_32bit(param): """ Skip parameters in a parametrize on 32bit systems. Specifically used here to skip leaf_size parameters related to GH 23440. """ marks = pytest.mark.skipif( compat.is_platform_32bit(), reason="GH 23440: int type mismatch on 32bit" ) return pytest.param(par...
575226d01867ae1f898fc821fe1d51de5eb630fb
32,099
from typing import Any def check_int(data: Any) -> int: """Check if data is `int` and return it.""" if not isinstance(data, int): raise TypeError(data) return data
814155f2407cd0e8b580372679f4cecfcc087d9e
32,100
def onehot_encoding(categories, max_categories): """Given a list of integer categories (out of a set of max_categories) return one-hot enocded values""" out_array = np.zeros((len(categories), max_categories)) for key, val in enumerate(categories): out_array[key, int(val)] = 1.0 return out_...
89203b285faed64b4519a2ad5234b77b4fa837aa
32,102
def canny(gl_image, low_threshold=50, high_threshold=150): """Applies the Canny transform""" return cv2.Canny(gl_image, low_threshold, high_threshold)
de2d7194e9df6ab4cc7cda25a0b5ccd37f81822b
32,103
def res_stage(block:nn.Module, ic:int, oc:int, num_layers:int, dflag:bool=True, btype:str='basic', fdown:bool=False): """ Arguments --------- block : nn.Module the block type to be stacked one upon another ic : int # of input channels oc : int # of output channels ...
6cd95ba6d923265093daca2bdf888bde248dfd12
32,104
def getFirstValid(opts, default): """Returns the first valid entry from `opts`, or `default` if none found. Valid is defined as ``if o`` returns true.""" for o in opts: if o: return o return default
799a6ea4a993f0a112fa38b882566d72a0d223e0
32,105
def grid_density_gaussian_filter(data, size, resolution=None, smoothing_window=None): """Smoothing grid values with a Gaussian filter. :param [(float, float, float)] data: list of 3-dimensional grid coordinates :param int size: grid size :param int resolution: desired grid resolution :param int smo...
d4c833aee72d28a760584cbd995595497d740531
32,108
def print_train_time(start, end, device=None): """Prints difference between start and end time. Args: start (float): Start time of computation (preferred in timeit format). end (float): End time of computation. device ([type], optional): Device that compute is running on. Defaults to N...
9935f2c12bac8e8beca38075dd6f80b7211318b7
32,110
def Moving_Average_ADX(data, period=14, smooth=14, limit=18): """ Moving Average ADX ADX Smoothing Trend Color Change on Moving Average and ADX Cross. Use on Hourly Charts - Green UpTrend - Red DownTrend - Black Choppy No Trend Source: https://www.tradingview.com/script/owwws7dM-Moving-Average-ADX/ ...
63595d9cc53999ae1e4b75c971b4388f092da649
32,112
def forbid_end(interval, function): """ Forbids an interval variable to end during specified regions. In the declaration of an interval variable it is only possible to specify a range of possible end times. This function allows the user to specify more precisely when the interval variable can end. In p...
fee64b27578f78632ed84d2575a7b2dfb6de39e2
32,113
import re def get_all_anime(total_pages: int) -> list: """ Get all the anime listed on all the pages of the website. :param total_pages: Total number of pages of HorribleSubs. :return: List containing the names of all the anime. """ titles = [] for page in range(1, total_pages + 1): ...
91160353c7b488f21fbc7ed0a50974193a4b45bf
32,114
def network_generator( rw: int, cl: int, b: float, xi: float, P: float, mu: float, bipartite: bool, ) -> ArrayLike: """ function to generate synthetic networks with nested, modular and in-block nested structures. Generates networks with a fixed block size and increasing number of...
f9c6d615b117a2aa7ee22b7615ddcdbcaf628a71
32,115
def convert_rgb_to_hex(rgb: tuple([int, int, int])) -> str: """Take an RGB value and convert it to hex code. Args: rgb: a color represented as rgb values. Returns: Hex code of color or None if the RGB code is invalid. """ # Validate user Input is not negative or greater than 255 ...
c20c6a96dbe577eff4421df28403a57e1f038e4e
32,116
def localVarName(value, position): """A name of a class.""" if not value[0].islower(): return Error('BadLocalVariableName', 'Local variable must start with a lower case letter', position, LINES) return None
d4f8838497109fcf41e9c904aaddc31edd69eadc
32,117
def nodeAndOutputFromScenegraphLocationString(string, dag): """ Returns a tuple containing the node defined in a location string and its corresponding Output. """ try: outputNodeUUID = uuidFromScenegraphLocationString(string) outputNode = dag.node(nUUID=outputNodeUUID) outputNodeOutputName = string.split(":...
d7fa1f03b3121f4dbcc9baac8c94bb5113fbc378
32,118
def rivers_with_station(stations): """Returns the names of rivers on which a station is situated""" return set(stations_by_river(stations).keys())
c2e78ff18c3fdc73f04e145beae77d914a0ee287
32,119
def check_string_is_nonempty(string, string_type='string'): """Ensures input is a string of non-zero length""" if string is None or \ (not isinstance(string, str)) or \ len(string) < 1: raise ValueError('name of the {} must not be empty!' ''.format(string_type))...
527e60b35f6a827ee9b1eae3c9a3f7abc596b7ff
32,120
def last_frame_with_txt(vid, txt, duration): """Take the last frame from vid, show it for duration with txt overlay.""" frame = list(vid.iter_frames())[-1] clip = ImageClip(frame, duration=duration) return CompositeVideoClip([ clip, TextClip(txt, font=MOVIEPY_FONT, color='black', bg_colo...
e7a62332cb4ae69addc12bc679eb30479432caf2
32,121
import torch def load_dataset(dataset_size=100, dataset_start=0, shuffle=True, sentence_level=False, n_authors=15, k=5, features=u""): """ Load dataset :return: """ # Load from directory if sentence_level: reutersc50_dataset = torchlanguage.datasets.ReutersC50SentenceDataset( ...
2ace76a461699e9f0bdf7ca838d414a3c618898a
32,122
def df_as_table(dataframe, size='50'): """ :param dataframe: pandas dataframe to be displayed as a HTML table :param size: string to set realtive table size in percent standard 50% :return: string containing a html table """ shape = dataframe.shape n_cols = shape[1] n_rows = shape[0] ...
3634a90b3e3d4ef5c8cc737e19a0540305528959
32,123
def ecdh(privkey, pubkey): """ Given a loaded private key and a loaded public key, perform an ECDH exchange :param privkey: :param pubkey: :return: """ return ecdsa.ecdh(privkey, pubkey)
650607024f3fcd10fd7649897461c69a3d80596b
32,124
def portfolio_margin_account(self, **kwargs): """Get Portfolio Margin Account Info (USER_DATA) GET /sapi/v1/portfolio/account https://binance-docs.github.io/apidocs/spot/en/#get-portfolio-margin-account-info-user_data Keyword Args: recvWindow (int, optional): The value cannot be greater than 60...
88a1087d44187ed130211ab7d42fdcbb54a038f3
32,126
from typing import Any from typing import Mapping def init_hyperparams(*, class_name: str, hyperparams, hyperparams_class) -> Any: """ Construct a hyperparams object from either a mapping or another hyperparams object. """ if isinstance(hyperparams_class, type) and is_dataclass(hyperparams_class): ...
2aa4ebc5ec9e6d4502f7873e6517dc5285f8604e
32,127
def _is_y(filename): """ Checks whether a file is a Nanometrics Y file or not. :type filename: str :param filename: Name of the Nanometrics Y file to be checked. :rtype: bool :return: ``True`` if a Nanometrics Y file. .. rubric:: Example >>> _is_y("/path/to/YAYT_BHZ_20021223.124800") ...
adbb75533934d5050658b8a5078e66438b3381df
32,129
def is_scheduler_filter_enabled(filter_name): """Check the list of enabled compute scheduler filters from config. """ filters = CONF.compute_feature_enabled.scheduler_available_filters if len(filters) == 0: return False if 'all' in filters: return True if filter_name in filters: ...
f40e99f49a49aa24e66de72bad82b87ccf6ae8a2
32,130
from m2py.numerical.roots import nraphson def juros_price(PV, PMT, n, PV0=0): """ Calcula taxa de juros de um parcelamento pela table price Usado comummente em cŕedito concedido ao consumidor :param PV: Valor a Vista / Valor Presente :param PV0: Entrada :param PMT: Valor da Parcela ...
d593f27616c7028b39e80dff47a446a40fe43338
32,131
import json import re def delexicalisation(out_src, out_trg, category, properties_objects): """ Perform delexicalisation. :param out_src: source string :param out_trg: target string :param category: DBPedia category :param properties_objects: dictionary mapping properties to objects :return: delexicalised stri...
55108ff40e8739571a99a3481221c82c0fcbf255
32,132
def create_attention_mask_from_input_mask_v1(from_tensor, to_mask): """Create 3D attention mask from a 2D tensor mask. Args: from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...]. to_mask: int32 Tensor of shape [batch_size, to_seq_length]. Returns: float Tensor o...
0f83dd4a2e5cf904f19f89ce5b42e562c4ba401e
32,133
import hashlib def md5(filename): """Hash function for files to be uploaded to Fl33t""" md5hash = hashlib.md5() with open(filename, "rb") as filehandle: for chunk in iter(lambda: filehandle.read(4096), b""): md5hash.update(chunk) return md5hash.hexdigest()
35068abafee2c5c4b1ac672f603b0e720a8c9a8c
32,134
from typing import Iterable from typing import Any from typing import Tuple def pairwise(iterable: Iterable[Any]) -> Iterable[Tuple[Any, Any]]: """ Divide the given iter into pairs and return as tuple pairs. s -> (s0,s1), (s1,s2), (s2, s3), ... """ a, b = tee(iterable) next(b, None) return zi...
c9867a51d238ee51a993465b1757b387d0c9be6a
32,135