content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os import subprocess def _get_xcode_version(xcode_app): """Returns the version of Xcode installed at the given path. Args: xcode_app: Absolute path to the Xcode app directory, e.g /Applications/Xcode.app. Returns: A tuple of (Xcode version, Xcode build version), or None if th...
6f365317504f99d34962da7380a714bc69739fc1
667,885
def _mg_len_ ( mgraph ) : """ Len of multigraph """ _graphs = mgraph.GetListOfGraphs() return 0 if not _graphs else len ( _graphs )
03137cff8c4ce8a6038275a53f9db4ce09585377
667,886
import torch def margin_loss(y_pred, y_true, margin=0.3): """Compute the margin loss.""" dp = torch.sum(y_true * y_pred, dim=-1) dm = torch.max(y_pred - y_true, dim=-1).values return torch.nn.functional.relu(dm - dp + margin)
162516a7775b84b1f15f9939e41ab9ede80fb50e
667,887
def counting_bobs(text): """ Function that counts the number of bobs in a text. text: string return: int """ text = text.lower() bobs_number = 0 for letter in range(len(text)): if letter >= 2: if (text[letter - 2] == 'b' and text[letter - 1] == 'o' an...
141c97647b2a2d64fcdf197777c82c08916d13ff
667,888
def getKtTuningOptions(dbElem): """Get the appropriate KTServer tuning parameters (bucket size, etc.)""" # these are some hardcoded defaults. should think about moving to config tuningOptions = "#opts=ls#bnum=30m#msiz=50g#ktopts=p" # override default ktserver settings if they are present in the # e...
ebb6c8fcef88ccae8377924462c4c685397440f2
667,889
def extract_columns(df, config_name, problem_name, target_columns): """ Extracts columns data for specific config and problem with new labels """ column = df.loc[(df['Config'] == config_name) & (df['Problem'] == problem_name)] column = column[target_columns].reset_index(drop=True) return column
c726f4ca6dc5ff5ceb5cd8dc334d0def21cd2873
667,890
def checkRecord(self, s): """ :type s: str :rtype: bool """ A_count = 0 i = 0 while i < len(s): if s[i] == 'A': A_count += 1 if A_count > 1: #1 absence return False elif s[i] == 'L': ...
44076ccfd68b42debb0bf0caff4dea09d34a3bcd
667,891
def IsInTargetRange( target, error_ref, warning_percentage, error_percentage, value): """Test if a value falls into warning or error range around a target. Args: target: The target value. error_ref: The error reference as the base for warning/error percentage. warning_percentage: The percentage of ...
edcb405bd409d543005e95907faa1eaa0a1304a9
667,892
import fnmatch def verify_delete_rule(rule_pattern, artifacts_queue, materials, products): """ <Purpose> Filters artifacts from artifacts queue using rule pattern and consumes them if they are in the materials set but are not in the products set, i.e. were deleted. <Arguments> rule_pattern: ...
3c031b40021a4b4261c7d44535bf1ab7d01a6029
667,893
def SplitStringAtSeparator(string,sep): """ split string at commas :param str string: string :param str sep: separator character :return: strlst(lst) - list of splited strings """ #return filter(lambda s: len(s) > 0, string.split(sep)) strlst=[]; items=string.split(sep) for s in...
2c5358d7c0e3374a7ffd198beb3352709b6401e6
667,894
import random def random_color() -> str: """Generate a random hex string.""" return "".join("{0:02x}".format(random.randrange(1 << 8)) for _ in range(3))
e9cbcb187c7a044f8953c400be92277c8b4e7764
667,895
def get_row_values(model, keys): """Get the values needed to fill a row in the table Parameters ---------- model : `dmsky.Model` Model that we are getting the data from keys : list Names of the properties we are reading Returns ------- vals : dict A dict...
aaa2d8298999f9a2c75a038e65563ec91c6fe299
667,896
def tree_win(win): """ get the window children tree :param win: win object :return: """ position_info = win.rectangle() # L, T, R, B # L52, T111, R1010, B151 # 相当于左上角和右下角两个点的坐标 win_data = {} win_data['pos'] = (position_info.left, position_info.top, position_info.right, position_in...
b0eaa4ad05910faee3a051d8f14d6fe070c1fb16
667,897
from typing import Dict import os import requests import yaml def read_input(input_object: str) -> Dict: """ Read workflow definitions from file or URL. :param input_object: input filename or URL :returns: definitions converted into dict """ if os.path.isfile(input_object): with open(...
97e4ddc45d468a0594a197a0f2bad2a7280c293c
667,898
def tile_key(tile): """Key which sorts tiles into blocks""" v = 2 ** 16 * int(tile[0] / 8) + int(tile[1] / 8) return v
5b28c43f3bd03830c2083a8a71fb686323fa8798
667,899
def _add_GTF_annotations_to_adata(adata, GTF_df, index_col="index", gene_id="gene_ids", chr_key="seqname"): """ Add GTF annotations to an adata object. Parameters: ----------- adata AnnData object for single-cell data. type: anndata.adata GTF_df DataFrame of a ...
2dc42a3bb3f99457add088c00049f056058b00f8
667,900
def extract_subnet_info(sts): """从字符串中提取子网信息,字符串的格式为 xxxx/prefix :param sts: :return:成功返回 (subnet,prefix,) ,否则返回 None """ pos = sts.find("/") if pos < 2: return None subnet = sts[0:pos] pos += 1 try: prefix = int(sts[pos:]) except ValueError: return None re...
4cd69e8146713707689bb003e7c64ee750189d6c
667,901
def _str_to_list(s): """Converts a comma separated string to a list""" _list = s.split(",") return list(map(lambda i: i.lstrip(), _list))
c977685188bd84a35a08ff6d193659cc9d5135dc
667,902
def tokenized_by_answer(context, answer_text, answer_start, tokenizer): """ Locate the answer token-level position after tokenizing as the original location is based on char-level snippet modified from: https://github.com/haichao592/squad-tf/blob/master/dataset.py :param context: passage :par...
1cf4e1782390d5007b7c705e53b8f8aa71681db5
667,903
def get_set_of_interest(infile): """funtcion to load in a list of gene names""" with open(infile) as handle: data = handle.read().split() outset = set([]) for entry in data: outset.add(entry.rstrip()) return outset
3e0797dacb9a7432f300dfc448f38412ff51b4e8
667,904
def seed_generator(generator, logger, seed=0): """Set seed for Dataloader generators. DataLoader will reseed workers the "Randomness in multi-process data loading" algorithm. Use `generator` to preserve reproducibility. For more information, see https://pytorch.org/docs/stable/notes/randomness.html. ...
887a968f6a0b76e6bdbc8a11bc1f61416f8af76f
667,905
def __check_epsilon_productions(cnf_variables, cnf_productions, cfg_productions): """ Check whether all reachable epsilon productions from Context Free Grammar are present in Chomsky Normal Form productions. """ cfg_epsilon_productions = set( filter( lambda prod: prod.head in cn...
200fd0a1d9fc828a8c8c05336dbafa1c38f81c83
667,906
def realtime_learning_curves(runs): """ example how to extract a different kind of learning curve. The x values are now the time the runs finished, not the budget anymore. We no longer plot the validation loss on the y axis, but now the test accuracy. This is just to show how to get different information into ...
30e32dc69c817aebb2c8fa033f0b571784b888ec
667,907
def build_merge(input_names, name, concat_axis): """function which adds concat merging of input_names""" return { "class_name": "Merge", "name": name, "config": { "output_mask": None, "output_mask_type": "raw", "dot_axes": -1, "output_shape...
b66dbd87fa85cff67687bde6767d65ff05c144a6
667,908
def lfnToPFN( path, tfcProt = 'rfio'): """Converts an LFN to a PFN. For example: /store/cmst3/user/cbern/CMG/TauPlusX/Run2011A-03Oct2011-v1/AOD/V2/PAT_CMG_V2_4_0/H2TAUTAU_Nov21 -> root://eoscms//eos/cms/store/cmst3/user/cbern/CMG/TauPlusX/Run2011A-03Oct2011-v1/AOD/V2/PAT_CMG_V2_4_0/H2TAUTAU_Nov21?svcCla...
11d8669892dd6d8df6dd86b5c51c7af2050289d5
667,909
from sys import stderr def validate_dictionary_value(command, dict_key, actual_body, expected_body): """ Print error message for validation failure and return True if validation passed, and False otherwise. This function expects that actual_body and expected_body are dictionaries. The comm...
18be8132c6d42167a0fbf3449bfb3510494a42f6
667,910
def bytes_to_readable_str(num_bytes, include_b=False): """Generate a human-readable string representing number of bytes. The units B, kB, MB and GB are used. Args: num_bytes: (`int` or None) Number of bytes. include_b: (`bool`) Include the letter B at the end of the unit. Returns: (`str`) A strin...
04ca844a745f192fd06f4346cac38e1ba410305e
667,912
def encode_labels(label_encoder, data): """ encode the data using the label encoder --- @param label_encoder: label encoder to encode data @param data: a dataframe """ return label_encoder.transform(data)
3ae5eadd79c41e41605ac83ea173b0786931fc0b
667,913
def getTakeSurveyRedirect(entity, info): """Returns the redirect for taking a Survey. Args: entity: a Survey entity info: a dictionary contain a survey and params entry """ survey_entity = entity params = info return '/%s/take/%s' % (params['url_name'], survey_entity...
90260d0bf6920b44dbb45a4ba344589ebf18d459
667,914
def issue_to_dict(issue): """ Convert an issue to a dictionary suitable for outputting to csv """ issue_data = {} issue_data['id'] = issue.id issue_data['title'] = issue.title issue_data['description'] = issue.description issue_data['due_date'] = issue.due_date issue_data['labels'] =...
3ae05441a873a54c04588684f45581d2d7d17b04
667,915
def jacobi(x: int, n: int): """Jacobi symbol.""" if n <= 0: raise ValueError("'n' must be a positive integer.") if n % 2 == 0: raise ValueError("'n' must be odd.") x %= n r = 1 while x != 0: while x % 2 == 0: x //= 2 nm8 = n % 8 if nm8 ...
8bd6e1ba2bdbc28e2866afaefe2f7cdca7993f53
667,918
def list_dims(l): """ """ return [len(l)] + list_dims(l[0]) if l and isinstance(l, list) else []
209ca3e83aba4c28e19f968b133f8f9c89df1cd5
667,919
import itertools def _generate_association_rules(patterns, confidence_threshold): """ Given a set of frequent itemsets, return a dict of association rules in the form {(left): ((right), confidence)} """ rules = {} for itemset in patterns.keys(): union_frequent = patterns[itemset] ...
2905663835dad14cbb32d81f5b19c3a01f0df41b
667,920
def filterLargeClusters(clusters, input_size, cluster_fraction_thresh): """ Remove big clusters which have more points than a given fraction of total points in the input data. Arguments: clusters: [list] a python list containing found clusters in the reachability diagram plot (optional) - ...
d929a6e38e8297deb0912c7b2cc7f079858a7bc0
667,921
import requests def search_qms(keyword, limit=10, list_only=True, add_prefix=True): """Search for QMS tile providers from Quick Map Services. Args: keyword (str): The keyword to search for. limit (int, optional): The maximum number of results to return. Defaults to 10. list_only (bool...
ced370effbef75ea90c1f08e9d76df41cef1be56
667,922
import re def validate_language_code(language_code): """ Checks whether the language code given follows the ISO format, e.g "en" :param language_code: the string being checked :type language_code: str :returns: whether the code is valid :rtype: bool """ return re.match('[a-z]{2}', la...
688ff2699eb0373296b384a23e49678421951a72
667,923
import math def to_time(seconds): """Convert a number of seconds into human readable compact string.""" prefix = '' if seconds < 0: prefix = '-' seconds *= -1 minutes = math.floor(seconds / 60) seconds -= minutes * 60 hours = math.floor(minutes / 60) minutes -= hours * 60 days = math.floor(hou...
d09c9557799e700302197e565fad87ef43583ba0
667,924
def task_docs() -> dict: """Build sphinx document.""" return { 'actions': ['sphinx-build -q -W -j 4 -b html docs docs/_build/html'], }
d88637dc31ea19944b8582026d7ed5d00d2d3996
667,925
def mode_addition(H, name, inv, flow, in_edge = None, in_guard = None, out_edge = None, out_guard = None): """ Add a mode to a hybrid automaton ------------------------------------------------------------------------------------ input: H Hybrid automaton HybridSystemABC name Name of the location strin...
fa63c75ef692e019d435a8e42dbe9092dea75052
667,926
def validate_user_name(user_name): """Validate if user's name doesn't contain any numbers""" try: if not any(letter.isdigit() for letter in user_name): return True except: pass return False
186cf1e213fa6e659c6b38fbacc9be25b589aa30
667,927
def _infection_indicator( health_states, infected_state_index): """Returns a binary vector that indicates whether individuals are infected.""" return [int(state == infected_state_index) for state in health_states]
cbdb63aba8caa843e81655602284b14403b28507
667,928
import codecs def get_long_description(): """Reads the main README.rst to get the program's long description""" with codecs.open("README.rst", "r", "utf-8") as f_readme: return f_readme.read()
2d774fa0ddc1164db5f50a995ecc11316d0aa724
667,930
from typing import List def find_next_value_in_sorted_list(lst: List[int], old: int, new: int): """ iold=1 and inew=2, but there is no value of 2, so we skip to 3 """ if new in lst: return new iold = lst.index(old) if new > old: list_high = lst[iold+1:] list_low = lst[...
b1ac93d6d11a791f3b58ea84e867216d37be054f
667,931
def productOfAdjacents(i, n, number): """Returns the product of n adjacent digits starting at i""" """Takes in the number as a string""" product = 1 for i in range (i, i+n): product *= int(number[i]) return product
2744e285bf7770be742b592eb0d5a47d21230f44
667,932
import os def txtDetect(choice = False): """ Detects all the txt files contained in the current working folder. """ files = [] global cFile cFile = "commands.txt" for i in range(len(os.listdir())): if os.listdir()[i][-4:] == ".txt": files.append(os.listdir()[i]) if...
41e47d3ca0d3014e39ec698e49e0e6b3b830492b
667,933
def insert_newlines(string, every=64): """ Insert a newline after ’every‘ characters Arguments: - every : The amount of characters before a newline is inserted """ return '\n'.join(string[i:i + every] for i in range(0, len(string), every))
38058941618f022f9c465a3a49e5ff05d551c82d
667,934
def get_checked_extrapackages(): """ Reads the Airflow Dockerfile and returns all lines and which packages are currently set """ with open("../../docker/airflow/Dockerfile") as f: while True: line = f.readline() if not line: break if "RUN pip ...
40fceb7c2358c52bd9c635cb56311f65f297039d
667,935
def filter_stops(stop_info): """ Filter for only type 0 stops, ie load/unload""" new_stop_info = {} for stop in stop_info: if stop_info[stop]["location_type"] == "0": new_stop_info[stop] = stop_info[stop] return new_stop_info
d23c1f857ef41268b453aa17d905b391a1fc1f91
667,936
from datetime import datetime from typing import Optional def get_int_from_datetime(value: datetime) -> Optional[int]: """ :param value: datetime with or without timezone, if don't contains timezone it will managed as it is UTC :return: None if value is not datetime else seconds since the Epoch """ ...
b06e6839e713c411f381ed3c3cd1b5a2fa7f0a21
667,937
import os import json def load_json(filename): """ Loads a json file and returns a python object generated from parsing the json. """ module_path = os.path.dirname(__file__) output = [] with open(os.path.join(module_path, 'data_files', filename)) as dat: for idx, lin in enumerate(d...
8652315ddef05ad7a11cded42c3b2e7581464382
667,938
import os import subprocess def git(*args): """Invoke git""" env = os.environ.copy() env["GIT_TERMINAL_PROMPT"] = "0" return subprocess.check_call(["git"] + list(args), env=env)
51f654cdd447ca4b29959f0c9005c30650bcd21c
667,939
def tokens_to_ops(token_dict): """returns a list of ops from a {tokenId:token_obj} dict""" outops = [] for t in token_dict.values(): outops.append(t.as_op()) return outops
cf130b145198a74725b7219417e28b05a13aa721
667,942
import re def read_file_to_list(filename): """Read file to map""" rows = [] rules = {} file = open(filename, "r") for line in file: line = line.strip() if line == "": continue #3: 4 5 6 m = re.search(r'^([0-9]+):\s+([0-9\s+]+)$',...
81c1b68fa8b69d89cd9e61b34edb1c61ba1c9da5
667,943
def table_exists(table_name, connection, schema=None): """Returns `True` if a table exists in a database. Parameters ---------- table_name : str The name of the table. connection : .PeeweeDatabaseConnection The Peewee database connection to use. schema : str The schema i...
0c4434796042b788963e9c7f9ea52438aabc9b28
667,944
def maxSumNonAdjacent(nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 if len(nums) == 1: return nums if len(nums) == 2: return max(nums[0], nums[1]) # Time Complexity - O(n) # Space Complexity - O(1) first, second = nums[0...
715997dcff354d623daf8130c125af56c69501a3
667,945
def get_cep_conference_call_id(ad): """Get CEP conference call id if there is an ongoing CEP conference call. Args: ad: android device object. Returns: call id for CEP conference call if there is an ongoing CEP conference call. None otherwise. """ for call in ad.droid.telec...
681a38c1ed0d8518ba8d80c5f54bb2abb9755407
667,946
import argparse def get_argument_parser(): """Define command line arguments.""" # there are no flags, but --help will still work return argparse.ArgumentParser()
71cc63609670ecf67f6d993f527a1f58230f6ea7
667,947
def format_test_id(test_id) -> str: """Format numeric to 0-padded string""" return f"{test_id:0>5}"
91d6acefdda63300a32c832320662d9b5403d9fd
667,948
def _format_column_name(raw_column_name, year=None): """Formats a raw column name to remove: spaces, year and character with accents. Args: raw_column_name (str): a column name year: the year tu remove Returns: (str) The formatted column name. """ raw_column_name = ('_'...
f826a5fdef59f69a67129a3efe3812150f99d578
667,949
from typing import List def is_safe_path(path: str) -> bool: """Checks whether the given path attempts traversal with /. Returns True if path is safe, False otherwise.""" is_safe = True new_comps: List[str] = [] for comp in path.split('/'): if not comp or comp == '.': continue...
369fc037235b7e5fe42610e0af31338f6cf9409d
667,950
import os import subprocess def run_cmd(cmdlist): """ Reusable function for running external commands """ new_env = dict(os.environ) new_env['LC_ALL'] = 'C' try: stdout = subprocess.check_output(cmdlist, env=new_env) except subprocess.CalledProcessError: pass else: if s...
20ff2afb85d6248d3c863c091d7be1d8a3e1161e
667,951
from typing import List def get_interval_in_s(interval: List[str]) -> List[int]: """Converts an interval in string form (e.g. [1:10, 2:30] in seconds, e.g. [70, 150] seconds""" return [int(sec.split(":")[0]) * 60 + int(sec.split(":")[1]) for sec in interval]
18e21da1cdf3bd13f91550283040f9bcfbd14cb5
667,952
def qualifier(entry): """ Get the qualifer for this entry. """ return entry["Qualifier"][0]
ec15b37a6f08a6317af422630ab87fbe7fb06427
667,953
def get_info_dic(s): """ Parse the string from the VCF INFO column and return it as a dictionary. """ info_tuples = [t.split('=') for t in s.split(';')] info_tuples = [t for t in info_tuples if len(t) == 2] tags = [t for t in info_tuples if len(t) != 2] # try: d = {k: v for (k, v) in ...
b05e0a2859a5289ae46a2dd0f191360324cd8fa0
667,954
import logging def _logger(cls): """Creates a logger with a name suitable for a specific class. This function takes into account that implementations for classes reside in platform dependent modules, and thus removes the final part of the module name. :param type cls: The class for which to crea...
79d76ebacaa1f7566aab2961a185c968ea9e6f3f
667,955
def get_strings(soup, tag): """Get all the string children from an html tag.""" tags = soup.find_all(tag) strings = [s.string for s in tags if s.string] return strings
205da9aa8214cef5fdf4d97c084b6bf0c7756554
667,956
def transform_period(period, frequency): """ detects 'YYYY-YYYY' or 'YYYYMM-YYYYMM' inputs and transforms them into lists of YYYY or YYYYMM that the API can understand the function does not check whether the other inputs for period are valid! period: depending on freq, either YYYY or YYYYMM (or 'YYYY-YY...
b1453d7948d36d1fb2aefcabd6576929d3441879
667,957
def stride_parser(lines): """Parses stride output. Returns a ``full_id:{data}`` dictionary. The parser does not currently support the following (useful) options: - hydrogen bond assignments (-h) - contact order calculation (-k) The returned data is a dictionary with th...
7cca59e4979b123ad5932745b60607f0a86f3971
667,958
def require_methods(*method_args): """Class decorator to require methods on a subclass. Example usage ------------ @require_methods('m1', 'm2') class C(object): 'This class cannot be instantiated unless the subclass defines m1() and m2().' def __init__(self): pass ...
e822d633c66af5e4ce7ec6eda397ffa456a58aba
667,960
def get_val_string(input): """ String for a value, formatted for CSycles """ val = "" if input.type == 'VALUE': val = "{0: .3f}f".format(input.default_value) elif input.type in ('RGBA', 'VECTOR'): val = "new float4({0: .3f}f, {1: .3f}f, {2: .3f}f)".format( input.defau...
5559ba4862b60503a40de5c0dd934595223e8198
667,961
def applyUserPreset(nodeName:str, presetName:str): """ applyUserPreset(nodeName, presetName) -> None Applies a given user preset to the current node. @param nodeName: Name of the node to apply the preset to. @param presetName: Name of the preset to use. @param node: (optional) a Node object to a...
f3d29925d7d217004beb0f5ec20028cf72f4383e
667,962
import argparse def parse_args(): """Process input arguments""" parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--train', '-r', default='data/full_omics_train_norm.tsv', ...
352a0a4b64be9be0569ad78af5f8080b6701e62e
667,963
import torch def validation(model, validloader, criterion, device): """ Implement a function for the validation pass """ test_loss = 0 accuracy = 0 for images, labels in validloader: images, labels = images.to(device), labels.to(device) output = model.forward(images) test_loss...
efa13f08b6e3a9f15c04cfbb9a069dbf5bd838ba
667,964
def check_dim(gr, DIM): """ Checks if it is a 9x9 grid :param gr: 2D list :return: None """ l = len(gr) if(l != DIM): return False for i in range(0, DIM): if(len(gr[i]) != l): return False return True
7b79d6000bedce7f3dee7a853a378282cae379e2
667,965
def fmt_addr(addr): """ Format a Bluetooth hardware address as a hex string. Args: addr (bytes): raw Bluetooth address in dongle format. Returns: str. Address in xx:xx:xx:xx:xx:xx format. """ return ':'.join(reversed(['{:02x}'.format(v) for v in bytearray(addr)]))
06433ed5fc270bcf28b999e00c9de5e4159d7398
667,966
def _new_block_definition(block_name): """ This will return a new block definition with the given block name :param block_name: Name of the block to define :return: str """ return """ myData = attributes "%s" version:1 ( -- Define the act...
51de9a007e6f84d9ce84663421523c3198ef72e9
667,967
from typing import List from pathlib import Path def install_requires() -> List[str]: """ Populate install_requires from requirements.txt """ requirements_txt = Path(__file__).parent.joinpath("requirements.txt").read_text() return [requirement for requirement in requirements_txt.split("\n")]
e6845d00a53b0f9bffa2d83066be7b542c92de0d
667,968
def autoplace_snap_all(): """ autoplace_snap_all() -> None. Performs autoplace snap of all nodes in current context group. @return: None. May return exception it top context group has subgraph locked. """ return None
08dda4b6db611e9a4740f789af730452ab818f8f
667,969
def _parse_control_depends(fields): """ Parse the package names of the 'Depends:' directive in a debian control file. References: https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-controlsyntax https://www.debian.org/doc/debian-policy/ch-relationships.html#declaring-relations...
10148a8573d03d626ba7c35d706ce7ebdf88f05f
667,970
import requests import os import json def azrequest(endpoint, url, subscription_key, request_data): """Send anomaly detection request to the Anomaly Detector API. If the request is successful, the JSON response is returned. Aim to generalise this to go into MLHUB to send request. """ headers =...
3e49929d6e44294eca536883a95f0537c05c98b9
667,971
def get_ipsec_udp_key_config( self, ) -> dict: """Get IPSEC UDP key material configuration, seed lifetime, max activation wait time, and whether to persist seed on appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - ikeless ...
b972d689c0cdd88e369f2c637d85515c473e9f45
667,972
import torch def get_jacobian(net, x, noutputs): """From https://gist.github.com/sbarratt/37356c46ad1350d4c30aefbd488a4faa""" x = x.squeeze() n = x.size()[0] x = x.repeat(noutputs, 1) x.requires_grad_(True) y, _ = net(x) y.backward(torch.eye(noutputs)) return x.grad.data
9f4e2c4b50a297ad191bdce9f3d71edeef09134f
667,973
def decode_pass(boarding_pass : str) -> tuple[int, int, int]: """Get the row, column and seat id from a boarding pass""" row = int(boarding_pass[:7].replace("F", "0").replace("B", "1"), 2) column = int(boarding_pass[7:].replace("L", "0").replace("R", "1"), 2) return row, column, row * 8 + column
7b88b36f4e3c810c08121de5141cb8cd06cf4564
667,974
def HEX(red_value, green_value, blue_value): """Return HEX values from RGB string""" hexval = "#%02x%02x%02x" % (red_value, green_value, blue_value) return hexval
084242dabc4611a217938d96faeac4c6a28e27b2
667,975
import requests def send_request(url: str) -> requests.models.Response: """Send a request to an endpoint. Args: url (str): Endpoint. Returns: response (Response): Request response. """ try: response = requests.get(url) response.raise_for_status() return ...
e5eb63320786b1ffe6d8f5114fd979e671857d53
667,976
def readBit(integer, position): """ :param integer: :return boolean: Description: This function will take in an integer and a position value. The return will be a boolean based on whether the bit is 1 or 0 at the requested position of the integer. Example: integer = 2...
94808581e2a8f55a10f4a68f35c1781a7e59609c
667,978
import os def getFileSize(pan): """ return the size of a file in bytes. @param pan [string] = a pathname @return [int] """ try: size = os.stat(pan).st_size except: size = 0 return size
711079d6de98fb642dc48c6c5e2af3cca3f98297
667,979
def _has_version(name): """Check whether a package identifier has a version component.""" return name.rpartition("-")[2].replace(".", "").isdigit()
e18e3aec0a4fa0944723ed704de6cd6b0d1c2ed3
667,980
def is_comment(line): """check whether a line is a comment""" return line.strip().startswith("#")
ea8be8d15e8e120702a597d410acc414a1cb2590
667,981
import requests def fetch_cat_fact(): """Fetches cat's fact.""" response = requests.get('https://cat-fact.herokuapp.com/facts/random') response.raise_for_status() return response.json()['text']
93add98ac9fcfcc20ddcb2e072569809a6d6a150
667,982
def read_root(): """Display status.""" return {"status": "up"}
a4af67847090584a5fd7072ec079cc8afd636d38
667,983
def passthrough(func): """A Decorator that will call the same named function on the wrapped object. Expected interface requires a `_wrapped` attribute on the wrapper object to contain a pointer to the wrapped object. """ def wrap(self, *args, **kwargs): """This function allows arguments...
31b09f06f0a66a3160d55c7e408e812f4d9cc571
667,984
def merge_bindings(program, node, bindings): """Create a combined Variable for a list of bindings. Args: program: A cfg.Program instance. node: The current CFG node. bindings: A list of cfg.Bindings. Returns: A cfg.Variable. """ v = program.NewVariable() for b in bindings: v.PasteBindin...
8443d40defc8f5950f886809bf616a4137dd6c6d
667,985
def fetch_reg_type_table(): """ >>> import winreg >>> def a(): ... for n_ in [name_ for name_ in dir(winreg) if name_.startswith("REG")]: ... yield n_, getattr(winreg, n_) ... >>> l = list(a()) >>> for n_, v in sorted(l, key=lambda x: x[1]): ... print(f"{v}: "{n_}"...
91d304faeac8c21bdaea2bd904da5f69652ec611
667,986
async def heartbeat(): """ Example heartbeat function for proxies and load balancers to check """ return { 'status': 'ok' }
7087322f2bc4b1bc03888a9b7191504ae62dde98
667,987
import json import sys def load_data_files(main_dir): """Loads the data files.""" try: # Load the data files. rocks_file = open("%s/rocks.json" % main_dir, "r") rocks = json.load(rocks_file) rocks_file.close() minerals_file = open("%s/minerals.json" % main...
9cfbc4177d5d0ee735c723dced09d685aa1600ce
667,988
def ct_mimetype(content_type): """Return the mimetype part of a content type.""" return (content_type or '').split(';')[0].strip()
1e6fd5d841c38b76c6197a46a138593003c29486
667,989
def correct_description(description): """Given an description, return a version with any typos pedantically corrected.""" for old, new in ( ('- ', ' - '), (' -', ' - '), (' -', ' -'), ('- ', '- '), ): description = description.replace(old, new) r...
cf5086f0c56ca92de7d29302388aca7d4ea7858f
667,990
import os def find_inventory(inv, path): """Find the dynamic inventory file""" if os.path.isfile(inv): return inv for root, dirs, files in os.walk(path): if inv in files: return os.path.join(root, inv)
e75519de694c3d6ab7d558de507cc9b1db9874ea
667,991
import os def rebase_file_args(current_dir, files): """REbase file command line params after moving working dir to the script's dir""" if isinstance(files, list): if (files[0] == '-') or (files[0] == 'db:'): return files else: return [ os.path.join(current_dir, fn)...
cbacf79838af1ec028638b4b01f15d1b771c7dc4
667,992