content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import itertools def cmr_filter_urls(search_results): """Select only the desired data files from CMR response.""" if 'feed' not in search_results or 'entry' not in search_results['feed']: return [] entries = [e['links'] for e in search_results['feed']['entry'] if 'li...
403cfe92f6520af59a851b7b1913404be429a507
640,273
def get_shorturl(ctx, slug): """Get the target of a shorturl by its slug.""" query = 'SELECT `target` FROM `shorturls_public` WHERE `slug` = %s' ctx.execute(query, (slug)) candidate = ctx.fetchone() return candidate['target'] if candidate else None
9e986febb1d5ef0c78dee1bf05eb5ddf5e1a25f3
640,274
def is_float(value): """Check if value is a float.""" return isinstance(value, float)
a0b52166c42b6bceaffa18e8057f0408196acaab
640,275
def player_last_awarded_submission(profile): """Returns the last awarded submission date for the profile.""" entry = profile.scoreboardentry_set.order_by("-last_awarded_submission") if entry: return entry[0].last_awarded_submission else: return None
15e3ec8b0b0fc218c89a3dbe0484b30191dd399f
640,276
def main2(): """ Reverse-engineered code of the program from main1() """ def getSumDiv(n): s = 0 for i in range(1, n // 2): if n % i == 0: s += i s += n return s r2 = 2 * 2 * 19 * 11 r2 += 3 * 22 + 17 print('Part 1:', getSumDiv(r2)) r2 ...
39f78383cd2217d993241f0d6ffa6a31c6f370c2
640,278
def remove_parenthesis_break(words_list): """Doc.""" new_words_list = [] parenthesis_num = 0 new_words = [] is_line_end = True for words in words_list: if not words: continue new_words += words if not words[-1].startswith('//'): for word in words:...
e4eef58e593bf46e33a4f36c8c41393d44a67cc5
640,279
def max_dc(vetor, inicio, fim): """ Busca o valor máximo através da divisão e conquista. Usa os valores início e fim para a recursão """ if inicio == fim: return vetor[inicio] meio = int((inicio + fim) / 2) aux1 = max_dc(vetor, inicio, meio) aux2 = max_dc(vetor, meio + 1, fim) ...
eb1df4310a9052dab5fd1477df59adaed7ee2d73
640,280
def denormalize_colors(rgb_norm, mean_rgb=(0.485, 0.456, 0.406), std_rgb=(0.229, 0.224, 0.225)): """ Denormalize colors Args: rgb_norm: Image in RGB format, normalized by normalize_colors() Numpy array of shape (h, w, 3) mean_rgb, std_rgb: Mean and standard deviation for RGB cha...
01cc5e25496647919f9841b9432a5422813558a7
640,281
def isdict(mixed): """ Check if the given argument is a dict. :param mixed: :return: bool """ return isinstance(mixed, dict)
cfd7938614ccfb79ae87338c5b036fc4ae4d7fe3
640,283
import os def sslize_config(config): """Give a new configuration with SSL enabled for the listener""" config.set('listener', 'ssl', 'true') # Replace relative paths by absolute ones ssl_cert = config.get('listener', 'ssl_cert') if not ssl_cert or ssl_cert[0] != '/': ssl_cert = os.path.joi...
3355ea9a8a083f260342bc0ccaddc159ad29931c
640,284
def swagger_type_to_pydantic_type(t, models=[]): """Given a swagger type or format or ref definition, return its corresponding python type""" # Take a swagger type and return the corresponding python type if t in models: return t mapping = { # swagger type: pydantic type (https://pydant...
10be23eed09be6b8ee05bd47b9e83464fbe147f4
640,285
def getTol(**kwargs): """ Returns the tolerances based on kwargs. There are two ways of specifying tolerance: 1. pass in "tol" which will set atol = rtol = tol 2. individually set atol and rtol. If any values are unspecified, the default value will be used. """ DEFAULT_TOL = 1e-12 if...
3692e44eaca2dc2d4818c2e96d8437b71250f737
640,286
import math def attention(query, key, value, mask=None, dropout=None): """Scaled Dot Prodction Attention implmentation. Args: query (torch.Tensor): batch of query matrix, (..., sequence_length, d_k). key (torch.Tensor): batch of key matrix, (..., sequence_length, d_k). value (torch.Te...
c316fce96bed9653fea8cbd1a1a3bd60492abf57
640,287
def get_seat_id(row, column): """Get seat id from row and column.""" return row * 8 + column
d18f9a990007189c86d23ad29b5694565f8c5526
640,288
import os import argparse def dir_path(path: str): """Utility function for argparse to check existence of a passed directory. Parameters ---------- path : str Absolute path to local directory. """ if os.path.isdir(path): return path else: raise argparse.ArgumentT...
7861f6b6c479885e8e13f167f6186662be0ba635
640,289
import socket import argparse def validate_argument_ip(value): """Validator for IP argument.""" try: socket.inet_aton(value) except socket.error: raise argparse.ArgumentTypeError('"%s" is not a valid IP address.' % value) return value
72c06955e194e9bd2f6c7750c097dca10563949d
640,290
def get_function_name(func): """ Return the name of a function """ return func.__name__
17b7a1b5756371abcd47a7627c19eebba32573da
640,291
def _check_remove_node_out(sub_elite, node, outg, incm): """ Recursively remove connecting incoming and outgoing nodes if ~either~ outgoing or incoming empty """ remove_count = 0 if len(incm) > 0: for _node in incm: sub_elite["nodes"][_node]["outgoing"].remove(node) re...
f2e44f14ddcce2318c59516491bbc8fd25feb635
640,292
def Name(uri): """Get just the name of the object the uri refers to.""" # Since the path is assumed valid, we can just take the last piece. return uri.split('/')[-1]
e0ef4264d82d97675222c015f2bd0dd9cc0accac
640,293
def write(fn, data): """ Write string to a file. """ f = open(fn, "w") f.write(data) f.close() return True
afe49cb91e180a16f12059fb9e2a7e0c1e271c97
640,295
def rm_www_prefix(text): """ Remove www prefix """ prefix = "www." if text.startswith(prefix): return text[len(prefix) :] return text
e9b460268126f13531cbeb308d7960d0694ef8f8
640,296
import requests import json def pptn_configuration(url, port, cookie): """ Applies TN configuration on specified port :param url: base url :param cookie: Cookie value :param port: Port where TN will be activated :return: Port configuration Status Code :Example: result = pptn_configura...
81cde64180470044bf253332fef4ff7f4ba38402
640,298
def font_size( custom_font, f_size): """ Changes font size :param custom_font: font used by Message in Tkinter GUI :param f_size: font size the user selects :return: font used by GUI """ custom_font.config(size=f_size) return custom_font
fa73387cc79f73ed68cfa7f22ad1715d691bd942
640,299
def is_string(value, arg_name, logger=None): """ Verifies whether a parameter is correctly defined as string. :param value: value of the parameter :param arg_name: str, parameter name :param logger: logger instance :return: boolean, True if value is a string, False otherwis...
df86a421b43a4b432e8c0d6770af1e9aef3727ec
640,300
def is_complex(object): """Check if the given object is a complex number""" return isinstance(object, complex)
2ca855f273fb52ba2f3203ac5d4363ccdb3c454d
640,301
def used_by(classes): """Get variables used by components.""" used = [] for cls in classes: try: used += cls.input_var_names except TypeError: pass return used
91598b3d307abbfaca6bad125d46213c5bf47287
640,302
import random def _id(obj): """Get an id for deduping members""" return obj.get("name", random.random)
2ba16d130c38d4dc03c2725a16c84f2ced06819d
640,303
def _create_advertisement(pack_type) -> bytes: """ Service type prefixed with the total line length """ advertisement = f"# service={pack_type}\n".encode() hex_len = hex(len(advertisement) + 4)[2:] hex_len = hex_len.zfill(4) advertisement = hex_len.encode() + advertisement + b"0000" retu...
f4b4a7729d2f6406c01ffd1f9aa77c3af688a974
640,304
def auth(mysql,u,p): """ authenticates user credentials @param mysql: a mysql object for MySQL database @param u: username @param p: password """ cursor = mysql.connect().cursor() cursor.execute("SELECT * from creds where username = %s and password = %s", [u,p]) data ...
409354282a1198447806fb3cb728b92f110441f6
640,305
def cal_IoU(detectedbox, groundtruthbox): """ 计算两个水平竖直的矩形的交并比 :param detectedbox: list, [leftx_det, topy_det, width_det, height_det, confidence] :param groundtruthbox: list, [leftx_gt, topy_gt, width_gt, height_gt, 1] :return iou: 交并比 """ leftx_det, topy_det, width_det, height_det, _ = detec...
576eb024e968d8488389c11e50399411895518e2
640,306
def SetDsymutilPath(dsymutil_path, full_args): """Linker driver action for -Wcrl,dsymutilpath,<dsymutil_path>. Sets the invocation command for dsymutil, which allows the caller to specify an alternate dsymutil. This action is always processed before the RunDsymUtil action. Args: dsymutil_path: string, T...
004ed876e07b50748ea7e8a5f2828dad2eede2b9
640,307
import copy def strip_registered_meta_comments(messy_dict_or_list, in_place=False): """Removes Prereg Challenge comments from a given `registered_meta` dict. Nothing publicly exposed needs these comments: ``` { "registered_meta": { "q20": { "comments": [ ... ], <~~...
85ef4ab3dd7e193c9048d32255963b5d21362e4a
640,308
import json def load_sequences(filename): """Load JSON NE sequences. :param filename: Name of JSON file to load :type filename: String :return: Deserialized JSON object :rtype: Dictionary """ with open(filename, "r") as read_file: data = json.load(read_file) return data
046b3930bcfa35214847df339aa5b990e4a1b699
640,309
def safe_print_integer(value): """ safe_print_integer """ try: print("{:d}".format(value)) except ValueError: return False except TypeError: return False return True
af6164c9a9f93f1f5d29430752591bb851dcf96b
640,311
import os def load_text_file(i): """ Desc: Load text file into string or list Target: end users Input: { text_file - name of text file (keep_as_bin) - if 'yes', return only bin (encoding) - by default 'utf8', however sometimes we us...
9a8a0939479f1b83b43d30ff9eb200f4deb5edb7
640,312
def _next(user_input): """ Convenience function that checks if user intended to skip a parameter setting. @param user_input: String input provided by the user. @return: True, if user provided an input that indicates parameter input skip. False otherwise. """ return user_input.upper() == ...
c7940099a39b3e19111e8e33b4dee18157dba684
640,313
def int_to_hex(num): """Convert an int to a hexadecimal string""" num = int(num) vals = { 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'} if num < 0: sign = '-' num = -num else: sign = '' if num < 10: return sign + str(num) if num < 16: return si...
6d62ceb245defecc9f857928b010dbf6ff2120f3
640,315
def next_lesson_after_title(self, edge, fsmStack, request, useCurrent=False, **kwargs): """ Edge method that moves us to right state for next lesson (or END). """ fsm = edge.fromNode.fsm unitStatus = fsmStack.state.get_data_attr('unitStatus') nextUL = unitStatus.get_lesson() if nextUL.is_que...
e338bc8d6f4c5aab851affb371d4af4bd075fc02
640,316
from typing import List def smallerNumbersThanCurrent1(nums: List[int]) -> List[int]: """ 排序与映射:你的索引是多少,就有多少个数字小于你[严格说应该是 小于等于你] https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/solution/java-pai-xu-yu-ying-she-by-lzhlyle/385413/ """ length = len(nums) if l...
2f49feaf684645262a9ab61001401b9c7073b49f
640,317
import os def which(name, flags=os.X_OK): """Analogue of unix 'which'. Borrowed from the Twisted project, see their licence here: https://twistedmatrix.com/trac/browser/trunk/LICENSE Copied from ``pytest_shutil.cmdline.which`` to allow testing on conda-forge where ``pytest-shutil`` is not av...
77d2013d2741e7af5636f798a9e55f32676d5184
640,318
import os def cid2filename(cid, prefix): """ Creates a training image path out of its CID name Arguments --------- cid : name of the image prefix : root directory where images are saved Returns ------- filename : full image filename """ return os.path.join(prefix, ...
5cb6084c664a69783500bb9a2316f4ae7e656506
640,319
import string import random def random_string(n=5, uppercase=True): """Generates a random string of a given length, containing only uppercase letters and digits.""" letters = string.ascii_uppercase if uppercase else string.ascii_lowercase return ''.join(random.choice(letters + string.digits) for _ in range(n))
17217709bd8b6dd2985ec43c3323641af9e59fe5
640,320
import argparse def parse_args(): """ Parses the command line arguments. """ # Create an instance of the Argument Parser parser = argparse.ArgumentParser() # Then, add the required arguments for this parser.add_argument("--env", dest="env", action="store_true", help...
b91fee49f98f9dc751486dfa0398a35aa5af430c
640,321
def uncertainty_metric(actuals, upper_bound, lower_bound, avg_volume): """ This function aims to compute the Uncertainty Metric for the Novartis Datathon, 3rd edition. Given the actuals followed by the upper_bound and lower_bound intervals and the average volume, it will compute the metric score. ...
8a3fdc573e27b0f5b4318bb270b6cf2deeec299a
640,322
import argparse import os def parse_config_create_cmd_args(arglist): """Parse command line arguments for 'cfg_create subcommand. Args: arglist: A list of all command line arguments including the mandatory input configuration file name. Returns: A Namespace object of parsed ar...
1ef95fb461e72bdb61cdd7b3ba6a703488a8f375
640,323
def forward(network, X): """ Activate all networks by applying them sequentially :param network: list of network :param X: set of data :return: """ activations = [] input = X for l in network: activations.append(l.forward(input)) # Update to next input = activations...
f2a21b4c4791414092bb51069a1434a343cae59a
640,324
def check_changed_repo(repos, prefix, super_visor, requires, blacklist): """ Helper to compare current yaml and previous yaml """ errors_found = 0 curr_dict = {f["name"]: f for f in repos[0]} remove_repos = set() sigs_attention = set() for repo in repos[1]: if repo["name"] in c...
7301fd43f1ea07933f78d80507bd936c5e6d072c
640,325
import subprocess def ref_exists(repo, ref): """ Check if ref exists using show-branch (works for branches, tags, and raw SHAs) :param repo: The path to the repo to check :param ref: The ref to check :return: True if ref exits, False if not """ return subprocess.run(["git", "show-branch", ...
a000e81a41a8d4529a52609bfd6a6192f64fe4d5
640,326
def valorFerias(valor=0, dias=0, extra=0): """ -> Função para cálcular o valor férias. :param valor: Valor do salário base. :param dias: Quantidade de dias de férias. :param extra: Valor da média de horas extras no ano. :return: Retorna o valor férias. """ baseValorFerias = ((v...
6800c88ff65563e9cf4de7cbd535ff195adbd0b8
640,327
def delete(command, release_name, purge, disable_hook): """ Delete release chart """ delete_command = command + " uninstall " if not purge: delete_command += " --keep-history" if disable_hook: delete_command += " --no-hooks" delete_command += " " + release_name retur...
c8c0a0c03b6354af67efe8f26078b23855ba7504
640,328
def construct_return_statement(prediction, dog_detection, human_detection): """Construct a str return statement from predicted breed and results of dog/human detector.""" if dog_detection: return 'This is a {}.'.format(prediction) elif human_detection: return 'This human looks like a {}.'.fo...
3a675ab56706b34efc4b3e511566ead2fc26799f
640,329
from typing import Any import json def jsonify(obj: Any) -> str: """Convert a Python object to JSON.""" return json.dumps(obj, sort_keys=True, indent=4)
95a128b5b26d22ac52d82a06c3764786a1f7f903
640,330
def RunLengthDecode(data): """ RunLength decoder (Adobe version) implementation based on PDF Reference version 1.4 section 3.3.4: The RunLengthDecode filter decodes data that has been encoded in a simple byte-oriented format based on run length. The encoded data is a sequence of runs...
b771c38ca0acab438c7ea72b2b3b00517e1327c6
640,331
def evaluate_zero_vector(M, i): """ :param M: R x C matrix :param i: C-vector (a.k.a. image) :return: M * i an R-vector >>> M = Mat(\ ({'a','b'}, {'#', '@', '?'}),\ {\ ('a', '#'): 1, ('a', '@'): 2, ('a', '?'): 3,\ ('b', '#'): 10, ('b', '@'): 20, ('b', '?'): 30...
442e74cd7f70af2192513c49b93503fe3ea02f51
640,332
def poisson(t, y, den): """Poisson's equation for radially symmetric density den(r) = |u(r)|^2.""" y1, y2 = y y1d = y2 y2d = -den(t) / t return [y1d, y2d]
88edf97499185d51e86cb5777e44ae342e15ce98
640,333
def code_block(lines, language=''): """ Mark the code segment for syntax highlighting. """ return ['```' + language] + lines + ['```']
746fb444353fa141ab6b0e0324db4809c129e64f
640,334
def normalize(s): """ Normalize strings to space joined chars. Args: s: a list of strings. Returns: A list of normalized strings. """ if not s: return s normalized = [] for ss in s: tokens = [c for c in list(ss) if len(c.strip()) != 0] normalized...
98ca9bb41ef72087a2e154b37bde056acef9420c
640,335
def get_default_config(): """Returns a default config file""" config = { 'outdir': 'outdir', 'seed': 42, 'gpu': 0, 'dataset': 'CIFAR10', 'num_classes': 10, 'test_sample_num': 1, 'test_start_index': 0, 'recursion_depth': 1, 'r_averaging': 1,...
3c7c4f546215508b2dce79777edcacacbf7f83c4
640,336
def aov(total_revenue, total_orders): """Return the AOV (Average Order Value). Args: total_revenue (float): Total revenue. total_orders (int): Total number of orders. Returns: aov (float) as average order value """ return total_revenue / total_orders
883c81f1dd511cbf37858447c7e2b930dd7a99d3
640,337
def _join_prodigy_tokens(text): """Return all prodigy tokens in a single string """ return "\n".join([str(i) for i in text])
3cec234d5de4efacc68c867b68cd235b18f7a988
640,338
import sys def register_command(cls): """Decorator for registering new PWNGEF (sub-)command to GDB.""" sys.modules[__name__].__commands__.append(cls) return cls
e27fc2a73d698bed33cf0e1ee23c8bbb366d4a90
640,339
def eliminate_row(df, column_to_search, value_to_search): """ INPUTS -df: pandas dataframe to modify -column_to_search: takes a column name where to search for a specific value -value_to_search: takes a value to search in the specified column OUPUT -returns a dataframe where the unnecessary ...
8dc6aa7c23f3bf4607751047d909640a1ccaafcd
640,340
def find_flat_segment(polygon): """ Find beginning and end indexes of a horizontal section in the polygon. This section can be made of several consecutive segments. If the polygon contains several flat sections, this function only identify the first one. The polygon is a list of 2D coordinates (x, y...
7030beb603cfa24ab601d6d83a444692a6508f4d
640,341
def test_classifier(classifier, inputs, labels): """Compute mean subset accuracy for a classifier. Args: classifier: A scikit-learn classifier. inputs: a Kx464 array of linearised input images. labels: a K-vector of integer labels. Returns: A scalar mean accuracy score. """ return classifier...
8f0968c4df172a91a914c81ca9e763c831fa7bf6
640,342
import re def name_check(name): """ NAME: name_check ---------- DESCRIPTION: Replaces and corrects users' park name query with a unique identifier in order to save them searching for the exact name of the national park. Works for the top 20 national parks in terms of number of visits. ----...
4f1cb36da3cd24784903e0dca7ea191bc200ee3a
640,344
def get_cpu_state_dict(model): """Save all state dict variables except the digital twins ones.""" cpu_state_dict = {} for key, val in model.state_dict().items(): if not '.dt' in key: cpu_state_dict[key] = val.cpu() return cpu_state_dict
d84f237753c269f12bf04a7a75ad1e02a1269885
640,345
import re import warnings def _build_any_numeric_capability(term, cap, num=99, nparams=1): """ Build regexp from capabilities having *any* digit parameters (substitute matching \d with pattern \d and return). """ _cap = getattr(term, cap) if _cap: cap_re = re.escape(_cap(*((num,) * npa...
a4e90a4501ba6245ca00bbd2c5fb95d910afc97e
640,346
def _get_outside_corners(corners, board): """ Return the four corners of the board as a whole, as (up_left, up_right, down_right, down_left). """ xdim = board.n_cols ydim = board.n_rows if corners.shape[1] * corners.shape[0] != xdim * ydim: raise Exception("Invalid number of corners! %d...
9ddd8b60771e74451a4ea7abd4bd5bb55846d89e
640,347
import os def real_getenv(space, name): """Get an OS environment value skipping Python cache""" return space.newtext_or_none(os.environ.get(name))
b46b7ea6c32c11aac7ebfcfa40b8cbe0545a392d
640,348
def get_sorted_clusters(clusters): """ Obtains a sorted list of clusters. :param pd.DataFrame clusters :rtype List[str] """ return sorted(clusters['classification'].unique())
58d2117c003654ab81d50b869945aabc81f91ccb
640,349
def c_to_f(temperature): """ Converts a temperature in Celsius to Fahrenheit. """ return temperature * 9 / 5 + 32
865f92d2c170c3eaf03f097c4cc1f79bf16a12ef
640,350
def _GetBalancingModes(): """Returns the --balancing-modes flag value choices name:description dict.""" balancing_modes = { 'RATE': """\ Spreads load based on how many requests per second (RPS) the group can handle. There are two ways to specify max RPS: *--max-rate* which define...
f67994a09aa2e5ce83611d240920b58e9c000778
640,351
def add(x, y): """Adding these two numbers""" return x + y
61ccb7b027c226a9389dac619d733366a469d8d6
640,352
def parse_link_id(link): """ extracts the div[@id] from the links on the DocumentsForBill pages """ return link.get('href')[link.get('href').find("'") + 1 : link.get('href').rfind("'")]
cff5024ea271027d595810837f6722bd0d690f1e
640,353
def get_intersection(u, v, node_presence): """ Get the intersection between the presence of u and v. :param u: First Node :param v: Second Node :param node_presence: Node presence :return: Interection """ intersec = [] for ut0, ut1 in zip(node_presence[u][::2], node_presence[u][1::2...
95d368872af2c3b3abb88a773ff448149f526fb6
640,354
def policy_generator(context, request, policy_actions=None, create_form=None, resource_choices=None, resource_type=''): """IAM Policy generator""" policy_actions = policy_actions or {} resource_choices = resource_choices or {} return dict( policy_actions=policy_actions, resource_type=res...
a11df98cc2f7bbeb6c6674c008d15913da4c4606
640,355
def chute_find_field(chute, key, default=Exception): """ Find a field in a chute definition loading from a paradrop.yaml file. """ if key in chute: return chute[key] elif 'config' in chute and key in chute['config']: return chute['config'][key] elif isinstance(default, type): ...
064171e9f96eb9c99840d69fd56d687c4f0a23d9
640,356
import time def timeit(method, showparams = False): """ Define an inner function that invoke the method and measure the time that takes to run it. """ def inner(*args, **kw): """ This function will compute the time that takes to invoke the function passed by...
682270f90d55bc7300dde63336f559ed930555e0
640,357
def scale(df, samples, scale_value=100): """Return copy of dataframe with a set of columns normalized Parameters ---------- df : pandas dataframe The data frame to be normalized samples : list of str Column identifiers to use for indexing the data frame scale_value : Optional[fl...
441c766ec03adf59c51ac8d79a4b8ec3e53d42b9
640,358
def _check_array_range(istart, iend, npts): """ Takes two indices, checks that they are in the correct order, ie. start is smaller than end, checks that start>=0 and end<=npts, and checks that start!=end. """ istart = int(istart if istart<iend else iend) iend = int(istart if istart>iend ...
b042448a0169d686e1a185133e8c324d5c74d242
640,359
def GetObjcopyCmd(target): """Return a suitable objcopy command.""" if target == 'mips32': return 'mipsel-nacl-objcopy' return 'arm-nacl-objcopy'
75651777e07b275a0fc503ab17f29e0152788af2
640,360
import typing import importlib def get_callable(s: typing.Union[str, dict, typing.Callable]) -> typing.Callable: """ A "feature function" can be specified in 3 ways: - as Python callable object - as string of dot-separated names, where the part up to the last dot is taken as Python \ module spe...
701df5dc55363ce9bcbc239f2ad05682118fb5b3
640,361
def c_to_f(c_temp): """ Converts from Celsius to Farenheint """ try: return (float(c_temp) * 9.0 / 5.0) + 32.0 except ValueError: return None
f32139c4c21eccae59ef35cd932b4941de601c96
640,362
import re def get_no_export_output(vm_host): """ Get no export routes on the VM Args: vm_host: VM host object """ out = vm_host.eos_command(commands=['show ip bgp community no-export'])["stdout"] return re.findall(r'\d+\.\d+.\d+.\d+\/\d+\s+\d+\.\d+.\d+.\d+.*', out[0])
b3f9a12245c0d4331e88da07ffb7918fabce4c5f
640,363
def _is_partial_index(gbi_file): """Check for truncated output since grabix doesn't write to a transactional directory. """ with open(gbi_file) as in_handle: for i, _ in enumerate(in_handle): if i > 2: return False return True
a017cbb265c4e4f82f35e933a637356ec0efba73
640,364
def guard_hashtag(content: str, match: str) -> bool: """ Guard statement: Verifies if a reply is replying to a message from the actual bot. To be used in conjunction with a return. False if the code should keep running. True if the code should stop running. """ return not content.startsw...
825d3a4d6015fd1c444569a5ba234feeb009cb67
640,365
def iterable(item): """ Predicate function to determine whether a object is an iterable or not. >>> iterable([1, 2, 3]) True >>> iterable(1) False """ try: iter(item) return True except TypeError: return False
14edd2795694245cca22d748307bf4722851b216
640,366
def mock_read(string): """Monkey patch read function.""" def read(_=None): """Mock read function.""" return string return read
0045835addea4d7da7196512d8914e51c9b7b3e3
640,367
def get_geofence_collection_arn(region, account_id, collection_name): """ Helper to convert Geofence Collection name to ARN, since this information is not available directly from the Geofencing API. """ return f"arn:aws:geo:{region}:{account_id}:geofence-collection/{collection_name}"
390f35418111b4a0d806a690172c99903362e4c0
640,368
def find_even_index(arr): """Return the index where sum of both sides are equal.""" if len(arr) == 0: return 0 for i in range(0, len(arr)): sum1 = 0 sum2 = 0 for j in range(0, i): sum1 += arr[j] for k in range(i + 1, len(arr)): sum2 += arr[k]...
cc6f3622ebd283091875e6d8a575551b618c318f
640,369
def report_total_intake(element_totals, total_value): """Reports element-wise total""" element_totals[0]+=element_totals[0] element_totals[1]+=element_totals[1] element_totals[2]+=element_totals[2] element_totals[3]+=element_totals[3] total_value+=total_value return element_to...
9f291706b2adf0d722f95fcbc8367ab20c3df34c
640,370
from typing import Counter def build_vocab(lst): """Return vocabulary for iterable `lst`.""" vocab_count = Counter(w for txt in lst for w in txt.split()) vocab = list(map(lambda x: x[0], sorted(vocab_count.items(), key=lambda x: -x[1]))) return vocab, vocab_count
3bc37d5409e4680ab24f0298d34122273b0733a0
640,371
def prediction_class_names(predictions, class_to_idx): """ 转换索引到类别名称 Args: predictions ([int]): 要预测的类别索引 class_to_idx (dict): 类别到id映射 Returns: class_names ([str]): 返回预测的类别名称 """ class_dict = {val: key for key, val in class_to_idx.items()} class_idxs = [class_dict[pre...
6e7325d7094e3820f741bb83fe82081b27782155
640,372
import socket import os def create_s3_key(config, file_path): """Creates backup S3 key""" key = config.get('s3cfg', 's3_backup_prefix').strip('/') + '/' + \ socket.getfqdn() + '/' + \ config.get('sync_config', 'artifactory_backup_task_version_folder').strip('/') + \ ...
9a7a6a8b5320afc384fd51dc52b6d9938d79c0bb
640,373
def insert_prefix(data, axis=False): """ Adds a prefix entry effectively forcing a initial zero state for the graphs. Should be applied to both axis and data. """ data.insert(0, " " if axis else 0) return data
0b59d8f16ce6b6b4e1d391cba0fc4334e02c854d
640,374
from pathlib import Path def expand_paths(path_or_pattern): """ Make a list of paths from a glob pattern From https://stackoverflow.com/a/51108375 """ path = Path(path_or_pattern).expanduser() parts = path.parts[1:] if path.is_absolute() else path.parts return list(Path(path.root).glob(str...
3ac05b697723d4d6d6685b9c15f3f00618f7839a
640,375
def tofloat(v): """Check and convert a string to a real number""" try: return float(v) if v != '.' else v except ValueError: raise ValueError('Could not convert %s to float' % v)
9345a55bcd4f4e8e57aef9d456eb6ba7e0b26646
640,376
def taylor_4(xs, h, y0, f, df_x, df_y, df_xx, df_yy, df_xy, **derivatives): """Taylor 4rd""" ys = [y0] for k in range(len(xs)): second_summand = f(xs[k], ys[k]) * h third_summand = ( df_x(xs[k], ys[k]) + df_y(xs[k], ys[k]) * f(xs[k], ys[k]) ) * (h ** 2) / 2 fourth...
845af257337ceb871cbea4b4b38f541795a7ee7f
640,377
from typing import List def single_number_math(nums: List[int]) -> int: """2∗(a+b+c)−(a+a+b+b+c)=c""" return 2*sum(set(nums))-sum(nums)
348d2d5ad14da87aefb5feba5961eef40357b490
640,378
def _pow(a, b): """C-like power, a**b """ return a**b
02101594d22a3366912b468de96bfe0bdab44102
640,379