content
stringlengths
42
6.51k
def fibonacci(number): """Enter a positive interger, return a fibonacci list""" # ### INSTRUCTOR COMMENT: # As noted above, this sort of input sanitation should not be in # such a simple function. Separate concerns. Simplify. (Also, it's # spelled "integer" in your docstring.) # The only test that makes sense to...
def parseFraction(f): """Parse a fraction (a string of the form N/D) returning a float. Returns None if f is not in the form N/D, or if D is 0.""" p = f.find("/") if p < 1: return None s1 = f[:p] s2 = f[p+1:] try: v1 = int(s1) v2 = int(s2) except ValueError: r...
def uniq(seq): """ Return a copy of seq without duplicates. """ seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
def RiemannSphere(z): """Map the complex plane to Riemann's sphere via stereographic projection. """ t = 1 + z.real * z.real + z.imag * z.imag return 2 * z.real / t, 2 * z.imag / t, 2 / t - 1
def _first_paragraph(text, join_lines=False): """Return the first paragraph of the given text.""" para = text.lstrip().split('\n\n', 1)[0] if join_lines: lines = [line.strip() for line in para.splitlines(0)] para = ' '.join(lines) return para
def compound_intrest(principal, time_in_years, rate_of_intrest): """ This method will compute the compound intrest """ return round(principal * (( 1 + rate_of_intrest/100 ) ** time_in_years), 2)
def create_edge(_source, _target, _label='', _edge_type=''): """Creates an edge whose id is "source_target". Parameters: _source (str): source node @id _target (str): target node @id _label (str): label shown in graph _edge_type (str): type of edge, influences shape on graph """ re...
def mantPN_val(mant, x): """ Evaluate (Horner's scheme) a MantPN `mant` at specific value `x` - scalar or other objects (like PN). Type of x is most important. Examples -------- >>> mantPN_val([3.0,0,1,2.1], 5.0) # 3 * 5**0 + 0 * 5**(-1) + 1 * 5**(-2) + 2 * 5**(-3) 3.0568 >>> mantPN_v...
def abbreviate_name(a_string, max_length): """ Abbreviate a name to the first max_length - 5 Append ellipsis to the remainder :param a_string: A string to be abbreviated :param max_length: The max length the string can be. :return: An abbreviated string """ if len(a_string) > int(max_len...
def lremove(string, prefix): """ Remove a prefix from a string, if it exists. >>> lremove('www.foo.com', 'www.') 'foo.com' >>> lremove('foo.com', 'www.') 'foo.com' """ if string.startswith(prefix): return string[len(prefix):] else: return string
def GetCamelCaseName(lower_case_name): """Converts an underscore name to a camel case name. Args: lower_case_name: The name in underscore-delimited lower case format. Returns: The name in camel case format. """ camel_case_name = '' name_parts = lower_case_name.split('_') for part in name_parts: ...
def rho_lam(z, rho_lam_0, w): """w => w(z)""" return rho_lam_0 * (1+z)**(3*(1+w(z)))
def _str_lower_equal(obj, s): """Return whether *obj* is a string equal, when lowercased, to string *s*. This helper solely exists to handle the case where *obj* is a numpy array, because in such cases, a naive ``obj == s`` would yield an array, which cannot be used in a boolean context. """ re...
def ALMAGetBandLetter( freq ): """ Return the project observing band letter from frequency * freq = Frequency in Hz """ if freq<117.0e9: return "A3" elif freq<163.0e9: return "A4" elif freq<211.0e9: return "A5" elif freq<275.0e9: return "A6" elif fre...
def quadratic_ease_in_ease_out(t, b, c, d): """ Accelerate until halfway, then decelerate. """ t /= d/2 if t < 1: return c / 2 * t * t + b t -= 1 return -c / 2 * (t * (t - 2) - 1) + b
def manifest_only(deps = [], inverse = False): """Returns only .arcs files""" if inverse: return [d for d in deps if not d.endswith(".arcs")] return [d for d in deps if d.endswith(".arcs")]
def list_update(l1, l2): """ Used instead of list(set(l1).update(l2)) to maintain order, making sure duplicates are removed from l1, not l2. """ return [e for e in l1 if e not in l2] + list(l2)
def __sizeof_fmt(num, suffix='B'): """ Get size in a human readable object. :param num: size in blocks (int) :param suffix: suffix to use for output strings (default: "B") (str) :returns: string of size (str) """ for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < ...
def emptyNone(val): """Short summary. Parameters ---------- val : dict Any dict, where None values exist. Returns ------- dict An object that matches `val` with all None values replaced with empty strings. """ for k in val.keys(): if type(val[k]) is...
def is_html(response): """ Returns True if the response is either `text/html` or `application/xhtml+xml` """ content_type = response.get('Content-Type', None) return bool(content_type and content_type.split(';')[0] in ('text/html', 'application/xhtml+xml'))
def part2(in_list): """basically a rewrite of part 1, for shame""" size = len(in_list) i = 0 steps = 0 while True: next_step = i + in_list[i] if in_list[i] >= 3: in_list[i] -= 1 else: in_list[i] += 1 if size <= next_step or next_step < 0: ...
def _to_url_params(data, glue=".", separator=","): """ Converts data dictionary to url parameters """ params = {} for key, value in data.items(): if isinstance(value, bool): params[key] = 1 if value else 0 elif isinstance(value, list): params[key] = separator....
def is_begin_tag(tag): """ Simple helper """ return tag.startswith('B-')
def convert_idx(text, tokens): """ Generate spans for answer tokens spans: List of tuples for each token: (token_start_char_idx, token_end_char_idx) """ current = 0 spans = [] for token in tokens: current = text.find(token, current) # Find position of 1st occurrence; start sear...
def hashable(obj): """ Convert obj to a hashable obj. We use the value of some fields from Elasticsearch as keys for dictionaries. This means that whatever Elasticsearch returns must be hashable, and it sometimes returns a list or dict.""" if not obj.__hash__: return str(obj) return obj
def factorial(n): """ Calcula el factorial de n. n int > 0 returns n! """ if n == 1: return 1 return n * factorial(n-1)
def makeSystemCall(args): """ make a system call @param args must be an array, the first entry being the called program @return returns a tuple with communication from the called system process, consisting of stdoutdata, stderrdata """ import subprocess msg = subprocess.Popen(args, s...
def Far2Celsius(temp): """ Simple temperature conversion for the right system (metric) """ temp = float(temp) celsius = (temp - 32) * 5 / 9 return "%0.1f" % celsius
def map(n, dep, arr, I = 0): """Remape la valeur n compris dans l'intervalle dep sur l'intervalle arr.""" (x, y) = dep (i, j) = arr res = ((n - x) * (j - i)) / (y - x) + i if I == 1: res = int(res) return res
def seconds_to_timestring(duration): """ Return a formatted time-string for the given duration in seconds. Provides auto-rescale/formatting for values down to ns resolution >>> seconds_to_timestring(1.0) '1.0s' >>> seconds_to_timestring(100e-3) '100.0ms' >>> seconds_to_timestring(500e-6)...
def fix_name(dir_name): """The dir path at this point has the project name included in it. We want to strip out the pieces we don't care about. """ if '/' not in dir_name: return None slash = dir_name.index('/') return dir_name[slash+1:]
def str_null_empty(value:str) -> str: """ Test if a string is null or empty Args: value (str): string to test Raises: TypeError: if ``value`` is not a string. ValueError: if ``value`` is null or empty. Returns: str: ``value`` """ if not isinstance(value, st...
def _handle_units(data, error): """ Handle Quantity inputs. Any units on ``data`` and ``error` are removed. ``data`` and ``error`` are returned as `~numpy.ndarray`. The returned ``unit`` represents the unit for both ``data`` and ``error``. Used to parse inputs to `~photutils.aperture.apertur...
def deleteFromList(alist, indexes, delOffset): """ deletes from the list at certain indexes Args: alist (list): a list of elements. indexes (array): an array of index to delete at. Result: the updated offset after delete operation """ for i in inde...
def merge_two_dicts(dict1, dict2): """Merge two dictionaries. :param dict dict1: :param dict dict2: :returns: merged_dict :rtype: dict """ merged_dict = dict1.copy() # start with x's keys and values merged_dict.update(dict2) # modifies z with y's keys and values & returns None ret...
def SplitTextTitleRest(title): """ This is used to split a string made of several lines separated by a "\n", following multi-line DocString convention. "Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description....
def strip_leading_numbers(s): """ Return a string removing leading words made only of numbers. """ s = s.split() while s and s[0].isdigit(): s = s[1:] return u' '.join(s)
def screen_out_path(input_fastq): """ Determine the path to the output file created by fastq_screen given an input fastq file. :param str input_fastq: Path to input fastq or fastq.gz :returns: Path to fastq_screen output file """ path_parts = input_fastq.split('.') if path_parts[-1] =...
def convert_string_to_pascal_case(string): """ Converts a strong to Pascal case """ # Split string string = [s.strip() for s in string.split(" ")] # Capitalize each word string = [s[0].upper() + s[1:] for s in string if s] # Join string string = "".join(string) # Return string re...
def get_lang_from_corpus_name(corpus_name): """ Determines the language of a corpus based on its name. """ if corpus_name.startswith("conll03_en") or corpus_name.startswith("ud_en"): return "en" elif corpus_name in ["conll03_de", "germeval"]: return "de" else: return Non...
def get_term_description(record): """Gets the term description from a course record. Removes the "Quarter" suffix from a term description, turning "Fall 2019 Quarter" into "Fall 2019". :param record: Dictionary containing the term description value. :returns: Trimmed term name. """ te...
def aslist_cronly(value): """ Split the input on lines if it's a valid string type""" if isinstance(value, str): value = filter(None, [x.strip() for x in value.splitlines()]) return list(value)
def last_consecutives(vals, step=1): """ Find the last consecutive group of numbers :param vals: Array, store numbers :param step: Step size for consecutive numberes, default 1 :return: The last group of consecutive numbers of the input vals """ group = [] expected = None for ...
def str_to_bool(my_str): """helper to return True or False based on common values""" my_str = str(my_str).lower() if my_str in ['yes', 'y', 'true', '1']: return True elif my_str in ['no', 'n', 'false', '0']: return False else: raise ValueError("unknown string for bool convers...
def luds(pwd: str): """ Get LUDS representation of a password. pwd: Password we need to handle. return: A tuple of segment list, which contains a pair of PCFG tag and length of the tag. """ struct = [] prev_tag = "" t_len = 0 cur_tag = " " for c in pwd: if c.isalpha(): ...
def formatDateTime(raw: str) -> str: """ Helper function. Converts Image exif datetime into Python datetime Args: raw (str): exif datetime string Returns: str - python compatible datetime string """ datePieces = raw.split(" ") if len(datePieces) == 2: return da...
def create_envs(service_component_name, *envs): """Merge all environment variables maps Creates a complete environment variables map that is to be used for creating the container. Args: ----- envs: Arbitrary list of dicts where each dict is of the structure: { <environment...
def clean_javascript(js): """ Remove comments and all blank lines. """ return "\n".join( line for line in js.split("\n") if line.strip() and not line.startswith("//") )
def sort_datasets_by_state_priority(datasets): """ Sorts the given list of datasets so that drafts appear first and deleted ones last. Also secondary sorts by modification date, latest first. """ sorted_datasets = [] sorted_datasets.extend(sorted([dataset for dataset in datasets if dataset['state'] == ...
def row_includes_spans(table, row, spans): """ Determine if there are spans within a row Parameters ---------- table : list of lists of str row : int spans : list of lists of lists of int Returns ------- bool Whether or not a table's row includes spans """ for c...
def num_hex(input1): """ convert 2 digit number to hex """ return bytearray.fromhex(str(input1).zfill(2))
def contains_uppercase(pw): """ Takes in the password and returns a boolean value whether or not the password contains an uppercase. Parameters: pw (str): the password string Returns: (boolean): True if an uppercase letter is contained in the Password, False otherwise. """ chara...
def pddx(pdd=66.4, energy=6, lead_foil=None): """Calculate PDDx based on the PDD. Parameters ---------- pdd : {>0.627, <0.890} The measured PDD. If lead foil was used, this assumes the pdd as measured with the lead in place. energy : int The nominal energy in MV. lead_foil : {No...
def string_to_list(word): """ Take each character of the 'word' parameter and return a list populated with all the characters :param word: string :return: list of string's characters """ return [c for c in word]
def bounding_box(p1,p2,buffer=0): """Returns left, bottom, right and top coordinate values""" if p1[0] < p2[0]: left=p1[0] right=p2[0] else: left=p2[0] right=p1[0] if p1[1] < p2[1]: bottom=p1[1] top=p2[1] else: bottom=p2[1] top=p1[1] ...
def isBinaryPalindrome(num): """assumes num is an integer returns True if num in binary form is a palindrome, else False""" return str(bin(num))[2::] == str(bin(num))[:1:-1]
def max_or_min_recursion(tup, find_max = True): """ Returns the largest or smallest element in the tuple, depending on the optinal parameter. >>> max_or_min_recursion((1,2,3,4)) 4 >>> max_or_min_recursion((13,2,3,4), False) 2 >>> max_or_min_recursion((13,2,33,-4), True) 33 """ ...
def construct_manta(source, value, network_id): """ Constructs a dictionary from manta outputs that can be imported into the Neo4j database. :param source: :param value: :param network_id: :return: """ node_dict = {} node_dict[source] = {} node_dict[source]['target'] = networ...
def get_type(mal, kitsu_attr): """ Get the type of the weeb media. :param mal: The MAL search result. :param kitsu_attr: The attributes of kitsu search result. :return: the type of the weeb media """ mal_type = mal.get('type') if mal_type: return mal_type show_type = kitsu_a...
def calculate_slot(ts, step): """Calculate which `slot` a given timestamp falls in.""" return int(ts/step) * step
def is_permutation_sort(s1, s2): """Uses sorting.""" s1_list = list(s1) s2_list = list(s2) s1_list.sort() s2_list.sort() return s1_list == s2_list
def hex_distance(h1, h2): """Get hexagonal distance (manhattan distance) of two hexagon points given by the hexagonal coordinates h1 and h2 Parameters ---------- h1 : int, int Hexagonal coordinates of point 1. h2 : int, int Hexagonal coordinates of point 2. Returns ----...
def get_grid(args): """ Make a dict that contains every combination of hyperparameters to explore""" import itertools # Make a list of every value in the dict if its not for k, v in args.items(): if type(v) is not list: args[k] = [v] # Get every pairwise combination hyperpar...
def coast(state): """ Ignore the state, go straight. """ action = { 'command': 1 } return action
def _run_lambda_function(event, context, app, config): # pragma: no cover """Run the function. This is the default when no plugins (such as wsgi) define an alternative run function.""" args = event.get('args', []) kwargs = event.get('kwargs', {}) # first attempt to invoke the function passing the ...
def sensibleBulk(Tw,Ta,S,rhoa=1.2,Ch=1.5e-3,cpa=1004.67): """ Sensible heat flux from water using the bulk exchange formulation Inputs: Tw - Water temp [C] Ta - Air temp [C] S - Wind speed magnitude [m s^-1] rhoa - air density [kg m^-3] Ch - Stanton numb...
def sort_dict_of_lists(the_dict): """Make dict of unordered lists compareable.""" return {key: sorted(value) for key, value in the_dict.items()}
def example1(S): """Return the sum of the elements with even index in sequence S.""" n = len(S) total = 0 for j in range(n): # loop from 0 to n-1 # note the increment of 2 total += int(S[j]) return total
def serialize_soil_carbon(analysis, type): """Return serialised soil carbon data""" return { 'id': None, 'type': type, 'attributes': { 'total_soil_carbon': analysis.get('total_soil_carbon', None).get('b1_first', None), 'soil_carbon_density': int(analysis.get('soil...
def list_all_equal(lst): """Return true if all elements in the list are equal.""" return len(set(lst)) == 1
def function(name="Gauss"): """ Example function that prints a welcome message. Second paragraph should explain the function in more detail. Include citations to relevant literature and equations whenever possible. WRITE THE DOCSTRING FIRST since it helps reason about the design of your function an...
def getkeyval(key,commentdct): """ returns the value of the key commentdct can be {'default': ['4'], 'maximum': ['6'], 'required-field': [''], 'note':['this is', ' a note']} now key='default' will return the number 4 key='note' will return 'this is\\n a note' """ #--------minimum, minimum>, maximum, maximum<...
def repository(repo, ssh): """Return the url associated with the repo.""" if repo.startswith('k8s.io/'): repo = 'github.com/kubernetes/%s' % (repo[len('k8s.io/'):]) elif repo.startswith('sigs.k8s.io/'): repo = 'github.com/kubernetes-sigs/%s' % (repo[len('sigs.k8s.io/'):]) elif repo.start...
def float_trail_free(x): """Return a formatted float without trailing zeroes. This is an awful hack.""" # https://stackoverflow.com/a/2440786/313032, Alex Martelli return ('%.15f' % x).rstrip('0').rstrip('.')
def get_display_title(meta_data): """ get display org for cards on web app :return: string """ doc_type = meta_data["doc_type"].strip() doc_num = meta_data["doc_num"].strip() doc_title = meta_data["doc_title"].strip() return doc_type + " " + doc_num + " " + doc_title
def get_mod_func(callback): """Convert a fully-qualified module.function name to (module, function).""" try: dot = callback.rindex(".") except ValueError: return (callback, "") return (callback[:dot], callback[dot + 1:])
def rb_fit_fun(x, a, alpha, b): """Function used to fit rb.""" # pylint: disable=invalid-name return a * alpha ** x + b
def bool_to_string(b): """Convert a boolean type to string. Args: b (bool): A Boolean. Raises: TypeError Returns: str: String representation of a bool type. """ s = str(b).lower() if s in ["true", "false"]: return s raise TypeError("Value must be True o...
def remove_implications(ast): """ @brief Removes implications in an AST. @param ast The ast @return another AST """ if len(ast) == 3: op, oper1, oper2 = ast oper1 = remove_implications(oper1) oper2 = remove_implications(oper2) if op == '-...
def re_tab(s): """Return a tabbed string from an expanded one.""" l = [] p = 0 for i in range(8, len(s), 8): if s[i - 2:i] == " ": # collapse two or more spaces into a tab l.append(s[p:i].rstrip() + "\t") p = i if p == 0: return s else: ...
def _format_help_dicts(help_dicts, display_defaults=False): """ Format the output of _generate_help_dicts into a str """ help_strs = [] for help_dict in help_dicts: help_str = "{} ({}".format( help_dict["var_name"], "Required" if help_dict["required"] else "Optional",...
def days_from_common_era(year): """ Returns the number of days from from 0001-01-01 to the provided year. For a common era year the days are counted until the last day of December, for a BCE year the days are counted down from the end to the 1st of January. """ if year > 0: return year *...
def get_max_value1(matrix: list) -> int: """ Parameters ----------- Returns --------- Notes ------ """ if not matrix or not matrix[0]: return 0 rows, cols = len(matrix), len(matrix[0]) res = [] for i in range(rows): tmp = [] for j in rang...
def monthNameToNumber(month_name): """ Takes the name of a month and returns its corresponding number. """ # A dictionary that converts a month name to its # corresponding number. month_name_to_number = \ {"January" : 1, "February" : 2, "March" : 3, "April" : 4, "Ma...
def capitalize_string_words(src_string): """ Capitalize all the words in the given string :param src_string: source string :return: """ return ' '.join([s.capitalize() for s in src_string.split(' ')])
def square_area(side): """ 2. Function with one input and one output This function demonstrates how a function returns a processed output based on the received input This function calculates the area of a square side: the side of the square, must be a positive number area: the area of the s...
def realLines(lines): """Parses out any commented lines and removes any initial blanks of specified list of strings""" rl = [] for r in lines: r = r.strip() if r and r[0] != '#': rl.append(r) return rl
def illegal(x): """Save the passengers if the pedestrians are crossing illegally.""" # if passenger vs passenger (shouldn't be possible) if x["Passenger_int"] == 1 and x["Passenger_noint"] == 1: return -1 # if ped v ped elif x["Passenger_int"] == 0 and x["Passenger_noint"] == 0: # ab...
def embedding_acc(true_label, pred_label): """ :param true_label: list :param pred_label: list :return: """ true_dict = {i:true_label.count(i) for i in range(10)} pred_dict = {i:pred_label.count(i) for i in range(10)} true_count = list(true_dict.values()) true_count.sort(rev...
def get_metric(line, name, split): """ Get metric value from output line :param line: console output line :param name: name of metric :param split: split character :return: metric value """ start = line.find(name) + len(name) + 1 end = line.find(split, start) return line[start:en...
def getNormalized( counts ): """Rescale a list of counts, so they represent a proper probability distribution.""" tally = sum( counts ) if tally == 0: probs = [ d for d in counts ] else: probs = [ d / tally for d in counts ] return probs
def _if_none_match_passes(target_etag, etags): """ Test the If-None-Match comparison as defined in section 3.2 of RFC 7232. """ if not target_etag: # If there isn't an ETag, then there isn't a match. return True elif etags == ['*']: # The existence of an ETag means th...
def isiterable(something): """ check if something is a list, tuple or set :param something: any object :return: bool. true if something is a list, tuple or set """ return isinstance(something, (list, tuple, set))
def find_min_rotate_recur(array, low, high): """ Finds the minimum element in a sorted array that has been rotated. """ mid = (low + high) // 2 if mid == low: return array[low] if array[mid] > array[high]: return find_min_rotate_recur(array, mid + 1, high) return find_min_rot...
def euclidean_distance(histo1, histo2): """ Euclidean distance between two histograms :param histo1: :param histo2: :return: """ val = 0 lnot = [] for w in histo1: if w in histo2: val += (histo1[w] - histo2[w]) ** 2 lnot.append(w) else: ...
def Linkable(filename): """Return true if the file is linkable (should be on the link line).""" return filename.endswith('.o')
def add(lst, arg): """Add an item to a list. Equivalent to Djangos' add. Args: lst (list): A list. arg (mixed): Any value to append to the list. Returns: list: The updated list. """ lst.append(arg) return lst
def _calc_diff(c, x, y, i, j): """Print the diff using LCS length matrix by _backtracking it""" added = [] removed = [] if i < 0 and j < 0: return added, removed elif i < 0: sub_added, sub_removed = _calc_diff(c, x, y, i, j - 1) added += sub_added removed += sub_remo...
def _create_documents_per_words(freq_matrix: dict) -> dict: """ Returns a dictionary of words and the number of documents in which they appear. :param freq_matrix: The frequency matrix to be summarized. :return: A dictionary of words and the number of documents in which they appear. """ doc_...
def binary_search(numbers, number): """Binary search Locates the number in the list of sorted numbers. Looks at the middle element, and proceeds recursively to the left or to the right, depending on whether the number was smaller or bigger, respectively Returns the position of the found number, or the...