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 do here is a type check that the # input is a positive integer. Something like: # if not (isinstance(number, int) and number > 0): # raise TypeError("Not a positive integer") # try: number = int(number) except IndexError: return 'Argument must be supplied on the command line.' except TypeError: return 'Argument must not be a list' except ValueError: return 'Argument must be a integer, not "%s"' % number if number < 1: return 'Argument must be a positive integer, not %d' % number else: # ### INSTRUCTOR COMMENT: # It is suboptimal to put the main block of code in a function # so indented. That is usually a sign that you should simplify your # logic. Using the assert check above, all of below can become # the entire function block. # fibList = [1] fibNum = 1 for index in range(1,number): fibList.append(fibNum) fibNum += fibList[index-1] return fibList
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: return None if v2: return 1.0 * v1 / v2 else: return None
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 """ return { 'data': { 'id': f"{_source}__{_target}", '_label': f"\n\u2060{_label}\n\u2060", 'name': _label, 'source': _source, 'target': _target, '_edge_type': _edge_type }, 'classes': '' }
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_val([3,0,1,2], 5) 3.056 >>> from fractions import Fraction >>> mantPN_val([3,0,1], Fraction(1,3)) Fraction(12, 1) """ ### >>> p(PolyNum([5.])) # 3. * 5.**0 + 0 * 5.**(-1)1 + 1 * 5.**(-2) + 2 * 5.**(-3) ### PolyNum('(~3.056~)') # # not important case, consuming long time x_1 = 1/x y = mant[-1] # mantR = mant[::-1] #transcrypt doesn`t like `[::-1]` mantR = list(reversed(mant)) for p1 in mantR[1:]: y = y * x_1 + p1 return y
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_length): return str(a_string[0:int(max_length-5)]+'...') return a_string
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: if part: camel_case_name += part.capitalize() return camel_case_name
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. """ return isinstance(obj, str) and obj.lower() == s
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 freq<375.0e9: return "A7" elif freq<510.0e9: return "A8" elif freq<730.0e9: return "A9" elif freq<960.0e9: return "A10" if freq<2000.0e9: return "A11" else: return "UK"
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) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
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 dict: emptyNone(val[k]) else: if val[k] is None: val[k] = '' return val
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: return steps + 1 steps += 1 i = next_step
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.join(map(str, value)) elif isinstance(value, dict): for subkey, subvalue in value.items(): if isinstance(subvalue, list): params[glue.join((key, subkey))] = separator.join(map(str, subvalue)) else: params[glue.join((key, subkey))] = subvalue else: params[key] = value return params
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 search from 'current' if current < 0: raise Exception(f"Token '{token}' cannot be found") spans.append((current, current + len(token))) current += len(token) # next search start from the token afterwards return spans
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, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() # msg = subprocess.call(args) - recommended version; we don't use it, since we want to get back the system message return msg
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) '500.0us' >>> seconds_to_timestring(20000.0) '20000.0s' >>> seconds_to_timestring(453e-9) '453.0ns' >>> seconds_to_timestring(3000e-9) '3.0us' >>> seconds_to_timestring(100e-12) '0.1ns' """ if duration >= 1000e-3: return str(duration) + "s" if duration >= 1000e-6: return str(duration * 1e3) + "ms" if duration >= 1000e-9: return str(duration * 1e6) + "us" return str(duration * 1e9) + "ns"
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, str): raise TypeError("value is required to be a string instance.") s = value.strip() if len(s) > 0: return value raise ValueError("must not be null or empty string")
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.aperture_photometry` and `~photutils.aperture.PixelAperture.do_photometry`. """ # check Quantity inputs unit = set(getattr(arr, 'unit', None) for arr in (data, error) if arr is not None) if len(unit) > 1: raise ValueError('If data or error has units, then they both must ' 'have the same units.') # strip data and error units for performance unit = unit.pop() if unit is not None: unit = data.unit data = data.value if error is not None: error = error.value return data, error, unit
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 indexes: if i[0] + i[1] - delOffset >= 0 and i[0] + i[1] - delOffset <= len(alist): del alist[i[0] + i[1] - delOffset] delOffset = delOffset + 1 return delOffset
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 return merged_dict
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. The summary line may be used by automatic indexing tools; it is important that it fits on one line and is separated from the rest of the docstring by a blank line. The summary line may be on the same line as the opening quotes or on the next line. The entire docstring is indented the same as the quotes at its first line (see example below)." The only difference is that the blank line is not needed, but can be there. """ title_split = title.strip().split("\n") page_title_first = title_split[0].strip() page_title_rest = " ".join( title_split[1:] ).strip() return (page_title_first,page_title_rest)
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] == 'gz': path_parts.pop() if path_parts[-1] in ['txt', 'seq', 'fastq', 'fq']: path_parts.pop() path_parts[-1] += '_screen' path_parts.append('txt') return '.'.join(path_parts)
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 return string
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 None
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. """ term = record["termDesc"] return " ".join(term.split(" ")[0:2])
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 val in reversed(vals): if (val == expected) or (expected is None): group.append(val) else: break expected = val - step return group
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 conversion:%s".format(my_str))
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(): if c.isupper(): cur_tag = "U" else: cur_tag = "L" elif c.isdigit(): cur_tag = "D" else: cur_tag = "S" if cur_tag == prev_tag: t_len += 1 else: if len(prev_tag) > 0: struct.append((prev_tag, t_len)) prev_tag = cur_tag t_len = 1 struct.append((cur_tag, t_len)) return tuple(struct)
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 datePieces[0].replace(":","-") + " " + datePieces[1].replace("-",":") else: return ""
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 variable name>: <environment variable value>, <environment variable name>: <environment variable value>, ... } Returns: -------- Dict of all environment variable name to environment variable value """ master_envs = { "HOSTNAME": service_component_name, # For Registrator to register with generated name and not the # image name "SERVICE_NAME": service_component_name } for envs_map in envs: master_envs.update(envs_map) return master_envs
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'] == 'draft'], key=lambda sorting_key: sorting_key['metadata_modified'], reverse=True)) sorted_datasets.extend(sorted([dataset for dataset in datasets if dataset['state'] not in ['draft', 'deleted']], key=lambda sorting_key: sorting_key['metadata_modified'], reverse=True)) sorted_datasets.extend(sorted([dataset for dataset in datasets if dataset['state'] == 'deleted'], key=lambda sorting_key: sorting_key['metadata_modified'], reverse=True)) return sorted_datasets
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 column in range(len(table[row])): for span in spans: if [row, column] in span: return True return False
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. """ characters = list(pw) for i in characters: if i.isupper(): return True return False
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 : {None, '30cm', '50cm'} Applicable only for energies >10MV. Whether a lead foil was used to acquire the pdd. Use ``None`` if no lead foil was used and the interim equation should be used. Use ``50cm`` if the lead foil was set to 50cm from the phantom surface. Use ``30cm`` if the lead foil was set to 30cm from the phantom surface. """ if energy < 10: return pdd elif energy >= 10: if lead_foil is None: return 1.267*pdd-20 elif lead_foil == '50cm': if pdd < 73: return pdd else: return (0.8905+0.0015*pdd)*pdd elif lead_foil == '30cm': if pdd < 71: return pdd else: return (0.8116+0.00264*pdd)*pdd
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] return (left-buffer, bottom-buffer, right+buffer, top+buffer)
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 """ if len(tup) == 1: return tup[0] return tup[0] if tup[0] < max_or_min_recursion(tup[1:], find_max) and not find_max else tup[0] if tup[0] > max_or_min_recursion(tup[1:], find_max) and find_max else max_or_min_recursion(tup[1:], find_max)
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'] = network_id + ', cluster ' + str(value) return node_dict
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_attr.get('showType') subtype = kitsu_attr.get('subtype') if show_type or subtype: return show_type or subtype
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 ------- float distance """ a1, b1 = h1 a2, b2 = h2 c1 = -a1-b1 c2 = -a2-b2 return (abs(a1 - a2) + abs(b1 - b2) + abs(c1 - c2)) / 2
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 hyperparam, values = zip(*args.items()) grid = [dict(zip(hyperparam, v)) for v in itertools.product(*values)] return grid
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 lambda event and context try: ret = app(*args, event=event, context=context, **kwargs) except TypeError: # try again without passing the event and context ret = app(*args, **kwargs) return ret
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 number cpa - Specific heat of air [J kg-1 K-1] """ return -rhoa*cpa*Ch*S*(Tw-Ta)
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_carbon_density', None)), 'areaHa': analysis.get('area_ha', None) } }
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 and how you'll explain it. Parameters ---------- name : str Name of the person to be greeted. Describe all parameters this way. Returns ------- message : str The welcome message. Describe all return values this way. Examples -------- >>> print(function()) Welcome to the project, Gauss! """ return f"Welcome to the project, {name}!"
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<, min-fields---------- #returns the number or None if key.upper() in [ 'minimum'.upper(), 'minimum>'.upper(), 'maximum'.upper(), 'maximum<'.upper(), 'min-fields'.upper()]: try: val=commentdct[key][0] return float(val) except KeyError: return None #--------field, note, units, ip-units, # default, type, object-list, memo---------- #returns the value or None if key.upper() in [ 'field'.upper(), 'note'.upper(), 'units'.upper(), 'ip-units'.upper(), 'default'.upper(), 'type'.upper(), 'object-list'.upper(), 'memo'.upper()]: try: val=commentdct[key] st='' for el in val: st=st+el+'\n' st=st[:-1] except KeyError: return None return st #--------required-field, autosizable, unique-object, required-object---------- #returns True or False if key.upper()in [ 'required-field'.upper(), 'autosizable'.upper(), 'unique-object'.upper(), 'required-object'.upper()]: return commentdct.has_key(key) #--------key, reference---------- #returns a list if key.upper()in [ 'key'.upper(), 'reference'.upper()]: try: return commentdct[key] except KeyError: return None
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.startswith('istio.io/'): repo = 'github.com/istio/%s' % (repo[len('istio.io/'):]) if ssh: if ":" not in repo: parts = repo.split('/', 1) repo = '%s:%s' % (parts[0], parts[1]) return 'git@%s' % repo return 'https://%s' % repo
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 or False.")
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 == '->': return ('ou', ('non', oper1), oper2) else: return ast return ast
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: l.append(s[p:]) return "".join(l)
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", ) if help_dict.get("default") and display_defaults: help_str += ", Default=%s)" % help_dict["default"] else: help_str += ")" if help_dict.get("help_str"): help_str += ": %s" % help_dict["help_str"] help_strs.append(help_str) return "\n".join(help_strs)
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 * 365 + year // 4 - year // 100 + year // 400 elif year >= -1: return year * 366 else: year = -year - 1 return -(366 + year * 365 + year // 4 - year // 100 + year // 400)
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 range(cols): tmp.append(0) res.append(tmp) for i in range(rows): for j in range(cols): up, left = 0, 0 if i > 0: up = res[i-1][j] if j > 0: left = res[i][j-1] res[i][j] = max(up, left) + matrix[i][j] return res[-1][-1]
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, "May" : 5, "June" : 6, "July" : 7, "August" : 8, "September" : 9, "October" : 10, "November" : 11, "December" : 12, } return month_name_to_number[month_name]
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 square, must be a positive number """ area = side * side return area
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: # abstain if both are law violating if x["Law Violating_noint"] == 1 and x["Law Violating_int"] == 1: return -1 # return 1 if noint is law violating, 0 if not elif x["Law Violating_noint"] == 1: return 1 if x["Law Violating_int"] == 1: return 0 # if the choice is between an AV and pedestrians else: # if the pedestrian group is crossing illegally if x["Law Violating_int"] == 1: return 0 if x["Law Violating_noint"] == 1: return 1 return -1
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(reverse=True) pred_count = list(pred_dict.values()) pred_count.sort(reverse=True) acc = sum(min(true_count,pred_count)) return acc*100/sum(pred_count)
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:end]
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 that there is "a current # representation for the target resource", so there is a match to '*'. return False else: # The comparison should be weak, so look for a match after stripping # off any weak indicators. target_etag = target_etag.strip('W/') etags = (etag.strip('W/') for etag in etags) return target_etag not in etags
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_rotate_recur(array, low, mid)
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: val += histo1[w] * histo1[w] for w in histo2: if w not in lnot: val += histo2[w] * histo2[w] return val
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_removed added.append((j, y[j])) elif j < 0: sub_added, sub_removed = _calc_diff(c, x, y, i - 1, j) added += sub_added removed += sub_removed removed.append((i, x[i])) elif x[i] == y[j]: sub_added, sub_removed = _calc_diff(c, x, y, i - 1, j - 1) added += sub_added removed += sub_removed return added, removed elif c[i][j - 1] >= c[i - 1][j]: sub_added, sub_removed = _calc_diff(c, x, y, i, j - 1) added += sub_added removed += sub_removed added.append((j, y[j])) elif c[i][j - 1] < c[i - 1][j]: sub_added, sub_removed = _calc_diff(c, x, y, i - 1, j) added += sub_added removed += sub_removed removed.append((i, x[i])) return added, removed
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_per_words = dict() for sentence, freq_table in freq_matrix.items(): for word, frequency in freq_table.items(): if word in doc_per_words: doc_per_words[word] += 1 else: doc_per_words[word] = 1 return doc_per_words
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 position at which the number should be inserted to preserve order Time complexity T(n) = O(log n) Space complexity S(n) = O(log n) """ def bin_search(a, b): """a and b are inclusive indices""" if a == b: return a if number <= numbers[a] else a + 1 middle = (a + b) // 2 if number <= numbers[middle]: return bin_search(a, middle) else: return bin_search(middle + 1, b) return bin_search(0, len(numbers) - 1)