content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def invalid_entitlements_fixture(request): """A parameterized pytest fixture which returns invalid entitlements. Args: request : Built-in pytest fixture Returns: [String]: A string containing invalid Entitlements. """ return request.param
7f98b101bd8db303bb62a8c392689694f3a46805
73,561
def returns(*args): """ The decorator is used to allow us to specify the keys of the dict that the task returns. This is used only to signal to the user the inputs and outputs of a task, and deduce what arguments are required for a chain. """ if not args or len(args) != len(set(args...
96f7056b7bb30188d63b650c62d9932ba06c2996
73,562
def build_regionvit_fpn_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ bottom_up = build_regionvit_backbone(cfg, input_shape) in_features = cfg.MODEL.FPN.IN_FE...
c9e2872f15916df02051cf001482927fcaea183a
73,563
from typing import Any def circuit_regions( draw: Any, max_max_cycle: int = 1000, max_num_qudits: int = 20, max_volume: int = 200, max_qudit: int = 1000, empty: bool | None = None, ) -> CircuitRegion: """Hypothesis strategy for generating `CircuitRegion`'s.""" if empty is True: ...
7e4c53ce36c2e4070964574227aa208ac6d22e70
73,566
def surface_area(r): """ this is a test to see how to combine two versions """ return np.pi*r**2
3fb0475124ee65ea37386c7a9ea7d4f04a3bf25a
73,567
def __get_time_weight_in_list(d: dict) -> timedelta: """Returns the minimum time weight from the time list contained in the dict values ex: {'key': [time(hour=12), time(hour=9)]} => timedelta(hour=9) """ weights = [__get_time_weight(t) for t in d[1]] return min(weights)
e13c0240c5cf716f0023e831ecdd3dcf70a36270
73,568
import re def compute_word_freq(filename): """ Computa a frequencia de ocorrencia de palavras em um dado arquivo de texto. Devolve um dicionario mapeando cada palavra com pelo menos 5 caracteres (ignorando caixa alta e baixa) na sua frequencia de ocorrencia. Considere uma palavra como qualqu...
97b142281453a36a04e96345d91c67f052fd98c2
73,569
def pairwise_distance_np(feature, squared=False): """Computes the pairwise distance matrix in numpy. Args: feature: 2-D numpy array of size [number of data, feature dimension] squared: Boolean. If true, output is the pairwise squared euclidean distance matrix; else, output is th...
8c8e512da171fa8626dab58a031463e44ab7cf1c
73,570
def _get_triplet_ipsative_score(pair_score, trait_size, item_dt, item_sign): """ 配对比较分数转自比分数 :param pair_score: list(int), 配对比较分数 :param trait_size: int, 特质的数量 :param item_dt: dict(int: int), 试题维度字典 :param item_sign: list(1|-1), 试题正反向列表 :return: list(int), 自比分数列表 """ score = np.zeros...
7dc57f1148d65f4822c499418ab8470c0d04ae29
73,571
import requests def coinbase_price_check(coinbase_api_key, coinbase_api_secret, coin): """Check the price of a cryptocurrency against Coinbase to see if it fell below the minimum price Args: coinbase_api_key: An API key for Coinbase APIv2 coinbase_api_secret: An A...
622785a111e7019244479d4e520b119f873d7aa9
73,572
def _tensor_apply_decay_with_sparse(weight_decay, if_apply, weight, gradient): """Get grad with weight_decay.""" if if_apply: indices = gradient.indices values = op_add((op_gather(weight, indices, 0) * weight_decay, gradient.values)) shape = gradient.dense_shape return RowTensor(...
d8dfa894f085d2b23300bdb25b787375453b325a
73,574
def cal_performance(pred, gold,IGNORE_ID,normalize_length=False,smoothing=0.0): """Calculate cross entropy loss, apply label smoothing if needed. Args: pred: N x T x C, score before softmax ;;;; gold: N x T """ pred = pred.view(-1, pred.size(2)) gold = gold.contiguous().view(-1) loss = cal_loss(p...
a859c97a20bf643b6a580ce6cc50acb674339dc8
73,576
def exponential(x, halflife): """ Returns a decay factor based on the exponential function .. math:: f(x) = 2^(-x/halflife). :param x: The function argument. :param halflife: The half-life of the decay process. """ return 2 ** (-x / halflife)
2561d42f87c2818e82c2cc065592acf9ac8202fe
73,577
def down_sample(u_fine, grid_fine, grid_coarse): """Compute cell-averages of `u_fine` on the coarse grid.""" if grid_fine.n_dims == 2: raise Exception("Needs to be implemented.") ngf = grid_fine.n_ghost ngc = grid_coarse.n_ghost ncf = grid_fine.n_cells[0] - 2*ngf ncc = grid_coarse.n_ce...
6b1bc6b59fb698f992e21ca0817551e4c4ee9d0b
73,578
from ssd_util import SsdUtil from sonic_platform_base.sonic_ssd.ssd_generic import SsdUtil def import_ssd_api(diskdev): """ Loads platform specific or generic ssd_util module from source Raises an ImportError exception if none of above available Returns: Instance of the class with SSD API imp...
8e457604b28a4ba7e2c141751dce96c966edae8b
73,579
def get_cpu_part(): """Get the CPU part. :returns: The CPU part. :rtype: string """ return get_cpu_info("CPU part")
7faa09c02ce895752a8f97cc74a023fe729a0ef4
73,580
def keywithmaxval(dict): """ a) create a list of the dict's keys and values; b) return the key with the max value""" if len(dict) > 0: v=list(dict.values()) k=list(dict.keys()) return k[v.index(max(v))] else: return "Check"
56bc272c1ed65c60ddd0cea51a46736885796d9b
73,581
import pickle def decache(name, msg='', silent=False): """ decache a file """ try: with open(DIR_CACHE + name + '.pkl', 'rb') as f: obj = pickle.load(f) if not msg: msg = name msg = str(msg).ljust(30) + ' (loaded from cache)' if not silent: p...
b4792db83eb31f25649091d1f54f5e7453b31180
73,582
from typing import Iterable from pathlib import Path from typing import Optional from typing import Dict def to_lwpolylines( paths: Iterable[Path], *, distance: float = MAX_DISTANCE, segments: int = MIN_SEGMENTS, extrusion: 'Vertex' = Z_AXIS, dxfattribs: Optional[Dict] = None) ...
5d167e77e76fd6327a24fe4e24ee618302ddd875
73,583
import torch def augment_and_mix(image, trans, cfg): """Perform AugMix augmentations and compute mixture. Args: image: PIL.Image input image preprocess: Preprocessing function which should return a torch tensor. Returns: mixed: Augmented and mixed image. """ aug_list ...
e3503547e2dfe990b85cf91c3f947901c7cd799d
73,585
from typing import Dict from typing import Callable from typing import Optional def qualys_command_flow_manager( client: Client, args: Dict[str, str], command_name: str, command_methods: Dict[str, Callable]) -> Optional[CommandResults]: """ Args: client: Client object for makin...
f9a763708d503ac89efa1d0673fae7959966d7db
73,586
def rm_strheader(images): """ Remove the header of the images base64 string from front-end :param images: the input should be the base64 string of the image :raises TypeError: if input is not a string :returns: base64 string without data header :rtype: string """ if type(images) is not...
7466621dfa0a5bb31eb8735da89d68b885cb04ea
73,587
def glmfit(X, y, c=None, tail='both'): """ Linear estimation using GLM models ----------------------------------- Paramters: X: sample*feature. Independent matrix y: sample*yfeature. Dependent matrix c: contrast matrix tail: tails for significance Returns: -------- cope: ...
4ff2f7902a132c8b5f1a91a2752b8d76d7aa0a26
73,588
def test_structure_hook_func(converter): """ testing the hook_func method """ def can_handle(cls): return cls.__name__.startswith("F") def handle(obj, cls): return "hi" class Foo(object): pass class Bar(object): pass converter.register_structure_hook_func(can...
c61be290b3c7cbb2af87d47b76f09a662ada2fb5
73,589
def box_to_rect(box, width, height): """ :param box: center_x, center_y, bbox_w, bbox_h :param width: image width :param height: image height :return: x1, y1, x2, y2(in pixel) """ x, y, w, h = box x1 = (x - w * 0.5) * width y1 = (y - h * 0.5) * height x2 = (x + w * 0.5) * width...
32413d14e242f2d790c5ae9c93418abb4152df46
73,590
def __get_profile_from_points(voters, cands, voter_points, cand_points, approval_threshold): """Generates a list of approval sets from 2d points according to approval_threshold.""" profile = {} for v in voters: distances = {cand: __euclidean(voter_points[v], cand_points[cand]) for cand in cands}...
efbd633e669cae71a6774e3f1656346b8f06cb19
73,591
def calc_mean_std(features): """ :param features: shape of features -> [batch_size, c, h, w] :return: features_mean, feature_s: shape of mean/std ->[batch_size, c, 1, 1] """ batch_size, c = features.size()[:2] features_mean = features.reshape(batch_size, c, -1).mean(dim=2).reshape(batch_size, c...
fea325f57491cf06a4c2ffec4fb0a187ddea4a0a
73,592
import pickle def loadDownloader(tickerType): """loads from intermediate pickle file """ with open(tickerType + ".pickle", "rb") as f: return pickle.load(f)
2032e856cfc0e1d0048d1aa61dfc66a4ef9fa486
73,593
def _generate_one_ephemeris( cmd): """generate one orbfit ephemeris **Key Arguments:** - ``cmd`` -- the command to execute [cmd, object] **Return:** - ``results`` -- the single ephemeris results """ global cmdList cmd = cmdList[cmd] results = [] for c in cmd: ...
dfd25a0942b094f0e5034ac06192983f35e4ae43
73,594
def setbreak(depth = 0): """ Pause the script for inspection at next script statement. """ return __setbreak(depth + 2)
142d5fec24652a4afb484120bd8a0c647e649077
73,595
def PGD(S, cov, rho, criterion=None): """ PGD algorithm """ n = cov.shape[0] # Implement the PGD algorithm d_k, V_k = np.linalg.eigh(cov) s_k, U_k = np.linalg.eigh(cov) t_k = np.linalg.eigh(S)[0] cov_sqrt = np.dot(np.sqrt(d_k) * V_k, V_k.T) prec_sqrt = np.dot(np.sqrt(1 / d_k) * V_k, V_k....
ba11f8a6138437b0025dab7fd83dd003da41cec3
73,596
def route(command): """ :param command: a RemoteCommand :return: route string """ return "/api/v1/{}/{}/".format(service_constants.API_NAME, command.value)
1a6d477771815959d026fa20f56fdf21d4913baf
73,597
def compute_roi_pool(attrs, inputs, _): """Compute definition of roi_pool""" assert attrs.layout == "NCHW" return [topi.vision.rcnn.roi_pool_nchw( inputs[0], inputs[1], pooled_size=get_const_tuple(attrs.pooled_size), spatial_scale=attrs.spatial_scale)]
62aee416f8417274bc1d729b791dc5325fef1e23
73,598
import copy import datasets def average_validation(records, weights): """ This is for population shift datasets Args: records (dict): Dictionary of records from a single training run weight (list): List of domains weights Returns: float: validation accuracy of the best checkpoint...
80d9e6e7ba336b430d4f17e60f3a2409aa6dd49d
73,599
def gomc_sim_completed_properly(job, control_filename_str): """General check to see if the gomc simulation was completed properly.""" job_run_properly_bool = False output_log_file = "out_{}.dat".format(control_filename_str) if job.isfile(output_log_file): with open(job.fn(f"{output_log_file}"), ...
542c22836e22a3cc97a38744959dcb21b833c7a0
73,600
from pathlib import Path from typing import Dict from typing import Any import warnings def fetch_openml_dataset(dataset_id: int, data_directory: Path = get_data_dir(), ) -> Dict[str, Any]: """ Gets a dataset from OpenML (https://www.openml.org), or from t...
b26eea4057bbe45d72314de43b20756aec8e10ad
73,601
import json def build(**kwargs): """ build message, return dict """ t = Template(template()) content = t.substitute(**kwargs) return json.loads(content)
1e9dd75f385e0cb8f5cfe92f04a4823c98dd70a4
73,602
import torch def gcxgcywh_to_cxcywh(boxes, anchors): """ Decode bounding box coordinates predicted by the model, since they are encoded in the form mentioned in the encoding function. They are decoded into center-size XYWH coordinates. :param boxes: encoded bounding boxes, i.e. output of the mod...
c4dda7ea9696fb4620079f06a59e7e672e29d8d3
73,603
import sqlite3 def connect_db(): """Connects to the specific database.""" rv = sqlite3.connect(db_uri, uri=True) rv.row_factory = sqlite3.Row return rv
79734752d6fbae92f736f59fa40d9b5ab0090ca6
73,604
from unittest.mock import patch async def setup_unifi_integration( hass, config, options, clients_response, devices_response, clients_all_response ): """Create the UniFi controller.""" hass.data[UNIFI_CONFIG] = [] hass.data[UNIFI_WIRELESS_CLIENTS] = unifi.UnifiWirelessClients(hass) config_entry = ...
d031e0244cfe315c66b137fd7967d40cfef7a385
73,605
def mean(data, key=None): """ mean with data type check :param data: points :param key: key function :return: """ if key is not None: data = [key(point) for point in data] data = filter(lambda x: isinstance(x, (int, float, long)), data) if len(data) < 1: return None ...
92e7142628706a467875b03d88dcb1a748e85068
73,606
def SqrNorm(x): """Square of the norm. :param x: return sum(x*x) :return: return sum(x*x) """ return sum(x*x)
03f35a7395ba74981eace38b634a14210932cffd
73,607
from pathlib import Path def create_h5temp_global() -> Path: """Create temporary global HDF5 rawfile. Returns: Path: Path object of filename. """ fn = Path("/tmp/data/MXD13A2.006.VIM.h5") rows = 2000 cols = 7200 with h5py.File(fn, "a", driver="core", backing_store=True) as h5f...
02f884b613f2da23ce2344adf70e9f9707cab3a9
73,608
from typing import Tuple from typing import Sequence def sample_text_elements(workspace_id: str, dataset_name: str, sample_size: int, filter_func, remove_duplicates=False, random_state=None) -> Tuple[Sequence, int]: """ :param sample_size: if None, return all elements without samplin...
a603cd188bc5d593abb20b51fd99286bf49ac53d
73,609
import socket def create_connection(server=None, port=None, timeout=None, use_ssl=False): """Create a socket or a secure ssl socket. Hopefully some day such functionality will be included in python3. :returns socket :rtype socket.SocketType """ # based on socket.create_connection() if us...
8596d3dc7c0cf7e75933618c0c302f5ddb63a420
73,610
def build_cudnn_layers(layers, units, activation, memory_cell, direction, dropout, name): """ Builds layers optimized for CuDNN if hparams.use_cudnn_layers is True. Args: layers: The number of layers. units: The number of units per layer. activation: Activation function to ...
872b86984d2771e0b9c6425534ef567789a28e7d
73,612
from typing import Union from datetime import datetime def get_next_trading_date(date: Union[str, datetime.date, datetime.datetime, pd.Timestamp], n:int=1) -> pd.Timestamp: """ 获取指定日期之后的第 n 个交易日 :param date: 指定日期 :param n: 第 n 个交易日 :example: .. code-block:: python3 ...
e177529697377be8c5c86c7bd05b75419a65e9f4
73,613
def new_superuser(db, new_superuser_factory): """Return a new superuser""" return new_superuser_factory()
7b0751788c9aea1cd37b7e26deb5a7f6e1d6a35f
73,614
def _parse_numpy_pixeltype_from_string(s): """ example: "image_FLOAT_3D.nii.gz" -> 'float32' """ if 'UNSIGNEDCHAR' in s: return 'uint8' elif 'CHAR' in s: return 'int8' elif 'UNSIGNEDSHORT' in s: return 'uint16' elif 'SHORT' in s: return 'int16' elif 'UNSIG...
8066c9eab8b31fa290ac68d44b6bd448a3a689de
73,615
def _compute_distance(x1, x2, mean_vector, epsilon=0.0000001): """ Compute distances between data points by using L1 on normalized data : sum(abs(x1-x2)/(mean_vector+epsilon)) Parameters ---------- x1 : array First vector x2 : array Second vector mean_vector : array ...
358c728862703dd4b83ec423caf69910a51bc1f7
73,616
def scan(name, work_queue, result_queue): """Loads data into work_queue, then gets results from result_queue.""" try: with open(name, 'rb') as f: for i in read_in_chunks(f): work_queue.put(i) except IOError: return 'Error' else: work_queue.join() ...
efcc9309ea7c3b229489df209e2a797cf8d62ba2
73,617
from vtk import vtkImageBlend def combine_images(*images): """ Layer images onto each other (centered) and return the output """ width, height = 0, 0 for i in images: new_w, new_h, _ = i.GetDimensions() if new_w > width: width = new_w if new_h > height: ...
630a141f26a2347710f9eb851fa04ffe700a1a0f
73,618
def calc_dist_folded(x,y,z,unitcells,shifts=None,matrix=False,npt=False): """New: take into account pbc danger of accumulative error x -- x-coordinates of positions, ntime x natom y -- y-coordinates of positions, ntime x natom z -- z-coordinates of positions, ntime x natom unitcells -- array wi...
29b9f925df52c5a548be2224d680005a9691a25a
73,619
def ortho(modes): """\ Orthogonalize the given list of modes. """ N = len(modes) A = np.array([[np.vdot(p2,p1) for p1 in modes] for p2 in modes]) print 'A.shape ',A.shape e,v = np.linalg.eig(A) print 'e', e print 'v', v print v[:,0] ei = (-e).argsort() print 'ei', ei ...
1aa604023614fe0415cf4bb20bdcb600bf18e791
73,620
def get_databases_list(server_uri, query): """ List databases on a specified MySQL server Arguments: server_uri : URI of MySQL server e.g. mysql://user@host:3306/ query : optional regular expression to filter databases e.g. .*_core_.* """ if db_uri.startswith('mysql') is False: r...
7ebd266b08712d3ba1b5bcaac4271e0e669140cf
73,621
import re def remove_superscripts(word: str) -> str: """ This function removes all superscripts from a given word. :param word: A given word :return: The given word stripped from superscripts. """ rx = '[' + re.escape(''.join(SUPERSCRIPTS_TO_UNICODE_CHARS.keys())) + ']' return re.sub(rx, ...
6cfbb0d4cbe64c9ec488c64adad8d1f6941afaa7
73,622
import urllib import json def get_articles(id): """Function to retrieve news sources list from the News api""" get_articles_url ='https://newsapi.org/v1/articles?source={}&apiKey={}'.format(id,api_key) with urllib.request.urlopen(get_articles_url) as url: get_articles_data = url.read() ...
dfcbfcc48d8739cb6e9a69692604704cbf7333c4
73,623
def set_zenangle(profs, zen=None): """Set zenith angles to a new value. If zen is missing, angles cycle in steps of 10 degrees between 0 and 70 over the profile set.""" if zen: zenlist = [zen] else: zenlist = range(0, 71, 10) for p in range(profs['nprof']): profs[p]['zena...
41d7099e7eb7ac9da1532c28be00b1a574e84e6e
73,625
def preprocess(X): """ Optional preprocessing for secondary data format. @param X: list of lists of lists (glogs, function calls, function call + attributes) """ for i in range(len(X)): for j in range(len(X[i])): X[i][j] = ' '.join([str(x) for x in X[i][j]]) X[i] = '\n'.j...
b759c0353dfeb5c2d4292fd541c8dba507c1ccea
73,626
import requests from bs4 import BeautifulSoup def question_info_get(qid): """ 获取问题的标签 Parameters ---------- qid : int question id. Returns ------- keywords:list 问题关键词 """ headers = { "User-Agent": "", "Connection": "", "Accept": "", "Accept-La...
fb5f1d6bf41a267237f24d677e43c51c474a90f7
73,627
def initialize_logger(options): """Initialize logger instance.""" # Default of None means to use colorama's autodetection to determine whether or not to use color color = None if options.get("force_color"): color = True if options.get("no_color"): color = False enable_logging(ve...
041b9df2be0ce015aa79650b4eb0599c1ef5ae12
73,628
def get_registration_extension_form(*args, **kwargs): """ Convenience function for getting the custom form set in settings.REGISTRATION_EXTENSION_FORM. An example form app for this can be found at http://github.com/open-craft/custom-form-app """ if not getattr(settings, 'REGISTRATION_EXTENSION_FORM...
d07155c013ea62ce1c8aa96bbab2b2fa66b15633
73,630
def _add_one_hot_encoding(df, skip_one_hot_columns=None, one_hot_columns=None): """ integer columns are converted to onehot columns. This is helpful in gradient based models LR,NN. Returns a dict mapping old column to new column names. """ new_columns_dict = {} dtypes_df = df.dtypes if one...
4ea21a4383ef921848594e387ba650c72234850e
73,631
import yaml def read_config(filename): """Read configuration file. :param filename: Path to configuration file. """ with open(filename) as f: params = yaml.safe_load(f) return params
7fb88e746c7cdc234a648a3a6216fa49f682f9d9
73,632
def reverse_dict(d): """Reverses direction of dependence dict >>> d = {'a': (1, 2), 'b': (2, 3), 'c':()} >>> reverse_dict(d) # doctest: +SKIP {1: ('a',), 2: ('a', 'b'), 3: ('b',)} :note: dict order are not deterministic. As we iterate on the input dict, it make the output of this function d...
95bd1f427a4e6635b678e129c8f2d69b4b083f9f
73,633
def compute_absolute_power(freqs, powers, band, method='sum'): """Compute absolute power for a given frequency band. Parameters ---------- freqs : 1d array Frequency values. powers : 1d array Power spectrum power values. band : list of [float, float] Band definition. ...
92db5c6b62bd778b708168de85277265682c5da8
73,634
from typing import Optional def get_server_trust_group(location_name: Optional[str] = None, resource_group_name: Optional[str] = None, server_trust_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> Awaitab...
8e84a2d0d0b0ac3a93bb9bec1cd54c3bfaadf455
73,635
def get_csr(ttl=None, common_name=None, locality=None, country=None, province=None, organization=None, organizational_unit=None): """Generate a csr for the vault Intermediate Authority Depending on the configuration of the CA signing this CR some of the fields embedded in the CSR ma...
f3362a7ba941e2f625da2badd3dd1fddb2894062
73,637
def set_unauthorized(nxt: HTTPFunc, ctx: HTTPContext) -> Future[HTTPContext | None]: """Sets response status code to UNAUTHORIZED. Args: nxt (HTTPFunc): to run next. ctx (HTTPContext): to process. """ return set_status(UNAUTHORIZED)(nxt, ctx)
60b9bda0b1db5426f7ec6d535c5ab4b5fe458ed8
73,638
from typing import List from typing import Dict def flatten_dict(d) -> List[Dict]: """ Use this helper functon to flatten a dict holding API response data and namespace the attributes. """ def expand(key, val): if isinstance(val, dict): return [(key + "." + k, v) for k, v in f...
be0f0df42048276e1c16cfcf117de4c7d096e7be
73,639
def argmax(array): """Return the index of the minimum element of an array. Examples -------- >>> _argmin(np.array([1,-1,2,3])) (3,) >>> _argmin(np.array([[0,1],[2,1]])) (1, 0) """ return np.unravel_index(np.argmax(array), array.shape)
d3e4914fd00eb13cc91c53159f7b95c9d92359b8
73,640
def spectroscopic2name(el,roman): """ Convert from spectroscopic notation, e.g. Fe XI to 'fe_11'. Parameters ---------- el : `str` Elemental symbol, e.g. Fe for iron roman : `str` Roman numeral spectroscopic symbol """ elu = el.lower() romanu = roman.upper() idx...
ca48b58f525333b4a9c1d5ae475a2c752dcc4c10
73,641
def poly_fit(traj, traj_len=30, threshold=0.002): """ Input: - traj: Numpy array of shape (2, traj_len) - traj_len: Len of trajectory - threshold: Minimum error to be considered for non linear traj Output: - int: 1 -> Non Linear 0-> Linear """ t = np.linspace(0, traj_len - 1, traj_le...
16daa3f38fd8b0c073dbe014585e29aade3e04b9
73,642
def get_all_classes_properties_numerical(endpoint=None): """ search for all class/property combinations with numerical objects. here we are relying on the defined structure using rdfs:range and rdfs:domain (TBOX) and not on the data level :param endpoint: :return: a list of class/property combinatio...
3ab48c9b38ce29a5f63295750fe5130a2cb75ec4
73,643
def dup(integer): # real signature unknown; restored from __doc__ """ dup(integer) -> integer Duplicate an integer socket file descriptor. This is like os.dup(), but for sockets; on some platforms os.dup() won't work for socket file descriptors. """ return 0
aac98f8c767d2224b3949aea4aafcb83d0c0ee1c
73,644
def evaluate(session, loss_op, accuracy_op, feed_dict): """Evaluate the model. Computes the loss and accuracy with repeated calls with the specified feed_dict. Halts, when session.run raises an tf.errors.OutOfRangeError (i.e. the whole dataset was iterated trough once and returns the average loss and accurac...
0d01b28f11ef054f6319bfa27ec9107c9cc6d853
73,645
import torch def communities_to_labels(n_nodes, communities): """ For n_nodes nad a communties dictionary or list of lists returns a list with size 'n_nodes' assigning to each node index the corresponding node community. :param n_nodes: :param communities: :return: """ comm_labels = t...
e961568fff8959e909f0b44469a745d33ff5233d
73,646
import torch def to_q(mod, dim=0, CHUNK_SIZE=128): """Var approx distribution generator for a convolutional layer.""" assert isinstance(mod, ConvNdGaussianMixin) def q(mean, log_var, dim=1 + len(mod.kernel_size)): r"""Reinterpret fully factorized Gaussian `q` as factorized by slice. Deta...
0d47ce2d71ad7aa5ea20b707ddc995d0a0057b23
73,647
def build_orthogonalizer(S): """ Form the orthogonalization matrix A = S^{-1/2} using pure NumPy. """ # Application of a function to a matrix requires transforming to # the diagonal basis, applying the function to the diagonal form, # then backtransformation to the original basis. eigval, ei...
fbed8405fddb8857d98219ba1c10841e0f00b404
73,648
def process_raw(procstatus, dscfg, radar_list=None): """ Dummy function that returns the initial input data set Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries data set co...
42af295ccb30a521f1c0502628d66826a550558a
73,649
def load_data(filename: str): """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
c1120d155f784f0ea17dbaf7afe2f2545c2a591f
73,650
def check_intensifiers(text, INTENSIFIER_MAP): """ Utility function to check intensifiers of an emotion :param text: text chunk with the emotion term :return: boolean value and booster value for intensifiers """ # BOOSTER_MAP = {"B_INCR": 2, # "B_DECR": 0.5} intensity_word...
2c35b6b66395bc7105b9fb1b9cf7f04b5686cb8d
73,652
def create_email_message(to_emails, from_email, subject, text, html): """ Create the appropriate plaintext or html email object. Returns: email - an instance of either `django.core.mail.EmailMessage` or `django.core.mail.EmailMulitiAlternatives` based on whether or not `html_message` ...
45049b4230e761487383879b5a3a65ca2c1260d5
73,654
def get_next_code(last_code): """Generate next code based on the last_code.""" return (last_code * 252533) % 33554393
9fcf416df3448a8ca46a55073f66d12cd8fc2593
73,656
from typing import Optional def get_app_sec_security_policy(config_id: Optional[int] = None, security_policy_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppSecSecurityPolicyResult: """ Use this data sou...
9ee579e5d116aef2bdf915030de1de93f847efe7
73,658
def mixer_b32_224(pretrained=False, **kwargs): """ Mixer-B/32 224x224 Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601 """ model_args = dict(patch_size=32, num_blocks=12, hidden_dim=768, **kwargs) model = _create_mixer('mixer_b32_224', pretrained=pretrained,...
da7283d4286ec3f900a6abc2a39d3b386857ef1d
73,659
from typing import List def read_data(file: str) -> List[LabeledSentence]: """ Reads a dataset in the CoNLL format from a file The format is one token per line: [word] [POS] [syntactic chunk] *potential junk column* [NER tag] One blank line appears after each sentence :param file: string filen...
c89bad6fd011722daa5e6b7c92a97b5947296590
73,660
import requests def get_histogram(ID, filename): """ GET request to get histogram image from server/database Args: ID (str): user name filename (str): filename Returns: i (nparray) : array of histogram image """ djson = { "username": ID, "filename": fi...
ebbabb5847dea64c46daa0f802c15a3816b98b09
73,661
def detach_flc_policy(session, lc_policy_id, volume_id, return_type=None, **kwargs): """ Detach a volume from a file lifecycle policy. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type lc_policy_id: str :para...
bd2a944eba3f999f7c132d2292448dfd6506298a
73,662
import base64 def decode(b64): """ Decode given attribute encoded by using Base64 encoding. The result is returned as regular Python string. Note that TypeError might be thrown when the input data are not encoded properly. """ barray = base64.b64decode(b64) return barray.decode('ascii')
5c04c43247d1415ca8f1398c3b8206c50a7e0fa4
73,663
from unittest.mock import patch async def async_setup_sdm(hass, config=CONFIG, with_config=True): """Prepare test setup.""" if with_config: create_config_entry(hass) with patch( "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation" ): return awa...
e5e649e7bdc4428f578a85c2979077152e635902
73,664
def get_date(s): """Returns date object from string.""" if s.find(".") != -1: # DD.MM.YYYY(.) format args = s.split(".") if args[len(args) - 1] == "": args.pop() args.reverse() else: # YYYY-MM-DD format args = s.split("-") args = list(map(int,...
83145a9775685808aaf4855265dcdd37e37fb746
73,665
def _get_x_ranges(obs_mean, obs_cov): """Get integration limits (8 sigma interval, includes > 99.99% of area).""" x_ranges = [] for (idx, var) in enumerate(np.diag(obs_cov)): std = np.sqrt(var) x_range = [obs_mean[0][idx] - 4.0 * std, obs_mean[0][idx] + 4.0 * std] x_ranges.append(x_r...
0d2174acfa264079e688db75e38f7ce4ff342570
73,666
def _strip(value): """ Strip the input value if it is a string and returns None if it had only whitespaces """ if isinstance(value, basestring): value = value.strip() if len(value) == 0: return None return value
958d385d20260dc61d7b069911365242bcc73463
73,668
from typing import Union from typing import Tuple from typing import Any from typing import Dict def _tupleize_compound_item(k: Union[Tuple, str], v: Any) -> Dict: """ converts a JSON-input compound key/value pair into a dictionary of tuples """ if _is_compound_key(k): return {_tupleize_compound_key(k): _tupl...
63ec7fc8eae7a6240cd633143851ed422e951e6c
73,669
def norm_minmax(pixspec, vmin=None, vmax=None, axis=0): """Normalize features in the [0,1] range. Parameters ---------- pixspec: ndarray the set of spectra to normalize vmin: float custom minimum value; if None, computed from data vmax: float custom maximum value; if Non...
f2c00fa6f5211d14129d09f00f557e05358cb796
73,670
def read_traj_clusters(filename): """ Parses a textfile of online clusters, where each line contains the space-separated values of one cluster-center. """ read_line = lambda s: [float(p) for p in s.split(" ")] with open(filename, "r") as infile: traj_clusters = np.array([read_line(line) ...
4dcb0fc538b72a9dc2f3b91512b82348259712f1
73,671
import requests def get_multizone_status(host, services=None, zconf=None): """ :param host: Hostname or ip to fetch status from :type host: str :return: The multizone status as a named tuple. :rtype: pychromecast.dial.MultizoneStatus or None """ try: status = status = _get_status(...
59c7be58cf276ec5e5b1bb2352563494f87f3d06
73,673
import json def load_global(what): """ Load data that is not specific to a single issue/MR. For example users, milestones, issue list or MR list. """ path = DIR / f"{what}.json" if not path.exists(): return fetch_global(what) with open(path) as f: return json.load(f)
fa9718d6111a091758bae38c6147586b6deaa5fe
73,674
def pdvec(data, Nint, epsmax=1): """make persistence vector with the top Nint persistences using rips complex""" digs, ints0, ints1 = gettree_int(data, edgelen=edgelen) out1 = _pdproc(ints1, Nint) out0 = _pdproc(ints0, Nint) return (out0, out1)
cfd719eb7f3f4d877499ad6d2779424fec9b03fd
73,675