content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import pyarrow as pa def ST_IsValid(geos): """ Check if geometry is of valid geometry format. :type geos: Series(dtype: object) :param geos: Geometries in WKB form. :rtype: Series(dtype: bool) :return: True if geometry is valid. :example: >>> import pandas >>> import arctern...
466f29367dbdc7c09581f7bedda72fe729bdd73d
32,000
import copy import json import logging def import_email(assessment, campaign_number, template_smtp): """Import email from file.""" temp_template = Template(name=f"{assessment.id}-T{str(campaign_number)}") temp_smtp = copy.deepcopy(template_smtp) temp_smtp.name = f"{assessment.id}-SP-{campaign_number}"...
7359ff21d159b0f5d7fce90fe58ae17ef785e271
32,001
import time def get_framerate(has_already_started, start_time, frame_counter, frame_rate, frame_num=5, decimal_round_num=2): """ Returns current framerate of video based on time elapsed in frame_num frames. Works in...
61db421be9e8d5a0e810a79875eac2b776be99ca
32,002
def check_for_solve(grid): """ checks if grid is full / filled""" for x in range(9): for y in range(9): if grid[x][y] == 0: return False return True
5fc4a8e7a2efaa016065fc0736aa5bdb7d4c92f8
32,003
def Sn(i, length): """Convert an int to a binary string.""" s = '' while i != 0: digit = i & 0xff i >>= 8 s += chr(digit) if len(s) > length: raise Exception("Integer too big to fit") while len(s) < length: s += chr(0) return s
607c2b8e82379db091505d7422edc17ea121bc3f
32,004
import os def _get_config_file_schema(): """ Return the path to the parameters file json schema. """ module_file = _decode_filesystem_path(__file__) return os.path.join(os.path.dirname(module_file), "pystepsrc_schema.json")
7a67cf8c5496d21dcff1b9e40c054e5961adab7f
32,005
def parse_args(): """Parse command line arguments""" parser = ArgumentParser( description='Print contents of a parsed config file', formatter_class=ArgumentDefaultsHelpFormatter, ) parser.add_argument( 'pipeline', metavar='CONFIGFILE', nargs='?', default='settings...
67462f2078ede7dfb9d9e0956b32f1eb09b2a747
32,006
import copy def _normalize_annotation(annotation, tag_index): """ Normalize the annotation anchorStart and anchorEnd, in the sense that we start to count the position from the beginning of the sentence and not from the beginning of the disambiguated page. :param annotation: Annotation object :param tag_inde...
a7da5810711ada97a2ddcc308be244233fe813be
32,007
def read_lc(csvfile, comment='|'): """ Read a light curve csv file from gAperture. :param csvfile: The name of the csv file to read. :type csvfile: str :param comment: The character used to denote a comment row. :type comment: str :returns: pandas DataFrame -- The contents of the csv fi...
74e53cbfe902e9d23567569ec0f4c5ef5ef75baa
32,008
def check_cutoffs(cutoffs): """Validates the cutoff Parameters ---------- cutoffs : np.ndarray or pd.Index Returns ---------- cutoffs (Sorted array) Raises ---------- ValueError If cutoffs is not a instance of np.array or pd.Index If cutoffs array is empty. ...
db0a3a477b27883aa1d29486083cf3e6c993e021
32,009
def hook(images, augmenter, parents, default): """Determines which augmenters to apply to masks.""" return augmenter.__class__.__name__ in MASK_AUGMENTERS
0e1e6589bc37d90b0ac8249e11dee54140efd86a
32,010
def _get_videos(course, pagination_conf=None): """ Retrieves the list of videos from VAL corresponding to this course. """ videos, pagination_context = get_videos_for_course( str(course.id), VideoSortField.created, SortDirection.desc, pagination_conf ) videos = li...
21774a476424b8f68f67c368fb72343fb9cfd552
32,011
import torch def sample_stacking_program(num_primitives, device, address_suffix="", fixed_num_blocks=False): """Samples blocks to stack from a set [0, ..., num_primitives - 1] *without* replacement. The number of blocks is stochastic and can be < num_primitives. Args num_primitives (int) ...
f5927edc11b2e20fcfb4b19b6ecddd92ba911841
32,012
def get_mmr_address(rn, m0m1): """Return address of an memory-mapped register and its size in bits. """ mmr_map = { 0b00 : 0xf0400, 0b01 : 0xf0500, 0b10 : 0xf0600, 0b11 : 0xf0700 } address = mmr_map[m0m1] + (rn * 0x4) size = get_register_size_by_addres...
53b92051d7ac64f5e288a121dae7e764166c9d2e
32,013
import sys def with_translations(**columns): """Decorator that creates a translations table for the decorated model. Creates a table mapped to a ``ModelTranslations`` class (given a decorated model class ``Model``) containing the provided `**columns`, with references to the :class:`.Language` and the...
22928f878de1480bcd483b7313642969483c3dd8
32,014
def thread_map(func, data): """ http://code.activestate.com/recipes/577360-a-multithreaded-concurrent-version-of-map/ """ #todo: this is disabled return map(func, data) N = len(data) result = [None] * N # wrapper to dispose the result in the right slot def task_wrapper(i): result[i] = func(data[i]) threa...
eec6efd698a71c63b0c1a7c0c0c4df1f21e3b62f
32,015
import re def number_of_a_char(element: Element): """ get number of linked char, for example, result of `<a href="#">hello</a>world` = 5 :param element: :return: length """ if element is None: return 0 text = ''.join(element.xpath('.//a//text()')) text = re.sub(r'\s*', '', text...
9d1394552b740844aadacc3fe3b2f802b698c18a
32,016
def preprocessing_fn(batch): """ Standardize, then normalize sound clips """ processed_batch = [] for clip in batch: signal = clip.astype(np.float64) # Signal normalization signal = signal / np.max(np.abs(signal)) # get pseudorandom chunk of fixed length (from SincN...
25ce4a077027239126d02b62e93ca0a3bcb15b5e
32,017
def elast_quad9(coord, params): """ Quadrilateral element with 9 nodes for classic elasticity under plane-strain Parameters ---------- coord : coord Coordinates of the element. params : list List with material parameters in the following order: [Young modulus, Poisso...
c27bae77ca54a3a370ccdac5b5550f73cb121d9a
32,018
from typing import Union from pathlib import Path def peek(audio_file_path: Union[str, Path], output: str = "np"): """ Returns a tuple of audio data and its sampling rate The audio data can be a numpy array or list """ data, sr = sf.read(audio_file_path, dtype="float32") data = data.transpose(...
30b47c77ab92cf0a544d84605204261c899f9e9a
32,019
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
import os def intersect_by_tf(emotion_dict): """ Takes multiple emotion word lists and intersects them by their term frequency, leading to the emotional difference between sets of any size. Args: emotion_dict: dict of summed up emotional scores based on the tf scores of the underlying words ...
f46a02b736a76bd3adcc1efaf7638452241567ce
32,021
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
import random from sys import path def random_avg_subdir(myinput, dims = "", n = 20): """ Get the average of n faces chosen from different subdirectories of myinput. You can also pass a list of directories into myinput instead of a string representing the target directory """ results = [] if isinstan...
83313fb7d31b0d07600dfc1424a2f94a37eca29c
32,030
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 sys import exc_info def _triple(): """Return a (type, value, tb) triple.""" try: one() except IndexError: return exc_info() else: raise AssertionError('We should have had an IndexError.')
455826d91dfcb5e6f76b46e4f2631c03f4e55474
32,042
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
import os def sample_images2(imgs, model, path, idx=None,save=False): """Saves a generated sample from the test set""" true_map = Variable(imgs['B'].type(Tensor)) save_image(true_map, os.path.join(path, 'test_results/gt', str(idx)) +'.jpg', normalize=True) fake_B = model(Variable(imgs['A'].type(Tensor...
2d03f7756aeed6cb4bb7106c7393a42bf7dc2ee4
32,044
def grep_annotations_multiple_files(files_list, regex, base_path, grep_type): """ :todo Refactor and remove the ugly type option """ annotations_list = [] for f in files_list: annotations = [] if grep_type == "code": annotations = grep_code_annotations(f, regex, base_path...
434ed6f72026a62cd410d8b7d62b35a5e1fe5440
32,045
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
import os def naming_convention(file_dir, file_name): """Rename files with 8-character hash""" long_hash = sha1sum(os.path.join(file_dir, file_name)) file_prefix, file_sufix = file_name.split('.') new_name = '{file_prefix}-{short_hash}.{file_sufix}'.format( file_prefix=file_prefix, sho...
c150ce78ddfa6ac35e74421eb89979d3e069a585
32,052
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
import struct def get_short_chan_id(source: hex, dest: hex) -> bytes: """Return a short channel id (bytes) based on source and destination provided. """ channel = [ channel for channel in config.rpc.listchannels(source=source)["channels"] if channel["destination"] == dest ][0][...
11e3bccf4fb120b05c9da118f3e05dfc02394a9e
32,057
import logging import os def register_logging(app): """日志处理器""" class RequestFormatter(logging.Formatter): def format(self, record): record.url = request.url record.remote_addr = request.remote_addr return super(RequestFormatter, self).format(record) request_fo...
d657df03bffa1bcd3a0bcbee20389e654b9f863f
32,058
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
import hmac def proxy_signature_is_valid(request, secret): """ Return true if the calculated signature matches that present in the query string of the given request. """ # Allow skipping of validation with an explicit setting. # If setting not present, skip if in debug mode by default. skip_v...
4050c736188b53e274a16d26c4f45d8ac1983785
32,062
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