content
stringlengths
42
6.51k
def groupby(func, seq): """ Group a collection by a key function >>> from sympy.multipledispatch.utils import groupby >>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank'] >>> groupby(len, names) # doctest: +SKIP {3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']} >>> iseven = lambda x: x % 2 == 0 >>> groupby(iseven, [1, 2, 3, 4, 5, 6, 7, 8]) # doctest: +SKIP {False: [1, 3, 5, 7], True: [2, 4, 6, 8]} See Also: ``countby`` """ d = dict() for item in seq: key = func(item) if key not in d: d[key] = list() d[key].append(item) return d
def getPath(arch): """ Different paths for different architectures """ return "c:/windows/temp/cmd.war" if arch is "windows" else "/tmp/cmd.war"
def get_url_walmart(search_term): """ :param search_term: :return: """ template = "https://www.walmart.com/search?q={}" search_term = search_term.replace(" ", "+") url = template.format(search_term) print(f"Constructed Walmart URL: \n >>{url}<<") return url
def repeated_square(a, n, mod=None): """ Computes a^n % mod, with a belonging to a ring with 1 (not checked) and n > 0. """ ns = list(bin(n)[2:])[1:] b = a for coef in ns: if coef == '1': b = (b * b * a) else: b = (b * b) if mod is not None: b %= mod return b
def custom_func_average(populator, *args, **kwargs): """Get an Excel formula to calculate the average of multiple values. Parameters ---------- args : list A list of all values to calcualte the average of. Any value that is empty ("") or nan ("nan") are ignored. """ args = [a for a in args if a not in ["", "nan"]] if len(args) == 0: return "" ##DIV/0!" return "AVERAGE({})".format(",".join(args))
def GetInstanceTypeByCPU(cpu_cores: int) -> str: """Return the instance type for the requested number of CPU cores. Args: cpu_cores (int): The number of requested cores. Returns: str: The type of instance that matches the number of cores. Raises: ValueError: If the requested amount of cores is unavailable. """ cpu_cores_to_instance_type = { 1: 't2.small', 2: 'm4.large', 4: 'm4.xlarge', 8: 'm4.2xlarge', 16: 'm4.4xlarge', 32: 'm5.8xlarge', 40: 'm4.10xlarge', 48: 'm5.12xlarge', 64: 'm4.16xlarge', 96: 'm5.24xlarge', 128: 'x1.32xlarge' } if cpu_cores not in cpu_cores_to_instance_type: raise ValueError( 'Cannot start a machine with {0:d} CPU cores. CPU cores should be one' ' of: {1:s}'.format( cpu_cores, ', '.join(map(str, cpu_cores_to_instance_type.keys())) )) return cpu_cores_to_instance_type[cpu_cores]
def _is_projective(parse): """ Is the parse tree projective? Returns -------- projective : bool True if a projective tree. """ for m, h in enumerate(parse): for m2, h2 in enumerate(parse): if m2 == m: continue if m < h: if ( m < m2 < h < h2 or m < h2 < h < m2 or m2 < m < h2 < h or h2 < m < m2 < h ): return False if h < m: if ( h < m2 < m < h2 or h < h2 < m < m2 or m2 < h < h2 < m or h2 < h < m2 < m ): return False return True
def RK4(diffeq, y0, t, h): """ RK4 method for ODEs: Given y0 at t, returns y1 at t+h """ k1 = h*diffeq(y0, t) # dy/dt at t k2 = h*diffeq(y0+0.5*k1, t + h/2.) # dy/dt at t+h/2 k3 = h*diffeq(y0+0.5*k2, t + h/2.) # dy/dt at t+h/2 k4 = h*diffeq(y0+k3, t + h) # dy/dt at t+h return y0 + (k1+k4)/6.0 + (k2+k3)/3.0
def is_empty(text): """ Determine if a string value is either None or an empty string. :param text: the string to test :return: True, if the string has no content, False otherwise """ return text is None or len(text) == 0
def convert_to_float(frac_str): """ convert string of fraction (1/3) to float (0.3333) Parameters ---------- frac_str: string, string to be transloated into Returns ------- float value corresponding to the string of fraction """ try: return float(frac_str) except ValueError: num, denom = frac_str.split('/') try: leading, num = num.split(' ') whole = float(leading) except ValueError: whole = 0 frac = float(num) / float(denom) return whole - frac if whole < 0 else whole + frac
def sphinx_swaps(start, goal, limit): """A diff function for autocorrect that determines how many letters in START need to be substituted to create GOAL, then adds the difference in their lengths and returns the result. Arguments: start: a starting word goal: a string representing a desired goal word limit: a number representing an upper bound on the number of chars that must change >>> big_limit = 10 >>> sphinx_swaps("nice", "rice", big_limit) # Substitute: n -> r 1 >>> sphinx_swaps("range", "rungs", big_limit) # Substitute: a -> u, e -> s 2 >>> sphinx_swaps("pill", "pillage", big_limit) # Don't substitute anything, length difference of 3. 3 >>> sphinx_swaps("roses", "arose", big_limit) # Substitute: r -> a, o -> r, s -> o, e -> s, s -> e 5 >>> sphinx_swaps("rose", "hello", big_limit) # Substitute: r->h, o->e, s->l, e->l, length difference of 1. 5 """ # BEGIN PROBLEM 6 if len(start) == 0: return len(goal) elif len(goal) == 0: return len(start) elif start == goal: return 0 elif limit < 0: return 1 elif start[0] == goal[0]: return sphinx_swaps(start[1:],goal[1:],limit) elif start[0] != goal[0]: return 1 + sphinx_swaps(start[1:],goal[1:],limit-1) # END PROBLEM 6
def rights_converter(term): """A converter for normalizing the rights string. This is based on the assumption that the FGDC rights statement will contain the word ``unrestricted`` when a layer is public and ``restricted`` when it is not. """ if term.lower().startswith('unrestricted'): return 'Public' elif term.lower().startswith('restricted'): return 'Restricted' return term
def wrap_with_run(code: str) -> str: """Wrap with a run so it is a function, not a 'script'""" lines = code.split("\n") good_lines = ["def run() -> None:"] for line in lines: good_lines.append(" " + line) return "\n".join(good_lines)
def preprocess_gdelt_gkg_location(x): """ For GDELT GKG """ res_list = [] # print(x) for location in x: x_split = location.split('#') res = dict() res['type'] = x_split[0] res['full_name'] = x_split[1] res['country_code'] = x_split[2] res['adm1_code'] = x_split[3] res['latitude'] = x_split[4] res['longitude'] = x_split[5] res['featureID'] = x_split[6] res_list.append(res) return res_list
def fast_floatformat(number, places=-1, use_thousand_separator=False): """simple_floatformat(number:object, places:int) -> str Like django.template.defaultfilters.floatformat but not locale aware and between 40 and 200 times faster """ try: number = float(number) except (ValueError, TypeError): return number #return '' # floatformat makes -0.0 == 0.0 if number == 0: number = 0 neg_places = False if places < 0: places = abs(places) neg_places = True if places == 0: # %.0f will truncate rather than round number = round(number, places) # .format is noticably slower than %-formatting, use it only if necessary if use_thousand_separator: format_str = "{:,.%sf}" % places formatted_number = format_str.format(number) else: format_str = "%%.%sf" % places formatted_number = format_str % number # -places means formatting to places, unless they're all 0 after places if neg_places: str_number = str(number) if not "." in str_number: return str_number if len(str_number) > len(formatted_number): return formatted_number int_part, _, _ = formatted_number.partition(".") if str_number.rstrip("0")[-1] == ".": return int_part return formatted_number
def _p_value_color_format(pval): """Auxiliary function to set p-value color -- green or red.""" color = "green" if pval < 0.05 else "red" return "color: %s" % color
def register_server( body ): # noqa: E501 """Register a server Add an API server to the testbed. # noqa: E501 :param body: :type body: dict | bytes :rtype: str """ return 'Not Implemented', 501
def item_repr(ob): """Generates a repr without angle brackets (to avoid HTML quoting)""" return repr(ob).replace('<', '(').replace('>', ')')
def peak_colors(peak_list, colors=["k", "b", "r", "g", "c", "m"]): """ This is a fill-in function until I've got some kind of standard colors implemented. It takes a list of integral ranges and returns an identically indexed dictionary with each value of the form (integral_range, color) """ integrals = {} for i, integral in enumerate(peak_list): integrals[i] = (integral, colors[i]) return integrals
def unquote(str): """Remove quotes from a string.""" if len(str) > 1: if str[0] == '"' and str[-1:] == '"': return str[1:-1] if str[0] == '<' and str[-1:] == '>': return str[1:-1] return str
def get_change_of_set(orig_set, obj, mode): """ get a tuple change_tuple=(increased, decreased), assuming one changes the set with the object (add or remove) """ if mode == '+': if obj not in orig_set: # new object to add to the set return (obj, None) elif mode == '-': if obj in orig_set: # existing object to remove from the set return (None, obj) # set unchanged return (None, None)
def linear_search(items, x): """Searches for an item in a list of items. Uses linear search to find the index of x in the list items. Args: x: An item. items: A list of items. Returns: The index of x if it is in the list items, otherwise None. """ for i in range(len(items)): if x == items[i]: return i return None
def historical_imagery_photo_type_to_linz_geospatial_type(photo_type: str) -> str: """Find value in dict and return linz_geospatial_type, else return the original value string. """ geospatial_type_conversion_table = { "B&W": "black and white image", "B&W IR": "black and white infrared image", "COLOUR": "color image", "COLOUR IR": "color infrared image", } lgs_value = geospatial_type_conversion_table.get(photo_type.strip().upper()) if lgs_value: return lgs_value else: return photo_type
def get_numeric_list(numeric_range): """Convert a string of numeric ranges into an expanded list of integers. Example: "0-3,7,9-13,15" -> [0, 1, 2, 3, 7, 9, 10, 11, 12, 13, 15] Args: numeric_range (str): the string of numbers and/or ranges of numbers to convert Raises: AttributeError: if the syntax of the numeric_range argument is invalid Returns: list: an expanded list of integers """ numeric_list = [] try: for item in numeric_range.split(","): if "-" in item: range_args = [int(val) for val in item.split("-")] range_args[-1] += 1 numeric_list.extend([int(val) for val in range(*range_args)]) else: numeric_list.append(int(item)) except (AttributeError, ValueError, TypeError) as error: raise AttributeError( "Invalid 'numeric_range' argument - must be a string containing " "only numbers, dashes (-), and/or commas (,): {}".format( numeric_range)) from error return numeric_list
def hanoi(n, a, b, c): """ >>> hanoi(5, "a", "b", "c") [('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b'), ('c', 'a'), ('c', 'b'), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('b', 'a'), ('c', 'a'), ('b', 'c'), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b'), ('c', 'a'), ('c', 'b'), ('a', 'b'), ('c', 'a'), ('b', 'c'), ('b', 'a'), ('c', 'a'), ('c', 'b'), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b'), ('c', 'a'), ('c', 'b'), ('a', 'b')] """ if n == 0: return [] else: return hanoi(n-1, a, c, b) + [(a, b)] + hanoi(n-1, c, b, a)
def file_contains_string(path, string): """Returns whether the file named by path contains string. Args: path: path of the file to search. string: string to search the file for. Returns: True if file contains string, False otherwise. """ with open(path, 'r') as f: for line in f: if string in line: return True return False
def remove_noise_char(word): """ Parser and disambiguator can express the information about which meaning a word has. This helper function removes this information. :param word: A corpus word. :type word: str :return: The corpus word stripped off the information mentioned above. :rtype: str """ return word[:word.index("(i")] if "(i" in word else word
def sort_portals(ab, maxx, maxy): """Returns portals in (inner, outer) order.""" (ax, ay), (bx, by) = ab ba = ab[1], ab[0] if ax == 2 or ay == 2 or ax == maxx - 2 or ay == maxy - 2: return ba elif bx == 2 or by == 2 or bx == maxx - 2 or by == maxy - 2: return ab raise ValueError(f'Cannot sort portals {ab}')
def search4letters(phrase, letters='aeiou'): """ ->return a set of the 'letters' found in 'phrase'. :param phrase: phrase where the search will be made :param letters:set of letters that will be searched for in the sentence :return returns a set () """ return set(letters).intersection(set(phrase))
def _get_column_letter(col_idx): """Convert a column number into a column letter (3 -> 'C') Right shift the column col_idx by 26 to find column letters in reverse order. These numbers are 1-based, and can be converted to ASCII ordinals by adding 64. """ # these indicies corrospond to A -> ZZZ and include all allowed # columns if not 1 <= col_idx <= 18278: raise ValueError("Invalid column index {0}".format(col_idx)) letters = [] while col_idx > 0: col_idx, remainder = divmod(col_idx, 26) # check for exact division and borrow if needed if remainder == 0: remainder = 26 col_idx -= 1 letters.append(chr(remainder+64)) return ''.join(reversed(letters))
def miles_to_kilometers(d_in_miles): """Convert distance from miles to kilometers PARAMETERS ---------- d_in_miles : float A distance in miles RETURNS ------- d_in_kms : float A distance in kilometers """ d_in_kms = 1.60934*d_in_miles return d_in_kms
def get_baseline_number_from_name(baseline): """ This helper function will retrieve parse the default baseline name structure for the # in it. The default structure is B# <DATE> for example a baseline name:, 'B12 032120' would return '12' :param baseline: The baseline that needs its name parsed :return: The Baseline "revision" number """ baseline_name = baseline.get('name') # Split on the space, get the first part; drop the 'B' return str(baseline_name).split(' ')[0][1:]
def chimera_to_ind(r: int, c: int, z: int, L: int): """[summary] Args: r (int): row index c (int): column index z (int): in-chimera index (must be from 0 to 7) L (int): height and width of chimera-units (total number of spins is :math:`L \\times L \\times 8`) Raises: ValueError: [description] Returns: int: corresponding Chimera index """ if not (0 <= r < L and 0 <= c < L and 0 <= z < 8): raise ValueError( '0 <= r < L or 0 <= c < L or 0 <= z < 8. ' 'your input r={}, c={}, z={}, L={}'.format(r, c, z, L)) return r * L * 8 + c*8 + z
def nth_combination(iterable, r, index): """Equivalent to ``list(combinations(iterable, r))[index]``. The subsequences of *iterable* that are of length *r* can be ordered lexicographically. :func:`nth_combination` computes the subsequence at sort position *index* directly, without computing the previous subsequences. """ pool = tuple(iterable) n = len(pool) if (r < 0) or (r > n): raise ValueError c = 1 k = min(r, n - r) for i in range(1, k + 1): c = c * (n - k + i) // i if index < 0: index += c if (index < 0) or (index >= c): raise IndexError result = [] while r: c, n, r = c * r // n, n - 1, r - 1 while index >= c: index -= c c, n = c * (n - r) // n, n - 1 result.append(pool[-1 - n]) return tuple(result)
def are_in_file(file_path, strs_to_find): """Returns true if every string in the given strs_to_find array is found in at least one line in the given file. In particular, returns true if strs_to_find is empty. Note that the strs_to_find parameter is mutated.""" infile = open(file_path) for line in infile: if len(strs_to_find) == 0: return True index = 0 while index < len(strs_to_find): if strs_to_find[index] in line: del strs_to_find[index] else: index = index + 1 return len(strs_to_find) == 0
def _hydrogen_count_from_string(nhyd_str): """ Get the hydrogen count from a SMILES hydrogen count string Example: 'H' returns 1 and 'H2' returns 2 """ if nhyd_str == 'H': nhyd = 1 else: nhyd = int(nhyd_str[1:]) return nhyd
def _row_to_chemical(row): """ Helper function to translate from a row in a pandas data frame to a dictionary with the desired schema. Parameters ---------- row : :class:`pd.Series` Row from pandas dataframe. Must have entries for ``'Chemical Formula'``,``'Property 1 value'`` and ``'Property 2 value'``. Returns ------- dict Dictionary containing chemical data in a more convient format, i.e. ``{'formula': ..., 'band_gap': ..., 'color': ...}``. """ return { 'formula': row['Chemical formula'], 'band_gap': row['Property 1 value'], 'color': row['Property 2 value'], }
def mergeDictionaries(*dicts): """mergeDictionaries(*dicts): merge dictionaries into a new one""" merged = {} for d in dicts: merged.update(d) return merged
def valid_history(history, expected_count, expected_messages=None): """Checks if history is valid""" expected_messages = expected_messages or [] if len(history) != expected_count: return False for i, value in enumerate(expected_messages): if history[i]["type"] != value: return False return True
def convert_error_dict_to_list(error_dict, error_code=None): """ Given an error dict (returned by Marshmallow), convert into a list of errors """ return_value = [] for f, errors in error_dict.items(): # error can be a string, a dictionary, list of string or a list of dictionary if isinstance(errors, str) or isinstance(errors, dict): # if error is just a singular, wrap it in a list so we can treat it the same way errors = [errors] for error in errors: if isinstance(error, dict): error['property'] = f elif isinstance(error, str): error = dict(message=error, property=f) if error_code is not None: error['error_code'] = error_code return_value.append(error) return return_value
def generate_anisotropy_str(anisotropy): """Generate a string from anisotropy specification parameters. Parameters ---------- anisotropy : None or tuple of values Returns ------- anisotropy_str : string """ if anisotropy is None: anisotropy_str = 'none' else: anisotropy_str = '_'.join(str(param) for param in anisotropy) return anisotropy_str
def sections(classified, sects=None): """Returns sections (and their items) from a nested dict. See also: L{classify} @param classified: Nested dictionary. @type classified: C{dict} @param sects: List of results. It should not be specified by the user. @type sects: C{list} @return: A list of lists in where each item is a subsection of a nested dictionary. @rtype: C{list} """ if sects is None: sects = [] if isinstance(classified, dict): for key in classified.keys(): sections(classified[key], sects) elif isinstance(classified, list): sects.append(classified) return sects
def any_value(items: list): """ Function that extracts values from a list and checks if they are diff from None,0,{},[],False... First value that is diff from them is being returned :param items: List of items that is searched for non-null values :return: First value that fits the criteria """ for item in items: if item: return item
def find_largest_number(list_of_nums): """ Use this as an example of how to work through the steps in the lesson. """ largest_num = list_of_nums[0] for num in list_of_nums: if num > largest_num: largest_num = num return largest_num
def get_title_content(json_elem): """ Allows to generate a title content for a given json element json_elem. """ title_content = "" if json_elem["Count"] > 0: if json_elem["Count"] > 10: for i in range(10): title_content = title_content + json_elem["Names"][i] + ", " title_content = title_content + "..." else: for i in range(json_elem["Count"] - 1): title_content = title_content + json_elem["Names"][i] + ", " title_content = title_content + json_elem["Names"][json_elem["Count"] - 1] return title_content
def make_info_page(data, preview=False): """ Given a data entry from a make_info output, create a file description page. This includes the template and any formatted categories. Preview mode adds the final filename to the top of the page and makes the categories visible instead of categorising the page. @param data: dict with the keys {cats, meta_cats, info, filename} @param preview: if output should be done in preview mode @return: str """ # handle categories separator = '\n\n' # standard separation before categories cats_as_text = '' if data['meta_cats']: cats_as_text += separator cats_as_text += '<!-- Metadata categories -->\n' cats_as_text += '\n'.join(sorted( ['[[Category:{}]]'.format(cat) for cat in data.get('meta_cats')])) if data['cats']: cats_as_text += separator cats_as_text += '<!-- Content categories -->\n' cats_as_text += '\n'.join(sorted( ['[[Category:{}]]'.format(cat) for cat in data.get('cats')])) if preview: text = 'Filename: {filename}.<ext>\n{template}{cats}'.format( filename=data['filename'], template=data['info'], cats=cats_as_text.replace('[[Category:', '* [[:Category:') .replace('<!-- ', "''") .replace(' -->', ":''")) else: text = '{template}{cats}'.format( template=data['info'], cats=cats_as_text) return text.strip()
def adjust_fg_positions(fg_id, positions): """ Adjusts a prospect's position given their fangraphs player_id (fg_id). Not heavily necessary unless a player has been mis-classified as a pitcher when they should be a hitter or vice versa. """ positions_dict = { } if fg_id in positions_dict: positions = positions_dict.get(fg_id) return positions else: return positions
def vector_to_string(vector, sep): """Convert 1D vector to String. Parameters ---------- vector - array-like : vector to convert sep - String : String to use as separator between elements Returns ------- strVector - String : vector as String with elements separated by sep """ strVector = "" for el in vector[:-1]: strVector += str(el) + sep return strVector + str(vector[-1])
def is_function(value): """ Check if a param is a function :param value: object to check for :return: """ return hasattr(value, '__call__')
def get_spelling_suggestions(spelling_suggestions): """Returns spelling suggestions from JSON if any """ res = [] if spelling_suggestions and spelling_suggestions[0] and spelling_suggestions[0]['s']: res = spelling_suggestions[0]['s'] return res
def merge_list(list1, list2): """ Merges the contents of two lists into a new list. :param list1: the first list :type list1: list :param list2: the second list :type list2: list :returns: list """ merged = list(list1) for value in list2: if value not in merged: merged.append(value) return merged
def label_latexify(label): """ Convert a label to latex format by appending surrounding $ and escaping spaces Parameters ---------- label : str The label string to be converted to latex expression Returns ------- str A string with $ surrounding """ return '$' + label.replace(' ', r'\ ') + '$'
def get_alg_shortcode(alg_str): """ Get shortcode for the models, passed in as a list of strings """ if alg_str == "adahedged": return "ah" else: return alg_str
def f90float(s): """Convert string repr of Fortran floating point to Python double""" return float(s.lower().replace('d', 'e'))
def parse_csv_results(csv_obj, upper_limit_data): """ Parses the raw CSV data Convers the csv_obj into an array of valid values for averages and confidence intervals based on the described upper_limits. Args: csv_obj: An array of rows (dict) descriving the CSV results upper_limit_data: A dictionary containing the upper limits of each story Raturns: A dictionary which has the stories as keys and an array of confidence intervals and valid averages as data. """ values_per_story = {} for row in csv_obj: # For now only frame_times is used for testing representatives' # performance. if row['name'] != 'frame_times': continue story_name = row['stories'] if (story_name not in upper_limit_data): continue if story_name not in values_per_story: values_per_story[story_name] = { 'averages': [], 'ci_095': [] } if (row['avg'] == '' or row['count'] == 0): continue values_per_story[story_name]['ci_095'].append(float(row['ci_095'])) values_per_story[story_name]['averages'].append(float(row['avg'])) return values_per_story
def get_elapsed(start, end): """ used to calculate the time between two time stamps :param start: start time :param end: end time :return: a string in minutes or seconds for the elapsed time """ elapsed = end - start if elapsed < 60: return '{0:.2g}'.format(end - start) + " seconds" else: return '{0:.2g}'.format((end - start) / 60.0) + " minutes"
def get_code ( x, code_out, code_in ): """Convert from one coding to another :Parameters: *x* input to be coded *code_out* desired code of the output *code_in* code of the input :Example: >>> code_out = [-1,1] >>> code_in = [0,1] >>> get_code ( 1., code_out, code_in ) 1 >>> get_code ( 0., code_out, code_in ) -1 >>> get_code ( 0., code_in, code_in ) 0 >>> get_code ( 0., code_in, code_out ) Traceback (most recent call last): ... ValueError: list.index(x): x not in list """ if isinstance ( code_in, (list,tuple) ): return code_out[code_in.index(x)] else: return code_out[code_in.tolist ().index(x)]
def assign_signal_vals(sig_sets): """Assign values to each signal in a list of signal sets. Values are assigned so that the values in each set are unique. A greedy algorithm is used to minimise the signal values used. A dictionary of signal values index by signal is returned. """ signals = set().union(*sig_sets) possible_vals = set(range(len(signals))) assigned = {} # Sort the signals so that assign_signal_vals is deterministic based on input. # Without sorting Python iterates the signals set in arbitrary order. # Note that possibly changes on each Python invocation based on the hashing seed. for sig in sorted(signals): used_vals = [{assigned.get(ss) for ss in sig_set} for sig_set in sig_sets if sig in sig_set] assigned[sig] = min(possible_vals.difference(*used_vals)) assert all(len({assigned[x] for x in sig_set}) == len(sig_set) for sig_set in sig_sets) # Returned dictionary should only be used for lookup, not iteration to ensure overall process is deterministic. return assigned
def linear_search(List, item): """ Find the element in list using linear search >>> from pydsa.searching.linear_search import linear_search >>> List = [3, 4, 6, 8, 12, 15, 26] >>> item = 6 >>> linear_search(List, item) 2 """ index = len(List) for i in range(0, index): if List[i] == item: return i return -1
def get_figsize(aspect_ratio, max_dim=16.0, min_dim=0.0): """Return tuple based on aspect ratio and desired size. Arguments: aspect_ratio (float): (ymax - ymin)/(xmax - xmin) max_dim (float, inches): Maximum size in either dimension. min_dim (float, inches): Minimum size in either dimension. If supplied, this takes precedence over the aspect ratio when the two conflict. Returns: figsize (tuple (xwidth, ywidth)): Figure size with given aspect ratio """ if not (aspect_ratio > 0.0): raise ValueError(f"Bad aspect ratio {aspect_ratio}") if aspect_ratio > 1: y = max_dim x = max(y / aspect_ratio, min_dim) else: x = max_dim y = max(x * aspect_ratio, min_dim) return (x, y)
def build_sort_args(sortFlds): """ Build sort argumenets :param sortFlds: :return: """ print ("-- There are %s sort fields specified --" % sortFlds) args = () flds = str(sortFlds).split(',') if len(flds) > 0: args = tuple(flds) print ("-- Sort Fields --", args) return args
def getUnigram(words): """ Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of unigram """ assert type(words) == list return words
def pow2_exponent(val: int) -> int: """Compute exponent of power of 2.""" count = 0 while val > 1: count += 1 val >>= 1 assert val == 1 return count
def constraint_5(maze): """Checks that each cell is reachable from an adjacent cell.""" # Asserts that each cell is not a tuple of four Falses. for row in maze: for cell in row: list_5 = [False for direction in cell if direction is False] if len(list_5) == 4: return(False)
def calc_temp(delta_h, t_0, lapse): """ Calculates atmospheric temperature assuming constant lapse rate Args delta_h - difference in geopotential heights between layers in m t_0 - base temperature of previous layer in K lapse - lapse rate in K/m Return temperature - float in units of K """ return t_0 + lapse * delta_h
def revac(b, root=True): """ Another very basic symetric cipher function that just makes sure keys don't get stored in cleartext :param b: (bytes) byte sequence to cipher :param root: (bool) used for recursion, do not give any arguments :return: (bytes) ciphered byte sequence """ l = len(b) hl = int(l / 2) if l == 1: return b elif not l % 2 and l <= 2: result = [b[1], b[0]] elif not l % 3 and l <= 3: result = [b[2], b[1], b[0]] elif not l % 4: result = revac(b[0:hl], root=False) + revac(b[hl:l], root=False) elif not l % 6: result = revac(b[0:hl], root=False) + revac(b[hl:l], root=False) else: result = revac(b[0:hl], root=False) + [b[hl]] + revac(b[hl + 1:l], root=False) if root: return bytes(result) else: return result
def analysis_krn(analysis): """ Returns a dictionary of keywords by row. This index can be used to quicky find a keyword by row. 'krn' stands for 'keyword row name'. """ return analysis.get("krn", {})
def round_up(x,step): """Rounds x up to the next multiple of step.""" from math import ceil if step == 0: return x return ceil(float(x)/float(step))*step
def replace_missing(value, missing=0.0): """Returns missing code if passed value is missing, or the passed value if it is not missing; a missing value in the EDF contains only a period, no numbers; NOTE: this function is for gaze position values only, NOT for pupil size, as missing pupil size data is coded '0.0' arguments value - either an X or a Y gaze position value (NOT pupil size! This is coded '0.0') keyword arguments missing - the missing code to replace missing data with (default = 0.0) returns value - either a missing code, or a float value of the gaze position """ if value.replace(' ','') == '.': return missing else: return float(value)
def buoy_distance(pixel_width, focal_length, ACTUAL_WIDTH=0.4): """ Calculates the distance of the buoy from the boat. The algorithm uses the similar triangles in the following equation: (focal_len / pixel_width) = (actual_distance / actual_width) Keyword arguments: pixel_width -- The width of the buoy in pixels focal_length -- The focal length of the camera in pixels ACTUAL_WIDTH -- The actual width of the buoy in desired units (default 0.4m) Returns: distance -- The distance of the buoy in the units of the ACTUAL_WIDTH """ return focal_length * ACTUAL_WIDTH / pixel_width
def run_now_endpoint(host): """ Utility function to generate the run now endpoint given the host. """ return f'https://{host}/api/2.1/jobs/run-now'
def encode_string(data: str) -> bytes: """ Takes a string and return a bytes encoded version of the data. Must be reversible with `decode_bytes()`. """ return data.encode("utf-8")
def div_by_nums(i, nums): """ Test if number (i) is divisible by array of numbers (nums) :param i: :param nums: :return: """ for n in nums: if i % n == 0: return True return False
def host_and_port(value): """ Parse "host:port" string into (host, port) tuple. >>> host_and_port('host:1') ('host', 1) >>> host_and_port(' host:1 ') ('host', 1) >>> host_and_port('host:foo') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "reloadconf/__main__.py", line 33, in host_and_port return host.strip(), int(port.strip()) ValueError: invalid literal for int() with base 10: 'foo' """ host, port = value.split(':') return host.strip(), int(port.strip())
def get_total_chemsys(entries, open_elem=None): """ Args: entries: open_elem: Returns: """ elements = {elem for entry in entries for elem in entry.composition.elements} if open_elem: elements.add(open_elem) return "-".join(sorted([str(e) for e in elements]))
def contfractbeta( a: float, b: float, x: float, ITMAX: int = 5000, EPS: float = 1.0e-7 ) -> float: """Continued fraction form of the incomplete Beta function. Code translated from: Numerical Recipes in C. Example kindly taken from blog: https://malishoaib.wordpress.com/2014/04/15/the-beautiful-beta-functions-in-raw-python/ :param float a: a :param float b: b :param float x: x :param int ITMAX: max number of iterations, default is 5000. :param float EPS: epsilon precision parameter, default is 1e-7. :returns: continued fraction form :rtype: float """ az = 1.0 bm = 1.0 am = 1.0 qab = a + b qap = a + 1.0 qam = a - 1.0 bz = 1.0 - qab * x / qap for i in range(ITMAX + 1): em = float(i + 1) tem = em + em d = em * (b - em) * x / ((qam + tem) * (a + tem)) ap = az + d * am bp = bz + d * bm d = -(a + em) * (qab + em) * x / ((qap + tem) * (a + tem)) app = ap + d * az bpp = bp + d * bz aold = az am = ap / bpp bm = bp / bpp az = app / bpp bz = 1.0 if abs(az - aold) < EPS * abs(az): return az raise ValueError( "a={0:f} or b={1:f} too large, or ITMAX={2:d} too small to compute incomplete beta function.".format( a, b, ITMAX ) )
def ts(strr): """Changes a string of the form b'\xc3' into the form "\xc3" """ return str(strr)[1:].replace('\'', '\"')
def sent_error_setup(creds, s3_folder, device_value, search_value): """Send error test setup.""" return creds, s3_folder, search_value, device_value
def myfunc(n): """Python 2 example.""" return '#' * n
def log2b(value): """Binary log2""" log_val = 0 while value != 0: value >>= 1 log_val += 1 return log_val
def isscalar(x): """Is x a scalar type?""" # Workaroud for a bug in numpy's "isscalar" returning false for None. from numpy import isscalar return isscalar(x) or x is None
def lower_keys(x): """converts the payload dict keys to all lowercase to match schema Args: x:payload """ if isinstance(x, dict): return dict((k.lower(), v) for k, v in x.items()) else: return "msg_fromat_incorrect"
def git_ref_from_eups_version(version: str) -> str: """Given a version string from the EUPS tag file, find something that looks like a Git ref. """ return version.split("+")[0]
def v_str(v_tuple): """turn (2,0,1) into '2.0.1'.""" return ".".join(str(x) for x in v_tuple)
def findFunc(point1, point2): """find the linear function that fits two points""" #if((point1[0] == 0.0) and (point2[0] == 0.0)): # m = "dne" # b = "dne" #elif((point1[1] == 0.0) and (point2[1] == 0.0)): # m = 0 # b = 0 #else: m = ((point2[1] - point1[1]) / (point2[0] - point1[0])) b = (((point2[0] * point1[1]) - (point1[0] * point2[1])) / (point2[0] - point1 [0])) return m, b
def all_equal(a): """Constrains all elements of a to be either 0 or 1 """ cnf = [] for a0, a1 in zip(a, a[1:]): cnf.extend([[a0, -a1], [-a0, a1]]) return cnf
def is_int(msg): """Method used to check whether the given message is an integer return int or raises an exception if message is not an integer """ try: return int(msg) except ValueError: raise Exception("Unexpected message format (expected an integer). Message: %s" % (msg))
def internal_dot(u, v): """Returns the dot product of two vectors. Should be identical to the output of numpy.dot(u, v). """ return u[0]*v[0] + u[1]*v[1] + u[2]*v[2]
def tail(f, window=20): """ Returns the last *window* lines of file object *f* as a list. From http://stackoverflow.com/a/7047765/6226265. """ if window == 0: return [] BUFSIZ = 1024 f.seek(0, 2) bytes_i = f.tell() size = window + 1 block = -1 data = [] while size > 0 and bytes_i > 0: if bytes_i - BUFSIZ > 0: # Seek back one whole BUFSIZ f.seek(block * BUFSIZ, 2) # read BUFFER data.insert(0, f.read(BUFSIZ)) else: # file too small, start from beginning f.seek(0,0) # only read what was not read data.insert(0, f.read(bytes_i)) linesFound = data[0].count('\n') size -= linesFound bytes_i -= BUFSIZ block -= 1 return ''.join(data).splitlines()[-window:]
def reverse_str(str): """ Returns reversed str """ if len(str) == 1: return str return str[-1] + reverse_str(str[:-1])
def is_rgb(in_col): """ Check whether input is a valid RGB color. Return True if it is, otherwise False. """ if len(in_col) == 3 and type(in_col) == tuple: if ( type(in_col[0]) is int and type(in_col[1]) and type(in_col[2]) and 0 <= in_col[0] <= 255 and 0 <= in_col[1] <= 255 and 0 <= in_col[2] <= 255 ): return True else: return False else: return False
def tomo_dagger(tomo_op): """ the dagger of OP is -OP the dagger of OP+ is OP-""" if tomo_op[0] == '-': return tomo_op[1:] if tomo_op[-1] == '-': return tomo_op[:-1] + '+' if tomo_op[-1] == '+': return tomo_op[:-1] + '-' else: return '-' + tomo_op
def get_category_name(id_, categories): """ Return category name """ if id_ is None or id_ == '': return None item = categories[int(id_)] if item['active'] is True: return item['name'] return None
def _quote_wrap(value): """Wrap a value in quotes.""" return '"{}"'.format(value)
def Bayes_oracle_estimator(data, mean_signal, std_signal, std_noise): """ See Large-scale inference: empirical Bayes methods for estimation, testing, and prediction (Efron, 2010, page 6) """ return mean_signal + (std_signal ** 2 / (std_signal ** 2 + std_noise ** 2)) * (data - mean_signal)
def get_j1939_limit(number_of_bits: int) -> int: """For a given signal length in bits, return the lowest invalid value, if the data was represented as an unsigned integer. :param number_of_bits: The length of the J1939 signal in bits. :return: The lowest possible value containing valid data. """ limit = 0 if number_of_bits == 2: limit = 0x3 elif number_of_bits == 4: limit = 0xF elif number_of_bits == 8: limit = 0xFF elif number_of_bits == 10: limit = 0x3FF elif number_of_bits == 12: limit = 0xFF0 elif number_of_bits == 16: limit = 0xFF00 elif number_of_bits == 20: limit = 0xFF000 elif number_of_bits == 24: limit = 0xFF0000 elif number_of_bits == 28: limit = 0xFF00000 elif number_of_bits == 32: limit = 0xFF000000 else: limit = 0xFFFFFFFFFFFFFFFF return limit
def internal_cross(u, v): """Returns the cross product of two vectors. Should be identical to the output of numpy.cross(u, v). """ return(u[1]*v[2] - v[1]*u[2], u[2]*v[0] - v[2]*u[0], u[0]*v[1] - v[0]*u[1])
def DATE_TO_STRING(_format, date): """ Converts a date object to a string according to a user-specified format. See https://docs.mongodb.com/manual/reference/operator/aggregation/dateToString/ for more details :param _format: The date format specification. :param date: expression or variable of a Date, a Timestamp, or an ObjectID :return: Aggregation operator """ return {'$dateToString': {'format': _format, 'date': date}}
def duplicate_encode_oneline_gen(word): """List comp version.""" return "".join("(" if word.count(c) == 1 else ")" for c in word)
def get_import_tests(pkginfo, import_tests_metada=""): """Return the section import in tests :param dict pkginfo: Package information :param dict import_tests_metada: Imports already present :return list: Sorted list with the libraries necessary for the test phase """ if not pkginfo.get("packages"): return import_tests_metada olddeps = [] if import_tests_metada != "PLACEHOLDER": olddeps = [ x for x in import_tests_metada.split() if x != "-" ] return sorted(set(olddeps) | set(pkginfo["packages"]))