content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Iterable def is_collection_like(c): """ Determine whether an object is collection-like. :param object c: Object to test as collection :return bool: Whether the argument is a (non-string) collection """ return isinstance(c, Iterable) and not isinstance(c, str)
f6d1a916870fd03dc3e01b5ba3f4ff94a125f9b5
572,099
def q_to_phred33(Q): """ Turn Phred-scaled integer into Phred+33 ASCII-encoded quality """ return chr(Q + 33)
e0752e6917dde7e11264f7a3eab5ff07bc60f032
572,100
import torch def svm_loss(x, y): """ Computes the loss and gradient using for multiclass SVM classification. Inputs: - x: Input data, of shape (N, C) where x[i, j] is the score for the jth class for the ith input. - y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and 0 <= y[i] < ...
5f36dc353c4f6e26b7ae89e5996018ae0f5effb3
572,105
def non_qualified_code(code): """ Some codes, e.g. ISO 3166-2 subdivision codes, are compound and are formatted as "{country_code}-{subdivision_code}". For validation cases we often care about extracting the non-qualified subdivision code in such cases. """ return code.split("-", 2)[1]
aa5f6363349e11e1a3307be7bb6ed724d636883a
572,108
def rect_sum(rect: list[list[int]], x1: int, y1: int, x2: int, y2: int) -> int: """Calculates sum of pixels of a rectangle within given borders Args: rect (list[list[int]]): matrix of integers x1 (int): top left border X coordinate y1 (int): top left border Y coordinate x2 (int):...
0ee770a2ce72c44b137416ea7dbec140dfb1bd2b
572,113
def fmt_numeric(value: float, precision=10) -> str: """Format any numeric value. Args: value: The numeric value to format. precision: The numeric precision Returns: The numeric value with the given precision. """ return "{{:.{precision}g}}".format(precision=precision).forma...
6def7729b4ae8907ee9d610768025163bf9546d0
572,115
import uuid def get_str_uuid() -> str: """Returns UUID as string""" return str(uuid.uuid4())
9dc15c0652131cf636a6a2074e2050c968a274f0
572,119
import torch def task_loss(target, output, criterion, weights): """ Compute the loss per task / label. :param target: target labels :param output: predicted labels :param criterion: loss criterion :param weights: the weight per task / label :return: the computed loss """ loss = to...
328bdfbca955d6218735f3220c95809a72bab215
572,120
import torch def gradient_penalty(y, x, device): """Compute gradient penalty: (L2_norm(dy/dx) - 1)**2.""" weight = torch.ones(y.size()).to(device) dydx = torch.autograd.grad(outputs=y, inputs=x, grad_outputs=weight, ...
f40b358051627342547ff8b8b7c42004bed8c3f2
572,121
def count_lines_in_file(file_path: str, buffer_size: int = 1024 * 1024) -> int: """Count the number of lines in the given file. :param file_path: path to the file :param buffer_size: size of temporary buffer during reading the file :return: number of lines """ n_lines = 0 with open(file_pat...
2b3dd1180922b923997a57ff166f8f084d4caebc
572,122
def recursive_get(data, keys, _top=True): """ Recursively slice a nested dictionary by a list of keys. Parameters: data (dict): nested dictionary to get from. keys (list): list of keys/indices to delve into. Raises: KeyError: if any in chain keys are missing, IndexError...
23b8f6994d804c9687685d294d97276c310ab4f4
572,124
def testDegrees(g1, g2): """ Check if the graphs have the same number of vertices of different degrees. :param g1: The first graph. :param g2: The second graph. :return: True if both graphs have the same number of vertices of different degrees. False, otherwise. """ degreesG1 = [0] * len(g1....
a14c2c1d52ac5f8f0cf3ef8bf5efeb4b411b78e7
572,125
def read_html_file(filePath): """Open a html file being encoded utf-8 or ANSI. Return a tuple: [0] = Message beginning with SUCCESS or ERROR. [1] = The file content in a single string. """ try: with open(filePath, 'r', encoding='utf-8') as f: text = (f.read()) except: ...
75c32e962e43fba87e929797d57312c28f6c532e
572,126
def lininterpol(first,second,x): """Perform linear interpolation for x between first and second. Parameters: 1. first: [x1, y1], where x1 is the first x value and y1 is its y value 2. second: [x2, y2], where x2 is the second x value and y2 is its y value 3. x: the x value whose y value will be ...
a896d81c4631eeb185229be18cf5952ba7c2b097
572,127
def job_specifications(config): # type: (dict) -> dict """Get job specifications config block :param dict config: configuration object :rtype: dict :return: job specifications """ return config['job_specifications']
7caecdf17547dcb32508c98ab25dd99b866de937
572,129
def is_prime(n: int) -> bool: """ Checks if a number n is prime :param n: Integer number to test :return: Boolean value - True if n is prime, else False """ if n < 2: return False i: int = 2 while i * i <= n: if n % i == 0: return False i += 1 r...
d9aa77fe74bf9069fd434cbbe06765ac33c5db7a
572,134
def _parse_table(value): """ Parses a textual table that the console commands generate. Each row is converted into a dictionary. """ lines = value.split('\n') header = None rows = [] for l in lines: if l.startswith('+-'): pass elif l.startswith('|'): ...
b2cf5fe86665fe2a873d8ae0aa6f4403192d4a4a
572,137
def filter_blackwhitelist(l, key): """ Filter black/whitelist for the keys that belong to the subdirectory which is embedded into the nested dictionary structure with the given key. Three different cases: - if l is None, then return none - if key is None, then we are at the top-level dictio...
d9edbf5b95d1baa5d741aa55173f032132c96ea0
572,144
import math def safe_exp(value): """Exponentiation with catching of overflow error.""" try: ans = math.exp(value) except OverflowError: ans = float("inf") return ans
8a809a2502adcf47078fc284aa3026f0f48d87e5
572,146
def order_salaries(df): """Turn salary range into ordered variable.""" df = df.copy() cats = ['< 10k', '10k to 20k', '20k to 30k', '30k to 40k', '40k to 50k', '50k to 60k', '60k to 70k', '70k to 80k', '> 80k'] df['salary_range'] = (df.salary_range.cat .s...
36e0f39ed3ff7aa67e433e55952de268f686955f
572,151
def constrain_to_number_events(all_data, minimum_event_count): """Remove trials with too few events. :param all_data: The output of :func:`make_data_preds`; or data conforming to this dictionary style. :param minimum_event_count: The minimum number of events we want in a trial. :retu...
44b801e2c3c0f5262a55b8f8796088b8ff044af5
572,152
def string_replacer(line): """Take string literals like 'hello' and replace them with empty string literals, while respecting escaping.""" r = [] in_quote = None escapes = 0 for i, c in enumerate(line): if in_quote: if not escapes and c == in_quote: in_quote = No...
072c672cfe2c22edeca5f52685cf402bac4d09fa
572,154
from typing import Optional def diff_index(iterable1, iterable2) -> Optional[int]: """Return the index where iterable2 is different from iterable1.""" return next((index for index, (item1, item2) in enumerate(zip(iterable1, iterable2)) if item1 != item2), None)
da37f7a96a3ab34e5169ae67d4c26c418a85c497
572,155
import re def get_instances_from_report(report_file_path): """ Parse StegExpose report and return a list of (class, score). E.g. [('p', 0.10), ('n', 0.05)] """ instances = [] with open(report_file_path, 'r') as report_file: for line in report_file: # Filter the lines witho...
dc5bbf747aa642456ec3080e2ca93a0f6a3086e1
572,160
import warnings def check_warnings(usage, options): """ Function for testing whether the docstring contains a usage part and a options part. Args: usage: a string the retrieve from the docstring. options: a string that retrieve from the docstring. Returns: returns 1 if no usage pat...
ba3aec254c80c65c27ad3c2615285017c5e8c6e5
572,164
def _get_image_url(host, port, mode): """Set the URL to get the image.""" if mode == 'mjpeg': return 'http://{}:{}/axis-cgi/mjpg/video.cgi'.format(host, port) if mode == 'single': return 'http://{}:{}/axis-cgi/jpg/image.cgi'.format(host, port)
963d0043b0c677594d54fa1d04a8307299e2b227
572,165
def combineHv(x1, x2): """ Combine/Reduce function for the mappers Parameters ---------- x1 : list element1 x2 : list element2 Returns ------- tuple ``(x1[0]+x2[0], x1[1]+x2[1])`` """ return (x1[0]+x2[0], x1[1]+x2[1])
8b0fd37e283981e3d46855b2c2e92b4d67b8a701
572,166
def keep_rows_by_multi_index(df, multi_index_name, multi_index_value): """Keeps rows with given multi-index values from a DataFrame. Args: df: DataFrame with samples as rows and multi-indices. multi_index_name: String, the name of the multi-index. multi_index_value: String or a list of strings, the val...
46c5398fe7a2bd36ecca56cb55f092da0e73ee78
572,168
def std_average(four_month_std): """ A function that computes the std specific average. This is just the average :param: four_month_std A series with the historical % change std :return: float The average """ return four_month_std.mean()
ae76aa1ef8400595c72a7e58e2e883f0fde2a7be
572,169
def invert(f): """ Simple function call: invert(val) """ return 1.0 - f
47b47c57f07cdadcc112b57ce22feae7e13d9d18
572,170
import re def _remove_Abbrev(line: str) -> str: """ Remove abbreviation #.#.#. #.#. #. (e.g. U.S., U.S.A., ...). Abbreviations often cause problems when separating sentences. """ line = re.subn(r'\s\w\.\w\.\w\.\s', ' ', line)[0] line = re.subn(r'\s\w\.\w\.\s', ' ', line)[0] line = re.subn...
9b1f2381345642cdb8068ebb71df0ee793bfa04b
572,171
def lowest_common_ancestor(go_tree, term1, term2): """ Find the lowest common ancestor (LCS) of all paths in the GO DAG. :param go_tree: :param term1: :param term2: :return: List of LCS's found on each possible path. """ go_term1 = go_tree[term1] go_term2 = go_tree[term2] if go...
d62f2582b191e1bfee8c4e11cb7ab0e3ab7b47c7
572,172
def bayesdb_population_table(bdb, population_id): """Return the name of table of the population with id `id`.""" sql = 'SELECT tabname FROM bayesdb_population WHERE id = ?' cursor = bdb.sql_execute(sql, (population_id,)) try: row = cursor.next() except StopIteration: raise ValueError...
87f3432084a9537272c087995bcaf4f36bc8225c
572,173
def fetch_counter(cursor, category): """ Get the coutner value for the provided category from the database counter table """ cursor.execute("SELECT * FROM counters WHERE category == '%s'" % (category)) counter = cursor.fetchone()['count'] return counter
81d2355396671faeca7c2c04b08a97be68185cd9
572,183
def get_api_fqdn(gitlab_repo): """ Determine if the provided GitLab repo object refers to a hosted GitLab instance or to publically hosted gitlab.com, and indicate what base FQDN to use for API requests. """ if gitlab_repo.fqdn[-10:] == "gitlab.com": return False, "api.gitlab.com" re...
beec41bf36fb3d908c40d5f708ee6c761f9590fb
572,187
def _get_rest_service_wadl_url(rest_service_base_url: str) -> str: """ Return the URL to the WADL of BAM's REST service. :param rest_service_base_url: Base URL of BAM's REST service. :type rest_service_base_url: str :return: The URL to the WADL of BAM's REST service. :rtype: str """ ret...
03ad5c9a0c39c7ed53dd14f8f8916035b1f2d4d1
572,190
def create_hr_context_output(result: list) -> list: """ For creating context and human readable :param result: list of raw data :return: list """ hr_context_output_list = [] for result_row in result: hr_context_output_list.append({ 'Id': result_row.get('Id', ''), ...
b15186e3d72330e0891e0f59ea2c6f6b70ebe77b
572,193
def mean(curr_avg: float, n: int, new_value: float) -> float: """ Updates an average value using the real time streaming algorithm which uses constant space for calculations and doesn't overflow a sum counter. Gives the exact value not an approximation. NB: Value of curr_avg doesn't matter for firs...
3a29802caa23f80d305bfa46e0227c457865d849
572,198
def dbextfile(db, tablename = None): """Compose filename from database record for a given table""" return db.extfile(tablename)
e19f556dba77955136e825d83023c3abf34a2258
572,199
import hashlib def pwd_hash(plain: str, salt: str) -> str: """Generate a hash for a password using SHA3-512.""" return hashlib.sha3_512(f'{plain}{salt}'.encode()).hexdigest()
0cd2c343d4b2126d296876eb8c95c2c818e2c00f
572,202
def get_object(model, session, *args, **kwargs): """ Use get() to return an object, return None if object does not exist. """ try: model_object = session.query(model).filter(*args, **kwargs).first() return model_object except Exception as e: return None
c717781a04a5401e883860458bd309c61ad2e3a8
572,207
def truly_relativize(target, relative_to): """Return a relative path to `target` from `relative_to`. Args: target: string, path to directory we want to get relative path to. relative_to: string, path to directory from which we are starting. Returns: string: relative path to `target`. ...
92ddee0befb4bc4c52ca6352259dc1718628893d
572,208
def _list_tool_categories(tl): """ Given a list of dicts `tl` as returned by the `parse_tool_list` method and where each list element holds a key `tool_panel_section_id`, return a list of unique section IDs. """ category_list = [] for t in tl: category_list.append(t.get('tool_panel_s...
bfbb5325108fe9fef895edd74761521b729ec965
572,209
def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name
6bb3a8b6a76014a5b10d20e120121255601c01f9
572,215
def read_chain_file(chain_file): """Read chain file. Create dict chain_id: (start, end).""" ret = {} f = open(chain_file, "r") for line in f: if not line.startswith("chain"): continue line_data = line.rstrip().split() start = int(line_data[5]) end = int(l...
12108dc2593ab46041b8034d13096d35a87d988f
572,217
import re def _SubstituteErrorParams(fmt, params): """Replaces $N with the Nth param in fmt. Args: fmt: A format string which may contain substitutions of the form $N, where N is any decimal integer between 0 and len(params) - 1. params: A set of parameters to substitute in place of the $N string. ...
18c252fcf182d964e632252fb0c3a025c5ce6263
572,222
def clean_spaces(m): """Replace unencoded spaces in string. :param str m: a match object :return: the cleaned string """ return m.group(0).replace(" ", "=20")
38987388f2d0b3465dd0188264c8b065bf57bfc6
572,226
def nearest_point_on_line(point, line): """Return the nearest point on a line """ return line.interpolate(line.project(point))
e100855ea775c43d54bc9e4256c9757386444ee6
572,228
def list_startswith(lst, prefix): """ Check whether `lst` starts with the given `prefix` list. """ return len(prefix) <= len(lst) and all(a == b for a, b in zip(lst, prefix))
8a82b1d5ad06995e123885871547d6cafb98562a
572,229
def read_input_to_list(path): """ read inputfile from path and return list of ints """ with open(path) as file: return [int(x) for x in file.readlines()]
22e8da700c4beb9f4c6c481197a085c1dfb83663
572,230
def create_matrix(nr_rows, nr_cols): """ Create a 2d list of size """ matrix = [[0 for i in range(nr_cols)] for j in range(nr_rows)] return matrix
cb1f2525a64e8b3f3265157e76a4d2e51501a7d6
572,234
def assertEqualWithComparator(comparator): """ Fail a little less cryptically that unittest.assertTrue when comparing a result against a target value. Shows the result and the target in the failure message. """ def decoratedComparator(self, result, check, errMsg=None, **kwargs): errMsg ...
4d6e48fa910a60fa9a56ad8892b3714bf44493d8
572,239
def all_relevant_registers_filled(registers, relevant_registers) : """ @param registers : a dictionary of each register content { 'register #': 'value' } @param relevant_registers : an ordered list of register indexes related to that method call @rtype : True if all the relevant_registers are fille...
cba6d33b168749dd989bcf850f4cbcde01e43b3f
572,240
import pytz def convert_timezone(obj, timezone): """Convert `obj` to the timezone `timezone`. Parameters ---------- obj : datetime.date or datetime.datetime Returns ------- type(obj) """ if timezone is None: return obj.replace(tzinfo=None) return pytz.timezone(timezon...
aa6f2d2616a560bc55f6666955d33a295121ac57
572,241
def generate_sa_sizes_cmd(sa_sizes): """ Generate the command line argument to specify the sa_sizes. Concatenate each size in the sa_sizes to generate the final argument. Parameters ---------- sa_sizes: list A list containing the sizes for each optimization stage. """ length = len(...
9fecf6c49f593afdf3940cf96939e7cd146959c0
572,242
def convert_to_type(input_value, new_type, input_value_name=None): """ Attempts to convert input_value to type new_type and throws error if it can't. If input_value is None, None is returned If new_type is None, input_value is returned unchanged :param input_value: Value to be converted :param ...
be9abf676d346970c1c96f755ba805062d094ce1
572,250
import gzip def zopen(fname, mode): """Opens a file with gzip if it ends on '.gz', otherwise normal. Args: fname: Name of the file to open. mode: File operation mode string. Returns: File like object. """ if fname.endswith(".gz"): return gzip.open(fname, mode) ...
4b761d89283d535aae3f15d1444f8c3713041bd8
572,253
import torch def evaluate_ece(confidences: torch.Tensor, true_labels: torch.Tensor, n_bins: int = 15) -> float: """ Args: confidences (Tensor): a tensor of shape [N, K] of predicted confidences. true_labels (Tensor): a tensor of shape [N,] of ground truth labe...
052ca3804019bd319ec9c6b7451c088aa47e9f62
572,257
def archimedes(dp, rhog, rhos, mu): """ Calculate the dimensionless Archimedes number. .. math:: Ar = \\frac{dp^3 \\rho_g (\\rho_s - \\rho_g) g}{\\mu^2} Parameters ---------- dp : float Particle diameter [m] rhog : float Gas density [kg/m³] rhos : float Solid de...
6ab7a9eaa4110af00e5340e18f39ca7143d3f58f
572,262
import typing def get_ctffind_4_1_0_extract_dict() -> typing.Dict[str, str]: """ Returns the extraction dict for the ctffind4 meta information. Arguments: None Returns: Dictionary with key as key and regular expression as value. """ return { 'version': r'.*CTFFind version ([^...
8ff71e2b98bc2227bf9624a023ff29912a795636
572,263
def finished(json_data, table): """Gets all the finished tournaments from the JSON data and shows the following: - name of the the tournament - variant of the tournament - winner of the tournament - Number of the palyers in the tournament """ finished_tournaments = json_data[...
6d5a332ac42ab9257e5fad5a51ebfe694bb9ff75
572,266
def get_macro_mol_sel(pdb_processed_file,selection='protein or dna or rna'): """ Get macro molecule selection from a PBD interpretation object, for non bonded overlaps calculation Args: pdb_processed_file : Object result from pdb_interpretation of a file selection (str): By default a string to select t...
e7dcaba66771d17d82418b5a2e1bef385cebdc65
572,270
import stripe def get_supported_currency_choices(api_key): """ Pull a stripe account's supported currencies and returns a choices tuple of those supported currencies. :param api_key: The api key associated with the account from which to pull data. :type api_key: str """ stripe.api_key = ...
c823e6c81292f138454b4851693524e6e4ad7fa4
572,272
from typing import Dict import json def str_to_dict(s: str) -> Dict: """ Load dict from string. """ return json.loads(s)
9140c002b0fc10b92cf6b52912d6820327827a6a
572,274
def base2p15_decode(base2p15: str) -> str: """ Encode/decode given base2p15 string as binary string :param base2p15: A base2p15 string, generated by base2p15_encode :type base2p15: str :returns: A binary string e.g. 00001001 :rtype: str """ bit_string = "" offset = 0xa1 padding ...
38a88b5551fbee775c3b945c340f18b25a18cb37
572,276
def func(f, xmin, xmax, step = None): """Create sample points from function <f>, which must be a single-parameter function that returns a number (e.g., math.sin). Parameters <xmin> and <xmax> specify the first and last X values, and <step> specifies the sampling interval. >>> chart_data.func(math.sin, ...
6422af2f85286411728169cc77a4b781429b9061
572,281
def get_subseq(s, op): """Returns the subsequent sequence of applying (op) on the sequence 's', in such a way that 'new[i] = old[i+1] (op) old[i]'. For example: op = lambda a, b: b - a → then a difference sequence is returned: new[i] = old[i+1] - old[i] ...
d93990bb2094d63f0e38c7c7f861b6505ddfe258
572,282
def model_chunk(chunk, x, params, possible, run_doc): """ Runs input through a model chunk (function) :param chunk: (string) name of model chunk :param x: input tensor :param params: {dict} hyperparams (sub-selection) :param possible: {dict} local function names :param run_doc: {Ordered dict...
fd1bb15f53cd4bb7c57a19318249eaf875e7e81c
572,285
def build_cache_key(**arguments) -> str: """ Создаёт строковый ключ кэша из всех строк ключей и значений словаря >>> build_cache_key(arg1='value1', arg2='value2') 'arg1;value1;arg2;value2' >>> build_cache_key(user=User('vasya man'), scope=Organization('Org1')) 'scope;Организация:_Org1;user;vas...
62796953a3498a812b44467f94c81e326a7b8260
572,289
def filter_only(keep_list, filter_list): """Filter out items in an iterable not in the keep_list. :param keep_list: list of key names to keep. :type: list of str :param filter_list: iterable to filter. :type: list or dict """ return list( filter( lambda key: key in keep_...
f683eb328f663bd6b30cdc3d0e7b8b542bd5e73a
572,290
from typing import Optional from datetime import datetime def date_to_day_of_week(date: Optional[str] = None) -> int: """ Convert a date into day of week :param date: Optional. If not passed in, then current day is used. :return: Day of the week starting with [0=Monday, 6=Sunday] """ if date i...
156689667bf76b0894a4ca2ef81aa33f26d481fa
572,292
import requests def get(url: str, **kwargs) -> requests.Response: """Sends a GET request to the given `url`.""" resp = requests.get(url, **kwargs) resp.raise_for_status() return resp
0ce21c08dfd33322bbc46e910249d183aaf12974
572,295
import re def strip_extra_whitespace(text): """ Remove extra whitespace from text Args: text: string to strip extra whitespace from Returns: str: text without extra whitespace """ return re.sub(r"[\s]{2,}", " ", text).strip()
94149027cd29a7180ac8c45de54ef4901e3ca652
572,297
def check_cloud(path: str): """Naive check to if the path is a cloud path""" if path.startswith("s3:"): return True return False
f622fd3b479a2bca7e2ed405c861a5ae528b65a8
572,298
def grant_role(role, target): """Helper method to construct SQL: grant privilege.""" return f"GRANT {role} to {target};"
928acdcfa7ea6f28d09714ee3a91e4507c59dfb0
572,301
def classpath_entry_xml(kind, path): """Generates an eclipse xml classpath entry. Args: kind: Kind of classpath entry. Example values are 'lib', 'src', and 'con' path: Absolute or relative path to the referenced resource. Paths that are not absolute are relative to the p...
5b350d2e2dc75f96348ba83fed739a83ac144053
572,302
def my_sum(a: float, b: float) -> float: """Sum of two floats Parameters ---------- a : float First value to sum b : float Second value to sum Returns ------- float The sum of ``a`` and ``b`` See also -------- MyClass Example ------- >>...
61584b150deba81a9005aaf874005ad550e1b377
572,306
import torch def sample_gumbel(shape, eps=1e-10): """ NOTE: Stolen from https://github.com/pytorch/pytorch/pull/3341/commits/327fcfed4c44c62b208f750058d14d4dc1b9a9d3 Sample from Gumbel(0, 1) based on https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categor...
aef89f95c7324f30c57737ba69f50cb0e0cd4755
572,307
def to_bytestring (s): """Convert the given unicode string to a bytestring, using the standard encoding, unless it's already a bytestring""" if s: if isinstance(s, str): return s else: return s.encode('utf-8')
26be74aac5ef8d18ce512e535b2acfe633577548
572,313
from typing import Any from typing import Tuple from typing import Union def _resolve_optional(type_: Any) -> Tuple[bool, Any]: """Check whether `type_` is equivalent to `typing.Optional[T]` for some T.""" if getattr(type_, "__origin__", None) is Union: args = type_.__args__ if len(args) == 2 ...
ddb0e198862944d757357ee3fc92f3577fb42875
572,314
import itertools def get_combinations_from_dict(attr): """Generates combinations from a dictionary containing lists Input: attr = {"latency": [1,2,3], "reliability": [99.99, 99.9] } Output: attribute_name: ["latency", "reliability"] attribute_combin...
90f47725ffd7f4ba5a591f44277df71e42fbad50
572,317
def keyword(name=None): """Decorator to set custom keyword names to functions and methods. This decorator creates the ``robot_name`` attribute on the decorated keyword method or function. Robot Framework checks for this attribute when determining the keyword's name. library.py:: @keyword...
c6362611589a584bbb720693e54a969a863d43f0
572,320
def proc_to_str(val, entry): """Process a value to string""" return str(val)
04c01556c1f6673f3935b9880a7eb4e6839badb6
572,322
def solution(A): # O(N) """ Given an array of integers find the only unique value in an array of pairs >>> solution([3, 2, 3, 2, 5, 4, 4]) 5 >>> solution([3, 2, 3, 2, 5, 4, 3, 4, 8, 5, 3]) 8 >>> solution([3, 2, 3, 2, 5, 4, 4, 5]) """ ...
05b5db9e80680a13964955c50e4021a69a47f012
572,323
def _is_dynamodb_critical_exception(err): """Return true for botocore exceptions due to exceeded througput.""" error_code = getattr(err, "response", {}).get("Error", {}).get("Code") return error_code in {"ProvisionedThroughputExceededException", "UnrecognizedClientException"}
323c509cf3e748c5e46c6b2571ce0ddf3eae4408
572,326
def split_by_content_type(list_of_files, supported_extensions): """Split the files into a dict by type.""" d = {} for file_type in supported_extensions: d[file_type] = [f for f in list_of_files if file_type in f] return d
6d67f5cb889bb2fd3f185bd008a3e4456cdfc060
572,327
import six def is_str(val): """Returns True/False whether the given value is a string.""" return isinstance(val, six.string_types)
c3561f9e76750626573a974dc0a6a5a56918629e
572,329
import random def change_case(char): """Randomly return the lower or uppercase verion of the inputted char""" return char.upper() if random.choice([0,1]) else char.lower()
5df4fe2af3dce61deb01f2d23958bb970d8d3115
572,330
def find_difference_list(list1: list, list2: list) -> list: """This function takes as input two lists and returns the difference list between them Args: list1 (list): first list list2 (list): second list Returns: difference_list (list): list containing the difference elements between...
74da273f4beaaa4eaea49556996359412281b385
572,331
def process_ciphers(results, service): """Process Ciphers Args: results (Element): XML results from firewall service (str): A string containing either mgmt or ha for ciphers Returns: set_ciphers_list (list): A list of ciphers already set on the firewall """ set_ciphers_list...
d87e4383b4be06e5536ebdd2f1584d04e65cae2a
572,337
import json from collections import defaultdict def no_duplicates(file, attribute="Name"): """Assert whether or not dict has duplicated Names. `attribute` can be another attribute name like "$id". Args: file (str or dict): Path of the json file or dict containing umi objects groups attri...
5754347be89f9f254f6716fda771fd2c2d06f1c5
572,338
def side_of_line(l, p): """Returns on which side of line `l` point `p` lies. Line `l` must be a tuple of two tuples, which are the start and end point of the line. Point `p` is a single tuple. Returned value is negative, 0, or positive when the point is right, collinear, or left from the line, res...
c3cdf2bcf5f4bb083b884e69e8209375831b4f6e
572,339
def extract_people_sequence(mocap_data): """ Extract all of the matrices for each frame per person. Extracting this information will make it possible to simple loop the frames and create the mocap data for one person. :param dict mocap_data: :return: People data :rtype: dict """ peo...
afb64b74fad6a807d194a16779d409f24ac88f09
572,342
from typing import Optional def create_resource_entry(resource: dict, full_url: str) -> Optional[dict]: """ Create bundle entry that contains a *resource* and a *full_url*. """ if not resource: return None return ({ "resource": resource, "fullUrl": full_url })
1fda640eb04b1acb6b045b296038c988bd2b4727
572,350
def convert_rgb_to_y(img, dim_order='hwc'): """ Get Y(CbCr) value from RGB image (standard conversion) :param img: input image array in RGB form :return: array of Y values """ if dim_order == 'hwc': return 16. + (64.738 * img[..., 0] + 129.057 * img[..., 1] + 25.064 * img[..., 2]) / 256. ...
963b67244c4e14e171f10b5df021572372c48aef
572,353
def position_to_lane(container_position: str) -> int: """ Converts a container position string (e.g. A01, A02, etc.) to a lane index. A01 => Lane 1 A02 => Lane 2 **Assumes there is only one row in positions; A01 and B01 both convert to Lane 1** :param container_position: OvDx container positi...
d7b9f50e27d6bff436e94ce2f4b48d42423ae954
572,355
def read_compromised_relays_file(in_file): """Parse file containing compromised relays.""" compromised_relays = [] with open(in_file) as f: for line in f: line = line.strip() if (line[0] == '#'): continue compromised_relays.append(line) return ...
3217daab8e44a40860a9a8a91140a3fb0cf1e19e
572,360
def _is_init_account(txinfo): """ Returns True if all log_instructions are "InitializeAccount" """ log_instructions = txinfo.log_instructions if len(log_instructions) == 0: return False for log_instruction in log_instructions: if log_instruction != "InitializeAccount": retur...
b6e578835b9b4ea4e702fbdb20060a7555f0b919
572,363
def calculateInterpolatedAveragePrecision( recalls, precisions ): """ Calculates interpolated average precision according to PASCAL VOC competition. :param recalls list of all recalls, sorted ascendingly :param precisions list of all precisions, with order matching corresponding recall val...
a6898b1a13a765b21b986b9406a687c2d5d26b67
572,366
from typing import Tuple from typing import List def get_elec_hyperparams() -> Tuple[ int, int, int, int, Tuple[int, ...], Tuple[int, ...], List[Tuple[int, ...]], ]: """Get hyperparameters for electron data.""" nchains = 25 nelec_total = 7 nion = 3 d = 3 permutation...
b157778ab65aeb068e07870cc02f6f02d9d8f8bf
572,367