content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def flatten(obj: JSONObject) -> FlatJSON: """ Flattens a JSON object to a dict with a single level of mapping. Key become tuples that store the path from the top-level object down to the value. Object keys are stored as str, Array index as int Arguments: obj: json object to flatten Returns...
e71511826e4b74bc40bdec257ce761902ee91300
81,335
import random from datetime import datetime import uuid def get_product(): """ Returns a random product generator function based on shared/resources/schemas.yaml Usage: from fixtures import get_product product = get_product() """ PRODUCT_COLORS = [ "Red", "Blue", "Gree...
df608e8aa124792f8ed6baff92a04d01fa8aaa32
81,336
def b58encode(v): """ encode v, which is a string of bytes, to base58.""" long_value = 0 for c in v: long_value = long_value * 256 + c result = "" while long_value >= __b58base: div, mod = divmod(long_value, __b58base) result = __b58chars[mod] + result long_value = ...
d1643703e3bee0e9a1d83fe7d5a71eeaf1fecc06
81,338
def resize_smallest(frames: tf.Tensor, min_resize: int) -> tf.Tensor: """Resizes frames so that min(height, width) is equal to min_resize. This function will not do anything if the min(height, width) is already equal to min_resize. This allows to save compute time. Args: frames: A Tensor of dimension [tim...
8a064e78986bbb81f0107042063b8bbfe05ce438
81,339
def centerxywh_to_topleftxywh(boxes): """ args: boxes:list of center_x,center_y,width,height, return: boxes:list of x,y,x,y,cooresponding to top left and bottom right """ x_top_left = boxes[0] - boxes[2] / 2 y_top_left = boxes[1] - boxes[3] / 2 width = boxes[2] height = b...
d5ea2716e982369b0052df6ee9f757e13e32c779
81,341
def compute_posture(df_dict): """ Computes posture, or bounding volume, of the body on a per frame basis. Args: df_dict (dict): dict of data frames, indexed by body parts Returns: DataFrame: resulting data frame comprising frame-level bounding volume values """ list_X = [] list_Y =...
1fbcf3c00fcce4c51c566a11bb44aa8e92cad5ea
81,342
from typing import Optional def _old2new_label(old_label: str) -> Optional[str]: """ Converts old-style BigEearthNet label to the new labels. > Note: Some labels were removed! This function will return `None` if the label was removed and raise a `KeyError` if the input label is unknown. "...
a99d978ebebc0fa2fa093e1ee7d9adde106a284b
81,344
def parts(a, b): """https://stackoverflow.com/a/52698110""" q, r = divmod(a, b) return [q + 1] * r + [q] * (b - r)
f6bffd65b39b83532d7105966a503e7e8c96db55
81,345
def is_parameterized_generic(type_, raising=True): """ Returns whether ``type_`` is a generic type with some type arguments supplied, for example ``List[int]`` or ``List[T]`` (but not ``List``) - in other words, a :class:`types.GenericAlias`. If ``type_`` is not a type as defined by :func:`~int...
67edef470ac351038034626b9e27190d5bc340af
81,346
def sine_offset(tee, location, alpha): """Return sine of angle between position of sun at local time tee and when its depression is alpha at location, location. Out of range when it does not occur.""" phi = latitude(location) tee_prime = universal_from_local(tee, location) delta = declination(t...
682894b3b94ab5c300748dca84610934307e592f
81,347
def reverse_looping_deconvolution_data_reuse_patterns(upsampling_factor, height, in_channels, kernel_size, original_operator="D-SP", width:int = None): """ input: upsampling_factor:int - the upsampling factor height:int - the height of the input image width:int - the width of the input i...
ecba08ec1fa15002dbff849c520ae7be0a1d3c74
81,348
def murphy_skill(xmodel,xobs,xref=None,ignore_nan=True): """ Murphy Skill metric """ if ignore_nan: sel=np.isfinite(xmodel+xobs) else: sel=slice(None) m=xmodel[sel] o=xobs[sel] if xref is None: xref=o.mean() ms=1 - np.mean( (m-o)**2 )/np.mean( (xref-...
ff5b894a2513949db0490e20a263aac1499ad40a
81,349
def project_to_cameras(poses_set, cams, ncams=4): """ Project 3d poses using camera parameters Args poses_set: dictionary containing 3d poses cams: dictionary containing camera parameters ncams: number of cameras per subject Returns t2d: dictionary with 2d poses ...
3ee7eeb0ae3dca5ccbeb219de77cb1416d6cee6e
81,350
def exclude(items, excludes): """Exclude removes all items in a list that is in the excludes list (for dirs)""" for ex in excludes: items = [x for x in items if not ex in x] # return items return items
5a9de305dbfc804b06e6533dd20030b8cbca00f8
81,351
def get_pathway_kegg_url(specie_id): """Get patwhway URL for A SINGLE specie.""" return urljoin(KEGG_PATHWAYS_URL, get_pathways_kegg_id(specie_id))
8fb792d51917ba346f3599dada9df490cc527d16
81,352
import numpy def calculate_migration_time(vms, bandwidth): """Calculate the mean migration time from VM RAM usage data. :param vms: A map of VM UUIDs to the corresponding maximum RAM in MB. :param bandwidth: The network bandwidth in MB/s. :return: The mean VM migration time in seconds. """ re...
83881d08c457924a7770fb072d401578a53d04b4
81,354
import math def get_path(s1, s2): """ runs astar on the map""" def distance(n1, n2): """computes the distance between two stations""" latA, longA = n1.position latB, longB = n2.position # convert degres to radians!! latA, latB, longA, longB = map( lambda d:...
f712c7aff3e1da0bc58b687fb5ab97fcb2418233
81,355
def chord_symbol_root(figure): """Return the root pitch class of a chord. Args: figure: The chord symbol figure string for which the root is computed. Returns: The pitch class of the chord root, an integer between 0 and 11 inclusive. Raises: ChordSymbolError: If the given chord symbol cannot be i...
dd66b1ddfea6589d651bb209b3c8a3a126fabcb9
81,356
def flatten_entrypoints(ep): """Flatten nested entrypoints dicts. Entry points group names can include dots. But dots in TOML make nested dictionaries: [entrypoints.a.b] # {'entrypoints': {'a': {'b': {}}}} The proper way to avoid this is: [entrypoints."a.b"] # {'entrypoints': {'a.b': {}}...
2b8e600c1932f0b2f3a64e5d7cdccb841bc82030
81,357
def elslib_CylinderValue(*args): """ :param U: :type U: float :param V: :type V: float :param Pos: :type Pos: gp_Ax3 :param Radius: :type Radius: float :rtype: gp_Pnt """ return _ElSLib.elslib_CylinderValue(*args)
3ef438f3e8c3bc2ff1fddf29911d9994512d1053
81,358
def Get_random_valid_grid(size): """Returns a single valid raw grid out of 9! possible combiantions""" #getting size values and shuffling them values_to_set = [i for i in range(size)] shuffle(values_to_set) #assigning them to a size x size board on the main descending diagonal, by doing so, the init...
0ca8ffe41cada0b18cef4cf4367a9c3225c39d29
81,359
def enframe(data, window_size, hop_size): """Divide 1D data in frames""" if data.ndim != 1: raise TypeError('Input must be a 1-dimensional array.') n_frames = 1 + (len(data) - window_size) // hop_size framed = np.empty((n_frames, window_size)) for i in range(n_frames): framed[i] = da...
ba8729c76641495f1900a3d9bcd46c37f8f2d2ad
81,360
import decimal def get_decimal_count(value, is_drop_trailing_zeros=True) -> int: """Return decimal count. https://stackoverflow.com/a/6190291/2402577 See https://stackoverflow.com/a/11227878/2402577 for drop the trailing zeros from decimal. """ value = str(value) if is_drop_trailing_zero...
ac0272c74eb5ed14694af7c13fcfb287d1eeea4c
81,361
def valid_timezone(x: str) -> bool: """ Retrun ``True`` if ``x`` is a valid human-readable timezone string, e.g. 'Africa/Abidjan'; otherwise return ``False``. """ return x in TIMEZONES
e9d88334130e7b9f7513f1e5d0813573f2c3357d
81,362
from turbinia.client import TASK_MAP import copy def validate_recipe(recipe_dict): """Validate the 'recipe' dict supplied by the request recipe. Args: recipe_dict(dict): Turbinia recipe in need of validation submitted along with the evidence. Returns: Tuple( bool: Whether the recipe has a va...
e504d7cec9e133b856057e4c73e38adde476d4bf
81,363
def hello_world(): """Main landing page""" return render_template('index.html')
8c9cdb3d6d1b4fd55985b604bf1fa4ca297da1fc
81,364
def plot_verified_region_control_set_point(verification_model, control_set_point, power_reference_points): """ Plot for a given control set point and (multiple) power reference points. :param verification_model: The verification model :param control_set_point: A fixed control set point :param power_...
1d3e7863aae8b87c05eb8a6c49b076a893e2babc
81,365
import ctypes def encrypt(cert_or_certlist, msg, algo=szOID_NIST_AES256_CBC, initvector=geninitvector): """Encrypt ``msg`` one or many :class:`Certificate` using ``algo`` with the initial vector ``initvector``. If ``geninitvector`` is left as it is, it will generate a random one. Algorithms...
2430a0991155f2652dae028f5c032e3224a3d569
81,367
import torch import math def get_log_p_and_kl_(generative_model, inference_network, obs, obs_id, num_particles): """Compute log weight and log prob of inference network. Args: generative_model: models.GenerativeModel object inference_network: models.InferenceNetwork object obs: tensor...
18c076cb06b9490b2b5c8674727efa6c37c1446c
81,368
def _GenerateEstimatorConstructor(estimator_class_name, variable_types, variable_names, extension_class_name): """ Generates the consructor for the estimator class. """ code = ["\n\npublic {0}(IHostEnvironment env".format(estimator_class_name)] # Generate the Constructor parameters for variable_...
19366e1e25befa2e0723604d31f0f59b602b9b51
81,369
def getExt(fileName, allowedExts=None): """Returns the extension from the given file name. If ``allowedExts`` is ``None``, this function is equivalent to using:: os.path.splitext(fileName)[1] If ``allowedExts`` is provided, but the file does not end with an allowed extension, a :exc:`Path...
5385ce1fb6376acfeef6b08f9682948080ffdee2
81,370
import json from typing import cast from typing import Type def dump(obj, fp, *, indent=None, sort_keys=False, core: "Core" = None, **kw): """ Dumps an object into a Writer with support for HomeControl's data types """ return json.dump( obj, fp, cls=cast(Type[JSONEncoder], partial(JSONEncoder,...
cb7162b9b58c99d11d3beec4bb3a8554d8f9a8c7
81,371
def mXZpm_HB(mu,P,mXZj,mXZtot,eps_s): """ Calculates the upper and lower bounds on the number of errors in the sifted X or Z basis, for each pulse intensity, using the Hoeffding bound. Defined after Eq. (4) in [1]. mXplus[j] and mXmin[j], or mZplus[j] and mZmin[j]; j = {1:3} Parameters ...
8f9cbeb4642bfc5efcf6e27a55244aefb2bb7b2b
81,372
from typing import Any def is_born_in(Subject, Object): """ Ex: Xu is born in 1902 or 1903 in a family of farmers in Hubei (China RRB) """ anything = Star(Any()) return Subject + Token("is born in") + Object + anything
0d38a92ba7c47ece4b46aff9f61f212d1a5a04e5
81,373
def get_project_single_branch_links(request, project_id, branch_id): """ Display single branch links """ if request.method != 'GET': return res.get_template_data(request, 'presenter/not_found.html', {}) project_entry = GitProjectEntry.objects.filter(id=project_id).first() if project_entry is No...
81f5984f7d0b9e9c24e63434680838bddb00209a
81,375
def cpi(token="", version="stable", filter="", format="json", **timeseries_kwargs): """Economic data https://iexcloud.io/docs/api/#economic-data Args: token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-results fo...
9eac6e15daaf99393817ee1a25e805d3f39ffadf
81,376
def make_universal_sf(config): """Generate a symmetry function applied to all elements.""" kind, inner = parse_config(config) if kind == "rad": return _make_universal_rad(**inner) if kind == "ang": return _make_universal_ang(**inner) else: raise ValueError( f"...
3603bed8cfd8db35c40f0d25aa2be585dfeec5c2
81,378
def format_bootstrap_metrics_to_dataframe( metrics: dict, decimals: int, ) -> pd.DataFrame: """ Format a dictionary of metrics into a dataframe for easier logging and printing. """ # Convert dictionary to dataframe df = pd.DataFrame(metrics).transpose() # Reorder columns and round colum...
452c5ba883d2d31bac56e89779fcbafec59d39fb
81,379
def get_classification(random_state = 42): """ Creates a classification dataset. Wrapper for sklearn's make_classification. :param random_state: Specifies a random seed :return: A tuple of X,y values. """ X, y = sklearn.datasets.make_classification( n_samples = 1000, n_class...
043b19ed3adf48bc2c8be86d7d1e8632a723e6c3
81,380
from typing import Optional async def get_asset_digest(genome: str = g, asset: str = a, tag: Optional[str] = tq): """ Returns the asset digest. Requires genome name asset name and tag name as an input. """ tag = tag or DEFAULT_TAG try: return Response( content=rgc[CFG_GENOMES_K...
7ef505fa39d6f50c53662e825295276ef9bdc15c
81,381
import nlopt def acq_max_with_tracing(ac,gp,bounds): """ A function to find the maximum of the acquisition function using the 'DIRECT' library. Input Parameters ---------- ac: The acquisition function object that return its point-wise value. gp: A gaussian process fitted to the relevant d...
b4ba813f0199e7e43ad7e35a261d04e2870ee5f7
81,382
def delete_cert(account_number, cert): """ Delete a certificate from AWS :param account_number: :param cert: :return: """ return assume_service(account_number, 'iam').delete_server_cert(cert.name)
a776f34445c61426af8ee982785fdd6a126cdb6c
81,383
import math def calculations_6(q_coppelia): """! Builds the 6 dof Jacobian by computing the transformation matrices, extracting the geometric vectors from the results and finally building the matrix. @param q_coppelia: vector of the joint positions @return Js: Jacobian matrix """ p = np.p...
637feab7c015d14585a41428076f2929a9786f6c
81,384
def predict_sequence_class(sequence, vectorizer_model, classifier_model, class_labels): """ inputs: DNA sequence, model and class labels (dictionary) Function takes in a DNA sequence returns its class amongst: [G protein coupled receptors', Tyrosine kinase', 'Tyrosine phosphatase', 'Synthetase', 'Syntha...
7760662355f7039a075b190256e0b11e364959ea
81,386
from functools import reduce def replace(names_to_check, non_valid=None, rmap=None): """ Removes characters defined in non_valid from strings defined in names_to_check Does not mutate strings in names_to_check, but returns new strings with invalid characters replaced by a single space :param nam...
67702fd88e0085d886d680eebe320549b031a6de
81,387
def get_bmi_category_df(): """ Get the dataframe for the bmi category :return: data and schema for the data frame """ data = [("Male", 171, 76, 1.71, 25.99, "Overweight", "Enhanced risk"), ("Female", 151, 96, 1.51, 42.1, "Very severely obese", "Very high risk")] schema = StructType([...
9f031724797f3308df891fec8dfdf351957f7b21
81,388
def sense_predictor(word_rnn_outputs, tag_feats, target_senses, num_senses, words_count, predict_sense, sense_smoothing): """Network for predicting sense separately""" if predict_sense: sense_features = word_rnn_outputs sense_features = tf.concat([sense_features, tag_feats], ...
e0962a5dda4ca81b49897868c76625682eebf4c3
81,389
def showscal(data, property="ke", **kwargs): """ showf(data, var, units) Arguments: data : xarray.DataSet that contains dimensions of t,x,y and a variable w (scalar) """ data.piv.vec2scal(property=property) fig, ax = contour_plot(data, **kwargs) return fig, ax
435f434a22ce6da1cf48157d812799279823f8c5
81,390
import requests def download_torrent_file(torrent_file_url): """ Функция скачает по ссылке торрент файл и вернет его название. Если не получится, вернет None """ user_agent = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' rs = requests.get(torrent_file_url, heade...
41f7ef4a03266b16a7a1d8e1add4b13ecc2e0ea6
81,391
def run(*datasources, **options): """Executes given Robot data sources with given options. Data sources are paths to files and directories, similarly as when running pybot/jybot from command line. Options are given as keywords arguments and their names are same as long command line options without hyph...
755b7b35ffb13df1f2dc6badfbbaf354aa4dc985
81,392
def get_new_session(): """ 获取新Session """ session = session_factory() return session
7e04843aefa1b250d0808a700ed3c3addc6feb70
81,393
def get_download_mode(): """Return the mode used to download references and mappings, either normal "http" file transfer or json "rpc" based. In theory HTTP optimizes better with direct support for static files from Apache, but RPC is more flexible and works through firewalls. The key distinction...
19a76bae07679bd6272b2b70ed11fdc99c3a4a61
81,394
import numpy def complex_to_int(data): """ This converts from complex64 or 128 data to int16 data. Parameters ---------- data : numpy.ndarray Returns ------- numpy.ndarray """ new_shape = _validate_input(data) if data.dtype.name == 'complex128': view_dtype = num...
3e068373fa31d6a636de3b1b1fc71928c20b2788
81,395
def _binary_method(op): """Implement a forward binary method with a noperator, e.g., __add__.""" def func(self, other): self, other = coerce([self, other]) if isinstance(other, Image): return Image( op(self._value, other._value), copy=False ).merge_proper...
19cb264d4897277537650e4c829bcdeb3775bead
81,396
def point_copy(p): """Utility function to coerce a list or tuple into Point3 format""" return Point3(p[0], p[1], p[2])
11d05c444e3ec856f163eb2f568c9bfe0debf65d
81,397
def get_new_lp_file(test_nr): """ Get name of new LP file """ return "test/{0}-new.lp".format(test_nr)
f7527a053a640d080f3aecd9db24623d5563b250
81,400
def readQueue(): """ Description: Reads SQS Queue for processing Links: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html#SQS.Client.receive_message Expects: Nothing Returns: message array, each in JSON """ sqs = boto3.client('sqs',region_n...
6221e08b9b2d7339f2c6579ce73f80775badea0e
81,402
def comments_listing(request,option=None): """ Generate Comment Listing template. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param option: Whether or not we should generate a CSV (yes if option is "csv") :type option: str :returns: :cla...
b45a494a0bfd02562ae52e3e5aaa49931c8961b2
81,403
def get_auth_instance(credentials, auth_type): """ Returns an *Auth instance suitable for the requests package """ model = AUTH_TYPE_MAP[auth_type] if model is None: return None username = credentials.username if auth_type == NTLM and credentials.type == credentials.EMAIL: us...
52ed597ee191781fe996e44db67529e5fd272141
81,404
def transmit(message: str) -> str: """ Convert a message to a NATO code word transmission. """ result = [] for char in ALPHANUM_RE.findall(message.upper()): result.append(ALPHANUM_TO_NATO[char]) return " ".join(result)
d67d27ff400b131a62d405ba0391461b8b7ad31c
81,405
import PIL def pilshow_imageobject_vscode(image_object: PIL.Image.Image): """When used with a VS Code "Interactive Window", displays the referenced image object. Args: image_object (PIL.Image.Image): Reference an existing Image object """ # if isinstance(image_object, PIL.Image.Image): ...
7556e791e5cdc5a0a8a10701a3ddac0e5c37b46f
81,406
def calculate_bmu_indexes(): """Create a tensorflow graph for calculating the best matched indexes in a SOM.""" mapdata = tf.placeholder(tf.float32, shape=(None, None), name="som") fcsdata = tf.placeholder(tf.float32, shape=(None, None), name="fcs") squared_diffs = tf.pow(tf.subtract( tf.expand_...
b028351b20d8bcfd18d1f29aafece07a140488d9
81,407
def tokenize(tokenizer, data, max_length = 128): """ Iterate over the data and tokenize it. Sequences longer than max_length are trimmed. :param tokenizer: tokenizer to use for tokenization :param data: list of sentences :return: a list of the entire tokenized data """ tokenized_data = [] ...
30b3786c1299bc42cd2698eae83ce1c6bdc3cfbe
81,408
import torch def empty_like(input_, dtype): """Wrapper of `torch.empty_like`. Parameters ---------- input_ : DTensor Input dense tensor. dtype : data-type Data type of output. """ return torch.empty_like(input_._data, dtype=dtype)
6f2a8b5392cb854fd7bb782fe8de0766653bb3b5
81,409
def remove_host(host, service_instance): """ Removes host from vCenter instance. Returns connection state of host host Name of ESXi instance in vCenter. service_instance The Service Instance Object from which to obtain host. """ host_ref = utils_common.get_mor_by_property(...
fc00ce2806c575c60745ee5d1335b3489a51e1d9
81,411
def unbind_slot_luks1(module, device, slot): """Unbind slot in a LUKS1 device. This involves removing both the clevis metadata in LUKSMeta as well as its associated keyslot. Return <result> <error>""" _unused, err = get_jwe_luks1(module, device, slot) if err: errmsg = "{0}:{1} is not bound t...
14db4d116a3ae121f047cbe5f2710d7a99a574fe
81,412
def detect_peaks_1d(timeseries, delta_peak, threshold, peak_width=5): """ detect_peaks_1d Starting from the largest burst event in the time series at hand, we identify a set of disjunct sub records, placed symmetrically around the peak of burst events which exceed a given amplitude threshold until ...
7d30d9ed9d9c68c36d843939c18110ebe0162ef0
81,413
def __calculate_always_decrease_rw_values( table_name, gsi_name, read_units, provisioned_reads, write_units, provisioned_writes): """ Calculate values for always-decrease-rw-together This will only return reads and writes decreases if both reads and writes are lower than the current provisi...
c25985b74e91794151b2c193f2b9cceae911d805
81,415
def _compute_residuals(X, column_index, alpha, gram, max_iter=5000, tol=1e-3, method='lasso'): """Compute the residuals of the regression of a given column of the design matrix against the other columns""" n_samples, n_features = X.shape i = column_index X_new = np.delete(X,...
5bb915536fa54d6a3861f6b0d3572f6674dbe2d9
81,416
def load_imagenet_targets() -> np.ndarray: """ Returns the ground-truth labels of the ImageNet valdation set. """ _check_imagenet_folder() return tv_datasets.ImageFolder(root=ImageNetValidationData).targets
75962488b547c0a0788ebd9dc3158340447c47c8
81,417
def create_dataset(number_of_input): """Create new dataset :rtype: str """ dataset = models.Dataset(number_of_input=number_of_input) dataset.save() return str(dataset)
666e75c723a7033bb3978ba07c118e8430aa7522
81,419
import logging def find_log_path(lg): """ Find the file paths of the FileHandlers. """ out = [] for h in lg.handlers: if isinstance(h, logging.FileHandler): out.append(h.baseFilename) return out
efab0cb7eafd0491e1365224dc83f816c7bb1b51
81,420
def apply_packaged_translation(pkg, input_text, translator, num_hypotheses=4): """Applies the translation in pkg to translate input_text. Args: pkg (Package): The package that provides the translation. input_text (str): The text to be translated. translator (ctranslate2.Translator): The...
e476e20a73348959e22466f94cf4033782cc791e
81,421
def _shuffling_queue(shuffling_queue_capacity, min_after_dequeue, dtypes, fields_as_list): """Creates a shuffling queue with enqueue/dequeue pair. Always a single writing thread.""" # Named tuples loose the 'named' part when going via queue shuffling_queue = tf.RandomShuffleQueue(shuffling_queue_capacity, min_af...
37c832eb72dfbf8365963abacd125394f4e7612b
81,422
from datetime import datetime def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime): serial = obj.isoformat() return serial raise TypeError ("Type not serializable")
287b7e3396bba08f001ee658e1d3adf0b4b4b12a
81,424
import requests def send_proms_pingback(pingback_target_uri, payload, mimetype='text/turtle'): """ Generates and posts a PROMS pingback message :param pingback_target_uri: a URI, to where the pingback is sent :param payload: an RDF file, in one of the allowed formats and conformant with the PROMS pin...
09ecff1835352f08e7fc5f4bce545585798e688c
81,426
def sal_structure( prediction, observation, thr_factor=None, thr_quantile=None, tstorm_kwargs=None ): """ Compute the structure component for SAL based on :cite:`WPHF2008`. Parameters ---------- prediction: array-like Array of shape (m,n) with prediction data. NaNs are ignored. obse...
2b6ae019ca2aaab8ec0243f2fc5aa24f6f3c1e97
81,427
import re def expand_zoo_variables(custom_env, string_to_process): """ развернуть в строке переменные окружения zoo поискать в строке '%KEY%' если есть то заменить на соответсвующее значение из словаря и так для каждого ключа в словаре :param string_to_process: :return...
14064b112f3c46f4c22f3959aeff5cd6d02e3634
81,428
async def async_unload_entry( hass: HomeAssistant, config_entry ): # pylint: disable=unused-argument """Handle integration unload""" for cancel_handle in hass.data[DOMAIN].get("cancel_handlers", []): if cancel_handle: cancel_handle() if hass.services.has_service(DOMAIN, "report"): ...
b0e0cf7a907c6106ccd17ea8705afb07f59f4041
81,430
def repeated_KFold_cv(estimator,X,y,repeat,sample_weight=None,n_splits=5,pipeline_learner_step='auto',pred_int=0,random_state=None): """ Perform k-fold cross-validation with multiple random splits Args: estimator: sklearn estimator instance X: data matrix (nxm) y: response (n-vector) repeat: number of time...
7d5dcc2a86447ae9cf576b18ce034a600d220992
81,431
from datetime import datetime def status_summary(request): """Return number of recent errors as json.""" fmt = getparam(request, "fmt", "html", options=["html", "json"]) num_mins = getintparam(request, "window", 5, minimum=1, maximum=100, fmt=fmt) mins_ago = datetime.datetime.now() - datetime.timedel...
d6ba8d1cad37f6a4b0e40d593dbc682667d97f3c
81,432
import re def split_host_port(address, default_host=None, default_port=None): """Split address to host port The format of address like: host1, host1:8888, 1.1.1.1, 1.1.1.1:8888, :8888 >>> split_host_port('host1:8888') ('host1', '8888') >>> split_host_port('host1') ('host1', None) ...
dc75fa033d02664d47c1a62259a2e30c9a489a56
81,433
def keywords(text): """Get the top 10 keywords and their frequency scores ignores blacklisted words in stopwords, counts the number of occurrences of each word, and sorts them in reverse natural order (so descending) by number of occurrences. """ text = split_words(text) # of words before re...
66e2cfe4af9dea6440763602b81bfc6cfb3133b7
81,434
def extract_latregion_rectilinear(cube, lat_bounds): """Extract region of interest from a regular lat/lon grid. Returns subset of the original cube that contains only the latitude range of interest. """ southern_lat, northern_lat = lat_bounds lat_constraint = iris.Constraint(latitude=lambda cell...
a8195d1444ca6dbfb0a2a03e5b586176d790200f
81,436
from typing import Dict def get_detail_context(workflow: models.Workflow) -> Dict: """Create the context to render the details page. :param workflow: Workflow being manipulated :return: Dictionary to render the details page """ context = { 'workflow': workflow, 'table_info': None}...
e1e644c6a801d7e41d7657ddc09c8b412a3b6143
81,437
def transpose2(x, dim1, dim2): """Transpose two axes `dim1` and `dim2` of a tensor.""" perm = list(range(len(x.shape))) perm[dim1] = dim2 perm[dim2] = dim1 return tf.transpose(x, perm)
710d04740f07355603225cbcd0dce2b03f8d7f7e
81,438
def is_pmap(pmap): """Check this here so people don't mistake pmap and PMap. Parameters ---------- pmap : obj An object Returns ------- bool Returns True if it is a pyrsistent.pmap """ return isinstance(pmap, PMap)
f8a28218681b445b9f7534db29654d28fcd91e9f
81,439
import torch def estimate_grad_moments(xloader, network, criterion, steps=None): """Estimates mean/sd of gradients without any training steps inbetween - this gives the total_XXX kind of estimators which are only evaled once per epoch on the whole dataset""" with torch.set_grad_enabled(True): network.eval() ...
7bb57bd5db63270c162e6c3801bba39f2bfeba4b
81,440
def register( request ): """ Uses the user registration form to display form, create user account from valid data (on POST), or show errors if data is invalid. If the change is successful, user is logged in and redirected to their homepage. :param request: request object :return: HttpRes...
ec9bb390f407248414db35ae4a7c8055f1508401
81,441
import requests def public_ip(): """ Pytest fixture for current public IP-address. :return: Public IP-address. :rtype: str """ assert PROXY_HOST is not None r = requests.get(URL_HTTP) assert r.status_code == 200 return r.json()['origin']
a0614e4958356a1251432f201fc00e86d2e58dbd
81,443
import torch def patch_label_2d( model, img, pre_processing, output_processing, patch_size, stride, batch_size, device, num_classes, ): """Processes a whole section""" img = torch.squeeze(img) h, w = img.shape[-2], img.shape[-1] # height and width # Pad image with patch_size/2: ps = int(np.f...
c2eee8c2c9d63b26cf3e544dfe19e90e081ec4d0
81,446
def to_2d(arg, raw=False, expand_axis=1): """Reshape argument to two dimensions. If `raw` is `True`, returns NumPy array. If 1-dim, will expand along axis 1 (i.e., Series to DataFrame with one column).""" if raw or not checks.is_array(arg): arg = np.asarray(arg) if arg.ndim == 2: r...
bdff16165384395b2cae0b244f86d8ed4c6e3efb
81,447
import random def generate_fake_ohlc_data(data_df): """ Generates fake ohlc data for each row of twitter sentiment dataframe. Used for testing without creating database or making api calls to finnhub. Args: data_df: Dataframe containing time and twitter sentiment socres for each currency ...
5b6608765a7a8300a17c9cda3a4dab3a2c18327b
81,448
def index(request): """View function for Home page site""" # Generate counts of some of the main objects num_bloggers = BlogAuthor.objects.count() num_blogs = Blog.objects.count() num_comments = Comment.objects.count() context = { 'num_bloggers': num_bloggers, 'num_blogs': num_bl...
2918cd4d2f4793beaddb88713d24e18346cec797
81,449
def handle_accept(current_request=None): """处理C端 accept""" url_prefix = "http://" + current_request.host c_path = current_request.path #类似 /v1/h5/house/info url_suffix = c_path.replace(url_prefix, "") a = my_config.getAccept(url_suffix) logger.info("Accept is %s", a) return a
d5469dec08602610f3922fa9acb09e78e1c2989d
81,450
def simple_doctor_alarm_generators(update_vals=None): """A function for returning Doctor alarm event generators. Returns generators for a given number of Doctor alarms. :param update_vals: preset values for ALL update events :return: generators for alarms as specified """ return _simple_alarm_...
236d01f23ed3c3095488d2de6343285f0e8ae301
81,451
def open_acqusition(c3d_file): """ Opens a c3d file with BTK """ reader = btk.btkAcquisitionFileReader() reader.SetFilename(c3d_file) reader.Update() return reader.GetOutput()
c961b7581c7347ec537429c50277e99e3b5697df
81,452
def merge_wordpiece_tokens(paired_tokens): """ Combine tokens that have been broken up during the wordpiece tokenization process The weights of the merged token is the average of their wordpieces :param paired_tokens: A list of tuples with the form (wordpiece_token, attention_weight) :return: A list...
f33edbcb48e54277d7bc4132c0cfa67aa1170cf0
81,453
def home(): """List all available api routes.""" return ( f"Welcome to Honolulu, Hawaii's Climate Home Page:<br/>" f"Available Routes:<br/>" f"<br/>" f"List of Precipitation Data with Corresponding Dates:<br/>" f"/api/v1.0/precipitation<br/>" f"<br/>" f"Li...
08cb0c5ae57d3dd672459aef018c7de9d1cbab56
81,454
def index(): """ Redirect to the root of the swagger docs """ return redirect('/apidocs/')
480b106ab557c3957add6c10752ef41d0065a3cc
81,455