content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import string def get_values(revision): """ Get the values to determine edit type (editorial or content). """ values = { "words": len([w for w in revision["content"].split() if w not in string.punctuation]), "images": len(revision["images"]), "links": len(revision["links"]), "urls": len(revision["urls"]), ...
6c1bc828325b25088fd558b7f0d94e9ab5b92b5e
690,250
import ast def is_name_in_ptree(name, ptree): """ Return True if an ast.Name node with the given name as its id appears anywhere in the ptree, False otherwise """ if not ptree: return False for node in ast.walk(ptree): if isinstance(node, ast.Name) and (node.id == name): ...
c2d6d0001c3baf14c110ff351c8a1c5e97b256d8
690,251
def get_location(http_info): """Extract the redirect URL from a pysaml2 http_info object""" assert 'headers' in http_info headers = http_info['headers'] assert len(headers) == 1 header_name, header_value = headers[0] assert header_name == 'Location' return header_value
dac8617d634467b16e58d2a02c1a37e4520e7746
690,252
import os def filenameparser(string, type=''): """ Parses a filepath in several ways 1. type = '' returns [filename, fileextension] 2. type = 'basename' returns basename """ if type == '': return os.path.splitext(string) elif type == 'basename': return os.path.basename(stri...
31adcf8cd397b0306faace1e1f8325c54027c345
690,254
def modus_ponens(p, q): """Implements the modus ponens logic table: p -> q""" if p: return q else: return not p
b60b99f4cf1c7d2fe7d1c7b96ed8350e2d8a7a9f
690,255
import sys def get_first_line_number(node): """ From Python 3.8 onwards, lineno for decorated objects is the line at which the object definition starts, which is different from what Python < 3.8 reported -- the lineno of the first decorator. To preserve this behaviour of Vulture for newer Python v...
56a1b2bbf8b8f8167ff1df7ff872467a5532e682
690,256
def interval_idx(x, xi): """ Given a grid of points xi (sorted smallest to largest) find in which interval the point x sits. Returns i, where x \in [ xi[i],xi[i+1] ]. Raise ValueError if x is not inside the grid. """ assert x >= xi[0] and x <= xi[-1], ValueError( 'x=%g not in [%g,%g]' %...
630d44e645def046bb156f71ba69c1abb9ea69ec
690,257
def print_test(a): """ Added for get_input parameter injection testing. :param a: input :type a: int :return: len(a) as str """ return str(len(a))
043cc9260bd08d4e06686501f266ad33099636ae
690,259
def atResolution(rect): """ Returns true iff the rectangle described is at resolution """ return True
07d3c787aeb74f6395260d21abe5555722f348f9
690,262
import time import os def readtrain(traindir): """ Reads the training subset of CLS-LOC challenge of ILSVRC 2015 :param traindir: The folder containing the training class subfolders :returns: traindict(A dictionary with full path to each image as a key, and the corresponding label name as the cor...
96bf5c5308ba5a207b8b2649e887e710712389a5
690,263
def _isSubsequenceContained(subSequence, sequence):# pragma: no cover """ Checks if the subSequence is into the sequence and returns a tuple that informs if the subsequence is into and where. Return examples: (True, 7), (False, -1). """ n = len(sequence) m = len(subSequence) for i in ra...
aa064fd1017342e0d980aadba69a1929f02a1e8f
690,264
import torch def add_jitter(mat, jitter_val=1e-3): """ Adds "jitter" to the diagonal of a matrix. This ensures that a matrix that *should* be positive definite *is* positive definate. Args: - mat (matrix nxn) - Positive definite matrxi Returns: (matrix nxn) """ if hasattr(mat, "a...
78fc79cfcbcbd4845025ab465ac9dce3a8c978b2
690,265
def v3_settings_new_pin_json(): """Return a /v1/ss3/subscriptions/<SUBSCRIPTION_ID>/settings/pins (new pin).""" return { "account": "12345012", "settings": { "normal": { "wifiSSID": "MY_WIFI", "alarmDuration": 240, "alarmVolume": 3, ...
8e35a1644432b462694fd75ecfc4ff79198becc0
690,266
def get_service(v1, service): """Get service spec for service""" return v1.list_service_for_all_namespaces(watch=False, field_selector="metadata.name=%s"%service)
de7327bbece40d3015424605c8f481367a13549e
690,267
def MakeSpecificSKUPropertiesMessage(messages, instance_properties, total_count): """Constructs a specific sku properties message object.""" return messages.FutureReservationSpecificSKUProperties( totalCount=total_count, instanceProperties=instance_properties)
de3e9b6a4f85a886cdbfac66e71d2a16e589024c
690,269
def gl_add_user_group_project(gl_project_group, gl_user, gl_access_level): """ Adds a Gitlab user to a Gitlab project or group at the given access level :param gl_project_group: A Project or Group object :param gl_user: A User instance :param gl_access_level: A gitlab.Access_Level. Can be gitlab.GUE...
a223bb06201f0ffd1ba7d4c6466368433f60816d
690,270
import torch def poisson(datum: torch.Tensor, time: int, dt: float = 1.0, **kwargs) -> torch.Tensor: # language=rst """ Generates Poisson-distributed spike trains based on input intensity. Inputs must be non-negative, and give the firing rate in Hz. Inter-spike intervals (ISIs) for non-negative da...
67d999f5d31b03f62eefc64f1af06b3e5f09a7cd
690,271
def parse_dimensions(dimensions): """ Parse the width and height values from a dimension string. Valid values are '1x1', '1x', and 'x1'. If one of the dimensions is omitted, the parse result will be None for that value. """ width, height = [d.strip() and int(d) or None for d in dimensions.split...
69e02ab02dd0d37c4d72e591f40d91dff0d18de1
690,272
def table_names(): """Dict of some test table names with characters that are not url safe with url-escaped versions. """ return { "Test table 1": "Test%20table%201", "Test/Table 2": "Test%2FTable%202", "Another (test) table": "Another%20%28test%29%20table", "A & test & ta...
cb37f4f64b1ae0a4053b664a50f420731550c492
690,273
def ft(f: list, g: list) -> list: """ 直接计算 y_n = f_n * g_n = \sum_m=0^M-1{f_n-m}{g_m} 复杂度 O(MN) """ N, M = len(f), len(g) if M > N: # let M < N f, g = g, f M, N = N, M L = M + N - 1 y = [0] * L for n in range(L): for m in range(M): if n-m ...
939f2c57978e6c3b06391f3434a32ac6e4157858
690,274
def class_to_name(class_label): """ This function can be used to map a numeric feature name to a particular class. """ class_dict = { 0: "Hate Speech", 1: "Offensive Language", 2: "Neither", } if class_label in class_dict.keys(): return class_dict[class_label...
c5618725473f6459660610934ea8ffa2a0a04f39
690,275
def is_subgraph(G, H): """ Checks whether G is a subgraph of H, that is whether all the edges of G belong to H """ edges1 = set(G.edges()) edges2 = set(H.edges()) return len(edges1) == len(edges1 & edges2)
9d57238cbf0854ed1cb7c60afb7d6e008a927348
690,276
import argparse def _looks_like_flag(token: str, parser: argparse.ArgumentParser) -> bool: """ Determine if a token looks like a flag. Unless an argument has nargs set to argparse.REMAINDER, then anything that looks like a flag can't be consumed as a value for it. Based on argparse._parse_optional(). ...
212cf4c0d5a6e013fdf191f43b2425552ccb5149
690,278
def ns_faint(item_name): """Prepends the faint xml-namespace to the item name.""" return '{http://www.code.google.com/p/faint-graphics-editor}' + item_name
d1e28638b1735b3f14752ba684528f134666dd77
690,279
import os import json import sys def get_db_pwd(cfg): """ Helper function that fetches the user's PostgreSQL database password from the secret.json file. The secret.json is set up according to the README.md file. :return: the database password stored in secret.json """ if os.path.isfile(cfg['...
429c7587bac7ce1721e345c848c993a682509a9b
690,280
def string_to_array(str_value): """converts cell contents to list, splitting by commas""" return [item.strip() for item in str_value.split(',')]
56b52eb5182af7a38e6def07a9a49e49731ea4bd
690,281
def polygon(self, nvert="", x1="", y1="", x2="", y2="", x3="", y3="", x4="", y4="", **kwargs): """Creates annotation polygons (GUI). APDL Command: /POLYGON Parameters ---------- nvert Number of vertices of polygon (3 NVERT 8). Use /PMORE for polygons with more than ...
9af0e648121c08d2438745eb18e345cf41ae36c7
690,282
import importlib def base_pkg(): """Provide a reloaded base package as a fixture.""" pkg = importlib.import_module("{{ cookiecutter.project_slug }}") return importlib.reload(pkg)
bc98d798439d8155381d4c44da65f5ea590d71a3
690,283
def get_admin_site_name(context): """ Get admin site name from context. First it tries to find variable named admin_site_name in context. If this variable is not available, admin site name is taken from request path (it is first part of path - between first and second slash). """ admin_site_...
c18da7e89ff6c6190d276956e7031cac74683b63
690,284
def list_get_index(list_var, index, default=None): """Provide equivalent of dict().get().""" if index < len(list_var): return list_var[index] else: return default
a5c0338a609a4d8958896ea2fd7aaa9262ad0f48
690,286
def to_iso_format( date_time): """ Return a string representing the date and time in ISO 8601 format, YYYY-MM-DD HH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DD HH:MM:SS If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and mi...
41fcc983707874da2bac3407f5f3bfdb8e9807b8
690,287
def re_fun(number): """递归调用,计算某个数的阶乘""" if number == 1: return number return number * re_fun(number - 1)
a57c3a4f3d8609c4733004dee47e15e3dfbe45f1
690,289
import torch def _flip_path_probability(cum_log_prob, xlens, path_lens): """Flips a path probability matrix. This function returns a path probability matrix and flips it. ``cum_log_prob[i, b, t]`` stores log probability at ``i``-th input and at time ``t`` in a output sequence in ``b``-th batch. Th...
0cfc4bf059f277137381b45873a7041dc0c62375
690,290
def get_data_matching_filter(filter_by, raw_data): """ Returns a list of data matching filter_by from a given STB's raw_data :param filter_by: Tuple containing (filter_name, filter_value) :param raw_data: Dictionary of raw stb_data for 1 STB. :return: List of dictionary entries from flattened STB ma...
acce77c830371022be09ff0dc1337e419fd0818e
690,291
def select_latest_verified_vm_image_with_node_agent_sku(publisher, offer, sku_starts_with, batch_client): """ Select the latest verified image that Azure Batch supports given a publisher, offer and sku (starts with filter). :param batch_client: The batch client to use. :type batch_client: `batchserv...
08fe7940f3f0b69701fdf5f3bec79bab69209820
690,292
def is_float(arg): """ Returns True iff arg is a valid float """ if isinstance(arg, float) or isinstance(arg, int): return True try: float(arg) except ValueError: return False return True
408ce0ef3e1d40c4e82808785368c621448a6001
690,293
def make_rest(step_size): """ this method constructs a placeholder for a rest note """ return {"rest":step_size}
c4ad4a70c1417c82decc554712652f225ff124af
690,294
def get_sessions_by_dimensions( service, profile_id, startDate, endDate, segment, dimensions, metrics="ga:sessions" ): """ Query the API for channel grouping for sessions WITH dimensions And sort query output by the first dimension specified Args: service: authenticated connection objec...
c0099624b25e91f2d0d4f5363d55663309369bcd
690,295
def backpointer_cell_to_string(cell): """Makes a string of a cell of a backpointer chart""" s="[" for (k,rhs) in cell: s+="(%i, %s)"%(k,",".join(rhs)) s+="]" return s
a3a416fd08ffdfb96419f6202b54e478052eb631
690,296
def cutStrAndAlignRight(s,length=8): """ Cuts the string down to the specified length and if it's shorter then it aligns it to the right """ if len(s) >= length: return s[0:8] else: return ' '*(length-len(s))+s
01a83bb99cb8f9e1e23ea1470011f68bdd2738c0
690,297
def line_split_to_str_list(line): """E.g: 1 2 3 -> [1, 2, 3] Useful to convert numbers into a python list.""" return "[" + ", ".join(line.split()) + "]"
3f06e0f03b22d4dd92939afe7a18d49a1bc236dc
690,299
from pathlib import Path def single_duplicate_bond_index_v3000_sdf(tmp_path: Path) -> Path: """Write a single molecule to a v3000 sdf with a duplicate bond index. Args: tmp_path: pytest fixture for writing files to a temp directory Returns: Path to the sdf """ sdf_text = """ ...
b698fbef40ffc32edb7ee41f76d0c6d53e2ddb3c
690,300
def extract_github_owner_and_repo(github_page): """ Extract only owner and repo name from GitHub page https://www.github.com/psf/requests -> psf/requests Args: github_page - a reference, e.g. a URL, to a GitHub repo Returns: str: owner and repo joined by a '/' """ if githu...
dbcee3c500d6650a1a48c372412ce5e37723b34b
690,301
def true_num_ops(exponent_matrix): """ without counting additions (just MUL & POW) and but WITH considering the coefficients (1 MUL per monomial) """ num_ops = 0 for monomial_nr in range(exponent_matrix.shape[0]): for dim in range(exponent_matrix.shape[1]): exp = exponent_matrix[...
169282e628a022d71ab6ddb03a35b8eda4022ef7
690,302
import itertools def fold (paper, along, line, nrows, ncols): """Folds `paper` `along` (`'X'` or `'Y'`) axis at the horizontal or vertical `line`. The size of `paper` is `nrows`-by-`ncols`. The `paper` is modified in-place (dots "below" or "right" of the fold are deleted and a new `(nrows, ncols)` p...
8ef99e199b63e7c5c55ee553f83155ffb406718e
690,303
from typing import Union def invalid_output( query: dict, db_query: Union[str, dict], api_key: str, error: str, start_record: int, page_length: int) -> dict: """Create and return the output for a failed request. Args: query: The query in format as defined in wrapper/input_format.py. ...
4a97a89f5ce7003d582b23b8e7ca036eff74a3b0
690,304
def clean_label(labels): """ Remove undesired '' cases """ labels = list(filter(''.__ne__, labels)) return labels
fcf42c2353a4ce19b8cc697789459f8b24d795d6
690,305
def time_mirror(clip): """ Returns a clip that plays the current clip backwards. The clip must have its ``duration`` attribute set. The same effect is applied to the clip's audio and mask if any. """ return clip.time_transform(lambda t: clip.duration - t - 1, keep_duration=True)
4f7283cf53090946ed41fc1c736a7c84f7cfba37
690,306
import argparse def _add_and_parse_args(): """Build the argparse object and parse the args.""" parser = argparse.ArgumentParser(prog='mbr_strip', description=('A command line utility for stripping the MBR ' + 'out of a Soft...
01e15625520282593300658181e9210e95d3571f
690,307
import ast def real_repr(thing): """Converts the given value into a string which when evaluated will return the value. This one is smart enough to take care of ASTs""" if isinstance(thing, ast.AST): fields = [real_repr(b) for a, b in ast.iter_fields(thing)] return '%s(%s)' % (thing.__class...
0264cf2a5d4f2be124e6ce9d8431fbe9193ae50d
690,308
def get_smallest_divisible_number_brute_force(max_factor): """ Get the smallest divisible number by all [1..max_factor] numbers by brute force. """ number_i = max_factor while True: divisible = True for factor_i in range(1, max_factor+1): if number_i % factor_i > 0: ...
f30159375bf852e77da2fcee21f8c5e407042b95
690,310
from typing import Any from typing import List def lst(*a: Any) -> List[Any]: """Returns arguments *a as a flat list, any list arguments are flattened. Example: lst(1, [2, 3]) returns [1, 2, 3]. """ flat = [] for v in a: if isinstance(v, list): flat.extend(v) else: ...
cb1c03058fab81071a22e7ca6febe898676c9a40
690,311
def parse_stam(organization_data): """ Used to parse stamnummer of organization. """ return str(organization_data["stamNr"])
2937dc908a3a81d9bca35fe47a5327d4befbf22d
690,312
import subprocess def _call_mb(command_list): """ call the command as sps """ proc = subprocess.Popen( command_list, stderr=subprocess.STDOUT, stdout=subprocess.PIPE ) comm = proc.communicate() if proc.returncode: raise Exception(comm[0].decode()) return co...
ad34041161c37fb8982ba9634be04beeda290718
690,313
def _get_list(list_=None): """get list from yaml file element""" if not isinstance(list_, list): if list_ is None: _ = [] else: _ = [list_] else: _ = list_ return _
8c8d5a0bb8ed767e01950359f8053771ed5cd5a7
690,314
def getaBasicMapCombinations(B): """ This function gets all possible combinations of the basic 2x2 constellation. :param B: 2^B-QAM for PAPR calculation purposes. :return: All possible combinations. """ basicMapCombinations = [] if(B==4): for i in range(8): for j in range...
c038fbcaa9a0772f725e0f6ef31fbc06a1ba9ac8
690,315
import numpy def rotation_matrix(angle, axis): """ Creates a 3x3 matrix which rotates `angle` radians around `axis` Parameters ---------- angle : float The angle in radians to rotate around the axis axis : array The unit vector around which to rotate Returns ...
d78d3f8e21fdd710f742bb917c4026890af77b14
690,316
def construct_type(code): """Construct type in response.""" # return 'https://bcrs.gov.bc.ca/.well_known/schemas/problem#{}'.format(code) return code
f98dfa58c6d6573a2dd5d37851be638831a96156
690,317
def silverS(home_score, away_score): """Calculate S for each team (Source: https://www.ergosum.co/nate-silvers-nba-elo-algorithm/). Args: home_score - score of home team. away_score - score of away team. Returns: 0: - S for the home team. 1: - S for the away team. ""...
29b714fa9392deba82310fe3bcab7f23300c82bb
690,318
def _get_run_tag_info(mapping): """Returns a map of run names to a list of tag names. Args: mapping: a nested map `d` such that `d[run][tag]` is a time series produced by DataProvider's `list_*` methods. Returns: A map from run strings to a list of tag strings. E.g. {...
7840615622176894d6623aa26f4dd5ae0d204620
690,319
def trrotate_to_standard(trin, newchan = ("E", "N", "Z")): """Rotate traces to standard orientation""" return trin.rotate_to_standard(newchan)
85471e817e2000a3781b32237dcea488109378d7
690,320
def score(boards, number, index): """Return the final score of the board that contains index.""" first = index - index % 25 return int(number) * sum(int(boards[i]) for i in range(first, first + 25))
83df16bd015277c1906343b61be7702ff8d2a3bd
690,321
from typing import OrderedDict def get_feature_type_map(feature_arraycol_map, types_of_features): """ Returns OrderedDict of feature-name -> feature_type string (options: 'vector', 'embed'). """ if feature_arraycol_map is None: raise ValueError("Must first call get_feature_arraycol_map() to set featur...
f66cadee3bee21f4e726d73ae61f502cb896eb12
690,322
def Set_Interface_Client(interface="", address=""): """ configure for client to get gateway """ Client = ( "interface "+ interface + "\nip address "+ address + "\nexit\n" ) return Client
8c5252d757d4b382c18bb1e158e6cd9bb140b520
690,323
def convert_idx(text, tokens): """ List of tuples for each token: (token_start_char_idx, token_end_char_idx) """ current = 0 spans = [] for token in tokens: current = text.find(token, current) # Find position of 1st occurrence; start search from 'current' if current < ...
011e54afcf516b8e1c2bd4221c6cc659f3608ae2
690,324
import secrets import hashlib def create_transaction_token(n=1, salt='nawoka'): """Create a payment token for Google enhanced ecommerce""" tokens = [secrets.token_hex(2) for _ in range(0, n)] # Append the salt that allows us to identify # if the payment method is a valid one tokens.append(hashlib....
1636bb5b03f9bfe9e2cd93660b6314d64150759d
690,325
import socket import re def get_ip(): """ Get IP address """ ip = socket.gethostbyname_ex(socket.gethostname())[2][0] aid = re.sub('\.', '_', ip) return aid
b48bc168f946aa5e991eaa72e7ef0f23beefb1a1
690,326
def combine_two_lists_no_duplicate(list_1, list_2): """ Method to combine two lists, drop one copy of the elements present in both and return a list comprised of the elements present in either list - but with only one copy of each. Args: list_1: First list list_2: Second list Return...
4caa2d3494eeef61d502bc898433d04362e81f39
690,327
def match1(p, text): """Return true if first character of text matches pattern character p.""" if not text: return False return p == '.' or p == text[0]
be9c804b03ff13a1e40a7661be13b4d48a8aaad6
690,328
import os def get_extension(path): """ Returns the file extension of the specified path. Example:: >>> get_extension('a.pdf') 'pdf' >>> get_extension('b.js.coffee') 'coffee' >>> get_extension('c') '' >>> get_extension('d/e.txt') 'txt' """ ...
02d79c2a3c834fe2825d134c39383c118d9c40d4
690,329
def normalize_db_entry(line, table): """ Make testing more consistent and reasonable by doctoring certain db entries. Args: line: a String, the line to remove the object id from. table: a map from object ids to file paths. """ files_index = line.find('INSERT INTO "tsk_files"') path...
4663c6d3489a24c0e695a58a8ceffc850e538315
690,330
def tune_install(): """ User input for data source and state machine tuning """ tune = {} # ================================================================== # DATA SOURCE EXAMPLES # ================================================================== source = 6 # user input choose data ...
6168a4ffe77db19779f0ef7a4fd8d97f7c17d921
690,331
def fix_spellfile(wordlist): """Take the old file and append it piecemeal to a new list. This function checks that the old element exists, that the word and the next word don't match, and that the item doesn't start with an :kbd:`!`. These are words that are considered incorrect and can be safely i...
9dc8c5f176a4ded35e7e3aa6d124151bfe4f2bf7
690,332
import os def extract_MODIS_timestamp(mod_directory): """ extracts the acquisition time of MODIS scenes into a new list ## for more information see: https://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date :return: """ MODIS_timestamp_list = [] for filename...
61fbf4af8adfd034641c114231e1b04bf6fcc3be
690,333
import json def parse(json_string: str): """[take a json string and return a python object] Args: json_string (str): [a json string] Returns: [type]: [a python object] """ return json.loads(json_string)
62117fd94d1724584df37897490a8b65780d6d30
690,334
def scan_mv_pca_model_params(model, df_scree): """ Get model params. Extract model params of PCA. Parameters ---------- model : object Fitted PCA object. Returns ------- model_params : dict Model parameter. """ # Select parameters n_components = model._...
249e1b88e8d463b16fe7e42f2ba6b1caa02492d9
690,335
import random def shuffle(lst): """ Shuffle a list """ random.shuffle(lst) return lst
2a50b74306c8fd580a2b9c6ae392d9ce9b34b786
690,336
def subnetToList(listoflist): """ :param listoflist: :return: """ d_temp = [] for l in listoflist: d_temp.append(l.encode('ascii')) print(d_temp) return d_temp
b97a0a9ac59160c8ca37183d612688a201840c36
690,337
from typing import List def __clean_loops(seq: List[int]) -> List[int]: """ Method to remove loops from AS path. """ # use inverse direction to clean loops in the path of the traffic seq_inv = seq[::-1] new_seq_inv = [] for x in seq_inv: if x not in new_seq_inv: new_seq...
fb4f296405fcbec648785eea511add513acb92b8
690,338
import math def bit_length(i: int) -> int: """Returns the minimal amount of bits needed to represent unsigned integer `i`.""" return math.ceil(math.log(i + 1, 2))
672063db380fd0957e68b0974a13e64b610c999b
690,339
from typing import Mapping def extract_fak(fak): """Extracts the (raw) (f, a, k) triple from a dict or tuple/list fak. Also asserts the validity of input fak. >>> extract_fak(('func', (1, 2), {'keyword': 3})) ('func', (1, 2), {'keyword': 3}) If fak has only two input items and the second is a di...
da7ad92eb8489cb601216d85ffaecf381d659f6c
690,340
from typing import Iterable def unique_string(all_strings: Iterable[str], not_unique: str, template: str = '{0}_{1}', start: int = 1): """[summary] Args: all_strings (Iterable[str]): [description] not_unique (str): [description] te...
bbd621933113b77b9e3f0cdb46895d693b4ff581
690,341
import requests import json def get_movie_info(): """ function to send a "GET" HTTP request and get top 250 movies of IMDB then serializing it and dump it in a json file """ API_KEY = 'YOUR-API-KEY' url = f'https://imdb-api.com/en/API/Top250Movies/{API_KEY}' # Delete ...
b9183bddeaa7d8bf42161add10238b41c9ca4523
690,342
from typing import Union def convert_volume(value: Union[float, str]) -> float: """Convert volume to float.""" if value == "--": return -80.0 return float(value)
f93ed46f865ce14e2886bcac8fd0aa56b04f0658
690,345
def sleeper_service(sleep_duration): """ :type sleep_duration: int :rtype: dict """ service = { 'name': "sleeper", 'docker_image': 'alpine', 'monitor': True, 'required_resources': {"memory": 1 * 1024 * 1024 * 1024}, # 1 GB 'ports': [], 'environment': ...
272d6fcca57450eca6a5ac334795303e40d917de
690,347
import os def listdir(path): """Returns a list of entries contained within a directory. Args: path: string, path to a directory. Returns: [filename1, filename2, ... filenameN] as strings. Raises: errors. NotFoundError if directory doesn't exist. """ return os.listd...
e2b52c2b9885bad2fb5e1a938906a41e46052c29
690,348
def get_row_col_num_from_sheet(sheet_name): """ sheet_name(str: -> xlrd.sheet.Sheet)という名のシートに対し, それの行数, 列数を返す. """ row_num = sheet_name.nrows col_num = sheet_name.ncols return row_num, col_num
07f9ce6775c602a54bcb20cdf0eae91fc7169047
690,349
from io import StringIO import sys def dump(pkt): """ Ugly but killerbee needs "special" scapy version pkt: packet to be dumped """ result = "<html><pre>" capture = StringIO() save_stdout = sys.stdout sys.stdout = capture pkt.show() sys.stdout = save_stdout for l in captu...
136bc2ac56b1b8e438a2bb04f905527f746ce934
690,350
def _ag_checksum(data): """ Compute a telegram checksum. """ sum = 0 for c in data: sum ^= c return sum
32d1ef971fc1fb63fb0583c32c309de3de41f39d
690,351
def can_add_elem(self, gameArray): """初始化元素为零的元素数量为16个。每查找到一个非零的元素,计数减1. 如果没有是零的元素,不必添加新元素""" num_zero = 16 # 添加一个判断,如果数组全部非0,不添加元素 for i in range(self.WINDOW_BLOCK_NUM): for j in range(self.WINDOW_BLOCK_NUM): if gameArray[i][j] != 0: num_zero -= 1 if num_zero == ...
62c7d77c69b9c3c157753bd871c4d56a419842d3
690,352
def getSymbols(equation): """Return a set of symbols present in the equation""" stopchars=['(',')','*','/','+','-',','] symbols=set() pos=0 symbol="" for i, c in enumerate(equation,1): if c in stopchars: pos=i if(len(symbol)!=0): if not all(i.isdig...
48340b864aec640389ea2af9704de501e6648e0c
690,353
import turtle def create_turtle(x, y): """[summary] Create the turtle pen with specific attributes [description] Set speed and pen color Direction is set default due east Pen is returned in list with x and y coordinates """ t = turtle.Pen() t.speed(8) t.pencolor("white") r...
305a0e63801821543a9087e245e4cc4c7ceee03d
690,354
def transform_pts(T, pts): """ copied from https://github.com/ylabbe/cosypose/blob/master/cosypose/lib3d/transform_ops.py """ bsz = T.shape[0] n_pts = pts.shape[1] assert pts.shape == (bsz, n_pts, 3) if T.dim() == 4: pts = pts.unsqueeze(1) assert T.shape[-2:] == (4, 4) ...
ccb2efc851c9270bf86d64597b51e371876839c9
690,355
import random import string def rndstr(length): """Generate random string of given length which contains digits and lowercase ASCII characters""" return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length))
698dde72332c8995ebae01ad861037b61bc3be8f
690,356
def bb_union(*bbs): """Returns a bounding box containing the given bboxes""" return [min(*x) for x in zip(*[b[0] for b in bbs])],[max(*x) for x in zip(*[b[1] for b in bbs])]
74631549fdd2aebb1e96790d54b88796d1f0dbe7
690,357
def search_list_of_objs(objs, attr, value): """Searches a list of objects and retuns those with an attribute that meets an equality criteria Args: objs (list): The input list attr (str): The attribute to match value (any): The value to be matched Returns: list[any]: The lis...
061920f5acac2a4b1f3368aef8f8d42472454861
690,358
def tw_to_rgb(thxs): """ Convert a 12-digit hex color to RGB. Parameters ---------- thxs : str A 12-digit hex color string. Returns ------- tuple[int] An RGB tuple. """ if len(thxs) != 13: if len(thxs) == 12: raise ValueError("thxs is not cor...
c5117924c009c65685604fb2e99ebacb3e051588
690,359
import six def _deep_string_coerce(content, json_path="json"): """ Coerces content or all values of content if it is a dict to a string. The function will throw if content contains non-string or non-numeric types. The reason why we have this function is because the `self.json` field must be a dic...
fa3777f3abfd678fdf4f5245570863fb49252430
690,360
def make_pair(coll, lbracket='<', rbracket='>'): """ A context aware function for making a string representation of elements of relationships. It takes into account the length of the element. If there is just one element, the brackets are left of, but when there are more, all the elements will be sepera...
2d3726adb7765a2a0eb2fc6fe238427b683f68e3
690,361
def leia_int(msg): # sem tratamento de erro """ -> Func que remplaza o int() e valida o mesmo. :param msg: input (descrição que mostra na tela) :return: o valor em int() do usuario. """ while True: numero = input(msg) if numero.isdigit(): valor = int(numero) ...
f60b23bbda9c8fee6c13c2a4fc2304d6ef6c6150
690,362