content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def player_team(replay_json): """ Returns a list of names of the players on the replay recorder's team """ own_team = get_own_team(replay_json) return [v['name'] for v in replay_json['first']['vehicles'].values() if v['team'] == own_team]
e1510fae3b5f68f22f70ac440fc509ed51c28994
3,620,400
def get_image_writer_set(): """Return the set of installed image writers. The set is returned as a dictionary where names of the image writers are the keys, and the image writer class objects are the values. """ return ImageWriterLoader().loader.get_object_set()
3d703fe96513d2b142efee71d68038df28011aee
3,620,401
import requests import io import logging import time def get_image(location, request_timeout=60, http_max_retries=2, http_retry_interval=3): """Wrapper function that routes to appropriate utility to get image data. Args: location: location of source image data. This can be a URL, ...
79548a39b9508dce7d6806e0e0421e2abd9b196b
3,620,402
import os import re def get_flags(source): """Gets flags from a source file. Args: source (str): Path to the source file (could be any extension). Returns: list[dict[str, _]]: List of maps with keys "type", "name", "default", and "descr" for the respective fields correspondin...
7cb7dc28b333154904619887dba5d21140141809
3,620,403
import torch from typing import Tuple def convert_to_distributed_tensor(tensor: torch.Tensor) -> Tuple[torch.Tensor, str]: """ For some backends, such as NCCL, communication only works if the tensor is on the GPU. This helper function converts to the correct device and returns the tensor + original de...
71eb98868aa89bbfdea4019eff0b93256cb82025
3,620,404
def update_global_variable(): """ 修改全集变量(global关键字) :return: """ global count count = 10 return count
69c91bce24fc77dc731e05178849528e59bae4ba
3,620,405
def cancelReserve(request): """ 알림톡/친구톡 전송요청시 발급받은 접수번호(receiptNum)로 예약전송건을 취소합니다. - 예약취소는 예약전송시간 10분전까지만 가능합니다. - https://docs.popbill.com/kakao/python/api#CancelReserve """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # 예약 알림톡/친구톡 전송 접수번호 receiptNum = "0180...
63960abac51f2121a56e38b48de737c1c9c604b9
3,620,406
def _staircase_ecdf(p, data, complementary=False, q_axis="x", line_kwargs={}): """ Create a plot of an ECDF. Parameters ---------- p : bokeh.plotting.Figure instance, or None (default) If None, create a new figure. Otherwise, populate the existing figure `p`. data : array_like ...
19f8945698cfb6138c67ce025df3bcffb6463f46
3,620,407
def GenerateConfig(context): """Generates the route config""" resources = [ { 'name': context.env["name"], 'type': 'pubsub.v1.topic', 'properties': { 'topic': context.env["name"] }, 'accessControl': { 'gcpIamPolicy': MergeCallingServiceAccountWithAdminPermissionsIntoBindings(context.env, c...
53f7e44ae4f2514826d673572932f91767dd0efd
3,620,408
def get_programs(x_gw_ims_org_id, authorization, x_api_key): # noqa: E501 """Lists Programs Returns all programs that the requesting user has access to # noqa: E501 :param x_gw_ims_org_id: IMS organization ID that the request is being made under. :type x_gw_ims_org_id: str :param authorization: B...
b0907272c5539aec88d2e761a271cd08b61d7b75
3,620,409
def get_non_lib(functions): """ Get all non-library functions @param functions: List of db_DataTypes.dbFunction objects @return: a subset list of db_DataTypes.dbFunction objects that are not library functions. """ return [f for f in functions if not f.is_lib_func]
7f536ff98d647ba5e497b8550bc2497ef45e814b
3,620,410
def _check_duplicates(data, name): """Checks if `data` has duplicates. Parameters ---------- data : pd.core.series.Series name : str Name of the column (extracted from geopandas.GeoDataFrame) to check duplicates. Returns ------- bool : True if no duplicates in data. """ ...
429ce8d092b3a39fc44eeca91d593db22fe7364d
3,620,411
def path_surroundings(md, path, *, radius_pix=130, maxwidth_pix=1000, maxheight_pix=800, maxdist_pix=500, path_color=(255, 100, 0), shorten_by_rotating=True): """Create a generator of ...
a07a66d673f407f37e582d578196bb5053597aa1
3,620,412
def _has_textframe(obj): """ Check if placeholder has TextFrame """ return hasattr(obj, 'TextFrame') and hasattr(obj.TextFrame, 'TextRange')
087e6df38e55d99637e8e7ea998257f323d6d141
3,620,413
def get_mapping(combinable_list): """Determine the mapping from acceptance_id to the register id that can be used to index into an array. """ result = {} array_index = 0 while len(combinable_list) != 0: # Allways, try to combine the largest combinable set first. k ...
085f28c8d1263bc2e547a5671e115d86992af231
3,620,414
import gzip def read_sbs_from_vcf(vcf_file): """ Only reads the chrom, pos, ref and alts from the VCF file. Not strict about checking the headers, and will not filter any mutations. Lines with multiple alts will be split into one mutation for each alt. Non-single-base-substitutions (e.g. deletions...
3b669928e74fcf357c9586998ae908afec5f2008
3,620,415
def get_path(abs_url, **kwargs): """ """ if abs_url is None: return None return urlparse(abs_url, **kwargs).path
caf61367db8cf289251185c967cfb28212f61cbe
3,620,416
def clean_chamber_input(chamber): """ Turns ambiguous chamber information into tuple (int, str) with chamber id and chamber name """ if type(chamber) == str: if chamber == '1': chamber = 1 elif chamber == '2': chamber = 2 elif chamber == 'GA': chamber ...
0ad20c117fc90e523e85ef7061a548b20c68dc92
3,620,417
def search_for_letters(phrase: str = 'life, the universe, and everything', letters: str = 'forty two') -> set: """Display any 'letters' found in a 'phrase'.""" return set(letters).intersection(set(phrase))
36944391599abf971512d21819f88dee9af42f36
3,620,418
import yaml def loadyaml(file, default={}): """Utility function to load from yaml file""" try: with open(file, "r", encoding="utf-8") as f: t = yaml.load(f, Loader=yaml.FullLoader) except FileNotFoundError: t = default return t
a6720094340b71039d2e53ec1f48493480e4e26a
3,620,419
import argparse import google import os def main(args: argparse.Namespace) -> int: """This functions splits a PDF document using the Document AI API""" if not args.project_id: _, project_id = google.auth.default() args.project_id = project_id parent = f"projects/{args.project_id}/locations...
d305707117b68cb481b335d8ec5b61f8bc62aee7
3,620,420
from pathlib import Path def load_fitresult(fit_dir): """ Load a fitresult into a fitting_torch.TorchSingleFitResult or :class:`~pyhdx.fitting_torch.TorchBatchFitResult` object The fit result must be in the format as generated by saving a fit result with `save_fitresult`. Parameters ---------- ...
322c88b9f6b4ff566704b2528963aed52342e752
3,620,421
import getpass def secret(prompt=None, empty=False, default=None): """Prompt a string without echoing. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. default : float, optional Value to return if r...
45c0857e24421dd04909119b324fa6c942f4e640
3,620,422
import os def update_note(store, note, path): """Update a note from the content in a local file """ ext = utils.get_file_ext(path) processor_cls = note_processors.get(ext) processor = processor_cls(path) note.title = processor.get_title() note.content = processor.get_content() note.upd...
177994d9b8933b12c1856949b8cdd2d665730219
3,620,423
def parse_station_list_to_csv(filepath_or_buffer) -> str: """ Return CSV-formatted data """ return _parse_station_list(filepath_or_buffer).to_csv()
c231daaf5bb343f05a959aa2cdbdf85d4f3984b0
3,620,424
def pipelines_name_version_get(name, version): # noqa: E501 """pipelines_name_version_get Return pipeline description and parameters # noqa: E501 :param name: :type name: str :param version: :type version: str :rtype: None """ try: logger.debug( "GET on /pipel...
75c1b15242813539b9cf0f7daf24497ee2357601
3,620,425
import urllib def govuk_url(path): """ :returns: url to the GOV.UK Pay endpoint defined by `path` :param path: path without leading `/` e.g. `payments` """ return urllib.parse.urljoin(settings.GOVUK_PAY_URL, path)
0e0a179d3a6107f9a7f253b5a4d18f8ed3558dcd
3,620,426
def _any_sat(bdd, u, l): """ Recursive part of any_sat """ #Base Cases if u in [0,1]: return l var = _get_var_name(bdd, u) #Arbitrarily consider lower branch if bdd["t_table"][u][1] == 0: l.append("%s" % var) new_u = bdd["t_table"][u][2] else: l...
d8ed5287dff81bb51db711d2929e4810741e67e7
3,620,427
def map_mean_of_horizontal_active_links_to_node(grid, var_name, out=None): """Map the mean of active links in the x direction touching node to the node. map_mean_of_horizontal_active_links_to_node takes an array *at the links* and finds the average of all horizontal (x-direction) link neighbor values ...
b6ef9d12c9f458052473161cd79feb9476b169fd
3,620,428
def gmm_density_centered(x, std): """ Assumes dim=-1 is the component dimension and dim=-2 is feature dimension. Rest are sample dimension. """ if x.dim() == std.dim() - 1: x = x.unsqueeze(-1) elif not (x.dim() == std.dim() and x.shape[-1] == 1): raise ValueError('Last dimension must...
b050114b27ea9163cdaee61077b972bea744cf72
3,620,429
def process_pairs_vg(alns_tuple): """ Finds the pairs in alignments of one read :param alns_tuple: alignments of one read in as a tuple :return: read_id, AS pairs, mapq, metric scores """ read_id, alignments, mapqs, obs_max, end = alns_tuple return read_id, alignments, mapqs, calc_scores((re...
e1bb6cf24ba51e011b937f52586f52bc8d382cd5
3,620,430
from pathlib import Path import logging import yaml def params_from_yaml(args): """Extract the parameters for preparation from a yaml file and return a dict""" # Check the path exists try: config_file_path = Path(args.config) assert config_file_path.exists() except Exception: l...
36beadd8fa4f27471c514a963838aac216aad434
3,620,431
def get_task_monitor(node, uri): """Get a TaskMonitor for a node. :param node: an Ironic node object :param uri: the URI of a TaskMonitor :raises: RedfishConnectionError when it fails to connect to Redfish :raises: RedfishError when the TaskMonitor is not available in Redfish """ try: ...
ee69431e5c9f6711840b01150791296658920fc5
3,620,432
def get_user_ids_from_assigned_location_ids(domain, location_ids): """ Returns {user_id: [location_id, location_id, ...], ...} """ result = ( UserES() .domain(domain) .location(location_ids) .non_null('assigned_location_ids') .fields(['assigned_location_ids', '_id...
12e50ad5befece3c64e7d8172c7cfdb4751ec6de
3,620,433
def extract_sift(fn, extractor, detector): """提取图像特征""" im = cv2.imread(fn, cv2.IMREAD_GRAYSCALE) # SIFT检测器可以检测特征,而基于SIFT的提取器可以提取特征并返回它们 return extractor.compute(im, detector.detect(im))[1]
3d9997b5f57f1fd496dbedb6a327bdfa3a59915f
3,620,434
def is_operator_or_function(term): """ Checks if the term is a LaTeX mathematical operator or function. Source: http://web.ift.uib.no/Teori/KURS/WRK/TeX/symALL.html Args: term: string to be checked. Returns: True if the term is a mathematical operator, False otherwise. """ ...
b4992ffeb213979e9507cbc1b76ad1e861eef7f2
3,620,435
def getGasDensity(x=None, y=None, z=None, grid=None, ppar=None): """Calculates the gas density Parameters ---------- x : ndarray Coordinate of the cell centers in the first dimension y : ndarray Coordinate of the cell centers in the second dimension y ...
04b7a1f4b4441d06ce92b5f6b6fc09e2e614affb
3,620,436
def load_embeds(text_embed, img_embed, dcca_embed): """ Load image and sentence embeddings and create a concatenated version :param text_embed: pickle file containing the sentence embeddings :param img_embed: pickle file containing the image embeddings :param dcca_embed: pickle file containing the deep...
c74da889f05126d4ac2ace30463041d5cb9e22c3
3,620,437
import re def serialize(settings, exclude=None): """Return a consistent, human-readable string serialization of settings.""" if exclude is None: exclude = [] sdict = dict(_variables(settings)) sdict = { k: v for k, v in sdict.items() if k not in exclude } sstr = dumps(sdict, sort_keys=True...
535da5800141d6ef5ebdbeff23579a246480a271
3,620,438
from typing import List from typing import Union def list_or_first(x: List[str]) -> Union[List[str], str]: """ Returns a list if the number of elements is greater than 1 else returns the first element of that list """ return x if len(x) > 1 else x[0]
82e86001b35ecd6542a22fac3c5dd7f7723966d6
3,620,439
import re def parse_version(version_str): """'10.6' => [10, 6]""" return [int(s) for s in re.findall(r'(\d+)', version_str)]
16cfcfc292eb89b6231a266c687f9dfd8caa5a8d
3,620,440
def user(): """Get user details depending on friendship. If you are friends, sensitive data will be shown aswell. Returns: JSON reponse with the basic and sensitive user details. """ username = request.args.get('username') if username is None or username == '': username = auth...
842395d3206356f369db985abcc5de719848e7de
3,620,441
import requests def display_selected_patient_info(MRI): """ Get a patient's latest information and ECG trace image As a very important functionality of the server, the function sends a 'GET' request to the server, get a string that includes all patient's latest info and ECG image b64 string. Then ...
d0a47848451801517e9125bbd7de3b40023cbd60
3,620,442
def circ(x, y, d=1): """ Generation of a circular aperture. Args: | x (np.array[N,M]): x-grid, metres | y (np.array[N,M]): y-grid, metres | d (float): diameter in metres. | comment (string): the symbol used to comment out lines, default value is None. | delimiter (string...
7ff75431b25489db40c6d54710443c2bc4b105d1
3,620,443
from typing import Optional def labels( adata: AnnData, label_filepath: str = None, index_col: int = 0, sep: str = "\t", copy: bool = False, ) -> Optional[AnnData]: """Add label transfer results into AnnData object Parameters ---------- adata: AnnData The data object to a...
221ab6f4ed9d4eb8a189010c45205fbffc3878ab
3,620,444
def contains_common_item_2(arr1, arr2): """ loop through first array and create dictionary object where the keys are the items in the array loop through the second array and check if item in second array exists in the created dictionary """ array1_dict = {} for item in arr1: array1_dict[...
83b4eafe7904d47fd65db3fc3e5a4d598a51efea
3,620,445
def complex_function(z): """ The complex function to plot. *You can write any function here*. :param z: a numpy 2d array of complex numbers. """ return (z - 1) / (z + 1)
242f6b84c50dedbbf28edf52c558d572ab4c6c85
3,620,446
from typing import Union from pathlib import Path from datetime import datetime def write_summary_file(input_folder: Union[Path, str], output_folder: Union[Path, str] = None, geocode_helper: str = None) -> Path: """ Create a new ``.xlsx`` summary file. This f...
4eb7bae9c7a896a7f8e9c976cfeff06481d6f669
3,620,447
def generate_lists(image_dir, subdir): """ 80 images per class in total and 256 classes. Generate a list of lists. Each list contains 256*5 images. :return: a list of lists. Each list contains 256*5 images. """ # last 20 images are for test. index = range(1, 81, 1) # np.random.shuffle(index...
cf3cf9ce7d950f431a161ffc75d6c1f0e0fc8a87
3,620,448
def get_embed(input_data, vocab_size, embed_dim): """ word embedding 输入. :param input_data: 输入. :param vocab_size: 总词语数. :param embed_dim: w2v 维数 :return: Embedded input. """ #embedding 初始化,这边不采用预先训练的embeding,边训练边调参数 embedding = tf.Variable(tf.random_uniform((vocab_size,embed_dim),-...
798e31d7a016e517ec933b55e97eb035e1755f7b
3,620,449
import binascii def encrypt(text, parola): """ Derives a 256-bit key using the PBKDF2 key derivation algorithm from the password. It uses a random password derivation salt (128-bit). This salt should be stored in the output, together with the ciphertext, because without it the decryption...
94ca306d06c64b36facac38a9f44a403b86aadac
3,620,450
def gList(question, items, returnsIndex): """ Returns an item or its index from a list based on user input. :param question: String containing prompt to be displayed. :param items: List of items of which user should choose from. :param returnsIndex: Boolean indicating whether the function should return the item o...
b746338e62c29371e116738ef76b9cf176841259
3,620,451
from typing import List from typing import Union def get_fuselage(dirname: str, isurface: int, surface: Body, yduplicate: bool, nodes: List[np.ndarray], unused_line_elements: List[np.ndarray], quad_elements: List[np.ndarray], ...
69f3e9135252cb6596f8430d7c0adfa202e3f27c
3,620,452
import json def _get_helper(json_expecting_func, **kwargs): """ Helper function used by several functions below """ try: payload = json_expecting_func(**kwargs) response, status_code, mimetype = json.dumps(payload), 200, "application/json" except exceptions.BadRequest as exc: ...
9ff97c5ae07d4f6e6d086813b5287199336c45be
3,620,453
from typing import List def hash_files(paths: List[str]): """ MD5 checksum a list of file paths """ return map(hash_file, paths)
501347f2dc21e7c6e8b53f36c0df0e63b959166c
3,620,454
import os import re def get_version(*file_paths): """Retrieves the version from django_toosimple_q/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) ...
a198d80f80824eb2840e645fc13518abfa341dff
3,620,455
def _probability_of_improvement(mu, sigma, y_max, xi): """ Calculates the probability of improvement at the point 'x', for which: mu = mean(x) sigma = std(x) TODO: should be in log-domain? Parameters ---------- mu : array_like, shape (n,) Mean. sigma : array_like, s...
7a806f78bbb92e534bb04690d933d0c0d9781d25
3,620,456
def length_of_year(year): """ the length of a day :param year: The year you wuld like to know the length. :returns: exact days. a day is longer then 365 days. """ return float(365.2564) if is_leap_year(year) else float(364.2564)
516b46c92869ff520fbbb57aece371ea8176a86a
3,620,457
def remove_hydrogens(mol): """Removes any hydrogens from the graph of a molecule. This is a wrapper around rdkit.Chem.rdmolops.RemoveHs. Parameters ---------- mol: rdkit.Chem.Mol The molecule to be modified. Returns ------- mol: rdkit.Chem.Mol A new molecule with the h...
9b066b40485e3e7dcb5e31eb2bd692022d6b1cd1
3,620,458
def pixel_to_meter(sample, line, geotransform, shift=False): """provide point in map projection coordinates. Parameters ========== sample, line: <integer> Sample and line of an image in pixel coords Geotransform in format as given by GDAL datasets.GetGeoTransform() Returns ======= tupl...
645e482658b3dbf81afceecb90d7d8ed69a92cb1
3,620,459
import logging import requests def get_status(api_key=None, request_id=None, proxies=None, auth=None): """ Получить состояние активации: http://sms-activate.ru/stubs/handler_api.php?api_key=$api_key&action=getStatus&id=$id :param api_key: ключ API авторизации на сервисе :param request_id: id актив...
bf07cd84dcce32a5d842ffe746624e6bf8781955
3,620,460
def match_event(event_type): """Return event type matcher.""" def matcher(func): """Add decorated function to list for event matching.""" func = add_skill_attributes(func) func.matchers.append( {"event_type": { "type": event_type}}) return func ret...
b0e9edf2e246418513c83c2e91101df34e714309
3,620,461
def fetch_data_for_date(record_date, site_id, data_dir): """ Download radar data for a given date and siteId from public S3 bucket """ files = [] bucket = S3.Bucket('noaa-nexrad-level2') data_site_prefix = '{record_date}/{site_id}'.format(record_date=record_date, site_id=site_id) for s3_obje...
6d4213ff2f5d79095925062fca9b92e25680a44a
3,620,462
def update_item_from_dict(table_name, key, dictionary, client): """ Update the item identified by `key` in the DynamoDB `table` by adding all of the attributes in the `dictionary`. Args: table_name (str): key (dict): dictionary (dict): client: Returns: dict ...
333e74bb6f270cb794f6fe8da2de0ad9a40d3a9f
3,620,463
def indirect_bp_names(): """Return a list of valid Indirect Branch Predictor names.""" return _indirect_bp_classes.keys()
21ea71889882fe61d5041f7390f41b08d5e04622
3,620,464
def device_action(device): """ Generates an actionable text for a :class:`~two_factor.plugins.phonenumber.models.PhoneDevice`. Examples: * Send text message to `+31 * ******58` * Call number `+31 * ******58` """ assert device.__class__.__name__ == 'PhoneDevice' number = mask_phone_numb...
f79c4ba89da7bf022d28e15507d091800915243b
3,620,465
def main_app_url(module_scoped_container_getter): """ Wait for the api from fastapi_main_app_main to become responsive """ return h.get_app_url(module_scoped_container_getter, "fastapi_main_app_main")
5f228b31b37d3221038fa57764a447b727f9534a
3,620,466
def _get_sign_array_1d(i: int, nsyms: int) -> Array: """Calculate array of nsyms signs that alternate every 2**i entries.""" sym_ints = jnp.arange(nsyms) # The exponent below is simply a clever way to get the value of the i_spin-th bit # of each integer in the sym_int array, to give us signs which alte...
98f72eab66fb0ee8beb4735a8dfa2b387d61bcae
3,620,467
def solve(lines): """Solve the problem.""" mem = dict() mask = "X" * 36 for line in lines: if line.startswith("mem"): m = MEM_RE.match(line) loc, val = [int(v) for v in m.groups()] mem[loc] = apply_val_mask(mask, val) elif line.startswith("mask"): ...
875eb79467bfa98a7fa90cf2eb13fe3ff74faeae
3,620,468
def _squash_unicode_in_bestrefs(bestrefs, localrefs): """Given bestrefs dictionariesy `bestrefs` and `localrefs`, make sure there are no unicode strings anywhere in the keys or complex values. """ refs = {} for filetype, refname in bestrefs.items(): if isinstance(refname, tuple): ...
50cc5fb89bfb329465e37bbbff469862181f1659
3,620,469
def enum(**enums): """Enable use of enums by utilizing types""" return type('Enum', (), enums)
0e9fd35df64ae775d2bf245c376cc0c9af06b4a6
3,620,470
import configparser def create_arithmetictrainer_from_files(*files) -> Arithmetictrainer: """ Create a Arithmetictrainer from a configuration file. """ config_files = configparser.ConfigParser() config_files.read(*files) if len(config_files.sections()) == 0: raise ValueError("Could not...
ad2a98d32372257a4e11886373a0403e395b7f5e
3,620,471
def shrink(epsilon, x): """The shrinkage operator. This implementation is intentionally slow but transparent as to the mathematics. Args: epsilon: the shrinkage parameter (either a scalar or a vector) x: the vector to shrink on Returns: The shrunk vector """ # try e...
a2e6f7c2692420dfbf33156a2ee0c29df70acebb
3,620,472
def profiler_dtype_func(dtype, null=False): """ Return a function that check if a value match a datatype :param dtype: :param null: :return: """ def _float(value): if null is True: return fastnumbers.isfloat(value, allow_nan=True) is True and fastnumbers.isint(value) is ...
e2e22020c4bc14b660d2d6ecfbd5f239175cd4f1
3,620,473
def stop(job_id, event, action, resource, _count): """App stop event type""" job_name = '{}:event={}:action={}'.format( resource, event, action ) func_kwargs = dict( job_id=job_id, app_name=resource, ) return job_name, func_kwargs
56f1496c860396f76cee105e007803eb850ca679
3,620,474
def kurt(im): """Return kurtosis = mean((image-mode)/2)^4). """ mode = stats.mode(im, axis = None)[0][0] z_score = (im-mode)/2 z_score = z_score**4 k = float(z_score.mean().values) return k
96c949167437ef43e31f4a96444ef4ffb6af6b4e
3,620,475
def _format(str_lst, concise): """Format a string for printing. Parameters ---------- str_lst : list of str List containing all elements for the string, each element representing a line. concise : bool, optional, default: False Whether to print the report in a concise mode, or not. ...
da69e0682636f1bf5af02683a17849b0824dbcc3
3,620,476
def vector_add(v, w): """adds corresponding elements""" return [v_i + w_i for v_i, w_i in zip(v, w)]
ed85d5d1158e46109966b3c09f3d33d5acae8c98
3,620,477
from typing import Mapping from typing import Set from typing import Tuple def get_chebi_role_to_children() -> Mapping[str, Set[Tuple[str, str]]]: """Get the ChEBI role to children mapping.""" df = get_filtered_relations_df('chebi', relation=has_role) return multisetdict( (role_id, ('chebi', chemi...
583c28dbdd00a24df49d9b25d5e99a34de182cc0
3,620,478
def resample_solar_flux(solar_flux_file, sensor_waves, sensor_fwhms): """ Resample solar flux to sensor wavelengths. Arguments: solar_flux_file: str Solar flux filename. sensor_waves: array Sensor wavelengths. sensor_fwhms: array Sensor FWHMs. Retu...
307f4617926bb4b61d254b8f905666a315313376
3,620,479
import argparse def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="NAS Search") parser.add_argument("--dataset_type", type=str, default='celebA', help="dataset...
a61da813ea43158d916aa9d21e696d9d3b9dd17a
3,620,480
def nexthop_is_local(next_hop): """ Check if next-hop points to the local interface. Will be True for Connected and Local route strings on Cisco devices. """ interface_types = ( 'Eth', 'Fast', 'Gig', 'Ten', 'Port', 'Serial', 'Vlan', 'Tunn', 'Loop', 'Null' ) for type in interf...
fd74119d54998fafcb9400adaaa2c95b42671734
3,620,481
def mouse_body_geometry(beta,gamma,s,theta,phi): """ This function calculates the configuration of the mouse body In this configureation, it has four free parameters: azimuth and elevation of the nose/hip Returns the points, which define the model: center-points and radii theta el is elevation of th...
912125befcfa554aa53b1bb90dfbe531d8ca5ea0
3,620,482
def _set_mul(x, y): # noqa:F811 """ Multiplications in interval arithmetic https://en.wikipedia.org/wiki/Interval_arithmetic """ # TODO: some intervals containing 0 and oo will fail as 0*oo returns nan. comvals = ( (x.start * y.start, bool(x.left_open or y.left_open)), (x.start *...
38cd52d09c81ca9e295cad1b1ce385862dd19442
3,620,483
def calculate_expval(xcoords, wfuncs): """ Calculates the expected values :math:`<x>` for the x-coordinate by numerically calculating the integral .. math:: \\int_{x_{min}}^{x_{max}} | \\psi (x) |^2 x dx Args: xcoords (1darray): Array containing the x-coordinates wfuncs (nd...
83a1aca725c03799d6c4f0b8c85f7c8d5364004d
3,620,484
def generate_bbox(cls_map, reg, scale, threshold): """ 得到对应原图的box坐标,分类分数,box偏移量 """ # pnet大致将图像size缩小2倍 stride = 2 cellsize = 12 # 将置信度高的留下 t_index = np.where(cls_map > threshold) # 没有人脸 if t_index[0].size == 0: return np.array([]) # 偏移量 dx1, dy1, dx2, dy2 = [...
e9cb9b7b3b949bfb51c46c3f9a625a46286c1275
3,620,485
def logistic_expval(mu, tau): """ Expected value of logistic distribution. """ return mu
f6ac18144d5543d50c04f8e042bb8b5f8c8ea5ec
3,620,486
def is_(var): """intuitive handling of variable truth value also for `numpy` arrays. Return `True` for any non-empty container, otherwise the truth value of the scalar `var`. Caveat of the most unintuitive case: [0] evaluates to True, like [0, 0]. >>> import numpy as np >>> from cma.utilities...
dd7be0e1535c6a616a1984b7d4b4cab3b03fbfbd
3,620,487
def abs_load_diff(ilp_vars, x, y, vnfs, vims, dec_vars, types=['cpu', 'ram']): """ Calculating the actual load difference between two vims x and y. """ load_x = 0.0 load_y = 0.0 for res_type in types: if res_type == 'cpu': type_used = 'core_used' type_tot = 'cor...
d8ba5c46de41becb001b0fcc2a94d78b6f5aa5c7
3,620,488
def facebook_auth_settings(request): """ Facebook Auth client side ID. """ context = {} context['FACEBOOK_AUTH_ID'] = getattr(settings, 'SOCIAL_AUTH_FACEBOOK_KEY', '') return context
521a9caec5ad83c7398ae635c696ee3d5e6c6366
3,620,489
def keras_model_fn(hyperparameters): """keras_model_fn receives hyperparameters from the training job and returns a compiled keras model. The model will be transformed into a TensorFlow Estimator before training and it will be saved in a TensorFlow Serving SavedModel at the end of training. Args: ...
42009db35825ea915153b1ebfe726f19bb686d5d
3,620,490
import re import tarfile import io def _check_open_tarball(testcase, response): """ Check http-response headers and open tar ball from content. """ testcase.assertTrue(re.search(r'attachment;\s*filename="[^"]*.tar.gz"', response['Content-Disposition'])) testcase.a...
ffa0aa59f102fffb3c11664ee5f486f424b6acd8
3,620,491
def square_shaper(x, y, side_length=1): """Shaper function for a square with a given side length. Parameters ---------- x : float or array-like x-component of the step. y : float or array-like y-component of the step. side_length : float Square side length. Returns ...
1ade17ad77035ef35ae88cda264e1e23978766f2
3,620,492
def make_non_pad_mask(lengths, xs=None, length_dim=-1): """ See https://github.com/espnet/espnet/blob/e962a3c609ad535cd7fb9649f9f9e9e0a2a27291/espnet/nets/pytorch_backend/nets_utils.py#L179 """ return ~make_pad_mask(lengths, xs, length_dim)
950d8af7559ff08c7bd55bb36b2fc95fc7bbc574
3,620,493
def to_nsec(val): """Returns value in nanoseconds if value is ROS time/duration, else value.""" return val.to_nsec() if isinstance(val, genpy.TVal) else val
b8c3d6d9f7662a89e5d48ff7cb4456adc84ebb5c
3,620,494
import sqlite3 def prob14(cur: sqlite3.Cursor) -> pd.DataFrame: """Show the 1984 winners and subject ordered by subject and winner name; but list Chemistry and Physics last. The expression subject IN ('Chemistry','Physics') can be used as a value - it will be 0 or 1. Parameters ---------...
83a52bff0bc5f50d5ac428d0c2b996cb4ee154ac
3,620,495
def instructor_get_projects(): """ Returns all the projects created by the instructor """ # TODO: get the userid from the auth service userid = "1" # get all the project ids for this user with db_utils.db_session() as session: query = db.select([Project]).where(Project.columns.instru...
87e209aecf3fb853741e755c5a04850b819f775f
3,620,496
def GetKDPPacketHeaderInt(request=0, is_reply=False, seq=0, length=0, key=0): """ create a 64 bit number that could be saved as pkt_hdr_t params: request:int - 7 bit kdp_req_t request type is_reply:bool - False => request, True => reply seq: int - 8 sequence numb...
7a56abb0f1ccbe1a7da1a9e0c6b70418e00ef0be
3,620,497
import os def get_model(args, iteration: int): """Use the corresponding iCluster Model.""" logger.info("Setting up icluster-{} model...".format(args.mode)) save_dir = os.path.join(args.save_dir, MODEL_NAMES[args.mode], "iteration_{}".format(iteration)) if args.mode == "vanilla": ...
c19b8c4ec3bc8833730f1204e02142acd781e458
3,620,498
import json def save_items_list(drive_service, file_location): """ save cloud items list in a json file :param file_location: location where file needs to be saved :param drive_service: servive object for drive :return: True if list successfully saved else false """ files = drive_service.f...
9f5dc557bbbfa102bf4acfa3fb9af9014b229c83
3,620,499