content
stringlengths
42
6.51k
def speed_for_human(speed): """ Returns a string showing human readable speeds given in Mbps. """ if not speed: return "" elif speed >= 1000000 and speed % 1000000 == 0: return f"{int(speed / 1000000)} Tbps" elif speed >= 1000 and speed % 1000 == 0: return f"{int(speed / ...
def filter_by_energy_structure(record): """ Include only records that have an 'energyratestructure' field defined. True: filter out False: keep :param record: :return: """ if "energyratestructure" not in record.keys(): return True else: return False
def get_consecutive_num(arr): """ Method to get indices of second number in a pair of consecutive numbers Note: solve_90f3ed37 uses this function """ rows = [] for i in range(len(arr) - 1): if (arr[i] + 1) == arr[i + 1]: rows.append(arr[i + 1]) return rows
def update_config_from_override(default_config_dict, override_config_dict): """ Update a given dictionary values with settings on other dictionary. Used to override the configuration """ for k in iter(default_config_dict): if k in override_config_dict: default_config_dict[k] = ov...
def normalize_case(string: str) -> str: """ Converts a string to lower case. Todo: Follow Python 2.5 / Dropbox conventions. :param string: Original string. :returns: Lowercase string. """ return string.lower()
def gen_query_string(params): """Generate a query string from the parameter dict.""" return '&'.join('{}={}'.format(k, v) for k, v in params.items())
def swap(number, i1, i2): """ Swap given bits from number. :param number: A number :type number: int :param i1: Bit index :type i1: int :param i2: Bit index :type i2: int :return: A number with given bits swapped. :rtype: int >>> swap(0b101011, 1, 4) == 0b111001 True ...
def scale_factor(z: float) -> float: """Scale factor from redshift. Parameters ---------- z : float Redshift. Returns ------- a : float Scale factor. """ return 1 / (1 + z)
def get_config_env_key(k: str) -> str: """ Returns a scrubbed environment variable key, PULUMI_CONFIG_<k>, that can be used for setting explicit variables. This is unlike PULUMI_CONFIG which is just a JSON-serialized bag. """ env_key = "" for c in k: if c == "_" or "A" <= c <= "Z" or "0...
def sjoin(iterable, sep=' ', tpl='%s'): """Cast each item to a string using `tpl` template, then join into a single string.""" return sep.join( [tpl % str(x) for x in iterable] )
def num_colors(x): """x is the fraction of the total players who are on a single team""" return int(round(1.0 / x))
def celsius_to_fahr(degrees_celsius: float) -> float: """Convert degrees celsius to degrees fahrenheit""" return (degrees_celsius * 9.0 / 5.0) + 32.0
def norm2(score, size1, size2): """ Normalization similar to norm2 in Pelta et al 2008 (from Xie & Sahinidis 2006) for MAX-CMO. norm1(struct1,struct2) = 2*tabmatch_score(struct1,struct2) / (#sses(struct1) + #sses(struct2)) Parameters: score - tableau match ...
def expected_output_test(tests, verbose=True): """ Runs tests, check the expected output and list the failures. Prints things in the console if put in verbose mode. Args: tests (list[(expected_output, function_to_call, *args)]): The list of tests to run in the form of a list of tupl...
def _get_ids_for_cameras(cameras): """Get list of camera IDs from cameras""" return list(map(lambda camera: camera.id, cameras))
def contain_unknown_chars(s: str, chars: str): """ >>> contain_unknown_chars("hogehoge", chars="hoge") False >>> contain_unknown_chars("hogehoge", chars="hog") True """ return len(set(s) - set(chars)) > 0
def stroffset(offset): """Represent a timezone offset into a string. Args: offset: A signed integer representing the offset in seconds. Returns: A string with the offset, with sign (+/-) and hours:minutes (e.g. +00:00). """ sign = '+' if offset >= 0 else '-' hours = abs(offset)/3600 minutes = ab...
def smoothed_estimate(n_x: int, N: int, d: int) -> float: """Estimates with 1-Laplace smoothing the probability of a category from a multinomial distribution. Args: n_x (int): The count of some outcome "x" among ``N`` trials. SHOULD be non-negative. SHOULD be no ...
def set_default_value(parameters, label, default_value=None, data_type="float"): """ Convert a default value from string, otherwise specify one. """ new_parameters = parameters.copy() data_types = { "float" : float, "int" : int} if label not in new_parameters: #...
def xgcd(a,b): """xgcd(a,b) returns a tuple of form (g,x,y), where g is gcd(a,b) and x,y satisfy the equation g = ax + by.""" a1=1; b1=0; a2=0; b2=1; aneg=1; bneg=1 if(a < 0): a = -a; aneg=-1 if(b < 0): b = -b; bneg=-1 while (1): quot = -(a // b) a = a % b a1 = a1 + quot*a2; b1 = b1 + quot*b2 if(a == ...
def _set_to_routes(route_set): """The reverse of _routes_to_set. _set_to_routes(_routes_to_set(routes)) == routes """ return [dict(r) for r in route_set]
def _VersionList(release): """Parse a version string into a list of ints. Args: release: The 'release' version, e.g. '1.2.4'. (Due to YAML parsing this may also be an int or float.) Returns: A list of ints corresponding to the parts of the version string between periods. Example: '1.2...
def arguments_to_list(args): """Convert a dictionary of command-line arguments to a list. :param args: command-line arguments :type args: dictionary :return: list of command-line arguments :rtype: list """ arguments = [] for key, value in args.items(): arguments.append(key) ...
def sum_digits(n): """Calculate the sum of digits. Parameters: n (int): Number. Returns: int: Sum of digitis of n. Examples: >>> sum_digits(42) 6 """ s = 0 while n: s += n % 10 n //= 10 return s
def iswritable(f): """ Returns True if the file-like object can be written to. This is a common- sense approximation of io.IOBase.writable. """ if hasattr(f, 'writable'): return f.writable() if hasattr(f, 'closed') and f.closed: # This mimics the behavior of io.IOBase.writable...
def good_suffix_mismatch(i, big_l_prime, small_l_prime): """ Given a mismatch at offset i, and given L/L' and l' arrays, return amount to shift as determined by good suffix rule. """ length = len(big_l_prime) assert i < length if i == length - 1: return 0 i += 1 # i points to leftmo...
def strip_newsgroup_header(text): """ Given text in "news" format, strip the headers, by removing everything before the first blank line. Parameters ---------- text : str The text from which to remove the signature block. """ _before, _blankline, after = text.partition('\n\n') ...
def _combine_filenames(filename1, filename2): """Combine the filename attribute from multiple UVData objects. The 4 cases are: 1. `filename1` has been set, `filename2` has not 2. `filename1` has not been set, `filename2` has 3. `filename1` and `filename2` both have been set 4. `filename1` and `...
def has_new_posts(topic): """ Returns ``True`` if the given topic has new posts for the current User, based on the presence and value of a ``last_read`` attribute. """ if hasattr(topic, 'last_read'): return topic.last_read is None or topic.last_post_at > topic.last_read else: ...
def instance_attributes(inst): """Given an instance, lists the name of all public non-callable members. Attributes: inst (obj): The instance of the object. """ return [n for n in dir(inst) if not n.startswith('_') and not callable(getattr(inst, n))]
def oo_filter_container_providers(results): """results - the result from posting the API calls for adding new providers""" all_results = [] for result in results: if 'results' in result['json']: # We got an OK response res = result['json']['results'][0] all_result...
def match_substrings(text, items, getstr=None, cmp=None, unmatched=False): """ Matches each item from the items sequence with sum substring of the text in a greedy fashion. An item is either already a string or getstr is used to retrieve a string from it. The text and substrings are normally compare...
def reduce_sequences(object_a, object_b): """Performs an element-wise addition of sequences into a new list. Both sequences must have the same length, and the addition operator must be defined for each element of the sequence. """ def is_seq(obj): """Returns true if the object passed is a s...
def pn_cli(module, switch=None, username=None, password=None, switch_local=None): """ Method to generate the cli portion to launch the Netvisor cli. :param module: The Ansible module to fetch username and password. :return: The cli string for further processing. """ cli = '' if username an...
def safe_int(num): """Transform a string into int type with safety.""" # this function is mainly designed for elasticsearch # since there are lots of bad int types num = num.strip() if '.' in num: # when the num is something like: `88.` return int(float(num)) return int(num)
def color_post_response_ok(devid, hue, saturation): """Return color change response json.""" return ''' { "idForPanel": "''' + devid + '''", "hue": ''' + str(int(hue)) + ''', "saturation": ''' + str(int(saturation)) + ''' }'''
def _valid_task_name(name): """Check if ``name`` is a valid Fabric task name""" if not name: return False if name.startswith('-'): return False if ' ' in name: return False if ':' in name: return False if '.' in name: return False return True
def imt(token, i=None, m=None, t=None): """Helper function to simplify comparisons Instance, Match and TokenType :param token: :param i: Class or Tuple/List of Classes :param m: Tuple of TokenType & Value. Can be list of Tuple for multiple :param t: TokenType or Tuple/List of TokenTypes :return:...
def fail_response(data): """ When an API call is rejected due to invalid data or call conditions, the function response's data key contains an object explaining what went wrong, typically a hash of validation errors. For example: { "status" : "fail", "data" : { "title" : "A title is require...
def boundary(value, arg): """Defines a boundary for an integer. If the value of the integer is higher than the boundary, then the boundary is returned instead. Example: {{ comment.depth|:"4" }} will return 4 if the value of comment.depth is 4 or higher, but will return 1, 2 or 3 if the value of co...
def colored_div(*spans, color=''): """Produce an HTML div box with color.""" spans = '<br>'.join(str(item) for item in spans) div = ( f'<div style="background:{color}; display:inline-block">' + spans + '</div>' ) return div
def cambiar_espacios(cadena): """Dado un string, escribir una funcion que cambie todos los espacios por guiones.""" return cadena.replace(' ','-')
def to_timestamp(datetime_timestamp): """Convert UTC datetime to microsecond timestamp used by Hangouts.""" try: return int(datetime_timestamp.timestamp() * 1000000) except: return -1
def dict_filter(dic, keys: list) -> list: """ Get values from a dict given a list of keys :param dic: dictionary to be filtered :param keys: list of keys to be used as filter :return: """ return [(dic[i]) for i in keys if i in list(dic.keys())]
def CombineMetrics(loss_metric_weight_pairs): """Combines metrics from `loss_metric_weight_pairs` according to weights. Keys must either exist in all metrics, in which it will be processed as a weighted sum, or exist in only one metrics, in which case it will be copied. Args: loss_metric_weight_pairs: a l...
def CI_compare(CI1, CI2): """Return +1 if CI1 > CI2, -1 if CI1 < CI2, 0 if overlapping""" if CI1[1] < CI2[0]: return -1 elif CI2[1] < CI1[0]: return +1 else: return 0
def delay_exponential(base, growth_factor, attempts): """ Calculate time to sleep based on exponential function. The format is:: base * growth_factor ^ (attempts - 1) Base must be greater than 0, otherwise a ValueError will be raised. """ if base <= 0: raise ValueError("The ...
def get_pagination_readable_message(header: str, limit: int, page: int) -> str: """ Generate pagination commands readable message. Args: header (str): Message header limit (int): Number of elements to retrieve. page (int): Page number. Returns: str: Readable message. ...
def chunks(l, n): """ Split list in chunks - useful for controlling memory usage """ if n < 1: n = 1 return [l[i:i + n] for i in range(0, len(l), n)]
def _reldiff(a, b): """ Computes the relative difference of two floating-point numbers rel = abs(a-b)/min(abs(a), abs(b)) If a == 0 and b == 0, then 0.0 is returned Otherwise if a or b is 0.0, inf is returned. """ a = float(a) b = float(b) aa = abs(a) ba = abs(b) if a == ...
def rk4(t, x, xdot, h ): """ t : time x : initial state xdot: a function xdot=f(t,x, ...) h : step size """ k1 = h * xdot(t,x) k2 = h * xdot(t+h/2 , x + k1/2) k3 = h * xdot(t+h/2, x + k2/2) k4 = h * xdot(t+h , x + k3) x = x + (k1 + 2*k2 + 2*k3 + ...
def k_fold_boundaries(values, folds): """Take a list of values and number of folds, return equally spaced boundaries as tuples""" return [ (int((i / folds) * len(values)), int(((i + 1) / folds) * (len(values)))) for i in range(folds) ]
def check_chk(chk, name, requires_chk): """Check that chk is provided when required Parameters ---------- chk : int name : str requires_chk : [str] """ if chk is None: if name in requires_chk: raise ValueError(f"must provide chk for '{name}'") else: ...
def xy2block(x, y): """convert an index to a the x-y-coordinate of the 3x3 block (the third neighborhood) of the cell. Possible values are x from 1..3 and y from 1..3""" return [((x - 1) // 3) * 3 + 1,((y - 1) // 3) * 3 + 1]
def cut_top(tree): """ {B : {a : x, b : y}, B : {c : z}} --> {a : x, b : z, c : z} or {A : [a, b], B : [c]} --> [a, b, c] """ r = {} try: for d in tree.values(): for k,v in d.iteritems(): r[k] = v except AttributeError: try: ...
def unquote(name): """Remove string quotes from simple `name` repr.""" return name.replace("'","").replace('"','')
def _collate_message_types(summaries): """collate different error message types""" message_type_count = {} for summary in summaries: for message in summary.get('summary').get('validationSummary').get('messageTypes'): message_type_count[message.get('messageType')] = message_type_count.set...
def clean_unicode(text): """A function to clean unsee unicode character like \\u2xxx Args: text (str): Can be news title or news body Returns: [str]: A unicode-free string """ clean_text = text.encode("ascii", errors="replace").strip().decode("ascii") clean_text = clean_text.repl...
def list_atoms_of_type(subset,num_atom_types,atom_type_list): """Creates a list containing the numbers of all atoms of the atom types in the list subset.""" atom_subset_list = [] n = 0 for i in range(num_atom_types): for j in range(atom_type_list[i]): if subset.count(i): ...
def parse_recvd_data(data): """ Break up raw received data into messages, delimited by null byte """ parts = data.split(b'\0') msgs = parts[:-1] rest = parts[-1] return (msgs, rest)
def validate_str(obj) -> str: """ Check that obj is a string and then convert it to unicode. Parameters ---------- obj: Any Object that should be a string Returns ------- str `obj` as a string. Raises ------- ValueError If `obj` is not a string. ...
def concat_sttn_name(x): """ Customized helper to make sure station names have unified format: LikeThisOne. """ if len(x) == 1: w = x[0] return w[0].upper() + w[1:] else: return ''.join([w.capitalize() for w in x])
def decay_function(value, epoch, reduction_rate): """ Applies to the input value monothonical decay. Parameters ---------- value : int, float epoch : int Current training iteration (epoch). reduction_rate : int The larger the value the slower decay Returns -------...
def stringify(sentence, vocab): """ Given a numericalized sentence, fetch the correct word from the vocab and return it along with token indices in the new sentence Example: sentence : "1 2 3" vocab : { 1 : "Get" 2 : "me" 3 : "water" }...
def UnitStringIsValid(unit: str) -> bool: """Checks to make sure that a given string is in fact a recognized unit used by the chromium perftests to report results. Args: unit (str): The unit string to be checked. Returns: bool: Whether or not it is a unit. """ accepted_units = [ "us/hop"...
def connected_group(graph, start, connected = None): """Find all nodes that are connected to the specified node.""" if not connected: connected = [] if start in connected: return connected connected.append(start) for node in graph[start]: connected = connected_group(graph,...
def split_on_chunks(sequence, length: int, no_rest=False): """ Split a sequence to chunks same length. A length must be more 0. If leaved a rest of elements and flag no_rest is False, returns it as a last tuple, othewise - appends the rest to the penultimate item, if exists. Arguments: ...
def float_or_null(v): """Return a value coerced to a float, unless it's a None.""" if v is not None: v = float(v) return v
def _signed_int(value: int) -> int: """ The method makes sure that our 32bit int is signed so we negate it """ if value & 0x80000000: value -= 0x100000000 return value
def overflow_format(num, overflow): """ Returns string of the given integer. If the integer is large than given overflow, '{overflow}+' is returned :param num: int :param overflow: int :return: str """ if not isinstance(num, int): raise ValueError('Input argument "num" should be int...
def update_lifecycle_test_tags(lifecycle, test, tags): """Returns lifecycle object after creating or updating the tags for 'test'.""" if not lifecycle["selector"]["js_test"]: lifecycle["selector"]["js_test"] = {test: tags} else: lifecycle["selector"]["js_test"][test] = tags return lifecy...
def _schema_validation(jsonData): """ Input data Schema: - A JSON with top hierarchy 'SLA' and 'results' dicts: jsonData = {'SLA':dict, 'result':dict} dict('SLA') = {'requirements':['time','price', 'resolution'], 'order':['prod_list']} dict('result') = {'s3_credentials':[host, bucket, api-k...
def read_key_dict(obj, key): """Given a dict, read `key`, ensuring result is a dict.""" assert key in obj, 'key `%s` not found' % key assert obj[key], 'key `%s` was blank' % key assert isinstance(obj[key], dict), 'key `%s` not a dict' % key return obj[key]
def column_is_foreign_key(column): """Returns whether a column object is marked as a foreign key.""" foreign_key = column["is foreign key"] if isinstance(foreign_key, str): foreign_key = foreign_key.lower() if foreign_key in {"y", "n", "yes", "no", "-"}: foreign_key = foreign_ke...
def text_to_lowercase(text): """Set all letters to lowercase""" return text.lower()
def pad_sequences(sentences, max_len): """ Pads the end of a sentence or cuts it short. :param sentences: :param max_len: :return: """ padded_sentences = [] for sent in sentences: padded_sent = [] sent_len = len(sent) for idx in range(1, max_len): ...
def paint(width, height, performance): """Calculates how many paint does one need for given area @param width: area's width @param height: area's height @param performance: paint performance/m^2""" area = width * height return area / performance
def biome(val, params): """ Quantize value val into ranges specified by params """ # print(val) if val < params[1]: # sea return 0 if val < params[2]: # plains return 1 if val < params[3]: # hills return 2 return 3
def pad_block(block, size, char='\x04'): """Pad a bytestring to a specified number of bytes.""" if len(block) > size: raise ValueError('Block cannot be larger than size to be padded.') elif len(block) < size: pad_length = size - len(block) block += (char * pad_length).encode()[:pad_l...
def G2mu(G, E): """compute poisson ratio from shear modulus and Youngs modulus E """ return E/(2*G)-1
def next_velocity(v, force, next_force, dt): """ calculates next velocity component for a particle.""" """ parameters ---------- v : float velocity component of particle force : float current force felt by particle next_force : float force felt by particle at future ...
def delBlank(strs): """ Delete all blanks in the str. """ ans = "" for e in strs: if e != " ": ans += e return ans
def map_range(x, in_min, in_max, out_min, out_max): """ Maps and constrains an input value from one range of values to another. (from adafruit_simpleio) :return: Returns value mapped to new range :rtype: float """ in_range = in_max - in_min in_delta = x - in_min if in_range != 0: ...
def convert(quality): """ converts quality (percent) to dbm. """ if quality <= 0: dbm = -100 elif quality >= 100: dbm = -50 else: dbm = (quality / 2) - 100 return int(dbm)
def is_500(exception): """Return True exception message contains 500""" return "500" in str(exception)
def fit_config(rnd: int): """Return training configuration dict for each round. Keep batch size fixed at 32, perform two rounds of training with one local epoch, increase to two local epochs afterwards. """ config = { "batch_size": 32, "local_epochs": 1 if rnd < 2 else 2, } r...
def normalize(pos, ref, alt, left_only=False): """simplify a ref/alt a la vt normalize so that ref=CC, alt=CCT becomes ref=C, alt=CT. this helps in annotating variants. This code relies on the observation by Eric Minikel that many annotation misses can be addressed by removing common suffix and prefixe...
def split_list(lst, n): """ split lst into two parts with the first part having n elements, and return a list that contains these two parts. """ return [ lst[:n+1], lst[n+2:] ]
def duplicate_count(text: str): """ Counts the number of duplicate letters in a word """ repeat_list = [] fixed_text = text.upper() for char in fixed_text: counts = fixed_text.count(char) if counts > 1: repeat_list.append(char) return len(set(repeat_list))
def parse_field_content(field_name, content): """Parse content fields if nested using dot notation, else return content as is. e.g. for acrray content and field_name casebody.data.opinions.text, we return content[casebody][data][opinions][text]. If any nest level is an array we return only the first in...
def tag2ts(ts_tag_sequence): """ transform ts tag sequence to targeted sentiment :param ts_tag_sequence: tag sequence for ts task :return: """ n_tags = len(ts_tag_sequence) ts_sequence, sentiments = [], [] beg, end = -1, -1 for i in range(n_tags): ts_tag = ts_tag_sequence[i] ...
def _map_configurations(map_conf_args, grid_conf_args, invar, ref_mod): """ Create and/or modify map configuration dictionary for map plots """ if not map_conf_args.keys(): map_conf = { 'proj': 'stere', 'zoom': 'crnrs', 'crnr_vals': grid_conf_args['meta data']...
def determinant(matrix): """ Calculates the determinant of a matrix. matrix is a list of lists whose determinant should be calculated If matrix is not a list of lists, raise a TypeError with the message matrix must be a list of lists If matrix is not square, raise a ValueError with the message ...
def recallAtK(cls, ranking, k): """ This function takes a class label ('cls'), a ranked list 'ranking' of (class,score) pairs (ranked by virtue of being sorted in descending order of score) and a parameter 'k', and returns 1 if 'cls' is in 'ranking' in the top 'k' ranked classes. The word 'recall' ...
def intersect(key_a, mask_a, key_b, mask_b): """Return if key-mask pairs intersect (i.e., would both match some of the same keys). For example, the key-mask pairs ``00XX`` and ``001X`` both match the keys ``0010`` and ``0011`` (i.e., they do intersect):: >>> intersect(0b0000, 0b1100, 0b0010, 0...
def date(date_time): """Return a human readable string for a datetime object.""" return date_time.strftime("%Y-%m-%d %H:%m %Z") if date_time else "not provided"
def get_sorted_key_index(class_key, class_dict): """ Given class_dict, returns an index that would result from ordering the keys in class_dict according to their values and accessing one of the keys (class_key). That index can be used to access multiclass prediction scores """ assert(isinstance...
def funcName(func): """Returns the name of a function or instance method; if the function is a callable object then returns the name of the object's class. """ try: return func.__name__ except AttributeError: pass try: return func.__class__.__name__ except AttributeEr...
def convert_int(str_num): """ Convert string number to integer """ if str_num.isnumeric(): return int(str_num) else: return int(float(str_num))
def generate_title(s: str) -> str: """Remove underscores and capitalize first letter to each word""" s = s.replace('_', ' ') s = s.title() return s