content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def find_min_max(data): """Solution to exercise C-4.9. Write a short recursive Python function that finds the minimum and maximum values in a sequence without using any loops. """ n = len(data) min_val = data[0] max_val = data[0] def recurse_minmax(idx): nonlocal min_val, max_v...
b8f50d1dafa0f66ab61db8d4974c8d201cd4dc3c
3,617,800
def generate_T3_uvh5(name, pt_dec, tstart, ntint, nfint, filelist, params=T3PARAMS, start_offset=None, end_offset=None): """Generates a measurement set from the T3 correlations. Parameters ---------- name : str The name of the measurement set. pt_dec : quantity The pointing declinat...
c0714aa0ec61c8c5762424f8a5d3f3434237c978
3,617,801
import torch from functools import reduce def mask_with_tokens(t, token_ids): """ 用记号遮掩 """ init_no_mask = torch.full_like(t, False, dtype=torch.bool) mask = reduce(lambda acc, el: acc | (t == el), token_ids, init_no_mask) # print("mask",mask) return mask
f233f2e2111e02919ff3795820f024b0e5b850a1
3,617,802
def isStandard(descriptorType): """ >>> isStandard(0x0a) True >>> isStandard(0x22) False >>> isStandard(0x61) False >>> isStandard(0x1a) True """ # See USB Common Class Specification s. 3.11 for this field's structure # Bit 7: reserved # Bits 6..5: descriptor type ...
a4e002e58c07638cb14d1a13a27ac7232af140cf
3,617,803
def split_test(df, test_method='fo', test_size=.2): """ method of splitting data into training data and test data Parameters ---------- df : pd.DataFrame raw data waiting for test set splitting test_method : str, way to split test set 'fo': split by ratio ...
8256a16f3f73f42e06c7b28f34295a39dc8e2091
3,617,804
def store_bot_config(host, content): """Stores a new version of bot_config.py. Returns the ndb.Key of the new stored entity. """ if not _validate_python(content): raise ValueError('Invalid python') # The memcache entry will be cleared out automatically after 60s. Try a best # effort. signature = _get...
2930b24b764e9b931f0c36fa921d6c4c2d1a3772
3,617,805
def equals(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when t...
9a9951ee08251cebfda90d52e4e1e04bb2510a5b
3,617,806
def binary_close(fig, size=5): """ Joins unconnected pixel by dilation and erosion""" selem = disk(size) img = pad(fig.img, size, mode='constant') img = binary_closing(img, selem) img = crop_skimage(img, size) return Figure(img, raw_img=fig.raw_img)
98a4c5393a7010eef7ff7e6f94a08fe359600d08
3,617,807
def build_delete_item(obj): """Build div tag for delete details""" parent = "None" if obj.parent is not None: parent = obj.parent.name return ( "<ul><li>Serial: %s</li><li>Subject: %s</li><li>Parent: %s</li><li>Description: %s</li>" "<li>x509 Extension: %s</li><li>Created: %s</...
f1bb11f2bec57035abea6667a05127d856086b61
3,617,808
def get_user_token(user, purpose, minutes_valid): """Return login token info for given user.""" token = ''.join( dumps([ user.get_username(), get_auth_hash(user, purpose), ]).encode('base64').split('\n') ) return { 'id': get_meteor_id(user), 'token...
a2706da9fe38b10c85815c8a6d2a821e27004b3d
3,617,809
def commonChild(s1, s2): """ Finds the longest substrings of s1 and s2 that match and returns its length. """ # Traceback approach only needs to hold two rows of s2 (we assume characters in s2 make up the columns) tb = [[0 for _ in s2] for _ in range(2)] # DEBUG_MATRIX(s1, s2, tb) # Loop ...
8eab93652e9dc1f1b41b937dd7a401efd39f156f
3,617,810
def cell_content_to_str(v): """ Convert the value of a cell to string :param v: Value of a cell :return: """ if v: if isinstance(v, float) or isinstance(v, int): return str(int(v)) else: return str(v).strip() else: return None
b73746d735ed155d387512704b91fc92c0c93560
3,617,811
def create_haar_state(num_qubits: int): """Create a random Haar quantum state Args: num_qubits (int): number of qubits Returns: qiskit.QuantumCircuit """ psi = 2*np.random.rand(2**num_qubits)-1 psi = psi / np.linalg.norm(psi) qc = qiskit.QuantumCircuit(num_qubits, num_qubit...
aa9be2e086f20daaf6597bf726e148fecbf4b9ae
3,617,812
def partition_layers(layers, split=2): """ partitions the each layer of a list according to the layer # and number of elements """ layers_partitioned = [] for i in range(len(layers)): num_parts = split ** i layer_partitioned = partition_list(layers[i], num_parts) layers_partitioned....
be76def26a41488203540b257e1ded0d279bbdb8
3,617,813
import os def enter_file(file_type, file_path=""): """Request file path from user until path exists. Parameters ---------- file_type: str Type of file to display in input line file_path: str (optional) Initial file path to try """ while not os.path.exists(file_path): ...
7470761a3b41eedd7a6d98f088b7a693bfd7428a
3,617,814
def __hamming_distance_with_hash(dhash1, dhash2): """ *Private method* 根据dHash值计算hamming distance :param dhash1: str :param dhash2: str :return: 汉明距离(int) """ difference = (int(dhash1, 16)) ^ (int(dhash2, 16)) return bin(difference).count("1")
c8a28a3f20a037fe9e96bfe82cb522caf6600337
3,617,815
def _van_es_entropy(X, m): """Compute the van Es estimator as described in [6].""" # No equation number, but referred to as HVE_mn. # Typo: there should be a log within the summation. n = X.shape[-1] difference = X[..., m:] - X[..., :-m] term1 = 1/(n-m) * np.sum(np.log((n+1)/m * difference), axi...
90143d9395bf3851a848ac6f0e0349a5131349fb
3,617,816
def insert_coke(message): """Function to add ingested coke. Parameters ---------- message : telebot.types.Message The message object. Returns ------- msg : success or failure message - to be displayed at Telegram's chat. """ message_text = message.text.lower().split(' ') ...
95e97edd600351a1f1e828d01bad17b37cd94263
3,617,817
def safelyexecutenativecode(binary_file_name, arglist): """ <Purpose> Experimental! Executes code in an arbitrary programming language that was compiled using the toolchain. <Arguments> binary: The file name of the binary to launch. arglist: A list of strings that should be used as the comman...
507679c1cc30534e61b4486f9ceb215984443a1e
3,617,818
async def async_browse_media( hass: HomeAssistant, media_content_type: str, media_content_id: str, cast_type: str, ) -> BrowseMedia | None: """Browse media.""" if media_content_type != DOMAIN: return None try: get_url(hass, require_ssl=True, prefer_external=True) except ...
333ee495d5a0be9f3ce1957473aa0f6e5ded09ad
3,617,819
def is_internal_ip(ip): """ 判断是否为内网ip :param ip: :return: """ if ip in ('127.0.0.1', '0.0.0.0', 'localhost'): return True ip = ip_into_int(ip) net_a = ip_into_int('10.255.255.255') >> 24 net_b = ip_into_int('172.31.255.255') >> 20 net_c = ip_into_int('192.168.255.255') >>...
f68ccf10d7aff3f6b0bb853077ddc90489d48420
3,617,820
def part_3b_output_equilb_NVT_started(job): """Check to see if the equilb_NVT (set temperature) gomc simulation is started.""" return gomc_simulation_started(job, equilb_NVT_control_file_name_str)
e86a95a13438c9da4a4214e4e82ee90e22b79dc9
3,617,821
def readAllSopv(sopvFilepath, logger = None): """Return information of all registered scanposes in VOCS.""" sopvs = [] first_line = True with open(sopvFilepath, 'r') as f: for line in f: if first_line: first_line = False continue sopvs.appe...
531e14ad2684b9c4a7afe9164090fe6e3a09c0b1
3,617,822
def _min_to_sec(minutes): """converts minutes to seconds, assuming that input is a number representing minutes""" return minutes*60
dff3330038c7e8cd1abda2c8a0a4433979fedf58
3,617,823
def get_ip(request) -> str: """ 获取当前请求的ip地址 :param request: :return: """ if request.META.get('HTTP_X_FORWARDED_FOR', None): ip = request.META['HTTP_X_FORWARDED_FOR'] else: ip = request.META['REMOTE_ADDR'] return ip
eb084135920231aa176e6099d70ed3954b407070
3,617,824
def aggregate_argmax(z_mean, z_logvar, new_mean, new_log_var, labels, kl_per_point): """Argmax aggregation with adaptive k. The bottom k dimensions in terms of distance are not averaged. K is estimated adaptively by binning the distance into two bins of equal width. Args: z_mean: Mean...
6c262a3b6356ad4a6f5493b1174db3d120f828dd
3,617,825
def get_file_data_old(archivo): """ Separa del nombre del archivo y extrae nombre de Centroide (ctrd) y cultivo (clt) """ diccionario = {} listado = archivo.split('-') diccionario['ctrd'] = listado[0] condicion = 'TS(S2)' in listado[1] or\ 'TS(TC)' in listado[1] or\ ...
4d02b5b77aaf0abfc768c898534493d3723ef54e
3,617,826
def mask_rcnn_loss(mask_outputs, mask_targets, select_class_targets, params): """Computes the mask loss of Mask-RCNN. This function implements the mask loss of Mask-RCNN. As the `mask_outputs` produces `num_classes` masks for each RoI, the reference model expands `mask_targets` to match the shape of `ma...
7cbf78de040fba38d66e0e669ab8fecfea06e3ae
3,617,827
from typing import Optional def get_error_handler( request: web.Request, config: Optional[Config] ) -> Optional[_Handler]: """Find error handler matching current request path if any.""" if not config: return None path = request.rel_url.path for item, handler in config.items(): if ...
a49351ab5479b653f45eff3bc6b069b354615154
3,617,828
def subject_stats_comparison(combined_df): """ Calculates the percentage of subjects with an exclusion and the rate of exclusions per patient. Parameters: combined_df: A DataFrame in the format provided by prepare_for_comparison Returns: A DataFrame with run names as the index and the colu...
ebf3ec1771861565130d926af1b59405ca74e1f9
3,617,829
def flip_randomly_left_right_image_with_annotation(image_tensor, annotation_tensor): """Accepts image tensor and annotation tensor and returns randomly flipped tensors of both. The function performs random flip of image and annotation tensors with probability of 1/2 The flip is performed or not performed fo...
bfad843de51500fb83dd453680983cbc983af8f1
3,617,830
from typing import Dict def dict_squares(n: int) -> Dict[int, int]: """Generates a dictionary with numbers from 0 to n as keys which are mapped to their squares using dictionary comprehension. doctests: >>> dict_squares(2) {0: 0, 1: 1, 2: 4} >>> dict_squares(5) {0: 0, 1: 1, 2: 4, 3: 9,...
4101d0256069c07da6c3d5a8d1e40783a4b26eea
3,617,831
from ostap.trees.trees import Tree def tproject ( tree , ## the tree histo , ## histogram what , ## variable/expression/list to be projected cuts = '' , ## selection/weighting criteria ...
d13a565fe99693fd7b814efa24aad7a5787ecdb0
3,617,832
import sys import os def dfl_local_dir(): """ Infers a default local directory, which is DFL_DIR_PARENT/<project name>, where the project name is guessed according to the following rules. If we detect we're in a repository, the project name is the repository name (git only for now). If we're...
425a5cf2ae634fed325da55e336bf4527a63c524
3,617,833
def factor_cartesian(table): """Factor a cartesian products of lists The function unrolls a cartesian product of lists. The table argument is a list of sequences and the output is a tuple of lists Example: >>> factor_cartesian([('a1','b1'),('a1','b2'),('a2','b1'),('a2','b2')])...
8b283944644d89c863e2bc7f5dc3824fa26ca27e
3,617,834
import argparse def parse_args(): """ Initializes command line arguments and parses them on startup returning the parsed args namespace. """ parser = argparse.ArgumentParser() bot = parser.add_argument_group('Discord Bot') bot.add_argument( '--token', '-t', required=True, type...
3f8ae0e284c9b917b76bac48a4f9bd254e76403d
3,617,835
def _palettize_seq(seq): """" seq must be a sequence of 3-d numpy arrays with dtype np.uint8, all with the same depth (i.e. the same length of the third dimension). """ # Call np.unique for each array in seq. Each array is viewed as a # 2-d structured array of colors. depth = seq[0].shape[-...
491831139adf23a13403e68a30ea0b33ec636e21
3,617,836
import mimetypes def _fetch_bundle_contents_blob(uuid, path=''): """ API to download the contents of a bundle or a subpath within a bundle. For directories, this method always returns a tarred and gzipped archive of the directory. For files, if the request has an Accept-Encoding header containin...
d709378344a9a7916bbdb96f2102ddc02f430293
3,617,837
def get_parents(model): """ Return the list of instances refered as "parents" of a given model instance. """ result = list() options = getattr(model, 'RoleOptions', None) if options: parents_list = getattr(options, 'permission_parents', None) if parents_list: for ...
cd8fd84bfc9fc87e9a7374d505b14fb3c1ff6034
3,617,838
import socket def _setDNSCache(): """ DNS缓存 """ def _getaddrinfo(*args, **kwargs): if args in _dnscache: # print str(args) + " in cache" return _dnscache[args] else: # print str(args) + " not in cache" _dnscache[args] = socket._getaddrinfo(*args...
b4d46a204e66113e81bc4ade3768a35edf6d4bba
3,617,839
def create_word2vec(all_questions, embeddings_dim, window, workers, min_count): """ Create the word2vec model""" model = gensim.models.Word2Vec(sentences=all_questions, size=embeddings_dim, window=window, workers= workers, min_count=min_count) # vocab size words = list(model.wv.vocab) print("vocab...
808c42339bb4596427fa4c784cd58d7b89d1a171
3,617,840
import math def velocity_line_trajectory(start, end, velocity, sampling_rate=0.01): """ start and end being n dimentional points, velocity a float value (meter per seconds) and the sampling rate between two points, returns a list of instance of States corresponding to a point going from start...
dabe203380cbcdc4ce3ff82ca7372b99caf4c68e
3,617,841
from .Equal import Equal def isEqual(*, value): """ Check that a numeric value is equal to {value} """ return Equal(value)
fa7c9c26c092a8a2cae1d2ad6a5e4255d93abdaf
3,617,842
def wrap_coro(coro, unpack, *args, **kwargs): """ building a coroutine receiving one argument and call it curried with *args and **kwargs and unpack it (if unpack is set) """ if unpack: async def _coro(value): return await coro(*args, *value, **kwargs) else: async def _co...
2e1916f5f34be5878a3af64ea28b5ffb56f6b350
3,617,843
def rasterizeSourcePositionList(shape, led_pattern, illumination_source_position_list_na=[], objective_numerical_aperture=0.25, objective_magnification=10, syst...
ddde89a347f32d9e3aa3ee1530f041e0bf639e71
3,617,844
from typing import List def list_to_dict(list: List, name_key: str = "name", value_key: str = "value"): """ Returns a key-value pair dictionary with given list of dictionary having `name` and `value` keys or custom keys. """ if not is_list(list): raise AttributeError( "Argument...
81c4b0597b8012b51f9d6cb619948d6afe972c6e
3,617,845
from typing import Tuple def _one_grid_to_points( axes: GridPointsLike, *, dim_domain: int, ) -> Tuple[np.ndarray, Tuple[int, ...]]: """ Convert a list of ndarrays, one per domain dimension, in the points. Returns also the shape containing the information of how each point is formed. ...
ac830c070ff2f456f75ac7f079e7d19987942bc8
3,617,846
def mAP(results, k=200, AP=True): """ Arguments : results = related images list for sorted file list k = mAP@k AP = whether return AP list for each images return : mAP value """ aps = [] for truth, result in enumerate(results): result = result[:k] ...
17da5fc85fdee24e24771e785298dfc71e2948a5
3,617,847
from typing import Any import typing def hint_is_specialized(hint: Any, target: Any) -> bool: """Checks if a type hint is a specialized version of target. E.g., hint_is_specialized(ClassVar[int], ClassVar) is True. isinstance will invoke type-checking, which this methods sidesteps. Behavior is undef...
b651fc05290de82ab5a5833d10ca68d6a96f2d7a
3,617,848
from typing import Dict from typing import Union def compute_selection_criteria( blast: Dict[str, Union[int, float]] ) -> Dict[str, Union[int, float]]: """Calculate a series of parameters used to discriminate which entries should be kept to search for a core genome from a series of blast files (*....
cc12be84aad55de090b0e6ba26eaeb5c77706073
3,617,849
def _get_matching_project_config(cfg, prj): """ Returns best match project configuration for given solution configuration. """ with error_context(prj): # If the project doesn't have any configurations, it means that we # failed to parse it properly, presumably because it defines its ...
7fd5fb92ae5efe8afcf1ba63e20158fadcab2c7b
3,617,850
def build_spc_queue(rxn_lst): """ Build spc queue from the reaction lst for the drivers :return spc_queue: all the species and corresponding models in rxn :rtype: list[(species, model),...] """ if 'all' in rxn_lst: # First check if rxn_lst is a bunch of species spc_queue = r...
0dbe4e2bc3db16dc5dc83a55f0f802d4dfae853f
3,617,851
def patch_telomeres(bands_by_chr): """Account for special case with Drosophila melanogaster """ for chr in bands_by_chr: first_band = bands_by_chr[chr][0] start = first_band[1] if start != '1': stop = str(int(start) - 1) pter_band = ['pter', '1', stop, '1', st...
23057227c526bb3837fd0c02233ddac4671c6956
3,617,852
import scipy.cluster as spcluster def cluster_sites(mol, tol, give_only_index=False): """ Cluster sites based on distance and species type. Args: mol (Molecule): Molecule **with origin at center of mass**. tol (float): Tolerance to use. Returns: (origin_site, clustered_sites)...
37c913a484c29420fefb72c41cf9f71b2bd8cbb3
3,617,853
def get_comment_notification_targets(comment): """ Gets a list of comments that should get a notification about this new comment :param PostComment|AnswerComment comment: :param set user_ids: set of user_ids to exclude :return: returns a tuple, first item is comments to notify, sec...
d2b0ff99705117b7642366d7080a3a29c48dc22a
3,617,854
def build_model(params: dict, build_options: dict = None) -> CompartmentalModel: """ Build the compartmental model from the provided parameters. """ params = Parameters(**params) # Get country/region details country = params.country pop = params.population # Create the model object ...
7738f8e31536822a50856186ffff38c70d807ca6
3,617,855
import six def gen_spewer_method(name, args): """Generates spewer code for a single opcode.""" method_name = "spew" + name # Generate code like this: # # void spewGuardShape(CacheIRReader& reader) { # spewOp(CacheOp::GuardShape); # spewOperandId("objId", reader.objOperandId()); ...
a8e546df4a9cfd0562611d8f456f8e109c331062
3,617,856
from typing import Optional def cir_LRsRQRQ(w, Rs, L, R1: Optional[float] = None, Q1: Optional[float] = None, n1: Optional[float] = None, fs1: Optional[float] = None, R2: Optional[float] = None, Q2: Optional[float] = None, n2: Optional[float] = N...
596951396a68140347cf06844041fcdf87a46974
3,617,857
from typing import List def smallest_positive_integer_not_in_array(arr: List[int]) -> int: """ [1..N] can cover everything from 1 to (N * (N+1) / 2) """ res = 1 for num in arr: if num > res: return res else: res += num return res
9d01e051c278beab40aefa6618a4a5f4934e451a
3,617,858
def module_enclosing_func(offset): """ Test function to see if module-level enclosures are detected """ def module_closure_func(self): """ Actual closure function, should be reported as: putil.tests.my_module.module_enclosing_func.module_closure_func """ self._exobj.add_e...
399212d5cc04479639cdb5cacb50b167327f2445
3,617,859
def out_of_bounds_replace(llhs, params, out_of_bounds): """ replace out of bounds llh evals with large, valid values""" llhs[out_of_bounds(params)] = NAN_REPLACE_VAL return llhs
d774ba545cdd8ac99932966495f581a2436c8aab
3,617,860
import numpy def fourier_sum ( func , N , xmin , xmax , fejer = False ) : """Make a function/histiogram representation in terms of Fourier series >>> func = lambda x : x * x >>> fsum = fourier_sum ( func , 4 , -1 , 1 ) >>> print fsum >>> x = ... >>> print 'FUN(%s) = %s ' % ( x , fsum ( x ) ) ...
566a1640fa1d3bc4c69658bce7e5847fe1103edf
3,617,861
def get_retrieval_model(params): """ This method returns the Retrieval class requested in the parameter dict. Args: params(dict): A dict of parameters. In this method, the parameters 'logger' and 'query_generation', and 'search_engine' are required. Based on the requested retrievel model, so...
f90596d7bd280a6a000e59b6fe05d05afbdc957c
3,617,862
def trigrams(docs): """create trigrams""" return [trigram_model[bigram_model[doc]] for doc in docs]
c5ecd514e233858abc875fc3a8026a1b0494fd9f
3,617,863
import nilearn.image as niimg def concat_imgs(in_files, out_file=None): """ Use nilearn.image.concat_imgs to concat images of up to 4 dimensions. Returns ------- out_file: str The absolute path to the output file. """ return niimg.concat_imgs(in_files)
04b5e376b3d20623ed66e08ffe704875568cebbc
3,617,864
def conv_2d(in_nodes, nb_filter, filter_size, strides=1, padding='same', activation='relu', bias=True, weights_init='truncated_normal', bias_init='truncated_normal', regularizer=None, weight_decay=0.001, trainable=True, restore=True, reuse=False, name="conv_2d"): """ ...
73b8e104cf398e0d34b77c36c1d53a083c2b52df
3,617,865
from datetime import datetime import sys import os import traceback import threading import time def run(args=None, cwd=None): """Run a cake build with the specified command-line args. @param args: A list of command-line args for cake. If this is None sys.argv is used instead. @type args: list of string, ...
8da4034120bc1c03d3a11bfb5e4fab13cb8c4a78
3,617,866
def tensor_repr(fra_data, dtype=None): """Creates a tensor representation of the FRA.""" dtype = dtype or tf.float64 res = dict() res["fixing_date"] = tf.convert_to_tensor( fra_data["fixing_date"], dtype=tf.int32) res["fixed_rate"] = tf.convert_to_tensor( fra_data["fixed_rate"], dtype=dtype) con...
415c6b40e17015d074a0cdb387184468b26a2143
3,617,867
def find_section_clamping_values(zlevel, lowerfract, upperfract): """Find int8 values that correspond to lowerfract & upperfract of zlevel histogram From igneous (https://github.com/seung-lab/igneous/blob/master/igneous/tasks/tasks.py#L547) """ filtered = np.copy(zlevel) # remove pure black fr...
fc0ebcbca1f10d2028d2ddd829092532544c44d9
3,617,868
def get_levels(content, language=None): """ Returns a list of integers whose value is for the content of the same index. :param content: Either a list of strings, or a list of dictionaries that contain 'content' and 'language' keys. :param language: Optional, only needed if only passing in a list of str...
f38acf80394c95ca395a1fd1dc755b1338275ad0
3,617,869
import logging def losses(args): """Set up ``losses`` dict which stores model losses per epoch as well as evaluation metrics""" losses = {} keys = ["D", "Dr", "Df", "G"] if args.gp: keys.append("gp") eval_keys = ["w1p", "w1m", "w1efp", "fpnd", "coverage", "mmd"] if not args.fpnd: ...
b4da1c280968c510b59d598d699c331194196100
3,617,870
import fastapi def read_search(search_id: int, search_repository: repository.search_repository.SearchRepository = fastapi.Depends(), user: auth.authentication.User = fastapi.Depends(auth.authentication.get_current_user)): """ Get the details for a previously submitted search request. ...
e3117f0ad4a66725c0117640d7a54a0f3dabdb19
3,617,871
def mask_colorize(mask, num_classes, color_map): """ transfor one mask to a maske with color :param mask: mask with shape [h, w] :param num_classes: number of classes :param color_map: color map with shape [N, 3] """ color_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') color...
27a9eb472af4633c7856ee0535334561b1e64723
3,617,872
import configparser def parse_config(filename): """Parses github-snooze-button configuration files. Args: filename: The name of a file in ConfigParser .ini format, described below. Returns: A dictionary of dictionaries, one inner dictionary per repository. Default val...
86067a6a6e570b540d576aed8cd684bcc826e038
3,617,873
def load_vehicles(country, vehicles, last_updated): """Load list of vehicles from given country into database.""" clean_vehicles(country) with elastic() as client: for vehicle in vehicles: vehicle.save(using=client) upsert_metadata(country, last_updated) return True
d49060d4aa29539bb83c12ee50962298eba130fe
3,617,874
def get_ini_conf(fname): """ Very simple one-lined .ini file reader, with no error checking """ with open(fname, "r") as handle: return {i.split("=")[0].strip(): i.split("=")[-1].strip() for i in handle.readlines() if i.strip()}
180c3106bb40c26b6628ff19dcb2c233a7f6a8d7
3,617,875
def calc_ratios2(roi,edict,which=0): """ edict is a dictionary containing the event information. Calculate for each photon the ratio of the source to the background. """ #ens = [[b.emax for b in roi.bands if b.ct==0],[b.emax for b in roi.bands if b.ct==1]] ens = [[b.emax for b in roi.bands if b...
b30c8fe6ef233911be893fa37947a401d3165318
3,617,876
def multiclass_jaccard_loss_softmax(logits, labels, weight_class_sample_prob=False, weight_class_global_prob=False, train_class_probs=None, name='loss'): """ multiclass Jaccard loss measure, softmax is applied internally on the y_preds Args: logits the predicted logits with shape [batchsize, ..., c...
f75d858aed5a1632c1e25cffb1c959fed84ad39f
3,617,877
def get_testbed_vars(): """ returns the testbed variables in a dictionary :return: testbed variables dictionary :rtype: dict """ return getwa().get_testbed_vars()
2a454b30bbdf5373b97b368d9501ceea64a66018
3,617,878
def sign_user(user_data, fields=None): """Sign user data.""" signer = Signer(current_app.config['SECRET_KEY'], salt='newdle-users') return dict( user_data, signature=signer.get_signature( _get_signature_source_bytes(user_data, fields) ).decode('ascii'), )
bfc2cd033fb52ed38365619f81155fcef0a06e1b
3,617,879
def svn_repos_parse_dumpstream3(*args): """svn_repos_parse_dumpstream3(svn_stream_t * stream, svn_repos_parse_fns3_t parse_fns, void * parse_baton, svn_boolean_t deltas_are_text, svn_cancel_func_t cancel_func, apr_pool_t pool) -> svn_error_t""" return _repos.svn_repos_parse_dumpstream3(*args)
e9454e92e865e1885353b77f1b43f82d11af052b
3,617,880
import re def decode_string_six_bits(binary: str, max_chars: int) -> str: """Decode binary string by decoding every sequence of six bits. Args: binary (str): Binary string max_chars (int): Maximum length of resulting string Raises: ConvertException: Resulting string too large ...
71b88d4eeddd6558471fc5b2cb2a1f8737e40d68
3,617,881
import os import tqdm def apply_scbc(ds, mizuroute_exe, bmorph_config, client=None, save_mults=False, **tqdm_kwargs): """ Applies Spatially Consistent Bias Correction (SCBC) by bias correcting local flows and re-routing them through mizuroute. This method can be run in parallel by providing a `das...
72182536eaecd2872f1dbdf32887989f9aebbf11
3,617,882
import socket def whois(ip_address): """Whois client for Python""" whois_ip = str(ip_address) try: query = socket.gethostbyname(whois_ip) except Exception: query = whois_ip s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.ripe.net", 43)) s.send(query....
7440f936ca866bc74ccd4e0d81bff56e46b82f60
3,617,883
def get_interesting_columns_all2D(datapath, column_indices, number_of_spectra, n_rows): """ This will return a LIST of 2D DATA SETS. Each 2D spectrum in the list will just be from the columns chosen by the user. """ n_columns = len(column_indices) all_relevant...
1cdff842f34656a0b98741d1174bc4d0ed5c8fb6
3,617,884
def oned_bump_combined(): """ display all 1d traveling bump figures in one. """ fig = plt.figure(figsize=(10,4)) """ oned_const_vel #(oned_const_vel_bump,[],['oned_const_vel_bump_fig.pdf']), """ #######################################################################################...
8605f774a48fbd0945ca4a5b14c1fc373f070f7e
3,617,885
def get_det_coords(size: int, spacing: float) -> np.ndarray: """Compute pixel-center positions for 2D detector The centers of the pixels of a detector are usually not aligned to a pixel grid. If we center the detector at the origin, odd images will have a pixel at zero, whereas even images will have tw...
76a4582107a36b39670a33fe464107585db86941
3,617,886
def inverse_document_frequency(word, document_number, document_frequency): """Calculate idf value of a word Args: word: the word to be scored. document_number: number of documents in dataset. document_frequency: Frequency of a word in documents dataset, i.e. if a document ha...
1efce5bc5ed0f9bebc555c736bce7a7b8fcf71fb
3,617,887
def str_to_acemask(lvl, is_object): """Return the acemask from a simplified access level :param lvl: the access level to map, in "none, "read", "write" or "read/write" :type lvl: str :param is_object: defined if the level corresponds to a data object or a coll...
30a782770c8a74874130125683406314e051a4a9
3,617,888
import pickle def min_probabilities(p=0.0): """ !! OBSOLETE FUNCTION !! :param p: p percentage, int(0 < p < 1) :return: list of families with min(can be tuned) probabilities larger than p """ min_prob = [] with open(saved_feature_path + '/prob_of_each_sample_25families', 'rb') as fp: ...
78583ea256eea8e2293c9ea845263532f5d5318a
3,617,889
from typing import Optional from typing import Dict from typing import Any def BRANCH_DESCRIPTOR( project: ProjectHandle, branch: BranchHandle, urls: Optional[UrlFactory] ) -> Dict[str, Any]: """Dictionary serialization for branch descriptor. Parameters ---------- projec...
a8b4f98d57e2a477e15b21c98953da1178df074a
3,617,890
def evaluate_lenet5(train_set_x, train_set_y, valid_set_x, valid_set_y, test_set_x, test_set_y, learning_rate=0.1, n_epochs=10, nkerns=[20, 50], batch_size=BATCH_SIZE): """ Demonstrates lenet on MNIST dataset :type learning_rate: float :param learning_rate: learning ...
5526e8edaa349159e399cc21f5125ccd53a7977f
3,617,891
def require_volume_exists(f): """Decorator to require the specified volume to exist. Requres the wrapped function to use context and volume_id as their first two arguments. """ def wrapper(context, volume_id, *args, **kwargs): db.api.volume_get(context, volume_id) return f(context,...
8894631eeee76c7c3656c533c2294df1becf4ec8
3,617,892
def longitudinal_distance(reference: StateSE2, other: Point2D) -> float: """ Longitudinal distance from a point to a reference pose :param reference: the reference pose :param other: the query point :return: the longitudinal distance """ return float( np.cos(reference.heading) * (oth...
d1e71ef1e1bed1e7daefc8f77d609ff9fb201edb
3,617,893
def _log_bessel_kve_bwd(aux, g): """Reverse mode impl for bessel_kve.""" v, z = aux dtype = dtype_util.common_dtype([v, z], tf.float32) numpy_dtype = dtype_util.as_numpy_dtype(dtype) log_kve = _log_bessel_kve_custom_gradient(v, z) grad_z = tfp_math.log_add_exp( _log_bessel_kve_custom_gradient(v - 1.,...
0ab0e255ef3a0affe51cca968acc1965c945b957
3,617,894
import logging def send_message_via_backend(msg, backend=None, orig_phone_number=None): """send sms using a specific backend msg - outbound message object backend - MobileBackend object to use for sending; if None, use msg.outbound_backend orig_phone_number - the originating phone number to use...
8b2a8cf09a645be2c174335ea06d60809193d863
3,617,895
def check(text): """Check the text.""" err = "misc.bureaucratese" msg = "'{}' is bureaucratese." bureaucratese = [ "meet with your approval", "meets with your approval", ] return existence_check(text, bureaucratese, err, msg, join=True)
574c078f44cd6189aab91da5b9e59601d8cae5e0
3,617,896
def create_label_colormap(no_class=7, dataset=None): """Creates a label colormap used in Cityscapes segmentation benchmark. Returns: A Colormap for visualizing segmentation results. """ # GTA 19 Classes if (dataset == 'GTA') or ( no_class == 19) : colormap = np.array([ #...
f9de66711b02cc21d222051cc07ae18eb0e665cc
3,617,897
def confirm_current_token(token_type: str, revoked: bool = True) -> User: """ 验证token :param jti: str jti字符串 :param token_type: str token类型 :param revoked 是否撤销token :return (state, user) """ try: jti = get_raw_jwt()["jti"] token = TokenBlackList.where(jti=jti, token_type...
238dfa4fbce1f2c1fd2601f4e130d83f26b28885
3,617,898
import torch def rotate_image(img, max_rot_angle, dim=32): """Rotate image.""" # Pad image padding = int(dim * 1.5) padded_img, (x1, y1) = pad_image(img, padding=padding) # Rotate image rotation_deg = np.random.uniform(-max_rot_angle, max_rot_angle) x_np = padded_img.permute(1, 2, 0).numpy() x_np = n...
aefdb7374037cf9423c4663926f383b0f8e4d18d
3,617,899