content
stringlengths
42
6.51k
def find(collection, item, field='name'): """ Finds an element in a collection which has a field equal to particular item value Parameters ---------- collection : Set Collection of objects item value of the item that we are looking for field : string Name of the field from the object to inspect Returns ------- object Corresponding element that has a field matching item in the collection """ for element in collection: if element[field] == item: return element return None
def remove_suffix(suffix, string): """Removes suffix for string if present. If not, returns string as is Example: remove_suffix(".com", "example.com") => "example" """ if string.endswith(suffix): ls = len(suffix) return string[:-ls] else: return string
def interpolate(a0, a1, w): """ Interpolate between the two points, with weight 0<w<1 """ # return (a1 - a0) * w + a0 # Can make this smoother later return (a1 - a0) * ((w * (w * 6.0 - 15.0) + 10.0) * w * w * w) + a0
def get_email_headers(email) -> dict: """ Extracts the headers from the email and returns them as a dict. :param email: The email to extract the sender from. :return: The headers of the email. """ headers = {"sender": "N/A", "subject": "N/A"} for header in email["payload"]["headers"]: if header["name"] == "From": headers["sender"] = header["value"] elif header["name"] == "Subject": headers["subject"] = header["value"] return headers
def parse_table_name(default_schema, table_name, sql_mode=""): """Parse table name. Args: default_schema (str): The default schema. table_name (str): The table name. sql_mode(Optional[str]): The SQL mode. Returns: str: The parsed table name. """ quote = '"' if "ANSI_QUOTES" in sql_mode else "`" delimiter = ".{0}".format(quote) if quote in table_name else "." temp = table_name.split(delimiter, 1) return (default_schema if len(temp) is 1 else temp[0].strip(quote), temp[-1].strip(quote),)
def jaccard_score(a, b, ab): """Calculates the Jaccard similarity coefficient between two repositories. :param a: Number of times the second event occurred w/o the first event :param b: umber of times the first event occurred w/o the second event :param ab: Number of times the two events occurred together """ return ab / (a + b - ab)
def write_file(bytes, path: str): """Write to disk a rexfile from its binary format""" newFile = open(path + ".rex", "wb") newFile.write(bytes) return True
def alterModelDef(dbTuple, name=None, format=None, dbType=None, single=None, official=None, numver=None, purgeAge=None): """Alter GFE database definition. The definition is used in the dbs setting and has form: (name, format, type, single, official, numVer, purgeAge) i.e., Practice = ("Fcst", GRID, "Prac", YES, NO, 1, 24) Won't use these exact names since some might conflict with builtins Only supply what you want to change. To clone a model definition, just supply name='newname' """ n,f,t,s,o,v,p=dbTuple l=[] for old,new in [(n,name),(f,format),(t,dbType),(s,single),(o,official), (v,numver),(p,purgeAge)]: if new is None: l.append(old) else: l.append(new) return tuple(l)
def inputs(form_args): """ Creates list of input elements """ element = [] html_field = '<input type="hidden" name="{}" value="{}"/>' for name, value in form_args.items(): element.append(html_field.format(name, value)) return "\n".join(element)
def has_duplicates(s): """Returns True if any element appears more than once in a sequence. s: string or list returns: bool """ # make a copy of t to avoid modifying the parameter t = list(s) t.sort() # check for adjacent elements that are equal for i in range(len(t)-1): if t[i] == t[i+1]: return True return False
def gcd(a: int, b: int) -> int: """ Computes the gcd of a and b using the Euclidean algorithm. param a: int param b: int return: int gcd of a and b """ while b != 0: a, b = b, a % b return a
def _join_prefix(prefix, name): """Filter certain superflous parameter name suffixes from argument names. :param str prefix: The potential prefix that will be filtered. :param str name: The arg name to be prefixed. :returns: Combined name with prefix. """ if prefix.endswith("_specification"): return prefix[:-14] + "_" + name elif prefix.endswith("_patch_parameter"): return prefix[:-16] + "_" + name elif prefix.endswith("_update_parameter"): return prefix[:-17] + "_" + name return prefix + "_" + name
def tagsoverride(msg, override): """ Merge in a series of tag overrides, with None signaling deletes of the original messages tags """ for tag, value in override.items(): if value is None: del msg[tag] else: msg[tag] = value return msg
def value_to_angle(value, min_val, max_val): """Return angle for gauge plot""" angle = (value - min_val) / (max_val - min_val) angle *= 180 angle = max(min(angle, 180), 0) return 180 - angle
def centeroidOfTriangle(pa, pb, pc): """ when given 3 points that are corners of a triangle this code calculates and returns the center of the triangle. the exact type of center is called "centeroid". it is the intersection point of the connection of each angle to the middle of its opposed edge. two of these connections are enough to get the intersection point. https://en.wikipedia.org/wiki/Centroid https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_the_equations_of_the_lines """ # get the middle of the opposing line (point pa to point pb has middle cm) am = [(pb[0] + pc[0]) / 2, (pb[1] + pc[1]) / 2] bm = [(pa[0] + pc[0]) / 2, (pa[1] + pc[1]) / 2] denominator = (pa[0] - am[0]) * (pb[1] - bm[1]) - \ (pa[1] - am[1]) * (pb[0] - bm[0]) if denominator != 0: x = ((pa[0] * am[1] - pa[1] * am[0]) * (pb[0] - bm[0]) - (pa[0] - am[0]) * (pb[0] * bm[1] - pb[1] * bm[0])) / denominator y = ((pa[0] * am[1] - pa[1] * am[0]) * (pb[1] - bm[1]) - (pa[1] - am[1]) * (pb[0] * bm[1] - pb[1] * bm[0])) / denominator else: print(f"cant find center for {pa}, {pb}, {pc}") x = pa[0] y = pa[1] return [x, y]
def red(s): """Color text red in a terminal.""" return "\033[1;31m" + s + "\033[0m"
def add_newlines_by_spaces(string, line_length): """Return a version of the passed string where spaces (or hyphens) get replaced with a new line if the accumulated number of characters has exceeded the specified line length""" replacement_indices = set() current_length = 0 for i, char in enumerate(string): current_length += 1 if current_length > line_length and (char == " " or char == "-"): replacement_indices.add(i) current_length = 0 return "".join([("\n" if i in replacement_indices else char) for i, char in enumerate(string)])
def _get_last_layer_units_and_activation(num_classes, use_softmax=True): """Gets the # units and activation function for the last network layer. Args: num_classes: Number of classes. Returns: units, activation values. """ if num_classes == 2 and not use_softmax: activation = 'sigmoid' units = 1 else: activation = 'softmax' units = num_classes return units, activation
def format_text_list(text_list): """Create a formatted version of the given string according to MCF standard. This is used to format many columns from the drugs and genes dataframes like PubChem Compound IDentifiers or NCBI Gene ID. Args: text_list: A single string representing a comma separated list. Some of the items are enlcosed by double quotes and some are not. Returns: A string that is mcf property text values list enclosed by double quotes and comma separated. Example: input: ('test1, "Carbanilic acid, M,N-dimethylthio-, O-2-naphthyl ester", "test2"') return: ('"test1", "Carbanilic acid, M,N-dimethylthio-, O-2-naphthyl ester", "test2"') """ if not text_list: return '' formatted_str = [] in_paren = False cur_val = '' for char in text_list: if char == '"': in_paren = not in_paren elif char == ',': # if the comma is in between double quotes, then do not split if in_paren: cur_val += char # otherwise, split on the comma, prepend and append double quotes else: formatted_str.append('"' + cur_val.strip() + '"') cur_val = '' else: cur_val += char formatted_str.append('"' + cur_val.strip() + '"') return ','.join(formatted_str)
def C(b: int) -> dict: """Setting up type mismatch.""" return {'hi': 'world'}
def split_choices(choices, split): """Split a list of [(key, title)] pairs after key == split.""" index = [idx for idx, (key, title) in enumerate(choices) if key == split] if index: index = index[0] + 1 return choices[:index], choices[index:] else: return choices, []
def break_condition_final_marking(marking, finalMarking): """ Verify break condition for final marking Parameters ----------- marking Current marking finalMarking Target final marking """ finalMarkingDict = dict(finalMarking) markingDict = dict(marking) finalMarkingDictKeys = set(finalMarkingDict.keys()) markingDictKeys = set(markingDict.keys()) return finalMarkingDictKeys.issubset(markingDictKeys)
def create_paths(inputs): """Create an adjancency list of orbitor -> orbitee With the restriction that each object only orbits one other, this could/should have been a simple map, which might have made things easier """ objects = {} for line in inputs: try: a, b = line.split(')') objects.setdefault(a, []).append(b) objects.setdefault(b, []) except: print(line) return objects
def divide_list(input_list, n): """ Split a list into 'n' number of chunks of approximately equal length. Based on example given here: https://stackoverflow.com/questions/2130016/splitting-a-list-of-into-n-parts-of-approximately-equal-length :param input_list: list list to be split :param n: int number of chunks to split list into :return: list list of lists (chunks) """ avg = len(input_list) / float(n) last = 0.0 divided = [] while last < len(input_list): divided.append(input_list[int(last):int(last + avg)]) last += avg return divided
def fibonacci(n): """ Return the n-th Fibonacci number :param n: n-th fibonacci number requested :return: the n-th Fibonacci number """ if n in (0, 1): return n return fibonacci(n - 2) + fibonacci(n - 1)
def integrate(x_dot, x, dt): """ Computes the Integral using Euler's method :param x_dot: update on the state :param x: the previous state :param dt: the time delta :return The integral of the state x """ return (dt * x_dot) + x
def extendGcd(a, b): """ ax + by = gcd(a, b) = d (Introduction to Algorithms P544) we have two case: a. if b == 0 ax + 0 = gcd(a, 0) = a --> x = 1 y = 0,1,... --> y = 0 b. if a*b != 0 then, ax + by = ax' + (a%b)y'.And a % b = a - (a/b)*b so, ax + by= ay' + b[x' - (a/b)y'] --> x = x' y = x' - (a/b)y' """ if b == 0: return a,1,0 else: _b, _x, _y = extendGcd(b, a % b) d, x, y = _b, _y, _x - (a // b) * _y return d, x, y
def f_check_param_definition(a, b, c, d, e): """Function f Parameters ---------- a: int Parameter a b: Parameter b c : Parameter c d:int Parameter d e No typespec is allowed without colon """ return a + b + c + d
def add_collect_stats_qs(url, value): """if :url is `page.html?foo=bar` return. `page.html?foo=bar&MINCSS_STATS=:value` """ if '?' in url: url += '&' else: url += '?' url += 'MINCSS_STATS=%s' % value return url
def approx_2rd_deriv(f_x0,f_x0_minus_1h,f_x0_minus_2h,h): """Backwards numerical approximation of the second derivative of a function. Args: f_x0: Function evaluation at current timestep. f_x0_minus_1h: Previous function evaluation. f_x0_minus_2h: Function evaluations two timesteps ago. h: Time inbetween function evaluations. Returns: The approximated value of the second derivative of f evaluated at x0 """ return (-1*f_x0+2*f_x0_minus_1h-1*f_x0_minus_2h)/(h**2)
def usual_criterion(distance): """ implements usual criterion """ if distance > 0: return 1 else: return 0
def canon_besteffort(msg): """ Format is any: 2a00f6 2a#00f6 2a,00,f6 0x89,0x30,0x33 (123.123) interface 2a#00f6 ; comment (case insensitive) """ msg = msg.strip() msg = msg.split(';')[0] msg = msg.split(' ')[-1] msg = msg.replace(',', '') msg = msg.replace('#', '') msg = msg.replace('0x', '') return [int(msg[i:i+2],16) for i in range(0,len(msg),2)]
def func2(x, y): """second test function Parameters ---------- x : int, float or complex first factor y : int, float or complex second factor Raises ------ ValueError if both are 0 Returns ------- product : int, float or complex the product of x and y sum : int, float or complex the sum of x and y See Also -------- pandas.DataFrame.sum, xarray.Dataset.sum, pandas.Series.sum, xarray.DataArray.sum """ if x == 0 and y == 0: raise ValueError return x * y, x + y
def remove_element_two_pointers(nums, val): """ Remove elements with given value in the given array :param nums: given array :type nums: list[int] :param val: given value :type val: int :return: length of operated array :rtype: int """ # traverse from left to right left = 0 # traverse from right to left right = len(nums) - 1 while left <= right: # if left one is not matched, move forward if nums[left] != val: left += 1 # if right one is matched, move backward elif nums[right] == val: right -= 1 # replace left matched value with right unmatched one else: nums[left] = nums[right] right -= 1 return left
def rolling_average(current_avg: float, new_value: float, total_count: int) -> float: """Recalculate a running (or moving) average Needs the current average, a new value to include, and the total samples """ new_average = float(current_avg) new_average -= new_average / total_count new_average += new_value / total_count return new_average
def is_parenthetical(s): """ (str) -> bool Returns True if s starts with '(' and ends with ')' """ if len(s) < 2: return False else: return s[0] == "(" and s[-1] == ")"
def scientific_label(obj, precision): """ Creates a scientific label approximating a real number in LaTex style Parameters ---------- obj : float Number that must be represented precision : int Number of decimal digits in the resulting label Returns ------- str Approximated number in str, e.g., '5.000 \\times 10^{-6}', arising from the function call scientific_label(5e-06, 3) Example ------- import numpy as np import matplotlib.pyplot as plt x = np.linspace(-2, 2, 150) y = x**2 * 1e-5 plt.plot(x, y) ticks = plt.gca().get_yticks() labels = [r'$%s$'%scientific_label(i, 1) for i in ticks] plt.yticks(ticks=ticks, labels=labels) plt.show() """ precision = '%.' + '%se'%precision python_notation = precision % obj number, power = python_notation.split('e') scientific_notation = r'%s \times 10^{%s}'%(number, int(power)) return scientific_notation
def capitalize_first_letter(word): """ Function that capitalizes the first letters of words in the input.""" j = 0 capitalized_word = "" list_of_words_in_name = word.split() for word_in_name in list_of_words_in_name: i = 0 for char in word_in_name: if i == 0: capitalized_word += char.upper() else: capitalized_word += char i += 1 if j != len (list_of_words_in_name) - 1: capitalized_word += " " j += 1 return capitalized_word
def _dominates(w_fitness, w_fitness_other): """ Return true if ALL values are [greater than or equal] AND at least one value is strictly [greater than]. - If any value is [less than] then it is non-dominating - both arrays must be one dimensional and the same size, we don't check for this! """ dominated = False for iv, jv in zip(w_fitness, w_fitness_other): if iv > jv: dominated = True elif iv < jv: return False return dominated
def _jinja2_filter_humanizetime(dt, fmt=None): """ humanizes time in seconds to human readable format Args: dt: fmt: Returns: """ days = int(dt / 86400) hours = int(dt / 3600) % 24 minutes = int(dt / 60) % 60 seconds = int(dt) % 60 microseconds = int(((dt % 1.0) * 1000)) fmtstr = '' if days > 0: fmtstr += '{}d '.format(days) if hours > 0: fmtstr += '{}h '.format(hours) if minutes > 0: fmtstr += '{}m '.format(minutes) if seconds > 0: fmtstr += '{}s '.format(seconds) if microseconds > 0: # special case: only include ms for times below a minute. if minutes == 0 and hours == 0 and days == 0: fmtstr += '{}ms '.format(microseconds) return fmtstr.rstrip()
def _sort_merge(left: list, right: list) -> list: """Merge and sort list:left and list:right and return list:res""" res = [] i = j = 0 while(i < len(left) and j < len(right)): if left[i] <= right[j]: res.append(left[i]) i += 1 else: res.append(right[j]) j += 1 res.extend(left[i:]) res.extend(right[j:]) return res
def indent(text: str, amount: int) -> str: """indent according to amount, but skip first line""" return "\n".join( [ amount * " " + line if id > 0 else line for id, line in enumerate(text.split("\n")) ] )
def to_tractime(t): """Convert time to trac time format. Type of t needs float, str or int.""" st = '' if isinstance(t, str): st = t else: st = repr(t) st = ''.join(st.split('.')) if len(st) > 16: st = st[0:16] elif len(st) < 16: st = st + '0' * (16 - len(st)) return int(st)
def aes_pad_ (data): """Adds padding to the data such that the size of the data is a multiple of 16 bytes data: the data string Returns a tuple:(pad_len, data). pad_len denotes the number of bytes added as padding; data is the new data string with padded bytes at the end """ pad_len = len(data) % 16 if (0 != pad_len): pad_len = 16 - pad_len pad_bytes = bytearray (15) data += str(pad_bytes[:pad_len]) return (pad_len, data)
def rosenbrock_grad(x, y): """Gradient of Rosenbrock function.""" return (-400 * x * (-(x ** 2) + y) + 2 * x - 2, -200 * x ** 2 + 200 * y)
def power_iterative(base, exp): """Funkce vypocita hodnotu base^exp pomoci iterativniho algoritmu v O(exp). Staci se omezit na prirozene hodnoty exp. """ output = 1 for i in range(exp): output *= base return output
def is_null(left: str, _right: None) -> str: """Check if the `left` argument doesn't exist.""" return left + ' IS NULL'
def extract_from_lib(lib): """Extract relevant parameters from lib. Returns ------- [plx, plx_e, dist, dist_e, rad, rad_e, temp, temp_e, lum, lum_e] """ if lib is None: return [-1] * 10 return [ lib.plx, lib.plx_e, lib.dist, lib.dist_e, lib.rad, lib.rad_e, lib.temp, lib.temp_e, lib.lum, lib.lum_e ]
def move_location(current_location, direction): """Return a new (x, y) tuple after moving one unit in direction current_location should be tuple of ints (x, y) Direction is one of: ^ north v south > east < west """ direction_table = {"^": (0, 1), "v": (0, -1), ">": (1, 0), "<": (-1, 0)} cur_x, cur_y = current_location diff_x, diff_y = direction_table[direction] return (cur_x + diff_x, cur_y + diff_y)
def poly_extend(p, d): """Extend list ``p`` representing a polynomial ``p(x)`` to match polynomials of degree ``d-1``. """ return [0] * (d-len(p)) + list(p)
def state_support(state): """ Count number of nonzero elements of the state """ n = 0 for s in state: if s != 0: n += 1 return n
def escape_backslash(s: str) -> str: """Replaces any \\ character with \\\\""" return s.replace('\\', '\\\\')
def _get_or_add(cfg, name): """Gets cfg[name], or adds 'name' with an empty dict if not present.""" if name not in cfg: cfg.update({name: {}}) return cfg[name]
def strip_quotes(text: str) -> str: """Remove the double quotes surrounding a string.""" text = text.strip(' "') return text
def _parse_draw_keys(keys): """Convert keys on input from .draw.""" kwargs = dict( char='', codepoint=None, tags=[], ) # only one key allowed in .draw, rest ignored key = keys[0] try: kwargs['char'] = chr(int(key, 16)) except (TypeError, ValueError): kwargs['tags'] = [key] return kwargs
def read_dm3_eels_info(original_metadata): """Reed dm3 file from a nested dictionary like original_metadata of sidpy.Dataset""" if 'DM' not in original_metadata: return {} main_image = original_metadata['DM']['chosen_image'] exp_dictionary = original_metadata['ImageList'][str(main_image)]['ImageTags'] experiment = {} if 'EELS' in exp_dictionary: if 'Acquisition' in exp_dictionary['EELS']: for key, item in exp_dictionary['EELS']['Acquisition'].items(): if 'Exposure' in key: _, units = key.split('(') if units[:-1] == 's': experiment['single_exposure_time'] = item if 'Integration' in key: _, units = key.split('(') if units[:-1] == 's': experiment['exposure_time'] = item if 'frames' in key: experiment['number_of_frames'] = item if 'Experimental Conditions' in exp_dictionary['EELS']: for key, item in exp_dictionary['EELS']['Experimental Conditions'].items(): if 'Convergence' in key: experiment['convergence_angle'] = item if 'Collection' in key: # print(item) # for val in item.values(): experiment['collection_angle'] = item if 'Microscope Info' in exp_dictionary: if 'Voltage' in exp_dictionary['Microscope Info']: experiment['acceleration_voltage'] = exp_dictionary['Microscope Info']['Voltage'] if 'Name' in exp_dictionary['Microscope Info']: experiment['microscope'] = exp_dictionary['Microscope Info']['Name'] return experiment
def escape_url(raw): """ Escape urls to prevent code injection craziness. (Hopefully.) """ from urllib.parse import quote return quote(raw, safe="/#:")
def formatter(ms): """ formats the ms into seconds and ms :param ms: the number of ms :return: a string representing the same amount, but now represented in seconds and ms. """ sec = int(ms) // 1000 ms = int(ms) % 1000 if sec == 0: return '{0}ms'.format(ms) return '{0}.{1}s'.format(sec, ms)
def staircase(n: int, choices: set) -> int: """case 2 Generalized situation. In this case the sum would be f(n) = f(n-x1) + f(n-x2) + ... time complexity: O(n*|x|) space complexity: O(n) """ cache = [0] * (n + 1) cache[0] = 1 for i in range(1, n + 1): cache[i] = sum(cache[i - v] for v in choices if v <= i) return cache[n]
def _check_dict(values): """ Checks if dictionary's value is set to None and replaces it with an empty string. None values cannot be appended to in auditors. :param values: dictionary of key-values :return: configurations dictionary """ # check if value is None for key in values: if values[key] is None: values[key] = str() return values
def rename(filepath: str, name: str, file_format: str, net: str) -> str: """ :param filepath: path to file to create a new name for :param name: name of the object drawn :param file_format: type of content: video, picture of rosbag :param net: mainnet/testnet :return: new filename with a filepath """ res = filepath[0: filepath.rfind("/") + 1] + filepath[filepath.rfind("."):] res = ( res[0: res.rfind("/") + 1] + name + "_" + file_format + "_" + net + res[res.rfind("/") + 1:] ) return res
def placekitten_src(width=800, height=600): """ Return a "placekitten" placeholder image url. Example: {% placekitten_src as src %} {% placekitten_src 200 200 as mobile_src %} {% include 'components/image/image.html' with mobile_src=mobile_src src=src alt='placekitten' only %} """ return "//placekitten.com/{}/{}".format(width, height)
def call_if_callable(func, *args, **kwargs): """Call the function with given parameters if it is callable""" if func and callable(func): return func(*args, **kwargs) return None
def cohen_kappa(ann1: list, ann2: list, verbose=False): """Computes Cohen kappa for pair-wise annotators. :param ann1: annotations provided by first annotator :type ann1: list :param ann2: annotations provided by second annotator :type ann2: list :rtype: float :return: Cohen kappa statistic """ count = 0 for an1, an2 in zip(ann1, ann2): if an1 == an2: count += 1 A = count / len(ann1) # observed agreement A (Po) uniq = set(ann1 + ann2) E = 0 # expected agreement E (Pe) for item in uniq: cnt1 = ann1.count(item) cnt2 = ann2.count(item) count = ((cnt1 / len(ann1)) * (cnt2 / len(ann2))) E += count if E == 1.0: if verbose: print('WARNING Cohen\'s Kappa: single class agreement. E == 1.0, this would incur in a float division by 0.') return None else: return round((A - E) / (1 - E), 4)
def pars_to_descr(par_str): """ pars_to_descr() Converts numeric parameters in a string to parameter descriptions. Required args: - par_str (str): string with numeric parameters Returns: - par_str (str): string with parameter descriptions """ vals = [128.0, 256.0, 4.0, 16.0] descs = ["small", "big", "high disp", "low disp"] for val, desc in zip(vals, descs): par_str = par_str.replace(str(val), desc) par_str = par_str.replace(str(int(val)), desc) return par_str
def str_to_bool(value): """Python 2.x does not have a casting mechanism for booleans. The built in bool() will return true for any string with a length greater than 0. It does not cast a string with the text "true" or "false" to the corresponding bool value. This method is a casting function. It is insensitive to case and leading/trailing spaces. An Exception is raised if a cast can not be made. """ if str(value).strip().lower() == "true": return True elif str(value).strip().lower() == "false": return False else: raise Exception("Unable to cast value (%s) to boolean" % value)
def TSKVolumeGetBytesPerSector(tsk_volume): """Retrieves the number of bytes per sector from a TSK volume object. Args: tsk_volume (pytsk3.Volume_Info): TSK volume information. Returns: int: number of bytes per sector or 512 by default. """ # Note that because pytsk3.Volume_Info does not explicitly defines info # we need to check if the attribute exists and has a value other # than None. Default to 512 otherwise. if hasattr(tsk_volume, 'info') and tsk_volume.info is not None: block_size = getattr(tsk_volume.info, 'block_size', 512) else: block_size = 512 return block_size
def get_intersect_point(a1, b1, c1, d1, x0, y0): """Get the point on the lines that passes through (a1,b1) and (c1,d1) and s closest to the point (x0,y0).""" a = 0 if (a1 - c1) != 0: a = float(b1 - d1) / float(a1 - c1) c = b1 - a * a1 # Compute the line perpendicular to the line of the OF vector that passes throught (x0,y0) a_aux = 0 if a != 0: a_aux = -1 / a c_aux = y0 - a_aux * x0 # Get intersection of the two lines x1 = (c_aux - c) / (a - a_aux) y1 = a_aux * x1 + c_aux return (x1, y1)
def split_list(alist, wanted_parts=1): """ Split a list into a given number of parts. Used to divvy up jobs evenly. :param alist: list o' jobs :param wanted_parts: how many chunks we want :return: list o' lists """ length = len(alist) return [ alist[i * length // wanted_parts : (i + 1) * length // wanted_parts] for i in range(wanted_parts) ]
def complete_urls(setlist_urls): """Completes the setlist urls adding http://setlist.fm/ to each url""" complete_setlist_urls = [] for i in setlist_urls: link = "http://www.setlist.fm/" + i complete_setlist_urls.append(link) return complete_setlist_urls
def calculate_syntax_error_score(navigation_subsystem): """ Calculate syntax error score :param navigation_subsystem: list of chunks :return: syntax error score and filtered chunks """ score = 0 uncomplete_lines = [] for line in navigation_subsystem: stack = [] corrupted_line = False for character in line: if character in ('(', '[', '{', '<'): stack.append(character) else: stack_pop = stack.pop() or "" if character == ')' and stack_pop != '(': score += 3 corrupted_line = True continue elif character == ']' and stack_pop != '[': score += 57 corrupted_line = True continue elif character == '}' and stack_pop != '{': score += 1197 corrupted_line = True continue elif character == '>' and stack_pop != '<': score += 25137 corrupted_line = True continue if not corrupted_line: uncomplete_lines.append(stack) return score, uncomplete_lines
def fromVlqSigned(value): """Converts a VLQ number to a normal signed number. Arguments: value - A number decoded from a VLQ string. Returns: an integer. """ negative = (value & 1) == 1 value >>= 1 return -value if negative else value
def RPL_NOTOPIC(sender, receipient, message): """ Reply Code 331 """ return "<" + sender + ">: " + message
def format_number(num): """ Removing trailing zeros. :param num: input number :type num: float :return: formatted number as str """ str_num = str(num) if "." in str_num: splitted_num = str_num.split(".") if int(splitted_num[-1]) == 0: return "".join(splitted_num[:-1]) else: return str_num else: return str_num
def iterate_pagerank(corpus, damping_factor): """ Return PageRank values for each page by iteratively updating PageRank values until convergence. Return a dictionary where keys are page names, and values are their estimated PageRank value (a value between 0 and 1). All PageRank values should sum to 1. """ pages_number = len(corpus) old_dict = {} new_dict = {} # assigning each page a rank of 1/n, where n is total number of pages in the corpus for page in corpus: old_dict[page] = 1 / pages_number # repeatedly calculating new rank values basing on all of the current rank values while True: for page in corpus: temp = 0 for linking_page in corpus: # check if page links to our page if page in corpus[linking_page]: temp += (old_dict[linking_page] / len(corpus[linking_page])) # if page has no links, interpret it as having one link for every other page if len(corpus[linking_page]) == 0: temp += (old_dict[linking_page]) / len(corpus) temp *= damping_factor temp += (1 - damping_factor) / pages_number new_dict[page] = temp difference = max([abs(new_dict[x] - old_dict[x]) for x in old_dict]) if difference < 0.001: break else: old_dict = new_dict.copy() return old_dict
def sub_size_tag_from_sub_size(sub_size): """Generate a sub-grid tag, to customize phase names based on the sub-grid size used. This changes the phase name 'phase_name' as follows: sub_size = None -> phase_name sub_size = 1 -> phase_name_sub_size_2 sub_size = 4 -> phase_name_sub_size_4 """ return "__sub_" + str(sub_size)
def construct_engine_options(ts_directives, tm_engine_options, synctex=True): """Construct a string of command line options. The options come from two different sources: - %!TEX TS-options directive in the file - Options specified in the preferences of the LaTeX bundle In any case ``nonstopmode`` is set as is ``file-line-error-style``. Arguments: ts_directives A dictionary containing typesetting directives. If it contains the key ``TS-options`` then this value will be used to construct the options. tm_engine_options A string containing the default typesetting options set inside TextMate. This string will be used to extend the options only if ts_directives does not contain typesetting options. Otherwise the settings specified in this item will be ignored. synctex Specifies if synctex should be used for typesetting or not. Returns: ``str`` Examples: >>> print(construct_engine_options({}, '', True)) -interaction=nonstopmode -file-line-error-style -synctex=1 >>> print(construct_engine_options({'TS-options': '-draftmode'}, ... '', False)) -interaction=nonstopmode -file-line-error-style -draftmode >>> print(construct_engine_options({'TS-options': '-draftmode'}, ... '-8bit', False)) -interaction=nonstopmode -file-line-error-style -draftmode >>> print(construct_engine_options({}, '-8bit')) -interaction=nonstopmode -file-line-error-style -synctex=1 -8bit """ options = "-interaction=nonstopmode -file-line-error-style{}".format( ' -synctex=1' if synctex else '') if 'TS-options' in ts_directives: options += ' {}'.format(ts_directives['TS-options']) else: options += ' {}'.format(tm_engine_options) if tm_engine_options else '' return options
def ParseNatList(ports): """ Support a list of ports in the format "protocol:port, protocol:port, ..." examples: tcp 123 tcp 123:133 tcp 123, tcp 124, tcp 125, udp 201, udp 202 User can put either a "/" or a " " between protocol and ports Port ranges can be specified with "-" or ":" """ nats = [] if ports: parts = ports.split(",") for part in parts: part = part.strip() if "/" in part: (protocol, ports) = part.split("/",1) elif " " in part: (protocol, ports) = part.split(None,1) else: raise TypeError('malformed port specifier %s, format example: "tcp 123, tcp 201:206, udp 333"' % part) protocol = protocol.strip() ports = ports.strip() if not (protocol in ["udp", "tcp"]): raise ValueError('unknown protocol %s' % protocol) if "-" in ports: (first, last) = ports.split("-") first = int(first.strip()) last = int(last.strip()) portStr = "%d:%d" % (first, last) elif ":" in ports: (first, last) = ports.split(":") first = int(first.strip()) last = int(last.strip()) portStr = "%d:%d" % (first, last) else: portStr = "%d" % int(ports) nats.append( {"l4_protocol": protocol, "l4_port": portStr} ) return nats
def get_bucket_and_object(resource_name): """Given an audit log resourceName, parse out the bucket name and object path within the bucket. Returns: (str, str) -- ([bucket name], [object name]) """ pathparts = resource_name.split("buckets/", 1)[1].split("/", 1) bucket_name = pathparts[0] object_name = pathparts[1].split("objects/", 1)[1] return (bucket_name, object_name)
def _slope_one(p, x): """Basic linear regression 'model' for use with ODR. This is a function of 1 variable. Assumes slope == 1.0. """ return x + p[0]
def get_videos_meta(frame_width, frame_height, total_frames): """ get frame's meta """ meta = [] meta4 = [] meta.append(dict(nframes = total_frames, H = frame_height * 4, W = frame_width * 4)) meta4.append(dict(nframes = total_frames, H = frame_height, W = frame_width)) return meta, meta4
def length_func(list_or_tensor): """ Get length of list or tensor """ if type(list_or_tensor) == list: return len(list_or_tensor) return list_or_tensor.shape[0]
def _parse_output(out): """ >>> out = 'BLEU = 42.9/18.2/0.0/0.0 (BP=1.000, ratio=0.875, hyp_len=14, ref_len=16)' >>> _parse_output(out) [42.9, 18.2, 0.0, 0.0] :param out: :return: """ out = out[len('BLEU = '):out.find('(') - 1] numbers = out.split('/') return list(map(float, numbers))
def get_interface_type(interface): """Gets the type of interface Args: interface (str): full name of interface, i.e. Ethernet1/1, loopback10, port-channel20, vlan20 Returns: type of interface: ethernet, svi, loopback, management, portchannel, or unknown """ if interface.upper().startswith('ET'): return 'ethernet' elif interface.upper().startswith('VL'): return 'svi' elif interface.upper().startswith('LO'): return 'loopback' elif interface.upper().startswith('MG'): return 'management' elif interface.upper().startswith('MA'): return 'management' elif interface.upper().startswith('PO'): return 'portchannel' else: return 'unknown'
def get_intrinsic_name(signature): """ Get the intrinsic name from the signature of the intrinsic. >>> get_intrinsic_name("int8x8_t vadd_s8(int8x8_t a, int8x8_t b)") 'vadd_s8' >>> get_intrinsic_name("int32x4_t vaddl_high_s16(int16x8_t a, int16x8_t b)") 'vaddl_high_s16' >>> get_intrinsic_name("float64x2_t vfmsq_lane_f64(float64x2_t a, float64x2_t b, float64x1_t v, __builtin_constant_p(lane))") 'vfmsq_lane_f64' >>> get_intrinsic_name("poly16x8_t vsriq_n_p16(poly16x8_t a, poly16x8_t b, __builtin_constant_p(n))") 'vsriq_n_p16' >>> get_intrinsic_name("uint8x16_t [__arm_]vddupq_m[_n_u8](uint8x16_t inactive, uint32_t a, const int imm, mve_pred16_t p)") '[__arm_]vddupq_m[_n_u8]' """ tmp = signature.split(' ') tmp = tmp[1].split('(') return tmp[0]
def build_token_dict(vocab): """ build bi-directional mapping between index and token""" token_to_idx, idx_to_token = {}, {} next_idx = 1 vocab_sorted = sorted(list(vocab)) # make sure it's the same order everytime for token in vocab_sorted: token_to_idx[token] = next_idx idx_to_token[next_idx] = token next_idx = next_idx + 1 return token_to_idx, idx_to_token
def node_info(node_id, node_dict): """ ([(node_id, { 'label': 'diminuition...'))...] -> string with stats Takes a list of tuples (node_id, node_dict) Wraper which returns importance measures for a given node """ return '%s & %s & %.3f & %.3f' % (node_id, node_dict['label'], node_dict['computed importance factor'], node_dict['delta importance'])
def user_model(username): """Return a user model""" return { 'login': username, }
def myint(value): """ round and convert to int """ return int(round(float(value)))
def remove_keys_from_array(array, keys): """ This function... :param array: :param keys: :return: """ for key in keys: array.remove(key) return array
def get_prominent_color(layers): """returns the first non-transparent pixel color for each pixel""" final = [3] * len(layers[0]) for i in range(len(final)): for layer in layers: if layer[i] != 2: final[i] = layer[i] break return final
def to_c_str(v): """ Python str to C str """ try: return v.encode("utf-8") except Exception: pass return b""
def _get_filter_text(method, min_freq, max_freq): """Get the notes attribute text according to the analysis method and frequency range.""" filter_text = '%s with frequency range: %s to %s' %(method, min_freq, max_freq) return filter_text
def largest_minus_one_product(nums): """ Question 22.4: Find the maximum of all entries but one """ # iterate through and count number of negatives # least negative entry, least positive entry # greatest negative idx number_of_negatives = 0 least_negative_idx = -1 least_positive_idx = -1 greatest_negative_idx = -1 for idx, elt in enumerate(nums): if elt < 0: number_of_negatives += 1 if least_negative_idx == -1 or \ elt < nums[least_negative_idx]: least_negative_idx = idx if greatest_negative_idx == -1 or \ elt > nums[greatest_negative_idx]: greatest_negative_idx = idx else: if least_positive_idx == -1 or \ elt < nums[least_positive_idx]: least_positive_idx = idx if number_of_negatives % 2 == 0: if number_of_negatives < len(nums): idx_to_skip = least_positive_idx else: idx_to_skip = least_negative_idx else: idx_to_skip = greatest_negative_idx multiple = 1 for idx, elt in enumerate(nums): if idx != idx_to_skip: multiple *= elt return multiple
def total_cost(J_content, J_style, alpha = 10, beta = 40): """ Computes the total cost function Arguments: J_content -- content cost coded above J_style -- style cost coded above alpha -- hyperparameter weighting the importance of the content cost beta -- hyperparameter weighting the importance of the style cost Returns: J -- total cost as defined by the formula above. """ J = alpha * J_content + beta * J_style return J
def accusative(pronoun): """ Method to convert a pronoun to accusative form """ if pronoun == 'she': return 'her' elif pronoun in ['he','his']: return 'him' elif pronoun in ['they','their']: return 'them' else: return pronoun
def fuzzy_list_match(line, ldata): """ Searches for a line in a list of lines and returns the match if found. Examples -------- >>> tmp = fuzzy_list_match("data tmp", ["other", "data", "else"]) >>> print(tmp) (True, "data") >>> tmp = fuzzy_list_match("thing", ["other", "else"]) >>> print(tmp) (False, None) """ for match in ldata: if match in line: return True, match return False, None
def filter_words(st): """ Write a function taking in a string like WOW this is REALLY amazing and returning Wow this is really amazing. """ return st.capitalize()
def nomial_latex_helper(c, pos_vars, neg_vars): """Combines (varlatex, exponent) tuples, separated by positive vs negative exponent, into a single latex string.""" pvarstrs = ['%s^{%.2g}' % (varl, x) if "%.2g" % x != "1" else varl for (varl, x) in pos_vars] nvarstrs = ['%s^{%.2g}' % (varl, -x) if "%.2g" % -x != "1" else varl for (varl, x) in neg_vars] pvarstr = " ".join(sorted(pvarstrs)) nvarstr = " ".join(sorted(nvarstrs)) cstr = "%.2g" % c if pos_vars and cstr in ["1", "-1"]: cstr = cstr[:-1] else: cstr = "%.4g" % c if "e" in cstr: # use exponential notation idx = cstr.index("e") cstr = "%s \\times 10^{%i}" % (cstr[:idx], int(cstr[idx+1:])) if pos_vars and neg_vars: return "%s\\frac{%s}{%s}" % (cstr, pvarstr, nvarstr) if neg_vars and not pos_vars: return "\\frac{%s}{%s}" % (cstr, nvarstr) if pos_vars: return "%s%s" % (cstr, pvarstr) return "%s" % cstr
def is_phrase_a_substring_in_list(phrase, check_list): """ :param phrase: string to check if Substring :param check_list: list of strings to check against :return: True if phrase is a substring of any in check_list, otherwise false >>> x = ["apples", "bananas", "coconuts"] >>> is_phrase_a_substring_in_list("app", x) True >>> is_phrase_a_substring_in_list("blue", x) False """ return any(phrase in x for x in check_list)