content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from unittest.mock import Mock async def test_10_request(requests_mock: Mock) -> None: """Test `async request()`.""" result = {"result": "the result"} rpc = RestClient("http://test", "passkey", timeout=0.1) def response(req: PreparedRequest, ctx: object) -> bytes: # pylint: disable=W0613 ass...
fa9e03d5b3f5a4f594db29eae057607f790e158c
3,654,738
def entmax15(X, axis=-1, k=None): """1.5-entmax: normalizing sparse transform (a la softmax). Solves the optimization problem: max_p <x, p> - H_1.5(p) s.t. p >= 0, sum(p) == 1. where H_1.5(p) is the Tsallis alpha-entropy with alpha=1.5. Parameters ---------- X : paddle.Tensor ...
08887ec5aff323077ea6ea99bf6bd2b83bb4cc19
3,654,739
def get_dependency_graph(node, targets=None): """Returns the dependent nodes and the edges for the passed in node. :param str node: The node to get dependencies for. :param list targets: A list with the modules that are used as targets. :return: The dependency graph info. :rtype: GraphInfo """...
39667e034379477086062a9032f5007c12aba30e
3,654,740
from pathlib import Path def is_submodule_repo(p: Path) -> bool: """ """ if p.is_file() and '.git/modules' in p.read_text(): return True return False
26675ee25e431778325081ec80d45ff3d72c2046
3,654,741
def shift_contig(df2, remove): """ The function append shifted fragment from sort_cluster_seq function. Parameters ---------- df2 : pandas DataFrame DataFrame NRPS cluster fragment. remove : list List of cluster fragment, which should removed. Returns ------- df...
7df891785fc58d818af5b423c7fdbc3c4382951f
3,654,742
def _bocs_consistency_mapping(x): """ This is for the comparison with BOCS implementation :param x: :return: """ horizontal_ind = [0, 2, 4, 7, 9, 11, 14, 16, 18, 21, 22, 23] vertical_ind = sorted([elm for elm in range(24) if elm not in horizontal_ind]) return x[horizontal_ind].reshape((I...
bd8fe5261e024f5d5cdf1a2d77229dd564d947bf
3,654,744
def get_document(name, key): """Get document from Database""" constructor = Constructor() inst_coll = constructor.factory(kind='Collection', name=name) inst_doc = Document(inst_coll) doc = inst_doc.get_document(key) return doc
acd4e8117c0002d323a4fad79704a33437481657
3,654,745
from datetime import datetime import json def predict() -> str: """predict the movie genres based on the request data""" cur = db_connection.cursor() try: input_params = __process_input(request.data) input_vec = vectorizer.transform(input_params) prediction = classifier.predict(inp...
0ae49a8ab05d1df1c0beb07f322262a7a7ac8ee2
3,654,746
def SignificanceWeights(serializer, decay): """Multiplies a binary mask with a symbol significance mask.""" def significance_weights(mask): # (repr,) -> (batch, length, repr) # significance = [0, 1, 2] significance = serializer.significance_map assert significance.shape[0] == mask.shape[2] # sig...
545ac45149b8653f502d2dd864f92a40ee5919cb
3,654,747
def check_fun_inter_allocation(fun_inter, data, **kwargs): """Check allocation rules for fun_inter then returns objects if check""" out = None check_allocation_fun_inter = get_allocation_object(data, kwargs['xml_fun_inter_list']) if check_allocation_fun_inter is None: check_fe = check_fun_elem_d...
61f17844953f3260a23aff35a2f090a028dd9212
3,654,748
from typing import Optional def kernel_bw_lookup( compute_device: str, compute_kernel: str, caching_ratio: Optional[float] = None, ) -> Optional[float]: """ Calculates the device bandwidth based on given compute device, compute kernel, and caching ratio. Args: compute_kernel (str)...
efd70d5c2e5fc9295bccbfb05113474ac40ff1c9
3,654,749
def create_container( container_image: str, name: str = None, volumes: t.List[str] = None, ) -> str: """Create a new working container from provided container image. Args: container_image (str): The container image to start from. name (str, optional): The container name. vol...
be50e84169e5d3df5dfd9730493d7daa9788049b
3,654,751
def single_data_path(client, node_id): """ In order for a shrink to work, it should be on a single filesystem, as shards cannot span filesystems. Return `True` if the node has a single filesystem, and `False` otherwise. :arg client: An :class:`elasticsearch.Elasticsearch` client object :rtype:...
ae0b34f82acb6d12faf525f0270250cdf471a6f8
3,654,752
def sortorder(obj): """ Trys to smartly determine the sort order for this object ``obj`` """ if hasattr(obj, 'last'): return obj.last.timestamp() if isinstance(obj, str): # First assume pure numeric try: return float(obj) except ValueError: pa...
674ee77a87ccd7a0bd89a88b88a2682926a1135e
3,654,753
import json import re def get_more_details_of_post(post_url: str) -> json: """ :param post_url: the url of an imgur post :return: Details like Virality-score, username etc in JSON format """ details = {} try: request = HTMLSession().get(post_url) # some times, request isn't pr...
dd3d622c8a7e8f61daf24c2d0cc6752323d4693e
3,654,754
import struct import hmac import hashlib def subkey_public_pair_chain_code_pair(public_pair, chain_code_bytes, i): """ Yield info for a child node for this node. public_pair: base public pair chain_code: base chain code i: the index for this node. Returns a pair (new_...
8f31eb0ae3b063964ff46bcf6c78431d39d0e2ba
3,654,755
from typing import Optional def get_registry_description(metaprefix: str) -> Optional[str]: """Get the description for the registry, if available. :param metaprefix: The metaprefix of the registry :return: The description for the registry, if available, otherwise ``None``. >>> get_registry_descripti...
12b7aac7f880d6699ca85add1065eca49a06d278
3,654,756
import tqdm def evaluate(model, valid_exe, valid_ds, valid_prog, dev_count, metric): """evaluate """ acc_loss = 0 acc_top1 = 0 cc = 0 for feed_dict in tqdm.tqdm( multi_device(valid_ds.generator(), dev_count), desc='evaluating'): if dev_count > 1: loss, top1 = valid_...
7b228e7cadd71ec1ac31436767b92c4dadb5ec53
3,654,757
def _get_rank(player): """Get the rank of a player""" cursor = _DB.cursor() try: cursor.execute("SELECT score FROM scores WHERE player = ?", (player.lower(),)) rows = cursor.fetchall() if not rows: return 0 ps = rows[0][0] cursor.execute("SELECT count(*) F...
e556b9fb75f6b40c8c1be8759255dfc5953a1e9a
3,654,758
import pydoc def spec(func): """return a string with Python function specification""" doc = pydoc.plain(pydoc.render_doc(func)) return doc.splitlines()[2]
00b96364f77141fedd7d50396946fd4e29cc5d02
3,654,760
import posixpath def IsVirus(mi, log): """Test: a virus is any message with an attached executable I've also noticed the viruses come in as wav and midi attachements so I trigger on those as well. This is a very paranoid detector, since someone might send me a binary for valid reasons. I white-...
e30e91951ad49395d87bef07926cfdff4d15b3e2
3,654,763
def to_curl(request, compressed=False, verify=True): """ Returns string with curl command by provided request object Parameters ---------- compressed : bool If `True` then `--compressed` argument will be added to result """ parts = [ ('curl', None), ('-X', request.me...
b462f62031f4fe757bb7a45b50ced9bc2ea6a9b5
3,654,764
def prox_trace_indicator(a, lamda): """Time-varying latent variable graphical lasso prox.""" es, Q = np.linalg.eigh(a) xi = np.maximum(es - lamda, 0) return np.linalg.multi_dot((Q, np.diag(xi), Q.T))
85d6cb26c7a35dbab771e0a9f9c8979fba90e680
3,654,765
def get_gamma_non_jitted(esys): """Get log gamma Returns ------- float[:] """ if isinstance(esys.species[0].logc, float): v = np.empty(len(esys.species)) else: v = np.empty(len(esys.species), dtype=object) for i, sp in enumerate(esys.species): v[i] = 10.0 ** (sp....
f3d7f4b96676a10b7065196aac247006019da31e
3,654,766
def active_matrices_from_extrinsic_euler_angles( basis1, basis2, basis3, e, out=None): """Compute active rotation matrices from extrinsic Euler angles. Parameters ---------- basis1 : int Basis vector of first rotation. 0 corresponds to x axis, 1 to y axis, and 2 to z axis. ...
50218d9ce2296e3c4952cc77fe64e30c19e03f77
3,654,767
def runQuery(scenarioID): """ Run a query that aquires the data from the lrs for one specific dialoguetrainer scenario \n :param scenarioID: The id of the scenario to request the data from \t :type scenarioID: int \n :returns: The data for that scenario or error \t :rtype: [Dict<string, mixe...
0f57a4468354680b315a65263593979149bdb186
3,654,769
def is_spaceafter_yes(line): """ SpaceAfter="Yes" extracted from line """ if line[-1] == "_": return False for ddd in line[MISC].split("|"): kkk, vvv = ddd.split("=") if kkk == "SpaceAfter": return vvv == "Yes" raise ValueError
5693c8874ec9676bf19d9b1cb7ead5c1772a3f0b
3,654,770
def linear_scheduler(optimizer, warmup_steps, training_steps, last_epoch=-1): """linear_scheduler with warmup from huggingface""" def lr_lambda(current_step): if current_step < warmup_steps: return float(current_step) / float(max(1, warmup_steps)) return max( 0.0, ...
d9446ede5be0ed981ae00b0bccd494017057d834
3,654,771
from functools import reduce import operator from re import X def MajorityVoteN(qubits, nrounds, prep=[], meas_delay=1e-6, add_cals=False, calRepeats=2): """ Majority vote across multiple measurement results (same or dif...
7bc3b6161d5224ed7adf9248b32b0bd283f50c70
3,654,772
def getRatios(vect1, vect2): """Assumes: vect1 and vect2 are equal length lists of numbers Returns: a list containing the meaningful values of vect1[i]/vect2[i]""" ratios = [] for index in range(len(vect1)): try: ratios.append(vect1[index]/vect2[index]) excep...
e28f871986ab2b1b87cc3671b1c27ad14a0aadf8
3,654,773
def sampleset(): """Return list with 50 positive and 10 negative samples""" pos = [(0, i) for i in range(50)] neg = [(1, i) for i in range(10)] return pos + neg
77e5a0ca3ad8757f0ded2aec9d73312a66ac9044
3,654,774
def recognize_emotion(name, mode, dataset): """ The main program for building the system. And we support following kinds of model: 1. Convolutional Neural Network (CNN) 2. Support Vector Machine (SVM) 3. Adaboost 4. Multilayer Perceptron (MLP) Args: ...
eae092866f5190a637bbdb08c4ad7188b9cb88f3
3,654,775
def feedback(request): """ Feedback page. Here one can send feedback to improve the website further. """ return render(request, "groundfloor/common/feedback.html", context = None)
8dd9f8ae57ca49629820c58b54c7d98d705597bb
3,654,776
from typing import Tuple def fill_nodata_image(dataset: xr.Dataset) -> Tuple[np.ndarray, np.ndarray]: """ Interpolate no data values in image. If no mask was given, create all valid masks :param dataset: Dataset image :type dataset: xarray.Dataset containing : - im : 2D (row,...
c245f0cbfbb79737fb85b9b8fb8381aad6373926
3,654,777
def find(value, a_list): """ TestCase for find >>> find(26, [12,14]) True >>> find(40, [14, 15, 16, 4, 6, 5]) False >>> find(1, [1]) False >>> find(1, []) False >>> find(4, [2, 3, 2]) True """ # 现将列表变为<value, index>字典 if a_list is None or len(a_list) < 2: ...
dd466a8ffa0c760ed0af9ad109b5f4e3b85a62db
3,654,778
def transform_bbox( bbox, source_epsg_code, target_epsg_code, all_coords=False ): """ Transform bbox from source_epsg_code to target_epsg_code, if necessary :returns np.array of shape 4 which represent the two coordinates: left, bottom and right, top. When `all_coords` is set to...
cd6938b2dfcc02fe9c2a323e2b60339de216dd26
3,654,779
def distance_metric(vector1, vector2): """ Returns a score value using Jaccard distance Args: vector1 (np.array): first vector with minHash values vector2 (np.array): second vector with minHash values Returns: float: Jaccard similarity """ return distance.pdist(np.array([ve...
e1acbc9eff7ee8bc78be0307acacbca9e9d69265
3,654,780
from datetime import datetime def update_calendar(request): """ to update an entry to the academic calendar to be updated. @param: request - contains metadata about the requested page. @variables: from_date - The starting date for the academic calendar event. to_date - The en...
804f3f0443d192c0c18a501c40808f2406596491
3,654,781
def get_section(entry: LogEntry) -> str: """returns the section of the request (/twiki/bin/edit/Main -> /twiki)""" section = entry.request.split('/')[:2] return '/'.join(section)
dee463b5a662846da01fc2ef8d1c72c5b582e7e5
3,654,782
def reverse_lookup(d, v): """ Reverse lookup all corresponding keys of a given value. Return a lisy containing all the keys. Raise and exception if the list is empty. """ l = [] for k in d: if d[k] == v: l.append(k) if l == []: raise ValueError else: ...
d68f437aec47df964905779f99d58be84515fb72
3,654,783
def compile_channels_table(*, channels_meta, sources, detectors, wavelengths): """Compiles a NIRSChannelsTable given the details about the channels, sources, detectors, and wavelengths. """ table = NIRSChannelsTable() for channel_id, channel in channels_meta.items(): source_label = sources.l...
ac3099ef0440962b3fbfeec36f01ae92061b5693
3,654,784
from pathlib import Path def cpe2pkg_tool(): """Unsupported ecosystem CVE fixture.""" bin = Path(__file__).parent.parent / Path('tools/bin/cpe2pkg.jar') if bin.exists(): return str(bin) else: raise RuntimeError('`cpe2pkg.jar` is not available, please run `make build-cpe2pkg once.`')
7ad5489cd560f2820a5e77c46964514a5a34edc9
3,654,785
import threading def spawn_thread(func, *args, **kwds): """ Utility function for creating and starting a daemonic thread. """ thr = threading.Thread(target=func, args=args, kwargs=kwds) thr.setDaemon(True) thr.start() return thr
afaace7e02870390acb297106ac9d35c9a931a59
3,654,786
import uuid def get_thread_replies(parent_id): """ Get all replies to a thread If the thread does not exist, return an empty list :param parent_id: Thread ID :return: replies to thread """ assert type(parent_id) is uuid.UUID, """parent_id is not correct type""" reply_query = Query() ...
1b167dcc4ab09d50cda9feb478c8f1a4d0399e96
3,654,788
import torch def compute_acc(pred, labels): """ Compute the accuracy of prediction given the labels. """ return (torch.argmax(pred, dim=1) == labels).float().sum() / len(pred)
1b1ad83b9b4ae06f2bc80209e4e7339a421a39f3
3,654,789
async def read_update_status() -> str: """Read update status.""" return ( await cache.get(Config.update_status_id()) if await cache.exists(Config.update_status_id()) else "ready_to_update" )
0e80f7065665dbe1a41e59fe7c65904e58bb6d8f
3,654,790
def PCopy (inFA, err): """ Make copy an GPUFArray returns copy * inFA = input Python GPUFArray * err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inFA): print("Actually ",inFA.__class_...
df1047dc143fb5f8d8f4fd88a2b1ebc0904620a2
3,654,792
def _get_statuses(policy_type_id, policy_instance_id): """ shared helper to get statuses for an instance """ _instance_is_valid(policy_type_id, policy_instance_id) prefixes_for_handler = "{0}{1}.{2}.".format(HANDLER_PREFIX, policy_type_id, policy_instance_id) return list(SDL.find_and_get(A1NS, p...
fdddc26d3c2b65834d4b047a5565894b0d965f9d
3,654,793
def phase_lines(graph): """ Determines the phase lines of a graph. :param graph: Graph :return: dictionary with node id : phase in cut. """ if has_cycles(graph): raise ValueError("a cyclic graph will not have phaselines.") phases = {n: 0 for n in graph.nodes()} q = graph.nodes(in_deg...
9f1aab9e487bd258c88b0f149bcf613341945879
3,654,794
def BCELossConfig(argument_parser): """ Set CLI arguments :param argument_parser: argument parser :type argument_parser: ```ArgumentParser``` :returns: argument_parser :rtype: ```ArgumentParser``` """ argument_parser.description = """Creates a criterion that measures the Binary Cross E...
d0108459bdad9b2f6fad438bff542624b482ef7d
3,654,797
def gen_cities_avg(climate, multi_cities, years): """ Compute the average annual temperature over multiple cities. Args: climate: instance of Climate multi_cities: the names of cities we want to average over (list of str) years: the range of years of the yearly averaged temperature ...
9609add6a1514d09b42e2494e56c84522d3cb364
3,654,798
def tangentVectorsOnSphere( points, northPole = np.array([0.0,0.0,1.0]) ): """ Acquire a basis for the tangent space at given points on the surface of the unit sphere. :param points: N x 3 array of N points at which to acquire basis of tangent space. :param northPole: 3 array of point correspondin...
bfa23a393ac4d1b38c6c2b19207520db1bd83e03
3,654,799
import tkinter def _colorvar_patch_destroy(fn): """Internal function.\n Deletes the traces if any when widget is destroy.""" def _patch(self): """Interanl function.""" if self._tclCommands is not None: # Deletes the widget from the _all_traces_colorvar # and delete...
d38380316932d8ff2fee8bed8b931b5567588774
3,654,800
def pres_from_hybrid(psfc, hya, hyb, p0=100000.): """Return pressure field on hybrid-sigma coordinates, assuming formula is p = a(k)*p0 + b(k)*ps. """ return hya*p0 + hyb*psfc
4ebd90fb807ab9ea4c2b45d27da6f8b420c107f7
3,654,802
import urllib def url_exist(file_url): """ Check if an url exist Parameters ---------- file_url : string url of www location Returns ------- verdict : dtype=boolean verdict if present """ try: urllib.request.urlopen(file_url).code == 200 retu...
717ee7073ab56e8611eb46f042ab7c18f2db0f33
3,654,803
from scipy import stats def chi_square(observed, expected): """ Compute the chi square test """ # glen cowan pp61 temp = [] for (n, nu) in zip(observed, expected): if nu != 0: temp += [((n - nu) ** 2) / nu] # compute p value mychi = sum(temp) p = stats.chi2.sf(...
4b0577ec4e4b4dc6b99b00a54e78f1014b9cf93a
3,654,804
def theta_8(p, q, h, phi, a, b): """Lower limit of integration for the case rho > a, rho > b.""" result = np.arctan(r_8(p, q, phi, a, b)/h) return(result)
913ceb462885fba93cbdb6bddaa5523c119821bc
3,654,806
def collect_genewise(fst_file, file_name, gene_names, gene_to_fst): """take in the file name, opens it. populates a dictionary to [gene] = fst file_name = defaultdict(str) FBgn0031208 500000 16 0.002 21.0 1:2=0.05752690 """ file_name = file_name.split("_gene")[0] f_in = open(fst_file, "r") ...
ea62da67a7084103859244bf7f192c2f4433124c
3,654,807
import torch def bbox_overlaps_batch(anchors, gt_boxes): """ :param anchors: (N, 4) ndarray of float :param gt_boxes: (b, K, 5) ndarray of float :return: (N, K) ndarray of overlap between boxes and query_boxes """ batch_size = gt_boxes.size(0) if anchors.dim() == 2: N = anchors...
cc5a88e6a1d5cd42b1827091cbee311e4f33bbb6
3,654,808
from typing import Tuple from typing import Callable from typing import Any import re def extract_curve_and_test(curve_names: str, name: str) -> Tuple[str, Callable[[Any], bool]]: """Return a curve and a test to apply for which of it's components to twist.""" twist_match = re.match(rf"(?P<curve>[{curve_names...
e4849ff7145bae0c2c900d0aa747ec7a14fb96ac
3,654,809
import numpy def psf_gaussian(psf_shape, psf_waist, psf_physical_size=1, psf_nphoton=2): """Return 3D gaussian approximation of PSF.""" def f(index): s = psf_shape[index] // 2 * psf_physical_size c = numpy.linspace(-s, s, psf_shape[index]) c *= c c *= -2.0 / (psf_waist[index] ...
77ccab6aaa141564751a0eafd13398f904673006
3,654,810
def get_employee_record(id_num): """Gets an employee's details if record exists. Arguments: id_num -- ID of employee record to fetch """ if not id_num in names or not id_num in cities: return 'Error viewing record' return f'{id_num} {names[id_num]} {cities[id_num]}'
108b6e3482022e8e65e09bda1dd8a78ca7850cfe
3,654,811
def list_aliases(): """ Gets the list of aliases for the current account. An account has at most one alias. :return: The list of aliases for the account. """ try: response = iam.meta.client.list_account_aliases() aliases = response['AccountAliases'] if len(aliases) > 0: ...
13fa5d4ded6811bbcbd6062cf7f690b08c41354e
3,654,812
def MapToSingleIncrease(val): """ Need 30 minute values to be sequential for some of the tools(i.e. 1,2,3,4) so using a format like 5,10,15,20 won't work. """ return val/5
fe89d7ccb8bef511e2ad90a07ad0346c58ba894d
3,654,813
def get_columns_for_table(instance, db, table): """ Get a list of columns in a table Args: instance - a hostAddr object db - a string which contains a name of a db table - the name of the table to fetch columns Returns A list of columns """ conn = connect_mysql(instance) cursor...
567a7e3e6ebbf33cee3cb088e1725bd2b11edcef
3,654,814
def registra_aluno(nome, ano_entrada, ano_nascimento, **misc): """Cria a entrada do registro de um aluno.""" registro = {'nome': nome, 'ano_entrada': ano_entrada, 'ano_nascimento': ano_nascimento} for key in misc: registro[key] = misc[key] return registro
e56da99ec90de9ebca204ccc3c3f3555b9bbbc64
3,654,815
def create_small_table(small_dict): """ Create a small table using the keys of small_dict as headers. This is only suitable for small dictionaries. Args: small_dict (dict): a result dictionary of only a few items. Returns: str: the table as a string. """ keys, values = tuple...
08da78580fbf4cee8c30acb21ce7fa928a9c17b1
3,654,818
def get_normalized_list_for_every_month(variable_r, list_of_ranges_r, tags_r): """ :param variable_r: big list with all the data [sizes][months] :param list_of_ranges_r: sorted list of range (sizes...Enormous, etc.) :return: normalized list for each month (numbers are percentage respect to the total by...
4a3b837e6bf254dbd3255a8ca0a5d103d34bd2a9
3,654,819
def mark_as_possible_cluster_member(g, possible_cluster_member, cluster, confidence, system, uri_ref=None): """ Mark an entity or event as a possible member of a cluster. :param rdflib.graph.Graph g: The underlying RDF model :param rdflib.term.URIRef possible_cluster_member: The entity or event to mark...
851da7d12781723c7c2fb4bc13ac14172c890daf
3,654,820
def twodcontourplot(tadata_nm, tadata_timedelay, tadata_z_corr): """ make contour plot Args: tadata_nm: wavelength array tadata_timedelay: time delay array tadata_z_corr: matrix of z values """ timedelayi, nmi = np.meshgrid(tadata_timedelay, tadata_nm) # find the maxi...
2e8850e1c8153c9c307ff785ddd1d1d127163190
3,654,821
def make_example_dags(module_path): """Loads DAGs from a module for test.""" dagbag = DagBag(module_path) return dagbag.dags
ffc2fd47bbee7d2124da199d6b5101103500fbf2
3,654,822
def count_good_deals(df): """ 7. Считает число прибыльных сделок :param df: - датафрейм с колонкой '<DEAL_RESULT>' :return: - число прибыльных сделок """ # http://stackoverflow.com/questions/27140860/count-occurrences-of-number-by-column-in-pandas-data-frame?rq=1 return (df['<DEAL_RESULT...
1f3ef9b9e0f7924d45d5ce84a77938f19386b6bc
3,654,823
import time import itertools import sh def match_lines_by_hausdorff(target_features, match_features, distance_tolerance, azimuth_tolerance=None, length_tolerance=0, match_features_sindex=None, match_fields=False, match_stats=False, field_suffixes=('', '_match'), match_strings=None, constrain_target_features...
d9c08e8e156a525495a03e5e9d6881c33ecdf0a2
3,654,824
def create_anchors_3d_stride(grid_size, voxel_size=[0.16, 0.16, 0.5], coordinates_offsets=[0, -19.84, -2.5], dtype=np.float32): """ Args: feature_size: list [D, H, W](zyx) sizes: [N, 3] list of list or array,...
129e54a855bbacb2026eb08b5741ab70dd0374f4
3,654,828
def combined_roidb(imdb_names): """ Combine multiple roidbs """ def get_roidb(imdb_name): imdb = get_imdb(imdb_name) print('Loaded dataset `{:s}` for training'.format(imdb.name)) imdb.set_proposal_method("gt") print('Set proposal method: {:s}'.format("gt")) roidb...
4660a6ffff11511c449629c9fdb7f5d566a886f9
3,654,829
from re import A def render_locations_profile(list_id, item_id, resource, rfields, record): """ Custom dataList item renderer for Locations on the Profile Page - UNUSED @param list_id: the HTML ID of the list @param item_id: the HTML ID of the item @param resource: the S3R...
dbec0b41b16fa48996a735372bfb001b386c7300
3,654,830
def exception_log_and_respond(exception, logger, message, status_code): """Log an error and send jsonified respond.""" logger.error(message, exc_info=True) return make_response( message, status_code, dict(exception_type=type(exception).__name__, exception_message=str(exception)), ...
c784efd4b8adbbc463ff1d2a499ffd598253349d
3,654,832
import re def parse_cdhit_clusters(cluster_file): """ Parses cdhit output into three collections in a named tuple: clusters: list of lists of gene ids. reps: list of representative gene for each cluster lookup: dict mapping from gene names to cluster index In this setup, cluster ids are...
fe0634c1991f0bd687f8be675ff15cb3290c919c
3,654,833
import torch def evaluate(model: nn.Module, dataloader: DataLoader) -> Scores: """ Evaluate a model without gradient calculation :param model: instance of a model :param dataloader: dataloader to evaluate the model on :return: tuple of (accuracy, loss) values """ score = 0 loss = 0 ...
f23fbd72a24122b3a665f29918c52bbd5515d204
3,654,834
from operator import and_ def remote_judge_get_problem_info(problem_id: str, contest_id: int = -1, contest_problem_id: int = -1): """ { "code":0, "data":{ "isContest":"是否在比赛中", "problemData":{ "title":"题目名", "content":"题目内容", ...
aa7f8100bc7516659cf535e0fa7222b6f7b1a065
3,654,835
def can_write(obj, user): """ Takes article or related to article model. Check if user can write article. """ return obj.can_write(user)
9cb7cc046b63fb82670c4667abe169d6a1a279e4
3,654,836
def create_external_question(url: str, height: int) -> str: """Create XML for an MTurk ExternalQuestion.""" return unparse({ 'ExternalQuestion': { '@xmlns': 'http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd', 'ExternalURL': url, ...
d249e82225ab2c1546bd871c166e9b683622a15d
3,654,837
def credentials_batch_account_key_secret_id(config): # type: (dict) -> str """Get Batch account key KeyVault Secret Id :param dict config: configuration object :rtype: str :return: keyvault secret id """ try: secid = config[ 'credentials']['batch']['account_key_keyvault_s...
4e7cfb100c2d50ef13d47295ff0b5bb0e3351986
3,654,838
import re def is_C2D(lname): """ """ pattns = ['Conv2D'] return any([bool(re.match(t,lname)) for t in pattns])
a12bfd9857543e568148659f782615b3f2de4b83
3,654,839
def encounter_media(instance, filename): """Return an upload file path for an encounter media attachment.""" if not instance.encounter.id: instance.encounter.save() return 'encounter/{0}/{1}'.format(instance.encounter.source_id, filename)
79e4d8fae1d41edf362e99e6da11442a71565aa0
3,654,840
from datetime import datetime def time_range_cutter_at_time(local,time_range,time_cut=(0,0,0)): """ Given a range, return a list of DateTimes that match the time_cut between start and end. :param local: if False [default] use UTC datetime. If True use localtz :param time_range: the TimeRa...
57e851fb5b6ae8873dde5719dec668c25561f687
3,654,842
def _darknet_conv( x: np.ndarray, filters: int, size: int, strides: int = 1, batch_norm: bool = True ) -> tf.Tensor: """create 1 layer with [padding], conv2d, [bn and relu]""" if strides == 1: padding = "same" else: x = ZeroPadding2D(((1, 0), (1, 0)))(x) # top left half-padding ...
f58153aa0c8af8df93289b872309f1c907941848
3,654,843
def _build_topic_to_consumer_topic_state_map(watermarks): """Builds a topic_to_consumer_topic_state_map from a kafka get_topics_watermarks response""" return { topic: ConsumerTopicState({ partition: int((marks.highmark + marks.lowmark) / 2) for partition, marks in watermarks_...
78ef0710e4823031ad079313484dba0eacc37135
3,654,844
from typing import Optional def elgamal_keypair_from_secret(a: ElementModQ) -> Optional[ElGamalKeyPair]: """ Given an ElGamal secret key (typically, a random number in [2,Q)), returns an ElGamal keypair, consisting of the given secret key a and public key g^a. """ secret_key_int = a if secret_...
35de350b6bb434e1bb3d2c52d90f9a96be72dc1f
3,654,845
def current_default_thread_limiter(): """Get the default `~trio.CapacityLimiter` used by `trio.to_thread.run_sync`. The most common reason to call this would be if you want to modify its :attr:`~trio.CapacityLimiter.total_tokens` attribute. """ try: limiter = _limiter_local.get() e...
7abec5d74b9cfdaa663fd432587ea19440b7132f
3,654,846
import copy def _mask_board(board): """ A function that copies the inputted board replaces all ships with empty coordinates to mask them. :param board: a 2D numpy array containing a string representation of the board. All ships should be visible. :return: a 2D numpy array containing a string represent...
c6832c90ac96d61563e37482773abf627d92a05a
3,654,847
def remove_head_id(ref, hyp): """Assumes that the ID is the begin token of the string which is common in Kaldi but not in Sphinx.""" ref_id = ref[0] hyp_id = hyp[0] if ref_id != hyp_id: print('Reference and hypothesis IDs do not match! ' 'ref="{}" hyp="{}"\n' 'Fil...
210798e8a02f555f70a1d9f2de9ce098dd0669fb
3,654,849
def convert_image_np(inp): """Convert a Tensor to numpy image.""" inp = inp.numpy().transpose((1, 2, 0)) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) return inp
446feda40cc6698b5cbc80c3b14fa3212ef2800b
3,654,850
def get_miner_day_list(): """ 存储提供者每天的miner数据 :return: """ miner_no = request.form.get("miner_no") date = request.form.get("date") data = MinerService.get_miner_day_list(miner_no, date) return response_json(data)
4fd523e8855ba498a1d694e532d27c863e7f9407
3,654,851
def get_notebook_logs(experiment_id, operator_id): """ Get logs from a Experiment notebook. Parameters ---------- experiment_id : str operator_id : str Returns ------- dict or None Operator's notebook logs. Or None when the notebook file is not found. """ notebook =...
d98865cdbca25839bb6010ab5e726fd35d162ada
3,654,852
from typing import Callable def modify_env2( function: Callable[[_UpdatedType], _SecondType], ) -> Kinded[Callable[ [Kind2[_Reader2Kind, _FirstType, _SecondType]], Kind2[_Reader2Kind, _FirstType, _UpdatedType], ]]: """ Modifies the second type argument of a ``ReaderBased2``. In other words, i...
5ed2c5deaaa376e4884f31e3ba08d3b2839cc1a5
3,654,853
def model_trees(z, quantiles, normed=False, dbhfile='c:\\projects\\MLM_Hyde\\Data\\hyde_runkolukusarjat.txt', plot=False, biomass_function='marklund'): """ reads runkolukusarjat from Hyde and creates lad-profiles for pine, spruce and decid. Args: z - g...
ba3c1ea345031a8b5434e1dd4f005b1c2c1e74ce
3,654,854
def inject_general_timeline(): """This function injects the function object 'Tweet.get_general_timeline' into the application context so that 'get_general_timeline' can be accessed in Jinja2 templates. """ return dict(get_general_timeline=Tweet.get_general_timeline)
56b395da0facda561061c8f63eb3eb26c07f3605
3,654,855
def get_vaccinated_model(model, area=None): """Get all states that can be vaccinated or recovered (by area). Parameters ---------- model : amici.model Amici model which should be evaluated. areas : list List of area names as strings. Returns ------- states : list ...
c03a9d048abb08561463b1975ffec663f24267b3
3,654,857
from datetime import datetime def MicrosecondsToDatetime(microseconds): """Returns a datetime given the number of microseconds, or None.""" if microseconds: return datetime.utcfromtimestamp(float(microseconds) / 1000000) return None
69fd3dc3b8d1a97e7a64037cabe988365b2c6e63
3,654,858