content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_test_image(): """Test image representing coordinate grid -------------------- | | | | | | | -------------------- | | | | | | | -------------------- | | | | | | | -------------------- | | | | | | | --------------...
54fcf5167aecbd131171d0dab8dac0bb4303f7d4
68,300
def next_missing_index(prefix, i): """ Determine netxt index that has not yet been downloaded """ while(index_exists(prefix, i)): i = i+1 return i
f0105c0d37bdf69e93af6d2fd41dd90f2d6b19f6
68,301
import os def get_dir(message="Select a directory"): """ DESCRIPTION: Spawns a GUI window to ask user for a directory INPUT: None OUTPUT: list of files spawns GUI file explorer window to choose data file EXAMPLE: file_list = getFolderList() :param message: Message to print in file dia...
2395969e382627b30564f20cdfa88fdd4f0932d2
68,302
import re def filename_from_name(name): """Shorten the name of a whatever to something suitable as a filename. e.g. Water's Edge -> waters-edge """ name = unicode(name) name = name.lower() name = re.sub(u'[ _]+', u'-', name) name = re.sub(u'[\'.()]', u'', name) return name
546239b3a0b8e0399d3d444bf528c55bcc3cea54
68,303
def get_total_balance(): """ Get total balance Returns: --------- Returns total balance of all accounts """ return sum(record['values']['balance'] for record in get_accounts())
d03a09ab27fc646ce3a68364fccfc0784d09ce26
68,304
def generate_mu_z(size=1000, z0=0.3, dmu_0=0.1, dmu_1=0.02, random_state=None, cosmo=None): """Generate a dataset of distance modulus vs redshift. Parameters ---------- size : int or tuple size of generated data z0 : float parameter in redshift distribution: ...
bda9f00784f1a16724a4482d504090446cd5061e
68,305
def compute_test_rates(): """Compute the exact rates to test HAL takes in integer rates values This function handles the floating point to integer issues """ test_rates = np.sort(list(BASE_RATES) + list(INTERMEDIATE_RATES)) print("Base rates:\n{}".format(BASE_RATES)) print("Intermediate...
25326962772b155c46a697c756ea6838fe4cbc39
68,306
def rsqrt(x): """Take reciprocal of square root of input x. Parameters ---------- x : PrimExpr Input argument. Returns ------- y : PrimExpr The result. """ return call_intrin(x.dtype, "tir.rsqrt", x)
de6b0756a232c8513832ec36d76531c076fb2805
68,307
def compile_device_info(host_name, node_name, mid, name) -> DeviceInfo: """Return Device Info of the Server.""" return DeviceInfo( # TODO - add SW version and such from https://pve.proxmox.com/pve-docs/api-viewer/#/version entry_type=DeviceEntryType.SERVICE, identifiers={ ("Domain"...
edda8983bfe8f4285beeca4b300b91b9227df37d
68,308
def convert_bxd_name(name: str) -> str: """ the names of BXDs are not consistent across all metadata and VCF files, so we sometimes have to convert their names >>> convert_bxd_name("4512-JFI-0469_BXD100_RwwJ_phased_possorted_bam") "BXD100_RwwJ_0469" >>> convert_bxd_name("4512-JFI-0410_BXD013_T...
577f936d81fdd7a87bd02fec069ff5f09e3b1412
68,309
from typing import Optional from typing import Any import functools import asyncio async def create_pool( settings_: RedisSettings = None, *, retry: int = 0, job_serializer: Optional[Serializer] = None, job_deserializer: Optional[Deserializer] = None, default_queue_name...
1248a0053bb9ccbe9961120d52a745add885f622
68,310
def ExactCover(grid, x, y): """ Calculates the Exact Cover for an element in the grid and returns all possible numbers. """ x_axis = get_x_axis_elements(grid[x]) y_axis = get_y_axis_elements(grid, y) BlockOfCoordinates = ReturnBlockOfCoordinates(x, y) block = set() steps = in...
ae8ef61ae32b976ff369641644538ab34b4c10e4
68,311
import torch def makeInp(inputs): """Move tensors onto GPU if available. Args: inputs: A dict with a batch of word-indexed data from DataLoader. Contains ['brk_sentence', 'bs_inp_lengths', 'style', 'sentence', 'st_inp_lengths', 'marker', 'mk_inp_lengths'] Returns: inputs: The dict with same structure but s...
af00b78f33627f45e505a6b8c75fb07ef29b94e6
68,312
def parse_uniprot_xml_metadata(sr): """Load relevant attributes and dbxrefs from a parsed UniProt XML file in a SeqRecord. Returns: dict: All parsed information """ # TODO: What about "reviewed" status? and EC number xref_dbs_to_keep = ['GO', 'KEGG', 'PDB', 'PROSITE', 'Pfam', 'RefSeq'] ...
ba61c15076e658d126fed4161c0319d27279576a
68,313
import torch def get_dataloader(data, config, train_idx, valid_idx): """ Only used during training """ data = Dataset(mode='train') # num_train = len(data) # indices = list(range(num_train)) # split = int(np.floor(valid_ratio * num_train)) # if shuffle: # np.random.seed(0) ...
a973081e2e8e360a6d18a1ae56de8458c0b59807
68,314
import html def parse_cbr_key_indicators(content: str): """ The function to parse USD, EUR and precious metals rates from CBR site """ root = html.fromstring(content) tables = root.xpath('//table')[:2] result = {} for table in tables: for row in table[0][1:]: key =...
34b3820706be413fcb9cf9b1f735bf5870d8cad9
68,315
from typing import Optional from typing import Dict import warnings import tqdm import time import os def knn( train_df: pd.DataFrame, test_df: pd.DataFrame, k: int = 1, approx: bool = False, seq_nns: int = 10, seq_nn_dict: Optional[Dict] = None, return_knn_labels: bool = False, verbos...
1bb2bfe85d9f3e83047ffcf54855645d61a046bf
68,316
def kl_divergence(p, q, regularizer=None): """ Returns a notion of "distance" between two probability distributions p and q. """ if regularizer is None: regularizer = lambda: 0 return -tl.sum(p * tl.log(q / p)) + regularizer()
85d2aae875a39321752e476d0cfb00d8571ea0a3
68,317
import warnings def rename_internal_nodes(tree, names=None, inplace=False): """ Names the internal according to level ordering. The tree will be traversed in level order (i.e. top-down, left to right). If `names` is not specified, the node with the smallest label (y0) will be located at the root of t...
d5df42023afe184af41d7553b2e1491b09d5edc1
68,318
def compare_score_file(df_res, df_res_ref): """ Compare df_res """ col_list = ["raw_score", "norm_score", "mc_pval", "pval"] for col in col_list: v_ = df_res[col].values v_ref = df_res_ref[col].values err_msg = "Inconsistent values: {}\n".format(col) err_msg += "|{:^...
e8fddbe5a019525ab86696d0be9e77c89e32e77f
68,319
def get_base64(cred=None, filename=CFG_FILENAME, api=None): """Return base64 encoded string.""" assert api credentials = _read_cfg( default_value=cred, filename=filename, key_to_read=api ) output = b64encode("{}".format(credentials).encode(encoding="ascii")) return output.decode("ascii")
8dd23a0c762348f116dc171ad8c1e0d884c90b6b
68,320
import requests import json def api(q, user): """ http://docs.ruyi.ai/344886 """ url = 'http://api.ruyi.ai/v1/message' params = { 'q': q.strip(), 'app_key': config.RUYI_API_KEY, 'user_id': user.id } try: r = sess.get(url, params=params) except requests.R...
fa2dc307d2d1df99e6ab236965bc663a3f017e32
68,321
def calc_iou(box_a, box_b): """Computes IoU of two axis aligned bboxes. Args: box_a, box_b: 6D of center and lengths Returns: iou """ max_a = box_a[3:6] max_b = box_b[3:6] min_max = np.array([max_a, max_b]).min(0) min_a = box_a[0:3] m...
541c0f681dfb1f62495ed78d06c588de2eedd0e0
68,322
def sub_cupydense(left, right): """ Perform the operation ``out := left - right`` Parameters ---------- left : CuPyDense Matrix to be added. right : CuPyDense Returns ------- out : CUPyDense """ _check_same_shape(left, right) return left - right
2dad4a44b0610ce0f89ee562a10606603224a5f5
68,323
def polyphase_filter_decimate(x, m, f): """Decimate x by m with filter taps f.""" return np.sum(polyphase_core(x, m, f), axis=0)
575da79126da7fadd90d0a4604ff2460793dc6d2
68,324
def headers(mime, length): """Returns a list of HTTP headers given the MIME type and the length of the content, in bytes (in integer or sting format).""" return [('Content-Type', mime), ('Content-Length', str(length))]
da5f73591bf9d4bbc8b1d01f4d6babf0de54ce00
68,325
def search_parser(lineno, line, syntax): """Finds a proper parser function for a given line or raises an error :param lineno: :param line: :type syntax: :class:`plim.syntax.BaseSyntax` """ for template, parser in syntax.parsers: matched = template.match(line) if matched: ...
5040a687e9fc7053dbba1b9d756040378ce5e704
68,326
def triangulate(A, order): """Convert linear array to 2-D array with triangular coefficient layout""" AT = sp.zeros((order + 1, order + 1)) k = 0 for i in range(order + 1): for j in range(i + 1): AT[i, j] = A[k] k += 1 return AT
d30bd30a4c9a39a07e722d586676d15b68b767cc
68,327
def generate_changes(dns_zone, action, data): """ Produces a change request (additions, deletions) with the specified data """ return dns_zone.discovery.changes().create( project=utils.get_gcp_config()['project'], managedZone=dns_zone.name, body={action: data})
d198b559db07a6b2f507ab898477effe432e79c0
68,328
def read_file_binary(filename: str) -> bytes: """Get the contents of a binary file contained with qutebrowser. Args: filename: The filename to open as string. Return: The file contents as a bytes object. """ path = _path(filename) with _keyerror_workaround(): return pat...
26bb04963a2e27e3abd3784860602a21cb42365c
68,329
import os def path_to_resources(): """ Returns the path to the resources folder. """ if os.path.isdir("resources"): return "resources" + os.sep if os.path.isdir("tests") and os.path.isdir("src"): return "tests" + os.sep + "resources" + os.sep raise FileNotFoundError( "C...
79a4ff91b0cb8a60042c3d828d72ad132cac3df4
68,330
def wordle_score(data_connection): """Create a wordle score.""" WordleScore.client = data_connection return WordleScore
6cdefa5f46e6bfbc26ac9c05f0ed15ac296b6a4a
68,331
def get_dir(dir: str, permissions=0o0775, exist_ok : bool=True): """Makes a directory at the given location Args: dir (str): Path of the directory permissions ([type], optional): Permissions of directory. Defaults to 0o0775. exist_ok (bool, optional): If True, program will continue if d...
44dba12399e5ff781c96607693658ec2e3ad6917
68,332
def selection_rate(y_true, y_pred, *, pos_label=1, sample_weight=None): """Calculate the fraction of predicted labels matching the 'good' outcome. The argument `pos_label` specifies the 'good' outcome. """ if len(y_pred) == 0: raise ValueError(_EMPTY_INPUT_PREDICTIONS_ERROR_MESSAGE) select...
8682334c7095a8bfa451aa757fd38a0ea01898f1
68,333
import statistics def run_stats(this_set): """ Find standard deviation and mean (average) for the data set. """ # Simply calculate Mean & StdDev for this set. # Return TUPLE of FLOATS return statistics.mean(this_set), statistics.stdev(this_set)
35ce499654bf7e8fe43d862b5456b0578a093fc7
68,334
def highest_match_action(ic, dc, sc, im, dm, sm, cost): """Given the following values, choose the action (insertion, deletion, or substitution), that results in the highest match score (ties are broken using the distance values). This is used within the dynamic programming algorithm. * ic - inserti...
d1d5b47e02ec9df8b65d3856b8ebba70511ca4d4
68,335
def routes_messages(): """Returns currently active messages and notifications for routes specified by parameter 'r'. If you want to specify multiple routes, use the 'r[]' key in the query string. If no routes are specified, all active messages will be returned.""" params = utils.qs_params( command='m...
58a77d5ca7776727f448cd5170898c2edae206a0
68,336
def generate_csv_url(sheet_url): """ Utility function for generating csv URL from a google sheets link This function generates a link to a csv file from a link used to edit a google sheets file. The gid must be present in the URL. Parameters ---------- sheet_url : str The URL for the...
d941ef98f3400175b9db4f7ef5da858fc6426caf
68,337
import time def register(request): """ List all snippets, or create a new snippet. """ if request.method == 'GET': return Response('get') elif request.method == 'POST': ''' Sample input { "client_id" :12, "client_secret" : "123sdf", "em...
17ac306df386ad5ae4ee36c77d953c04d7843302
68,338
def get_buffer_variable(a_variable_name): """Return the Vim buffer variable named `a_variable_name'.""" return get_prefixed_variable("b", a_variable_name)
a43371a80793a6d73d388db3a2e01635d570b53c
68,339
import argparse def parse_arguments(): """Parse evaluation arguments""" parser = argparse.ArgumentParser() parser.add_argument( "-y", "--truth-path", type=str, required=True, metavar="PATH", help="path to the file of with ground truth output (CSR: nr_insts...
1a23fd3ad5ed6093a019a43bc071de442ce59a95
68,340
from course.views import may_set_pretend_facility as mspf def may_set_pretend_facility(user): """ Check if a user may set pretend_facility :param user: a :class:`accounts.User:` instance :return: a :class:`bool` """ return mspf(user)
933dddca3c5caa028bd667c0b4f4d311f71e62cc
68,341
def dataAPIFactory(makeInstances=True): """ This is a convenience factory for creating a DataAPI instance. """ kwds = {} api = DataAPI apiArgs = [] return apiFactory(instanceKwds=kwds, makeInstances=makeInstances, api=api, apiArgs=apiArgs)
21ebbc0d98a8b16e088e69e884c18d17e8610d68
68,342
from evennia.web.webclient.views import webclient def webclient(request): """ Webclient page template loading. """ # disable autologin until it's fixed in devel session = request.session session.flush() session.save() return webclient(request)
16930fb9737ea8d9f7ad108499dc1adb80638627
68,343
import types def register(struct_type): """Register a `numba.core.types.StructRef` for use in jit-code. This defines the data-model for lowering an instance of `struct_type`. This defines attributes accessor and mutator for an instance of `struct_type`. Parameters ---------- struct_type ...
dfdbe76aa21368994524e8118aa5ba649c567502
68,344
from typing import Iterable import torch from typing import Optional def sentences_to_tensor(sentences: Iterable[str], tokenizer: object, device: torch.device, max_sequence_length: Optional[int] = None, regularize: bool = ...
01e53abaf34ab437590e1234c3b4721aec2844dd
68,345
def hashed_kgrams(string, k): """Return hashes of all k-grams in a string""" hashes = [hash(string[offset:offset+k]) for offset in range(len(string) - k + 1)] return np.array(hashes)
8258aad6a9e13757672c9843a15934862b412c6f
68,346
import os import textwrap import subprocess import tempfile import tarfile import time import shutil def restore_system(backup_file, include_storage_reinstall=False, clone=False): """Restoring system configuration.""" if (os.path.exists(constants.CGCS_CONFIG_FILE) or os.path.exists(tsconfig.CONFI...
18822954bb70c2df9450694040ca3867250d9ae1
68,347
def enum(**enums): """ http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python """ return type('Enum', (), enums)
38e7eeaa682709a624ffbaa861023c18cf7c421d
68,348
import scipy def robust_std(l, alpha=1/scipy.stats.norm.ppf(0.75)): """ Compute a robust estimate of the standard deviation for the list of values *l* (by default, for normally distributed samples --- see https://en.wikipedia.org/wiki/Median_absolute_deviation). """ return alpha * mad(l)[0]
17fa4bb89552231ccd7e829a793d5b4c18d4ef8d
68,349
def get_parcel_and_address_ids(latitude, longitude): """Takes a label's point and gets its address and land parcel IDs from the database. Returns None if no match (possible due to the vagaries of addressing & land titling)""" # get postgres connection from pool pg_conn = pg_pool.getconn() pg_conn.a...
2fe0ea6f50f270ed32f50f7867b6bf83fb8d7a3e
68,350
def add_nprocessors_option(parser,default_nprocessors,default_display=None): """Add a '--nprocessors' option to a parser Given a parser instance 'parser' (either OptionParser or ArgumentParser), add a '--nprocessors' option. The value of this option can be accessed via the 'nprocessors' attribute ...
cbc1fb90f258271f9cc09fb87b5c7be566776f9b
68,351
import os import six import logging def run_training(hps, experiment_proto, train_dir, train_input_paths, val_input_paths, tuner=None, master='', metrics_targets=None, metrics_measur...
f629b319153e465819568f42e237e38394218ec4
68,352
def not_found(error): """Handler for 'not found' error.""" return make_response(jsonify({'error': 'Not found'}), 404)
2d71367f72bed2ff80eddaa09ce43e46c5924cc6
68,353
def CheckProg(context, prog_name): """Simple check if a program exists in the path. Returns the path for the application, or None if not found. """ res = SCons.Conftest.CheckProg(context, prog_name) context.did_show_result = 1 return res
2b03f98e3cde1ac97c7557f8c1d42ecb1e46b04b
68,354
def encode_apb(dest): """ https://gpsd.gitlab.io/gpsd/NMEA.html#_apb_autopilot_sentence_b """ nmea = '$OPAPB,' nmea += 'A,A,' # 1,2 Set to valid if dest.xte is None: nmea += ',,,' # 3,4,5 XTE is not valid else: dir_to_steer = 'R' if dest.xte > 0 else 'L' nmea += '{:.3f},{}...
947cfdc299c2f7214d7953559f8296669e1eac8f
68,355
import os def parse_translation_table(translation_table_file): """ Parse the translationTable.xml into an ElementTree :param translation_table_file: the name of the input file :return: ElementTree """ if not os.path.exists(translation_table_file): raise Exception("Error: translation t...
cdb60cf6b52520310f960f98f6f06372c7d28c73
68,356
from typing import Set def write_itemscheme(obj: model.ItemScheme, locale=DEFAULT_LOCALE): """Convert :class:`.ItemScheme`. Parameters ---------- locale : str, optional Locale for names to return. Returns ------- pandas.Series """ items = {} seen: Set[Item] = set() ...
db0fe86a62218d14ffbe9470cf855175328b6a0d
68,357
def read_nifti(name): """Read nifti1 data""" return nb.nifti1.load(name)
71bba97760eb5389ad41d7f9bccf9554f17eca73
68,358
def plot_confusion_matrix(actual: np.ndarray, predictions: np.ndarray, save: str = None, normalize: bool = False, title: str = "Confusion matrix"): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. Source: http://...
ebfec9aa49681fc2476f322b32bd0467b176e8e9
68,359
def nurbs_curve2(): """ Creates a 5th order 2D NURBS Curve instance """ # Create a curve instance curve = NURBS.Curve() # Set curve degree curve.degree = 4 # Set weighted control points curve.ctrlptsw = [[5.0, 5.0, 0.5], [10.0, 10.0, 1.0], [20.0, 15.0, 0.1], [35.0, 15...
12494acdc51251042fa0ad29cef98feb764e5e0f
68,360
import json import os import sys def _test_main() -> None: """Main function for testing using the command line. Args: None Returns: None """ # Replace with your testing JSON # pylint: disable=line-too-long input_string = ( ' {"date": "YYYYMMDD", ' '"target_platform": "mc",' '...
929d348a069dbe1083f476eb79099f691f9e8029
68,361
def get_user_input_environment(env, reparam=False): """Validate action input for adversarial environment role. Args: env: Multigrid environment object. reparam: True if this is a reparameterized version of the environment. Returns: Integer action. """ max_action = env.adversary_action_dim - 1 ...
cb8da1704722b3c466f05bcbc82ca31a6472418a
68,362
import struct def cusparseCreate(): """ Initialize CUSPARSE. Initializes CUSPARSE and creates a handle to a structure holding the CUSPARSE library context. Returns ------- handle : int CUSPARSE library context. """ handle = _ffi.new('cusparseHandle_t *') status = _ff...
258c6784d326d7bfd654df8f87f000afe83ddf5d
68,363
import sqlite3 import sys def createdb(db, verbose=False): """ Create the database connection :param db: :return: """ try: conn = sqlite3.connect(db) except sqlite3.Error as e: sys.stderr.write("ERROR Creating database: {}\n".format(db)) sys.stderr.write(e) ...
a5d3e8e77855018e0157d043c89680eade47e53b
68,364
from bs4 import BeautifulSoup import re def clean_review(raw_review): """Function to convert raw review from df to words""" text_nothtml = BeautifulSoup(raw_review).get_text() text_letters = re.sub("[^a-zA-Z]", " ", text_nothtml) text_lower = text_letters.lower() text_tokens = text_lower.split() ...
02c2902c9f20bab4c861a93842fdddd4c6ce76cc
68,365
def get_capillary_rotation(capillaryImage,zTranslate): """ Finds the rotation angle of the capillary with respect to the camera position **return slope in degrees (rotational angle) capillaryCoords = 2D array (from get_string_interface_coordinates) """ #binarize image of capillary ...
2efbd72684da6e0277f5fffc2a1b888ac6e071b9
68,366
def combined_loss(new_params, log_probab_actions_old, value_predictions_old, policy_and_value_net_apply, padded_observations, padded_actions, padded_rewards, reward_mask, gamma...
5fb55af174a6a03ea18d0b5fcce6e97abc999b9a
68,367
def get_nic_information(idrac_ip): """Get nic information""" data = _make_request(REDFISH_URI.format(idrac_ip) + "/NetworkInterfaces") network_uri_list = [item['@odata.id'] for item in data["Members"]] all_nics = [] for item in network_uri_list: item = item.replace("Interfaces", "Adapters...
98088d870ca1730b5eace7801bd879d541c6532f
68,368
def shortcdstime2jd(days, milliseconds): """ Convert cds time to julian date """ offset = days + (milliseconds / 1000.) / (24. * 60. * 60.) return julian_epoch + offset
823395c7986b568581cb00b8095056eaa01fdd37
68,369
from typing import Dict def _get_claim(context: X12ParserContext) -> Dict: """Returns the current claim record for the patient (either subscriber or dependent)""" if _is_patient_a_dependent(context.patient_record): claim = context.patient_record[TransactionLoops.CLAIM_INFORMATION][-1] else: ...
441b1cebd320ac5e84636fde42ecfd3b177d5309
68,370
def cloudinary_direct_upload(callback_url, **options): """Deprecated - please use cloudinary_direct_upload_field, or a proper form""" params = utils.build_upload_params(callback=callback_url, **options) params = utils.sign_request(params, options) api_url = utils.cloudinary_api_url("upload", resource_t...
de51c4ee5acfcbb38412846d0583113b55b77fcf
68,371
def parse(hdfs_path): """ Parse the given path and return its components. :type hdfs_path: str :param hdfs_path: an HDFS path, e.g., ``hdfs://localhost:9000/user/me`` :rtype: tuple :return: scheme, netloc, path """ return _HdfsPathSplitter.parse(hdfs_path)
9aa4e56de6eb2a701fc49025966eac884da234fd
68,372
def Choi_LS_Pauli_mem(k, channel, cycles=1, optimize='optimal', full_output=1): """ WITHOUT CONTROL ON RANK Version where we try to keep memory in check. Main impact from M_k: needs $24^k$ complex128 entries. Could be reduced to $16^k$ at the price of many extra calculations. Yields the le...
f4675a8c4bfb59a845e255b7ab3fb3bf174ce9f7
68,373
from typing import Union def digits_sum(n: Union[int, BigInt]) -> int: """Get sum of digits in number Args: n: Number Returns: Sum of digits in number Examples: >>> digits_sum(123) 6 >>> digits_sum(BigInt(123456)) 21 """ return sum(get_digits...
3d422038e68c66602e842eda33c2f71ae396de3b
68,374
def traverse_robustness(claim: dict, discussion: dict, assign_values=True) -> float: """Recursive robustness of a claim, based on its weight and the weights of its entire subtree. Args: claim (dict): The claim for which to calculate robustness. discussion (list): The discussion `claim` belo...
4ea356b268d7155bfb918765ae22957814a8dc39
68,375
import requests async def get_or_create_pmid(handler, user, collection_name, pmid, github_token): """ Get the contents of this PMID file, or create it if it doesn't exist. """ p = int(pmid) repo_name = get_repo_name_from_collection(collection_name) try: pmid_contents = await handler.github...
53cf90ed639a3e9266e2c0db5d5a8d91924ac21b
68,376
import os def find_rgb_d_image_folders(input_folder, use_stereo_depth=False, use_registered_depth=False): """Return RGB and depth image folders paths for all the sensors. Note: Path is relative to the input folder path. Args: inpu...
1756e7a3a01520aedbd9c08e5d0d4dbfa94c79d3
68,377
def plot_raceline(Track_type, class_params: dict, LASTIDX, Car_type, savestr, save_results=False, line_type="EI"): """ Args: Track_type: class_params: LASTIDX: Car_type: savestr: save_results: line_type: the method used to get the raceline (EI, NEI, random) """ TRACK_NAME = Track_type.__name__ try...
d1cd1d86edeace388fa36bce0ee3f5df61c2363f
68,378
def create_multiscale_sauvola(window_size_list=[3,5,7,11,15,19], train_k=False, train_R=False, train_alpha=False, norm_type='bnorm', base_filters=4, ...
ec6c6d89fb5bcbbc72bc3920ab8e92b19181bed8
68,379
def manip( at='', path='.', recursive=False, ignore=True, modify=False, prefix='new_', posfix='', log=True ): """INSTRUCTIONS Decorator that transforms an [str] = function( [str]:text, *args, **kwargs ) into an function that apllies itself into a folder.\n The default values for the new function can be set ...
1b4331963de371297a395a02724ea381cd8b9bd4
68,380
def search_results(intent, session): """ Search GitHub for the intent's query slot """ query = intent['slots']['query']['value'] results = search_repositories(query) card_title = "Search Results for " + query if results['items']: top_repo = results['items'][0] speech_outp...
1b7560e5b79c7ab5cb7f1011e5609561a07d2e48
68,381
import os import locale from datetime import datetime import re def process_image(conn, image_id, params): """ Extract the specified image's log files into local files. @param conn: The BlitzGateway connection @param image_id: The source OMERO Image Id @param params: The script parameters ...
c29569f126f141562178eccfedd4c09981f90f3a
68,382
def get_linkresolver_url_by_ip(request, citation): """ Use the WorldCat registry API to get the appropriate OpenURL resolver for the user, based on their IP address. """ worldcat_registry = "http://www.worldcat.org/registry/lookup?IP={ip}" worldcat_tag = "{http://worldcatlibraries.org/registry/...
e04e11a2a47810d437591a9550e58d343e5647a9
68,383
import errno def signalfd(signals, fd=NEW_SIGNALFD, flags=0, closefd=CLOEXEC_DEFAULT): """Create a new signalfd Arguments ---------- :param sigset_t signals: raw cdata to pass to the syscall :param int signals: A single int representing the signal to listen for :param list signals: A list...
9f84cd37035ec3e8a06579b76acadbeae8b99701
68,384
def byte_array_declaration(data: bytes, name: str) -> str: """Generates a byte C array declaration for a byte array""" type_name = '[[maybe_unused]] const std::byte' byte_str = ''.join([f'std::byte{{0x{b:02x}}},' for b in data]) array_body = f'{{{byte_str}}}' return f'{type_name} {name}[] = {array_b...
015f0cb1a4dfd94b6f488b4eae0b58860da4d1dc
68,385
import copy def assemble_read_pairs(pairs: list, dist: int) -> str: """Assemble a string from substrings :param pairs: a group of substrings pairs :type pats: list (of tuples (of strs)) :param dist: the distance between the read-pairs :type dist: int :returns: the assembled string :rtype:...
89913d359a012877fa69d6ad632fdc1de4343fc7
68,386
import torch def box_iou(box1, box2): """ Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format. Arguments: box1 (Tensor[N, 4]) box2 (Tensor[M, 4]) Returns: iou (Tensor[N, M]): the NxM matrix containing the...
9913cb2a210802288e711f676cadd8c8d7e89f0a
68,387
def fizzbuzz(node): """ takes a value and returns fizz is divisible by 3, buzz if divisible by 5, fizzbuzz if divisble by both, or just the value if none of the conditions are met """ if node.val % 3 == 0 and node.val % 5 == 0: node.val = 'fizzbuzz' return node elif node.val ...
8d2125342f0f792d4f6b057c07fa8545f220f254
68,388
from typing import Tuple from typing import Any def loadProperty(xml: ET.Element) -> Tuple[Any, Any]: """Load a Qt Property from XML.""" for variant in xml: return (xml.get("name"), _loadVariant(variant)) raise ValueError("No property in provided XML")
e532800424e17580bb95b221a439b7928439d783
68,389
import tokenize def parse(css): """Parse a CSS *group of selectors*. If you don't care about pseudo-elements or selector specificity, you can skip this and use :meth:`~GenericTranslator.css_to_xpath`. :param css: A *group of selectors* as an Unicode string. :raises: :class:`Selec...
8fe9112383ba62fbe3a0a1ba808a55f7d869adb6
68,390
import sys import traceback def import_class(import_str): """Returns a class from a string including module and class.""" mod_str, _sep, class_str = import_str.rpartition('.') __import__(mod_str) try: return getattr(sys.modules[mod_str], class_str) except AttributeError: raise Impo...
47a83f5009d51cb1901bf8e003b1d5b98e95c97f
68,391
def svm_train(X, Y, lambda_, lr=1e-3, steps=1000, init_w=None, init_b=0): """Train a binary SVM classifier. Parameters ---------- X : ndarray, shape (m, n) training features. Y : ndarray, shape (m,) binary training labels. lambda_ : float regularization coefficient. ...
b633b433e8d53c45d21d19c884e40de6ed1b9212
68,392
def remove_logical_channel_assignment(client): """ Client assignation to an Optical Channel --- delete: description: Remove logical assignations between specified client and Optical Channel assigned. produces: - application/json parameters: - name: client in: path descrip...
ebfcafc87da687f7180ffd3c58e6054e2bd0a659
68,393
def get_version_string() -> str: """Returns version of GDM and of all registered extension packages.""" return " GDM Version: {}. Registered extension packages: {}.".format( _version.version, extensions.get_registered_package_info())
862d0f2437ef6aab376f9d0165414de2414163a3
68,394
import features def get_feature_extractors(): """ Return list of feature extractors given in `features.py` """ return [getattr(features, x) for x in dir(features) if isinstance(getattr(features, x), type) and x != 'BaseFeatureExtractor' and getattr(features, x).__bases_...
98a2eb81b98e02218ce83e669cbdf67b11c63227
68,395
def find_previous_tries_attempts(target_try_attempts): """ :param target_try_attempts: An AttemptLog queryset :type target_try_attempts: django.db.models.QuerySet :return: A queryset matching previous tries' attempts for each try in `target_try_attempts` :rtype: django.db.models.QuerySet """ ...
7b7bb30632e2f4f54b7d52778efeeb9e760d283c
68,396
import time import torch def find_all_boxes(output, conf_thresh, num_classes, anchors, num_anchors, only_objectness=1, validation=False): """ find boxes from output """ num_classes, num_anchors = int(num_classes), int(num_anchors) anchor_step = int(len(anchors) / num_anchors) # output = (bacth, (...
8791575379c58f01a44fc4ac8b275713154b75c5
68,397
import os import csv def ReadTimeStamps(path) : """ Look for timestamps.txt and strobo_timstamps.txt in path Return N, the number of lines and timestamps a list containing all data """ file = os.path.join(path,'timestamps.txt') if not os.path.exists(file) : file = os.path.join(path,'s...
9c5f9d54fa32b27c330d27255b1ded3f9a92cbf7
68,398
from datetime import datetime def encode_jwt(username, domain: str = None): """Get JWT encoded token.""" current_time = datetime.datetime.utcnow() expires_on = current_time + datetime.timedelta(seconds=JWT_EXPIRATION_DELTA) # Идея хранить в payload user_id признана несостоятельной. access_token_pa...
93692ed90318148cb638d4ba7b63cd8723fc1d1c
68,399