content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_average_precisions(gt: list, predictions: list, class_names: list, iou_thresholds: list) -> np.array: """Returns an array with an average precision per class. Args: gt: list of dictionaries in the format described below. predictions: list of dictionaries in the format described below. ...
e04e04cb5214219a5fdb341a4577036241b8b241
46,000
import random def make_stan_person(num1, num2): """字段列表 "busi_reg_no":"客户号", "ctnm":"客户名称", "cten":"拼音/英文名称", "client_tp":"客户类别",1客户,2商户 "account_tp":"账户分类",1/2/3代表1、2、3类账号 "busi_type":"业务类型", "smid":"主体特约商户编号", "citp":"证件类型", "citp_ori":"证件类型原值", "citp_nt":"证件类型说明", "c...
c8d30542b75de2f499cf664319eb5fc0fb0d2fec
46,001
def zeros(shape, dtype=None, name=None): """ The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0. Args: shape(tuple|list|Tensor): Shape of the Tensor to be created, the data type of ``shape`` is int32 or int64. dtype(np.dtype|str, optional): Data type o...
d76ee2f286054459438b75136ab5404dbb26becb
46,002
import numpy def scroll_array(array: numpy.ndarray, dx: int=0, dy: int=0) -> numpy.ndarray: """ Scroll pixels inside a 3d array (RGB values) Use dy to scroll up or down (move the image of dy pixels) :param dx: int, Use dx for scrolling right or left (move the image of dx pixels) :param dy: int, ...
ac05c552af73a2a655938c7bfadbb5f6225b88f4
46,003
import pathlib def available_datasets(dataset_path=None, keys_only=True): """Get a list of available datasets. Parameters ---------- dataset_path: path location of saved dataset files """ if dataset_path is None: dataset_path = processed_data_path else: dataset_pat...
2aaf4b578ea992e1d43113c67f5f097d0f62abba
46,004
def get_user_by_username(username): """ Get user by username helper :param username: :return: user query object """ user = User.query.filter_by(username=username).first() return user
50816187b85bde183fdf6d3dfe4cb28d5fafebf3
46,005
def pproc_Kirchhoff_2d(size, shape: nparray, points: nparray, solution: nparray, D: nparray, S: nparray, loads: nparray): """ JIT-compiled function that calculates post-processing quantities at selected ponts for multiple left- and right-hand sides. ...
b5e40e229b9cefaad7f0fc9ca166946acde164b2
46,006
def make_interrupt(name, irq, description): """make an interrupt""" i = interrupt() i.name = name i.irq = irq i.description = description return i
b81580f4426da5b68ee69a532cddfa18fd2d99b5
46,007
def stacked_bar(tag, title, datalist): """ data list should be a list of dictionary formatted as follows {"name": "A" "data": { "R1_mapped": 50, "R2_mapped": 50, "R1_unmapped": 50, "R2_unmapped": 50, } } """ dataitems = "" for item in datalist: ...
2d19d8b15e10d54690f69940aa5cdedff317af00
46,008
def version(api, verify_version=False): """Obtain a dictionary of versions for the Podman components.""" response = api.request("GET", "/_ping") response.read() if response.getcode() == HTTPStatus.OK: return response.headers # TODO: verify api.base and header[Api-Version] compatible retu...
840e80866d009df10d77b5d8105de26f2b91c454
46,009
async def restart(hub, ctx, name, resource_group, **kwargs): """ .. versionadded:: 1.0.0 Restart a virtual machine. :param name: The name of the virtual machine to restart. :param resource_group: The resource group name assigned to the virtual machine. CLI Example: .. code-block...
4296e109471c2d376b9a571f1dc9749a9f4b8699
46,010
def mk_models_NO1(activation, mid_units, dropout_rate,dropout_rate_2,X_train,LEARNING_RATE): """ RGB画像を対象に分類を行います 入力サイズは基本(image_num,64,64,3) 畳み込みは2回 """ filter_num=get_filter_num() labels=get_labels() model = Sequential() model.add(Conv2D(32, (3, 3), padding='same',input_shap...
c7d958de69a74319d820495cdd25065cf00c6fd3
46,011
def cli(ctx, workflow_id, label): """Get a list of workflow input IDs that match the given label. If no input matches the given label, an empty list is returned. Output: list of workflow inputs matching the label query """ return ctx.gi.workflows.get_workflow_inputs(workflow_id, label)
266434ed4cf55c822cb231114d20f0388f70b879
46,012
def cvCalcAffineFlowPyrLK(*args): """ cvCalcAffineFlowPyrLK(CvArr prev, CvArr curr, CvArr prev_pyr, CvArr curr_pyr, CvPoint2D32f prev_features, CvPoint2D32f curr_features, float matrices, int count, CvSize win_size, int level, char status, float track_error, CvTermCriteria crit...
c3ea0716a12e993fee2a63219989f3abf9b2197e
46,013
import os def get_artifacts_store_name(): """Get the artifacts store name""" return os.getenv(POLYAXON_KEYS_ARTIFACTS_STORE_NAME)
1ec6f4e81c4483b0059f638bcd6ef7cce4d61ffd
46,014
from typing import Optional def build_sgpr( data: Dataset, search_space: SearchSpace, kernel_priors: bool = True, likelihood_variance: Optional[float] = None, trainable_likelihood: bool = False, num_inducing_points: Optional[int] = None, trainable_inducing_points: bool = False, ) -> SGPR: ...
709abf48da0bf2c4df8e6f7d3db76912477f06bf
46,015
def cb_config(data, option, value): """Script option changed, update our copy.""" option_name = option.split(".")[-1] if option_name in vimode_settings: vimode_settings[option_name] = value if option_name == 'user_mappings': load_user_mappings() if "_color" in option_name: lo...
64cee35e2dbe8cab3017e658ed21ac77bd078d98
46,016
def phasedivergent(repo, subset, x): """Mutable changesets marked as successors of public changesets. Only non-public and non-obsolete changesets can be `phasedivergent`. (EXPERIMENTAL) """ # i18n: "phasedivergent" is a keyword getargs(x, 0, 0, _(b"phasedivergent takes no arguments")) phase...
b7d9c00160bfe06d50d5e46903f6d0af46d0768e
46,017
def find_on_screen(file): """ :param file: image :return: the x and y coordinate and width and height dimensions of the image on the screen """ return gui.locateOnScreen(file)
9111e66abd4986ed7540dd9e6541c4220db81393
46,018
import os def _get_rpg_files(path_to_files, level): """Returns list of RPG files for one day sorted by filename.""" files = os.listdir(path_to_files) files = [f"{path_to_files}{file}" for file in files if file.endswith(str(level))] files.sort() return files
27ffcedb5c7f5fde6bf440c164327c81c40c0d73
46,019
from pyNastran.op2.dev.op4 import OP4 def proccess_drm1_drm2(op2file, op4file=None, dosort=True): """ Process op2/op4 file2 output from DRM1/DRM2 DMAPs to form data recovery matrices. Parameters ---------- op2file : string Either the basename of the .op2 and .op4 files, or the full ...
03721bfb60ec1893071e1bc8530ed033eb0d6d59
46,020
def ugrnn_transform(state: tf.Tensor, inputs: tf.Tensor, W_gates: tf.Tensor, b_gates: tf.Tensor): """ Performs a standard UGRNN transformation. """ # Compute the linear transformation for the gates stacked = tf.concat([inputs, state], axis=...
a0957ea7f183143d9f80c6043e892fe6157df835
46,021
def f(xx, uu, uref, t, p): """ Right hand side of the vectorfield defining the system dynamics :param xx: state :param uu: input :param uuref: reference input (not used) :param t: time (not used) :param pp: additionial free parameters (not used) :return: ...
e348be5a4f687e3aae1502b94d7810956b818747
46,022
def overview_data(vv, state = None,p = 0.25): """ Fetches, filters, and cleans Voteview NOMINATE data and returns as JSON string Args - p: sample proportion """ if state != None: p = 1.0 vv = filter_state(vv, state) vv = filter_cols(vv,COLS) vv = add_part...
3ff21acbdfe87fb013c303238dbfbea34f52c2d8
46,023
def return_prediction(model, sample): """Return a prediction for heart classification Arguments: model {model.h5} -- Pre-trained model to predict the heart classification sample {array} -- Sample of the ECG reading of dimension (1,186,1) Returns: string -- Returns the predictions ...
6e0e5885a32781fff3917f7cd1b1eb6a0e228cf5
46,024
import importlib import pkgutil def import_submodules(package, recursive=True): """ Import all submodules of a module, recursively, including subpackages :param package: package (name or actual module) :type package: str | module :rtype: dict[str, types.ModuleType] """ if isinstance(packa...
edd0ccfc16f1c3b73da765d2e530607e6f08ef19
46,025
import sys import warnings def include(obj_name): """ Includes the object with the given name. The requirement is satisfied when the respective object is exported. Parameters ---------- obj_name : `str` The object name to include when exported. Returns ------- placeho...
d4e8d039574cf8667bb46f58140a033e475639ee
46,026
def shownamespaces(context, mapping): """Dict of lists. Names attached to this changeset per namespace.""" repo = context.resource(mapping, b'repo') ctx = context.resource(mapping, b'ctx') namespaces = util.sortdict() def makensmapfn(ns): # 'name' for iterating over namespaces, templat...
e1364824d80acd4a1e4efeaa0ceabd7bac4c2525
46,027
def GetFlagValue(index): """Returns the flag value for the given index value (0...n-1).""" return bundle_firmware.gbb_flag_properties.values()[index]
60819cb01ebd03009052ec322515cc6010c6e62e
46,028
def get_translation(nmt_outputs, sent_id, tgt_eos, subword_option): """Given batch decoding outputs, select a sentence and turn to text.""" if tgt_eos: tgt_eos = tgt_eos.encode("utf-8") # Select a sentence output = nmt_outputs[sent_id, :].tolist() # If there is an eos symbol in outputs, cut them at that poin...
355a7f52489154a59d89aec50a8f61118d478797
46,029
def lstmcell_grad_h(input, hx, cx, w_ih, w_hh, b_ih, b_hh, dh, dc, target="cce"): """ Computes dh w.r.t. dw, db, dcx, dhx, dx. Args: input: akg.tvm.Tensor of type float16, float32. hx: akg.tvm.Tensor for hidden variable from previous cell. cx: akg.tvm.Tensor for state variable...
b45d0c57961db28e7de41d9c1830b3306e860fc3
46,030
def get_mod_whitelist(): """Return dict of modifications that are relevant for the data.""" mod_whitelist = {} for members in antibody_map.values(): for gene_name, phos_sites in members.items(): for residue, position in phos_sites: if gene_name not in mod_whitelist: ...
ae0ca3d7b04d3c5c5de07eed4b185556a92e1763
46,031
def urldecode(str): """ >>> print(urldecode("%E4%BD%A0%E5%A5%BD")) 你好 """ return unquote(str)
57d37690f4f12c2ca6ffd390de5e91b72d269897
46,032
def distance_uv(uv1, uv2): """ [cmds] UV 2 点間の距離を返す Args: p1 (list[float, float]): cmds の UV コンポーネント文字列 p2 (list[float, float]): cmds の UV コンポーネント文字列 Returns: float: 二次元座標の距離 """ uvCoord1 = cmds.polyEditUV(uv1, query=True) uvCoord2 = cmds.polyEditUV(uv2, query=True) ...
84c48ca8af1137b749bb9d224a8ab928afa4705f
46,033
from typing import Union from typing import Optional from typing import Dict from typing import Any from typing import List from typing import Tuple def apply(log: Union[EventLog, pd.DataFrame], parameters: Optional[Dict[Any, Any]] = None) -> List[ Tuple[Tuple[str, str], int, Dict[str, Any]]]: """ Provide...
91c4297bb07f0bdd40a3f998746d625d8ef1a5d3
46,034
def check_trading_day(df_indices, date): """ The function return the next trading day. Parameters: df_indices: List of trading days in the whole dataset date: The prediction day Returns: date: The next trading day """ while (True): if (date in df_indices): ...
d411bad3540c2a5501ee4f7028b2afc6969c69e0
46,035
import random import fractions def coPrime(x): """ Finds a random co-prime of given number """ n = x * 2 + 100000 # Upper limit for range of random integers y = random.randint(x * 2, n) if (fractions.gcd(x, y) != 1): return coPrime(x) else: return y
336a49b7fcb4d9659b404d09618fae783f14212c
46,036
def create_task_id(prefix): """ Create random task-id """ return "{prefix}-{id}".format(prefix=prefix, id=random_hex(6))
6dae23e5056351ba38f2b3c90b3f38329b05e6f7
46,037
def feh_calc(theta, V, EW, power): """Calculate the metallicity for a given magnitude and EW.""" a, b, c, d, e = theta # Wdash = reduced_ew(theta, V, EW) FeH = a + b*V + c*EW + d*EW**power + e*V*EW # FeH = d + f*np.power(Wdash, 1) + g*np.power(Wdash, 2) return FeH
9591aa54d077579c3d7c625615c2beb7758b4402
46,038
def metadata_parser(f): """ Parses a metadata file into dictionary. The metadata file is expected to have the following format: id;name;dtype where: - id denotes packet id (unsigned char or 1 byte uint) - name is the data channel name (str) - dtype is expected datatype (str) :param f: A file object with th...
91ccec2a0231f35e0693173e67bfda5498f941f5
46,039
import logging def _GetValueAndSource(sim, control, name, sources): """Returns value of specified telemetry 'name' and 'source'. Arguments: sim: Simulator telemetry dictionary. control: Controller telemetry dictionary. name: [string] Telemetry variable e.g. 'airspeed' or 'alpha'. sources: [list o...
6f7beb63bdd45d937584dc07e02452a53af94750
46,040
def _clean_sub_graphs(G_, min_length=80, max_nodes_to_skip=100, weight='length', verbose=True, super_verbose=False): """ Remove subgraphs with a max path length less than min_length, if the subgraph has more than max_noxes_to_skip, don't check length (this ...
6915596934cf20598cf424a49f400be974ce5e0d
46,041
def transform(*args): """ Transform XML document(s) using XSLT. `*args` contain string commands and/or options in the following format: [<options>] <xsl-file> {-p|-s <name>=<value>} [<xml-file>...] where <xsl-file> - main XSLT stylesheet for transformation <xml-file> - input...
c438746302fab6c7f997624fec0656c3605fe521
46,042
from typing import Union from typing import Mapping import hmac import hashlib def decode(secret: Union[str, bytes], token: Union[str, bytes]) -> Mapping: """Decode JWT.""" if isinstance(secret, str): secret = secret.encode() if isinstance(token, str): token = token.encode() try: ...
e8e1da5f797855b95b3ed3ed1d8cd3de376b134a
46,043
def bencode(data, f=None): """ Writes a serializable data piece to f The order of tests is nonarbitrary, as strings and mappings are iterable. If f is None, it writes to a byte buffer and returns a bytestring """ if f is None: f = BytesIO() _bencode_to_file(data, f) return f.getvalue() else: _bencode...
42edad06af3aba85752a1b2edd569f1349fd3ac0
46,044
def Mean0(a): """ Replacing np.mean(a, axis = 0) for 2D arrays Parameters ---------- a : 2D numpy array, floats Returns ------- average : 1D numpy array, floats Averages over the columns of a. """ average = np.zeros(a.shape[1]) for col in range(a.shape[1]): ...
7a3b1620a8dc481613d655a5716e11fac5954c69
46,045
import zipfile import time def download_burst(): """Returns an html table with the burst retrieved from the DB. """ images_path = "server/data/bursts" burst_id = int(request.args.get('burstId')) burst_format = request.args.get('format') burst = DB.get_burst(burst_id) files = int(burst['dur...
9a9c41c08083f725d5c80efff2a2a304248f806e
46,046
async def delete_order(request: web.Request, order_id) -> web.Response: """Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors :param order_id: ID of the order that needs to be deleted :type order_id: str ...
e77b8197feb05094665c54501f5824d284c7612b
46,047
def fio_json_output_with_error(fio_json_output): """ Example of fio --output-format=json output, with io_u error. Based on actual test run. """ err_line = ( "fio: io_u error on file /mnt/target/simple-write.0.0: " "No space left on device: write offset=90280222720, buflen=4096" )...
babfcd242a47091dc9b8acd29f24b6ebb398c679
46,048
def supprimeExtension(str): """ Fonction qui supprime l'extension de notre str param : str : string -> chaine de caractere qu'on souhaite supprimer l'extension. return string : chaine de caractere sans extenstion """ #appliquer cette fonction avant supprimePonctuation return "".join(str.spl...
63dda5c2987121f537501bddb4076aa432fbf51e
46,049
def has_equal_properties(obj, property_dict): """ Returns True if the given object has the properties indicated by the keys of the given dict, and the values of those properties match the values of the dict """ for field, value in property_dict.items(): try: if getattr(obj, field...
d96b17124121af5db31c9db096b5010aff01b233
46,050
def outerproduct(tensor1: BlockSparseTensor, tensor2: BlockSparseTensor) -> BlockSparseTensor: """ Compute the outer product of two `BlockSparseTensor`. The first `tensor1.ndim` indices of the resulting tensor are the indices of `tensor1`, the last `tensor2.ndim` indices are those of `tensor...
d19ef9a5d6fbb3d5c9f03a481ca02c48717833e9
46,051
def niriss_header(ra=53.1592277508136, dec=-27.782056346146, pa_aper=128.589, filter='F150W', grism='GR150R'): """Make JWST/NIRISS image header Parameters ---------- ra, dec : float, float Coordinates of the center of the image pa_aper : float Position angle of th...
09630a85ce3c1ec7cd437b3fd35d8daa0b7110ed
46,052
def validate_twilio_request(f): """Validates that incoming requests genuinely originated from Twilio""" # Adapted from https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-flask-app-by-validating-incoming-twilio-requests?code-sample=code-custom-decorator-for-flask-apps-to-validate-twilio-requests-3&c...
fa1d309e7e3b224e36a5a356d68ae0b2720475d4
46,053
import os def get_path_components(path): """ http://stackoverflow.com/questions/3167154/how-to-split-a-dos-path-into-its-components-in-python """ folders = [] while True: path, folder = os.path.split(path) if folder != "": folders.append(folder) else: ...
b91cb85af3097935028c94fdc354b6712e615ca4
46,054
def is_api(auth_entry): """Returns whether the auth entry point is via an API call.""" return (auth_entry == AUTH_ENTRY_LOGIN_API) or (auth_entry == AUTH_ENTRY_REGISTER_API)
27c4cec6294cc3d4fda4c7b801d2fc5b99724ae5
46,055
import numpy def calcROC(output, LTE): """Uses shogun functions to calculate the area under the ROC curve""" pm = PerformanceMeasures(Labels(numpy.array(LTE)), Labels(numpy.array(output))) auROC = pm.get_auROC() return auROC
6485ab7654e1f65eebae4d9b0043630d356966b2
46,056
def _GetCoveredBuilders(trybot_config): """Returns a dict mapping masters to lists of builders covered in config.""" covered_builders = {} for master, builders in trybot_config.iteritems(): covered_builders[master] = builders.keys() return covered_builders
e759be62c1c57045dca98e40f83beda6a7ddf7e5
46,057
import collections def _load_vocabulary(filename): """Loads a vocabulary file. Args: filename: Path to text file containing newline-separated words. Returns: vocab: A dictionary mapping word to word id. """ tf.logging.info("Reading vocabulary from %s", filename) vocab = collections.OrderedDict()...
bd4bca7cede67e43bcbfea39deb7392b85701ed0
46,058
def get_all_names(): """ Return a dictionary of all names, indexed by index. """ keys = get_singleton(create=False) if keys is None: return {} entries = keys.attr('entries') result = {} for entry in entries: idx = entry.index() result[idx] = entry.attr('name...
495c8dfcf2b7416be4a0f8dcf5bc28f62ecfd873
46,059
def format_power(power): """ Converts a value for a power (which may be floating point or a `fractions.Fraction` object), into a string either looking like an integer or a fraction. """ if not isinstance(power, Fraction): if power % 1.0 != 0.0: frac = Fraction.from_float(powe...
9bc7c914d979a9d2f38b7de65de773699ff4497e
46,060
def _aggregate_neighbors(estimator, neigh_Y, neigh_weights): """Aggregate the nearest neighbors rankings according to the weights.""" aggregate = estimator._rank_algorithm.aggregate neigh_data = zip(neigh_Y, neigh_weights) Y = [aggregate(Y, sample_weight) for Y, sample_weight in neigh_data] return...
763168c7d78a2d918109b017781b44cca6c6e78e
46,061
import time def float_scalar(size=DEF_MATRIX, rep=DEF_REP): """ Returns the execution time of performing the sum of a random number to each element of a random real matrix. Parameters ---------- size : int The dimension of the square matrix that will be used in...
99e24af45a64d8d3b98df23cc87c1dfb4b1163ea
46,062
from pkg_resources import iter_entry_points import copy import configparser import os def project(opts): """Update user options with the options of an existing PyScaffold project Params: opts (dict): options of the project Returns: dict: options with updated values Raises: :...
5bc7b8d40c9ee64eefb2db81d201c2458ce4af21
46,063
def xr_ds_ex(decode_times=True, nyrs=3, var_const=True): """return an example xarray.Dataset object, useful for testing functions""" # set up values for Dataset, 4 yrs of analytic monthly values days_1yr = np.array([31.0, 28.0, 31.0, 30.0, 31.0, 30.0, 31.0, 31.0, 30.0, 31.0, 30.0, 31.0]) time_edges = n...
fd06fa2fc5816b44c04804a41f595aad15d34d82
46,064
def evaluate(gold, pred): """ Produce CoNLL 2005 SRL evaluation results for a provided sentences given as lists of tags, with the first list being a list of targets. For example, [['-', 'love', '-'], ['(A0*)', '(V*)', '(A1*)']]. :param gold: gold labels :param pred: predicted labels :return: SRL...
b968c362bf8a8f743c77e290341a653a5dcfe375
46,065
import os from typing import OrderedDict def posix_times(space): """ posix_times - Get process times """ utime, stime, cu_time, cs_time, rtime = os.times() rdct_w = OrderedDict() rdct_w['ticks'] = space.newint(int(rtime)) rdct_w['utime'] = space.newint(int(utime)) rdct_w['stime'] = space.newin...
7d24fe5c5c3606182b7e687e4616924cdaa3a4d3
46,066
def setup_platform(opp, config, add_entities, discovery_info=None): """Set up the Pushbullet Sensor platform.""" try: pushbullet = PushBullet(config.get(CONF_API_KEY)) except InvalidKeyError: _LOGGER.error("Wrong API key for Pushbullet supplied") return False pbprovider = PushB...
0e782e48e09b9d6ace51359a7fcfb77e455d7071
46,067
def decode_from_bioes(tags): """ Decode from a sequence of BIOES tags, assuming default tag is 'O'. Args: tags: a list of BIOES tags Returns: A list of dict with start_idx, end_idx, and type values. """ res = [] ent_idxs = [] cur_type = None def flush(): ...
0308b2e0e527a03a2e2168143fb6b022c3a19496
46,068
def getMaxVoltCurr(ser): """Get the maximum voltage and current from the supply. The response is an array: [0] = voltage, [1] = current""" resp = spdQuery(ser, "GMAX\r") print(resp) return [int(resp[0][0:3])/10., int(resp[0][3:5])/10.]
27c9b70118477d8c60eb0fe245ef3a73ed1782bd
46,069
import os def with_data(request, new_package): """Builds a python package which includes data files.""" new_module, pkg_root = new_package data_dir = os.path.join(pkg_root, "data") os.mkdir(data_dir) write_py(data_dir, "data_1", data=True) with open(os.path.join(new_module, META_NAME), "w")...
940a092c04afcadcb9bade5fc7859612c44ad589
46,070
from datetime import datetime from typing import Union def datetime_x_days_ago_at_y_oclock( tz_aware_original_time: datetime, x: int, y: Union[int, float], z: str ) -> datetime: """Returns the datetime x days ago a y o'clock as determined from the perspective of timezone z.""" if isinstance(y, float): ...
cd0b13b2c3d219c549a4c8415232546fdaf87499
46,071
from datetime import datetime def timedelta2str(time_delta: timedelta) -> str: """Convert a timedelta object to its DICOM string counterpart. Parameters ---------- time_delta : timedelta The timedelta object to convert to string. Returns ------- str The timdelta objected ...
1e2e12fe833e2a2968c051c919300c366d655bcf
46,072
def getServiceForQS(query_str): """URI ends is followed by HTTP version (space-delimited) """ query_params = parse_qs(query_str) if ('s' in query_params): return query_params['s'][-1] eprint('HTTP request captured, but no service in URI. attributing data to _unspecified.') return '_unspeci...
6e9bd10f2c1ba618e2c3b180fef583069e5e9214
46,073
from typing import Callable def lazy_property(func: Callable) -> Callable: """ Decorator that makes a property lazy-evaluated. Inspired by: https://stevenloria.com/lazy-properties. Arguments: func: The function to be decorated as a lazy @property. Returns: Callable: The decorated ...
1633bf51cd32a1f4851aa17fd7da20fd79e0d921
46,074
def cancel_order(order_id): """ :param order_id: :return: """ params = {} url = "/v1/order/orders/{0}/submitcancel".format(order_id) return api_key_post(params, url)
6ae1ec7673e4cc153c06d4bb2d077c8c2b4313e1
46,075
def create(): """Create a new post for the current user.""" if request.method == "POST": group = request.form["group"] name = request.form["name"] rating = request.form["rating"] trigger = request.form["trigger"] error = None if not name: error = "Nam...
bc73b21357d9d3fd1dd08d81781bc0c6698ca4fe
46,076
from typing import Optional def get_ssl_cipher_suite(load_balancer_id: Optional[str] = None, name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSslCipherSuiteResult: """ This data source provides details about a specific Ss...
ca52b18977c883c39ed3389ac35f7cf85b03df58
46,077
def plot_cospectra(cosp, freqs, ylabels=None, title='Cospectra'): """Plot cospectral matrices Parameters ---------- cosp : ndarray, shape (n_freqs, n_channels, n_channels) ndarray of cospectra. freqs : ndarray, shape (n_freqs,) The frequencies associated to cospectra. Returns ...
e0e62401c26677f1f7596744de93f3715fefdd48
46,078
import logging import calendar import sys def get_timestamps(etree_xml): """Parse SAML assertion validity timestamps Timestamps are parsed from Conditions element and converted to Unix timestamps. :param etree_xml: etree element object :return: NotBefore, NotOnOrAfter """ logger = loggi...
5af3570832dc5d3e1cf8942ad021759e76f45e22
46,079
def update_account(admin_id, root, service_name, data): """Method to update the account for given storage service. Args: admin_id (str): Root privileges flag. root (str): Root privileges activation flag. service_name (str): The...
a975f01481cc621a787bd2d4688c8034820c87a8
46,080
import threading import traceback import functools def _invoke_on_executor_thread(func, thread_name, block=True): """ Return wrapper to run the function on a given thread. If block==False, the call returns immediately without waiting for the decorated function to complete. If block==True, the call wa...
5756a6daac380e374be8fa838cef6092df4b5652
46,081
def Distance(distance='euclidean', **kwargs): """Construct a factory function that produces Distance nodes. Parameters ---------- distance : str, callable Specifies the distance function to use (See elfi.Distance). **kwargs Any additional arguments to elfi.Distance. Returns ---...
ac788acb2fd1332b70269fc95d461eab4facf34b
46,082
def generate_body(du_dept_dict): """Return HTML that will be used for the body content of the box report BlogPage""" body = '<ul>' for item in du_dept_dict.items(): body += '<li>{}: {} GB</li>'.format(item[0], int(item[1]) / 1000000) # Convert to GB body += '</ul>' return body
66e67abb1870440106ee6914b2110d29fcc3e1cd
46,083
def file_handler_test_file() -> FileHandler: """Fixture returns FileHandler instance. FileHandler is constructed from test xlsx file in input_for_tests directory. Returns: :obj:`FileHandler`: Instantiated with actual Excel doc. """ file_handler_test_file = FileHandler( "input_f...
c366e06ddba2ebea22e3c5e732aea1bcef0a60cd
46,084
import warnings import six import pickle def load_dygraph(model_path, keep_name_table=False): """ To load python2 saved models in python3. """ try: para_dict, opti_dict = fluid.load_dygraph(model_path, keep_name_table) return para_dict, opti_dict except UnicodeDecodeError: ...
1a3cf84ab2fbf48db61160fadf08628ebbc84045
46,085
import timeit import wbia.plottool as pt import wbia.plottool as pt def timeit_grid( stmt_list, setup='', iterations=10000, input_sizes=None, verbose=True, show=False ): """ Timeit: >>> import utool as ut >>> setup = ut.codeblock( >>> ''' >>> import utool as ut ...
6c8ac55f49ba259fe0b92658f7d138b44c1faade
46,086
def get_profiles() -> dict: """Returns the profiles of all players. Returns ------- dict profiles of the players """ with OpenJson(PLAYERS_DATA_PATH + "profiles.json") as profiles_file: profiles = profiles_file.load() return profiles
f57664ea1d4956b1e4cfd79a4a0b154d2ad02d4b
46,087
def calculate_check_digit(data): """Calculate MRZ check digits for data. :data data: Data to calculate the check digit of :returns: check digit """ values = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "<": 0, "A": 10, "B": 11, "C": 12, "...
f2ebef63d8ee0f050ecaec6aa338a0ca6c4af237
46,088
def flatten(root): """Flatten a hierarchical YAML dictionary into one with composite keys. Args: root: [dict] A hierarchical dictionary. Returns: Equivalent dictionary with '.'-delimited keys. """ result = {} __flatten_into(root, '', result) return result
30a1ec62dd571973c70c6739e287c3e358c96907
46,089
def lookup(cubeWithData, cubeWithMap, sharedIndex): """ Returns the value of cubeWithData indexed by the index of cubeWithMap. cubeWithData must be indexed by sharedIndex and cubeWithData values must correspond to elements of sharedIndex. For example: Let's say you have a cube with an estimated inflati...
979e4c3be85be484d1deb3ef48b78dae9f0527cf
46,090
from re import X def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ # if someone has won the game, utility will be 1 or -1 according to who won # X wins --> utility = 1 # O wins --> utility = -1 if is_over(board): if winner(board) == X: ...
028e42f32fae39fff2e4e291caf6d708cb7b891f
46,091
def notimplemented(f): """Takes a function f with a docstring and replaces it with a function which raises NotImplementedError(f.__doc__). Useful to avoid having to retype docstrings on methods designed to be overridden elsewhere.""" def wrapper(self,*args,**kws): raise NotImplementedErro...
eefdee57d0ebb0727e9238bc7f678d90b36100a6
46,092
import random import pipes def make_become_cmd(cmd, user, shell, method, flags=None, exe=None): """ helper function for connection plugins to create privilege escalation commands """ randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32)) success_key = 'BECOME-SUCCESS-%s' ...
1e71ac1f4596688e76723634c05e996aaea51194
46,093
from .services import set_led_colour, set_target_temp, set_mug_name from typing import Callable from typing import Optional async def async_setup_platform( hass: HomeAssistantType, config: ConfigType, async_add_entities: Callable, discovery_info: Optional[DiscoveryInfoType] = None, ) -> bool: """A...
0d472201fd13de98c547a81b5e9808d1900b2a84
46,094
import os def _get_configuration(project_dir, args): """ Get the final configuration to use. This merges the defaults, file configuration if present, and command line arguments, in that order of priority. """ # Start with the default configuration config = _default_configuration() #...
d5d63417be19cab4b0ff66a86df58a46bc89b4c0
46,095
def readFileBytes(path) -> bytes: """ 读取文件字节数据 :param path: 文件路径 :return: 字节数组 """ with openReadBytesFile(path) as f: return f.read()
e923bcd27ef73ce7ce3620009bdeadefc33589e3
46,096
def check_if_list_and_matches_length( param: "object", expected_length: int, name: str = "parameter" ) -> list: """ Checks, if the passed variable is a list. Otherwise creates a list of the variable of length expected_length. Then checks if the length of the list is the expected length. Arg...
5579acc4ea82a60293da847b8d4e612246845808
46,097
def evaluatePortfolioRet(Rev_seq,t=12): """ @param Rev_seq: @param t:天数 默认12(月) 252 日 @return: """ ret_mean=e**(Rev_seq.apply(lambda x:np.log(x+1)).mean()*t)-1 ret_sharpe=Rev_seq.mean()*t/Rev_seq.std()/t**0.5 ret_winrate=Rev_seq[Rev_seq>0].count()/Rev_seq.count() ret_maxloss=maxDrawD...
f6072fade66b5abc4dff507adcc414672a559f35
46,098
def subs(exp, *s): """ Substitute the given subexpressions in the expression. """ if isinstance(exp, Expression): return exp.subs(*s) return exp
dfbb463ebb3a43355f6325de7a281951c74cc200
46,099