content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def funex(c): """ Compile a function by 'exec' :param c: function to compile :type c: string :return: the function 'f' declared in the input string :rtype: function """ dc = {} exec(c, dc) return dc['f']
79fac0aad493d47fc9fecbf30bfe4bc09a2f9908
49,800
import threading import time def get_fingerprint_batch(input_list, default_port=443, delay_time=0.5, max_threads=100): """ This is a parallel version of the TLS fingerprint primitive. Params: input_list- the input is a list of host:ports. default_port- default port to ...
6276e23290b35762eeeddb98a6d60e97135d29c2
49,801
def even_fib(ceiling): """ Returns the sum of all even Fibonacci numbers not exceeding ceiling. """ total = 0 fg = Fibonacci() n = next(fg) while n <= ceiling: if n % 2 == 0: total += n n = next(fg) return total
ad9163d34bc57767336fef5171d26e2cd3339a08
49,802
import json def get_table_columns(etcd_client, db, tbl): """ Get primary key column for table db.tbl. :param etcd_client: Etcd client. :param db: database name. :param tbl: table name. :return: Primary key column. :rtype: ColumnSet :raise ProgrammingError: if table or database doesn't...
091fe315cc7ad83af93e710cdf18526640fd6ed2
49,803
def _flatten_multiplicand_list(kernels): """Flatten a list of kernels which may contain _ProductKernel instances. Args: kernels: Python list of `PositiveSemidefiniteKernel` instances Returns: Python list containing the elements of kernels, with any _ProductKernel instances replaced by their `kernels...
d5a2700795b634fb2861998bc842df653456258b
49,804
def parse_bool_token(token): """ Parses a string token to convert it to its equivalent boolean value ignoring the case of the string token or leaves the token intact if it cannot. :param token: String to convert to ``True`` or ``False``. :type token: ``str`` :return: ``T...
bd9de30ee85921ba72a46e83eb96a0af104f998d
49,805
from typing import Union import abc def dictionary_writable( model: Union[type, abc.Dictionary] ) -> abc.DictionaryHooks: """ Retrieve a metadata instance. If the instance currently inherits its metadata from a class or superclass, this function will copy that metadata and assign it directly to th...
e0f60c42ae8d9a2eabc3b2ec4fb24bef52fcf8b3
49,806
import torch def log_prb_1l_per_smpl(x, ls): """ x=log(P) is a list of log probability tensors, and it has shape (batch_size, number_of_classes + 1, other dimensions like time, ...) ls is a list of labels with the same length as x. Each sample has one label in range [0, number_of_classes) ...
ad71c0fca4dea7e830db343acba296123e8e277d
49,807
def func_PS_Level(HA_Open, HA_Close, PS_pct_level=[0.35, 0.5, 0.95, 0.97], combine=False): """ 0. This function is for calculating the HA bars' bar size level, or called Price Status(PS). 1. This function has 4 arguments and return 2 arrays as output. 2. Input arguments including: (1) HA_Open: D...
3a2f9a9d200e800b0e314df7f01e4a3affa155d7
49,808
def angle(x0, x1): """Compute the angle between two vectors x0, x1 using the dot product""" mx0 = np.dot(x0, x0) mx1 = np.dot(x1, x1) return np.arccos(np.dot(x0,x1)/np.sqrt(mx0*mx1))
18b43c43e41d3ffb27c985f7338ea635f4f80cd8
49,809
import jsonschema def ipam_release_pool(): """Deletes a new Neutron subnetpool from the given reuest. This function takes the following JSON data and delegates the subnetpool deletion to the Neutron client. :: { "PoolID": string } Then the following JSON response is returne...
54751c9f983e667a603879995057f30d4b810e6d
49,810
import scipy def grubbs(timeseries, end_timestamp, full_duration): """ A timeseries is anomalous if the Z score is greater than the Grubb's score. """ try: series = scipy.array([x[1] for x in timeseries]) stdDev = scipy.std(series) # Issue #27 - Handle z_score agent.py Runtim...
14d05c35e65880ff7bdee9afc571ba173a814741
49,811
def _spatial_proximity(data, group_pop_var, total_pop_var, alpha=0.6, beta=0.5): """Calculate Spatial Proximity index. Parameters ---------- data : a geopandas DataFrame with a geometry column. group_pop_var : string The name of variable in data that contains the popula...
ba365819e1eef61c1042587a0e9370989752354b
49,812
def video_content_to_dict(vid_info_list): """Convert YouTube metadata list to dictionary.""" video_dict = {} for video in vid_info_list: if not video: continue title = video["title"] video_dict[title] = {"id": video["id"], "duration": video["duration"]} return video_d...
e56b211e9879ce783a8b145f267778dcaa0550b9
49,813
import requests def getwcs(dataset, applyomega=True, service="https://hla.stsci.edu/cgi-bin/fitscut.cgi"): """Return dictionary with WCS information for an image. Parameters ---------- dataset : str dataset name applyomega : bool, optional Apply HSC correction? Default value = Tr...
43d22dba3e8d882961deff5856361900f9ec8e68
49,814
import six def get_redis_from_settings(settings): """Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_...
03c555612aa67be6c3197cfd4c51a7145184436e
49,815
import wget async def download(uri): """ Guarda en el disco duro un archivo indicado por una URI Parámetro: > uri (str, por ejemplo 'http://www.inspyration.org/logo.png') Retorno: > contenido de un archivo (bytes, archivo de texto o binario) """ content = wget(uri) if content is ...
a2668b3182267bf2264bac382013f7fd9c0d4294
49,816
def print_symbol_table_node_to_dot(node, cur_id): """ Print the node of a symbol table as html table :param node: symbol table :param cur_id: current node id :return: dot string """ dot = "\t{} [\n\t shape=plaintext \n \tlabel=< <table border=\'0\' cellborder=\'1\' cellspacing=\'0\'\n\t>".fo...
d4a1b2dcb8bbc971d8100e74f2c887ce452cd1b9
49,817
def create_getter(var_name): """ Given the string name of a variable, creates a getter function for that variable and returns it. Args: var_name the name of the variable for which a getter should be created. """ def getter(self): """ The getter function to be returned.""" return geta...
7091280d2a804d818247ffcfa9e55c0d98bfe761
49,818
def James_Stein_estimator(data, std_noise): """ See Large-scale inference: empirical Bayes methods for estimation, testing, and prediction (Efron, 2010, page 6) """ mean_data = np.mean(data) dev = sum((data - mean_data) ** 2) return mean_data + (1 - (len(data) - 3) * (std_noise ** 2) / dev) * (d...
69db35bbeb65047b4c301bce673d11f7ddf51759
49,819
def predict_by_moving_avg_growth(stock, s, **_): """Returns predicted value of a stock Predicts the next price of a stock by extrapolating the moving average and its growth. Parameters ---------- stock : :obj:`stock` Stock to be predicted. s : int Number of data points used to...
c8e02b9c55bd339ff6f1793b697ba46647331326
49,820
def debug(): """ Method to debug server. """ return {'message': 'pong'}, 200
8e5f277279ecd2ca83b8823df5e75fbdeb208c6a
49,821
from typing import Union import types def get_admin_log(peer: Union[int, str] = None) -> list: """ Get a list of logs from the admin-logs. This method gets 'Join' and 'Leave' events by default, but you can uncomment the commented items and add them to your result list. :param peer: Union: [id, usern...
704a277eb9e1fde3cd119d5e3b7f73ffcc4e578a
49,822
def from_networkx(G): """ Convert a NetworkX graph into a Zen graph object. In creating the object, the NetworkX node object and node/edge data will be copied over (a shallow copy). **Returns**: The return type depends on the input type. * :py:class:`zen.Graph` if the input graph was a :py:class:`network...
e320a20749be2b9b99d90a1f8164706073f0593b
49,823
def find_subpixel_peak_position(corr, subpixel_method='gaussian'): """ Find subpixel approximation of the correlation peak. This function returns a subpixels approximation of the correlation peak by using one of the several methods available. If requested, the function also returns the signal ...
b915e6a2e1c71aa36d8423bb31ce2b625878ae38
49,824
import os def bulk_video_converter( video_path_tuple: tuple, fps_multiplier: int, dest_path: str = None, tkinter_label_object: Label = None, tkinter_label_percent_object: Label = None, tkinter_progressbar_object: Progressbar = None, tkinter_root_tk_object: Tk = None, tkinter_convert_bu...
807201175088e23272fbe2cb7b8f15ac2e86b4a7
49,825
def _vec_to_triu(vec): """Take vec and forms strictly upper triangular matrix. Parameters ---------- vec : array_like, shape[..., n] Returns ------- tril : array_like, shape=[..., k, k] where k is (1 + sqrt(1 + 8 * n)) / 2 """ n = vec.shape[-1] triu_shape = vec.shape + ...
8c5af1ad5089614280c048a84c572c04a958369e
49,826
import zlib import base64 def _compress(s: bytes): """ Compresses bytes for the payload. """ co = zlib.compressobj(wbits=-zlib.MAX_WBITS) b = co.compress(s) + co.flush() return base64.b64encode(''.join(map(chr, b)).encode())
6c6f1b04670c55f0417991fd3f9ab19ad42fefec
49,827
def render_Board_members_list_overlay(self, h, comp, *args): """Overlay to list all members""" h << h.h2(_('All members')) with h.form: with h.div(class_="members"): h << [m.on_answer(self.handle_event, comp).render(h) for m in self.all_members] return h.root
b818413dd28bac3043e1b83b83b1d7abf07416f3
49,828
def _token_to_int(t, token_list, token_cache, size_limit=float('inf')): """Return the int which represents a token, with caching. Throws a ValueError if token t is not in the token_list. There MUST be a _UNK token at the beginning of your vocab, or this may not halt. """ if t not in token_cache: ...
d2a46135197c38ff6ab08336fba9a4970fe6952f
49,829
import argparse import configparser import logging import os def parse_and_run_command(): """ Examples: # python -m telemetry_peak_analyzer \ -b telemetry_peak_analyzer.backends.JsonBackend -n "~/data.*.json" \ -s 2020-07-01 -e 2021-08-01 -t 10 # python -m telemetry_pea...
8f358ac009d50963022cab6cbf860f11a243e6d2
49,830
def select_data(df, countries_list, regions_list, ages_list, genders_list): """Extracts from the dataset the data corresponding to many criterias. Parameters: ----------- df : Pandas DataFrame dataset countries_list : list of str countries to be selected regions_list : ...
de6e24966f3060728657a4cc6685c8203bfa85e7
49,831
def revescape(text): """Any text. Escapes all "special" characters, except @. Forward slashes are escaped twice to prevent web servers from prematurely unescaping them. For example, "@foo bar/baz" becomes "@foo%20bar%252Fbaz". """ return urlreq.quote(text, safe=b'/@').replace(b'/', b'%252F')
227f420bb6f6c625f5f3b9be2d8142240a2c726d
49,832
from typing import cast def intersect1d(pda1 : pdarray, pda2 : pdarray, assume_unique : bool=False) -> pdarray: """ Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ---------- pda1 : pda...
8062173a51ecbec1933787de94e451c9f668165f
49,833
import re import io def _remove_unicode_encoding(xml_file): """ attempts to remove the "encoding='unicode'" from an xml file as lxml does not support that on a windows node currently see issue #38100 (Search.adml) For some reason this file is encoded 'utf-16' """ with salt.utils.files.fo...
b40cf886dca7932ccfeb75738d4ced2db6909bea
49,834
def add_data_reference(enc_key, enc_data): """Add DataReference to ``enc_data`` in ReferenceList of ``enc_key``. ``enc_data`` should be an EncryptedData node; ``enc_key`` an EncryptedKey node. Add a wsu:Id attribute to the EncryptedData if it doesn't already have one, so the EncryptedKey's URI att...
7d3d9cfabe9a645782ec58224a7824f7ec159fa8
49,835
from typing import Sequence from typing import Any from typing import List from typing import Dict def _get_items_as_rows(items_to_add: Sequence[Any], batch_number: int, result: str, operation: str, timestamp: str) -> List[Dict[str, Any]]: """Adds Content API results to...
70bc2976b0c47f7a66dea472599ba54a60702268
49,836
import os def is_subdir(child, parent): """ Determine if "child" is a subdirectory of "parent". If child == parent, returns True. """ child_path = os.path.realpath(child) parent_path = os.path.realpath(parent) if len(child_path) < len(parent_path): return False for i in range(len(parent_path)):...
d9f7ba81fd4148b6945148bc447c0bc9693232f5
49,837
from ba import _error def get_available_purchase_count(tab: str = None) -> int: """(internal)""" try: if _ba.get_account_state() != 'signed_in': return 0 count = 0 our_tickets = _ba.get_account_ticket_count() store_data = get_store_layout() if tab is not Non...
1b0d6afc0b9ba6a5d7ace211082d63dccefe8cae
49,838
def textops_rawtexttolines(text, linedelimiter="\n"): """ <Purpose> Converts raw text (a string) into lines that can be processed by the functions in this module. <Arguments> text: The text to convert into lines (basically, a sequence of strings). linedelimiter (optional, defaults to...
e146180f3dc02a036e84cbb04b5a4fd90b85abe8
49,839
import re def get_display_name(skill_name: str): """Splits camelcase and removes leading/trailing "skill".""" skill_name = skill_name.replace("_", " ").replace("-", " ") skill_name = re.sub(r'(^[Ss]kill|[Ss]kill$)', '', skill_name) return camel_case_split(skill_name).title().strip()
8e0cbfde49b6b6d7568084711bea31b7c75af05f
49,840
import pathlib from typing import Tuple def generate_images(*, path: pathlib.Path) -> Tuple[files.File, ...]: """ Get the assets images to create. Args: path: the destination path for the images. Returns: A tuple of the images to create. """ images = assets.get_images() r...
72ca85feaf1dbe1fdb6128b194683d7e46f0a260
49,841
from datetime import datetime def timestamp2datetime(value): """ 将一个时间戳值转换为系统所在时区的日期时间实例 """ return timezone.make_aware(datetime.fromtimestamp(value))
e4fd2eaf7c8404ee0d1c9f817ebbcc0c2367d22e
49,842
from typing import List def generate_eagle_track( conductivity: np.ndarray, potential: np.ndarray, start_loc: List[int], dirn_restrict: int, nu_par: float ): """ Generate an eagle track """ num_rows, num_cols = conductivity.shape burnin = 200 max_moves = num_ro...
47a82e40ca85031c93b37999fdf75558fbb6eb0e
49,843
def _expm_vjp(exp_matrix, matrix): """ Construct the left-multiplying vector jacobian product function for the matrix exponential. Intuition: `dfinal_dexpm` is the jacobian of `final` with respect to each element `expmij` of `exp_matrix`. `final` is the output of the first function in the b...
f2e75e92aa0877bab8788015f079d58ba07e5fa0
49,844
def precook(s, n=4, out=False): """ Takes a string as input and returns an object that can be given to either cook_refs or cook_test. This is optional: cook_refs and cook_test can take string arguments as well. :param s: string : sentence to be converted into ngrams :param n: int : number of ...
72d75158a21ae84b9c76ef09663a1db866821c9e
49,845
def motorcycle_data(): """ The motorcycle dataset where the targets are normalised to zero mean and unit variance. Returns a tuple of input features with shape [N, 1] and corresponding targets with shape [N, 1]. """ df = pd.read_csv("./data/motor.csv", index_col=0) X, Y = df["times"].values.resh...
07312be5992029aa5bdd8951ba257944ce4b6f45
49,846
def get_class_distribution(y): """Calculate number of samples per class.""" # y_cls can be one of [OH label, index of class, class label name string] # convert OH to index of class y_cls = flatten_y_if_onehot(y) # y_cls can be one of [index of class, class label name] classset = sorted(list(set(...
2005c17361d971dbb5f04e767fe6896c7cea1d0e
49,847
from re import S def gamma_at_2_coefficient(k): """Reference: https://dlmf.nist.gov/5.7#E3""" if k == 0: return S(0) elif k == 1: return S(1 + digamma(1)) else: return ((-1)**k*(zeta(k) - 1)/k)
4779e30a55ea0a90a501b8f6db1df141e7fe3f2f
49,848
import sys import warnings import os def parse_args(): """Parser/validator for the cmd line args.""" parser = get_parser() if len(sys.argv) < 2: parser.print_help() warnings.warn('Too few arguments!', UserWarning) parser.exit(1) # parsing try: params = parser.par...
91d9340d2d81075ed250f6ac34c64fa5e622c859
49,849
def unverified_user(error): """Displays the front page with an error that the user must verify their email before accessing data. """ messages = { "Email Unverified": [ "Please complete the sign up process by verifying your " "email account. You should receive a verificat...
a1127547f0d7bcf08a63f67f42c07170a04c8ecf
49,850
import torch def initialize_sampler_lp_(g, batch_size, args, target_idx, evaluate_panrep =False): """ When lp is used different loader is required """ full_node_list = torch.arange(g.number_of_nodes()) target_uns = torch.arange(g.number_of_nodes()) val_pct = 0.1 use_cuda = args.gpu >= 0 and torch...
15c86f3057b1099195dd873e6fecbe4fd840fae7
49,851
def _velocity_factor(velocity_units_in: str, velocity_units_out: str) -> float: """helper method for convert_velocity""" factor = 1.0 if velocity_units_in == 'm/s': factor /= 0.3048 elif velocity_units_in == 'ft/s': pass elif velocity_units_in == 'in/s': factor /= 12. eli...
6f2acab5bf14c61f44ac4c2a260d9d367462a5a1
49,852
def submit_notable(service, notable, num_enrichment_events): """ Submits fetched notable to Splunk for an Enrichment. Three enrichments possible: Drilldown, Asset & Identity. If all enrichment type executions were unsuccessful, creates a regular incident, Otherwise updates the integration context for the ...
50b76cdb23949d91726ef1c40a17c45f8e8acd22
49,853
def avoid_my_body(my_body, possible_moves): """ my_body: List of dictionaries of x/y coordinates for every segment of a Battlesnake. e.g. [ {"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0} ] possible_moves: List of strings. Moves to pick from. e.g. ["up", "down", "left", "right"]...
cbb7b41b32d8acb84262ab346c19d5f736e4d8a6
49,854
import torch def image_grid(img, row, col): """ img: N,h,w,x collage: 1,.., x """ bs,h,w,c=img.shape device = img.device collage = torch.zeros(h*row, w*col, c).to(device) for i in range(row): for j in range(col): collage[i*h:(i+1)*h,j*w:(j+1)*w] = img[i*col+j] ...
3a5ee47ca5bbc652e3882be2d3c54fc572d670eb
49,855
def sautMini(group1, group2): """Critère du saut minimal""" mini = float("inf") for e in group1: for t in group2: dist = distanceEucl(e,t) if dist < mini: mini = dist return mini
9a3e5f03c09a707f7e82f40388d39c5988fa5761
49,856
import time def main(): """Main program entry.""" """Maybe add two minute delay before code starts to allow Alchol sensor to heat up to adequate temperature""" # add a heading to each data entry into API with open("data.csv", "w") as fp: # adds a set heading fp.write("alcohol concent...
28f055e083859c28756e3e8d35158f4fc94864da
49,857
import logging def get_optimal_threshold(y_true, y_prob, grid_spacing=0.01, verbose=False): """For probabilities, find optimal threshold according to f1 score. For a set of groud truth labels and predicted probabilities of these la...
561ddfbf9ad0f5213b1f258a2701fc1efbaf8ec7
49,858
import logging def contour_dem(dem_fp, raster_band=1, min_val=None, max_val=None, method='basic', contour_interval=None, n_contours=None, contour_list=None, bbox=None, output_format='features', logger=None): """Contour the DEM using one of two approaches, export geojson. :param dem_fp: the fi...
f838e42125e4a856d632672658f79b13ce32fc4e
49,859
def apply_style_transfer(content_uri:str, style_uri:str) -> str: """ Applies the style transfer effect to provided images. Returns base64 image representation. """ content_image = decode_image(content_uri) content_image = process_image(content_image) style_image = decode_image(style_uri) ...
162a485ec367a110d920f0291432e41d0892094f
49,860
from typing import Optional def get_metadata(order_id: str) -> Optional[dict]: """ Retrieve metadata for an order """ res = table.get_item(Key={ "orderId": order_id, "productId": METADATA_KEY }) return res.get("Item", None)
5470ed460cb7e586ae6d8e0c6d4ac7f9da2a58d6
49,861
def SearchFetchable(session=None, **kwargs): """Search okcupid.com with the given parameters. Parameters are registered to this function through :meth:`~okcupyd.filter.Filters.register_filter_builder` of :data:`~okcupyd.json_search.search_filters`. :returns: A :class:`~okcupyd.util.fetchable.Fetcha...
6f9e1eb8f703b651c7a64958feef5249e58b55e9
49,862
def getChildrenByName(rootNode, name): """Returns all child nodes of a specified name. """ return [e for e in rootNode.childNodes if e.localName == name]
77b1f7c7c4760cd940c39d30a2d4850b2ca3c147
49,863
import ipaddress def tcp_traceflow(packet): """Trace packet flow for TCP. Args: packet (pyshark.packet.packet.Packet): Scapy packet. Returns: Tuple[bool, Dict[str, Any]]: A tuple of data for TCP reassembly. * If the ``packet`` can be used for TCP flow tracing. A packet can be re...
4923ca7019de16a1dd2d1717b0e42abaf708ddd8
49,864
def plot(rawfile, pvars=None, outimg=None): """Loads the rawspice file and plots the data. Args rawfile: path to the rawspice.raw file pvars: list of variables to plot. If `None`, all variables are plotted. save: path to save file """ # FIXME: some poop logic here... ...
2d3e56b2b42cf65587490738d5032d59d70e0e90
49,865
def protocols_with_string(string): """Return a list of protocols matching given string.""" # Normalize string while "//" in string: string = string.replace("//", "/") string = string.strip("/") if not string: return [] ret = [] for name in string.split("/"): ret.appe...
307eff482819ac287accf80f964f0b4593eee63b
49,866
def percentage(value, precision=2): """Convert `float` to #.##% notation as `str`. A value of 1 = `"100.00%"`; 0.5 = `"50.00%"`""" return f"{value:.{precision}%}"
7abd3fafa8fc6f8323ca448ff5022faa0f83aa60
49,867
import re def simbadnames(query): """Given a source name, or other SIMBAD query, generates a list of identifier matches See http://simbad.u-strasbg.fr/simbad/sim-fscript """ u = urlopen( """http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script=format+object+%%22+%%25IDLIS...
ef9500c8e5e07638482570644e350c3799fb0927
49,868
import inspect import functools def decorator(func): """ Glossy Decorator This decorator can be used to make your decorators glossy. It simplifies the creation of decorators by flattening their structure and reducing the number of wrapper functions required. It also adds some additional attri...
e2bce4f8fd07aaa51b8dc8b7ad1182ecc861a26d
49,869
import math def compute_cohen(participant_ids): """ """ k_tot = [] for co in combinations(participant_ids, 2): k = cohen_kappa_score(df_feedback.iloc[co[0]], df_feedback.iloc[co[1]]) if math.isnan(k): k=1 k_tot.append(k) c_k = np....
4552f359536a5e965b355e76bf017954bedbfea5
49,870
import re def findAlphanumeric(line): """Parse string to extract all non-numeric strings""" return re.findall(r'^\w+', line)
7ac210f35d347532ff9e68b4fd6f6f978b0c61ea
49,871
import os def strictlyCaseSensitiveFilenames(): """Determines whether case is strictly significant in filenames""" GVars.out.put('checking case-sensitivity of filenames',globals.INFO) GVars.out.push() testname1 = 'TestFileName_tempFile123.mod' testname2 = 'testfilename_tempfile123.mod' # Str...
db482589afc854d7b95ff7afc73ee347632f1157
49,872
import os def dir_size(path): """ Get the size of the directory represented by path recursively. :param path: Path to the dir whose size needs to be calculated :return: size in bytes of the dir """ # Closure for recursiveness def get_dir_size(path): size = 0 for entry in os...
4bee3b7013b3bd98d677fe2cee4bc59bfe9fd04b
49,873
import urllib import aiohttp async def _get_username_password(registry_name: str) -> UsernamePassword: """ Gets the UsernamePassword for logging into the meadowrun-managed Azure container registry. Can be passed to functions in docker_controller.py """ # https://github.com/Azure/azure-cli/blob/28...
3fb4285dadf2d4b169a649ae5af703b009e14896
49,874
def rep(data): """Checks if all labels are represented in the dataset `data`.""" labels = [0, 1] # Iteratively check if all labels are represented for i in range(len(data) - 1): row = data[i] label = row["label"] contains = label in labels if contains and labels: ...
803c561c48fec10c44154138e83e95405054dad5
49,875
import logging def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ # support logging in python3 logging.config.fileConfig( settings['logging.config'], disable_existing_loggers=False ) config = Configurator(settings=settings) conf...
594f75fe6dfb361fa82f20a670a3cacfb7992f0a
49,876
import subprocess def run_program(program, args=None, **subprocess_kwargs): """ Run program in a separate process. NOTE: returns the process object created by `subprocess.Popen()`. This can be used with `proc.communicate()` for example. If 'shell' appears in the kwargs, it must be False, ...
3c1b0d597855451bacddb1baf04c87a5fc23c198
49,877
import re def quota_size(value): """ Covnert a human readable quota size into a number of bytes. """ _UNITS_RE = re.compile('^\s*(?P<value>\d+(\.(\d*)?)?)\s*(?P<scale>[kMGTP]i?)?B?$') _UNITS_SCALES = {None: 1, 'k' : 1000, 'ki': 1024, 'M' : 1000**2,...
fa464aa6a87fa36ed32ca9506d0a5fa4c6474d6d
49,878
def register_project(): """Register a project at Conductor service if not done already. The function checks all projects in the users config file and if a project does not have an id already it will try register it at the specified Conductor Service. """ registration_id = request.json["id"] ...
0ba3c216a2b9181007f6d1c101166fee69caa15d
49,879
import logging def snow_and_ndsi_locations(src_info, no_data_value): """Generate Landsat snow locations and NDSI nodata locations Args: src_info <SourceInfo>: Information about the source data no_data_value <int>: No data (fill) value to use Returns: list(<int>): Locations where ...
d4a86cb2361d3ccca95e9317567b3fe98408aa3f
49,880
def compute_cov(tensor, tensor_right=None, normalizer=None): """Compute the empirical second moment of the rows of a 2D Tensor. This function is meant to be applied to random matrices for which the true row mean is zero, so that the true second moment equals the true covariance. Args: tensor: A 2D Tensor....
d86464a0bfb9c064f075f799586967ee56aae08f
49,881
from typing import Optional from typing import Any def parametrize_filebased(abspath: Optional[str], filename: str, relpath: Optional[str]) -> Any: """ Converts a target json file as a source of parameters for pytest. :param abspath: Absolute path of the json file :param filename: Name of the json fil...
2503c5bcd590114f23b09e4884b1dc8947f4ac94
49,882
from typing import Optional def hexbin_viz( df: pd.DataFrame, x: str, y: str, plot_width: int, plot_height: int, tile_size: Optional[float] = None, ) -> Panel: """ Render a hexbin plot """ # pylint: disable=too-many-arguments,too-many-locals xmin, xmax = df[x].min(), df[x]....
1e97d2f482806e09a09f43289297a2c696a1cc36
49,883
def _func_if(args, is_differentscenario, line, pos): """args[0]がTrueであればargs[1]を、そうでなければargs[2]を返す。""" _chk_argscount(args, 3, "IF", line, pos) a = args[0] _chk_boolean(a, "IF", 0) t = args[1] f = args[2] return t if a.value else f
abeefa1707dfda41b438eb1b42c0be65932e8a02
49,884
def profiler(output_file=None, sort_by='cumulative', lines_to_print=None, strip_dirs=False): """ A time profiler decorator :param str output_file: Path of the output file. If only name of the file is given, it's saved in the current directory. If it's None, the name ...
7b4314569e03ad1b929cfd0f72534dcf90598730
49,885
def find_overlapping_annotations(m, annotations): """Takes a markup object and a df of annotations from the same report""" def overlaps(m_span, a_span): m_span = [int(n) for n in m_span] a_span = [int(n) for n in a_span] #print(m_span, a_span) overlap = ((a_span[0] <= m_span[0] <...
7cc95cd8ecf7403c84a800f502364384ed208199
49,886
import math def _is_prime_bruteforce(prime): """Check if a number is prime using brute force and some caching. Our brute force method is a little smarter than the standard method, as we rule some factors out due to the following principles: 1) We already have a list of cached primes. If our supposed ...
60abdadb0b846deb3a1f4c861193d2b6ed42461d
49,887
from typing import Union def encode(data: Union[bytes, dict, int, list]) -> bytes: """Convert the given Python object to a bencoded string. Raises: ValueError: If the provided object type is not supported Returns: A bencoded string """ if isinstance(data, bytes): return _...
b3aadafa9d9bb00283a5f5e6fa00378c3026def3
49,888
import torch def match_grasp_view_and_label(end_points): """ Slice grasp labels according to predicted views. """ top_view_inds = end_points['grasp_top_view_inds'] # (B, Ns) template_views_rot = end_points['batch_grasp_view_rot'] # (B, Ns, V, 3, 3) grasp_labels = end_points['batch_grasp_label'] # (B, ...
ca26ba32bca1c196b43a6197ad13cd5c5ffb2a71
49,889
def execute_blueprint(cli, blueprint, repo_info, logger=None): """ Execute a blueprint """ if logger is None: logger = j.logger.logging errors = [] logger.info('Executing blueprint [{}]'.format(blueprint)) try: res, ok = check_status_code(cli.executeBlueprint(data={}, bluep...
596a64e1c71d9b4411610cdba1aaa9fb8c6ab444
49,890
def convert_meshio( mesh, ignore_unknown=False, import_dim=(1, 2, 3), element_id_name="element_id", material_id_name="material_id", ): """ Convert points and cells from meshio to ogs format. Parameters ---------- mesh : meshio mesh class The given mesh by meshio igno...
a77bc912776ca0c9dbf1194c22de43b4ffcd6121
49,891
def get_data(path_imgs,path_masks,axis=0, batch=50,buffer_size=300, size_crop=160,random_crop=False, augmentation=False,repeat=1, pixels=0,cache=True, ): """ Returns dataset already preprocessed """ data = tf.data.Dataset.from_generator(gener...
5e0c976d240783e0477e6cda649f75a77d4d332e
49,892
import numbers def torch_item(x): """ Like ``x.item()`` for a :class:`~torch.Tensor`, but also works with numbers. """ return x if isinstance(x, numbers.Number) else x.item()
dae9881c21a305b42e5c488723a88beb117bf90f
49,893
def small_world_random(G): """ Compute the average clustering coefficient and average shortest path length of a random network with the same number of nodes and edges as G Parameters ---------- G: Network X undirected graph Returns ------- C: float the random network cluste...
3e118e5da58492c1ac7b968802c4cbb79cd73270
49,894
def count(grid, c): """ Count the occurrences of an object "c" in the 2D list "grid". """ acc = 0 for row in grid: for elem in row: acc += c == elem return acc
6a497b5d052ce8e1d2619f2278010ecd41126a42
49,895
def strictly_upper_triangle(m): """ Returns a matrix containing the strictly upper triangle of m and zeros elsewhere. """ l = _np.shape(m)[0] out = m.copy() for i in range(0, l): for j in range(0, i + 1): out[i, j] = 0 return out
5f8f0a5d9f81fa5fc202f4541a2948cad6892cd3
49,896
def config_retry_strategy(retry): """Generate retry strategy.""" if not isinstance(retry, int): raise ValueError("Parameter retry should be a number") return {"limit": retry, "retryPolicy": "Always"}
cb436261391e57e845ac5019c7906a56edc2db64
49,897
def isomap_transform(data_scaled, labels) : """Compute the Isomap transform from a scaled data. Parameters ---------- data_scaled : numpy.ndarray A matrix with the scaled data to transform labels : numpy.ndarray Labels to assign to the transformed data (0 for real and 1 for sy...
2caae82611bbab244376d7cea0b4f5181b516691
49,898
def call_solver(matvec, matvec_args, hI, params, x0, tol): """ Code used by both solve_for_RH and solve_for_LH to call the sparse solver. Solves matvec(*matvec_args, x) = hI for x. PARAMETERS ---------- matvec (jax.tree_util.Partial): A function implementing the linear ...
4b0a701b127335c9fcccd350a5b1f37e07661d0d
49,899