content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_qa_args() -> Namespace: """Get command line arguments""" parser = ArgumentParser(description="Arguments for QA inference") parser.add_argument("dataset", type=load_jsonl_dataset, help="Path to the jsonlines dataset file") parser.add_argument("--text-col-names", dest="text...
040f9d668de345e65ce2bf77b992305797bd31d8
3,608,000
import shutil def get_archive_name_and_format_for_shutil(path): """Returns archive name and format to shutil.make_archive() for the |path|. e.g., returns ('/path/to/boot-img', 'gztar') if |path| is '/path/to/boot-img.tar.gz'. """ for format_name, format_extensions, _ in shutil.get_unpack_formats(...
152d68ea9613d7253f78c37ce85758a2c8bc67f9
3,608,001
def cosine_similarity(filename1, filename2): """ Wrapper around `bl_cosine_similarity` function. Params: - filename1 is the first file to use. - filename2 is the second file to use. Returns a dict {similarity, song1, song2} containing the computed cosine similarity and the created ...
dcaa29212e9b491d605beb45dd3eedd56f671fc5
3,608,002
def label_candidates_db(labeler, cids_query, label_functions, apply_existing=False): """ This function is designed to label candidates and place the annotations inside a database. Will be rarely used since snorkel metal doesn't use a database for annotations. Important to keep if I were to go back towar...
e62389370f377697446a72be5896157b3cd03ee7
3,608,003
import nibabel as nb import os import numpy as np import scipy.ndimage as ndimage import subprocess import skfmm # scikit-fmm def skeletonise_volume(vol_fname, threshold_type='percentage', threshold_val=0.2, method='edt', CLEANUP=True): """ Take an ROI, threshold it, and create 2d tract skeleton requires...
291d96a1ba5602369c1d76cfb257b0666cb61f00
3,608,004
from datetime import datetime def pickem_handler(event, context): """ Handles the requests from the `/pickem` command to the lambda function that is responsible for handling API requests. """ ## Uncomment this when I trigger from SNS params = parse_qs(event['body']) token = params['token'...
2c37efc9e8f782e38708948eeec43e9c04cf8593
3,608,005
import base64 import binascii import hashlib def do_handshake(method, headers, transport, protocols=()): """Prepare WebSocket handshake. It return http response code, response headers, websocket parser, websocket writer. It does not perform any IO. `protocols` is a sequence of known protocols. On suc...
207e24a28836ea3ea01a8b667e421de0b39286ed
3,608,006
async def get_all_people(): """Get all people from the database.""" persons = await collection.find().to_list(1000) return persons
0a3aff3fe4c39c2e3fcfb3abb78d50c166df910f
3,608,007
import inspect def plugin(cls): """Decorator to register a class as a Shell extension object This decorator can be used to register a class structure as a Shell extension object. After registering the class it self it will also scan for inner classes and register them as nested extension objects. ...
c788e5b84a05ea93570f66df36697f5c052c6f2a
3,608,008
import os import errno def IsFileExist(filename: os.PathLike) -> bool: """Checks if a resource file exists.""" try: filename = AsResourcePath(filename) if os.path.isfile(filename): return True except IOError as ex: if ex.errno != errno.ENOENT: raise ex # Reraise unknown error. return ...
3fdf56e4af9af4396a39bb6cec15393db7d3bcc6
3,608,009
def count_words(text: str, tokenizer=None) -> int: """ Count number of words in a text. Arguments: --------- text: str Text whose words are to be counted. tokenizer: default=None Object with a tokenize method. Either instantiated or not works. \ If tokenizer is available...
98f3c3e1baa3cedaecb905dcc1fd2e2d9559a741
3,608,010
import fnmatch def list_stacks(conn, name_filter='*', verbose=False): """List active stacks""" states = FAILED_STACK_STATES + COMPLETE_STACK_STATES + IN_PROGRESS_STACK_STATES + ROLLBACK_STACK_STATES s = conn.list_stacks(states) stacks = [] for n in s: if name_filter and fnmatch(n.stack_na...
3e9de4b7c30969c0a0b904f77563ec440970bac1
3,608,011
def agg_maxabs_sign_at_n(m, n=1): """ Select the farest value from 0 between the mean of the n greater values and the mean of the n lower values of array m Aggregate before the normalization :param m: array m, float or int """ m_ = np.copy(m) m_.sort() ...
4c62edde480776e6fda2e22e1d538849ce38c368
3,608,012
from typing import Tuple def run() -> Tuple[Response, int]: """ This function implements Action Provider interface for launching an action instance. This function parses the request_id from a request body and from it determines whether a new action should be launched or whether to return the ...
67608335fb2458448b5cf7d185d81abcc3af2275
3,608,013
import os def modpath(request): """ Ajax controller that prepares and submits the new modpath jobs and workflow. """ session = None try: session_id = request.session.session_key resource_id = request.POST.get('resource_id') cancel_status = request.POST.get('cancel', '') ...
8b57eb219ca731a480f548ec8d4f40ac564b1e30
3,608,014
import os def load_metaclass(namespace, class_name): """Load binary data into a MetaClass container. :param namespace: The name of the namespace for the class. :param class_name: Name of the class. :return: A MetaClass container, deserialized from previously deployed binary data. """ try: ...
11445dc9a7c56e985164b23249c3cc7d6924e2da
3,608,015
from operator import add def linear(m, c, x): """This function will calculate the y in y = m * x + c""" print("LINEAR EQUATION %d * %d + %d" % (m, x, c)) return add(multiply(m, x), c)
f9dcfdd8a1359923a11effb4fb48a910ea3ed7a8
3,608,016
from datetime import datetime async def UploadHandlerMem(request): """ POST handler that accepts uploads of files. It does not store the content of the file, just creates entry in the dictionary to keep track of upload activity. """ # You cannot rely on Content-Length if transfer is chunked. t...
76b106418dcadc477b4571cd429f1cebce57b3a9
3,608,017
def translate_url(url, lang_code): """ Given a URL (absolute or relative), try to get its translated version in the `lang_code` language (either by i18n_patterns or by translated regex). Return the original URL if no translated version is found. """ parsed = urlsplit(url) try: match ...
89ee11eb0a614121052011ed0b3de5a22c479bd4
3,608,018
def perspective(img, startpoints, endpoints, interpolation=Image.BICUBIC): """Perform perspective transform of the given PIL Image. Args: img (PIL Image): Image to be transformed. startpoints: List containing [top-left, top-right, bottom-right, bottom-left] of the orignal image endpoint...
d0ee2c38ae7675be6de5df153894d5ae51149cc6
3,608,019
def ray_to_Jonesvector(ode_sol, ne_extent, probing_direction = 'z'): """Takes the output from the 9D solver and returns 6D rays for ray-transfer matrix techniques. Effectively finds how far the ray is from the end of the volume, returns it to the end of the volume. Args: ode_sol (6xN float): N rays...
16cc88350f866a6394bb0e508641135e6b9f31bc
3,608,020
import sys def ToBytes(string): """Convert a str type into a bytes type Args: string: string to convert Returns: Python 3: A bytes type Python 2: A string type """ if sys.version_info[0] >= 3: return string.encode('utf-8') return string
3d84c928e91140b56a22d6e54b966a626b18d640
3,608,021
def plot_missing_data(df, sample_rate): """[summary] Args: df ([type]): [description] sample_rate ([type]): [description] Returns: [type]: [description] """ fig = msno.matrix(df.sample(sample_rate)) plot = fig.get_figure() # plot = fig.savefig('Missing Data Matrix.p...
064300948948234b65bd41dd6dcd437613cfed12
3,608,022
def is_unsupported(func): """ Checks whether the func is supported by dygraph to static graph. """ if any(func in m.__dict__.values() for m in BUILTIN_LIKELY_MODULES): translator_logger.log( 2, "Whitelist: {} is part of built-in module and does not have to be transformed...
1945f3f954625a594d72a4096bbf1504036ec140
3,608,023
import collections def recursive_dict_update(d, u): """Add all of the items of u into the d""" for k, v in u.items(): if isinstance(v, collections.Mapping): d[k] = recursive_dict_update(d.get(k, {}), v) else: d[k] = v return d
1fec47def1115a8a2938303c3868cf3af86b8c6c
3,608,024
def define_radius_by_order(node_loc, elems, system, inlet_elem, inlet_radius, radius_ratio): """ This function defines radii in a branching tree by 'order' of the vessel Inputs are: - node_loc: The nodes in the branching tree - elems: The elements in the branching tree - system: 'strahler','hor...
9001a09d22e255d48fd9f0ec715f78d019e3c657
3,608,025
def produce_labels(y, return_stats=True): """Produce labels array from e.g. event (unordered) trigger codes. Parameters ---------- y : ndarray, shape (n_epochs,) Array of trigger codes. return_stats : bool Whether to return optional outputs. Returns ------- inv : ndarr...
d89c419121a6f3ca0eff615d777489b31d7f2b41
3,608,026
def getSampleType(name): """Given a sample name return the sample type""" backgrounds = open("share/sampleNamesShort.txt").readlines() backgrounds = [i.rstrip("\n") for i in backgrounds] signal = ['TTS','BBS','TTD','BBD','XX','YY','zprime'] data = ['data'] sampletype = '' if name=='data': ...
82055b2df095e1771f9bd616d6a04759ef16c7ef
3,608,027
def read_szf_fmv_12(eps_file): """ Read SZF format version 12. beam_num - 1 Left Fore Antenna - 2 Left Mid Antenna - 3 Left Aft Antenna - 4 Right Fore Antenna - 5 Right Mid Antenna - 6 Right Aft Antenna as_des_pass - 0 Ascending - 1 Descending swath_indicator -...
2b4db2a6a2bbfe46302ea4d4d0fff4f7dab72336
3,608,028
def ped_liposarcoma(): """Create pediatric liposarcoma fixture.""" return { "label_and_type": "ncit:c8091##merger", "concept_id": "ncit:C8091", "xrefs": ["mondo:0003587", "DOID:5695"], "label": "Childhood Liposarcoma", "aliases": [ "Liposarcoma", "...
f69e480a449c9ecb8ceda3d8f14ec777afc769f3
3,608,029
def _prepare_float(data: str) -> str: """ Removes unnecessary characters from the string representing an integer """ return data.replace(",", ".")
ef786b391b6b510b95b52958d73efd7890d05b10
3,608,030
def random(self): """ :param seed: Put a seed to generate random FSMs (default: "seed") :param min: The minimum number of inputs or outputs in the FMS (included) :param max: The maximum number of inputs or outputs in the FMS (included) :param states: :return: A pack of random FSMs """ se...
fd2c928485bb5d9c8974f659996291d2b96c2bef
3,608,031
def translate_circuits(circuits, alias_dict): """ Applies :function:`translate_circuit` to each element of `circuits`. Creates a new list of Circuit objects from an existing one by replacing operation labels in `circuits` by (possibly multiple) new labels according to `alias_dict`. Parameters ...
d0722d18fd3ac79f0f17b37804048a82b6562020
3,608,032
import math def place_tacks(start, end, boat, wind): """Places tacks between two waypoints. Algorithm description: If no tacks are required, add the last point and return. Otherwise Get favored side and confidence on [-1, 1] Set lateral boundaries on the beat (r_bound, l_bound) ...
cf99341dfba65c4424e467f30324e30c0301fd17
3,608,033
import numpy def w_cache_predict(theta, lam, uvw, src, guv, wstep=2000, kernel_cache=None, kernel_fn=w_kernel, **kwargs): """Predict visibilities using w-kernel cache :param theta: Field of view (directional cosines) :param l...
1ce7f54ca22690b199cd7db5b57927f4f061fdb0
3,608,034
def eval_trace2vec(log): """Evaluate different parameter sets for trace2vec. This function starts with a baseline trace2vec model and varies different parameters in isolation to check how they affect the resulting accuracy of the model. The parameters under investigation are: window size, batch siz...
16b454d0c22b7243934e88b4a89126aaa3beab5e
3,608,035
import tqdm def find_shortest_time(source, target, cave): """ Use a modified version of Djikstra's algorithm. """ # Initialize algorithm unvisited = set() distances = {} options = SortedList() # Used for finding minimum - stores in format (distance, x, y, t) for x in range(cave.shape[...
24e2d8d242774d2e9b1fec2f4588073ce40f22ee
3,608,036
import numpy.oldnumeric as Numeric def vvmult(a,b): """ Compute a vector product for 3D vectors """ res = Numeric.zeros(3, 'f') res[0] = a[1]*b[2] - a[2]*b[1] res[1] = a[2]*b[0] - a[0]*b[2] res[2] = a[0]*b[1] - a[1]*b[0] return res
0c5f5d80aa716b7dd8d1b0a9193efdeb53450a64
3,608,037
import hashlib def generate_ext(content_type, body): """Implements the notion of the ext as described in http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-02#section-3.1""" if content_type is not None and body is not None and len(content_type) > 0 and len(body) > 0: content_type_plus_body =...
f4ee3845c68333b51c05ba2bba48e31ac4c989bd
3,608,038
import warnings def fit_2dgaussian(data, error=None, mask=None): """ Fit a 2D Gaussian plus a constant to a 2D image. Parameters ---------- data : array_like The 2D array of the image. error : array_like, optional The 2D array of the 1-sigma errors of the input ``data``. ...
a573ec1def4602dfea7d309c8b7de6d5b325eeab
3,608,039
def auth_backend_configured(name, mount_point, config): """ Configure the already enabled backend. :param name: ID for state definition :param mount_point: The mount point of the backend :param config: Dictionary with the config values to set. """ ret = { 'name': name, 'comm...
ff6a874bc00f853b6855c5a251f55674a5ce7aec
3,608,040
from mashcima.generate_staff_lines import generate_staff_lines from mashcima.transform_image import transform_image as transform_image_function from typing import Optional def multi_staff_annotation_to_image( repo: SymbolRepository, main_annotation: str, above_annotation: Optional[str], ...
1b3814badd4f3831995bab648abf52073239ada3
3,608,041
def _format_headers(tabs, current_tab_number, line_length): """Formats just the tab portion if the config specifies a multi-tab menu Called from format_menu() Args: tabs (list of tab.Tab): list of Tab objects current_tab_number (int): number of currently selected tab (always 0 for single-t...
d99d17790ff9580c2a13dd39876270a1b8b6d9d9
3,608,042
def counting_sort(values, max_value): """Sorts integers using the Counting Sort algorithm. Args: values: iterable, contains the integers to sort should be between 0 and max_value max_value: maximum value the numbers can take Returns: a sorted list of the nu...
fccf1b91bb2c300d22e316057b11dab3bb0ee86f
3,608,043
def strategy_none(cookies, cps, history, time_left, build_info): """ Always return None This is a pointless strategy that will never buy anything, but that you can use to help debug your simulate_clicker function. """ return None
6cd90c6eb7cfdc76683e663b69efcc893034d51d
3,608,044
from typing import Optional def convert_OBvalue( byte_string: bytes, is_little_endian: bool, struct_format: Optional[str] = None ) -> bytes: """Return encoded 'OB' value as :class:`bytes`.""" return byte_string
aebd92207aedbac0dc0c4cfac3e92ac099c5d640
3,608,045
import random import example def add_or_sub_in_base(sample_args): """Module for addition and subtraction in another base.""" context = composition.Context() entropy, sample_args = sample_args.peel() entropy_p, entropy_q = _entropy_for_pair(entropy) p = number.integer(entropy_p, signed=True) q = number.int...
f4fef4647332ede3c791649360c530584d9067bf
3,608,046
def cal_FCNet(ins, num_ins, num_outs, num_layers, hidden_size, dtype='float64', activation='tanh'): """ calculate FCNet api """ net = psci.network.FCNet( num_ins=num_ins, num_outs=num_outs, num_la...
8faa939a9d6efa5db2d2948a38f7039966e8f71c
3,608,047
from typing import Dict from typing import Tuple def merge_model_results(results: Dict[str, Dict[Tuple[str, int], pd.DataFrame]]) -> pd.DataFrame: """ Combine the results of running :func:`util.analyze_model` across a corpus into a single dataframe. :param results: Mapping from model name to dict...
5d8f01201b08a68ea865a331f6be8a6a50dd8786
3,608,048
def find_missing_integer(lst): """Returns the first missing integer in an ordered list. If not found, returns the next integer. """ try: return sorted(set(range(lst[0], lst[-1])) - set(lst))[0] except: return max(lst) + 1
1e8f25f1670933cf57ae042742c175aac7d905fb
3,608,049
def callcongress(): """Verify or collect State intofrmation.""" response = VoiceResponse() from_state = request.values.get('FromState', None) if from_state: gather = Gather( num_digits=1, action='/callcongress/set-state', method='POST', from_stat...
23497f7b16266a1d9cd215c0f1ab5a3f6bf23931
3,608,050
from typing import Dict from typing import Any def is_deprecated(property_dict: Dict[str, Any]) -> bool: """Test. Check if a property is deprecated without looking in description""" return False
2c65c4ead0ba216d26257b3622b074e840f107c8
3,608,051
import socket import errno import select def readNetstring(sock): """ Attempt to read a netstring from a socket. """ # First attempt to read the length. size = '' while True: try: c = sock.recv(1) except socket.error as e: if e.errno == errno.EAGAIN: ...
d4f0994b4c9020f23e970111fcc68be5b6cf55f2
3,608,052
def plug_has_source(plug, nested=False): """Return True if ``plug`` has any source connection, False otherwise. Args: nested (bool): If True, extend the check to all children in ``plug`` hierarchy. Returns: bool: """ stack = deque([plug]) while stack: plug =...
5b8f6a045199cc0f2a86a7da149ab732b2c3af95
3,608,053
import warnings def DeeplabV2(input_shape, upsampling=8, apply_softmax=True, weights='voc2012', input_tensor=None, classes=21): """Instantiate the DeeplabV2 architecture with VGG16 encoder, optionally loading weights pre-trained on VOC2012 segmentation. Note that pre-trained mo...
d78eea82315d2d074b40c1e263eadaf4c7ddd197
3,608,054
import msvcrt def anykeyevent(): """ Detects a key or function key pressed and returns its ascii or scancode. """ if msvcrt.kbhit(): a = ord(msvcrt.getch()) if a == 0 or a == 224: b = ord(msvcrt.getch()) x = a + (b*256) return x else: ...
0c38b6eca60bbb98a77859888e87ad8fc61ccf85
3,608,055
def get_data_month(data: pd.DataFrame) -> pd.Series: """Get month value from data. :param pd.DataFrame data: the data to get months from. :return: (*pd.Series*) -- list of months. """ return data["Date"].dt.month
06d630cc379b32c064273f9b611caebc676dcc50
3,608,056
import logging def parse_csv_data(csv_filename: str) -> list: """Takes in a csv filename and returns a list with each item being a new line of the file. :param csv_filename: The name of a csv filename, '.csv' appendix is optional :type csv_filename: str :return: A list of strings with each ...
ef388507534b6e7e1b82cf5e5f0036e9dd5819dd
3,608,057
from typing import Union def parse_message_data(message: str, user: Union[UserInfo, str] = '', command_prefix: str = '!') -> Message: """ Returns a Message object Parse the standard message data received from twitch IRC """ parts = message.split(' ') prefix = None channel = '' irc_comm...
73e956963ead532a9558f87eff08e61744a6bed3
3,608,058
def getScanDirectory(self): """Displays an open folder dialog window to allow the user to select the folder holding the DICOM files""" try: logger.info('WriteXMLfromDICOM.getScanDirectory called.') #cwd = os.getcwd() scan_directory = QFileDialog.getExistingDirectory( sel...
a14cb40986d5fde70972543161f147425dbc74b2
3,608,059
def format_cron_sec(cron_sec) -> int: """ Format the input second range :param cron_sec: initial second value :return: int(cron_sec) :rtype: int """ if not isinstance(cron_sec, str): raise TypeError( ErrorMsg.DATA_TYPE_ERROR.get_msg( ".The target type is {...
01b74280b7383e001acf27b131a69224fa2767c8
3,608,060
def pearson7(x, amplitude=1.0, center=0.0, sigma=1.0, expon=1.0): """Return a Pearson7 lineshape. Using the wikipedia definition: pearson7(x, center, sigma, expon) = amplitude*(1+arg**2)**(-expon)/(sigma*beta(expon-0.5, 0.5)) where arg = (x-center)/sigma and beta() is the beta function. ...
b5011e341be2988418bcc9157c897594463825c8
3,608,061
def _parse_form(request): """ Parse responses from user purchases. :param request: :return: """ d = request.POST dv = m.Delivery.objects.get(pk=int(d['dv-id'])) od = m.Order(request.user, dv, with_dummies=True) prev_purchases = {pc.product: pc for pc in od.purchases} for pd in dv...
5e46f1f1b8f226d6204a616e88f2800e666c71f6
3,608,062
def calculate_synset_similarity(measure,s1, s2): """ Calculates and returns the similarity between two synsets based on specified measurement """ if measure == 'path': similarity = s1.path_similarity(s2) elif measure == 'lch': similarity = s1.lch_similarity(s2) elif measure == '...
2e90a74af145849cecc79ed91b9640aefe64f197
3,608,063
def load(trained_model): """ Loads a pre-trained model. """ model = load_model(trained_model) return model
dd162a254073cea218a1d66a30c729711b9d6d74
3,608,064
def unafold_parser(lines=None): """Parser for unafold output""" result = ct_parser(lines) return result
5109b818dc64cfd028c6880d2c882ec55d64a416
3,608,065
def search_pubs_by_uuid(uuid): """ Search publications by `uuid`. Args: uuid (str): UUID of publication. Returns: list: List of matching :class:`.DBPublication` or ``[]`` if no match \ was found. """ with transaction.manager: return list(_get_handler()._ze...
ca1a50afe13da3bf87d67b5255415c020927a394
3,608,066
def import_with_fiona(fpath, source): """ Use fiona to import a parcel file. Return a list of dict objects containing WKT-formatted geometries in addition to any metadata. """ shapes = [] try: with fiona.drivers(): data = fiona.open(fpath) for obj in data: ...
663821e4a4cbd0486941b7f1c2b5a650af2bfda2
3,608,067
def binarychunk_submit(request): """Accepts requests which contain a packetized chunk of binary data uploaded for an encounter whose text has already been submitted but is waiting for all binary from the mobile client to be received prior to uploading to the data store. Note: There is a...
63ed0e1aeaa5dcb4b3092e4344796bddeed1f99e
3,608,068
def aggregate_space_time_average(VarTable, df_dict, suffix, start_date, end_date): """ VarTable: (dataframe) a dataframe with date ranges as the index df_dict: (dict) a dictionary to which computed outputs will be stored suffix: (str) a string representing the name of the original table start_date: ...
cc6c297b3e61e41fe2e169aaf8a3440d8683120f
3,608,069
import array def draw_arrow(gc, pt1, pt2, color, arrowhead_size=10.0, offset1=0, offset2=0, arrow=None, minlen=0, maxlen=inf): """ Renders an arrow from *pt1* to *pt2*. If gc is None, then just returns the arrow object. Parameters ========== gc : graphics context where to ...
bdd7af22baba561e2f6f96d62fbf14639d5b55aa
3,608,070
import os def _is_win() -> bool: """ 実行環境がWindowsかどうかを判定します :return: True Windows, False Windows以外 """ return os.name == 'nt'
f46e13641004cccea4ae4692ca0f8fbcb797cf32
3,608,071
def sort_return_tuples(response, **options): """ If ``groups`` is specified, return the response as a list of n-element tuples with n being the value found in options['groups'] """ if not response or not options.get("groups"): return response n = options["groups"] return list(zip(*(r...
14b49449d8fda6050bf4223365ba0f93918fe58a
3,608,072
def dare_scalar(A, B, Q, R): """ Solve the discrete-time algebraic Riccati equation for the scalar case of a single state and a single input. In this case the equation is a scalar quadratic equation. """ A, B, Q, R = [float(var) for var in [A, B, Q, R]] A2 = A**2 B2 = B**2 aa = -B2...
20278b42c809a6c4fd894abfb4721b09f15173a4
3,608,073
def _common_prefix(string_list): """ Given a list of pathnames, returns the longest common leading component """ if not string_list: return "" min_str = min(string_list) max_str = max(string_list) for i, c in enumerate(min_str): if c != max_str[i]: return min...
4360e712c6c4d3d650a226c1fe7f3a4941861513
3,608,074
def obs_residual_ssh(name, tides, sdt, edt): """Calculates the observed residual at Point Atkinson, Campbell River, or Victoria. :arg name: Name of station. :type name: string :arg sdt: The beginning of the date range of interest. :type sdt: datetime object :arg edt: The end of the date r...
d80cbefbf904d774144a9248fbffda9447701e73
3,608,075
def readIDMap(options): """ Load the specififed lookup table for hit IDs. If the parseStyle requested is 'gis', convert keys to integers. The values are always convereted to integeres since they are assumed to be taxids """ # map reads to hits if options.parseStyle == GIS: keyType = ...
061700e3797408072408474bb241aa18e9fd4898
3,608,076
def sky_to_camera(alt, az, focal, pointing_alt, pointing_az): """ FUNCTION COPIED FROM lstchain.reco.utils to avoid hiperta depend on lstchain. Coordinate transform from aky position (alt, az) (in angles) to camera coordinates (x, y) in distance Parameters ---------- alt: astropy Quantity a...
8e984ebf8a0a687149adae384e57c0d3ffe180fa
3,608,077
def qualify(func: object) -> str: """Qualify a function.""" return ".".join((func.__module__, func.__qualname__))
bfda7050ff94f407a2a0d4b00b87ecb0370e9110
3,608,078
from typing import Union from typing import List from typing import Tuple from typing import Callable def lives_duration_histogram( datasets: Union[AbstractTimeSeriesDataset, List[AbstractTimeSeriesDataset]], xlabel: str, label: Union[str, List[str]] = "", bins: int = 15, units: str = "m", vli...
8ada53d1fbf9e8998556aa44e48c8abb02d31d35
3,608,079
from datetime import datetime def marshal_background_event_data(request): """Marshal the request body of a raw Pub/Sub HTTP request into the schema that is expected of a background event""" try: request_data = request.get_json() if not _is_raw_pubsub_payload(request_data): # If...
34ae9bb1b9bb61f27dae1a432fb9a36d377faf5d
3,608,080
def render_from_json(file_path: str) -> Image.Image: """Render 2D image from specfile written in json. :param file_path: json specfile path. :type file_path: str :return: rendered and merged image. :rtype: Image.Image """ return PillowProjectSpec.from_json(file_path).render()
440a9177879329f819fff790a2ca514a40c109dc
3,608,081
from cms_mptt import models as mptt_models def install_mptt(cls, name, bases, attrs): """Installs mptt - modifies class attrs, and adds required stuff to them. """ if not Mptt in bases: return attrs if 'MpttMeta' in attrs and not issubclass(attrs['MpttMeta'], MpttMeta): raise Val...
7fd87571c58425c6d02b314002a2a937e4b5733a
3,608,082
def logout(): """ Logout will logout the current session and redirect to the main page. """ try: weblab_api.api.logout() except SessionNotFoundError: # We weren't logged in but it doesn't matter because we want to logout anyway. pass return redirect(url_for(".login", _ex...
e499786b245690a1e28a88ff05809e3edd7c4ac3
3,608,083
def delete_action(system_id: str, action_id: str): """删除Action权限模型""" url_path = f"/api/v1/web/systems/{system_id}/actions/{action_id}" return _call_iam_api(http_delete, url_path, data={})
639ce2b576cf68014d1164c76a5886994e886382
3,608,084
def getPinInfo(pincode = None): """ Gets Info about the given pincode {"district" : "district_name", "state" : "state_name"} """ global intialSetupFlag if not intialSetupFlag: setup() intialSetupFlag = True data, status = utils.custom_request(cowin_config['pinInfo_host'], cowin_config['url_getPinInfo'], urlP...
fe45be2963cc6d19a61e4db89c623ed3f1315488
3,608,085
def replace_node(network, name_to_node, **kwargs): """ name_to_node: map from name of the node to replace, to the new node """ def inner(node): if node.name in name_to_node: return name_to_node[node.name] else: return node return fns.transform_root_node_...
ae7114833f330c7368e8aa000d413b17c4f917e1
3,608,086
def set_buttons_color(text, item=None): """Sets buttons color: background (bg) foreground (fg) disabledforground (dfg) activebackground (abg) activeforeground (afg)""" bg, fg, abg, afg, dfg = None, None, None, None, None if text in ['info', 'rules', 'ok']: bg = color['bg'] ...
f0efa841abf31a9408477a20e05c6a73cabc688f
3,608,087
def forwardPropagation(features, weights): """ Given the input data features and the weights computes the predictions from the neural network. :param features: Numpy matrix of input data used to make prediction. Each row is a training example and each feature is a column. :param w...
bb12caccd3a42d07f0c421b8d49ebf6ee0cf7201
3,608,088
def filter_list_zones(auth_context, cloud, perm='read'): """List zone entries based on the permissions granted to the user.""" zones = list_zones(auth_context.owner, cloud) if not auth_context.is_owner(): try: auth_context.check_perm('cloud', 'read', cloud.id) except PolicyUnauth...
8b641d02de617f661c011f61937e4168b47ef43b
3,608,089
import requests import json def getSearch(request): """ To search datasets based on query - see search(request) in server.py """ # initialise query run summary = {} url = 'https://scicrunch.org/api/1/elastic/SPARC_PortalDatasets_pr/_search?api_key='+api_key size = '200' include...
d1b8d578e8d3647281247aa2d9e397abdee3bebd
3,608,090
import glob import os import re def get_fit_output_files(models_dir, model_pattern): """Get fit output files matching pattern.""" all_files = sorted(glob.glob(os.path.join(models_dir, '*'))) pattern = re.compile(model_pattern) matching_files = {} for f in all_files: match = pattern.sear...
5832eb5d050eae3fad3e8f710f481181c34017a8
3,608,091
def dimension(dim: float, tol: int = 0, step: float = 0.4) -> float: """ Given a dimension, this function will round down to the next multiple of the dimension. An additional parameter `tol` can be specified to add `tol` additional steps to add a tolerance to accommodate for shrinking. """ #...
a63b84bbc73d25da1c86c9919f61bd32071d92f9
3,608,092
def rgb2yuv(r, g, b): """Convert RGB triplet into YUV :return: YUV triplet with values between 0 and 1 `YUV wikipedia <http://en.wikipedia.org/wiki/YUV>`_ .. warning:: expected input must be between 0 and 1 .. note:: the constants referenc used is Rec. 601 """ check_range(r, 0, 1) ch...
0572f43b7e1d5dd0666850b4a41d885ec5892666
3,608,093
import gluon.contrib.plural_rules as package import pkgutil import sys import logging def read_possible_plural_rules(): """ Creates list of all possible plural rules files The result is cached in PLURAL_RULES dictionary to increase speed """ plurals = {} try: for importer, modname, isp...
f0bbde417c1173311e4265de16758a13638c1f02
3,608,094
import numpy def Projector(wfn, threshold=0.0, n_qubits=None) -> QubitHamiltonian: """ Notes ---------- Initialize a projector given by .. math:: H = \\lvert \\Psi \\rangle \\langle \\Psi \\rvert Parameters ---------- wfn: QubitWaveFunction or int, or string, or array : ...
eb1963c6eca095bac392065250fcb1f629a41e5f
3,608,095
from typing import List def get_swap_count(listA: List[int], listB: List[int], debug) -> int: """ Return the number of swaps we have to make in listB for it to match listA Args: listA: the first list listB: the second list debug: if True display debug output Returns: ...
781999f95ff51c106a2bae7d29e9189f925ff22f
3,608,096
import json import random def tlm(tlm_channel=None,**kwargs): """ This function produces a log message string to be passed into a logger method that captures parameter names and values based on the provided keyword arguments. The keyword arguments and values are encoded into JSON messages. Only values tha...
f4650740ad63d8e1c365da68115761c07d8a16b1
3,608,097
def send_mail(sender: str, recipients: list, title: str, text: str=None, html: str=None, attachments: list=None, **kwargs) -> dict: """ Send email to recipients. Sends one mail to all recipients. The sender needs to be a verified email in SES. """ msg = create_multipart_message(sender, recipients, ...
857e2c20908e3f9a726ba0bb591dad1d76c32ff8
3,608,098
import uuid def create_rand_person(): """Create user with random username, name and email""" user_name = uuid.uuid1() return factories.PersonFactory( # Make User Name different from Name name="User {}".format(user_name), email="{}@example.com".format(user_name) )
4f9744694454a3747bf9a88b324ae4f7051f00c0
3,608,099