content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime import dateutil def is_later(timestamp, period): """Return true if the current time > timestamp + period. Checks if the timestamp given is later than the current time + the period given in seconds. Attributes: timestamp -- integer, EPOCH. period -- integer, seco...
73d51bbb0294094107d7a2ee4068dcd753d01b4d
72,393
def parse_puzzle(puzzle, digits='123456789', nulls='0.'): """ Parses a string describing a Sudoku puzzle board into a dictionary with each cell mapped to its relevant coordinate, i.e. A1, A2, A3... """ # Serialise the input into a string, let the position define the grid location and .0 can be empty positions # ...
874bf52f708faf483c2b18118cad2c4fd7305c78
72,394
def visualize(history, regret_periods=None, time_labels=None, model_labels={}, style_algs={}, ax=[None, None, None], params=["lam"], subset_time=None, legend=True): """ Visualize online learning losses, weights, and parameters. Args: history (History): online learning History object regret...
954d64687b803dbac68fcb34ed03e404e5d1436f
72,396
def import_read_depth( gene, depth_of_coverage ): """ Import read depth data for target gene. Parameters ---------- gene : str Gene name. depth_of_coverage : str or pypgx.Archive Archive file or object with the semantic type CovFrame[DepthOfCoverage]. Returns ...
ac9437cf92a120728276adb6748ff65497318f2e
72,397
from typing import Any from typing import Callable from typing import Dict def authenticate(jwthenticator_server: str) -> Any: """ Wrapper function to verify user performing the request is authorized. The function extracts the JWT token from the header and verifies it against an jwthenticator serv...
3b6b38db3c1b0605839e89195dabb0b33ea997b2
72,398
def concat_complex(list_complex, width_in_bits, imreOrder=True): """ Concatenates the real and imaginary part into one integer. The specifed width counts for both the real and imaginary part. Real part is mapped on the LSB. Imaginary part is shifted to the MSB. """ # PD if imreOrder: ...
831275da0695a477f9f75da1e238f231ea8d39df
72,399
def byte_to_megabyte(byte): """Convert bytes to megabytes """ return byte / 1024 ** 2
32cd30fc627e6a834f79ccc969af384089ba23a4
72,400
def coords_to_distance(coords): """Transforms a list of coordinates into a list of distances between each point of these coordinates. Parameters ---------- coords : pd.DataFrame The coordinates, for each point. Must have a single index, and columns 'x' and 'y'. Returns...
e3f4ef54a700738bf17cd01727c7209618a5cefc
72,402
def extract_lines(response): """セリフを抽出する. 特訓前・特訓後・思い出エピソードのセリフを抽出する. :return: セリフ情報を保持した辞書オブジェクト """ line_block_ids = search_block_id(response, "セリフ集") def _extract_lines(index): """特訓前後のセリフを抽出する. セリフ集ブロックのidが1つだけしかない場合でも 同一インタフェースで操作できるようにするための内部関数. """ ...
2705d2ec8afe5c69d223fc2641487b1ad4c77cf6
72,403
import scgen def runScGen(adata, batch, cell_type, epochs=100, hvg=None, model_path='/localscratch'): """ Parametrization taken from the tutorial notebook at: https://nbviewer.jupyter.org/github/M0hammadL/scGen_notebooks/blob/master/notebooks/scgen_batch_removal.ipynb """ checkSanity(adata, batch...
dfe40a9ebe92f267d2522f2cccc8ab96ef20c40f
72,404
import numpy def _paa_to_symbols(X_paa, breakpoints,variables_size = 1,multivariate_output = None): """Transforms a Piecewise Aggregate Approximation representation into a SAX one given breakpoints. Example ------- >>> _paa_to_symbols(X_paa=numpy.array([-1., 0.1, 2.]), breakpoints=numpy.array([0.])) ...
4e7622fb0c70179d75678da9f26c878364ec222c
72,405
import time def support_vector_machine(): """ This function performs classification with support vector machine """ train_x, test_x, train_y, test_y = prepare_data() train_y = train_y.reshape((train_y.shape[0], )) classifier = SVC(kernel="rbf", C=10, gamma=1) start = time.time() cl...
3bd4fea6666a903a927bdb1bf97a9886dad8e22e
72,406
def treat_category(category: str) -> str: """ Treats a list of string Args: category (str): the category of an url Returns: str: the category treated """ return category.lower().strip()
a4c08383bdfb40e5e64bbf576df53a7f46fc07da
72,407
def parse_snmp_return(ret): """Check the return value of snmp operations :param ret: a tuple of (errorIndication, errorStatus, errorIndex, data) returned by pysnmp :return: a tuple of (err, data) err: True if error found, or False if no error found data: a string o...
d4e51c4ac10e2c10945c2e4096a1dae5a2ca731f
72,408
def simulate_uniform(range_lim, delta_lim, counts_lim): """Simulates uniform data of a specified size Parameters ---------- range_lim : list, int The upper limit of the uniform distribution delta_lim: list, int The offset between the two distributions count_lim : list, float ...
e202c5c3f4ecaf2518153d94b292ac0f8adeaa67
72,409
def _require_mapped(relation, rel_map, *args, **kwargs): """ Map the object if we have specific table for it; otherwise, return raw. """ predicate = _element_predicate(relation) if predicate in rel_map: return _rdf_object_from_element(predicate, relation, *args, **kwargs) try: r...
34de6052436da821ef6744d291c2522cbe7e0de3
72,410
from datetime import datetime def create_deploy_for_run( ctx: ExecutionContext, account: Account, node: Node, deploy_hash: str, dispatch_attempts: int, dispatch_duration: float, typeof: DeployType, associated_account: Account = None, ) -> Deploy: """Returns a domain object inst...
c2e14982fef05622fc9246874f68c380f5939d72
72,411
def inversion_mutation(individual: Individual) -> Individual: """ Performs inversion mutation A random sequence of genes is selected and the order of the genes in that sequence is reversed. Args: individual (Individual): Individual that will be mutated sigma (int): The mutation strengt...
41ca7d235535700d56b91eaeaad12cd7c7c78cd3
72,412
import main def handler(lambda_context): """ Return a function to invoke the main lambda handler with a mock context. """ return lambda: main.main({}, lambda_context)
bb5728cad94d92d14980d53a5b384e532717531e
72,413
def get_task_best(df_task, df_res_valid, df_truth): """Selects the best possible result for a task, based on the ground truth. Optimistically biased, only for determining upper bound! """ task_list = [] for task_id in df_task['task_id']: task_results = df_res_valid.lo...
cd6f92a68d8ebe78521ae00d789495140f13abee
72,414
import time async def api_speech_to_text() -> str: """Transcribe speech from WAV file.""" no_header = request.args.get("noheader", "false").lower() == "true" assert core is not None # Prefer 16-bit 16Khz mono, but will convert with sox if needed wav_data = await request.data if no_header: ...
f56562d3db34c7f6d5d1c3ad35536cb1948c771c
72,416
def visualize_coordinate_frame(im, K, R, t, vis_size_in_px=15): """Draws a coordinate frame on top of an image. Args: im: Input image. K: 3x3 intrinsic matrix. R: 3x3 rotation matrix. t: 3x1 translation vector. vis_size_in_px: Length of each axis in pixels. Return: The input image augment...
144c7cad7556d8d8fa1b9fda7227dbc226adf530
72,417
import token def maybe_make_parens_invisible_in_atom( node: LN, parent: LN, preview: bool = False, ) -> bool: """If it's safe, make the parens in the atom `node` invisible, recursively. Additionally, remove repeated, adjacent invisible parens from the atom `node` as they are redundant. Re...
50c97ec5d92948c4ddcb11e83912f3137e925d7a
72,419
import torch def boxes_iou_bev(boxes_a, boxes_b): """ :param boxes_a: (M, 5) :param boxes_b: (N, 5) :return: ans_iou: (M, N) """ ans_iou = torch.cuda.FloatTensor(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))).zero_() iou3d_cuda.boxes_iou_bev_gpu(boxes_a.contiguous(), boxes_b.c...
aad803ae1d29f92dfd0c7a17b0d0775f1dda1c3a
72,420
def _get_fully_qualified_class_name(obj): """ Obtains the fully qualified class name of the given object. """ return obj.__class__.__module__ + "." + obj.__class__.__name__
e427991067254c2ac1963c5ae59468ec2c0835e2
72,421
def convert_batchnorm(node, **kwargs): """Map MXNet's BatchNorm operator attributes to onnx's BatchNormalization operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) momentum = float(attrs.get("momentum", 0.9)) eps = float(attrs.get("eps", 0.001)) b...
9cf49f1d5f23877dae360c74086d501efb3cdaa8
72,424
import decimal def new_decimal(value): """Builds a Decimal using the cleaner float `repr`""" if isinstance(value, float): value = repr(value) return decimal.Decimal(value)
023809d3db3e863f66559913f125e61236520a6a
72,425
from datetime import datetime def now(tz: datetime.tzinfo = None ) -> effect.Depends[HasClock, datetime.datetime]: """ Create an `Effect` that succeeds with the current datetime Example: >>> from pfun import DefaultModules >>> now().run(DefaultModules) Args: tz: timezon...
66d14a2048940ac6a85849ba8bd20f8e5b320b7f
72,426
def preprocessar(f, freeling_values): """ Realiza a análise sintática e morfossintática da frase em português. :param f: string, frase em português. :param freeling_values: parâmetros da ferramenta Freeling :return: objeto da classe Frase_input com as caracteristicas gramaticais da frase em português """ map_co...
456ddb20bb0a44e72fb148dd27471be593a0d338
72,427
def get_private_endpoint(id: str, guid: str) -> str: """Get remote endpoint for delivering private payloads.""" _username, domain = id.split("@") return "https://%s/receive/users/%s" % (domain, guid)
773cdfc7d549eceaaf2de7031f03815e3f5c8af7
72,429
def reference_genome_features_to_JSON(genome_file): """ From genome reference (GBK format) convert CDS, gene & RNA features to JSON The following 2 are really good resources: * http://www.ncbi.nlm.nih.gov/books/NBK63592/ * http://www.ncbi.nlm.nih.gov/genbank/genomesubmit_annotation .. ...
9611e73352d2682ea404c1d2610d8492f1af61b1
72,431
def passport_valid(passport: dict) -> bool: """Check is a passport is valid by checking specific rules for each field.""" check_valid = PassportSchema().validate(passport) return check_valid == {}
856b53e8b637c749411d4c3711c66106562dfbd4
72,432
def add_frac(zaeler1, nenner1, zaeler2, nenner2): """Dieses Programm addiert 2 Brüche miteinander und kürzt sie mit ihrem größten gemeinsamen Teiler (ggt)""" #Variablen einführen zaeler=0 nennerg=0 ggt = 1 #überprüfen ob die Eingabe eine Ganzzahl ist if not(isinstance(zaeler1,int) and isinstance(ne...
c77734b40f83121656e49a7029cfe73c073ee45d
72,433
def geomconvert_C0BSplineToC1BSplineCurve(*args): """ * This Method reduces as far as it is possible the multiplicities of the knots of the BSpline BS.(keeping the geometry). It returns a new BSpline which could still be C0. tolerance is a geometrical tolerance. The Angular toleranceis in radians and mesures the ...
63e85896d3ec012829817cdc823602404e98500f
72,434
def detector( generator, model, iou_threshold=0.5, score_threshold=0.05, max_detections=100, save_path=None ): """ Evaluate a given dataset using a given model. # Arguments generator : The generator that represents the dataset to evaluate. model : The mod...
fdd2c35a9c46598b0a7feb0895bc7de2ce232416
72,436
from typing import List from typing import Tuple def get_modifications(protein_id: str) -> List[Tuple[str, int]]: """Return a list of modifications for a protein. Parameters ---------- protein_id : The UniProt ID of the protein to query Returns ------- : The list of modif...
fa01dee4120e6ee1f4f560ed4210cb1c64a9df20
72,437
def BFS_MIN(graph, start): """最短路径问题, 树的结构""" queue = [] queue.append(start) seen = set() seen.add(start) parent = {start:None} # 开始BFS搜索 while len(queue) > 0: vertex = queue.pop(0) nodes = graph[vertex] for w in nodes: if w not in seen: ...
91013649e813dd582b08d092f6f5c5c66e4cc92a
72,438
import html def generate_main_layout( theme='light', src_type='V', mode_val='single', fig=None, ): """generate the layout of the app""" source_label, measure_label = get_source_labels(src_type) source_unit, measure_unit = get_source_units(src_type) if mode_val == 'single': si...
ead18fba565e01ae31ad18217425348c761a7382
72,439
def _fix_col_name(df): """修复列名称""" # 更名 if ("股票代码" in df.columns) and ("股票简称" in df.columns): df.rename(columns={"股票代码": "证券代码", "股票简称": "证券简称"}, inplace=True) origin = df.columns def f(x): x = _remove_prefix_num(x) x = _remove_su...
6677eb2ad98d59ecbe3bc6605350c84b4a062379
72,440
def sol(arr, n, p): """ If we have more chocolates than cost we just pay from the balance otherwise we use all the balance and add the remaining to the total cost also making bal 0 """ bal = 0 res = 0 for i in range(n): d = arr[i-1]-arr[i] if i > 0 else 0-arr[i] # Careful...
75592d2783eba2e4721721b03f84ea5cebffbc78
72,441
def combined_median_absolute_deviation(data, x_0, **kwargs): """ Compute the sum of the median absolute deviations to the median of the samples and to the observed value. """ mad = median_absolute_deviation(data) mado = median_absolute_deviation_to_observation(data, x_0) cmad = mad + mado ...
9df9585cf9ef29f7183ce1e459acb9c16923774b
72,442
def is_atari_id(env_id): """ Returns True if env_id corresponds to an Atari env. """ env_id = env_id[:env_id.rfind("-")] for postfix in ("Deterministic", "NoFrameskip"): if env_id.endswith(postfix): env_id = env_id[:-len(postfix)] atari_envs = set(list_envs("atari")) return env_...
a5b5cff3748a2b0d66077604af30d2790070dc36
72,443
def ExtractX509Certificate(pem): """Extracts the certificate from a PEM-formatted string. @type pem: string @rtype: tuple; (OpenSSL.X509 object, string) @return: Certificate object and PEM-formatted certificate """ cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, pem) return (cert, ...
5fd06f74c90f697b66efe28d26c4db6be511a052
72,445
def wind(): """ Create a window and application for testing. Returns ------- `tuple` information to pass to test function. """ window, app = WINDOW, APP return window, app
b5fe4e5ff9233950688cc4955667935aa7dd27d4
72,446
def _make_dist_mat_sa(enrichment_type, dist_lim): """Generate a sample distance matrix to test spatial_analysis Args: enrichment_type (str): whether to generate for positive, negative, or no enrichment dist_lim (int): the threshold to use for selecting entries in the dis...
263fb0acbabf12cd54f709710e08084e53accd35
72,447
import torch def optimize_ancer( model: torch.nn.Module, batch: torch.Tensor, certificate: Certificate, learning_rate: float, isotropic_theta: torch.Tensor, iterations: int, samples: int, kappa: float, device: str = "cuda:0" ) -> torch.Tensor: """Optimize batch using ANCER, assumin...
8c018c880d5273aca1fe8a6798fad60691a0a09a
72,448
def get_serialized_logs_with_no_nodes(connection): """ Get the serialized log records that correspond to nodes that were deleted """ query = connection.execute( text(""" SELECT db_dblog.id, db_dblog.time, db_dblog.loggername, db_dblog.levelname, db_dblog.objpk, db_dblog.objname, db_dblog...
c2b4fc8b41d234ca0a631bdf899efdee832792a3
72,449
def _get_search_filter( service_name, service_version=None, os_name=None, os_version=None ): """Create a pymongo-style search filter using the system configuration, as described by software and OS on host. Args: service_name (str); Software/service name. service_version (str): Software/...
029265ac5cf17ded626058752bb601f6af0d411d
72,450
def treemap(): """Fake endpoint.""" if 'stress' in request.args: # Build a very large dataset return jsonify(recursive_d3_data()) with open('{}/examples/flare.json'.format(cwd), 'r') as djson: return djson.read() return jsonify({})
1dbddfbb41f38f1f86156425f6ae4673314f4c59
72,452
def _check_terminators(context): """ If any of the `TERMINATORS` predicates return True, terminate the execution. :param context: Context. :return: Updated context. """ preds = context.get(TERMINATORS, v()) if any(pred(context) for pred in preds): return context.discard(QUEUE) ...
007da4692734722d26fc087c7336edc4b09a0a15
72,453
def reshape_and_scale_single_image_back(image): """ Wrapper for utils.reshape_to_cv_format. """ image, _ = utils.reshape_to_cv_format(image, True) return image
c999287e0e075876a2687c1ee780b5175b216053
72,454
def index(request): """ Функция отображения для домашней страницы сайта. """ teacher_id = get_teachers_id(str(request.user)) all_groups = groups(teacher_id) st_groups = get_student_groups() for group in st_groups: all_groups.append(group) all_subjects = subjects_many(group_ids(t...
35db062ca84a717b3423f95a2cfbb532409dded2
72,455
def ncol(self): """ return the number of cols """ return len(self.columns)
723567269cf2779eef991c35f00814d7b541d75e
72,457
from datetime import datetime def format_delta(delta_seconds): """ Format a time delta nicely. :param delta_seconds: The number of seconds :type delta_seconds: number :rtype: string >>> from pysnptools.util import format_delta >>> print(format_delta(86403.5)) 1 day, 0:00:03.500000 ...
7a994061f46da409898e4e43af0c587db59ad2ed
72,458
def _add_name_scope_wrapper(func, api_signature): """Wraps `func` to expect a "name" arg, and use it to call `ops.name_scope`. If `func` already expects a "name" arg, or if `api_signature` does not expect a "name" arg, then returns `func` as-is. Args: func: The function to wrap. Signature must match `api...
feade9fa8882f8388b253afb2f0534bfd87988e3
72,459
import random import logging import time def fuse(destination : str, source : str, offset : tuple = None): """Fuse <source> into <destination>. Takes a REALLY long time ! Offset for <source> will be found automatically if <offset> is None <destination> : Name in .minecraft/saves of the map into whic...
811c54abbcc7f406bf0065d2f1146c06e528cf2c
72,460
def intersect_border(alpha,p,border): """ Find intersection point of a line with the border (given as distance l from point p with angle alpha) """ return find_intersect(alpha,p,border[0],border[1],ret_xy=False)
614bdd9a9678a08ee2bc53fd165c69ebe5aeb27e
72,461
def insertionsort(arr): """ In a given iteration: 1. swap arr[lo] with each larger entry to the left. 2. Increment lo pointer """ lo = 0 hi = len(arr) - 1 while lo <= hi: curr = lo while curr - 1 >= 0: if arr[curr] < arr[curr - 1]: arr...
64a44af7b563e708053f04da3970429dc05c4745
72,462
def get_rows(dependencygroup, leadingpath): """Return the rows for dependencygroup. Caller may have to format the values as strings.""" rows = [] sortedfilenames = sorted(dependencygroup.depnode_to_ca.keys()) for i in range(len(sortedfilenames)): f = sortedfilenames[i] ca = dependenc...
376740391b2de76d1be129c963126649aca0fa2e
72,463
import json def cam_param_json2dict(json_file_path): """Load the camera parameters form json file. Convert all parameters to numpy array. :param json_file_path: the json file path. :type json_file_path: str :return: camera parameter :rtype: dict """ dict_data = None with open(jso...
b8afe2104ba39606802b623877b26863519b365d
72,464
def _F_avg_psi(fw_states_T, basis_states, O, imag_limit=1e-10): """Implementation of F_avg in Hilbert space""" N = len(basis_states) U = gate(basis_states, fw_states_T) F = abs((O.dag() * U).tr()) ** 2 + (O.dag() * U * U.dag() * O).tr() assert abs(F.imag) < imag_limit, "%.2e > %.2e" % (F.imag, imag_...
c7db6276d9e4f3453964314e396bf01d755f96be
72,465
def etree_to_dict(t): """ convert the etree into a python dict """ tag = t.tag if '}' in tag: tag = t.tag.split('}', 1)[1] # LOG.info("TAG: %s" % tag) d = {tag: {} if t.attrib else None} children = list(t) if children: dd = defaultdict(list) for dc in map(etree_to_dic...
a325c2ecd22b12dce127998dd0998e1f88620858
72,466
def Iterate_Friction_Velocity(k_vk,u_200,Surf_roughness,g_inst,rn_inst, ts_dem, ts_dem_hot, ts_dem_cold,air_dens, Surface_temp,L,psi,psi_m200,psi_m200_stable,QC_Map, hot_pixels, slope): """ Function to correct the windspeed and aerodynamic resistance for the iterative process the output can be used as the new i...
9cdef411df09f049830512d6a54d628df83863ab
72,467
import requests def send_ocr_request(url): """ Function that sends request to OCR Space via API :param url: URL to png/jpg file :type url: string :return: Returns JSON response :rtype: string """ data = {'url': url, 'isOverlayRequired': False, 'apikey': ocr_token, 'language': 'pol'} ...
b46947b7f76213c15d114f959682554e6a8d1786
72,468
import functools def verify_help_scout_signature(f): """Middleware to validate Help Scout API calls https://developer.helpscout.com/webhooks/#verifying """ @functools.wraps(f) def wrapped(*args, **kwargs): sig = request.headers.get("X-HelpScout-Signature") if not _is_valid_signatu...
5e667883383fc514974029827ccd66b839cad7cd
72,469
def add_method(cls): """Decorator. @add_method(cls) binds the following function to the class cls.""" def decorator(func): #method = MethodType(func,cls) #setattr(cls, func.__name__, method) setattr(cls, func.__name__, func) return func ret...
b6f350651dddf90c1c9f88467d04fa7f53b8204f
72,470
import six def to_python(var): """ Converts strings that are really numbers to ints or floats May be more generic in the future :param var: a string :type var: six.string_types """ var = var[0] if isinstance(var, list) and len(var) == 1 else var if not isinstance(var, six.string_types...
e1e94a45058994685b86de1ebedf0c657520b3c4
72,473
def get_gtr(file, file_path, progress=True): """ Fetch Gateway To Research predicted industries Repo: https://github.com/nestauk/gtr_data_processing Commit: cd3cddb File: https://github.com/nestauk/gtr_data_processing/blob/master/notebooks/05_jmg_data_demo.ipynb Args: file_path (`str`,...
826883fb2ba786769128ba0cd7bb5a1a0b55bfbb
72,474
def remove_fuzziness_in_mask(seg_img, n_classes, class_to_color, fuzziness): """handle annoying nearby pixel values to each actual class label, e.g. 253, 254 for actual label 255""" seg_img_min = np.amin(seg_img) seg_img_max = np.amax(seg_img) seg_img_out = np.copy(seg_img) seg_img_raw = np.zeros(...
1f641461be8cf4bc270eee3cd1e318a24ffb8d80
72,476
import unicodedata def unidecode(s: str) -> str: """ Return ``s`` with unicode diacritics removed. """ combining = unicodedata.combining return "".join( c for c in unicodedata.normalize("NFD", s) if not combining(c) )
589dc0403c95e29f340070e3a9e81a6f14950c8e
72,477
def similarity_score(Article1,Article2): """ This function calculates Euclidean distance between to objects """ both_viewed = {} for item in dataset[Article1]: if item in dataset[Article2]: both_viewed[item] = 1 # The Conditions to check if they both have common rating ...
d9522fec4ad22126896c12c70c3d173ca1eb8a42
72,479
def remove_consequential_exchanges(data): """Remove exchanges with have a ``consequential`` property with a value of 1. These exchanges are not used in the cutoff system model.""" for ds in data: for exc in ds['exchanges']: if has_consequential_property(exc): logger.info...
f8b1e7e2662cb96ac8d332688d9078de8c450387
72,480
def convert_range_image_to_point_cloud(frame, range_images, camera_projections, range_image_top_pose, ri_index=0): """Convert range images to point cloud. Args...
2ddc169c15c232f50016d94d48ea3a9967baede8
72,482
from typing import Optional from typing import Tuple def generate_tx_spend_and_key_image( ack, out_key, recv_derivation, real_output_index, received_index: tuple ) -> Optional[Tuple[Sc25519, Ge25519]]: """ Generates UTXO spending key and key image. Corresponds to generate_key_image_helper_precomp() in...
3d2e7c0e8e03655b0a96285212a56994487c9de5
72,483
def construct_answer_dictionaries(label_row): """ Adds answer object and classification answer dictionaries from a label row if they do not exist. Integrity checks are conducted upon saving of labels. Args: label_row: A label row. Returns: LabelRow: A label row instance with update...
5a16143d4d05048452cea28a4c89e4a63fb1e4d3
72,484
def establishStepSpace(**args): """ _establishStepSpace_ Bootstrap method for the execution dir of a WMStep within a WMTask """ return StepSpace.StepSpace(**args)
1acdfa4e171fccf7289d919b8d3f865544d7a433
72,485
def AutoUpdateUpgradeRepairMessage(value, flag_name): """Messaging for when auto-upgrades or node auto-repairs. Args: value: bool, value that the flag takes. flag_name: str, the name of the flag. Must be either autoupgrade or autorepair Returns: the formatted message string. """ action =...
7153b7aa44d6d798aa58d9328ac49097016c0879
72,486
def euclidean_distance_1(x_list, data_list): """ :param x_list: [(x0, y0), (x1, y1), (x2, y2), ..., (xn-2, yn-2), (xn-1, yn-1)] data_list: [x_list_0 (same data structure as x_list), x_list_1, x_list_2, ..., x_list_n-2, x_list_n-1] :return: ed_list ...
4f09ad83ba529dfb456884c028fdf06ef995f850
72,487
import math def detect_first_stage(img, net, scale, threshold): """ run PNet for first stage Parameters: ---------- img: numpy array, bgr order input image scale: float number how much should the input image scale net: PNet worker ...
8e6c7029547763bfcafd52dd06c661bb380dee17
72,488
import ast import collections import logging def _get_ground_truth_detections(instances_file, allowlist_file=None, num_images=None): """Processes the annotations JSON file and returns ground truth data corresponding to allowlisted image IDs. Args:...
2650ff4ffeb13d0a7874164474fa47a82880d45d
72,489
import optparse def parse_opts(): """Parses command line options""" usage="Usage: %prog [options]" parser = optparse.OptionParser(usage) parser.add_option("-c", "--config", dest="config", type="string", help="report configuration file (required)") opts, args ...
44ae42377d067c32a666e4cb3099fbb7837a4c5a
72,490
def last_n(n, query_set): # type: (int, QuerySet[T]) -> List[T] """Get the last n results from a Django QuerySet, in a semi-efficient way. Returns a list.""" # We don't use reversed() because we would get a generator, # which causes bool(last_n(...)) to be True always. xs = list(query_set.r...
7aa834ce4cc033201c99f458df8053974d9e9207
72,491
def unfollow(id): """Unfollow a user""" user = token_auth.current_user() unfollowed_user = db.session.get(User, id) or abort(404) if not user.is_following(unfollowed_user): abort(409) user.unfollow(unfollowed_user) db.session.commit() return {}
5903e7fed3a2020b54b5b98336d23c2cd05d9ad0
72,492
def formulate_contingency(problem: pl.LpProblem, numerical_circuit: SnapshotOpfData, flow_f, ratings, LODF, monitor, lodf_tolerance): """ Formulate contingencies :param problem: :param numerical_circuit: :param flow_f: :param ratings: :param LODF: :param monitor: :return: """ ...
e1c7ec413dde9675ebd47f91859feeaae99e598e
72,493
from polynomials_on_simplices.generic_tools.code_generation_utils import CodeWriter def unique_identifier_bernstein_basis_simplex(vertices): """ Get unique identifier for the Bernstein polynomial basis on a simplex T. :param vertices: Vertices of the simplex T ((m + 1) x m matrix where row i contains the...
01403c12fbb51b7059006e4da22b35b16bb4b166
72,494
from typing import Dict from typing import Any def create_binance_symbols_to_pair(exchange_data: Dict[str, Any]) -> Dict[str, BinancePair]: """Parses the result of 'exchangeInfo' endpoint and creates the symbols_to_pair mapping """ symbols_to_pair: Dict[str, BinancePair] = dict() for symbol in exchang...
3605bbddaffb5a9018623277a8f19c1fc39d9f00
72,495
def _api(ctx, target, proto=None): """Resolve cell api.""" srv_recs = _resolve_srv(ctx.dns_domain, ctx.dns_server, target) if not srv_recs: raise context.ContextError('No srv records found: %s' % target) return (srv_recs, proto)
708c17ea586975e9a5b5eb360a1e2be28bc49198
72,496
import re def combine_placeholders(string, placeholders, _placeholder_re=re.compile(r'%\(([^)]+)\)')): """Replace ``%(blah)`` placeholders in a string. Each placeholder may contain other placeholders. :param string: A string that may contain placeholders :param placeholders: A dict containing placeh...
f75dc1cd7b9c1c1d036dbdc60221b426bd56d012
72,497
def quadratic(a, b, c): """ Always returns the smallest root as t0 """ discrim = b**2 - 4 * a * c if discrim < 0: return (False, 0, 0) rootd = discrim**(1/2) if b < 0: q = -0.5*(b - rootd) else: q = -0.5*(b + rootd) t0 = q / a t1 = c / q if t1 > t0: tm...
3acafea305892bc6d303a3c090411d3eb4eb2204
72,498
def density_to_cartesian(rho): """Compute Bloch sphere coordinates from 2x2 density matrix.""" a = rho[0, 0] b = rho[1, 0] x = 2.0 * b.real y = 2.0 * b.imag z = 2.0 * a - 1.0 return np.real(x), np.real(y), np.real(z)
bbf9a2af21945fff34740f0c682f60d2ab8b4c0b
72,499
import inspect def _get_pk(table): """Get the single column that is the table's PK.""" pks = inspect(table).primary_key.columns.values() assert len(pks) == 1 return pks[0]
90752825ab27854878c62b8ebeb600faba987088
72,500
def running(): """Return a dict with the running state of all Snips services. Returns: dict: A dict with all Snips services as keys and their running state (True or False) as value. .. versionadded:: 0.5.3 """ return _state(is_running)
b21932c5c97d75a699b47b59f1c8275cb06c98bb
72,501
from ._text import split_and_check from typing import Tuple def parse_range2d_int(s: str) -> Tuple[Tuple[int, int], Tuple[int, int]]: """Parse string like "0:3,4:5" -> ((0,3), (4,5))""" try: return tuple(tuple(int(x) for x in split_and_check(p, ":", 2)) for p in split_and_check(s, ",", 2)) except ...
497d611a01a4a7280692758228fa9927516f91cf
72,502
import json def parse_metric_file(metric_file): """ takes the metric file and extracts timestamps and avg_imgs / sec info """ maxStep, minTime, maxTime, avg_examples = 0, 0, 0, 0 with open(metric_file, "r") as f: for line in f: el = json.loads(line) if el['name'] == "c...
f56b2e6c1401de89ff25a7a0a825de9e2c43d9b3
72,503
def getsmiles_cactus(name): """Converts synonyms into SMILES strings. A function to use the public cactus (National Institutes of Cancer Research) webservice to retrieve a smiles string from a synonym. Args: name: any trivial or IUPAC name for a molecule Returns: Canonical smiles string f...
503d8d10b07e5ce2550c6495db7e93e80a8eded2
72,504
from typing import Type def nodetype_to_nodeitem(node_type: Type[bpy.types.Node]) -> NodeItem: """Create a NodeItem from a given node class.""" # Internal node types seem to have no bl_idname attribute if issubclass(node_type, bpy.types.NodeInternal): return NodeItem(node_type.__name__) retur...
d3daa956d6aea868700595b37164cd66154a0774
72,505
def tlv_data_xml(tlv_string_xml) -> bytes: """Return the XML data for the test tree as bytes.""" return xml_prettify(tlv_string_xml)
582055f4e4b2b7695feeeda38e1578bb434bde95
72,506
def comparison_total(bst): """ ------------------------------------------------------- Sums the comparison values of all Letter objects in bst. ------------------------------------------------------- Preconditions: bst - a binary search tree of Letter objects (BST) Postconditions: ...
2fe199d5364c79fd969dbfb2a3dfb7efd62c599a
72,508
from unittest.mock import call def make_cpp(func: object) -> object: """ The Holy Wrapper """ if _is_disabled(): return func name = _make_cpp(func) def cboost_wrapper(*args, **kwargs): return call(name, args, kwargs) return cboost_wrapper
c03d8ee0b58a875651b541dc2c09540e13faebd4
72,509
import shutil def _combine_out_files(chr_files, work_dir, data): """Concatenate all CNV calls into a single file. """ out_file = "%s.bed" % sshared.outname_from_inputs(chr_files) if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: with open(tx_...
1eca4712b24601f60faac6f88accb1239aca19c2
72,510