content
stringlengths
42
6.51k
def hadamard_complex(x_re, x_im, y_re, y_im): """Hadamard product for complex vectors""" result_re = x_re * y_re - x_im * y_im result_im = x_re * y_im + x_im * y_re return result_re, result_im
def render_pep440(vcs): """Convert git release tag into a form that is PEP440 compliant.""" if vcs is None: return None tags = vcs.split('-') # Bare version number if len(tags) == 1: return tags[0] else: return tags[0] + '+' + '.'.join(tags[1:])
def check_answer(guess, answer, turns): """checks answer against guess. Returns the number of turns remaining.""" if guess > answer: print("Too high.") return turns - 1 elif guess < answer: print("Too low.") return turns - 1 else: print(f"You got it! The answer was {answer}.")
def twosComp(val, bits): """compute the 2's complement of int value val""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val # return positive value as is
def _earliest_run_start( prev1_start, prev1_haplo, curr1_haplo, prev2_start, prev2_haplo, curr2_haplo): """ find the earliest "prev start" such that the "prev" and "curr" haplos match """ earliest_start = None if prev1_haplo == curr1_haplo: earliest_start = prev1_start ...
def gcd(a, b): """Finding the greatest common divisor""" assert int(a) == a and int(b) == b, 'The numbers must be integers only' if a < 0: a = -1*a if b < 0: b = -1*b if b == 0: return a else: return gcd(b, a%b)
def lerpv3(a,b,t): """linear interplation (1-t)*a + (t)*b""" return ( (1-t)*a[0] + (t)*b[0], (1-t)*a[1] + (t)*b[1], (1-t)*a[2] + (t)*b[2] )
def maximize(low, high, objective, stop): """ Find the scalar argument which maximizes the objective function. The search space is bounded to the closed interval [low, high]. input: low: the lower bound of the search interval high: the upper bound of the search interval objective: an objective func...
def column(matrix, i): """ Gets column of matrix. INPUTS: Matrix, Int of column to look at RETURNS: Array of the column """ return [row[i] for row in matrix]
def _dtree_filter_comp(dtree_data, filter_key, bin_class_type): """ List comprehension filter helper function to filter the data from the `get_tree_data` function output Parameters ---------- dtree_data : dictionary Summary dictionary output...
def get_forward_kin(var_name): """ Function that returns UR script for get_forward_kin(). Transformation from joint space to tool space. Args: var_name: String. name of variable to store forward kinematics information Returns: script: UR script """ return "%s = get_forward_kin(...
def to_lower_case(s): """ transform a unicode string 's' to lowercase ok, this one is trivial, I know """ return s.lower()
def format_bids_name(*args): """ write BIDS format name (may change this later) :param args: items to join :return: name """ return ("_").join(args)
def find_workexperience_line_indexes_in_resume_object(parsed_resume_no_empty_lines, filtered_resume_info): """Finds the first and last indexes in resume_object, where the lines correspond to the work_experience. Returns the index if found, else None.""" we_first_line_text = "" if not parsed_resume_no_empty_...
def get_aF(r1_norm, r2_norm): """ Computes the semi-major axis of the fundamental ellipse. This value is kept constant for all the problem as long as the boundary conditions are not changed. Parameters ---------- r1_norm: float Norm of the initial vector position. r2_norm: float...
def line_sep_before_code(ls): """for markdown""" r, is_code = [], False for ln in ls: if not is_code: if ln.startswith(' '): r.append('') is_code = True else: if not ln.startswith(' '): is_code = False r.ap...
def munge_pair(pair): """ Convert integer values to integers """ name, value, offset = pair if name in ['secure-mode', 'keep-pwd']: value = ord(value) return (name, value, offset)
def clean_web_text(st): """Clean text.""" st = st.replace("<br />", " ") st = st.replace("&quot;", '"') st = st.replace("<p>", " ") if "<a href=" in st: while "<a href=" in st: start_pos = st.find("<a href=") end_pos = st.find(">", start_pos) if end_pos !=...
def subtract_lists(x,y): """Subtract Two Lists (List Difference)""" return [item for item in x if item not in y]
def _get_recursive_config_key(config, key): """ Get the config value identified by the list of nested key values. :param config: Configuration dictionary. :param key: List of nested keys (in-order) for which the value should be retrieved. :return: The value in the configuration dictionary correspon...
def sort_group(indx, column1, column2): """ Parameters ---------- indx : integer column1 : list data type (contains strings of SOC NAMES / WORK STATES which need to be ordered.) column2 : list data type (contains integers which denote numbers of of certified applications.) Returns ------- sort_group : l...
def create_dico(item_list): """ Create a dictionary of items from a list of list of items. """ assert type(item_list) is list dico = {} for items in item_list: for item in items: if item not in dico: dico[item] = 1 else: ...
def seconds_to_timestamps(seconds): """Return a dict of timestamp strings for the given numnber of seconds""" m, s = divmod(seconds, 60) h, m = divmod(m, 60) hms_parts = [] if h: hms_parts.append('{}h'.format(h)) if m: hms_parts.append('{}m'.format(m)) if s: hms_parts...
def strtoint(value): """Cast a string to an integer.""" if value is None: return None return int(value)
def rest_api_parameters(in_args, prefix='', out_dict=None): """Transform dictionary/array structure to a flat dictionary, with key names defining the structure. Example usage: >>> rest_api_parameters({'courses':[{'id':1,'name': 'course1'}]}) {'courses[0][id]':1, 'courses[0][name]':'course1'} ...
def get_year_from_date_sk(date_sk): """ Return year from integer date in form YYYYMMDD. date_sk: Integer date in form YYYYMMDD """ return int(date_sk / 10000)
def generate_year_list(start, stop=None): """ make a list of column names for specific years in the format they appear in the data frame start/stop inclusive """ if isinstance(start, list): data_range = start elif stop: data_range = range(start, stop+1) else: da...
def is_float(s): """ Returns True if the given string is a float, False otherwise :param s: str :return: bool """ try: a = float(s) except (TypeError, ValueError): return False else: return True
def is_nested_list(mlist): """Is a list nested? Args: l ([list]): A Python list. Returns: [bool]: 1 is is a nested list, 0 is not and -1 is not a list. Examples: >>> from ee_extra import is_nested_list >>> is_nested_list([1,2,3]) >>> # 0 >>> is_nested_l...
def bin_digit(t, i): """Returns the ith digit of t in binary, 0th digit is the least significant. >>> bin_digit(5,0) 1 >>> bin_digit(16,4) 1 """ return (t >> i) % 2
def get_positions(start_idx, end_idx, length): """ Get subj/obj position sequence. """ return list(range(-start_idx, 0)) + [0]*(end_idx - start_idx + 1) + \ list(range(1, length-end_idx))
def is_untracked2(untracked_files): """Function: is_untracked2 Description: Method stub holder for git.Repo.git.is_untracked(). Arguments: """ status = False if untracked_files: return status else: return False
def gammacorrectbyte(lumbyte: int, gamma: float ) -> int: """Apply a gamma factor to a luminosity byte value Args: lumbyte: byte luminosity value gamma : gamma adjustment Returns: a gamma adjusted ...
def rreplace(s, old, new, occurrence): """ Credits go here: https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string :param s: string to be processed :param old: old char to be replaced :param new: new char to replace the old one :...
def calc_list_average(l): """ Calculates the average value of a list of numbers Returns a float """ total = 0.0 for value in l: total += value return total / len(l)
def pc(key): """ Changes python key into Pascale case equivalent. For example, 'this_function_name' becomes 'ThisFunctionName'. :param key: :return: """ return "".join([token.capitalize() for token in key.split('_')])
def count_emotion(session): """ Count number utterance per emotion for IEMOCAP session. Arguments --------- session: list List of utterance for IEMOCAP session. Returns ------- dic: dict Number of example per emotion for IEMOCAP session. """ d...
def white(s): """Color text white in a terminal.""" return "\033[1;37m" + s + "\033[0m"
def _try_convert(value): """Return a non-string from a string or unicode, if possible. ============= ===================================================== When value is returns ============= ===================================================== zero-length '' 'None' None 'True' ...
def min_to_hours(time): """ Returns hours in HH.MM - string format from integer time in hours. """ time /= 60 hours = int(time) minutes = (time * 60) % 60 return "%d:%02d" % (hours, minutes)
def issubclass_safe(x, klass): """return issubclass(x, klass) and return False on a TypeError""" try: return issubclass(x, klass) except TypeError: return False
def _parse_indent(indent): """Parse indent argument to indent string.""" try: return ' ' * int(indent) except ValueError: return indent
def vector_add(v, w): """adds corresponding elements""" return [v_i + w_i for v_i, w_i in zip(v, w)]
def trim_urls(attrs, new=False): """Bleach linkify callback to shorten overly-long URLs in the text. Pretty much straight out of the bleach docs. https://bleach.readthedocs.io/en/latest/linkify.html#altering-attributes """ if not new: # Only looking at newly-created links. return attrs ...
def merge(line): """ Helper function that merges a single row or column in 2048 """ new_line = [x for x in line if x !=0] while len(new_line) < len(line): new_line.append(0) for ind in range(len(new_line)-1): if new_line[ind] == new_line[ind+1]: new_line[ind] *= 2 ...
def entry_dict_from_list(all_slab_entries): """ Converts a list of SlabEntry to an appropriate dictionary. It is assumed that if there is no adsorbate, then it is a clean SlabEntry and that adsorbed SlabEntry has the clean_entry parameter set. Args: all_slab_entries (list): List of SlabEntr...
def _make_options_dict(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, sign=None, formatter=None): """ make a dictionary out of the non-None arguments, plus sanity checks """ options = {k: v for k, v in local...
def FrequentWords(text, k): """Generate k-frequent words of text.""" thisdict = {} for i in range(len(text) - k + 1): kmer = text[i: (i + k)] # print(kmer) try: thisdict[kmer] = thisdict[kmer] + 1 # print(thisdict.keys()) except KeyError: t...
def mf_replace(m, basic_dict): """ """ try: param = m.groups()[0] # There should be only one param defined if param in basic_dict.keys(): return basic_dict[param] except Exception: return None
def spw_filter(string): """Filter stopwords in a given string --> Titles of researchers' publications""" stopwords = ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', ...
def Publish(source_file): """Publish the given source file.""" return {'published_file': '/published/file.abc'}
def format_prayer(prayer: dict) -> str: """Format the reading. :param prayer Name of the prayer :return: Formatted prayer """ return f'<i><u><b>{prayer["Name"]}</b></u></i>\n\n{prayer["Prayer"]}'
def same_len(count, a:tuple): """Are a[0] and a[1] the same length?""" if len(a[0]) == len(a[1]): return count + 1 return count
def dim_comparator(val1, val2, name1, name2, dim_string, tolerance=0): """ Get the string representation of the relations. Args: val1: dimensional value of object 1 (int). val2: dimensional value of object 2 (int). name1: name of object 1 (str). name2: name of object 2 (str)...
def convert_tags(tags): """ Convert tags from AWS format [{'Key': '...', 'Value': '...'}, ...] to {'Key': 'Value', ...} format :param tags: tags in native AWS format :return: dict with tags ready to store in DynamoDB """ # dynamodb does not like empty strings # but Value can be empty, so c...
def escape_latex(s): """Borrowed from PyLaTeX (MIT license). Thanks. https://github.com/JelteF/PyLaTeX/blob/master/pylatex/utils.py """ _latex_special_chars = { '&': r'\&', '%': r'\%', '$': r'\$', '#': r'\#', '_': r'\_', '{': r'\{', '}': ...
def parse_cl_key_value(params): """ Convenience in parsing out parameter arrays in the form of something=something_else: --channel-name "H1=FAKE-STRAIN" """ return dict([val.split("=") for val in params])
def split_ranges(total, after=False, before=False): """ Given a range 1, 2, ..., total (page numbers of a doc). Split it in two lists. Example: Input: total = 9, after=1, before=False Output: list1 = [1]; list2 = [2, 3, 4, ..., 9]. Input: total = 9; after=False, before=1 Output: list1 =...
def parse_typename(typename): """ Parse a TypeName string into a namespace, type pair. :param typename: a string of the form <namespace>/<type> :return: a tuple of a namespace type. """ if typename is None: raise ValueError("function type must be provided") idx = typename.rfind("/") ...
def combine_strings(splitter): """Combine words into a list""" combined: str = " ".join(splitter) return combined
def level_to_kelvin(level): """Convert a level to a kelvin temperature.""" if level < 0: return 2200 if level > 100: return 6000 return (6000-2200) * level/100 + 2200
def replace_user_in_file_path(file_name, user): """Replace user name in give file path Args: file_name (str): Path to file user (str): New user to replace with Returns: str: New file path """ file_items = [x.strip() for x in file_name.strip().split('/') if...
def combination(n,m): """ Calculate the combination :math:`C_{n}^{m}`, .. math:: C_{n}^{m} = \\frac{n!}{m!(n-m)!}. Parameters ---------- n : int Number n. m : int Number m. Returns ------- res : int The calculated result. Examples ---...
def checkIfTableNeedExist(database, cursor, tableNameList): """ Input: the connected database this function will check if the tables that is needed for this program exists or not if yes: return 1 if no: return -1 """ for tableName in tableNameList: cursor.execute("SELECT name FROM sqlite_master WHERE typ...
def my_formatter(tick_value, pos): """convert 0.0 to 0 in the plot. Examples: ax.xaxis.set_major_formatter(formatter) ax.yaxis.set_major_formatter(formatter) """ if isinstance(tick_value, float): rounded_value = round(tick_value, ndigits=10) if rounded_value.is_integer(...
def get_w(node_s, node_w): """ node_s can be a set, list or a single node """ if isinstance(node_s, int): return node_w[node_s] else: return sum([node_w[n] for n in node_s])
def calculate_capacitance_factor( subcategory_id: int, capacitance: float, ) -> float: """Calculate the capacitance factor (piCV). :param subcategory_id: the capacitor subcategory identifier. :param capacitance: the capacitance value in Farads. :return: _pi_cv; the calculated capacitance factor...
def _embedding_aggregator(output_queue, n_worker): """ Process that aggregates the results of the workers. This should be the main/original process. Parameters ---------- output_queue: Queue This queue is the output queue of the workers. n_worker: int The number of worker pr...
def normalize_zip(code): """ Helper function to return 5 character zip codes only. :param code: string to normalize and format as a zip code :return: a five character digit string to compare as a zip code """ if code is None: return '' elif not isinstance(code, str): code =...
def quick_material(name): """ Get params of common materials. params: name: str, name of material. return: dictionary of material parameters. """ if name=='GB_Q345': return{ 'gamma':7849, 'E':2e11, 'mu':0.3, 'alpha':1....
def pprint_things(l): """Pretty print""" return ''.join("{:25}".format(e) for e in l.split("\t")) + "\n"
def _lst_for_pes(pes_dct, run_pes_idxs): """ Get a dictionary of requested species matching the PES_DCT format """ red_pes_dct = {} for (form, pidx, sidx), chnls in pes_dct.items(): # Grab PES if idx in run_pes_idx dct run_chnl_idxs = run_pes_idxs.get(pidx, None) if run_chnl_idx...
def floatnan(s): """converts string to float returns NaN on conversion error""" try: return float(s) except ValueError: return float('NaN')
def pointsToProperties(points): """Converts a (coordiante, properties) tuple to the properties only Arguments: points (array or tuple): point data to be reduced to properties Returns: array: property data Notes: Todo: Move this to a class that handles points an...
def AsList(arg): """Returns the given argument as a list; if already a list, return it unchanged, otherwise return a list with the arg as only element. """ if isinstance(arg, (list)): return arg if isinstance(arg, (tuple, set)): return list(arg) return [arg]
def custom_tuple(tup): """ customize tuple to have comma separated numbers """ tuple_string = "(" for itup in tup: tuple_string += "{:,d}".format(itup) + ", " if len(tup) == 1: return tuple_string[:-2] + ",)" return tuple_string[:-2] + ")"
def human_bytes(n): """ Return the number of bytes n in more human readable form. """ if n < 1024: return '%d B' % n k = (n - 1) / 1024 + 1 if k < 1024: return '%d KB' % k return '%.1f MB' % (float(n) / (2**20))
def patient_scan(patientcfg, add_sequence=None, sep=None): """Get patient/scan id Parameters ---------- patientcfg : Dict < json (patient config file with pid, scanid in top level) add_sequence : Bool (Flag to join sequence id with pid, scanid) sep : Str (separator, d...
def filter_names(name): """ This is just the filter function for the framework search :param name: :return: """ return name.lower()
def ellipsize(s, max_length=60): """ >>> print(ellipsize(u'lorem ipsum dolor sit amet', 40)) lorem ipsum dolor sit amet >>> print(ellipsize(u'lorem ipsum dolor sit amet', 20)) lorem ipsum dolor... """ if len(s) > max_length: ellipsis = '...' return s[:(max_length - len(ellips...
def pgcd(a, b): """Computes the biggest common divider""" while b != 0: r = a % b a, b = b, r return a
def is_whitespace(ch): """Given a character, return true if it's an EDN whitespace character.""" return ch == "," or ch.isspace()
def cobbdouglas(x, par): """ Cobb douglas utility function for 2 goods. INPUT: Parameters par (alpha) : relative preference for consumption to leisure, 0<alpha<1 Consumption bundle x : Consumption tuple x[0] : consumption x[1] : leisure OUTPUT...
def gate(self=str('h'), targetA=None, targetB=None, targetC=None, angle=None, theta=None, Utheta=None, Uphi=None, Ulambda=None, custom_name=None, custom_params=None): """Generate a gate from it's name as a string passed to sel...
def solve(task: str) -> int: """Find number of steps required to jump out of maze.""" current_index = 0 steps = 0 data = [int(item) for item in task.strip().split("\n")] while 0 <= current_index < len(data): next_index = current_index + data[current_index] data[current_index] += 1 ...
def _get_updated_values(before_values, after_values): """ Get updated values from 2 dicts of values Args: before_values (dict): values before update after_values (dict): values after update Returns: dict: a diff dict with key is field key, value is tuple of (before_va...
def levensthein_dist(input_command: str, candidate: str) -> int: """ Implement the Levenshtein distance algorithm to determine, in case of a non-existing handle, if theres a very similar command to suggest. :param input_command: The non-existing handle the user gave as input :param candidate: The (...
def strand_to_fwd_prob(strand): """Converts strand into a numeric value that RSEM understands. Args: strand: string 'forward', 'reverse', 'unstranded' Returns: numeric value corresponding the forward strand probability Raises: KeyError if strand is not 'forward', 'reverse' or ...
def ascii_chr(value): """ Converts byte to ASCII char :param value: ASCII code of character :return: char """ return bytes([value])
def process_function_types(type_string): """ Pre-process the function types for the Funcdecl """ split_string = type_string.split(' ') return ' '.join(str for str in split_string if '__attribute__' not in str)
def isabs(s): """Test whether a path is absolute""" return s.startswith('/')
def make_list(val): """make val a list, no matter what""" try: r = list(val) except TypeError: r = [val] return r
def is_hangul_char(character): """Test if a single character is in the U+AC00 to U+D7A3 code block, excluding unassigned codes. """ return 0xAC00 <= ord(character) <= 0xD7A3
def sum_of_squares(n): """ Calculate the sum of the squares of the first n natural numbers """ return sum(i ** 2 for i in range(1, n + 1))
def bin2balance_mxrb(b): """ Convert balance in binary encoding to Mxrb (a.k.a. XRB) The returned floating-point value will not be fully precise, as it has only 8 bytes of precision and not the needed 16 bytes (128 bits). """ assert isinstance(b, bytes) return 1.0 * int.from_bytes(b, 'b...
def tokenize(text): """Tokenize the given text. Returns the list of tokens. Splits up at spaces, and tabs, single and double quotes protect spaces/tabs, backslashes escape *any* subsequent character. """ words = [] word = '' quote = None escaped = False for letter in text: ...
def remove_blank(x): """creating a function to remove the empty words""" if(x !=' ' ): return(x)
def url(data): """ Adds a http:// to the start of the url in data. """ return "http://%s" % data["metadata"]["url"]
def compare(x, y): """Comparison helper function for multithresholding. Gets two values and returns 1.0 if x>=y otherwise 0.0.""" if x >= y: return 1.0 else: return 0.0
def get_expts(context, expts): """Takes an expts list and returns a space separated list of expts.""" return '"' + ' '.join([expt['name'] for expt in expts]) + '"'