content
stringlengths
42
6.51k
def to_dojo_data(items, identifier='id', num_rows=None): """Return the data as the dojo.data API defines. The dojo.data API expects the data like so: {identifier:"whatever", items: [ {name:"Lenin", id:3, ....}, ] } The identifier is optional. """ ret = {'items':items} if identifier: ret['identifier'] = identifier if num_rows: ret['numRows'] = num_rows return ret
def whichSide(point,line): """Returns -ve, 0, +ve if point is on LHS, ontop, or RHS of line""" linepoint, linedelta = line # determine which side of the fold line this initial point is on # which side of the line is it on? right hand side, or left? pdx = point[0]-linepoint[0] pdy = point[1]-linepoint[1] if linedelta[0]==0: return pdx elif linedelta[0]>0: return (linedelta[1]/linedelta[0])*pdx - pdy elif linedelta[0]<0: return pdy - (linedelta[1]/linedelta[0])*pdx
def xor_bytes(a, b): """Returns a byte array with the values from XOR'ing each byte of the input arrays.""" if len(a) != len(b): raise ValueError("Both byte arrays must be the same length.") return bytes([a[i] ^ b[i] for i in range(len(a))])
def epsilonMaquina(tipoDato): """ Funcion que trata de calcular el epsilon de la maquina mediante el algoritmo antes pre_ sentado. Input: tipoDato := esta pensado para ser uno de los tipos proporcionados por la li_ breria numpy. Output: Regresa el epsilon de la maquina calcula_ do con el tipo de dato especificado. """ epsilon = tipoDato(1.0) unidad = tipoDato(1.0) valor = unidad + epsilon while valor > unidad: epsilon = epsilon/tipoDato(2.0) valor = unidad + epsilon return epsilon*2
def null_space_check(null_space): """Part of the entorpy check to verify we've got a legitimate table Following the row pointers, there should be some bit of null space This just checks for at least 16 sequential null bytes... probably not the best check - revist this""" if null_space != "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00": return False else: return True
def index_chunks(chunks): """ Turns a chunks array into a dictionary keyed by chapter :param chunks: :return: """ dict = {} for chunk in chunks: if not chunk['chp'] in dict: dict[chunk['chp']] = [] dict[chunk['chp']].append(chunk['firstvs']) return dict
def exclude_bias_and_norm(path, val): """Filter to exclude biaises and normalizations weights.""" del val if path[-1] == "b" or "norm" in path[-2]: return False return True
def get_file_name(file_name, extension): """ Get full file name :param file_name: File name without extension :param extension: File extension :return: File name with extension """ if str(file_name).endswith(extension): full_file_name = str(file_name) else: full_file_name = str(file_name) + '.' + str(extension) return full_file_name
def humanReadable(kbytes): """Returns sizes in human-readable units.""" units = [(" KB", 2**10), (" MB", 2**20), (" GB", 2**30), (" TB", 2**40)] for suffix, limit in units: if kbytes > limit: continue else: return str(round(kbytes/float(limit/2**10), 1)) + suffix
def pixels_to_EMU(value): """1 pixel = 9525 EMUs""" return int(value * 9525)
def get_in(d, ks, default=None): """ Returns a value in a nested associative structure, where `ks` is a sequence of keys. Returns `None`, if the key is not present, or the `default` value, if supplied. """ *ks_, last = ks d_ = d for k in ks_: if type(d_) != dict or k not in d_: return default d_ = d_[k] if type(d_) == dict: return d_.get(last, default) return default
def plural(n, s, pl=None, str=False, justTheWord=False): """Returns a string like '23 fields' or '1 field' where the number is n, the stem is s and the plural is either stem + 's' or stem + pl (if provided).""" smallints = [u'zero', u'one', u'two', u'three', u'four', u'five', u'six', u'seven', u'eight', u'nine', u'ten'] if pl == None: pl = u's' if str and n < 10 and n >= 0: strNum = smallints[n] else: strNum = int(n) if n == 1: if justTheWord: return s else: return (u'%s %s' % (strNum, s)) else: if justTheWord: return u'%s%s' % (s, pl) else: return (u'%s %s%s' % (strNum, s, pl))
def lengthOfLastWord(s): """ :type s: str :rtype: int """ l = len(s)-1 rslt = 0 while l>=0 and s[l] == ' ': # l>=0 should occur first as l=-1 will fail for # empty string ('') l-=1 while l>=0 and s[l] != ' ': rslt +=1 l-=1 return rslt
def get_or_else_none(map_to_check, key): """ Use map.get to handle missing keys for object values """ return map_to_check.get(key, None)
def get_s3_url(s3_bucket: str, s3_key: str) -> str: """ Calculates the s3 URL for a file from the bucket name and the file key. """ return "%s.s3.amazonaws.com/%s" % (s3_bucket, s3_key)
def limit_data(names, data, limit): """ Limit data to the requested number of items, binning the rest into "Other" """ ret_names = list() ret_data = list() # Copy unfiltered data for idx in range(limit): if idx >= len(data): break ret_names.append(names[idx]) ret_data.append(data[idx]) # Aggregate filtered data otherSize = 0.0 for idx in range(limit, len(data)): otherSize += float(data[idx]) if limit < len(data): ret_names.append("Other") ret_data.append(otherSize) return ret_names, ret_data
def remove_seq_duplicates(question): """ Removes consequent sbj placeholders""" i = 0 while i < len(question) - 1: if question[i] == question[i + 1] and question[i] == "sbj": del question[i] else: i = i + 1 return question
def rgb_to_hsl(rgb_array): """! @brief Convert rgb array [r, g, b] to hsl array [h, s, l]. @details RGB where r, g, b are in the set [0, 255]. HSL where h in the set [0, 359] and s, l in the set [0.0, 100.0]. Formula adapted from https://www.rapidtables.com/convert/color/rgb-to-hsl.html @param rgb_array RGB array [r, g, b]. @return HSL array [h, s, l]. """ r, g, b = rgb_array r, g, b = (r/255), (g/255), (b/255) min_color, max_color = min(r, g, b), max(r, g, b) h, s, l = None, None, ((max_color+min_color) / 2) if min_color == max_color: h = s = 0 # Color is grayscale/achromatic. else: color_range = max_color - min_color s = color_range / (1 - abs(2 * l - 1)) if max_color == r: h = ((g - b) / color_range) % 6 elif max_color == g: h = (b - r) / color_range + 2 else: h = (r - g) / color_range + 4 h = round(h*60) # Degrees. s = round(s*100, 1) # Percentage [0% - 100%] whole numbers. l = round(l*100, 1) # Percentage [0% - 100%] whole numbers. return [h, s, l]
def headline_changes(value): """changes headline according to pressed button on sidebar""" return 'Please select Subject/Hemisphere' if value is None else 'Rotation: {}'.format(value)
def mittelwert(noten): """ Berechnet den Mittelwert der Liste noten auf 2 Stellen genau """ mean = round(sum(noten)/len(noten), 2) return mean
def and_combination(disjunction, term): """ Join a disjunction and another term together with an AND operator. If term is a lexeme, then we append it to the last conjunction in the disjunction. If `term` is itself a disjunction, then we do a pair-wise combination of every conjunction in both disjunctions. example: "(a or b) and (c or d)" with disjunction as [[a], [b]] and term as [[c], [d]] the result is [[a, c], [a, d], [b, c], [b, d]] """ if isinstance(term, list): # Combine two sub-expressions with AND return [conj1 + conj2 for conj1 in disjunction for conj2 in term] else: # Append an atom to the last expression (AND case) disjunction[-1].append(term) return disjunction
def problem_5_1(n, m, i, j): """ You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j). Example: Input: N = 10000000000, M = 10101, i = 2, j = 6 Output: N = 10001010100 """ x = ((2**(len(bin(n))-j)-1) << (j+1)) + (2**i - 1) return n & x | m << i
def is_tachy(age, hr): """ Determines if a patient is tachycardic or not based on age and a heart rate measurement Args: age: patient's age hr: heart rate recording of interest Returns: str: 'Tachydardic' or 'Non-Tachycardic' signifying the patient's tachycardia state """ tachy = False if age < 1: return'Patient is too young to detect tachycardia ' \ 'with this program. Patient must be at least 1YO' elif age >= 1 and age <= 2 and hr >= 151: tachy = True elif age >= 3 and age <= 4 and hr >= 137: tachy = True elif age >= 5 and age <= 7 and hr >= 133: tachy = True elif age > 8 and age <= 11 and hr >= 130: tachy = True elif age >= 12 and age <= 15 and hr >= 119: tachy = True elif age >= 15 and hr >= 100: tachy = True if tachy: return 'Tachycardic' else: return 'Non-Tachycardic'
def syntax_error_transformer(lines): """Transformer that throws SyntaxError if 'syntaxerror' is in the code.""" for line in lines: pos = line.find('syntaxerror') if pos >= 0: e = SyntaxError('input contains "syntaxerror"') e.text = line e.offset = pos + 1 raise e return lines
def satlin(n): """ Saturing Linear """ if n < 0: return 0 elif n > 1: return 1 else: return n
def readfile(name): """ Reads the file with the name and returns it as a string. :param name: The file name :return: The data in teh file as string """ try: # print ("READ", name) f = open(name) data = f.read().strip() f.close() return data except: return None
def stars(pval): """ Returns a string of stars based on pvalue """ if pval <= 0.01: return "***" elif pval <= 0.05: return "**" elif pval <= 0.10: return "*" return ""
def getXofMax(data): """ locates the index of the maximum value found in a list or an array @param data the list or array that should be analyzed @return the index position (zero-based) of the maximum """ valMax = data[0] xOfMax = 0 for i in range(len(data)): if data[i] > valMax: valMax = data[i] xOfMax = i return xOfMax
def subtract_vectors(u, v): """Subtract one vector from another. Parameters ---------- u : list XYZ components of the first vector. v : list XYZ components of the second vector. Returns ------- list The resulting vector. Examples -------- >>> """ return [a - b for (a, b) in zip(u, v)]
def calc_labour(yield_potential): """ Labour Costs Formaula Notes ------ Direct farm labour cost = Number of staff working full-time x wages x 30 hours Generalisation if statement on farm labour required if unknown """ farm_hours = yield_potential*0.2 labour_cost = farm_hours * 7 # wage return labour_cost
def CombineDicts(a, b): """Unions two dictionaries by combining values of keys shared between them. """ c = {} for key in a: if b.has_key(key): c[key] = a[key] + b.pop(key) else: c[key] = a[key] for key in b: c[key] = b[key] return c
def hargreaves(tmin, tmax, et_rad, tmean = None): """ Estimate reference evapotranspiration over grass (ETo) using the Hargreaves equation. Generally, when solar radiation data, relative humidity data and/or wind speed data are missing, it is better to estimate them using the functions available in this module, and then calculate ETo the FAO Penman-Monteith equation. However, as an alternative, ETo can be estimated using the Hargreaves ETo equation. Based on equation 52 in Allen et al (1998). :param tmin: Minimum daily temperature [deg C] :param tmax: Maximum daily temperature [deg C] :param tmean: Mean daily temperature [deg C]. If emasurements not available it can be estimated as (*tmin* + *tmax*) / 2. :param et_rad: Extraterrestrial radiation (Ra) [MJ m-2 day-1]. Can be estimated using ``et_rad()``. :return: Reference evapotranspiration over grass (ETo) [mm day-1] :rtype: float """ # Note, multiplied by 0.408 to convert extraterrestrial radiation could # be given in MJ m-2 day-1 rather than as equivalent evaporation in # mm day-1 if not tmean: tmean = (tmax + tmin)/2 return 0.0023 * (tmean + 17.8) * (tmax - tmin) ** 0.5 * 0.408 * et_rad
def range_is_valid(maximum): """Determine if the provided range is valid. Since the numbers that make up the list are expected to be from 0 to 9, ensure the provided maximum falls into that range. Parameters ---------- maximum: int Returns ------- boolean Whether or not the provided maximum is valid """ return maximum <= 9 and maximum >= 0
def to_smash(total_candies): """Return the number of leftover candies that must be smashed after distributing the given number of candies evenly between 3 friends. >>> to_smash(91) 1 """ print("Splitting", total_candies, "candies") return total_candies % 3
def _is_not_blank(val): """Tests if value is not blank""" return val or val == 0
def try_parse_bool(possible_bool): """Try to parse a bool.""" if isinstance(possible_bool, bool): return possible_bool return possible_bool in ["true", "True", "1", "on", "ON", 1]
def str_to_i(_s): """Converts a string to an integer, returns None if not an integer""" try: return int(_s.strip()) except ValueError: return None
def get_contained_functions(f): """ Given a function object, return a tuple of function names called by f """ return f.__code__.co_names
def get_combis(divs): """Get permutations of `divs`. Args: divs: list of ints Returns: combis: list of tuples """ combis = [] # Get list of all combinations of rows and columns for r in divs: for c in divs: combis.append((r, c)) return combis
def to_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') if isinstance(value, dict): value = value.items() return list(value)
def Leq_indicator(row): """ Determine the Indicator of Leq as one of five indicators """ if row < 37: return "Excellent" elif row < 47: return "Good" elif row < 58: return "Fair" elif row <= 85: return "Poor" else: return "Hazard"
def raises(callable, args=(), kwargs={}): """Check if `callable(*args, **kwargs)` raises an exception. Returns `True` if an exception is raised, else `False`. Arguments: - callable: A callable object. - args: A list or tuple containing positional arguments to `callable`. Defaults to an empty tuple. - kwargs: A dictionary containing keyword arguments to `callable`. Defaults to an empty dictionary. """ try: callable(*args, **kwargs) except Exception as exc: return True return False
def check_numeric(value_string): """ This function tries to determine if a string would be better represented with a numeric type, either int or float. If neither works, for example ``10 Mb``, it will simply return the same string provided :param value_string: input string to be parsed. :return: the input string, an int, or a float """ if type(value_string) in ('int', 'long', 'float'): return value_string try: if '.' in value_string: return float(value_string) except (TypeError, ValueError): pass try: return int(value_string) except (TypeError, ValueError): pass return value_string
def _encode_for_display(text): """ Encodes strings so they can display as ASCII in a Windows terminal window. This function also encodes strings for processing by xml.etree.ElementTree functions. Returns an ASCII-encoded version of the text. Unicode characters are converted to ASCII placeholders (for example, "?"). """ return text.encode('ascii', errors="backslashreplace").decode('utf-8')
def as_bool(x): """ Returns True if the given string in lowercase equals "true", False otherwise. """ return True if x.lower() == "true" else False
def recursive(x, y): """ Find the GCD or HCF of two numbers. :return: returns the hcf of two numbers. """ x, y = max(x, y), min(x, y) if y==0: return x return recursive(y, x%y)
def clamp(number: int or float, low: int or float, high: int or float) -> int or float: """Clamp a number """ if number < low: return low if number > high: return high return number
def insert_semicolon_break(words_list): """Doc.""" new_words_list = [] for words in words_list: if words[0].startswith('#'): new_words_list.append(words) continue new_words = [] in_for = False semicolon_counter = 0 for index, word in enumerate(words): next_word = '' if index + 1 < len(words): next_word = words[index + 1] new_words.append(word) if not in_for: if word == ';' and next_word[:2] != '//': new_words_list.append(new_words) new_words = [] if word == 'for': in_for = True else: if word == ';': semicolon_counter += 1 if semicolon_counter == 2: in_for = False semicolon_counter = 0 new_words_list.append(new_words) return new_words_list
def generate_payload(query): """Generate the payload for Gamepedia based on a query string.""" payload = {} payload["action"] = "query" payload["titles"] = query.replace(" ", "_") payload["format"] = "json" payload["formatversion"] = "2" # Cleaner json results payload["prop"] = "extracts" # Include extract in returned results # Only return summary paragraph(s) before main content payload["exintro"] = "1" payload["redirects"] = "1" # Follow redirects payload["explaintext"] = "1" # Make sure it's plaintext (not HTML) return payload
def get_mean_score(rating_scores): """Compute the mean rating score given a list. Args: rating_scores: a list of rating scores. Returns: The mean rating. """ return sum(rating_scores) / len(rating_scores)
def compute_testcase_status(step_status, tc_status): """Compute the status of the testcase based on the step_status and the impact value of the step Arguments: 1. step_status = (bool) status of the executed step 2. tc_status = (bool) status of the testcase 3. data_repository= (dict) data_repository of the testcase """ if step_status is None: return tc_status else: return tc_status and step_status
def hex2byte(hex_str): """ Convert a string hex byte values into a byte string. The Hex Byte values may or may not be space separated. """ bytes = [] hex_str = ''.join(hex_str.split(" ")) for i in range(0, len(hex_str), 2): bytes.append(chr(int(hex_str[i:i+2], 16))) return ''.join(bytes)
def contains_only(seq, aset): """ Check whether sequence seq contains ONLY items in aset. """ for c in seq: if c not in aset: return False return True
def parse_interval(interval_string): """Parses interval string like "chr1:12345-54321" and returns 3-tuple (chrom, start, end)""" try: tokens = interval_string.split(":") chrom = ":".join(tokens[:-1]) # some super-contig names have : in them start, end = map(int, tokens[-1].split("-")) except Exception as e: raise ValueError(f"Unable to parse off_target_region: '{interval_string}': {e}") return chrom, start, end
def transpose_data_dict(t): """converts a dict with 'fileds' and 'vals' (where vals are lists of lists) and coverts it into a dict where the keys are the fields and the values are the associate vals""" foo = {} for i,row in enumerate(t['vals']): for j,val in enumerate(row): field = t['fields'][j] if( not field in foo ): foo[field] = [] foo[field].append(val) return foo
def field_fmt(item): """Return the field format if appropriate.""" return '"{:s}"'.format(item['fmt']) if '"' not in item['fmt'] else item['fmt']
def encode(s, encoding="utf-8", errors="strict"): """ Auto encode unicode string to bytes. :param s: string :param encoding: bytes encoding(default:utf-8) :param errors: different error handling scheme :return: bytes """ if isinstance(s, bytes): return s return s.encode(encoding, errors)
def compute_sv_offset(frequency, pulse_length): """ A correction must be made to compensate for the effects of the finite response times of both the receiving and transmitting parts of the instrument. The magnitude of the correction will depend on the length of the transmitted pulse, and the response time (on both transmission and reception) of the instrument. :param frequency: Frequency in KHz :param pulse_length: Pulse length in uSecs :return: """ sv_offset = 0 if frequency > 38: # 125,200,455,769 kHz if pulse_length == 300: sv_offset = 1.1 elif pulse_length == 500: sv_offset = 0.8 elif pulse_length == 700: sv_offset = 0.5 elif pulse_length == 900: sv_offset = 0.3 elif pulse_length == 1000: sv_offset = 0.3 else: # 38 kHz if pulse_length == 500: sv_offset = 1.1 elif pulse_length == 1000: sv_offset = 0.7 return sv_offset
def plural(items, word): """Return number of items followed by the right form of ``word``. ``items`` can either be an int or an object whose cardinality can be discovered via `len(items)`. The plural of ``word`` is assumed to be made by adding an ``s``. """ item_count = items if isinstance(items, int) else len(items) word = word if item_count == 1 else word + 's' return '{0} {1}'.format(item_count, word)
def word2index(words, word_index): """ # Arguments words {list}: [w1,w2] word_index {dict}: {"w1":1} # Returns [1,2,3,4] """ result = [] for word in words: if word in word_index: result.append(word_index[word]) else: result.append(word_index["<UNK>"]) return result
def file_ext(v): """Split of the extension of a filename, without throwing an exception of there is no extension. Does not return the leading '.' :param v: """ from os.path import splitext if not v: return None try: try: v = splitext(v)[1][1:] except TypeError: v = splitext(v.fspath)[1][1:] if v == '*': # Not a file name, probably a fragment regex return None return v.lower() if v else None except IndexError: return None
def get_command_str(args): """ Get terminal command string from list of command and arguments Parameters ---------- args : list A command and arguments list (unicode list) Returns ------- str A string indicate terminal command """ single_quote = "'" double_quote = '"' for i, value in enumerate(args): if " " in value and double_quote not in value: args[i] = '"%s"' % value elif " " in value and single_quote not in value: args[i] = "'%s'" % value return " ".join(args)
def CorrectOrWrong(Input,word): """Check if Input is inside word""" if Input in word: return True else: return False
def _get_all_issue_tracker_keys(all_issue_trackers): """Collect all keys in all dicts.""" ret = set() for dct in all_issue_trackers: ret.update(dct.keys()) return ret
def LongValueFromJsonStats(json_stats, keys): """Get long integer value from stats with iterating keys. For example: when keys = ['stats', 'timeStats', 'uptime'], this returns long(json_stats['stats']['timeStats']['uptime']) if any. Args: stats: json keys: iterable keys Returns: long value if any. None otherwise. """ curr = json_stats for k in keys: if not curr or k not in curr: return None curr = curr[k] if not curr: return None return int(curr)
def is_element_index(index, shape): """Return True if index is a concrete index of nested sequence with given shape. Return False if index is an incomplete index or slice such that indexing operation would result another nested sequence rather than an element value. """ if isinstance(index, slice) or index is None: return False if isinstance(index, int): return len(shape) == 1 if len(index) == len(shape): for ind in index: if not isinstance(ind, int): return False return True return False
def setup_datafiles(shell,params_info): """ write the datafiles to disk build the parameters file """ parameters_text_items = [] for key,value in params_info.items(): shell.write_file(value['path'], value['text']) parameters_text_items.append("%s:%s" % (value['type'],value['path'])) # generate the parameters file to feed into the url parameters_text = '\n'.join(parameters_text_items) return parameters_text
def search_linearw(a, x): """ Returns the index of x in a if present, None elsewhere. """ i = 0 while i < len(a) and a[i] != x: i += 1 if i == len(a): return None else: return i
def prepare_opts(opts): """ >>> opts = {'<module>': 'Blog'} >>> prepare_opts(opts) {'<module>': 'Blog', '--model': 'Blog'} """ rv = opts.copy() rv.update({ '--model': opts.get('<module>') }) return rv
def E_eos(parameters, V): """ Birch-Murnaghan Energy""" E0, V0, B0, Bp = parameters E = E0 + (9.*B0*V0/16)*(((((V0/V)**(2./3))-1.)**3.)*Bp \ + ((((V0/V)**(2/3.))-1.)**2.)*(6.-4.*((V0/V)**(2./3.)))) return E
def add_until_100(array: list): """add numbers to a sum from list: array unless makes sum > 100""" if not array: # base case return 0 sum_remaining = add_until_100(array[1:]) if array[0] + sum_remaining > 100: return sum_remaining else: return array[0] + sum_remaining
def get_model_to_author_dict(model_name_tuples, lower=True): """ Get a dictionary of model names mapped to author names. Args: model_name_tuples (list or set): An iterable of ModelNames tuples of (model_name, author_name). Each name will be lower-case only. lower (bool, optional): Make all output names lower-case. Defaults to True. Returns: dict: Dictionary mapping model names to author names. Output will only be in lower-case. """ output = {} for (model_name, author_name) in model_name_tuples: if lower: model_name = model_name.lower() author_name = author_name.lower() if model_name in output: output[model_name].append(author_name) else: output[model_name] = [author_name] return output
def unicode_exp(exp): """ Get a exponent number for html format https://es.stackoverflow.com/questions/316023/imprimir-exponente-en-python """ # get different values for unitary exponenets (from 0 to 9) if exp == 1: return chr(0xB9) if exp == 2 or exp == 3: return chr(0xB0 + exp) else: return chr(0x2070 + exp)
def range_overlap(ranges): """Return common overlap among a set of [left, right] ranges.""" lefts = [] rights = [] if ranges: for (left, right) in ranges: lefts.append(left) rights.append(right) max_left = max(lefts) min_right = min(rights) if min_right - max_left >= 1: return (max_left, min_right)
def _compute_split_boundaries(split_probs, n_items): """Computes boundary indices for each of the splits in split_probs. Args: split_probs: List of (split_name, prob), e.g. [('train', 0.6), ('dev', 0.2), ('test', 0.2)] n_items: Number of items we want to split. Returns: The item indices of boundaries between different splits. For the above example and n_items=100, these will be [('train', 0, 60), ('dev', 60, 80), ('test', 80, 100)]. """ if len(split_probs) > n_items: raise ValueError('Not enough items for the splits. There are {splits} ' 'splits while there are only {items} items'.format( splits=len(split_probs), items=n_items)) total_probs = sum(p for name, p in split_probs) if abs(1 - total_probs) > 1E-8: raise ValueError('Probs should sum up to 1. probs={}'.format(split_probs)) split_boundaries = [] sum_p = 0.0 for name, p in split_probs: prev = sum_p sum_p += p split_boundaries.append((name, int(prev * n_items), int(sum_p * n_items))) # Guard against rounding errors. split_boundaries[-1] = ( split_boundaries[-1][0], split_boundaries[-1][1], n_items) return split_boundaries
def second(obj): """ get second element from iterable """ try: it = iter(obj) next(it) return next(it) except TypeError: return obj except StopIteration: return
def itr(iterable): """ An iteration tool for easy removal. """ return sorted(enumerate(iterable), reverse=True)
def rgb_to_hex(rgb): """ Convert an RGB color representation to a HEX color representation. (r, g, b) :: r -> [0.0, 1.0] g -> [0.0, 1.0] b -> [0.0, 1.0] :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value. :return: HEX representation of the input RGB value. :rtype: str >>> rgb_to_hex((1.0, 0.0, 0.0)) '#FF0000' """ r, g, b = (k*255 for k in rgb) return "#{0}{1}{2}".format( *(hex(int(round(k)))[2:].zfill(2) for k in (r, g, b)) ).upper()
def increments(deck, N): """deal with increment N""" newdeck = [None for _ in range(len(deck))] for i in range(len(deck)): newdeck[(i * N) % len(deck)] = deck[i] return newdeck
def is_eq(to_be_compared, val): """ Check that two values are almost equal (5% tolerance). """ try: return to_be_compared / val <= 1.05 # to_... is always >= val except ZeroDivisionError: return is_eq(to_be_compared + 1, val + 1)
def strip(s): """Strips non-Ascii characters from strings.""" return "".join(i for i in s if ord(i)<128)
def get_triplet_from_mag(ch_name): """Get the triplet (one mag, two grads) from mag by name hacking. Parameters ---------- ch_name : str Name of mag channel, e.g 'MEG 1231'. Returns ------- list List of three channels, e.g ['MEG 1231', 'MEG 1232', 'MEG 1233'] """ return [ch_name, ch_name[:-1] + '2', ch_name[:-1] + '3']
def parse_charge(dL): """ There are two options: 1) call FcM(**kwargs,fcs=[c1,c2,--cn]) with a list of length equal to the number of atoms 2) FcM(**kwargs,fcs=[[aidx1,aidx2,..,aidxn],[c1,c2,..cn]]) with a list of two sublist for atoms' indexes and fract charges """ a=[[],[]] parsed=False if len(dL) ==2: #necessario, ma non sufficiente per caso 2 try: len(dL[0])==len(dL[1]) if isinstance(dL[0][0],int) or isinstance(dL[0][0],float): parsed=True except: pass if not parsed and (isinstance(dL[0],int) or isinstance(dL[0],float)): #move to case2 for i in range(len(dL)): if dL[i]!=0: a[0].append(i) a[1].append(dL[i]) dL=a parsed=True if not parsed: print("Failed to parse charges") raise return dL
def is_bound(f): """Test whether ``f`` is a bound function. """ return getattr(f, '__self__', None) is not None
def join_as_compacted_paragraphs(paragraphs): """ :param paragraphs: List containing individual paragraphs; potentially with extraneous whitespace within :return: String with \n separated paragraphs and no extra whitespace """ paragraphs[:] = [' '.join(p.split()) for p in paragraphs] # Remove extra whitespace & newlines return '\n'.join(paragraphs)
def user_model(username, email=None): """Return a user model""" userinfo = { 'preferred_username': username, } if email: userinfo['email'] = email return userinfo
def _NextMaintenanceToCell(zone): """Returns the timestamps of the next maintenance or ''.""" maintenance_events = zone.get('maintenanceWindows', []) if maintenance_events: next_event = min(maintenance_events, key=lambda x: x.get('beginTime')) return '{0}--{1}'.format(next_event.get('beginTime'), next_event.get('endTime')) else: return ''
def num_eights(x): """Returns the number of times 8 appears as a digit of x. >>> num_eights(3) 0 >>> num_eights(8) 1 >>> num_eights(88888888) 8 >>> num_eights(2638) 1 >>> num_eights(86380) 2 >>> num_eights(12345) 0 >>> from construct_check import check >>> # ban all assignment statements >>> check(HW_SOURCE_FILE, 'num_eights', ... ['Assign', 'AugAssign']) True """ "*** YOUR CODE HERE ***" if not x: return 0 if x % 10 == 8: return 1 + num_eights(x // 10) else: return num_eights(x // 10)
def tweet_filter(tweet): """ Filter tweets to only be: - English - Contain no media """ try: if tweet['lang'] != 'en': return False if 'media' in tweet['entities'] and len(tweet['entities']['media']) > 0: return False #if 'urls' in tweet['entities'] and len(tweet['entities']['urls']) > 0: return False return True except KeyError: return False
def round_to_base (value, base=1): """ This method expects an integer or float value, and will round it to any given integer base. For example: 1.5, 2 -> 2 3.5, 2 -> 4 4.5, 2 -> 4 11.5, 20 -> 20 23.5, 20 -> 20 34.5, 20 -> 40 The default base is '1'. """ return int(base * round(float(value) / base))
def diff_dict(old, new): """ Compare two dicts and create dict (set_) with new or changed values/keys or a list (remove_) of missing keys. """ set_ = {} remove_ = [] for k in new.keys(): if k in old: # key exists in both if new[k] != old[k]: # but the value changed set_[k] = new[k] else: # something new appeared in new dict set_[k] = new[k] for k in old.keys(): if k not in new: # key from old which was not found in new remove_.append(k) # the remove array is a list of identifiers return set_, remove_
def get_fresh(old_issue_list, new_issue_list): """Returns which issues are not present in the old list of issues.""" old_urls = set(x['url'] for x in old_issue_list) return [x for x in new_issue_list if x['url'] not in old_urls]
def is_dynamic_cwd_width(x): """Determine if the input is a valid input for the DYNAMIC_CWD_WIDTH environment variable. """ return ( isinstance(x, tuple) and len(x) == 2 and isinstance(x[0], float) and x[1] in set("c%") )
def truncate_string(input_string, length): """Truncate a string. Params: - in_string: (type: string) string to truncate. - length: (type: int) length of output string. Returns: - result: (type: string) truncated string. """ return (input_string[:length] + '..') if len(input_string) > 1024 else input_string
def is_not_in_descending_order(a): """ Check if the list a is not descending (means "rather ascending") """ for i in range(len(a) - 1): if a[i] > a[i + 1]: return False return True
def dual(x, y): """ dual """ ret = 3 * x * x * x * y * y * y return ret
def indexPosition1D(i, N): """This function is a generic function which determines if index over a list of length N is an interior point or node 0 or node 1. """ if i > 0 and i < N-1: # Interior return 0, None elif i == 0: # Node 0 return 1, 0 elif i == N-1: # Node 1 return 1, 1
def lcstr(astr): """Convert a string to lower-case""" return astr.lower()
def json_default(o): """Handle unhandled JSON values""" # Convert pandas.DataFrame to lists try: tolist = o.values.tolist except AttributeError: pass else: return tolist() # Handle everything else by returning its repr return repr(o)
def _to_test_data(text): """ Lines should be of this format: <word> <normal_form> <tag>. Lines that starts with "#" and blank lines are skipped. """ return [l.split(None, 2) for l in text.splitlines() if l.strip() and not l.startswith("#")]