content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _to_system(abbreviation): """Converts an abbreviation to a system identifier. Args: abbreviation: a `pronto.Term.id` Returns: a system identifier """ try: return { 'HP': 'http://www.human-phenotype-ontology.org/' }[abbreviation] except KeyError: ...
f43942b242e67866028a385e6614133dc25b31b0
16,600
from typing import Union def apply_gate(circ: QuantumCircuit, qreg: QuantumRegister, gate: GateObj, parameterise: bool = False, param: Union[Parameter, tuple] = None): """Applies a gate to a quantum circuit. More complicated gates such as RXX gates should be decomposed into single qubit ga...
0babd68efb8bae67c5f610bcca3eb9f3b67630ad
16,601
from typing import Tuple import codecs def preprocess_datasets(data: str, seed: int = 0) -> Tuple: """Load and preprocess raw datasets (Yahoo! R3 or Coat).""" if data == 'yahoo': with codecs.open(f'../data/{data}/train.txt', 'r', 'utf-8', errors='ignore') as f: data_train = pd.read_csv(f, ...
78a7bfe7968ad47f797728ffb43c804ab8af6298
16,602
def loadSentimentVector(file_name): """ Load sentiment vector [Surprise, Sorrow, Love, Joy, Hate, Expect, Anxiety, Anger] """ contents = [ line.strip('\n').split() for line in open(file_name, 'r').readlines() ] sentiment_dict = { line[0].decode('utf-8'): [float(w) for w in li...
5d0d1f4598eeed455d080236720adcae357b6485
16,603
def unique_boxes(boxes, scale=1.0): """Return indices of unique boxes.""" v = np.array([1, 1e3, 1e6, 1e9]) hashes = np.round(boxes * scale).dot(v) _, index = np.unique(hashes, return_index=True) return np.sort(index)
fc9ab64356192828659f025af6aa112205fc838c
16,604
import os def compscan_key(compscan): """List of strings that identifies compound scan.""" # Name of data set that contains compound scan path = compscan.scans[0].path filename_end = path.find('.h5') dataset_name = os.path.basename(path[:filename_end]) if filename_end > 0 else os.path.basename(pat...
f66caa4da5ab6ba51d6167bc1638324233a21ec2
16,605
def HEX2DEC(*args) -> Function: """ Converts a signed hexadecimal number to decimal format. Learn more: https//support.google.com/docs/answer/3093192 """ return Function("HEX2DEC", args)
b4741d02acae7169854d1193ae5b43f6736257dc
16,606
def find_edges(mesh, key): """ Temp replacement for mesh.findEdges(). This is painfully slow. """ for edge in mesh.edges: v = edge.vertices if key[0] == v[0] and key[1] == v[1]: return edge.index
98247b64a0e5671a7dbbf314f314cef2c5c8aae3
16,607
def thumbnail(link): """ Returns the URL to a thumbnail for a given identifier. """ targetid, service = _targetid(link), _service(link) if targetid: if service in _OEMBED_MAP: try: return _embed_json(service, targetid)["thumbnail_url"] except (ValueEr...
9ca78af2a65a41a70fef73c35383ae9214fb2d96
16,608
def valve_gas_cv(m_dot, p_1, p_2, m_molar, T): """Find the required valve Cv for a given mass flow and pressure drop. Assumes that a compressible gas is flowing through the valve. Arguments: m_dot (scalar): Mass flow rate [units: kilogram second**-1]. p_1 (scalar): Inlet pressure [units: p...
07bd3f45392e03eb6744b98a3fde022aa517c4fc
16,609
def frequency_based_dissim(record, modes): """ Frequency-based dissimilarity function inspired by "Improving K-Modes Algorithm Considering Frequencies of Attribute Values in Mode" by He et al. """ list_dissim = [] for cluster_mode in modes: sum_dissim = 0 for i in range(len(recor...
80e21763d6f90ddc5a448f46247fd12253de5dbb
16,610
def _process_create_group(event: dict) -> list: """ Process CreateGroup event. This function doesn't set tags. """ return [event['responseElements']['group']['groupName']]
978b3ffc3c4aa72165914b79dc06cb7691c5c5a5
16,611
from typing import Any from typing import List def tree_labels(t: Node): """Collect all labels of a tree into a list.""" def f(label: Any, folded_subtrees: List) -> List: return [label] + folded_subtrees def g(folded_first: List, folded_rest: List) -> List: return folded_first + folded_r...
7ad1703a090cd761a99cd5323c9258e8d2d551b8
16,612
def find_best_split(rows): """Find the best question to ask by iterating over every feature / value and calculating the information gain.""" best_gain = 0 # keep track of the best information gain best_question = None # keep train of the feature / value that produced it current_uncertainty = gini(...
9b197c99b41e64e37b499b5d4b3c7758cda3b56e
16,613
def pad_data(data, context_size, target_size, pad_at_begin= False): """ Performs data padding for both target and aggregate consumption :param data: The aggregate power :type data: np.array :param context_size: The input sequence length :type context_size: int :param target_size: The target...
1b698a849a4ca82d87ce6c5711220b61cd21252b
16,614
import os def create_callbacks(path): """ Creates the callbacks to use during training. Args training_model: The model that is used for training. prediction_model: The model that should be used for validation. validation_generator: The generator for creating validation data. ...
d19b10e51bd5f2e90cf900a8a044c8d2dbe404e8
16,615
import os def SaveAsImageFile(preferences, image): """Save the current image as a PNG picture.""" extension_map = {"png": wx.BITMAP_TYPE_PNG} extensions = extension_map.keys() wildcard = create_wildcard("Image files", extensions) dialog = wx.FileDialog(None, message="Export to Image", ...
feaf05ab7a94f958c066a656901f86e01536edac
16,616
def egg_translator(cell): """If the cell has the DNA for harboring its offspring inside it, granting it additional food and protection at the risk of the parent cell, it is an egg. Active DNA: x,A,(C/D),x,x,x """ dna = cell.dna.split(',') if dna[1] == 'A' and dna[2] == 'C': return True ...
af0d9097c8a0b5002722c79d6ec8262a66cc375d
16,617
def all_different_cst(xs, cst): """ all_different_cst(xs, cst) Ensure that all elements in xs + cst are distinct """ return [AllDifferent([(x + c) for (x,c) in zip(xs,cst)])]
dfc75a54a92a4c8c2ef76af74250b9125c9bb647
16,618
def processing(task, region: dict, raster: str, parameters: dict): """ Cuts the raster according to given region and applies some filters in order to find the district heating potentials and related indicators. Inputs : * region : selected zone where the district heating potential is studi...
63a5548e886b575011e716e05a589715f027c316
16,619
import random def randbit(): """Returns a random bit.""" return random.randrange(2)
4b47101df7368b7cb423920e6a5338b76ab4ecaa
16,620
def calc_points(goals, assists): """ Calculate the total traditional and weighted points for all players, grouped by player id. Author: Rasmus Säfvenberg Parameters ---------- goals : pandas.DataFrame A data frame with total goals and weighted assists per player. assist...
1801cf2602a473bdf532e1c0ee58b883dc3e79d1
16,621
def get_links(browser, elemento): """ Pega todos os links dentro de um elemento - browser = a instância do navegador - element = ['aside', main, body, ul, ol] """ resultado = {} element = browser.find_element_by_tag_name(elemento) ancoras = element.find_elements_by_tag_name...
dc28e71452bd0c1ede651981e88ba26815a491dd
16,622
import io import base64 def file_to_base64(path): """ Convert specified file to base64 string Args: path (string): path to file Return: string: base64 encoded file content """ with io.open(path, 'rb') as file_to_convert: return base64.b64encode(file_to_convert.read())
0c942f8f4d29943c5a3aac6c954d9e2b1b2898a3
16,623
def get_simverb(subset=None): """ Get SimVerb-3500 data :return: (pairs, scores) """ simverb = [] if subset == 'dev': name = '500-dev' elif subset == 'test': name = '3000-test' else: name = '3500' with open('../data/SimVerb-3500/SimVerb-{}.txt'.format(name)) a...
5cec49bd232a883836029b8b011f09f360176910
16,624
def sample_image(size, min_r, max_r, circles, squares, pixel_value): """Generate image with geometrical shapes (circles and squares). """ img = np.zeros((size, size, 2)) loc = [] if pixel_value is None: vals = np.random.randint(0, 256, circles + squares) else: vals = [pixel_value...
25ab1afcd7256bc07ee55ac2e12cf9d834cb798c
16,625
def host_allocations(auth): """Retrieve host allocations""" response = API.get(auth, '/os-hosts/allocations') return response.json()['allocations']
505eeb0502f6480445ec5dff1cd3203eda96d475
16,626
def rosenbrock_grad(x, y): """Gradient of Rosenbrock function.""" return (-400 * x * (-(x ** 2) + y) + 2 * x - 2, -200 * x ** 2 + 200 * y)
c7acf0bbe11a6d1cbb38b6853eb1b508e3846657
16,627
import os def get_file( fname, origin, untar=False, cache_subdir="datasets", extract=False, archive_format="auto", cache_dir=None, ): """Downloads a file from a URL if it not already in the cache. By default the file at the url `origin` is downloaded to the cache_dir `~/.keras`...
7098b0ffbf70c8b7468c22637045068d32b71390
16,628
def extractYoujinsite(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if '[God & Devil World]' in item['tags'] and (chp or vol): return buildReleaseMessageWithType(item, 'Shenmo Xitong', vol, chp, frag=frag, postfix=postfix) if '[LBD&A]' in item['tags'] and (chp or vol):...
11463288cdcc7268b0b4657934dd8872a7d36580
16,629
import os import glob def get_patient_dirs(root_dir): """ Function used to get the root director for all patients :param root_dir: root director of all image data :return patient_paths: list of all patient paths, one for each patient """ search_path = os.path.join(root_dir, '[0-1]', '*') p...
d0d38f02214175b867fd8bf8b1e13db8ee8a83f2
16,630
import os import torch import logging import wget def _download(path: str, url: str): """ Gets a file from cache or downloads it Args: path: path to the file in cache url: url to the file Returns: path: path to the file in cache """ if url is None: return None ...
941f494e8d01817e61d11b83aa51816ca1459449
16,631
def get_logger() -> Logger: """ This function returns the logger for this project """ return getLogger(LOGGER_NAME)
33e11a06c357552c35f9ef089fd303ad15db0884
16,632
import json def write_guess_json(guesser, filename, fold, run_length=200, censor_features=["id", "label"], num_guesses=5): """ Returns the vocab, which is a list of all features. """ vocab = [kBIAS] print("Writing guesses to %s" % filename) num = 0 with open(filename, 'w') as outfil...
9f0055289ff462b0b3c067ea1e0a68c66a74136c
16,633
def upgrade_to_4g(region, strategy, costs, global_parameters, core_lut, country_parameters): """ Reflects the baseline scenario of needing to build a single dedicated network. """ backhaul = '{}_backhaul'.format(strategy.split('_')[2]) sharing = strategy.split('_')[3] geotype = region['...
947afef6d550b9022109c665fc311511f428e9f8
16,634
import hmac def get_url(request): """ Use devId and key and some hashing thing to get the url, needs /v3/api as input """ devId = DEV_ID key = KEY request = request + ('&' if ('?' in request) else '?') raw = request + f"devid={devId}" raw = raw.encode() hashed = hmac.new(key, ...
57e6d8dc6c0f282b227559aed5cd9c1f96f7d5b7
16,635
def _is_mapped_class(cls): """Return True if the given object is a mapped class, :class:`.Mapper`, or :class:`.AliasedClass`.""" if isinstance(cls, (AliasedClass, mapperlib.Mapper)): return True if isinstance(cls, expression.ClauseElement): return False if isinstance(cls, type): ...
7f09c1f4908bb62977de07ad4366fb8e6cc84cc2
16,636
from bs4 import BeautifulSoup def get_all_links_in_catalog(html) -> list: """Получает список всех ссылок на пункты из каталога.""" _soup = BeautifulSoup(html, 'html.parser') _items = _soup.find('div', class_='catalog_section_list').find_all('li', class_='name') links_list = [] for item in _items: ...
53e4fd9aaad8755ddd19328ae5d5f972cfbcdc3c
16,637
def digitize(n): """Convert a number to a reversed array of digits.""" l = list(str(n)) n_l = [] for d in l: n_l.append(int(d)) n_l.reverse() return n_l
e4355b68da41e4be87ce18b53afb2a406eb120c7
16,638
import matplotlib.pyplot as plt import time def run_example(device_id, do_plot=False): """ Run the example: Connect to the device specified by device_id and obtain impedance data using ziDAQServer's blocking (synchronous) poll() command. Requirements: Hardware configuration: Connect signal out...
9d3306fdac3084622e175a1ce9243a7bcf976daa
16,639
def _available_algorithms(): """Verify which algorithms are supported on the current machine. This is done by verifying that the required modules and solvers are available. """ available = [] for algorithm in ALGORITHM_NAMES: if "gurobi" in algorithm and not abcrules_gurobi.gb: ...
cd9310cb78d780154c56763cdf14573bc67ae7b5
16,640
import re def symbols(*names, **kwargs): """ Emulates the behaviour of sympy.symbols. """ shape=kwargs.pop('shape', ()) s = names[0] if not isinstance(s, list): s = re.split('\s|,', s) res = [] for t in s: # skip empty strings if not t: continue ...
bcaf1827ccee67098e619c3ec825f3b1aeb3f798
16,641
def create_intent(intent, project_id, language_code): """Create intent in dialogflow :param intent: dict, intent for api :param project_id: str, secret project id :param language_code: event with update tg object :return: """ client = dialogflow.IntentsClient() parent = client.project_ag...
59a150d4456d26f4cd8fa93a2cbfc131278d3ba0
16,642
from typing import List def construct_object_types(list_of_oids: List[str]) -> List[hlapi.ObjectType]: """Builds and returns a list of special 'ObjectType' from pysnmp""" object_types: List[hlapi.ObjectType] = [] for oid in list_of_oids: object_types.append(hlapi.ObjectType(hlapi.ObjectIdentit...
24eeb7dbd0de49e702acc574c9264d3e7bcdf904
16,643
def base_sampler(models, nevents, floating_params=None): """ Creates samplers from models. Args: models (list(model)): models to sample nevents (list(int)): number of in each sampler floating_params (list(parameter), optionnal): floating parameter in the samplers Returns: ...
af575d4a175239c2af4fe0e61658005a12225e5a
16,644
def menu_maker(): """Top Menu Maker In each html page """ result = "<center>" for i,item in enumerate(page_name): if item == "Home": targets_blank = "" else: targets_blank = 'target="blank"' # Hyper Link To Each Page In HTML File result += '\t...
6f9b38926d3eab31d1e5d32a49564f083df4f3cc
16,645
import http def project_generate_private_link_post(auth, node, **kwargs): """ creata a new private link object and add it to the node and its selected children""" node_ids = request.json.get('node_ids', []) name = request.json.get('name', '') anonymous = request.json.get('anonymous', False) if ...
bd006f64d02bf36509297b1a0778e3488093c682
16,646
def access_token_old_api(authen_code): """ 通过此接口获取登录用户身份(疑似是一个旧接口) :param authen_code: :return: """ # 先获取app_access_token app_access_token = _get_app_access_token() if not app_access_token: return None access_token_old_url = cfg.access_token_old_url headers = {"Content-T...
efb34044bc07aee817050ef39e8d8a72da7611fd
16,647
def denoising(image): """improve image quality by remove unimportant details""" denoised = cv2.fastNlMeansDenoisingColored(image, None, 10, 10, 7, 21) return denoised
b5407c1fcd84b49afe5c17e6a221d9da423444f6
16,648
def teams(): """Redirect the to the Slack team authentication url.""" return redirect(auth.get_redirect('team'))
7ea84c5319c7f64a24c7ae42bd0b7467934d8cba
16,649
def _clarans(metric): """Clustering Large Applications based on RANdomized Search.""" # choose which implementation to use, hybrid or cpu get_clusters = _get_clusters(metric, method='cpu') @jit(nopython=True) def clarans(data, k, numlocal, maxneighbor): """Clustering Large Applications base...
a56321ba094b78eaa6df18917b7c3ad32a3a6bec
16,650
def create_outlier_mask(df, target_var, number_of_stds, grouping_cols=None): """ Create a row-wise mask to filter-out outliers based on target_var. Optionally allows you to filter outliers by group for hier. data. """ def flag_outliers_within_groups(df, target_var, ...
95a7e3e5a0cb8dcc4aa3da1af7e9cb4111cf6b81
16,651
import contextlib def closing_all(*args): """ Return a context manager closing the passed arguments. """ return contextlib.nested(*[contextlib.closing(f) for f in args])
075056e1a92c63d5c1db0cda68d7cb447868653b
16,652
def _non_max_suppression(objects, threshold): """Returns a list of indexes of objects passing the NMS. Args: objects: result candidates. threshold: the threshold of overlapping IoU to merge the boxes. Returns: A list of indexes containings the objects that pass the NMS. """ if len(...
9952386f5a6c6f11b1fdbd37eaca6c273ea4b506
16,653
def binary_search(x,l): """ Esse algorítmo é o algorítmo de busca binária, mas ele retorna qual o índice o qual devo colocar o elemento para que a lista permaneça ordenada. Input: elemento x e lista l Output: Índice em que o elemento deve ser inserido para manter a ordenação da lista """ lo...
457c403ffeb2eb5529c2552bdbe8d7beee9199f2
16,654
def check_abrp(config): """Check for geocodio options and return""" try: abrpOptions = config.abrp.as_dict() except: return {} options = {} abrp_keys = ["enable", "api_key", "token"] for key in abrp_keys: if key not in abrpOptions.keys(): _LOGGER.error(f"Miss...
fa9c0f1643ae2793cf66498dbb8f27a033edeafd
16,655
import click def connect(config, job, attach): """ Connect to job. JOB may be specified by name or ID, but ID is preferred. """ jobs = config.trainml.run(config.trainml.client.jobs.list()) found = search_by_id_name(job, jobs) if None is found: raise click.UsageError("Cannot find ...
8a572a92eb9a0cd31af05218dec3ab369109cb31
16,656
def convert_magicc7_to_openscm_variables(variables, inverse=False): """ Convert MAGICC7 variables to OpenSCM variables Parameters ---------- variables : list_like, str Variables to convert inverse : bool If True, convert the other way i.e. convert OpenSCM variables to MAGICC7 ...
952bca9f07f8e032b33328c1b03470fd3150eabd
16,657
import asyncio import aiohttp async def fetch_disclosure(start, end): """期间沪深二市所有类型的公司公告 Args: start (date like): 开始日期 end (date like): 结束日期 Returns: list: list of dict """ start, end = pd.Timestamp(start), pd.Timestamp(end) start_str = start.strftime(r'%Y-%m-%d') ...
efb6b7706ed73c09c65e5d05567b3fdf38aee887
16,658
from re import T def get_loader( image_dir, attr_path, selected_attrs, crop_size=178, image_size=128, batch_size=16, dataset="CelebA", mode="train", affectnet_emo_descr="emotiw", num_workers=1, ): """Build and return a data loader.""" transform = [] if mode == "trai...
082d1b81b73df7c817fad024911fe431f8cf4a74
16,659
import json def remove_samples(request, product_id): """Removes passed samples from product with passed id. """ parent_product = Product.objects.get(pk=product_id) for temp_id in request.POST.keys(): if temp_id.startswith("product") is False: continue temp_id = temp_id.sp...
e9d0f112f17af463cfe7ddba2bd606d78fb50b3f
16,660
def csu_to_field(field, radar, units='unitless', long_name='Hydrometeor ID', standard_name='Hydrometeor ID', dz_field='ZC'): """ Adds a newly created field to the Py-ART radar object. If reflectivity is a masked array,...
c8052f51bbed2c16c744201b862fa43868d7d527
16,661
import os import requests def get_port_use_db(): """Gets the services that commonly run on certain ports :return: dict[port] = service :rtype: dict """ url = "http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv" db_path = "/tmp/port_db" if not os.pat...
4462ef74b5575905b75980827d5a5bb5ed05aee8
16,662
def calculate_com(structure): """ Calculates center of mass of the structure (ligand or protein). Parameters ---------- structure : biopython Structure object PDB of choice loaded into biopython (only chains of interest). Returns ------- A list defining center of mass of th...
35d6ed62d3943dff0aa1ef0c3a0d04b9235b84ac
16,663
def generate_config(context): """ Generate the deployment configuration. """ resources = [] name = context.properties.get('name', context.env['name']) resources = [ { 'name': name, 'type': 'appengine.v1.version', 'properties': context.properties } ...
9a997b87a8d4d8f46edbbb9d2da9f523e5e2fdc6
16,664
def check_regs(region_df, chr_name=None, start_name=None, stop_name=None, strand_name=None, sample_name=None): """ Modifies a region dataframe to be coherent with the GMQL data model :param region_df: a pandas Dataframe of regions that is coherent with the GMQL data model :param chr_name: (o...
ea00a9b755c8dc2943717254ecdb3390bbefe288
16,665
from typing import List from typing import Optional from typing import Sequence from typing import Union from typing import Dict from typing import Any from typing import cast def build_assets_job( name: str, assets: List[OpDefinition], source_assets: Optional[Sequence[Union[ForeignAsset, OpDefinition]]] ...
8e2353677e5085f0c1eb53ee24687e020912b2e5
16,666
def createBinarySearchTree(vs): """ Generate a balanced binary search tree based on the given array. Args: vs - an integer array {4, 5, 5, 7, 2, 1, 3} 4 / \ 2 5 / \ / \ 1 3 5 7 """ def _help...
5e1f7723a4b218d980d7d72ca8f949160ff8042d
16,667
def remove_end_same_as_start_transitions(df, start_col, end_col): """Remove rows corresponding to transitions where start equals end state. Millington 2009 used a methodology where if a combination of conditions didn't result in a transition, this would be represented in the model by specifying a trans...
f4b3ddca74e204ed22c75a4f635845869ded9988
16,668
from typing import Dict from typing import Any import os import re import sys from typing import cast from typing import List def read_config(path: str) -> Dict[str, Any]: """Return dict with contents of configuration file.""" newconf = { "setup": False, "servers": [], "okurls": [], ...
4d0f020ad37eb7ff4a599afdcedc85b4ac5cc934
16,669
def sieve(iterable, inspector, *keys): """Separates @iterable into multiple lists, with @inspector(item) -> k for k in @keys defining the separation. e.g., sieve(range(10), lambda x: x % 2, 0, 1) -> [[evens], [odds]] """ s = {k: [] for k in keys} for item in iterable: k = inspector(item) ...
6ebb76dfb3131342e08a0be4127fba242d126130
16,670
def get_model(config: BraveConfig) -> embedding_model.MultimodalEmbeddingModel: """Construct a model implementing BraVe. Args: config: Configuration for BraVe. Returns: A `MultimodalEmbeddingModel` to train BraVe. """ init_fn, parameterized_fns = _build_parameterized_fns(config) loss_fn = _build_...
eceff13cf9ec5bd5cdd126af52bbd4eb6fad6ebe
16,671
def upilab6_1_5 () : """ 6.1.5. Exercice UpyLaB 6.2 - Parcours vert bleu rouge (D’après une idée de Jacky Trinh le 19/02/2018) Monsieur Germain est une personne très âgée. Il aimerait préparer une liste de courses à faire à l’avance. Ayant un budget assez serré, il voudrait que sa liste de courses soit dans ses cap...
198a11e4059c39550bb398a473711073677a41d4
16,672
import torch def construct_filtering_input_data(xyz_s, xyz_t, data, overlapped_pair_tensors, dist_th=0.05, mutuals_flag=None): """ Prepares the input dictionary for the filtering network Args: xyz_s (torch tensor): coordinates of the sampled points in the source point cloud [b,n,3] xyz_t (to...
ca316834cc87e1527e4563407138aa92a46b92a3
16,673
def rmean(x, N): """ cutting off the edges. """ s = int(N-1) return np.convolve(x, np.ones((N,))/N)[s:-s]
eb34bd21523e685184155e65ccddc34e2eb6a428
16,674
def add_variant_to_existing_lines(group, variant, total_quantity): """ Adds variant to existing lines with same variant. Variant is added by increasing quantity of lines with same variant, as long as total_quantity of variant will be added or there is no more lines with same variant. Returns q...
1e958db4c684f0bf3f2d821fc06f422cc60d0168
16,675
def calculate_position(c, t): """ Calculates a position given a set of quintic coefficients and a time. Args c: List of coefficients generated by a quintic polynomial trajectory generator. t: Time at which to calculate the position Returns Position """ retu...
927737b41006df13e7bf751b06756eea02542491
16,676
def get_dqa(df): """Method to get DQA issues.""" try: df0 = df[(df.dob == '') | (df.dqa_sex != 'OK') | (df.dqa_age != 'OK') | (df.case_status == 'Pending')] df1 = df0[['cpims_id', 'child_names', 'age', 'case_category', 'dqa_sex', 'dqa_dob', 'dqa_age', 'case_st...
f2c30e87937ce4fac1dd00cd597ee52946d80d07
16,677
import pickle def get_3C_coords(name): """ Formatted J2000 right ascension and declination and IAU name Returns the formatted J2000 right ascension and declination and IAU name given the 3C name. Example >>> ra,dec,iau = get_3C_coords('3C286') >>> print ra,dec,iau 13h31m08.287984...
1e48ca0535c6cdb5eb2330f3dcfd666e40eef33f
16,678
import json def get(player): """Get the cipher that corresponding to the YouTube player version. Args: player (dict): Contains the 'sts' value and URL of the YouTube player. Note: If the cipher is missing in known ciphers, then the 'update' method will be used. """ if DIR.exists(...
dd658d8aad775fa7871e3efa642b0aad89f8f801
16,679
def divide(x, y): """A version of divide that also rounds.""" return round(x / y)
1bf9e5859298886db7c928613f459f163958ca7b
16,680
def create_root_ca_cert(root_common_name, root_private_key, days=365): """ This method will create a root ca certificate. :param root_common_name: The common name for the certificate. :param root_private_key: The private key for the certificate. :param days: The number of days for which the certific...
5bf83b8ba56c6dde9f6c2ed022c113350425aa33
16,681
def hist1d(arr, bins=None, amp_range=None, weights=None, color=None, show_stat=True, log=False,\ figsize=(6,5), axwin=(0.15, 0.12, 0.78, 0.80),\ title=None, xlabel=None, ylabel=None, titwin=None): """Makes historgam from input array of values (arr), which are sorted in number of bins (bins) in...
c74771de0df0e9f4d65490a09346d2af18d53cc7
16,682
def format_validate_parameter(param): """ Format a template parameter for validate template API call Formats a template parameter and its schema information from the engine's internal representation (i.e. a Parameter object and its associated Schema object) to a representation expected by the curre...
4ed21c80bf567beca448065089bfe22fef6cfb17
16,683
import string def get_template(name): """Retrieve the template by name Args: name: name of template Returns: :obj:`string.Template`: template """ file_name = "{name}.template".format(name=name) data = resource_string("pyscaffoldext.beeproject.templates", file_name) return...
933e597b48b5ed01a29d191fd0fe04371b1baeb6
16,684
def box3d_overlap(boxes, qboxes, criterion=-1, z_axis=1, z_center=1.0): """kitti camera format z_axis=1. """ bev_axes = list(range(7)) bev_axes.pop(z_axis + 3) bev_axes.pop(z_axis) # t = time.time() # rinc = box_np_ops.rinter_cc(boxes[:, bev_axes], qboxes[:, bev_axes]) rinc = rotate_iou...
45aa39e9f55f8198ccbe5faf6a00cf27279057fa
16,685
def _apply_graph_transform_tool_rewrites(g, input_node_names, output_node_names): # type: (gde.Graph, List[str], List[str]) -> tf.GraphDef """ Use the [Graph Transform Tool]( https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/ graph_transforms/README...
15d9609357d45fd164fd1569d35669148e66acd8
16,686
def big_bcast(comm, objs, root=0, return_split_info=False, MAX_BYTES=INT_MAX): """ Broadcast operation that can exceed the MPI limit of ~4 GiB. See documentation on :meth:`big_gather` for details. Parameters ---------- comm: mpi4py.MPI.Intracomm MPI communicator to use. objs: objec...
341591b207ef793b32e6b727f14533dbe119312d
16,687
def get_task(appname, taskqueue, identifier): """Gets identified task in a taskqueue Request ------- ``` GET http://asynx.host/apps/:appname/taskqueues/:taskqueue/tasks/:identifier ``` Parameters: - appname: url param, string, the application name under wh...
c11aadab178776a6246163f2146e9a91d949e3bc
16,688
def GetBuiltins(stdlib=True): """Get the "default" AST used to lookup built in types. Get an AST for all Python builtins as well as the most commonly used standard libraries. Args: stdlib: Whether to load the standard library, too. If this is False, TypeDeclUnit.modules will be empty. If it's True, ...
68b6ad916e4a2ab50774e5f1e8da7b1106cdb2e5
16,689
def assign_style_props(df, color=None, marker=None, linestyle=None, cmap=None): """Assign the style properties for a plot Parameters ---------- df : pd.DataFrame data to be used for style properties """ if color is None and cmap is not None: raise ValueErr...
93bd50e81a988594a42bce26a48d9d24e0e9c6ba
16,690
def to_dbtext(text): """Helper to turn a string into a db.Text instance. Args: text: a string. Returns: A db.Text instance. """ if isinstance(text, unicode): # A TypeError is raised if text is unicode and an encoding is given. return db.Text(text) else: try: return db.Text(text, ...
74704f42e8cb05be24df3b32e8964382da9c488e
16,691
import zmq import time def zmq_init(pub_port, sub_port_list): """ Initialize the ZeroMQ publisher and subscriber. `My` publisher publishes `my` data to the neighbors. `My` subscriber listen to the ports of other neighbors. `sub_port_list` stores all the possible neighbors' TCP ports. ...
fcde81e7387d49e99cd864cea233b1ba02ac679c
16,692
from typing import Dict from typing import Tuple import tqdm def get_all_match_fractions( residuals: Dict[str, np.ndarray], roi_mask: np.ndarray, hypotheses: np.ndarray, parang: np.ndarray, psf_template: np.ndarray, frame_size: Tuple[int, int], n_roi_splits: int = 1, roi_split: int = 0...
65e0da2634dc0f5870fa1c8620ab064f82ffc81a
16,693
def dot(u, v): """ Returns the dot product of the two vectors. >>> u1 = Vec([1, 2]) >>> u2 = Vec([1, 2]) >>> u1*u2 5 >>> u1 == Vec([1, 2]) True >>> u2 == Vec([1, 2]) True """ assert u.size == v.size sum = 0 for index, (compv, compu) in enumerate(zip(u.store,v.st...
e431800750c8f7c14d7412753814e2498fdd3c09
16,694
def isvalid(number, numbers, choices=2): """Meh >>> isvalid(40, (35, 20, 15, 25, 47)) True >>> isvalid(62, (20, 15, 25, 47, 40)) True >>> isvalid(127, (182, 150, 117, 102, 95)) False """ return number in sums(numbers, choices)
c32ee0fe1509c0c1f48bdf8f6b9f8fe5b00fb8f8
16,695
def from_rotation_matrix(rotation_matrix: type_alias.TensorLike, name: str = "quaternion_from_rotation_matrix" ) -> tf.Tensor: """Converts a rotation matrix representation to a quaternion. Warning: This function is not smooth everywhere. Note: In the fol...
2eab1984206c57ec64c4be2b3652008773d9c037
16,696
def mark_text(text): """Compact rules processor""" attrs = {} rules = [] weight = 0 attrs['len'] = len(text) text = text.replace('.', ' ').replace(',', ' ').replace(u'№', ' ').strip().lower() words = text.split() textjunk = [] spaced = 0 attrs['wl'] = len(words) attrs['junkl'...
7287535d3a9c3bb302f9cc98ca6e7fa2ec4c9a40
16,697
def create_faucet(client): """Create a wallet using the testnet faucet""" test_wallet = generate_faucet_wallet(client, debug=True) return test_wallet
a9cfb7e3287f30e49c741e7e0f9ac919d429a396
16,698
def model_flux(t_dec,B,P_max,R,Ne,d_l,z,mp,me,e,c,sigma_t,time,nu,Gamma,E_k, n,eps_b,eps_e,p,j_ang): """ Function for deriving the flux for the spectrum or light curve at given times and frequencies """ # calculate lorentz factors, characteristic frequencies and # jet break time gamma_m = Gamma*eps_e*((p-2)/(p-...
15658d57ae5d837d416731427e1227eb304b4b75
16,699