content
stringlengths
42
6.51k
def find_first(searched, vec): """return the index of the first occurence of item in vec""" for i, item in enumerate(vec): if searched == item: return i return -1
def get_funcobj(func): """ Return an object which is supposed to have attributes such as graph and _callable """ if hasattr(func, '_obj'): return func._obj # lltypesystem else: return func
def get_set_intersection(list_i, list_j): """ Get the intersection set Parameters ---------- list_i, list_j: list two generic lists Returns ------- intersection_set: set the intersection of list_i and list_j """ set_i = set(list_i) set_j = set(list_j) interse...
def list_to_space_str(s, cont=('{', '}')): """Convert a set (or any sequence type) into a string representation formatted to match SELinux space separated list conventions. For example the list ['read', 'write'] would be converted into: '{ read write }' """ l = len(s) str = "" if l < 1:...
def apply_transform(coords, trans): """transform coordinates according""" coords = [((x - trans[0]) / trans[1], (y - trans[3]) / trans[5]) for x, y in coords] return coords
def calc_target_angle(mean_bolds, median_angles): """ Calculates a target angle based on median angle parameters of the group. Parameters ---------- mean_bolds : list (floats) List of mean bold amplitudes of the group median_angles : list (floats) List of median angles o...
def is_valid_furl(furl): """Is the str a valid FURL or not.""" if isinstance(furl, str): if furl.startswith("pb://") or furl.startswith("pbu://"): return True else: return False else: return False
def format_includes(includes: list) -> str: """Format includes into the argument expected by GCC""" return " ".join([f"-I{path}" for path in includes])
def get_color(node, color_map): """ Gets a color for a node from the color map Parameters -------------- node Node color_map Color map """ if node in color_map: return color_map[node] return "black"
def extrae_coords_atomo(res,atomo_seleccion): """ De todas las coordenadas atomicas de un residuo, extrae las de un atomo particular y devuelve una lista con las X, Y y Z de ese atomo.""" atom_coords = [] for atomo in res.split("\n"): if(atomo[12:16] == atomo_seleccion): atom_coords = [ float(atomo[30:38]),...
def read_file(input_data): """ Function reads the input signal data and filters it to check if given input lines are valid. If some element in read line is invalid, the function will raise an Error :param input_data: single string read from standard input :return: single list of five strings with f...
def basecount(seq): """Count the frequencies of each bases in sequence""" freq = {} for base in seq: if base in freq: freq[base] += 1 else: freq[base] = 1 return freq
def size_of_row_in_file(row): """ Returns the approximate amount of bytes originally used to represent the given row in its CSV file. It assumes the delimiter uses only one byte. I also ignores quotes (-2 bytes) around escaped cells if they were originally present. I also don't think that it c...
def filter_languages(project_list, languages_set): """ Filter the project list to contain only the languages in the languages_set """ filtered_projects = [] for project in project_list: if project["repository_language"] in languages_set: filtered_projects.append(project) return filtered_projects
def split_kv(text_pair, sep): """Helper.""" try: key, value = text_pair.split(sep, 1) except TypeError: return None, text_pair except ValueError: return None, text_pair if not key: return None, None return key, value
def score(board, n): """ Calculate score. Inputs: board, a list of dictionaries. n, an int. Returns: an int. """ return sum(k for row in board for k, v in row.items() if not v) * n
def residueCenterAtomList(resName): """ Creates a list of atom names that constitutes the 'residue center' """ names = {} names["GLU"] = ["OE1", "OE2"] names["ASP"] = ["OD1", "OD2"] names["HIS"] = ["CG" , "ND1", "CD2", "NE2", "CE1"] names["CYS"] = ["SG"] names["TYR"] = ["OH"] nam...
def categorize_by_mortality(hurricanes): """Categorize hurricanes by mortality and return a dictionary.""" mortality_scale = {0: 0, 1: 100, 2: 500, 3: 1000, 4: 10000} hurricanes_by_mortality = {0:[],1:[],2:[],3:[],4:[],5:[]} for cane in hurrica...
def to_hsl(color: tuple) -> tuple: """Transforms a color from rgb space to hsl space. Color must be given as a 3D tuple representing a point in rgb space. Returns a 3D tuple representing a point in the hsl space. Saturation and luminance are given as floats representing percentages with a precisio...
def is_duplicate(s): """ Return True if the string 'Possible Duplicate is in string s or False, otherwise.' :param s: :return: """ return 'Possible Duplicate:' in s
def lengthOfLongestSubstring(s): """ :type s: str :rtype: int """ n= len(s) longest_substr="" max_length= 0 for i in range(n): seen={} current_length=0 for j in range(i,n): substr=s[i:j+1] if s[j] in seen: break ...
def is_device(lib_name): """return true if given name is associated with a device""" return lib_name.endswith(".device")
def get_last_name(full_name: str) -> str: """Get the last name from full name. Args: full_name: The full official name. Return: The last name in title case format. """ return full_name.split(' ')[-1].title()
def feuler(f, t, y, dt): """ Forward-Euler simplest possible ODE solver - 1 step. :param f: function defining ODE dy/dt = f(t,y), two arguments :param t: time :param y: solution at t :param dt: step size :return: approximation of y at t+dt. """ return y + dt * f(t, y)
def length_error_message(identifier, min_length=None, max_length=None): """Build length error message.""" additional = [] if min_length: additional.append('at least length {}'.format(min_length)) if max_length: additional.append('at most length {}'.format(max_length)) body = ', '...
def weight_to_duro(weight, boardside=True): """ Takes a weight in KG and returns an appropriate duro bushing. """ bushings = [78, 81, 85, 87, 90, 93, 95, 97] if not boardside: weight -= 5 weight -= 40 if weight < 0: weight = 0 approx_duro = ((weight) ** 0.66 ) + 79 duro = min(bushings, k...
def job_id_from_reponse(text): """Return a string representation of integer job id from the qsub response to stdout""" # # The output from SGE is of the form # "Your job 3681 ("TEST") has been submitted" # Your job-array 4321.1-3:1 ("wrfpost") has been submitted # job_id = text.spl...
def validate_cli(cli_string, expect=[], reject=[], ignore=[], retval=0, *args, **kwargs): """ Used to mock os.system with the assumption that it is making a call to 'conda-build'. Args: cli_string: The placeholder argument for the system command. expect: A list of strings that must occur in...
def replace_text(text, variables): """ Replace some special words in text to variable from dictionary @param text: raw text @param variables: dictionary of variables for replace """ for name, value in variables.items(): text = text.replace('#%s#' % name, str(value)) return text
def fib_recursiva(number): """Fibonnaci recursiva.""" if number < 2: return number return fib_recursiva(number - 1) + fib_recursiva(number - 2)
def diff_two_lists(first, second): """Create new list with diffs between two other lists.""" assert len(first) == len(second) return [x - y for x, y in zip(first, second)]
def kolmogorov_53(k, k0=50): """ Customizable Kolmogorov Energy spectrum Returns the value(s) of k0 * k^{-5/3} Parameters ---------- k: array-like, wavenumber: convention is k= 1/L NOT 2pi/L k0: float, coefficient Returns ------- e_k: power-law spectrum with exponent -5/3 for a...
def get_tag_groups_names(tag_groups: list) -> list: """ Returns the tag groups as a list of the groups names. Args: tag_groups: list of all groups Returns: The tag groups as a list of the groups names """ # tag_groups is a list of dictionaries, each contains a tag group name and...
def get_refresh_delay(elapsed: float) -> float: """Returns delay to wait for to store info. The main goal of this method is to avoid to have too low resolution in the very fast benchmarks, while not having gigantic log files in the very slow benchmarks. Parameters -------------------------...
def convert_16bit_pcm_to_byte(old_value: int) -> int: """Converts PCM value into a byte.""" old_min = -32768 # original 16-bit PCM wave audio minimum. old_max = 32768 # original 16-bit PCM wave audio max. new_min = 0 # new 8-bit PCM wave audio min. new_max = 255 # new 8-bit PCM wave audio max. byte_val...
def _parse_size(size_str): """Parses a string of the form 'MxN'.""" m, n = (int(x) for x in size_str.split('x')) return m, n
def json_authors_to_list(authors): """ Take JSON formatted author list from CrossRef data and convert to string in the same format as the search. """ match_authors = [] for author in authors: try: given = author['given'] except: given = '' try: ...
def _calc_prob_from_all(prob): """This can be used to detect insects when ldr is not available.""" return prob['z'] * prob['temp_strict'] * prob['v'] * prob['width']
def parse_int_set(nputstr=""): """Return list of numbers given a string of ranges http://thoughtsbyclayg.blogspot.com/2008/10/parsing-list-of-numbers-in-python.html """ selection = set() invalid = set() # tokens are comma separated values tokens = [x.strip() for x in nputstr.split(',')] ...
def getextension(filename): """ uses file name to get extension :param filename: :return: """ a = filename.rfind('.') return filename[a:]
def get_key_from_dimensions(dimensions): """ Get a key for DERIVED_UNI or DERIVED_ENT. Translate dimensionality into key for DERIVED_UNI and DERIVED_ENT dictionaries. """ return tuple(tuple(i.items()) for i in dimensions)
def get_first_guess_coordinates_product(commands): """Get result of multiplying a final horizontal position by a final depth received by straightforward approach; commands(list of list[direction(str), steps(int)]): instructions""" hor = 0 dep = 0 for com in commands: if com[0] == "up": ...
def duration_to_str(duration): """Converts a timestamp to a string representation.""" minutes, seconds = divmod(duration, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) duration = [] if days > 0: duration.append(f'{days} days') if hours > 0: duration.append(f'{hour...
def is_sequence(obj): """Check if object has an iterator :param obj: """ return hasattr(obj, '__iter__')
def sol(mat, m, n): """ Traverse column from the end if 1 is the value increase counter else switch to next row """ c = 0 j = n-1 i = 0 while i < m and j > -1: if mat[i][j] == 1: c = i j-=1 else: i+=1 return c
def fibonacci(n): """ :param n: :return: return the n-th Fibonacci number """ if n in (0,1): return n return fibonacci(n-2)+fibonacci(n-1)
def jwt_get_username_from_payload_handler(payload): """ Override this function if username is formatted differently in payload """ return payload.get('username')
def check_size(fsize, minsize): """Ensure that the filesize is at least minsize bytes. @param fsize the filesize @param minsize the minimal file size @return fsize >= minsize """ if fsize < minsize: print("Input file too small: %i instead of at least %i bytes." % ( ...
def get_size(bytes): """ Convert Bytes into Gigabytes 1 Gigabytes = 1024*1024*1024 = 1073741824 bytes """ factor = 1024 ** 3 value_gb = bytes / factor return value_gb
def apply_gain_x2(x, AdB): """Applies A dB gain to x^2 """ return x*10**(AdB/10)
def get_request_attribute(form_data, key, default=''): """ """ if key not in form_data: return '' return form_data[key]
def hexinv(hexstring): """ Convenience function to calculate the inverse color (opposite on the color wheel). e.g.: hexinv('#FF0000') = '#00FFFF' Parameters ---------- hexstring : str Hexadecimal string such as '#FF0000' Returns ------- str Hexadecimal string suc...
def IS_STR(v): """Check if the given parameter is an instance of ``str``.""" return isinstance(v, str)
def str_to_id(string, block): """Converts a string to a tuple-based id Args: string (str): Length is N*block, where each block is an int with leading zeros. block: Length of each block. Each block is an int with leading zeros. >>> str_to_id('000003000014000005', block=6) (3, 14, 5) ...
def pretty_string(name_list): """ Make a string from list of some names :param name_list: list of names [name#0, name#1, ...] :return: string in format: -name#0 -name#1 """ output_string = '' for s in name_list: output_string += '\n -' + s return output_st...
def _get_symbolic_filepath(dir1: str, dir2: str, file_name: str) -> str: """ Transform a path like: /Users/saggese/src/...2/amp/vendors/first_rate/utils.py into: $DIR1/amp/vendors/first_rate/utils.py """ file_name = file_name.replace(dir1, "$DIR1") file_name = file_name.replace(d...
def check_in_org(entry, orgs): """ Obtain the organization from the entry's SSL certificate. Determine whether the org from the certificate is in the provided list of orgs. """ if "p443" in entry: try: value = entry["p443"]["https"]["tls"]["certificate"]["parsed"]["subject"]["org...
def map_init(interface, params): """Intialize random number generator with given seed `params.seed`.""" import numpy as np import random np.random.seed(params['seed']) random.seed(params['seed']) return params
def create_incremented_string(forbidden_exprs, prefix = 'Dummy', counter = 1): """This function takes a prefix and a counter and uses them to construct a new name of the form: prefix_counter Where counter is formatted to fill 4 characters The new name is checked against a list of forbidden e...
def normalize(chromosome): """Make all probabilities sum to one.""" total = sum(chromosome.values()) return {card: probability / total for card, probability in chromosome.items()}
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'): """Converts an integer to a base36 string.""" if not isinstance(number, int): raise TypeError('number must be an integer') base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 <...
def inner_vertices(ver_dic, edg_dic): """ makes a list of inner vertex indeces """ inner=[] for ind in ver_dic: if len([k for (k, v) in edg_dic.items() if v.count(ind)==1])>1: inner.append(ind) return inner
def join(r_zero, r_one): """ Take(x, y, w, [h]) squares """ if not r_zero: return r_one if not r_one: return r_zero if not r_zero and not r_one: return None if len(r_zero) == 3: r_zero = (r_zero[0], r_zero[1], r_zero[2], r_zero[2]) if len(r_one) == 3: r_...
def manhattan_cost(curr, end): """ Estimates cost from curr (x0,y0) to end (x1,y1) using Manhattan distance. """ curr_x, curr_y = curr end_x, end_y = end return abs(curr_x-end_x) + abs(curr_y-end_y)
def get_lines_for(identifier, module_lines, block_type): """ Extract a Python value definition (list, tuple, dict) in Python code (such as the settings file), and return its content as a list of strings. Return an empty list if not found. """ delimiters_for = { str: ('', '\n'), l...
def get_prefered_quotation_from_string(string): """ Tries to determin the quotation (`"` or `'`) used in a given string. `"` is the default and used when no quotations are found or the amount of `"` and `'` are equal """ return "'" if string.count("'") > string.count('"') else '"'
def get_connection_name(connection_id, friend_list): """ Given a mutual friends' ID, check the given list of Facebook friends and extract the name. :param connection_id: Connection's (mutual friend) Facebook ID. :type connection_id: str :param friend_list: List ...
def _clip(n: float) -> float: """ Helper function to emulate numpy.clip for the specific use case of preventing math domain errors on the acos function by "clipping" values that are > abs(1). e.g. _clip(1.001) == 1 _clip(-1.5) == -1 _clip(0.80) == 0.80 """ sign = n / abs(n...
def validate_month(value): """ Function to validate the zodiac sign month Args: value (str): zodiac sign month to be validated Raises: (ValueError): Raise ValueError if the zodiac sign month invalid Return: value (str): valid zodiac sign month """ month = "" try: ...
def Unindent(string, spaces=2): """ Returns string with each line unindented by 2 spaces. If line isn't indented, it stays the same. >>> Unindent(" foobar") 'foobar\\n' >>> Unindent("foobar") 'foobar\\n' >>> Unindent('''foobar ... foobar ... foobar''') 'foobar\\nfoobar\\nfoobar\\n' """ newstring = '' ...
def find_first_slice_value(slices, key): """For a list of slices, get the first value for a certain key.""" for s in slices: if key in s and s[key] is not None: return s[key] return None
def _to_str(val): """Safe conversion.""" if val.strip() == "": return None return val.strip()
def soloList(data, index): """convert all values in a index in a list to a single list""" x = [] for i in data: x.append(i[index]) return x
def get_factors(n): """Return a list of the factors of a number n. Does not include 1 or the number n in list of factors because they're used for division questions. """ factors = [] for i in range(2, n): if n % i == 0: factors.append(i) return factors
def hidden_vars(vrs): """Slice dictionary `vrs`, keeping keys matching `_*`.""" return {k: v for k, v in vrs.items() if k.startswith('_')}
def cc_colors(coord, lighness=0): """Predefined CC colors.""" colors = { "A": ["#EA5A49", "#EE7B6D", "#F7BDB6"], "B": ["#B16BA8", "#C189B9", "#D0A6CB"], "C": ["#5A72B5", "#7B8EC4", "#9CAAD3"], "D": ["#7CAF2A", "#96BF55", "#B0CF7F"], "E": ["#F39426", "#F5A951", "#F8BF7D"],...
def create_json_from_stories(stories_and_location): """ Convert the preprocessed stories into a list of dictionaries. This will help us with making the 3d visualizations """ stories = [] for story, location, link, geo_coordinates, category, img_url, summary in stories_and_location: story_dict = {} story...
def ctoa(character: str) -> int: """Find the ASCII value of character. Uses the ord builtin function. """ code = ord(character) return code
def _solve_dependencies(dependencies, all_members=None): """Solve a dependency graph. :param dependencies: dependency dictionary. For each key, the value is an iterable indicating its dependencies. :param all_members: If provided :return: list of sets, each containing independe...
def clean_completion_name(name: str, char: str) -> str: """Clean the completion name, stripping bad surroundings 1. Remove all surrounding " and '. For """ if char == "'": return name.lstrip("'") if char == '"': return name.lstrip('"') return name
def single_l1(value_1, value_2): """ compute L1 metric """ return abs(value_1 - value_2)
def un_pad(word): """ Removes additional padding from string :param word: <string> :return: string after removing padding from it <string> """ padding_length = ord(word[len(word) - 1:]) un_padded_word = word[:-padding_length] return un_padded_word
def make_symmetry_matrix(upper_triangle): """ Make a symmetric matrix from a list of integers/rationals. """ length = len(upper_triangle) if length not in (3, 6, 10): raise ValueError("the length of the coxeter diagram must be 3 or 6 or 10.") if length == 3: a12, a13, a23 = uppe...
def scale_reader_decrease(provision_decrease_scale, current_value): """ :type provision_decrease_scale: dict :param provision_decrease_scale: dictionary with key being the scaling threshold and value being scaling amount :type current_value: float :param current_value: the current consumed ...
def flat(_list): """ [(1,2), (3,4)] -> [1, 2, 3, 4]""" res = [] for item in _list: res.extend(list(item)) return res
def rk4(y, f, t, h): """Runge-Kutta RK4""" k1 = f(t, y) k2 = f(t + 0.5*h, y + 0.5*h*k1) k3 = f(t + 0.5*h, y + 0.5*h*k2) k4 = f(t + h, y + h*k3) return y + h/6 * (k1 + 2*k2 + 2*k3 + k4)
def id_mapping(IDs1, IDs2, uniq_ref_only=True, IDs2_sorted=False): """ Mapping IDs2 to IDs1. IDs1 (ref id) can have repeat values, but IDs2 need to only contain unique ids. Therefore, IDs2[rv_idx] will be the same as IDs1. Parameters ---------- IDs1 : array_like or list ids for...
def start_of_chunk(prev_tag, tag, prev_type, type_): """Checks if a chunk started between the previous and current word. Args: prev_tag: previous chunk tag. tag: current chunk tag. prev_type: previous type. type_: current type. Returns: chunk_start: boolean. """...
def get_compound_type(compound_types): """Returns mcf value format of the typeOf property for a compound. This is applied to the 'Type' entry of each row of drugs_df. Args: compound_types: string of comma separated list of type values Returns: If the compound is of a drug type, then t...
def containsAny(str, set): """ Check whether sequence str contains ANY of the items in set. """ return 1 in [c in str for c in set]
def determine_pos_neu_neg(compound): """ Based on the compound score, classify a sentiment into positive, negative, or neutral. Arg: compound: A numerical compound score. Return: A label in "positive", "negative", or "neutral". """ if compound >= 0.05: return 'positive' ...
def first_dup(s): """ Find the first character that repeats in a String and return that character. :param s: :return: """ for char in s: if s.count(char) > 1: return char return None
def binary_search_iterative(arr, val, start, end): """searches arr for val. Parameters: arr (array): array to search. val (type used in array): value to search for in arr. Returns: (int) : index of val in arr if val is found. Otherwise returns -1 if val cannot be fo...
def _normalize_image_location_for_db(image_data): """ This function takes the legacy locations field and the newly added location_data field from the image_data values dictionary which flows over the wire between the registry and API servers and converts it into the location_data format only which i...
def reformat(formula): """Add spaces around each parens and negate and split the formula.""" formula = ''.join(f' {i} ' if i in '~()' else i for i in formula) return formula.split()
def _get_percentage_difference(measured, base): """Return the percentage delta between the arguments.""" if measured == base: return 0 try: return (abs(measured - base) / base) * 100.0 except ZeroDivisionError: # It means base and only base is 0. return 100.0
def repo_name(url): """Normalize repository name from git url.""" data = url.rstrip('/').split('/')[-2:] return '__'.join(data)
def make_word_groups(vocab_words): """ :param vocab_words: list of vocabulary words with a prefix. :return: str of prefix followed by vocabulary words with prefix applied, separated by ' :: '. This function takes a `vocab_words` list and returns a string with the prefix and the words...
def get_by_dotted_path(d, path, default=None): """ Get an entry from nested dictionaries using a dotted path. Example: >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a') 12 """ if not path: return d split_path = path.split('.') current_option = d for p in split_path: ...
def get_id(record): """Get the Id out of a VPC record. Args: record A VPC record returned by AWS. Returns: The VPC's ID. """ return record["VpcId"]