content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List import subprocess def run_bincapture(args: List[str]) -> bytes: """run is like "subprocess.run(args, capture_out=True, text=False)", but with helpful settings and obeys "with capture_output(out)". """ if _capturing: try: return subprocess.run(args, check=Tru...
61495c2be378f81fc9165b29a0c12c8d1b6c5d6c
3,653,200
def _EnumValFromText(fdesc, enum_text_val, log): """Convert text version of enum to integer value. Args: fdesc: field descriptor containing the text -> int mapping. enum_text_val: text to convert. log: logger obj Returns: integer value of enum text. """ log.debug("converting enum val:" + enum...
af923a2cf65a81914ebeab85de779f1502a2d943
3,653,201
def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) # print('correct shape:', corre...
a5b2c3d97c839e0ae9954ce48889d5b46966b3cb
3,653,202
def yyyydoy2jd(year,doy,hh=0,mm=0,ss=0.0): """ yyyydoy2jd Take a year, day-of-year, etc and convert it into a julian day Usage: jd = yyyydoy2jd(year,doy,hh,mm,ss) Input: year - 4 digit integer doy - 3 digit, or less integer, (1 <= doy <= 366) hh - 2 digit, or less int, (0 ...
7e0579197146435d4c3e5031de962b758555846f
3,653,203
def lon2index(lon, coords, corr=True): """convert longitude to index for OpenDAP request""" if corr: if lon < 0: lon += 360 lons = coords.lon.values return np.argmin(np.abs(lons - lon))
3fd3571ab221533708c32c9e28293a90ee9f30cd
3,653,204
def get_dynamic_call_address(ea): """Find all dynamic calls e.g call eax""" dism_addr_list = list(FuncItems(ea)) return [addr for addr in dism_addr_list if print_insn_mnem(addr) == 'call' and get_operand_type(addr, 0)==1]
1f4d0eb3bcfdf0728d12efdfd151246f0497c8dd
3,653,205
def iwbo_nats(model, x, k, kbs=None): """Compute the IWBO in nats.""" if kbs: return - iwbo_batched(model, x, k, kbs).mean() else: return - iwbo(model, x, k).mean()
5620e60710e6c25804d66f4c668f4670e033fdbe
3,653,206
def ko_json(queryset, field_names=None, name=None, safe=False): """ Given a QuerySet, return just the serialized representation based on the knockout_fields. Useful for middleware/APIs. Convenience method around ko_data. """ return ko_data(queryset, field_names, name, safe, return_json=True)
25d3b433ffec6eb4e6bb8c0d39a9080692dee4f2
3,653,207
def map(video_features_path, audio_hypothesis, file_uri, ier=False): """Maps outputs of pyannote.audio and pyannote.video models Parameters: ----------- video_features_path: str Path to the video features (.npy) file as defined in pyannote.video audio_hypothesis: Annotation hypothes...
1dbccac4e27378d92f03503e6e672937bde958da
3,653,208
def delete_demo(guid): """ Delete a demo object and all its children. :param guid: The demo's guid :return: """ web_utils.check_null_input((guid, 'demo to delete')) demo_service.delete_demo_by_guid(guid) return '', 204
eb0a205e4279003a99159b2aeb4b8caefd47c2be
3,653,209
def return_json(): """ Sample function that has been given a different name """ print("Tooler should render out the JSON value returned") return {"one": 1, "deep": {"structure": ["example"]}}
bf28fab61cabfc3a4f30736e58490d5df6702dc2
3,653,210
def get(url) -> str: """Send an http GET request. :param str url: The URL to perform the GET request for. :rtype: str :returns: UTF-8 encoded string of response """ return _execute_request(url).read().decode("utf-8")
2f0b6ed542f75f83478f672ef1f39f192dddbf66
3,653,211
import logging import random def brute_force(durs, labels, labelset, train_dur, val_dur, test_dur, max_iter=5000): """finds indices that split (labels, durations) tuples into training, test, and validation sets of specified durations, with the set of unique labels in each dataset equal to the specified la...
553463746d6c330c833189f070bd66b0c748f75a
3,653,212
from typing import Optional from typing import Dict import os def VOLUME(env: Optional[Dict] = None) -> Dict: """Get specification for the volume that is associated with the worker that is used to execute the main algorithm step. Parameters ---------- env: dict, default=None Optional envi...
2ae5d5e6b0f9eb2800498ce9734f0f45dc368be3
3,653,213
def train_step(model_optimizer, game_board_log, predicted_action_log, action_result_log): """Run one training step.""" def loss_fn(model_params): logits = PolicyGradient().apply({'params': model_params}, game_board_log) loss = compute_loss(logits, predicted_action_log, action_result_log) ...
628742cb6d2fe19d25b5e283c7bec6f5189fc7b5
3,653,214
def make_static_rnn_with_control_flow_v2_tests(options): """Make a set of tests to do basic Lstm cell.""" test_parameters = [ { "dtype": [tf.float32], "num_batches": [4], "time_step_size": [4], "input_vec_size": [3], "num_cells": [4], "use_sequence_...
aa29c5eddab46624c36be29ee9ce1e6a83efbd7a
3,653,215
def jaccard(structured_phrases, phrases_to_score, partial=False, status_callback=None, status_increment=None, pmd_class=PartialMatchDict): """ calculate jaccard similarity between phrases_to_score, using structured_phrases to determine cooccurrences. For phrases `a' and `b', let A be the set of documents `a...
c7af246028f59b2375974390f337063d740d2f53
3,653,216
import ast def print_python(node: AST) -> str: """Takes an AST and produces a string containing a human-readable Python expression that builds the AST node.""" return black.format_str(ast.dump(node), mode=black.FileMode())
06281c4622d2b13008c17763bb59f93dfc44527c
3,653,217
def reg2deg(reg): """ Converts phase register values into degrees. :param cycles: Re-formatted number of degrees :type cycles: int :return: Number of degrees :rtype: float """ return reg*360/2**32
c7dbd6119ad3bce9261fb3d78a369251ade2d8af
3,653,218
from typing import Union def flag_element(uid: int, reason: Union[key_duplicate, key_optimization, ReviewDeleteReasons], db_user: User, is_argument: bool, ui_locales: str, extra_uid=None) -> dict: """ Flags an given argument based on the reason which was sent by the author. This argument will...
d36a36e4d4f106e6a072884da3588bad0642302b
3,653,219
import os def export_bioimageio_model(checkpoint, export_folder, input_data=None, dependencies=None, name=None, description=None, authors=None, tags=None, license=None, documentation=None, covers=None, ...
8dbbbe8fea06f98566c46e3eba810dbfcbcdec88
3,653,220
import pathlib def load_config_at_path(path: Pathy) -> Dynaconf: """Load config at exact path Args: path: path to config file Returns: dict: config dict """ path = pathlib.Path(path) if path.exists() and path.is_file(): options = DYNACONF_OPTIONS.copy() option...
da5cc4b830ad3a50ec6713bb509d3db0862963bf
3,653,221
def _build_target(action, original_target, plugin, context): """Augment dictionary of target attributes for policy engine. This routine adds to the dictionary attributes belonging to the "parent" resource of the targeted one. """ target = original_target.copy() resource, _w = _get_resource_and_...
e3c62944d7083ee96ad510fff0807db50aed9602
3,653,222
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry): """Configure Gammu state machine.""" device = entry.data[CONF_DEVICE] config = {"Device": device, "Connection": "at"} gateway = await create_sms_gateway(config, opp) if not gateway: return False opp.data[DOMAIN][SMS_GA...
c0a14f2a92d06e814728ff0ceed05bff17acb66a
3,653,223
def grep_response_body(regex_name, regex, owtf_transaction): """Grep response body :param regex_name: Regex name :type regex_name: `str` :param regex: Regex :type regex: :param owtf_transaction: OWTF transaction :type owtf_transaction: :return: Output :rtype: `dict` """ retu...
b5e9899675a63fe9ede9a9cf612b2004d52bb364
3,653,224
def link(f, search_range, pos_columns=None, t_column='frame', verbose=True, **kwargs): """ link(f, search_range, pos_columns=None, t_column='frame', memory=0, predictor=None, adaptive_stop=None, adaptive_step=0.95, neighbor_strategy=None, link_strategy=None, dist_func=None, to_eucl=None)...
425f7ffe9bcda4700bc77e74c2e956f27f22d521
3,653,225
def get_classifier(opt, input_dim): """ Return a tuple with the ML classifier to be used and its hyperparameter options (in dict format).""" if opt == 'RF': ml_algo = RandomForestClassifier hyperparams = { 'n_estimators': [100], 'max_depth': [None, 10, 30, 50, 100...
a522cab05958023dd4239e4ec2b136d2510aec1b
3,653,226
def list_spiders_endpoint(): """It returns a list of spiders available in the SPIDER_SETTINGS dict .. version 0.4.0: endpoint returns the spidername and endpoint to run the spider from """ spiders = {} for item in app.config['SPIDER_SETTINGS']: spiders[item['endpoint']] = 'URL: ' + ...
71e7448a621565b540c8ade1dae04d8ef88d5fd2
3,653,227
def plot3dOnFigure(ax, pixels, colors_rgb,axis_labels=list("RGB"), axis_limits=((0, 255), (0, 255), (0, 255))): """Plot pixels in 3D.""" # Set axis limits ax.set_xlim(*axis_limits[0]) ax.set_ylim(*axis_limits[1]) ax.set_zlim(*axis_limits[2]) # Set axis labels and sizes ax.tick_params(axis=...
067219abba7f77f7c4fbb4404ff16a3f5192f7cd
3,653,228
from typing import Optional from typing import Dict from typing import Any def _get_slice_predictions( model: ModelBridge, param_name: str, metric_name: str, generator_runs_dict: TNullableGeneratorRunsDict = None, relative: bool = False, density: int = 50, slice_values: Optional[Dict[str, ...
2c985b824b298ddaa29b44574b8399ad07746997
3,653,229
import numpy def ellipse(a, b, center=(0.0, 0.0), num=50): """Return the coordinates of an ellipse. Parameters ---------- a : float The semi-major axis of the ellipse. b : float The semi-minor axis of the ellipse. center : 2-tuple of floats, optional The position of th...
bd4d4663981a0431e40b20d38cc48a7f2476c13b
3,653,230
from typing import List import os import shutil def _copy_inputs(test_inputs: List[str], project_path: str) -> bool: """Copies all the test files into the test project directory.""" # The files are assumed to reside in the repo's 'data' directory. print(f'# Copying inputs (from "${{PWD}}/{_DATA_DIRECTORY...
b801c4a7f42b16b8e6428aaf0889df906d3692a2
3,653,231
import os def pinghost(host): """ Ping target with a 1-second timeout limit :param str host: Destination to reach. IP address or domain name :returns: True if reached, otherwise False """ host = str(host).split(':')[0] # leave off the port if exists # print "Pinging" if os.name == 'p...
f0e6d84edf1093580159d08359bfd61adeb3b987
3,653,232
from typing import List def get_trade_factors(name: str, mp: float, allow_zero: bool, long_open_values: List, long_close_values: List, short_open_values: List = None, short_close_values:...
14a7a8c0968e85f996e9c1e8f473be142c66759b
3,653,233
def mbstrlen(src): """Return the 'src' string (Multibytes ASCII string) length. :param src: the source string """ try: return len(src.decode("utf8", errors = "replace")) except Exception, err: LOG.error("String convert issue %s", err) return len(src)
8b2f64b2791eebf898d3bf8104d93d86dcdd53a3
3,653,234
def adapted_border_postprocessing(border_prediction, cell_prediction): """ :param border_prediction: :param cell_prediction: :return: """ prediction_border_bin = np.argmax(border_prediction, axis=-1) cell_prediction = cell_prediction > 0.5 seeds = border_prediction[:, :, 1] * (1 - bord...
4e74c1a71fb5c5f90d54735fa3af241461b48ebb
3,653,235
def calc_bonding_volume(rc_klab, dij_bar, rd_klab=None, reduction_ratio=0.25): """ Calculate the association site bonding volume matrix Dimensions of (ncomp, ncomp, nbeads, nbeads, nsite, nsite) Parameters ---------- rc_klab : numpy.ndarray This matrix of cutoff distances for associat...
cf154af6287286c19d606a2324c548f70f90121b
3,653,236
def scale_enum(anchor, scales): """Enumerate a set of anchors for each scale wrt an anchor. """ w_w, h_h, x_ctr, y_ctr = genwhctrs(anchor) w_s = w_w * scales h_s = h_h * scales anchors = makeanchors(w_s, h_s, x_ctr, y_ctr) return anchors
8de95fc6966133a74f10318f23e97babcb36d5cd
3,653,237
def L1(): """ Graph for computing 'L1'. """ graph = beamline(scatter=True) for node in ['scattered_beam', 'two_theta', 'L2', 'Ltotal']: del graph[node] return graph
1bd17365107740a41d88ac3825ef2aca412bb616
3,653,238
def _highlight_scoring( original_example, subset_adversarial_result, adversarial_span_dict ): """ Calculate the highlighting score using classification results of adversarial examples :param original_example: :param subset_adversarial_result: :param adversarial_span_dict: """ original_ut...
788f903fe471ef539fe337c79858c04468ae3137
3,653,239
def server_hello(cmd, response): """Test command """ return response
7e0cc03d1b64afb1a4fc44264096e6888ddb5df2
3,653,240
import os def applyRigidAlignment(outDir, refFile, inDataListSeg, inDataListImg=[], icp_iterations=200): """ This function takes in a filelists(binary and raw) and makes the size and spacing the same as the reference """ isoValue = 1e-20 antialias_iterations = 30 print("\n#########...
9f76afc4acad994aaa3f2ee57304401abfe27eaf
3,653,241
def test_vectorised_likelihood_not_vectorised_error(model, error): """ Assert the value is False if the likelihood is not vectorised and raises an error. """ def dummy_likelihood(x): if hasattr(x, '__len__'): raise error else: return np.log(np.random.rand()) ...
1968be0c2ba147147e2ea5d4443c8bc87050d218
3,653,242
def display_timestamps_pair(time_m_2): """Takes a list of the following form: [(a1, b1), (a2, b2), ...] and returns a string (a_mean+/-a_error, b_mean+/-b_error). """ if len(time_m_2) == 0: return '(empty)' time_m_2 = np.array(time_m_2) return '({}, {})'.format( display_timestam...
b8bb0fa727c087a6bc1761d55e55143a12693d1e
3,653,243
def get_legendre(degree, length): """ Producesthe Legendre polynomials of order `degree`. Parameters ---------- degree : int Highest order desired. length : int Number of samples of the polynomials. Returns ------- legendre : np.ndarray A `degree`*`l...
5f939c7d759678f6c686c84b074c4ac973df8255
3,653,244
import os def _get_table_names(): """Gets an alphabetically ordered list of table names from facet_fields.csv. Table names are fully qualified: <project id>:<dataset id>:<table name> """ config_path = os.path.join(app.app.config['DATASET_CONFIG_DIR'], 'bigquery.json') ...
3684fa80f52aa3a2d61c6843992976870ae2bd59
3,653,245
def _get_controller_of(pod): """Get a pod's controller's reference. This uses the pod's metadata, so there is no guarantee that the controller object reference returned actually corresponds to a controller object in the Kubernetes API. Args: - pod: kubernetes pod object Returns: the refe...
9c9e58e2fc49729c618af2c5bb9b4d033d90a831
3,653,246
from typing import Any from typing import Dict from typing import List def proxify_device_objects( obj: Any, proxied_id_to_proxy: Dict[int, ProxyObject], found_proxies: List[ProxyObject], ): """ Wrap device objects in ProxyObject Search through `obj` and wraps all CUDA device objects in ProxyObje...
6d410245624d2992e37b5bce1832d7326caf4fe2
3,653,247
def monotonicity(x, rounding_precision = 3): """Calculates monotonicity metric of a value of[0-1] for a given array.\nFor an array of length n, monotonicity is calculated as follows:\nmonotonicity=abs[(num. positive gradients)/(n-1)-(num. negative gradients)/(n-1)].""" n = x.shape[0] grad = np.gradient(x) ...
3ff9c37975502cb12b9e2839a5f5580412084f8c
3,653,248
import subprocess def get_cluster_cids(): """return list of CIDs with pin types""" output = subprocess.check_output([ 'docker-compose', 'exec', '-T', 'cluster', 'ipfs-cluster-ctl', 'pin', 'ls' ]) return [ '-'.join([l.split()[0], l.split()[-1].lower()]) for l in output.d...
c38e2742fa0476e2240d9759c6d8525a3add083b
3,653,249
import os import getpass def download(homework, version="latest", redownload=False): """Download data files for the specified datasets. Defaults to downloading latest version on server. Parameters: homework (str): The name of the dataset to download data for, or "all" to download data for all...
a866e80848caa53c7abee7a3074b28d8d56e32bf
3,653,250
import attrs def parse_value_namedobject(tt): """ <!ELEMENT VALUE.NAMEDOBJECT (CLASS | (INSTANCENAME, INSTANCE))> """ check_node(tt, 'VALUE.NAMEDOBJECT') k = kids(tt) if len(k) == 1: object = parse_class(k[0]) elif len(k) == 2: path = parse_instancename(kids(tt)[0]) ...
ecb507ac9b0c3fdfbec19f807fba06236e21d7c5
3,653,251
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload Dyson cloud.""" # Nothing needs clean up return True
38a274e90c5fadc277e640cd6cc5442d5070dfd6
3,653,252
def quat_correct(quat): """ Converts quaternion to minimize Euclidean distance from previous quaternion (wxyz order) """ for q in range(1, quat.shape[0]): if np.linalg.norm(quat[q-1] - quat[q], axis=0) > np.linalg.norm(quat[q-1] + quat[q], axis=0): quat[q] = -quat[q] return quat
fc492998c5bdf2cf3b1aacbd42de72618bd74c01
3,653,253
def vis_bbox(im, dets): """Visual debugging of detections.""" for i in range(dets.shape[0]): bbox = tuple(int(np.round(x)) for x in dets[i, :4]) # class_name = CLASS_NAME[int(dets[i, 4]) - 1] class_name = ' ' score = 0.99 cv2.rectangle(im, bbox[0:2], bbox[2:4], (0, 204, 0...
c9bd2edb899d2a476eaff9bbbf91f1008e9d1c33
3,653,254
def parse_record1(raw_record): """Parse raw record and return it as a set of unique symbols without \n""" return set(raw_record) - {"\n"}
4ffd3ebd0aaa17ddd42baf3b9d44614784c8ff33
3,653,255
def execute_contract_creation( laser_evm, contract_initialization_code, contract_name=None ) -> Account: """ Executes a contract creation transaction from all open states""" # TODO: Resolve circular import between .transaction and ..svm to import LaserEVM here open_states = laser_evm.open_states[:] ...
ef1f0db204554c874c3aeea1ca6aa89ef7454d89
3,653,256
import re def isValid(text): """ Returns True if the input is related to the meaning of life. Arguments: text -- user-input, typically transcribed speech """ return bool(re.search(r'\byour awesome\b', text, re.IGNORECASE))
c6e4275d53cd632b4f5e255aa62b69c80fd37794
3,653,257
def list_shared_with(uri, async_req=False): """Return array sharing policies""" (namespace, array_name) = split_uri(uri) api_instance = client.client.array_api try: return api_instance.get_array_sharing_policies( namespace=namespace, array=array_name, async_req=async_req ) ...
2a9eb78c14e5bdc31a3ae5bfc077219bd06c768f
3,653,258
import html def format_html_data_table(dataframe, list_of_malformed, addLineBreak=False): """ Returns the predicted values as the data table """ if list_of_malformed: list_of_malformed = str(list_of_malformed) else: list_of_malformed = "None" # format numeric data into string ...
cc345d2cb87ddf7905d0d9a62cc6cd61b92ddc51
3,653,259
import math def colorDistance(col1, col2): """Returns a number between 0 and root(3) stating how similar two colours are - distance in r,g,b, space. Only used to find names for things.""" return math.sqrt( (col1.red - col2.red)**2 + (col1.green - col2.green)**2 + (...
ef18dede8312f78b4ba4258e87d4630863f1243c
3,653,260
from typing import Iterable def combine_from_streaming(stream: Iterable[runtime_pb2.Tensor]) -> runtime_pb2.Tensor: """ Restore a result of split_into_chunks into a single serialized tensor """ stream = iter(stream) first_chunk = next(stream) serialized_tensor = runtime_pb2.Tensor() serialized_ten...
af88c9eeec99c1d3d7ca9e5753b72cf09a0c6c85
3,653,261
def portageq_envvar(options, out, err): """ return configuration defined variables. Use envvar2 instead, this will be removed. """ return env_var.function(options, out, err)
8406985ac5f5d5d4bc93ded8c1392b1fe49e9ff7
3,653,262
def create_hash_factory(hashfun, complex_types=False, universe_size=None): """Create a function to make hash functions :param hashfun: hash function to use :type hashfun: callable :param complex_types: whether hash function supports hashing of complex types, either through nat...
23dee13f06f754caa9f7de5a89b855adbe7313a4
3,653,263
def estimate_key(note_info, method="krumhansl", *args, **kwargs): """ Estimate key of a piece by comparing the pitch statistics of the note array to key profiles [2]_, [3]_. Parameters ---------- note_info : structured array, `Part` or `PerformedPart` Note information as a `Part` or `Pe...
af2383ab2a94cf49a93a1f00d5bf575f19e0daa0
3,653,264
def print_parsable_dstip(data, srcip, dstip): """Returns a parsable data line for the destination data. :param data: the data source :type data: dictionary :param scrip: the source ip :type srcip: string :param dstip: the destination ip :type dstip: string :return: a line of urls and their hitcount "...
9e27733a9821e184e53f21ca38af9cdb61192743
3,653,265
def OrListSelector(*selectors) -> pyrosetta.rosetta.core.select.residue_selector.OrResidueSelector: """ OrResidueSelector but 2+ (not a class, but returns a Or :param selectors: :return: """ sele = pyrosetta.rosetta.core.select.residue_selector.FalseResidueSelector() for subsele in selec...
8f4443a6ee1bbcd2e76133e6a08eea2737e01383
3,653,266
def plot_regress_exog(res, exog_idx, exog_name='', fig=None): """Plot regression results against one regressor. This plots four graphs in a 2 by 2 figure: 'endog versus exog', 'residuals versus exog', 'fitted versus exog' and 'fitted plus residual versus exog' Parameters ---------- res : r...
e4c7859c32892d2d8e94ff884652846f5f15f513
3,653,267
from typing import List def get_circles_with_admin_access(account_id: int) -> List[Circle]: """ SELECT management_style, c_name FROM ( SELECT 'SELF_ADMIN' AS management_style, c.management_style AS c_management_style, c.admin_circle A...
ef0a24d299bdad549f9b0220e4a34499097eb19d
3,653,268
def combine(arr): """ makes overlapping sequences 1 sequence """ def first(item): return item[0] def second(item): return item[1] if len(arr) == 0 or len(arr) == 1: return arr sarr = [] for c, val in enumerate(arr): sarr.append((val[0], val[1], c)) sarr = s...
b46bb7f73fa6857ed4c980bdbdff77acde64b18d
3,653,269
from operator import sub def sub_fft(f_fft, g_fft): """Substraction of two polynomials (FFT representation).""" return sub(f_fft, g_fft)
a559429a4d10889be3ffa776153854248ac7a496
3,653,270
def recursive_fill_fields(input, output): """ Fills fields from output with fields from input, with support for nested structures. Parameters ---------- input : ndarray Input array. output : ndarray Output array. Notes ----- * `output` should be at least the sam...
5508f1681eaa3f2c5ccb44b6329ad012f85c42e8
3,653,271
import sys def load_parameters(model_type, parameter_file): """ Loads in all parameter values given in a parameter file. Parameters: model_type (str): sets the type of model, which determines the exact parameter set that is needed. Possible values for the p...
6fe50dcb668104e0dfd9e7b9c483564b9c9e36cf
3,653,272
def handle_dat_edge(data_all): """ 把dat_edge个每一条记录的info拆开,然后输出,方便后续的计算 为了简化计算,忽略时间信息,把所有的月份的联系记录汇总起来 """ def cal_multi_3(string): s = string.split(',') month_times = len(s) df = list(map(lambda x: list(map(eval, x.split(':')[1].split('_'))), s)) times_sum, weight_sum ...
4ae92d337a70326bae87399809b920b1ad2cce1e
3,653,273
def quadraric_distortion_scale(distortion_coefficient, r_squared): """Calculates a quadratic distortion factor given squared radii. The distortion factor is 1.0 + `distortion_coefficient` * `r_squared`. When `distortion_coefficient` is negative (barrel distortion), the distorted radius is only monotonically in...
b8a910e4de3a6c0a3793131503ed6ede8836bc89
3,653,274
import subprocess import os def run(executable: str, *args: str): """ Run executable using core.process configuration, replacing bin with configured one, appending and prepending args. """ command_list = effective_command(executable, *args) process = subprocess.run(command_list, ...
4255a831d7d617a4f34e77c628b34b4851c8c58a
3,653,275
def open_path(path, **kwargs): """ Parameters ---------- path: str window: tuple e.g. ('1990-01-01','2030-01-01') kwargs: all other kwargs the particular file might take, see the module for details Returns ------- """ info = _tools.path2info(path) module = arm_prod...
c4e87d0649dfde2139a4ecac797775309eb6a72e
3,653,276
import uuid def generate_code() -> str: """Generates password reset code :return: Password reset code :rtype: str """ return str(uuid.uuid4())
bcd8377afd5598e71f8bb8eb217c3f3fd53fc5c7
3,653,277
import os def process_file(name, files, url): """ Save file to shared folder on server, and return the name of the file. """ def allowed_file(filename): if "." not in filename: return False ext = filename.rsplit(".", 1)[1].lower() return ext in config.ALLOWED_E...
0c054c53cb8b24b1e2ff5e684453000fbd11a5a2
3,653,278
def decode_auth_token(auth_token): """ Decodes the auth token :param auth_token: :return: integer|string """ try: payload = jwt.decode(auth_token, app.config.get('SECRET_KEY')) return payload['sub'] except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again.' except jwt...
16fceb539f7aafb775b851e55f1b606a1c917cf9
3,653,279
import pickle import os def cached(path: str, validate: bool = False): """Similar to ``define``, but cache to a file. :param path: the path of the cache file to use :param validate: if `True`, always execute the function. The loaded result will be passed to the function, when the ...
d4b5b861bf43294d3e5f84b57f648a2e32b6428b
3,653,280
import ast def json(*arguments): """ Transform *arguments parameters into JSON. """ return ast.Json(*arguments)
3e3333617b63dc1b5e8e4b71ea5c2f0ea08bfff8
3,653,281
def get_default_volume_size(): """ :returns int: the default volume size (in bytes) supported by the backend the acceptance tests are using. """ default_volume_size = environ.get("FLOCKER_ACCEPTANCE_DEFAULT_VOLUME_SIZE") if default_volume_size is None: raise SkipTest( "Se...
ec24bfb9c07add5d1a800a1aaf9db3efb8727b3d
3,653,282
import functools def set_global_user(**decorator_kwargs): """ Wrap a Flask blueprint view function to set the global user ``flask.g.user`` to an instance of ``CurrentUser``, according to the information from the JWT in the request headers. The validation will also set the current token. This ...
f73a89d94d188b1c258cedca3439ab9c1c94180c
3,653,283
def sample_wfreq(sample): """Return the Weekly Washing Frequency as a number.""" # `sample[3:]` strips the `BB_` prefix results = session.query(Samples_Metadata.WFREQ).\ filter(Samples_Metadata.SAMPLEID == sample[3:]).all() wfreq = np.ravel(results) # Return only the first integer value fo...
6cb2ee0866efc9e841143c32e10cbb8feea813bc
3,653,284
import sys import os from typing import OrderedDict import shutil import json import six def OffsiteRestore( source_dir, encryption_password=None, dir_substitution=None, display_only=False, ssd=False, output_stream=sys.stdout, preserve_ansi_escape_sequences=False, ): """\ Restores ...
6dbc3d047b83ba93763ee31e750e61b3400bc7d9
3,653,285
def mlp_hyperparameter_tuning(no_of_hidden_neurons, epoch, alpha, roh, n_iter_no_change, X_train, X_validation, y_train, y_validation): """ INPUT no_of_hidden_neurons: 1D int arary contains different values of no of neurons present in 1st hidden layer (hyperparameter) epoch: ...
3ec079bbeae32a5e7e6b80e833336ecb8662cbf1
3,653,286
def play(p1:list[int], p2:list[int]) -> list[int]: """Gets the final hand of the winning player""" while p1 and p2: a = p1.pop(0) b = p2.pop(0) if a > b: p1 += [a, b] else: p2 += [b, a] return p1 + p2
2a2b561474b3cd0841dcbe881e74b4767b4102b1
3,653,287
def oda_update_uhf(dFs, dDs, dE): """ ODA update: lbd = 0.5 - dE / E_deriv """ if type(dFs) is not list: raise Exception("arg1 and arg2 are list of alpha/beta matrices.") E_deriv = np.sum(dFs[0] * dDs[0] + dFs[1] * dDs[1]) lbd = 0.5 * (1. - dE / E_deriv) if lbd < 0 or lbd > 1...
fcead1536db11f80ae9eb2e912ac9857f93de669
3,653,288
def authorize(*roles): """Decorator that authorizes (or not) the current user Raises an exception if the current user does not have at least one of the listed roles. """ def wrapper(func): """wraps the protected function""" def authorize_and_call(*args, **kwargs): """che...
f3fd8eb42924f8f956d0e3eae1499f64387fe96e
3,653,289
import time import math def trunked_greedy_by_size_offset_calculation(usage_recorders, show_detail=False): """ An offset calculation algorithm designed for variable-length inputs. @ params: usage_recorders : tensor usage recoders (name, start_op, end_op, s...
87c782301a4534aaffacc6aaf47a1f9b88b4ee39
3,653,290
import base64 import itertools import six def decrypt(secret, ciphertext): """Given the first 16 bytes of splunk.secret, decrypt a Splunk password""" plaintext = None if ciphertext.startswith("$1$"): ciphertext = base64.b64decode(ciphertext[3:]) key = secret[:16] algorithm = algor...
d4b0caca50d649633bb973d26bb174875d23b0e0
3,653,291
from unet_core.vessel_analysis import VesselTree def load_skeleton(path): """ Load the skeleton from a pickle """ # Delayed import so script can be run with both Python 2 and 3 v = VesselTree() v.load_skeleton(path) return v.skeleton
d9632de40310dd738eb7d07966d6eb04360c3b81
3,653,292
def industries_hierarchy() -> pd.DataFrame: """Read the Dow Jones Industry hierarchy CSV file. Reads the Dow Jones Industry hierarchy CSV file and returns its content as a Pandas DataFrame. The root node has the fcode `indroot` and an empty parent. Returns ------- DataFrame : A Pandas Data...
9d1de27e3e01572637e7afc729e0cd07d96b14e2
3,653,293
def ready(): """ A readiness endpoint, checks on DB health too. :return: a 200 OK status if this server is up, and the backing DB is ready too; otherwise, a 503 "Temporarily unavailable." """ try: # TODO: Move to a DAO class client = get_mongo_client() info = {} ...
526dda4fc4bffecde573b1b26cf5b33dcbd66d09
3,653,294
import typing def setup_callback(callback: typing.Awaitable): """ This function is used to setup the callback. """ callback.is_guild = False """ The guild of the callback. """ callback.has_permissions = [] """ The permissions of the callback. """ callback.has_roles = [] """ ...
4cb7849d9746166c95c96d18e27227b52160ff7a
3,653,295
def prepare_for_training(ds, ds_name, conf, cache): """ Cache -> shuffle -> repeat -> augment -> batch -> prefetch """ AUTOTUNE = tf.data.experimental.AUTOTUNE # Resample dataset. NB: dataset is cached in resamler if conf["resample"] and 'train' in ds_name: ds = oversample(ds, ds_na...
b072a7ced028b1627288a3f2bbf0233c85afbab8
3,653,296
def residual3d(inp, is_training, relu_after=True, add_bn=True, name=None, reuse=None): """ 3d equivalent to 2d residual layer Args: inp (tensor[batch_size, d, h, w, channels]): is_training (tensor[bool]): relu_after (bool): add_bn (bool): add b...
28fb8651c9a9755e8d0636c702b2bd77e7186fd1
3,653,297
def marks(family, glyph): """ :param family: :param glyph: :return: True when glyph has at least one anchor """ has_mark_anchor = False for anchor in glyph.anchors: if anchor.name: if anchor.name.startswith("_"): has_mark_anchor = True brea...
101555dcadfd78b0550606f843e32dce99de62b8
3,653,298
import re def generate_bom(pcb_modules, config, extra_data): # type: (list, Config, dict) -> dict """ Generate BOM from pcb layout. :param pcb_modules: list of modules on the pcb :param config: Config object :param extra_data: Extra fields data :return: dict of BOM tables (qty, value, foot...
7645929bfcfd3d7447a32ae2ea3074d6da86c368
3,653,299