content
stringlengths
42
6.51k
def ascii_line(chunk): """Create ASCII string from bytes in chunk""" return ''.join([ chr(d) if 32 <= d < 127 else '.' for d in chunk])
def missing_query(*args, **kwags): """ A query returning something not in the local DB """ response = { 'responseHeader': {'params': {'rows': 1}}, 'response': { 'numFound': 1, 'docs': [{ 'id': 'abcde', 'checksum': ['1234'], 'title': 'foo', 'version': '1', 'score': 1.0, 'dataset_id': 'dataset_bar|example.com', }], } } return response
def get_geonames_uri(geonames_id): """ Returns tuple of 0. GeoNames place URI 1. GeoNames place description URL """ geonames_uri = "http://sws.geonames.org/%s/"%(geonames_id,) geonames_url = "http://sws.geonames.org/%s/about.rdf"%(geonames_id,) return (geonames_uri, geonames_url)
def topic_with_device_name(device_name, topic): """Creates fully-formed topic name from device_name (string) and topic (string)""" if device_name: topic = device_name + "/" + topic return topic
def getParentProxyId(proxy): """ Return '0' if the given proxy has no Input otherwise will return the parent proxy id as a String. """ if proxy and proxy.GetProperty("Input"): parentProxy = proxy.GetProperty("Input").GetProxy(0) if parentProxy: return parentProxy.GetGlobalIDAsString() return '0'
def classToDict(obj=None): """ Transform an object into a dict so it can be JSONified. Useful for turning custom classes into JSON-compatible dictionaries. """ if obj == None: return {} _obj = {} _obj.update(obj.__dict__) return _obj
def avg(l): """Helper function to return the average of a list of numbers""" return sum(l)/len(l)
def hms(seconds): """ Return time as hours, minutes seconds :param seconds: input seconds :return: hours, minuted, seconds """ mins, sec = divmod(seconds, 60) hours, mins = divmod(mins, 60) return hours, mins, sec
def extract_coordinates(url): """Given Google maps url with coordinates in a query string extract latitude and longitude""" try: coordinates = url.split('q=')[-1] lat, lon = [coor.strip() for coor in coordinates.split(',')] except AttributeError: return None, None return lat, lon
def print_list_body(list_in, tabs, output="", indent=4): """Enumerate through each file key's parameter list items""" tabs += 1 for item in list_in: output += (" " * indent) * tabs + str(item) + "\n" return output
def sphinx_role(record, lang): """ Return the Sphinx role used for a record. This is used for the description directive like ".. c:function::", and links like ":c:func:`foo`. """ kind = record["kind"] if kind in ["class", "function", "namespace", "struct", "union"]: return lang + ":" + kind if kind == "define": return "c:macro" if kind == "enum": return lang + (":enum-class" if record["strong"] else ":enum") if kind == "typedef": return lang + ":type" if kind == "enumvalue": return lang + ":enumerator" if kind == "variable": return lang + (":member" if "parent" in record else ":var") raise RuntimeError("No known role for kind '%s'" % kind)
def calculate_scan_time(metadata): """Parse scan time from metadata. Returns: timestamp string """ scan_time = None if 'terraref_cleaned_metadata' in metadata and metadata['terraref_cleaned_metadata']: scan_time = metadata['gantry_variable_metadata']['datetime'] else: for sub_metadata in metadata: if 'content' in sub_metadata: sub_metadata = sub_metadata['content'] if 'terraref_cleaned_metadata' in sub_metadata and sub_metadata['terraref_cleaned_metadata']: scan_time = sub_metadata['gantry_variable_metadata']['datetime'] return scan_time
def averages(arr): """ Computes the average of two integers and returns an array of them. :param arr: array of integers. :return: an array of the averages of each integer-number and his follower. """ if arr is None: return [] return [(arr[x] + arr[x+1]) / 2 for x in range(len(arr)-1)]
def numTrees(n): """ O(n^2) / O(n). :type n: int :rtype: int """ N = {} N[0] = 1 N[1] = 1 for i in range(2, n + 1): N[i] = 0 for j in range(0, i): N[i] += N[j] * N[i - j - 1] return N[n]
def str_to_bool_safe(s, truelist=("True", "true", "T"), falselist=("False", "false", "F")): """ Converts a boolean codified as a string. Instead of using 'eval', compares with lists of accepted strings for both true and false bools, and raises an error if the string does not match any case. Parameters ---------- s : str The string to be read from truelist : tuple or list Tuple or list of strings interpreted as True. falselist : tuple or list Tuple or list of strings interpreted as False. Returns ------- res : bool """ if s in truelist: return True elif s in falselist: return False elif isinstance(s, bool): # In case the input is already a boolean. return s else: raise ValueError("Hey, the string '{}' could not be understood as a boolean.".format(s))
def getattr_by_path(obj, attr, *default): """Like getattr(), but can go down a hierarchy like 'attr.subattr'""" value = obj for part in attr.split('.'): if not hasattr(value, part) and len(default): return default[0] value = getattr(value, part) if callable(value): value = value() return value
def reverse_rows_ud(matrix): """ Flip order of the rows in the matrix[row][col] Using numpy only fits matrix lists with numbers: np_matrix = np.array(matrix) return np_matrix.flipud().tolist() To suit any list element type use general flipud. This reverse_rows_ud() is equivalent to reverse_list(), because it affects the row index, that is the first index. """ return list(reversed(matrix))
def value_or_none(elem): """Gets element value or returns None, if element is None :param elem: dataset element or None :return: element value or None """ return elem.value if elem else None
def createCGImageWithQuickTimeFromURL(url): """ Note: this function doesn't actually worked because the APIs used in here aren't properly wrapped (yet). """ return None imageRef = None err = noErr result, dataRef, dataRefType = QTNewDataReferenceFromCFURL(url, 0, None, None) if dataRef is not None: err, gi = GetGraphicsImporterForDataRefWithFlags(dataRef, dataRefType, None, 0) if not err and gi: # Tell the graphics importer that it shouldn't perform # gamma correction and it should create an image in # the original source color space rather than matching it to # a generic calibrated color space. result = GraphicsImportSetFlags(gi, (kGraphicsImporterDontDoGammaCorrection + kGraphicsImporterDontUseColorMatching) ) if result == 0: result, imageRef = GraphicsImportCreateCGImage(gi,None,0) if result != 0: print >>sys.stderr, "got a bad result = %d!"%(result,) DisposeHandle(dataRef) CloseComponent(gi) return imageRef
def quadratic_interp(a,f,x): """Compute at quadratic interpolant Args: a: array of the 3 points f: array of the value of f(a) at the 3 points Returns: The value of the linear interpolant at x """ answer = (x-a[1])*(x-a[2])/(a[0]-a[1])/(a[0]-a[2])*f[0] answer += (x-a[0])*(x-a[2])/(a[1]-a[0])/(a[1]-a[2])*f[1] answer += (x-a[0])*(x-a[1])/(a[2]-a[0])/(a[2]-a[1])*f[2] return answer
def strip_keys(data, keys): """return a copy of dict `data` with certain keys missing""" return dict([(key, val) for key, val in data.items() if key not in keys])
def title_case(sentence): """ :param sentence: sentence tp be converted :return: ret: string :example: >>> titlecase("This iS tHe") This Is The """ return ' '.join([i.capitalize() for i in sentence.split()])
def get_flow_output_value(flow, configuration): """ Extracts outputs from the flow record based on the configuration. :param flow: flow record in JSON format :param configuration: loaded application configuration :return: dictionary of outputs defined by name as a key and element as a value """ output = {'simple': {}, 'request': {}, 'response': {}} for configuration_output in configuration['output']: output[configuration_output['type']][configuration_output['name']] = flow[configuration_output['element']] return output
def ordinal_number(num): """create string with ordinal representation of number given """ # 10 through 20 all get 'th' suffix if num >=10 and num <=20: suffix = 'th' # suffix for all other numbers depends on the last digit in the number else: last_digit = num % 10 if last_digit == 1: suffix = 'st' elif last_digit == 2: suffix = 'nd' elif last_digit == 3: suffix = 'rd' else: suffix = 'th' return(str(num) + suffix)
def qinv(x, y, z, w): """ compute quaternion inverse """ inv_squared_magnitude = 1. / ( x*x + y*y + z*z + w*w ) invx = -x * inv_squared_magnitude invy = -y * inv_squared_magnitude invz = -z * inv_squared_magnitude invw = w * inv_squared_magnitude return invx,invy,invz,invw
def pad(octet_string, block_size=16): """ Pad a string to a multiple of block_size octets""" pad_length = block_size - len(octet_string) return octet_string + b'\x80' + (pad_length-1)*b'\x00'
def flatten_object(obj): """flatten an object into paths for easier enumeration. Args: an object Returns: a flat object with a list of pairs [(p_1, v_1), ..., (p_k, v_k)], (paths and values) Example: {x: 1, y : {z: [a, b], w: c}} will be flatten into [("/x", 1), ("/y/z/0", a), ("/y/z/1", b), ("/y/w", c)] """ paths = [] if isinstance(obj, (dict,)): for f in obj: sub_paths = flatten_object(obj[f]) for p in sub_paths: paths.append(("/{}{}".format(f, p[0]), p[1])) elif isinstance(obj, (list,)): for i, x in enumerate(obj): sub_paths = flatten_object(x) for p in sub_paths: paths.append(("/{}{}".format(i, p[0]), p[1])) else: paths = [("", obj)] return paths
def sort_by(array, key, descending=False): """ Sort an "array" by "key". >>> sort_by([{'a': 10, 'b': 0}, {'a': 5, 'b': -1}, {'a': 15, 'b': 1}], 'a') [{'a': 5, 'b': -1}, {'a': 10, 'b': 0}, {'a': 15, 'b': 1}] :param tp.List[tp.Mapping] array: list of dicts. :param str key: key name to use when sorting. :param bool descending: if True sort will be descending. :return tp.List[tp.Mapping]: a by "key" sorted list. """ return list(sorted(array, key=lambda k: k[key] if k[key] is not None else "", reverse=descending))
def app_model_or_none(raw_model): """ Transforms `raw_model` to its application model. Function can handle `None` value. """ return raw_model.get_app_model() if raw_model is not None else None
def binary_search(input_array, value): """Your code goes here.""" array_length = len(input_array) #("array length:", array_length) left = 0 right = array_length-1 while left <= right: mid = ( left + right ) // 2 #print("mid, mid value: ", mid, input_array[mid]) if input_array[ mid ] == value: return mid elif input_array[ mid ] < value: # midpoint value is smaller than target, then search right half left = mid + 1 else: # midpoint value is larger than target, then search left half right = mid - 1 return -1
def clean_config_for_pickle(full_conf): """Clean out any callable method instances, such as the gene_test_callback parameter passed to geneticalgorithm, as these are not pickleable. Acts in-place on full_conf parameter. Inputs: full_conf: The full_config dict structure, containing a 2-level configuration dict. Outputs: none - acts in-place on full_conf """ to_del = [] for section_key in full_conf: for param_key in full_conf[section_key]: if callable(full_conf[section_key][param_key]): to_del.append((section_key, param_key)) for item in to_del: del full_conf[item[0]][item[1]] return None
def get_index_table_name_for_release(data_release): """ Some datareleases are defined purely as ints which make invalid MySQL table names Fix that here by always prefixing release_ to the data_release name to make the MySQL table_name """ table_name = 'release_{}'.format(data_release) return table_name
def encode(s: str, encoding="utf8") -> bytes: """Shortcut to use the correct error handler""" return s.encode(encoding, errors="dxfreplace")
def _text_indent(text, indent): # type: (str, str) -> str """ indent a block of text :param str text: text to indent :param str indent: string to indent with :return: the rendered result (with no trailing indent) """ lines = [line.strip() for line in text.strip().split('\n')] return indent + indent.join(lines)
def __get_average_kor__(qars): """ Get the average of kor in the benin republic area """ total = 0 count = len(qars) if count == 0: count = 1 for i, x in enumerate(qars): total += x.kor result = total / count return "{:.2f}".format(result) if result != 0 else "NA"
def _wrap_string(some_string,soft_wrap_length=4): """ Do a soft wrap of strings at space breaks. """ fields = some_string.split() lengths = [len(f) for f in fields] wrapped = [[fields[0]]] current_total = lengths[0] + 1 for i in range(1,len(lengths)): if current_total >= soft_wrap_length: wrapped.append([]) current_total = 0 wrapped[-1].append(fields[i]) current_total += lengths[i] + 1 out = [] for w in wrapped: out.append(" ".join(w)) out = "\n".join(out) return out
def find_empty(brd): """ Uses the Sudoku problem as a Matrix input and returns the row/column location of the next empty field. :param brd: Matrix input of the board needed to solve for the Sudoku problem. :return: The row/column of the next empty field as a tuple. """ for i in range(len(brd)): for j in range(len(brd[0])): if brd[i][j] == 0: return i, j # i: row, j: column return None
def cmp_subst(subst_1, subst_2): """Compare two substitution sets. :arg dict subst_1: Substitution set. :arg dict subst_2: Substitution set. :returns bool: True if `subst_1` equals `subst2`, False otherwise. """ if len(subst_1) != len(subst_2): return False for item in subst_1: if subst_1[item] != subst_2[item]: return False return True
def sla_colour(value, arg): """ Template tag to calculate the colour of caseworker/templates/includes/sla_display.html """ since_raised = int(value) if arg == "hours": if since_raised >= 48: return "red" else: return "orange" elif arg == "days": if since_raised >= 5: return "green" elif since_raised < 5 and since_raised > 0: return "orange" elif since_raised <= 0: return "red" else: raise ValueError("Please specify whether the time remaining is hours or days eg \"value|sla_colour:'hours'\"")
def matriz_identidade(ordem: int = 1) -> list: """Cria uma matriz identidade.""" matriz = [] for linha in range(ordem): nova_coluna = [] for coluna in range(ordem): nova_coluna.append(0) if linha != coluna else nova_coluna.append(1) matriz.append(nova_coluna) return matriz
def is_num(var): """Check if var string is num. Should use it only with strings.""" try: int(var) return True except ValueError: return False
def _styleof(expr, styles): """Merge style dictionaries in order""" style = dict() for expr_filter, sty in styles: if expr_filter(expr): style.update(sty) return style
def _feet_to_alt_units(alt_units: str) -> float: """helper method""" if alt_units == 'm': factor = 0.3048 elif alt_units == 'ft': factor = 1. else: raise RuntimeError(f'alt_units={alt_units} is not valid; use [ft, m]') return factor
def is_student(user_bio): """Checks whether a GitHub user is a student. The bio of a user is parsed. If it contains phd the user will not be marked as a student. If the bio contains only the word student the user will be marked as a student. Args: user_id (string): user id which is named as "login" from the GitHub Api Returns: Boolean: Whether the user is a student or not """ user_bio = str(user_bio).lower() student = False if user_bio != "nan": # PhD students should be included mention_phd = "phd" in user_bio mention_student = "student" in user_bio student = not mention_phd and mention_student return student
def check_auth_by_token(token): """ This function is called to check if a token is valid """ return token == 'CRAZYTOKEN'
def jaccard(seq1, seq2): """Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. from: https://github.com/doukremt/distance """ set1, set2 = set(seq1), set(seq2) return 1 - len(set1 & set2) / float(len(set1 | set2))
def g(*args): """REGEX: build group.""" txt = '' for arg in args: if txt == '': txt = arg else: txt += '|' + arg return '(' + txt + ')'
def read_nion_image_info(original_metadata): """Read essential parameter from original_metadata originating from a dm3 file""" if not isinstance(original_metadata, dict): raise TypeError('We need a dictionary to read') if 'metadata' not in original_metadata: return {} if 'hardware_source' not in original_metadata['metadata']: return {} if 'ImageScanned' not in original_metadata['metadata']['hardware_source']: return {} exp_dictionary = original_metadata['metadata']['hardware_source']['ImageScanned'] experiment = {} print(exp_dictionary) if 'autostem' in exp_dictionary: print('auto') print(exp_dictionary.keys()) print() print(experiment)
def _try_eval(x, globals_, locals_): """return eval(x) or x""" try: return eval(x, globals_, locals_) except: return x
def timestr2sec(time_string): """ Convert a time string to a time interval Parameters ---------- time_string : str The string representing the time interval. Allowed units are y (years), d (days), h (hours), m (minutes), s (seconds) Returns ------- delta_t : float The time interval in seconds Examples -------- >>> timestr2sec("1d 2h 4.25s") 93604.25 >>> timestr2sec(None) 0.0 """ if not time_string: return -1 data = time_string.replace(' ', '') delta_t = 0 try: years, data = data.split('y') delta_t += float(years)*31536000 except ValueError: pass try: days, data = data.split('d') delta_t += float(days)*86400 except ValueError: pass try: hours, data = data.split('h') delta_t += float(hours)*3600 except ValueError: pass try: minustes, data = data.split('m') delta_t += float(minustes)*60 except ValueError: pass try: seconds, data = data.split('s') delta_t += float(seconds) except ValueError: pass return delta_t
def _generate_var_name(prefix, field_name): """ Generate the environment variable name, given a prefix and the configuration field name. Examples: >>> _generate_var_name("", "some_var") "SOME_VAR" >>> _generate_var_name("my_app", "some_var") "MY_APP_SOME_VAR" :param prefix: the prefix to be used, can be empty :param field_name: the name of the field from which the variable is derived """ return ( "_".join((prefix, field_name)).upper() if prefix else field_name.upper() )
def human_time(milliseconds, padded=False): """Take a timsetamp in milliseconds and convert it into the familiar minutes:seconds format. Args: milliseconds: time expressed in milliseconds Returns: str, time in the minutes:seconds format For example: """ milliseconds = int(milliseconds) seconds = milliseconds / 1000.0 minutes = seconds / 60 if padded: stamp = "{0:0>2}:{1:0>4.1f}".format(int(minutes), seconds % 60) else: stamp = "{0}:{1:0>4.1f}".format(int(minutes), seconds % 60) return stamp
def right_shift(number, n): """ Right shift on 10 base number. Parameters ---------- number : integer the number to be shift n : integer the number of digit to shift Returns ------- shifted number : integer the number right shifted by n digit Examples -------- >>> right_shift(123, 1) 3 >>> right_shift(0, 1) 0 >>> right_shift(1234, 2) 34 """ return number % 10 ** n
def camelcase(text): """ >>> camelcase("A Test title") 'aTestTitle' """ words = text.split() first = False for word in words: if not first: text = word.lower() first = True elif len(word) > 1: text += word[:1].upper() + word[1:] elif len(word) == 1: text += word[:1].upper() return text
def remove_comments(sql: str) -> str: """Remove comments from SQL script.""" # NOTE Does not strip multi-line comments. lines = map(str.strip, sql.split("\n")) return "\n".join(line for line in lines if not line.startswith("--"))
def preprocessing_tolist(preprocess): """ Transform preprocess into a list, if preprocess contains a dict, transform the dict into a list of dict. Parameters ---------- preprocess : category_encoders, ColumnTransformer, list, dict, optional (default: None) The processing apply to the original data Returns ------- List A list containing all preprocessing. """ list_encoding = preprocess if isinstance(preprocess, list) else [preprocess] list_encoding = [[x] if isinstance(x, dict) else x for x in list_encoding] return list_encoding
def solve_part1(puzzle_input): """Solve part 1 of today's puzzle. Find the two entries that sum to 2020; what do you get if you multiply them together? Parameters ---------- puzzle_input : str The puzzle input provided by the Advent of Code website. Returns ------- part1_answer : int The answer to part 1 of the puzzle Examples -------- In this list, the two entries that sum to 2020 are 1721 and 299. Multiplying them together produces 1721 * 299 = 514579, so the correct answer is 514579. >>> solve_part1('''1721 ... 979 ... 366 ... 299 ... 675 ... 1456''') 514579 """ # We need quick lookups, so we store the expense report as a set. expense_report = set(int(entry) for entry in puzzle_input.split()) for entry1 in expense_report: # This is the entry that needs to be in the expense report if the two # are to sum to 2020. entry2 = 2020 - entry1 if entry2 in expense_report: return entry1 * entry2
def _finditem(obj, key): """ Check if giben key exists in an object :param obj: dictionary/list :param key: key :return: value at the key position """ if key in obj: return obj[key] for k, v in obj.items(): if isinstance(v, dict): item = _finditem(v, key) if item is not None: return item
def sum_two_smallest_numbers(numbers): """The function that calculates the sum of lowest numbers.""" order = sorted(numbers, key=int) return order[0] + order[1]
def check_subtraction_file_type(file_name: str) -> str: """ Get the subtraction file type based on the extension of given `file_name` :param file_name: subtraction file name :return: file type """ if file_name.endswith(".fa.gz"): return "fasta" else: return "bowtie2"
def get_unallocated_seats(plan): """ Return a collection of unallocated seats :param plan: The seating plan for which to return the seats :return: A list of unallocated seat numbers """ return [ seat_number for row in plan.keys() if row.isnumeric() for seat_number in plan[row]["seats"] if plan[row]["seats"][seat_number] is None ]
def isnan(x): """Is x 'not a number' or 'None'""" from numpy import isnan try: return isnan(float(x)) except: return True
def bit_not(n, bit_length): """ defines the logical not operation :param n: the number to which the not operation is applied :param bit_length: the length of the bit to apply the not operation :return: """ return (1 << bit_length) - 1 - n
def _cross_ratio(z1, z2, z3, z4): """Calculate cross ratio between four values on a line""" nom = (z3 - z1) * (z4 - z2) den = (z3 - z2) * (z4 - z1) return nom / den
def block_to_smiles(block): """ Convert the formula of a block to a SMILES string """ if block == 'CH2': return 'C' elif block == 'NH': return 'N' elif block == 'O': return 'O' elif block == 'C6H4': return 'C1=CC=CC=C1' elif block == 'C4H2S': return 'C1=CSC=C1' elif block == 'CO': return 'C(=O)' elif block == 'CS': return 'C(=S)'
def redshift_to_frequency(z): """ Input : redshift Output : frequency in MHz """ nu = 1420/(1+z) return nu
def get_IO(IOfile): """ Given an IO specification for a network, Q, return a list of the input and output events. format is like ... [chanName]: I: [inputs] O: [outputs] """ events = set() chan = None lineType = lambda x: 2 if "O:" in x else 1 if "I:" in x else 0 try: with open(IOfile, "r") as fr: for line in fr: j = lineType(line) parts = [a.strip() for a in line.split(":")] parts = [p for p in parts if len(p) > 0] if j == 0: chan = parts[0] continue part2 = ( [] if len(parts) < 2 else [a.strip() for a in parts[1].split(",")] ) part2 = list(set(part2)) for msg in part2: if j == 1 and chan != None: events.add(chan + "?" + msg + ";") elif j == 2 and chan != None: events.add(chan + "!" + msg + ";") return events except Exception: return None
def check_profile_naming_to_id(profile_naming_to_id): """ :param profile_naming_to_id: :return: """ key_list = list(profile_naming_to_id.keys()) if type(key_list[0]) == str: return profile_naming_to_id elif type(key_list[0]) == int: return_dict = {} for i in profile_naming_to_id.keys(): return_dict[str(i)] = profile_naming_to_id[i] return return_dict
def nlbs(t9): """Finds the library number tuples in a tape9 dictionary. Parameters ---------- t9 : dict TAPE9 dictionary. Returns ------- decay_nlb : 3-tuple Tuple of decay library numbers. xsfpy_nlb : 3-tuple Tuple of cross section & fission product library numbers. """ decay_nlb = [] xsfpy_nlb = [None, None, None] for n, lib in t9.items(): if lib['_type'] == 'decay': decay_nlb.append(n) elif lib['_subtype'] == 'activation_products': xsfpy_nlb[0] = n elif lib['_subtype'] == 'actinides': xsfpy_nlb[1] = n elif lib['_subtype'] == 'fission_products': xsfpy_nlb[2] = n decay_nlb.sort() return tuple(decay_nlb), tuple(xsfpy_nlb)
def _strip_shape(name: str) -> str: """Strip the dimension name.""" if name[0] == "/": return name[1:] return name
def get_object_row_ids(object_metadata_records, id_field_key): """ Return a dict where each key is an object's ID and each value is the corresponding row ID of that object in the admin metadata table. We need row ID so that we can populate the connection field between field metadata records and their object. Args: object_metadata_records (TYPE): Description id_field_key (TYPE): Description Returns: TYPE: Description """ return {row[id_field_key]: row["id"] for row in object_metadata_records}
def forgiving_join(seperator, iterator): """ A join function that is more forgiving about the type of objects the iterator returns. """ return seperator.join(str(it) for it in iterator)
def status_map(state): """Return a numeric value in place of the string value for state""" if state == 'green': retval = 0 elif state == 'yellow': retval = 1 elif state == 'red': retval = 2 else: retval = 3 # fail return retval
def any_of(*args): """Return regex that matches any of the input regex patterns. The returned value is equivalent to writing:: r'(<arg1>|<arg2>|...)' """ return "({})".format("|".join(args))
def _getcontextrange(context, config): """Return the range of the input context, including the file path. Return format: [filepath, line_start, line_end] """ file_i = context['_range']['begin']['file'] filepath = config['_files'][file_i] line_start = context['_range']['begin']['line'][0] line_end = context['_range']['end']['line'][0] return [filepath, line_start, line_end]
def ToUnixLineEnding(s): """Changes all Windows/Mac line endings in s to UNIX line endings.""" return s.replace('\r\n', '\n').replace('\r', '\n')
def tic_tac_toe(board): """Lazy function to check if 3 in a row is obtained""" if (board[0][0] == board[1][0]) and (board[0][0] == board[2][0]) or \ (board[0][1] == board[1][1]) and (board[0][1] == board[2][1]) or \ (board[0][2] == board[1][2]) and (board[0][2] == board[2][2]) or \ (board[0][0] == board[0][1]) and (board[0][0] == board[0][2]) or \ (board[1][0] == board[1][1]) and (board[1][0] == board[1][2]) or \ (board[2][0] == board[2][1]) and (board[2][0] == board[2][2]) or \ (board[0][0] == board[1][1]) and (board[0][0] == board[2][2]) or \ (board[0][2] == board[1][1]) and (board[0][2] == board[2][0]): return True else: return False
def is_another_day(time_web: str, time_mobile: str) -> bool: """checks if days are different""" if time_web is None: return True if time_web < time_mobile: time_web, time_mobile = time_mobile, time_web year1 = time_web[0:4] year2 = time_mobile[0:4] if year1 != year2: return True month1 = time_web[5:7] month2 = time_mobile[5:7] if month1 != month2: return True day1 = time_web[8:10] day2 = time_mobile[8:10] if day1 != day2: return True return False
def merge(*args): """Implements the 'merge' operator for merging lists.""" ret = [] for arg in args: if isinstance(arg, list) or isinstance(arg, tuple): ret += list(arg) else: ret.append(arg) return ret
def unemployment_rate(earning, earning_new, unemployment): """ Args: earning: how much money the player earned last round earning_new: how much money the player earned this round unemployment: unemployment rate of the player had last round Returns: unemployment rate of the player has this round """ # based on okuns law delta_unemployment = ((earning - earning_new) / earning) / 1.8 new_unemployment = max(0, unemployment + delta_unemployment) return new_unemployment
def get_bbox_and_label(results, model_labels, image_width, image_height): """Draws the bounding box and label for each object in the results.""" bboxes = [] labels = [] scores = [] for obj in results: # Convert the bounding box figures from relative coordinates # to absolute coordinates based on the original resolution ymin, xmin, ymax, xmax = obj['bounding_box'] xmin = int(xmin * image_width) xmax = int(xmax * image_width) ymin = int(ymin * image_height) ymax = int(ymax * image_height) # Overlay the box, label, and score on the camera preview bbox = [xmin, ymin, xmax - xmin, ymax - ymin] label = model_labels[obj['class_id']] score = obj['score'] bboxes.append(bbox) labels.append(label) scores.append(score) return bboxes, labels, scores
def arguments_to_args_renames(arguments): """ The doc-opt parsed arguments include the - and -- and certain names are different. In order to have an apples-to-apples comparison with the new argparse approach, we must rename some of the keys. """ args = {} for k, v in arguments.items(): if k == '--download-attempts': args['download_attempts'] = int(v) elif k == '-u': args['update'] = v elif k == '-v': args['verbose'] = True # Should default to true elif k == '<file_path>': args['chef_script'] = v elif k == '-h': pass else: args[k.lstrip('-')] = v return args
def to_comma(string): """Replaces all the points in a string with commas. Args: string (str): String to change points for commas Returns: str: String with commas """ # Replace the points with strings in string try: string = string.replace(".", ",") except: print("The parameter string is not a str") finally: return string
def last_line_var(varname, code): """ Finds the last line in the code where a variable was assigned. """ code = code.split("\n") ret = 0 for idx, line in enumerate(code, 1): if "=" in line and varname in line.split("=")[0]: ret = idx return ret
def mac_str(n): """ Converts MAC address integer to the hexadecimal string representation, separated by ':'. """ hexstr = "%012x" % n return ':'.join([hexstr[i:i+2] for i in range(0, len(hexstr), 2)])
def sqrt_int(n): """ Calculate the integer square root of n, defined as the largest integer r such that r*r <= n Borrowed from: https://gist.github.com/hampus/d2a2d27f37415d37f7de Parameters ---------- n: int The integer to calculate the square root from Returns ------- out: int The value of the square root """ r = 1 while r * r <= n: r <<= 1 b = r = r >> 1 while b > 1: b >>= 1 r2 = r + b if r2 * r2 <= n: r = r2 return r
def generate_hosts_inventory(json_inventory): """Build a dictionary of hosts and associated groups from a Ansible JSON inventory file as keys. Args: json_inventory (dict): A dictionary object representing a Ansible JSON inventory file. Returns: dict(list(str)): A dictionary of hosts with each host having a list of associated groups. """ inventory_hosts = {k: [] for k in json_inventory['_meta']['hostvars'].keys()} inventory_groups = {k: v for (k, v) in json_inventory.items() if k != '_meta'} for group_name, group_info in inventory_groups.items(): if 'hosts' in group_info.keys(): for host in group_info['hosts']: inventory_hosts[host].append(group_name) return inventory_hosts
def generate_new_row(forecast_date, target, target_end_date, location, type, quantile, value): """ Return a new row to be added to the pandas dataframe. """ new_row = {} new_row["forecast_date"] = forecast_date new_row["target"] = target new_row["target_end_date"] = target_end_date new_row["location"] = location new_row["type"] = type new_row["quantile"] = quantile new_row["value"] = value return new_row
def color_switch(color): """ Rgb color switch for bounding box color, in case debugging is enabled. Keyword arguments: color -- color, in string format Return variables: integer, integer, integer (int, int, int; DEFAULT 0,0,0) """ if color == "white": return 255, 255, 255 elif color == "black": return 0, 0, 0 elif color == "red": return 234, 74, 28 elif color == "yellow": return 231, 234, 28 elif color == "orange": return 324, 147, 28 elif color == "blue": return 28, 44, 234 elif color == "green": return 28, 234, 34
def it(style, text): """ colored text in terminal """ emphasis = { "red": 91, "green": 92, "yellow": 93, "blue": 94, "purple": 95, "cyan": 96, } return ("\033[%sm" % emphasis[style]) + str(text) + "\033[0m"
def spin(programs, steps): """Spin programs from the end to the front.""" return programs[-int(steps):] + programs[:-int(steps)]
def restart_function(func): """ :param func: a function that returns None if it needs to be rerun :return: the value returned by func """ while True: returned_value = func() if returned_value == None: continue else: break return returned_value
def xgcd(a, b): """Calculates the extended greatest common divisor for two numbers (extended Euclidean algorithm). Parameters ---------- a : int First number. b : int Second number. Returns ------- int: The extended greatest common divisor for the two given numbers. """ if a == 0: return b, 0, 1 else: g, x, y = xgcd(b % a, a) return g, y - (b // a) * x, x
def set_default(obj): """ change sets to lists for json """ if isinstance(obj, set): return list(obj)
def find_opt(state, pair, data): """ return the best action available from the state """ lookup = "" for i in range(len(state)): lookup += str(state[i]) if i < len(state)-1: lookup += "," if lookup not in data[pair]: return "s" moves = data[pair][lookup] m_d = {} for m in moves.split(","): m_d[m.split(":")[0]] = float(m.split(":")[1]) best = "" max_v = 0 for m in m_d.keys(): if m_d[m] > max_v: best = m max_v = m_d[m] return best
def generate_file_name(runtime): """ Every runtime has -specific file that is expected by google cloud functions """ runtimes = { 'python37': 'main.py', 'nodejs8': 'index.js', 'nodejs10': 'index.js', 'go111': 'function.go' } return runtimes.get(runtime)
def unground(arg): """ Doc String """ if isinstance(arg, tuple): return tuple(unground(e) for e in arg) elif isinstance(arg, str): return arg.replace('QM', '?') else: return arg
def fibo(n): """Compute the (n+1)th Fibonacci's number""" a, b = 1, 1 i = 0 while i<n: a, b = b, a+b i += 1 return a
def generate_accessories(accessories, is_male): """ Generates a sentence based on the accessories defined by the attributes """ sentence = "He" if is_male else "She" sentence += " is wearing" def necktie_and_hat(attribute): """ Returns a grammatically correct sentence based on the attribute """ if attribute == "necktie" or attribute == "hat" or attribute == "necklace": return "a " + attribute return attribute if len(accessories) == 1: attribute = ( accessories[0].lower() if accessories[0] == "Eyeglasses" else necktie_and_hat(accessories[0].lower().split("_")[1]) ) return sentence + " " + attribute + "." for i, attribute in enumerate(accessories): attribute = ( attribute.lower() if attribute == "Eyeglasses" else necktie_and_hat(attribute.lower().split("_")[1]) ) if i == len(accessories) - 1: sentence = sentence[:-1] sentence += " and " + attribute + "." else: sentence += " " + attribute + "," return sentence
def default(input_str, name): """ Return default if no input_str, otherwise stripped input_str. """ if not input_str: return name return input_str.strip()