content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def list_all_videos(api_instance, location, account_id, access_token, page_size=100): # noqa """List all videos, using the API paging mechanism. The default page_size is set to 100 (the API default is 25). """ done = False skip = 0 all_videos = [] while not done: list_videos = api_...
e86960a23ccbb19a18bd4bedafa0db37869695ba
637,769
import json def DictToJSON(pydict): """Convert a dict to a JSON-formatted string.""" pretty_string = json.dumps(pydict, sort_keys=False, indent=2) # json.dumps sometimes returns trailing whitespace and does not put # a newline at the end. This code fixes these problems. pretty_lines = pretty_string.split('...
9c02d41efc12d27f210d2d0260826a7f2edaddd2
637,770
def get_sizeChange(size1, size2): """ Returns change in size of an echo as the ratio of the larger size to the smaller, minus 1. """ if (size1 < 5) and (size2 < 5): return 0 elif size1 >= size2: return size1/size2 - 1 else: return size2/size1 - 1
d8b75fa231c8a957db68e7fbac4e1f6ff2270533
637,777
import random def random_crop2d(*images, min_perc=0.5, max_perc=1.): """Crop randomly but identically all images given. Could be used to pass both mask and image at the same time. Anything else will throw. Warnings -------- Only works for channel first images. (No channel image will not work...
80d512f3a84b658ee70dde8311be0318aa89a068
637,779
import torch def split_and_sum(tensor, N): """spliting a torch Tensor into a list of uneven sized tensors, and sum each tensor and stack Example: A = torch.rand(10, 10) N = [4,6] split_and_sum(A, N).shape # (2, 10) Args: tensor (torch.Tensor): tensors to be split and ...
ba2c677935946967f7fc755b51234b003e119652
637,780
def csv_list(l): """Format list to a string with comma-separated values. """ if len(l) == 0: return "" return ', '.join(map(str, l))
0b9388d97a0620c8a105d2fd766358fbbfcc8ae8
637,782
def var_name(string: str) -> str: """Strips out the Variable name from a string :param string: e.g. $MY_PATH:$YOUR_PATH :return string: e.g. MY_PATH """ key = "" for char in string: if char.isalpha() or char.isdigit() or char == "_": key += char else: retu...
acce01104edaffc3ffe72c98e362ae0c0bcfa131
637,786
def load_embeddings(path, dimension=300): """ Loads the embeddings from a word2vec formatted file. word2vec format is one line per word and it's associated embedding (dimension x floating numbers) separated by spaces The first line may or may not include the word count and dimension """ vect...
0ae0777b371781ffbc1519f5828aa9d492b364d9
637,788
def nlineas(n): """Escribe n líneas o línea según el valor de n""" if n == 0: return "cero líneas" elif n == 1: return "una línea" elif n == 2: return "dos líneas" else: return "%d líneas" % n
addee9fcbab080ddbdf69c5cda573b557f0a6c59
637,789
def getConfigIds(config): """Get a list of all config fields that have been set along with the ID. :param config: The configuration object :type config: configuration.Configuration """ fields = [ f + ': ' + str(getattr(config, f)) for f in dir(config) if not f.startswith('_') ...
2f9b9258ebf2b001df2e3344853541425bb3adb7
637,793
def lasso(number: complex, unit: str = '') -> str: """ Make a large number more readable by inserting commas before every third power of 10 and adding units """ return f'{number:,} {unit}'.strip()
ce79711c10f44d88865f36c63023fc7a276a691f
637,794
def render_header(level_and_content): """ - level_and_content: None OR string OR list of [postive-int, string] OR tuple of (positive-int, string), the header level and content RETURN: string, the header """ if level_and_content is None: return "" if isinstance(level_and_content, st...
948e1f16c3ce11a6f30c12a44cdb436aae4b79d8
637,796
def remove_coords(cube): """ Remove non-essential coordinates from ``cube``. This should prevent a number of subsequent cube concatenation issues, plus reduce output file size. Note, however, that scalar coordinates, such as level number in the case of a vertical subset, are also removed. """ ...
06b5992bb457c8a63ba7e290b981af8bc66229cc
637,798
def add_gencfg_parser_options(p): """Add `pbsv1 genenrate-config` parser options""" p.add_argument('-o', '--cfg_fn', metavar="sv.cfg", dest="cfg_fn", type=str, default=None, help="Pbsv1 config file.") return p
3089a258131dffe153060aeabe8e6a82f0196cca
637,800
def guess_scheme(environ): """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' """ if environ.get("HTTPS") in ('yes','on','1'): return 'https' else: return 'http'
4e2451f231841df653af913f9242bd82134f9537
637,801
import base64 def authorization(pat_token, response_type): """ Creates the header for using api calls with PAT tokens """ authorization_base64_bytes = bytes(':'+pat_token, 'ascii') authorization_base64_encode = base64.b64encode(authorization_base64_bytes) authorization_base64_string = str(auth...
30d4b3ee2016adb9578016ec98739e8f39c74c91
637,804
from pathlib import Path def check_and_get_subdirectory(base_dir: Path, subdir_name: str) -> Path: """ Checks existance of base_dir, NON-existance of base_dir/subdir, and returns the Path(base_dir / subdir). Raises: FileNotFoundError if the base_dir does not exist OSError if the...
1df2d2f03b4933a25f1bba7e1cb62f6ce998ccb3
637,809
def uncompress_indices(compressed): """Reverse of compress_indices. """ indices = [] for i in range(len(compressed) - 1): indices.extend([i] * (compressed[i+1] - compressed[i])) return indices
8df26971dcc65dee4ce19c033040e940211c521b
637,812
def accuracy_metrics(act, exp): """Return precision and recall for a single query Args: act (set): actual result exp (set): expected result Returns: float, float: precision and recall """ if act == exp: # Consider the edge case: act=[] exp=[] ...
b88ca95bd4c1692f1b4215ba18b3a1b5b63a8bf0
637,816
def isgenerator(x): """ Returns `True` if the given value is sync or async generator coroutine. Arguments: x (mixed): value to check if it is an iterable. Returns: bool """ return any([ hasattr(x, '__next__'), hasattr(x, '__anext__') ])
057b6d6231e5edac726bf5142d374720fc381885
637,818
def to_years_and_months(months): """ Convert a integer value into a string of years and months e.g. 27 would be represented as '2 Years 3 Months' """ whole_years = months // 12 remaining_months = months % 12 result = '' if whole_years >= 1: if whole_years == 1: result...
ee151b5bedafda5c1e12edaf8069a9ba5e6825e9
637,819
import operator def sub_wo_carry(n1, n2): """ Substract two integer strings of same length without carry >>> sub_wo_carry('9007', '1234') '8873' """ l1 = [int(x)+10 for x in str(n1)] l2 = [int(x) for x in str(n2)] res1 = map(operator.sub, l1, l2) res2 = [str(x)[-1] for x in res1] ...
f4247c27f6c0b5e93205cb528100ec3ec41378b4
637,822
def generate_sets_item_query(names, sets): """ Builds a query with a specified number of sets. :param list names: The name of the workout item. :param int sets: The number of sets to generate in the query. :return: SQL compatible query as a string. """ master_tuple_list = [] for name in...
c7db77cd1ad81c5029ba1a71eaf35fa421033b32
637,825
def get_fname(dsrc,depTime,mforecast): """ Returns the name of the grib file on the NCDC server at the time requested Args: * 'dsrc' (string): type of source files for weather: either namanl or rap * 'DT (string): date and time of the grib file requested * 'mforecast' (string): ...
8e3a25e5c5e23802c870cfe253b276a8fa0c5d2e
637,829
import json def _hash_task(task): """ Returns a unique hash for identify a task and its params """ params = task.get("params") if params: params = json.dumps(sorted(list(task["params"].items()), key=lambda x: x[0])) # pylint: disable=no-member full = [str(task.get(x)) for x in ["path", "int...
f898bcc5ea95bf1fb79068043a7fc9348afd4372
637,836
import random def RandomSample(data, size): """Returns random sample of given size """ return data.ix[random.sample(data.index, size)]
063267fc19cdab65b435cf30763cea17284a0eca
637,843
def check_horizontal_winner(board) -> bool: """checks for horizontal winner""" for row in board: if row[0] == row[1] == row[2] and row[0] is not None: return True return False
5ca3bea6451e59c42dd032f472c155c4266fede6
637,846
def _comment(s): """Returns a new string with "#" inserted before each line in 's'.""" if not s: return "#" res = "".join(["#" + line for line in s.splitlines(True)]) if s.endswith("\n"): return res + "#" return res
e00d0d83a4605c81a8c5a176bac773544b3ebab7
637,848
def flatten_string_list(arglist): """ Assemble a list of string, such as for a subprocess call. Input should be a string or a list containing only strings or similar lists. Output will be a list containing only strings. """ if isinstance(arglist, ("".__class__, u"".__class__)): retur...
c96d98163286ff9b56f18530523e463f5e833269
637,851
def extract(input_data: str) -> tuple: """take input data and return the appropriate data structure""" rules = dict() messages = list() rules_input, messages_input = input_data.split('\n\n')[0:2] for rule_input in rules_input.split('\n'): rule_id, rule = rule_input.split(': ') rules...
f646868d39f095777e86b63a3a4eb1ba913d5aca
637,853
import math def aika(etäisyys, nopeus): """ Laske annetun etäisyyden ajamiseen tarvitun ajan tunneissa ja minuuteissa. """ aika = etäisyys / nopeus minuutit, tunnit = math.modf(aika) return (int(tunnit), int(minuutit * 60))
135036cbeae6f691b25f815ed069cde33aea1f13
637,854
def content_function(obj): """Just return content""" _, _, _, content = obj return 'content', content
7f11a6b86d81a1437b8643cd2461d44caeb2b4aa
637,856
import re def validate_maintenance_window(window): """Validate PreferredMaintenanceWindow for DBInstance""" days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") day_re = r'[A-Z]{1}[a-z]{2}' hour = r'[01]?[0-9]|2[0-3]' minute = r'[0-5][0-9]' r = ("(?P<start_day>%s):(?P<start_hour>%s):(?P<s...
ced6140fa250e157aaa532f7c531abf64e41768e
637,860
import ctypes from typing import Optional def _aligned_ptr_offset_in_object(obj: object, referent: object) -> Optional[int]: """Return the byte offset in the C representation of *obj* (an arbitrary Python object) at which is found a naturally-aligned pointer that points to *referent*. If *search_for* ...
accde7b5a999c62ad0a104d7dbdc7be46f109973
637,861
import pickle def load_classifier(model_path, vec_path): """ Loads classifier from subfolder . Parameters ---------- model_path: String The path where the classifier is stored vec_path: String The path where the vectorizer is...
103f7669b4e68ca836c605f1e0133317d02a6210
637,862
def check_config_inputs(arg): """ Checks that all the data that should be numerical from that config can be represented as a float. Parameters __________ arg: unknown any argument can be passed. Returns _______ is_number: Boolean Value is True if the arg is a number...
bcba3e7cc65a351d53ad2b6b07f73fb9eabcf299
637,865
def dim_check(dev_dist, std_min, std_max): """ Boolean: does value fall within allowed range? """ return std_min <= dev_dist <= std_max
c692c22ce131081597fea05b39d75e4ae8b0fdc6
637,866
import torch import operator def summarize_profiler_info(prof: torch.autograd.profiler.profile) -> str: """ Summarizes the statistics in the specified profiler. """ # create sorted list of times per operator: op2time = {} for item in prof.key_averages(): op2time[item.key] = ( ...
ab1cddab0f690b491012c9fa7fff9ee3c68a7c74
637,867
def decode(string): """Decodes a String""" dec_string = string \ .replace('&amp;', '&') \ .replace('&lt;', '<') \ .replace('&gt;', '>') return dec_string
fb930daa6761d78bfa6cde523a56ffe8be374da7
637,871
import glob def _get_header_files(include_dirs): """Return a list of all extra headers to include in checks.""" headers = [] for path in include_dirs: headers += glob.glob(path + "/**/*.h", recursive=True) headers += glob.glob(path + "/**/*.hh", recursive=True) headers += glob.glo...
981652963a8bbf71beef10a31a24d02fafd71695
637,874
def read_file(filename, delimiter=None, startline=0): """Reads a text file into a list of lists Parameters ---------- filename : string the file path to open delimiter : string (optional) the delimiter separating the column data (default to None for all white space) startline : ...
425daa6b70840a49277754e6e1422ffc73ef8b6d
637,877
def penalize_short(genotype, weight=20): """fitness function handling short notes Args: genotype ((int, int)[]): list of tuples (pitch, dur) representing genotype of a chromosome weight (int, optional): Defaults at 20. Defines penalty/reward rate Returns: int: aggregate fi...
ffde1330c2e2e6aa562c8f1a8047c6d0e08cd441
637,878
import requests from bs4 import BeautifulSoup import random def grab_a_paper(base_url): """ Given an arXiv base url, grab a random paper from that URL """ links = [] titles = [] papers = {} # a dictionary of links and titles # Get webpage and initialize bs object r = requests.get(bas...
bb86ad0e4862f32b2172402ee3395400e6a16939
637,881
def smallest_side(length: int, width: int, height: int) -> int: """Multiply the smallest edges of a gift to get its smallest side Args: length (int): The length of the gift width (int): The width of the gift height (int): The height of the gift Returns: int: The area of the...
23255925c38cd2347c543b0c8575381fe0b3809c
637,882
def _detect_fully_listened_track(remaining_duration, end_of_track_buffer) -> bool: """Performs the detection logic for whether a track was fully listened through Args: remaining_duration: The remaining duration of the track in milliseconds end_of_track_buffer: T...
7a7a1a04ef5c2bb6f53e81b47842b989d5491028
637,887
from typing import List def get_filename_from_query(query: List[str]) -> str: """Convert a keyword query into filenames to dump the paper. Args: query (list): List of string with keywords. Returns: str: Filename. """ filename = "_".join([k if isinstance(k, str) else k[0] for k in...
e61b2a0ffbfed37df4c77c2829312adc4df94a6f
637,892
def get_object_type(object_id): """ Obtain object type Parameters ---------- object_id : int object identifier Returns ------- object_type : str type of object """ # https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/naif_ids.html if object_id < -100000: ...
308e57d50f9f72fce7785ab07461cf98e1672cfb
637,893
def _import(class_path): """ Imports a module or class from a string in dot notation. """ bits = class_path.split('.') mod_name = '.'.join(bits[:-1]) cls_name = bits[-1] mod = __import__(mod_name, None, None, cls_name) return getattr(mod, cls_name)
4d96de56aca59f6aa22c24fc1fe3f006727cc810
637,898
def control_change_rate_cost(u, u_prev): """Compute penalty of control jerk, i.e. difference to previous control input""" return (u - u_prev) ** 2
09439fa7b2b6afa306e41e85434db3064be0a481
637,904
def cremona_letter_code(n): """ Returns the Cremona letter code corresponding to an integer. For example, 0 - a 25 - z 26 - ba 51 - bz 52 - ca 53 - cb etc. .. note:: This is just the base 26 representation of n, where a=0, b=1, ..., z=25. This extends the old Cremona notation (counting f...
afa88dbd202803b8f864ffd6ca624b701a8e631c
637,905
def compose( rf1, rf2 ): """Combines two reduction functions - normally ones which reduce over different axes - into one. Each reduction function should take a single MV as an argument and return a MV. Each should accept an optional keyword argument vid, defaulting to None.""" def rf12( mv, vid=None ):...
3660e4bf1e6fc84d7e713c9efa62fe02bad620d6
637,908
def add(x: int, y: int) -> int: """Add two numbers. >>> add(1, 2) 3 Args: x: An operand. y: An operand. Returns: x + y. """ return x + y
d93e4249d3afcef04821b16bad3d7878ac876d0c
637,909
def all_subclasses(cls): """Recursively find subclasses of a class. The subclasses should already be imported for this function to work properly. Args: cls (type): Class to inspect. Returns: set[type]: The set of subclasses. """ return set(cls.__subclasses__()).union( ...
bbb2ea7bd5ca98db05557886e22065bfa5aa7365
637,911
from pathlib import Path def api_image_file( test_image_path: Path, ) -> dict[str, tuple[str, bytes, str]]: """Return the dict with file needed to use post requests.""" return { "file": ( test_image_path.name, test_image_path.open("rb").read(), "image/png", ...
757542bea990c4ae02f071bcd783186efc6c96aa
637,912
def rolling_apply(df, window, func, shift=1, *args, **kwargs): """Calculate rolling apply() to all columns of a pandas dataframe Function can be used by ApplyFunc module. :param pd.DataFrame df: input pandas dataframe :param int window: size of rolling window. :param func: function to be applied ...
f86aefc605edb252da46c99b3079e659e087063a
637,914
def get_number_base(bitstring, base): """Transfer bitstring to a number in base `base`.""" nr = 0 for place, bit in enumerate(bitstring[::-1]): nr += base**place * int(bit) return nr
1a54f84dd67b245009831258b7e50a28924e7f5b
637,916
def eulers_method(f, y, dx, range): """ The Eulers method for a first order differential equation. :param f: First order differential equation to approximate the solution for. :type f: lambda :param y: The initial condition for the y-value. :type y: float, int :param dx: Step size. Smaller ...
a1b31fb2c842c86c89d8e5b7c52188e4cf00d97e
637,919
def ask_confirmation(action): """ Asks the user for confirmation of action. Parameters ---------- action : str The action to take place if confirmed. Returns ------- str : The action to be executed if confirmed, aborts otherwise. """ confirmation = str(input("P...
707e2ffdbd6c20b4495561c28a19730fac9e8615
637,926
import requests def buscar_avatar(usuario): """ Busca o avatar de um usuário no Github :param usuario: str com o nome de usuário no github :return: str com o link do avatar """ url = f'https://api.github.com/users/{usuario}' resp = requests.get(url) print(resp.status_code) return ...
30efe589ab16d0df83ad250eed88574e04260ec2
637,928
def clear_refills_2016(oven_refill_ends): """ Some of the automatically found refills in 2016 are incorrect and result e.g. from short oven stops. They are cleared out with this function based on manual selection and comparison with CALS. Parameters ---------- oven_refill_ends : list of timesta...
549284be03e6280304847792f7e5ac1d4ce83736
637,937
def _get_precip(sel_cim_data): """Return total precipitation.""" return sel_cim_data.TotalPrecip_tavg
22c19a4cfe377e7555ecb1c1384e934b54128216
637,938
def clean_hypothesis(hyp: str) -> str: """ Remove extra words after the question mark of the generated question Parameters ---------- hyp : str Hypothesis question Returns ------- str the cleaned hypothesis question """ _loc = hyp.find("?") if _loc == -1: #...
d9d8d9b5e8d32bf5325bc2658759bba83292c560
637,942
def calc_gamma(Ti): """Derive gamma from Ti""" return 1.0 / Ti
4d292cd554ca7ebfc70bc4bbe1d992ac3416b6d0
637,948
from functools import reduce import operator def bitor(*args): """ BITOR num1 num2 (BITOR num1 num2 num3 ...) outputs the bitwise OR of its inputs, which must be integers. """ return reduce(operator.or_, args)
f8d3ca6861e2af4d92765efa964ad4d3fedfc94d
637,949
def after_request(response): """Modify response headers including Access-Control-* headers. :param response: An instance of the response object. :return: As instance of the response object with Access-Control-* headers. """ response.headers.add( "Access-Control-Allow-Headers", "Content-Type...
e72de487bbf1bce1209bd653c5b0b8c491afa716
637,950
def drop_empty_rows(rows): """Return `rows` with all empty rows removed.""" return [row for row in rows if any(val.strip() for val in row)]
478270e8a47206da33810f7255c5e12bf4658cc0
637,954
def preprocess(theorem, chromosome): """ convert chromosome to complete Coq script Args: theorem (list): a list of string contains theorem or some pre-provided tactic. chromosome (list): a list of string. Returns: byte: a byte string will be passed to coqtop """...
56582dd43ab13e4ca4ffdbf0471129b8c230666e
637,955
def char_to_word_index(ci, sequence): """ Given a character-level index (offset), return the index of the **word this char is in** """ i = None for i, co in enumerate(sequence.char_offsets): if ci == co: return i elif ci < co: return i - 1 return i
ecdfafd0c301d98d3f600b34022eb2e605a6e1da
637,956
import hashlib def md5(filename): """ Return the MD5 hash of a file. Parameters ---------- filename : str The name of the file to check. Returns ------- str The MD5 hash in hexadecimal. """ with open(filename) as fin: return hashlib.md5(fin.read().enc...
b67d2ee63c82b31d589bdb2ec28047ef70831bb0
637,959
def get_dirs(basedir): """ Configuration of subdirectory names relative to the basedir. """ return { 'templates': basedir + '/templates', # Mako templates 'content': basedir + '/content', # Markdown files 'output': basedir + '/htdocs', 'static': basedir + '/static', ...
a9431de0d0fc30cfb93dd0ff3c677e5ce40cccdb
637,960
def GetTag(client, messages, tag): """Gets a tag by its name.""" get_tag_req = messages.ArtifactregistryProjectsLocationsRepositoriesPackagesTagsGetRequest( name=tag) return client.projects_locations_repositories_packages_tags.Get(get_tag_req)
603e58ae3da88d2ae7e13627c34f81614200e883
637,964
import re def get_max_deltas(filename): """Returns maximum gap parameters for the specified CoMetGeNe result file. :param filename: CoMetGeNe result file :return: tuple representing the gap parameters for genome and metabolic pathway, respectively """ pattern = re.compile("--- delta_G = (...
b090413681f751d4de0db0c9f7eb62748c700e39
637,966
from typing import Iterable def word_join( iterable: Iterable[str], use_repr: bool = False, oxford: bool = False, delimiter: str = ',', connective: str = "and", ) -> str: """ Join the given list of strings in a natural manner, with 'and' to join the last two elements. :param iterable: :param use_repr...
9ffcbe4a42f273db1138d4779dc9d23e9b5658f9
637,968
import torch def evaluate_acc(confidences: torch.Tensor, true_labels: torch.Tensor) -> float: """ Args: confidences (Tensor): a tensor of shape [N, K] of predicted confidences. true_labels (Tensor): a tensor of shape [N,] of ground truth labels. Returns: acc (floa...
12691e29500f9bced16a9b03c4ebc05c81d872af
637,969
def public(endpoint): """Declare an endpoint to be public, i.e., not requiring auth.""" # Store metadata on this function stating that it is unprotected endpoint.is_protected = False return endpoint
a775c79533e790abe01809d70f8ffbc49645ce57
637,971
from typing import Counter from functools import reduce import operator def add_dicts(*args): """ Adds two or more dicts together. Common keys will have their values added. For example:: >>> t1 = {'a':1, 'b':2} >>> t2 = {'b':1, 'c':3} >>> t3 = {'d':4} >>> add_dicts(t1, t...
7f4303d574e123cab80ad5cf84fe59f19980b2c6
637,973
def preprocess_image(image): """Preprocesses an image into the form suitable for machine learning model input. Args: image: The image to preprocess. Returns: The preprocessed image. """ return image / 255.0
c74f5a0b12b3487ff0fca7dd2eafa17ae4b3148a
637,976
def check_static_metrics(expected_metrics, error_message=""): """Create a callable to verify that the static provider response contains the expected values. To be used with the :meth:`run` function. The callable will raise an :class:`AssertionError` if the static metrics in the response are different ...
47ed71eb52f079377be83fe70cb5f2534f480bd3
637,980
import re def replace_strip(text): """ Remove newline, carriage return, tabs from string and split by ',' Parameters ---------- :param text: input text </br> :return: list of words """ data = re.sub(r"[\n\r\t]", "", text.lower()).split(",") data = [item.strip() for item in data] ...
da5317b2310faff2c9a015d32af41473e687a737
637,990
import json import requests def unpack_response(response): """ Fetches the JSON body of a response and returns a tuple composed of the response itself with the decoded JSON. """ try: j = response.json() except json.JSONDecodeError: j = response.text if response.status_code...
53c0fd9afd79d294ab282e46ae9feaecf178992f
637,993
def format_datetime(date_time): """Generate string from datetime object.""" return date_time.strftime("%Y-%m-%d %H:%M:%S")
9123fe7ae7a5d6d08c60c67faa6dd552a20448d5
637,996
def get_download_ranges_list(range_left, range_right, parts): """ function to get a list of ranges to be downloaded by each thread """ l = range(range_left, range_right + 1) dividend, remainder = divmod(len(l), parts) ranges_list = list( l[i * dividend + min(i, remainder) : (i+1) * dividend ...
8a6166773e88b56f673d85fc6a581fc5f401defb
637,997
def read_magnum_cluster_template(client, cluster): """Get the actual template associated with the one specified in the given Magnum cluster resource. Args: client (MagnumV1Client): the Magnum client to use to connect to the Magnum service. cluster (krake.data.openstack.MagnumClu...
6c61c927cee7d5448d4156fa0c2c2f1e02007a1c
637,998
def gen_property_of_type(name, _type, doc=""): """ Generates a type-forced property associated with a name. Provides type checking on the setter (coherence between value to be set and the type specified). @param name: property name @param _type: force type @param doc: documentation for the prop...
e90d83379d01013674d5f21f9ab3cfc036ab080a
638,001
def replace_quotes(match): """Replace match with « xxxxxxx ».""" length = len(match.group(0)) - 4 return "« " + length * "x" + " »"
5c872515db0a0e76d913ff80338bc35bf49ec920
638,003
import secrets def branch() -> str: """Return a branch name that is unique for every test case.""" random = secrets.token_hex(nbytes=3) return f"branch-{random}"
71c1bf62074737cfc41a2caca202f2e9b5dc69c4
638,004
def legendre_polynomial(x: float, n: int) -> float: """Evaluate n-order Legendre polynomial. Args: x: Abscissa to evaluate. n: Polynomial order. Returns: Value of polynomial. """ if n == 0: return 1 elif n == 1: return x else: polynomials = [...
9c1890f54ae0a91b8d4cd8771f7a944fd3f7e7ab
638,006
from typing import List def jaccard_similarity(correct_duplicates: List, retrieved_duplicates: List) -> float: """ Get jaccard similarity for a single query given correct and retrieved file names. Args: correct_duplicates: List of correct duplicates i.e., ground truth) retrieved_duplicate...
1a1d9adf32b43624b29336f8dc8fef025004a659
638,008
def make_cygpath_function(mounts): """Creates a make function that can be used in place of cygpath. Args: mounts: A list of tuples decribing filesystem mounts. Returns: The body of a function implementing cygpath in make as a string. """ # We're building a bunch of nested patsubst ...
68990df9a1fb9df78c13a4456c3882896cc70acc
638,010
def get_item_type(code): """Get item type from code.""" item_type = {0: "Zabbix agent", 1: "SNMPv1 agent", 2: "Zabbix trapper", 3: "simple check", 4: "SNMPv2 agent", 5: "Zabbix internal", 6: "SNMPv3 agent", ...
a4f425bfc29a0512d29d7d3e4b024410c1a481fb
638,011
def sensorsDifferenceSum(sensor_1, sensor_2): """ given two lists contains the reading of two sensors for the same place, give the total difference between there elements """ if len(sensor_1) == 0 or len(sensor_2) == 0: return 0 return abs(sensor_1[0] - sensor_2[0]) + sensorsDifferenceSu...
9ad0da3182528760edb22cf694c94b2d25e66c06
638,013
from typing import List def message_empty(sysex_data: List[int]) -> bool: """Return whether the sysex data is an empty message packet.""" return len(sysex_data) == 2
f17043a8ac49656253837f90d1e78501dbd9ce05
638,015
def mask_string(raw_str, right_padding=4) -> str: """Mask a string with a default value of 4.""" return raw_str[-right_padding:].rjust(len(raw_str), '*')
1a8d130c723f893e2bbaa3392841ce80dd659d30
638,018
def _field_set_recursively(resource, field_name, value): """Set a field for a given resource and all of its children. Args: resource (ResourceData): the resource to change. field_name (str): the field to set. value (str): the value of the field to set to. Returns: list. all...
eb8e489fe47a6cf99d673cbd3f7f7d65260098d6
638,020
def to_list(x): """ Return x if it is already a list, or return a list containing x if x is a scalar. """ if isinstance(x, (list, tuple)): return x # Already a list, so just return it. return [x]
4b1d303dfba85adec9bdee9b3cba6c93b7937543
638,021
def search_for_ISM(edge_IDs, transcript_dict): """ Given a list of edges in a query transcript, determine whether it is an incomplete splice match (ISM) of any transcript in the dict. Will also return FSM matches if they're there""" edges = frozenset(edge_IDs) ISM_matches = ...
87b40a7e97fd39a8833cbae33eaa392fb666ffec
638,023
def format_timeout(timeout): """Render server alive interval option.""" format_str = '-o ServerAliveInterval={}'.format return format_str(timeout) if timeout else ''
750c923cd08bad5d4e71d5c5d9a610f44f81213f
638,025
def transposed(matrix): """Returns the transpose of the given matrix.""" return [list(r) for r in zip(*matrix)]
30835a1583f365b558c39e8fd1b459e79e85448e
638,027
def word_len(word): """Returns the length of word not counting spaces >>> word_len("a la carte") 8 >>> word_len("hello") 5 >>> word_len('') 0 >>> word_len("coup d'etat") 10 """ num = len(word) for i in range(len(word)): if word[i] == " ": num = num-1 ...
c51a98e173b92a4efcd18d640de00d8015036c73
638,028
def pick_n_equispaced(l, n): """Picks out n points out of list, at roughly equal intervals.""" assert len(l) >= n r = (len(l) - n)/float(n) result = [] pos = r while pos < len(l): result.append(l[int(pos)]) pos += 1+r return result
2866786a994817d529e8a255d06614bd92f3e839
638,031