content
stringlengths
42
6.51k
def abbreviate(x): """ A small routine to automatically derive an abbreviation from the long name. """ try: first,last = x.split(' ') if len(last)>2: return "%s%s"%(first[0],last[0:3]) elif len(last)==1: return "%s%s"%(first[0:3],last[0]) else: return first[0:4] except: return x[0:4]
def merge_json(data1, data2): """merge lists in two json data together Args: data1 (json or None): first json data data2 (json): 2nd json data Returns: TYPE: merged data """ if not data1: return data2 else: for i in data2['list']: data1['list'][i] = data2['list'][i] return data1
def is_passphrase_valid_extended(phrase): """ each list item is alphabetically sorted, and again the value is added to the set uniquely """ word_list = phrase.split(" ") word_set = set(map(lambda v: ''.join(sorted(v)), word_list)) return len(word_list) == len(word_set)
def _build_self_message(msg, start, end, batch_size, total): """Creates a JSON object for batch processing. The function builds the message with all the details to be able to process the batch data when received. The aim of this message is this very same cloud function. Args: msg: A JSON object representing the message to modify function start: An integer representing the start index from the total ocurrences end: An integer representing the end index from the total ocurrences batch_size: An integer representing the amount of ocurrences in the batch total: An integer representing the total amount of ocurrences Returns: The incoming msg JSON object containing all the input parameters together. """ msg['start_index'] = start msg['end_index'] = end msg['batch_size'] = batch_size msg['total'] = total return msg
def _validate_subdomain(subdomain): """ Validates the given subdomain. Parameters ---------- subdomain : `None` or `str` Subdomain value. Returns ------- subdomain : `None` or `str` The validated subdomain. Raises ------ TypeError If `subdomain` was not given neither as `None` or `str` instance. """ if subdomain is not None: if type(subdomain) is str: pass elif isinstance(subdomain, str): subdomain = str(subdomain) else: raise TypeError( f'`subdomain` can be as `None` or as `str` instance, got {subdomain.__class__.__name__}.' ) if not subdomain: subdomain = None return subdomain
def get_state_salue(view, option): """Get selected values stored at the state element""" element_value = "" for element in view["state"]["values"]: element_value = view["state"]["values"][element].get(option, None) if element_value is not None: if element_value.get("selected_option", None) is not None: return element_value["selected_option"]["value"] return element_value.get("value", None)
def adjust_detector_length(requested_detector_length, requested_distance_to_tls, lane_length): """ Adjusts requested detector's length according to the lane length and requested distance to TLS. If requested detector length is negative, the resulting detector length will match the distance between requested distance to TLS and lane beginning. If the requested detector length is positive, it will be adjusted according to the end of lane ending with TLS: the resulting length will be either the requested detector length or, if it's too long to be placed in requested distance from TLS, it will be shortened to match the distance between requested distance to TLS and lane beginning. """ if requested_detector_length == -1: return lane_length - requested_distance_to_tls return min(lane_length - requested_distance_to_tls, requested_detector_length)
def encodeDict(items): """ Encode dict of items in user data file Items are separated by '\t' characters. Each item is key:value. @param items: dict of unicode:unicode @rtype: unicode @return: dict encoded as unicode """ line = [] for key, value in items.items(): item = u'%s:%s' % (key, value) line.append(item) line = '\t'.join(line) return line
def is_insert(line): """ Returns true if the line begins a SQL insert statement. """ return line.startswith(b'INSERT INTO') or False
def hex_byte_to_bits(hex_byte): """ Interpret a single hex character as bits. This function will accept a hex byte (two characters, 0-F) and cast it to a list of eight bits. Credit to StackOverflow user: "Beebs" for concise function implementation. Parameters ---------- hex_byte: str String of two characters representing the byte in hex. Returns ------- bits: list of int List of eight bits (0/1) representing each bit position in the input byte. See Also -------- hex_bits_from_str : Determine the bit-structure of multiple hex bytes in a string. """ binary_byte = bin(int(hex_byte, base=16)) # Use zfill to pad the string with zeros as we want # all 8 digits of the byte. bits_string = binary_byte[2:].zfill(8) return [int(bit) for bit in bits_string]
def index_of_first_zero_bit_moving_right_to_left(ii): """ Return the first the index of the first zero bit of the integer ii when moving right to left. Returns index in [0,...,nbits(ii)-1] # x >> y Returns x with the bits shifted to the right by y places. # This is the same as //'ing x by 2**y. # x & y Return bitwise and """ jj = 1 while ((ii & 1) > 0): ii >>= 1 jj += 1 #print(ii, "{0:b}".format(ii), jj, (ii&1)>0) return jj-1
def camel2snake(s): """Convert a camelCase name to snake_case""" o = '' lastcap = False for letter in s: lc = letter.lower() if not lc.isalpha(): lastcap = True if lc == '-': lc = '_' lastcap = True elif not lc.isalpha(): lastcap = True elif lc != letter: if not lastcap: o += '_' lastcap = True else: lastcap = False o += lc return o
def complemento_base (base): """ (str)-> (str) Programa para complementar la base dada >>> complemento_base('T') 'AT' >>> complemento_base('G') 'CG' >>> complemento_base('C') 'GC' :param base: base a complementar :return: base complementada """ comp_base = '' if (base == 'C'): comp_base = 'G' + base elif (base == 'T'): comp_base = 'A' + base elif (base == 'G'): comp_base = 'C' + base else: comp_base = 'T' return comp_base
def escape(s: str) -> str: """Escape HTML entity characters.""" s = s.replace('&', '&amp;') s = s.replace('<', '&lt;') s = s.replace('>', '&gt;') s = s.replace('"', '&quot;') return s.replace('\'', '&#x27;')
def get_filenames(i): """Returns the filepaths for the output MusicXML and .png files. Parameters: - i: unique identifier for the score Returns: - (sheet_png_filepath, musicxml_out_filepath) """ output_folder_prefix = "dataset/" sheet_png_out_filepath = output_folder_prefix + "{}-sheet.png".format(i) musicxml_out_filepath = output_folder_prefix + "{}-musicxml.xml".format(i) return (sheet_png_out_filepath, musicxml_out_filepath)
def front_back(str_: str) -> str: """Swap the first and last characters of a string.""" if len(str_) > 1: return f'{str_[-1]}{str_[1:-1]}{str_[0]}' return str_
def precedes(layers, n1, n2): """ Helper function to determine whether node n1 is in a layer that immediately precedes the layer of node n2. """ i = [k for k in range(len(layers)) if n1 in layers[k]][0] j = [k for k in range(len(layers)) if n2 in layers[k]][0] return i + 1 == j
def parse_string(string: str): """function to convert a string into a int list Example: Input: parse_string("64-64") Output: [64, 64] """ string_arr = string.split("-") int_list = [] for string in string_arr: try: int_list.append(int(string)) except: raise Exception("Invalid argument format on: " + string) return int_list
def _pkg_shortname(package): """ Strips out the package's namespace and returns its shortname. """ return package.split('/')[1]
def get_value(path, obj): """Returns the value of key in a nested data structure :param path: The path to the value to be returned :type path: str :param obj: Source of the data to return a value from :type obj: obj :return: Value based on the path or None :rtype: object """ try: path = path.split('.') for item in path: try: item = int(item) except ValueError: pass obj = obj[item] return obj except KeyError: return None
def distance(point1, point2): """Return the calculated distance between the points. Manhattan distance. """ x0, y0 = point1 x1, y1 = point2 return abs(x1 - x0) + abs(y1 - y0)
def is_mode_correct(mode_no): """The function checks the correctness of the game mode (number range from 1 to 2).""" try: num = int(mode_no) if num < 1 or num > 2: return False except ValueError: return False return True
def _bpe_to_words(sentence, delimiter='@@'): """Convert a sequence of bpe words into sentence.""" words = [] word = '' delimiter_len = len(delimiter) for subwords in sentence: if len(subwords) >= delimiter_len and subwords[-delimiter_len:] == delimiter: word += subwords[:-delimiter_len] else: word += subwords words.append(word) word = '' return words
def create_table(table_headers, table_rows): """Given array of table headers, and an array of arrays for each row, format as table""" ths = [{'value': header_name} for header_name in table_headers] trs = [{ 'tds': [{ 'value': col_val } for col_val in row] } for row in table_rows] return {'ths': ths, 'trs': trs}
def get_tags_for_deliverable(team_data, team, name): """Return the tags for the deliverable owned by the team.""" if team not in team_data: return set() team_info = team_data[team] dinfo = team_info['deliverables'].get(name) if not dinfo: return set() return set(dinfo.get('tags', [])).union(set(team_info.get('tags', [])))
def business_rule_2(account: int, use_br: bool, threshold: int) -> bool: """ Account sends >= threshold transactions within a day. Only works for scatter-gather. :param account: number of involved accounts :param use_br: whether to use this br :param threshold: the threshold :return: True when the laundering was successful, false when it is caught """ if not use_br: return True if (account - 2) < threshold: return True else: return False
def checkToken(aToken): """ Used by pickColumns, below: """ if ( aToken.find(';') >= 0 ): aList = aToken.split(';') aList.sort() newT = '' for bToken in aList: newT += bToken if ( len(newT) > 0 ): newT += ';' if ( newT[-1] == ';' ): newT = newT[:-1] return ( newT ) elif ( aToken.find(',') >= 0 ): aList = aToken.split(',') aList.sort() newT = '' for bToken in aList: newT += bToken if ( len(newT) > 0 ): newT += ',' if ( newT[-1] == ',' ): newT = newT[:-1] return ( newT ) return ( aToken )
def str_to_int(exp): """ Convert a string to an integer """ sum = 0 for character in exp: sum += ord(character) return sum
def _convert_paths_to_flask(transmute_paths): """ convert transmute-core's path syntax (which uses {var} as the variable wildcard) into flask's <var>. """ paths = [] for p in transmute_paths: paths.append(p.replace("{", "<").replace("}", ">")) return paths
def set_roles(db, roles): """ Add roles to a key-value store db :return: db """ db['roles'] = roles return db
def findXCoordinateFromDirection(direction): """ Returns delta X, when given a direction value """ if direction in (1, 5): return 0 elif direction in (2, 3, 4): return 2 elif direction in (6, 7, 8): return -2 else: error_template = "Unexpected direction value of: {0}" raise ValueError(error_template)
def dimensions(paths): """ Calculate the dimensions of a set of paths (i.e. minumum box) Returns (left, top, right, bottom) as a box. """ min_x = float('inf') min_y = float('inf') max_x = float('-inf') max_y = float('-inf') for path in paths: for point in path: #print("point: %s" % point) x = point[0] y = point[1] min_x = min(x, min_x) min_y = min(y, min_y) max_x = max(x, max_x) max_y = max(y, max_y) #print("Dimens: (%s %s) (%s %s)" % (min_x, min_y, max_x, max_y)) return (min_x, min_y, max_x, max_y)
def stepAndRepeat(singleExpansion, singleSpikePattern, step, repeat): """ Given a single instance of the expansion pattern and corresponding spike patter, plus the stepping distance between patterns and a repeat count, copy the expansion pattern to the 'repeat' number of places, separated by 'step' indices. """ fullExpansion = [] fullSpikePattern = [] for i in range(repeat): offset = i * step for expansionValue in singleExpansion: fullExpansion.append([expansionValue[0] + offset, expansionValue[1] + offset, expansionValue[2], expansionValue[3]]) for spikePattern in singleSpikePattern: fullSpikePattern.append([spikePattern[0], spikePattern[1] + offset]) return fullExpansion, fullSpikePattern
def hide_toolbar(notebook): """ Finds the display toolbar tag and hides it """ if 'celltoolbar' in notebook['metadata']: del(notebook['metadata']['celltoolbar']) return notebook
def _preprocess_image(image, return_debug_images=False): """Pre-process an image before comparing it to others. This should be done both to input images when classifying, and tile data images when importing. This function currently does nothing, but is kept to make it easier to experiment. Parameters ---------- image Image to process, with floats. return_debug_images If true, also return a list of (name, image) tuples with intermediate images. Returns ------- The processed image, and optionally debug images. """ if return_debug_images: return image, [] return image
def parse_commandline_args(args): """ Parse command line arguments :param args: list of arguments :return: parameter names and values """ assert len(args) == 7, f'ERROR: pass exactly 7 arguments to launch the simulation, not {len(args)}.' expected_par_names = ['lambda', 'tau', 'delta'] assert args[1] in expected_par_names and args[3] in expected_par_names and args[5] in expected_par_names, \ f'ERROR: parsed unexpected parameter name, one of {args[1], args[3], args[5]}' # Parameter names par_name_input_1 = str(args[1]) par_name_input_2 = str(args[3]) par_name_input_3 = str(args[5]) # Parameter values try: par_value_input_1 = int(args[2]) except ValueError: par_value_input_1 = float(args[2]) try: par_value_input_2 = int(args[4]) except ValueError: par_value_input_2 = float(args[4]) try: par_value_input_3 = int(args[6]) except ValueError: par_value_input_3 = float(args[6]) return par_name_input_1, par_value_input_1, par_name_input_2, par_value_input_2, par_name_input_3, par_value_input_3
def class_name(obj): """Returns the class name of the specified object. """ return obj.__class__.__name__
def generate_unsafe_ingress_entry(ingress_entry: dict, unsafe_ip: str) -> dict: """ Generates a dictionary from an unsafe ingress entry to the analysis response """ unsafe_ingress = { "IpProtocol": ingress_entry["IpProtocol"], "CidrIp": unsafe_ip, "Status": "warning", } if "FromPort" in ingress_entry: unsafe_ingress["FromPort"] = ingress_entry["FromPort"] if "ToPort" in ingress_entry: unsafe_ingress["ToPort"] = ingress_entry["ToPort"] return unsafe_ingress
def extract(node, path): """Pull bits of data out of the ecs bag structure""" ptr = node for item in path: if hasattr(ptr, item): ptr = getattr(ptr, item) else: return None return ptr
def bitsize(a): """ Compute the bitsize of an element of Z (not counting the sign). """ val = abs(a) res = 0 while val: res += 1 val >>= 1 return res
def getUVPins(faces, borders, uvFaces, uvBorders, pinBorders): """Find which uvBorders are also mesh borders""" if uvFaces is None: return set() if pinBorders: return set(uvBorders) pinnit = set() for face, uvFace in zip(faces, uvFaces): for i in range(len(face)): f = face[i] pf = face[i-1] uv = uvFace[i] puv = uvFace[i-1] if not(f in borders and pf in borders): if uv in uvBorders and puv in uvBorders: pinnit.add(puv) pinnit.add(uv) return uvBorders & pinnit
def blockReward(height): """ https://docs.decred.org/advanced/inflation/ I think this is actually wrong for height < 4096 """ return 31.19582664*(100/101)**int(height/6144)
def join2(xseries, sep=',', final_sep=' or '): """Regular "join", but with a special separator before the last item. Example: join2([a,b,c,d], ',', ' and ') --> 'a, b, c and d' """ return sep.join(xseries[:-1]) + final_sep + ''.join(xseries[-1:])
def yielder(it): """ Yield from generator. Adapted from: https://stackoverflow.com/a/40701031 """ try: return next(it) except StopIteration: return None
def pbb_to_dict(pbb_all): """ Function that takes the pbb_all array and turns it into a dictionary to be used and added to the pyart radar object. """ pbb_dict = {} pbb_dict['coordinates'] = 'elevation azimuth range' pbb_dict['units'] = '1' pbb_dict['data'] = pbb_all pbb_dict['standard_name'] = 'partial_beam_block' pbb_dict['long_name'] = 'Partial Beam Block Fraction' pbb_dict['comment'] = 'Partial beam block fraction due to terrain.' return pbb_dict
def flatten_dictionaries(input): """ Flatten a list of dictionaries into a single dictionary, to allow flexible YAML use Dictionary comprehensions can do this, but would like to allow for pre-Python 2.7 use If input isn't a list, just return it.... """ output = dict() if isinstance(input, list): for map in input: output.update(map) else: # Not a list of dictionaries output = input return output
def PerpProduct2D(a,b): """Computes the the 2D perpendicular product of sequences a and b. The convention is a perp b. The product is: positive if b is to the left of a negative if b is to the right of a zero if b is colinear with a left right defined as shortest angle (< 180) """ return (a[0] * b[1] - a[1] * b[0])
def GetValueFromListList(values,iteration): """ Function generating the random sample; in this case, we return a value from an input """ value = values[iteration] return value
def curvature(dx, dy, ddx, ddy): """ Compute curvature at one point given first and second derivatives. :param dx: (float) First derivative along x axis :param dy: (float) :param ddx: (float) Second derivative along x axis :param ddy: (float) :return: (float) """ return (dx * ddy - dy * ddx) / (dx ** 2 + dy ** 2) ** (3 / 2)
def retrive_sequence(contig_lst, rec_dic): """ Returns list of sequence elements from dictionary/index of SeqIO objects specific to the contig_lst parameter """ contig_seqs = list() #record_dict = rec_dic #handle.close() for contig in contig_lst: contig_seqs.append(rec_dic[contig].seq.tostring()) return contig_seqs
def normalize(rendered): """Return the input string without non-functional spaces or newlines.""" out = ''.join([line.strip() for line in rendered.splitlines() if line.strip()]) out = out.replace(', ', ',') return out
def recursive_len(item: list): """ Return the total number of elements with a potentially nested list """ if type(item) == list: return sum(recursive_len(subitem) for subitem in item) else: return 1
def hexString(s): """ Output s' bytes in HEX s -- string return -- string with hex value """ return ":".join("{:02x}".format(ord(c)) for c in s)
def subseq( seq, index ): """numpy-style slicing and indexing for lists""" return [seq[i] for i in index]
def extend_dictionary(d1, d2): """ Helper function to create a new dictionary with the contents of the two given dictionaries. Does not modify either dictionary, and the values are copied shallowly. If there are repeats, the second dictionary wins ties. The function is written to ensure Skulpt compatibility. Args: d1 (dict): The first dictionary d2 (dict): The second dictionary Returns: dict: The new dictionary """ d3 = {} for key, value in d1.items(): d3[key] = value for key, value in d2.items(): d3[key] = value return d3
def get_host_values(field, db_object): """Retrieves the list of hosts associated with peer.""" result = [] for entry in getattr(db_object, 'hosts', []): result.append(entry.hostname) return result
def decodeBits (len, val): """ Calculate the value from the "additional" bits in the huffman data. """ return val if (val & (1 << len - 1)) else val - ((1 << len) - 1)
def reverseBits(m): """ :param m: integer to reberse bits :return: integer with reverse bits and number of bits in m """ mRev = 0 n = 0 while m > 0: mRev <<= 1 mRev += m % 2 m >>= 1 n += 1 return mRev, n
def policy_threshold(threshold, belief, loc): """ chooses whether to switch side based on whether the belief on the current site drops below the threshold Parameters ---------- threshold (float): the threshold of belief on the current site, when the belief is lower than the threshold, switch side belief (numpy array of float, 2-dimensional): the belief on the two sites at a certain time loc (int) : the location of the agent at a certain time -1 for left side, 1 for right side Returns ------- act (string): "stay" or ""switch """ if belief[(loc + 1 ) // 2] <= threshold: act = "switch" else: act = "stay" return act
def split_and_strip(sep, s): """ Split input `s` by separator `sep`, strip each output segment with empty segment dropped. """ return [y for y in (x.strip() for x in s.split(sep)) if len(y) > 0]
def suppConfiguration(cfg): """Load the default pipeline configuration and adjust as necessary """ #Edit the input configuration with things specific to this task. cfg['debug'] = False # tasks = """dpp.checkDirExistTask dpp.serveTask dpp.extractLightcurveFromTpfTask # dpp.computeCentroidsTask dpp.rollPhaseTask dpp.cotrendSffDataTask # dpp.detrendDataTask dpp.trapezoidFitTask dpp.lppMetricTask # dpp.modshiftTask dpp.measureDiffImgCentroidsTask dpp.dispositionTask # dpp.saveOnError""".split() tasks = """dpp.checkDirExistTask dpp.serveTask dpp.extractLightcurveTask dpp.computeCentroidsTask dpp.rollPhaseTask dpp.cotrendDataTask dpp.detrendDataTask dpp.blsTask dpp.trapezoidFitTask dpp.modshiftTask dpp.measureDiffImgCentroidsTask dpp.dispositionTask dpp.saveClip""".split() cfg['taskList'] = tasks searchTaskList = """blsTask trapezoidFitTask modshiftTask measureDiffImgCentroidsTask dispositionTask""".split() cfg['searchTaskList'] = searchTaskList try: cfg['timeout_sec'] = int(cfg['timeout_sec']) except: cfg['timeout_sec'] = 150 return cfg
def in_order_traversal(root): """ @ input: root of lcrs tree @ output: integer list of id's in-order """ node_list = [] if root: node_list = in_order_traversal(root.child) # Left tree node_list.append(root.id) # Root of tree node_list = node_list + in_order_traversal(root.next) # Right tree return node_list
def td_rotate_90ccw(txtdict, wout, hout): """Rotate 90 CCW""" # y: x # x: w - y - 1 ret = {} for y in range(hout): for x in range(wout): xin = hout - y - 1 yin = x try: val = txtdict[(xin, yin)] except KeyError: raise KeyError( "out %uw x %u h: %ux, %uy out => invalid %ux, %uy in" % (wout, hout, x, y, xin, yin)) ret[(x, y)] = val return ret
def _convert_rho_to_krho(rho, size_ds: int): """ Converts the parameter ``rho`` (also noted: math:`\\varrho`) between :math:`0 < \\varrho < 1` in a value between 0 and the size of the reference game. :param list rho: The values (s) of :math:`\\varrho` to convert :param int size_ds: The size of the reference game :returns: the list of :math:`\\varrho \\times size\_ds` :rtype: list """ if isinstance(rho, list): return [x * size_ds for x in rho] elif isinstance(rho, float) and rho < 1.0: return [size_ds * rho] else: raise ValueError("Rho must be a float or a list of floats between 0.0 and 1.0")
def process_opt_with_defn(process, key, defns, values): """ Use the map of option definitions provided (defns) and map of project/user-selected preferences (values) to produces appropriate command line arguments for the given key (key). In all current cases, the proc_fn in the defns map will either return the flag (from defns) and some appropriate formatting of the value (from values), or will return an empty list. """ defn = defns[key] value = values[key] longname=key (flag, proc_fn) = defn args = proc_fn(process=process, longname=longname, flag=flag, value=value) return args
def format_latex(ss): """ Formats a string so that it is compatible with Latex. :param ss: The string to format :type ss: string :return: The formatted string :rtype: string """ tt = (str(ss).replace('_', ' ') .replace('%', '\%') ) return tt
def mergeDict(master, other): """Merge the given two dictionaries recursively and return the result.""" if isinstance(master, dict) and isinstance(other, dict): for key, value in other.items(): if isinstance(value, dict): if key not in master: master[key] = value else: master[key] = mergeDict(master[key], value) else: master[key] = value return master
def content_type(content_type_str): """Returns the actual type, as embedded in an xml ContentType attribute; application and version are disregarded.""" if content_type_str is None: return None if 'type=' in content_type_str: return content_type_str[content_type_str.rfind('type=') + 5:] # if ':' in content_type_str: # return content_type_str[content_type_str.rfind(':') + 1:] return content_type_str
def get_diff(old, new, value): """ Get the difference between old and new osu! user data. """ return float(new[value]) - float(old[value])
def fizz_buzz_one( start, end ): """ Note: This method returns a long string not a list. """ fizzbuzz = '' # range is NOT inclusive of the 2nd number, so add 1 to include it. # range(1,4) > 1,2,3. range(1, 4 + 1) > 1,2,3,4. for i in range(start,end+1): if i%3 == 0: fizzbuzz += "fizz" if i%5 == 0: fizzbuzz += "buzz" if i%3 != 0 and i%5 != 0: fizzbuzz += str(i) fizzbuzz += ' ' return fizzbuzz.rstrip()
def get_ending_datetime_of_timetable(timetable): """ Get the ending_datetime of a timetable, which corresponds to the arrival_datetime of the last timetable entry. :param timetable: timetable_document :return: None (Updates timetable) """ timetable_entries = timetable.get('timetable_entries') ending_timetable_entry = timetable_entries[len(timetable_entries) - 1] ending_datetime_of_timetable = ending_timetable_entry.get('arrival_datetime') return ending_datetime_of_timetable
def list_to_dict(seq): """ Take list and insert value in dict Using values from list as keys and index from list as values in BST. """ d = {} for v, k in enumerate(seq): d[k] = v return d
def time2s(t): """ t: "hh:mm:ss" """ h, m, s = t.split(":") return int(h)*3600 + int(m)*60 + int(s)
def red(string): """ Use ascii escape sequences to turn `string` in red color. Parameters ---------- string : str String to add red color to. Returns ------- red_string: str `string` with ascii escape codes added that will make it show up as red. """ return "\033[91m{}\033[0m".format(string)
def evaluate_accuracy(labels, predictions): """ Input: Arrays of labels and predictions, each containing either '0' or '1' Output: The fraction of predictions that correctly match the label """ # Make sure that the lengths of both arrays is equal assert(len(labels) == len(predictions)) # Score will count how many predictions are correct score = 0 for i in range(len(labels)): label = labels[i] prediction = predictions[i] if label == prediction: # If prediction is correct, increment score score += 1 # Return accuracy return (float(score) / float(len(labels)))
def base_taskname(taskname, packagename=None): """ Extract the base name of the task. Many tasks in the `drizzlepac` have "compound" names such as 'drizzlepac.sky'. This function will search for the presence of a dot in the input `taskname` and if found, it will return the string to the right of the right-most dot. If a dot is not found, it will return the input string. Parameters ---------- taskname : str, None Full task name. If it is `None`, :py:func:`base_taskname` will return `None`\ . packagename : str, None (Default = None) Package name. It is assumed that a compound task name is formed by concatenating `packagename` + '.' + `taskname`\ . If `packagename` is not `None`, :py:func:`base_taskname` will check that the string to the left of the right-most dot matches `packagename` and will raise an `AssertionError` if the package name derived from the input `taskname` does not match the supplied `packagename`\ . This is intended as a check for discrepancies that may arise during the development of the tasks. If `packagename` is `None`, no such check will be performed. Raises ------ AssertionError Raised when package name derived from the input `taskname` does not match the supplied `packagename` """ if not isinstance(taskname, str): return taskname indx = taskname.rfind('.') if indx >= 0: base_taskname = taskname[(indx + 1):] pkg_name = taskname[:indx] else: base_taskname = taskname pkg_name = '' assert(True if packagename is None else (packagename == pkg_name)) return base_taskname
def rawlist(*args): """Build a list of raw IRC messages from the lines given as ``*args``. :return: a list of raw IRC messages as seen by the bot :rtype: list This is a helper function to build a list of messages without having to care about encoding or this pesky carriage return:: >>> rawlist('PRIVMSG :Hello!') [b'PRIVMSG :Hello!\\r\\n'] """ return ['{0}\r\n'.format(arg).encode('utf-8') for arg in args]
def name_paths(name_dataset): """ provide article type make the needed files """ name_src = str(name_dataset + '_src_query') name_dst = str(name_dataset + '_dst_query') name_summary = str(name_dataset + '_sum') name_unique = str(name_dataset + '_unique_df') plot_unique = str(name_dataset + '_unique_plot') return name_src, name_dst, name_summary, name_unique, plot_unique
def generate_model_config(name, n_filters, nonlinearity='relu'): """ Generates a spec describing how to build the model Args: name: name for this model config n_filters: list of num filters for each layer - [n_layers] Returns: model_spec """ model_config = { 'name': name, 'n_filters': n_filters, 'nonlinearity': nonlinearity } return model_config
def extract(text, startText, endText): """ Extract the first occurence of a string within text that start with startText and end with endText Parameters: text: the text to be parsed startText: the starting tokem endText: the ending token Returns the string found between startText and endText, or None if the startText or endText is not found """ start = text.find(startText, 0) if start != -1: start = start + startText.__len__() end = text.find(endText, start + 1) if end != -1: return text[start:end] return None
def traverse_list_forward(head): """Traverse the LinkedList in forward direction""" if head is None: return -1 curr = head arr = [] while curr: arr.append(curr.data) curr = curr.next return ' '.join(map(str, arr))
def string_contains_environment_var(string): """Determines whether or not there is a valid environment variable in the string""" parts = string.split("$") # If there are no $ then there is no possiblity for there to be # an environment variable if len(parts) == 1: return False for index, part in enumerate(parts): # If the part has no length, then the first variable is an unescaped # Dollarsign and we will just continue (as it could be an invalid # var such as: $% if len(part) == 0: continue # If the first character is not an alpha or an _ then this is an # invalid environment variable and will not be treated as such if not part[0].isalpha(): continue if index > 0: # If we are not on the first element, then we check to see # if the previous entry ended in a "\" if it did, then that # means this value should have a literal dollar sign in it # so we just continue: # i.e. foo\$bar prev_part = parts[index - 1] if prev_part.endswith("\\"): continue # otherwise, then we've found a valid environment variable else: return True # If we are on the first element, and it does not end with a "\" # and it is not the last element in the array, then we must have # an environment Variable: # i.e.: /path/to/foo:$PATH elif not part.endswith("\\") and index + 1 != len(parts): return True return False
def duration_str(s): """ s: number of seconds Return a human-readable string. Example: 100 => "1m40s", 10000 => "2h46m" """ if s is None: return None m = int(s / 60) if m == 0: return "%.1fs" % s s -= m * 60 h = int(m / 60) if h == 0: return "%dm%ds" % (m, s) m -= h * 60 d = int(h / 24) if d == 0: return "%dh%dm" % (h, m) h -= d * 24 y = int(d / 365) if y == 0: return "%dd%dh" % (d, h) d -= y * 365 return "%dy%dd" % (y, d)
def is_blank_or_comment(x): """Checks if x is blank or a FASTA comment line.""" return (not x) or x.startswith('#') or x.isspace()
def clamp(value, abs_max): """clamp value""" value = max(-abs_max, value) value = min(abs_max, value) return value
def month_num(month_name: str): """Returns the number of a month, with January as month number 1. It;s case insensitive.""" months = [ 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december', ] return months.index(month_name.lower())+1
def partition(s): """Returns: a list splitting s in two parts Precondition: s is a string.""" first = "" second = "" # for x in s: # pos = s.find(x) # print(pos) # if pos % 2 == 0: # first += x # else: # second += x for pos in range(len(s)): if pos % 2 == 0: first = first + s[pos] else: second = second + s[pos] return [first, second]
def _check_nested_floats(thelist): """ Returns True if thelist is a (nested) list of floats INTERNAL HELPER If thelist recursively contains anything other than a list, tuple, int, or float, this function returns false. :param message: A custom error message (OPTIONAL) :type message: ``str`` """ result = True for item in thelist: if type(item) in [list,tuple]: result = result and _check_nested_floats(item) else: result = result and type(item) in [int,float] return result
def drawBorder(grid: list) -> list: """Draw a border around the maze""" for i, x in enumerate(grid): # Left and Right border x[0] = x[len(grid)-1] = (20,20,20) grid[i] = x grid[0] = grid[len(grid)-1] = [(20,20,20) for x in range(len(grid))] # Top and Bottom border return grid
def is_word_capitalized(word): """ Check if word is capitalized. Args: word (str): Word. Returns: (boole): True f word is capitalized. False otherwise. """ if not word: return False first_letter = word[0] return first_letter == first_letter.upper()
def isPerfectSquare(num: int) -> bool: """Okay. Solution is O(1).""" r = int(num ** 0.5) return r * r == num
def params(kernels, time, target, target_frame, observer, corr): """Input parameters from WGC API example.""" return { 'kernels': kernels, 'times': time, 'target': target, 'target_frame': target_frame, 'observer': observer, 'aberration_correction': corr, }
def getHostIP(url='www.google.com'): """Returns the (external) host ip for this machine""" import socket s = socket.socket() try: s.connect((url, 80)) return s.getsockname()[0] except Exception: return socket.gethostbyname(socket.gethostname())
def append(base, suffix): """Append a suffix to a string""" return f"{base}{suffix}"
def _insert_statement(name, d): """Generate an insert statememt. ex) insert into foo values (:a, :b, :c, ...) """ keycols = ', '.join(":" + c.strip() for c in d) return "insert into %s values (%s)" % (name, keycols)
def font_bold(mystring): """ Formats the string as bold, to be used in printouts. """ font_bold = "\033[1m" font_reset = "\033[0;0m" return font_bold + mystring + font_reset
def humanize_list(l): """Return a human-readable list.""" if len(l) == 1: return l[0] elif len(l) == 2: return "{0} and {1}".format(l[0], l[1]) else: return ", ".join(l[:-1]) + ", and " + l[-1]
def storable(obj): """ Remove fields that can't / shouldn't be stored. """ def get_data(a): if a.startswith('linked_'): return getattr(getattr(obj, a), 'uuid', None) else: return getattr(obj, a) return { a:get_data(a) for a in dir(obj) if not a.startswith('_') and not hasattr( getattr(obj, a), '__call__' ) }
def add_if_missing(add_this, path_list_str): """ if a path is missing in a path list separated by ';', append it """ path_list = path_list_str.split(';') if add_this in path_list: pass else: path_list.append(add_this) return ';'.join(path_list)
def normalized_device_coordinates_to_image(image): """Map normalized value from [-1, 1] -> [0, 255]. """ return (image + 1.0) * 127.5