content
stringlengths
42
6.51k
def _or(val_a, val_b, default=None): """ Used to allow specifying config values through os.environ Args: val_a: val_b: """ if val_a is not None: return val_a elif val_b is not None: return val_b else: return default
def rsplit_int(s): """ splits off the largest substring of digits from the right a string """ if s and s[-1].isdigit(): x,y = rsplit_int(s[:-1]) return x, y+s[-1] else: return s, ""
def pairwise_prefs_old(A,P,params): # old version of this routine """ Return a dict pref that gives for each pair (i,j) of alternatives from A the count as to how many voters prefer i to j. If params["missing_preferred_less"]==True: A short ballot is interpreted as listing the top alternative...
def min_n_discretes_objective_fn(n_global_discretes, term_width): """The minimal system size RootSolution/Unfold can handle with ObjectiveFns. Args: n_global_discretes: Number of global discretes term_width: The number of neighbouring sites each local operator affects. Returns: The minimum number of ...
def HSBtoRGB( nHue, nSaturation, nBrightness ): """HSB to RGB color space conversion routine. nHue, nSaturation and nBrightness are all from 0.0 to 1.0. This routine returns three integer numbers, nRed, nGreen, nBlue. nRed, nGreen and nBlue are all numbers from 0 to 255. """ # Scale the brightne...
def sum_items_at_even_indices(sequence): """ What comes in: -- A sequence of numbers. What goes out: Returns the sum of the numbers in the list that: -- are at EVEN INDICES. Side effects: None. Examples: sum_items_at_even_indices([3, 10, 6, 5, 5, 10]) returns 3 + ...
def reduce_repetitive_sequence(seq): """Reduces repetitive sequence to shortest non-overlapping repeat pattern Args: seq (str) Returns: min_unit (str) Example: 'AGAGAGAG': repetitive patters are 'AG' and 'AGAG'. this function returns 'AG' """...
def manhattan_distance(x1, x2, y1, y2): """Calculate Manhattan distance between (x1, y1) and (x2, y2). Parameters ---------- x1 : float x-coordinate of the first point. x2: float x-coordinate of the second point. y1: float y-coordinate of the first point. y2: float ...
def make_divisible(v, divisor=8, min_value=3): """ forked from slim: https://github.com/tensorflow/models/blob/\ 0344c5503ee55e24f0de7f37336a6e08f10976fd/\ research/slim/nets/mobilenet/mobilenet.py#L62-L69 """ if min_value is None: min_value = divisor new_v = max(min_val...
def getmatchingfiles(pattern1, pattern2, filelist): """ From a list of files get a new sorted list of files matching both patterns 1 and 2 :param pattern1: :param pattern2: :param filelist: :return: """ return [file for file in sorted(filelist) if pattern1 in file and pattern2 in file]
def joinstr(delim, ls, nl = True): """ Join and map str nl - controls whether a new line is added at the end of the output """ return delim.join(map(str, ls)) + ("\n" if nl else "")
def list_all_source_matched(similar_list): """return a list""" source_paths_matches = [] for item in similar_list: source_paths_matches.append(item["source reference path"]) return source_paths_matches
def _oncofuse_tissue_arg_from_config(data): """Retrieve oncofuse arguments supplied through input configuration. tissue_type is the library argument, which tells Oncofuse to use its own pre-built gene expression libraries. There are four pre-built libraries, corresponding to the four supported tissue t...
def module_exists(module_name): """ :param module_name: name of the module that needs to be checked. :return: True/False based on if the input module exists or not """ try: __import__(module_name) except ImportError: return False else: return True
def streaming_response_type(response_type: str) -> str: """Wrap the given response type with a reader for streaming functions.""" return f"std::unique_ptr<grpc::ClientReader<{response_type}>>"
def human_readable_size(num, suffix="B"): """Bytes to a readable size format""" for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, "Y", suffix)
def is_writable_attr(ext): """Check if an extension attribute is writable. ext (tuple): The (default, getter, setter, method) tuple available via {Doc,Span,Token}.get_extension. RETURNS (bool): Whether the attribute is writable. """ default, method, getter, setter = ext # Extension is w...
def convert_LTRB2QUAD(points): """Convert point format from LTRB to QUAD""" new_points = [points[0], points[1], points[2], points[1], points[2], points[3], points[0], points[3]] return new_points
def hadamard_tensor(qubits): """ Return the algorithm for H^{\otimes num_qubits}. qubits: tuple or list of ints, or an int; if it is an iterable, then it is the qubits to apply the hadamards to. if it is an int, then we apply the hadamards to qubi...
def _dec(fl): """Return a stringified more readable float, for debugging purposes.""" return '{:.2f}'.format(fl)
def quote(str): """Prepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. Does not add the surrounding double quotes. """ return str.replace("\\", "\\\\").replace(...
def get_role(logic_form: str, role_conversions: dict) -> str: """ Get role(s) from keywords in logic form. """ roles = [] for keyword, role in role_conversions.items(): if keyword in logic_form: roles.append(role) return ','.join(roles)
def read_buffer(file_handle, position): """ Reads a buffer, resilient to landing in the middle of a unicode string """ for i in range(1, 7): potential_chunk_end = position - i file_handle.seek(potential_chunk_end) try: next_buffer = file_handle.read(4096) retu...
def rotate_list(l, n): """ Rotate list l so that index n is now first """ return l[n:] + l[:n]
def type_convert(v): """ convert value to int, float or str""" try: float(v) tp = 1 if v.count(".") == 0 else 2 except ValueError: tp = -1 if tp == 1: return int(v) elif tp == 2: return float(v) elif tp == -1: return v else: assert False, "Unkn...
def dict_subset(dic, keys): """Extract subset of keys from dictionary.""" return dict((k, dic[k]) for k in keys if k in dic)
def resolve(var_or_value, ctx): """resolve context""" if var_or_value[0] == '"': return var_or_value[1:-1] return ctx.resolve_variable(var_or_value)
def float_or_none(item): """ Return the float of the value if it's not None """ if item is None: return None else: return float(item)
def format_findings(findings, root): """Format findings.""" for details in findings.values(): tmp_dict = {} for file_meta in details['files']: file_meta['file_path'] = file_meta[ 'file_path'].replace(root, '', 1) file_path = file_meta['file_path'] ...
def diff_2nd_xy(fpp, fpm, fmp, fmm, eps1, eps2): """Evaluates an off-diagonal 2nd derivative term""" return (fpp - fpm - fmp + fmm)/(4.0*eps1*eps2)
def validar_codigo_aplicacion_descuento(codigo_aplicacion, descuento_codigo_aplicacion): """ validar que exista con digo de aplicacion :param codigo_aplicacion: :param descuento_dia_promocion: :return: """ if codigo_aplicacion and descuento_codigo_aplicacion: if codigo_aplicacion == ...
def shout(word): """Return a string with three exclamation marks""" # Concatenate the strings: shout_word shout_word = word + "!!!" # Replace print with return return(shout_word)
def split_input_target(text_sequence): """ :param text_sequence: :param seq_index: :return: """ input_sequence = text_sequence[:-1] target_sequence = text_sequence[1:] return input_sequence, target_sequence
def isNamespace(str): """Determines whether a signature is a namespace. Returns the namespace name or "" if it is no namespace """ pos1 = str.rfind(' ') if pos1 < 0: return "" while (pos1 > 0) and (str[pos1] == ' '): pos1 -= 1 if (pos1 >= 8) and (str[pos1-8:pos1+1] == 'namespace'): ...
def authenticated(handler): """Decorator that checks if there's a user associated with the current session. Will fail if there's no session present. """ def check_authentication(self, *args, **kwargs): auth = self.auth if not auth.get_user_by_session(): self.redirect(self.uri...
def graphstr_to_answer(graph_string): """ input: 'http://project.org/info' output: 'info' """ i = len(graph_string) - 1 while graph_string[i] != '/': i -= 1 return graph_string[i + 1:].replace("_", " ")
def _process_line(line, dictsep, valsep, subsep): """ Process a given line of data using the dictsep, valsep, and subsep provided. For documentation, please see the docstring for ``config()`` """ if dictsep is None: return line, None try: key, val = line.split(dictsep, 1) ex...
def relative_intensity(norm_power, threshold_power): """Relative intensity Parameters ---------- norm_power : number NP or xPower threshold_power : number FTP or CP Returns ------- float IF or RI """ rv = norm_power/threshold_power ...
def update_variance(xdata, length, mean, var_m2): """Update estimate of mean and variance with new observations.""" length = length + 1.0 delta = xdata - mean mean = mean + delta / length var_m2 = var_m2 + delta * (xdata - mean) if length < 2: variance = float('inf') else: va...
def dd_ptv_duration_map_nb(record): """`map_func_nb` that returns duration of the peak-to-valley (PtV) phase.""" return record['valley_idx'] - record['start_idx']
def is_trap(row, i): """Helper function to read out-of-bounds tiles as safe.""" if 0 <= i < len(row): return row[i] return False
def fix_strings(rval): """Convert unicode to strings.""" if isinstance(rval, str): return str(rval) elif isinstance(rval, tuple): return tuple([fix_strings(x) for x in rval]) elif isinstance(rval, list): return [fix_strings(x) for x in rval] elif isinstance(rval, dict): ...
def calc_crc16(message_array): """ CRC16 Algorithm, given an array of "bytes" (8-bit numbers) calculate a CRC16. Polynomial: 0x11021 (17-bits) @param message_array, array of bytes to calculate a CRC16. """ message_length = len(message_array) * 8 # setup initial remainder (17 bits) remain...
def for_type(doc_type): """Determine if this plugin should run for file and/or directory.""" if doc_type in ('file', 'directory'): return True return False
def auto_untype(arg): """ The oposite of auto_type : takes a python base object and tries to convert it to XML typed string. """ if arg is True: return 'TRUE' elif arg is False: return 'FALSE' else: return arg
def replacelast(string, old, new, count = 1): """Replace the last occurances of a string""" return new.join(string.rsplit(old,count))
def fibonacciAtIndex(index): """ Returns the fibonacci number at a given index. Algorithm is using 3 variables instead of recursion in order to reduce memory usage and runtime """ a1, a2 = 1,1 position = 3 # while position <= index: while index > 2: temp = a1 a1 = a2 a2 += temp # position += 1 index -...
def get_ids(mydict,smarts_label): """ Given a dictionary and a value for an item returns all the keys with that value. """ items = mydict.items() ids_list = [] for ids,smarts in items: if smarts == smarts_label: ids_list.append(ids) return ids_list
def est_dans_grille(x, y, grille): """Verifier qu'un couple de coordonnees est dans la grille""" if 0 <= x < len(grille[0]) and 0 <= y < len(grille): return True else: return False
def _int_if_int(x): """ Method to return integer mapped value of x Args: x: (float or int), a number Returns: x: (float), value of x mapped as integer """ if int(x) == x: return int(x) return x
def intToBinary(number, size): """ Converts a decimal number to binary form Parameters: ========== number: Integer The Number to be converted into binary form size: Integer The maximum length of the returning binary list Returns: ======= list: Returns a lis...
def _int8_to_int12(first, second, third=None): """Convert three or two bytes to 12-bit integers.""" if first > 256 or second > 256: raise Exception("More than 8 bits") elif third is not None and third > 256: raise Exception("Third more than 8 bits") byte_1_end = second >> 4 byte_1 =...
def iterable(obj) -> bool: """ Determines if this object satisfies the iterable interface, which requires it to support either ``__iter__`` or ``__getitem__``. """ return hasattr(obj, '__iter__') or hasattr(obj, '__getitem__')
def find_non_numeric(in_col): """ Finds each unique entry in an iterable that cannot be typecast as float and returns a list of those entries. """ non_nums = [] for item in in_col: try: float(item) except: if item not in non_nums: non...
def normalize_grayscale(image_data): """ Normalize the gray scale image data with Min-Max scaling to a range of [0.1, 0.9] :param image_data: The image data to be normalized :return: Normalized image data """ a = 0.1 b = 0.9 grayscale_min = 0 grayscale_max = 255 return a + ( ( (i...
def median(values): """ >>> median([2, 4, 7, 6, 8]) 6 >>> median([2, 4, 6, 8]) 5.0 """ sorted_values = sorted(values) n = len(values) midpoint = n // 2 if n % 2: return sorted_values[midpoint] return ((sorted_values[midpoint - 1] + sorted_values[midpoint]) / 2)
def reset_L_and_R_in_array(edges, lefts): """ Take an array and re-sorts the values in such a way such that: - All "D" values remain in the exact same position - In the remaining spaces, "L" and "R" are sorted starting from the left with all "L" Example ----------- Input: [D, R, R, D, L...
def get_without(list, char="#"): """returns list with elements without char""" s = [] for line in list: if char not in line: s.append(line) return s
def nsf(num, n=1): """n-Significant Figures""" numstr = ("{0:.%ie}" % (n-1)).format(num) return float(numstr)
def tokenize_timeperiod(timeperiod): """ method breaks given timeperiod into 4 parts: (year, month, day, hour) for instance: daily 2015031400 -> ('2013', '03', '14', '00') hourly 2015031413 -> ('2013', '03', '14', '13') monthly 2015030000 -> ('2013', '03', '00', '00') ...
def groupify(data): """ Takes a dict with groups identified by ./ and turns it into a nested dict """ new = {} for key in data.keys(): if "./" in key: group, field = key.split("./") if group not in new: new[group] = {} new[group][field] = d...
def snKey(pre, sn): """ Returns bytes DB key from concatenation of qualified Base64 prefix bytes pre and int sn (sequence number) of event """ if hasattr(pre, "encode"): pre = pre.encode("utf-8") # convert str to bytes return (b'%s.%032x' % (pre, sn))
def pointsToCoordinatesAndPropertiesFileNames(filename, propertiesPostfix = '_intensities', **args): """Generates a tuple of filenames to store coordinates and properties data separately Arguments: filename (str): point data file name propertiesPostfix (str): postfix on file name to indicat...
def _unicode_char(char): """ Returns true if character is Unicode (non-ASCII) character """ try: char.encode('ascii') except UnicodeDecodeError: return True return False
def inclusion_no_params_with_context(context): """Expected inclusion_no_params_with_context __doc__""" return {"result": "inclusion_no_params_with_context - Expected result (context value: %s)" % context['value']}
def sort_words_case_insensitively(words): """Sort the provided word list ignoring case, and numbers last (1995, 19ab = numbers / Happy, happy4you = strings, hence for numbers you only need to check the first char of the word) """ word = sorted([word for word in words if word[0].isalpha()], ke...
def set_identifiers(database, group_by_attributes, identifier_name): """Sets a group-identifier based on a given set of attributes. Modifies the database but also returns a list of unique identifiers.""" identifiers = [] for section in database["sections"]: identifier = [] for attribute ...
def quantize_number(x, prec=2, base=.05): """ Quantize a number. This function sometimes gives rounding errors, because of imperfect float representation. This is not critical as people should enter grades already rounded to the correct decimals. And check the grade given afterwards. It might be...
def javaVarName(name): """Make a name like "asdf_adsf" into camel case at the locations of "_" and start with a lowercase letter.""" while "_" in name: idx = name.index("_") name = name[:idx]+name[idx+1:idx+2].upper()+name[idx+2:] #return name[0].lower()+name[1:] # allow user to actually spe...
def _compressed_name_to_c_string(compressed_name: str) -> str: """Convert a compressed name (with fragment references) to a string that the C++ compiler will accept. The primary reason for this function is because the hex escape sequence (\\xHH) in C/C++ has no length limit, so will happily run into the...
def combine_log_messages(msg): """ """ # throw out all empty ones msg = [x.strip() for x in msg if x] # combine again msg = "\r\n".join(msg) return msg
def normalizeStr(input): """ Normalizes the style of input """ try: return str(input).lower().strip().replace(' ', '_') except: return input
def escape(identifier, ansi_quotes, should_quote): """ Escape identifiers. ANSI uses single quotes, but many databases use back quotes. """ if not should_quote(identifier): return identifier quote = '"' if ansi_quotes else '`' identifier = identifier.replace(quote, 2*quote) re...
def check_only_strings_in_list_util(mflags, args_list): """Utility function for testing regular expressions used in argument parsing Tests if all space-separated values in mflags are in args_list and that there are no extra entries in args_list. If either of these tests fail, we return false. :par...
def lat_opposite(side): """ Returns the lateral opposite as defined by the keyword pair {"Right", "Left"} """ if side == 'Right': return 'Left' elif side == 'Left': return 'Right' else: raise ValueError("Lateral side error, (%s)" % side)
def int_from_bits(*bit_pos): """Combine the given bit positions as an integer where the given bit positions are set to 1. Bit positions start at 0. Args: *bit_pos (tuple/int): Tuple of integer bit positions where the bit positions start at 0. Returns: bits (int): Integer with the bit...
def _LJ_ab_to_epsilonsigma(coeffs): """ Convert AB representation to epsilon/sigma representation of the LJ potential """ if (coeffs['A'] == 0.0 and coeffs['B'] == 0.0): return {"sigma": 0.0, "epsilon": 0.0} try: sigma = (coeffs['A'] / coeffs['B'])**(1.0 / 6.0) epsilon =...
def fib(n: int) -> int: """ Fibonacci :param n: a number :return: Fibonacci of n """ if n < 2: return n else: return fib(n - 1) + fib(n - 2)
def get_commands(slaves): """Depending on OS, yield the proper nuke-and-pave command sequence.""" commands = {} for slave in slaves['win']: def cmd(command): return 'cmd.exe /c "%s"' % command def cygwin(command): return 'c:\\cygwin\\bin\\bash --login -c "%s"' % ( command.replace('"'...
def check_if_list_valid(items, content_type): """ Check if the passed items list is valid, Valid if length is greater than one. :param items: Items to check :param content_type: Type of content to parse :return: """ if len(items) < 1: return False else: return True
def rosenbrock(x, y): """ Rosenbrock function. Minimum: f(1, 1) = 0. https://en.wikipedia.org/wiki/Rosenbrock_function """ return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
def secondsToTime(seconds, outToString=False): """ Description: Function to write a duration in days, hours, minutes, seconds as a function of seconds. Parameters: - seconds: number of seconds to convert. - outToString: a flag (see below). Return: - a tuple (days,...
def TransformName(r, undefined=''): """Returns a resorce name from an URI. Args: r: JSON-serializable object. undefined: Returns this value if the resource cannot be formatted. Returns: A project name for selfLink from r. """ if r: try: return r.split('/')[-1] except AttributeError...
def distance_between_points(first_point, second_point): """ Calculates the Distance between 2 points. (x^2 + y^2) ^ 0.5 :param first_point: tuple of x and y value of point 1 :param second_point: tuple of x and y value of point 2 :return: Float value of the distance between the 2 points :rtype: ...
def _get_value(haystack, needles, missing_value=None): """ Safely traverses a many-level dictionary and returns the key value. Args: haystack (Dict) -- the thing we want to traverse needles (List of str or num) -- the traversal path through the haystack. The last item on the list is the ke...
def avg_salaries(departments, employees): """ Function calculating average salary of every department :param departments: list of departments in the db :param employees: list of employees in the db :return: dnt_salary: the dictionary of names of departments as keys and average salaries as values ...
def format_time(time_to_go): """Return minutes and seconds string for given time in seconds. :arg time_to_go: Number of seconds to go. :returns: string representation of how much time to go """ if time_to_go < 60: return '%ds' % time_to_go return '%dm %ds' % (time_to_go / 60, time_to_...
def get_data(event): """Returns the data property in a given event. :type event: dict :param event: event from CodePipeline. :rtype: dict :return: data property in ``event``. :raises KeyError: if ``event`` does not have a necessary property. """ return event['CodePipeline.job']['data'...
def trunc_text(input_text: list, length: list) -> list: """ Truncating the input text according to the input length. :param input_text: The input text need to be truncated. :param length: The length used to truncated the text. :return: The truncated text. """ return [row[:length[idx]] for i...
def f1_score(y_pred, y_true, average="micro"): """ F1 score for multi-label task @param y_pred: a list of list, each list item is a multi-label prediction @param y_true: a list of list, each list item is a multi-label gold result @param average: the average method, only micro and macro are supp...
def get_student_json(student): """This method returns the JSON of the student object""" student_json = { 'userid': student[0], 'username': student[1], 'type': student[2], 'userscore': student[3], 'age': int(student[4]), 'gender': student[5], 'gradlevel': ...
def levenshtein_distance(a,b): """ Calculates the Levenshtein distance between a and b. Written by Magnus Lie Hetland. """ n, m = len(a), len(b) if n > m: a,b = b,a n,m = m,n current = list(range(n+1)) for i in range(1,m+1): previous, current = current, [i]+[0]*m...
def cstring(string): """Extracts a null-terminated string from a byte array.""" return string.decode('utf-8').split('\0', 1)[0]
def naive_search(text, pattern): """ Naive string matching implementation. Runtime: - Best Case = Average Case: O(n) the first character does not match every time - Worst Case: O(n * m) Each time all characters match except the last :param text: text to be searched :type text: str :pa...
def lorentzian(x, w, e): """ An elementary Lorentzian """ return 1.0/(x-w+1j*e) - 1.0/(x+w+1j*e);
def fish(fs): """ Transform a list of fish represented by their time-to-spawn state into a list of the number of fish in each state indexed by their time-to-spawn. Under this strategy, the example input [3, 4, 3, 1, 2] would be transformed into [0, 1, 1, 2, 1, 0, 0, 0, 0]. """ fis = [0] * 9...
def is_custom_resource(resource_type): """ Return True if resource_type is a custom resource """ return resource_type and (resource_type == 'AWS::CloudFormation::CustomResource' or resource_type.startswith('Custom::'))
def _test(n, base, s, t): """Miller-Rabin strong pseudoprime test for one base. Return False if n is definitely composite, True if n is probably prime, with a probability greater than 3/4. """ # do the Fermat test b = pow(base, t, n) if b == 1 or b == n - 1: return True else: ...
def sieve(n): """Sieve away and only primes are left.""" primes = 2 * [False] + (n - 1) * [True] for i in range(2, int(n**0.5+1)): for j in range(i*i, n+1, i): primes[j] = False return [prime for prime, checked in enumerate(primes) if checked]
def pluralise_unit(unit, value): """ Modify units given from the API to include an 's' if the value is not singular. Units require an (s) at the end of their names to use this functionality. """ is_singular = value == "1" if "(s)" in unit: if is_singular: return uni...