content
stringlengths
42
6.51k
def isFrozen(status): """ Return a boolean indicating whether the given status name is frozen or not. @type status: C{unicode} @rtype: C{bool} """ return status.startswith(u'.')
def unwrap_string(s): """A utility function that converts a "'string'" to a "string" """ s = s.replace("'", "") return s
def list_of_val(val_for_list, list_len, num_lists = 1): """Generate a list or list of lists containing a single value. Parameters ---------- val_for_list : any Value that will be repeated in list or lists of lists. list_len : int Length of list output, or lists within list if multip...
def set_tif_names(directory, file_names): """ This function returns the directory + file_name of the inputs. In general, it is used to do mosaic with many geotiff files. :param directory: String :param file_names: String :return: list ...
def bubble_sort(lis): """ Put the largest element to the rightmost position each time 1. Set done flag = True 2. Start with i = 0, swap i and i + 1 if num[i] > num[i + 1] 3. done = False if any swap occured 4. Keep running while done is False """ j = 0 done = False while not done...
def get_neighbor(rows, ele): """ :param rows: lst, letters get from user :param ele: lst, current letter position :return neighbor: lst, the location tuple next to ele """ neighbor = [] # find valid location tuples that in 3x3 grid centered by ele for x in range(-1, 2): for y in range(-1, 2): test_x = ele[...
def str_to_byn(str_): """ str_to_bin([string]) UTF-8 Takes string. Return string of binary bites splited with " " Example input: bynary_to_string.str_to_byn('ex') output: '1100101 1111000' """ return ' '.join(bin(byte).lstrip('0b') for Item in str_ for byte in Item.encode())
def bigram_similarity(word1: str, word2: str) -> float: """ Returns a number within the range [0, 1] determining how similar item1 is to item2. 0 indicates perfect dissimilarity while 1 indicates equality. The similarity value is calculated by counting the number of bigrams both words share in commo...
def parse_citations(citations_text): """ """ citations = [c for c in citations_text.split("**ENTRY**") if c.strip()] citation_tuples = [] for citation in citations: if citation.startswith("doi"): citation_tuples.append( ("doi", citation[len("doi"):].strip() ) ) else: ...
def listsplit(liststr=''): """Return a split and stripped list.""" ret = [] for e in liststr.split(','): ret.append(e.strip()) return ret
def cliprgb(r, g, b): """ clip r,g,b values into range 0..254 """ def clip(x): """ clip x value into range 0..254 """ if x < 0: x = 0 elif x > 254: x = 254 return x return clip(r), clip(g), clip(b)
def _snmp_octetstr_2_string(binary_value): """Convert SNMP OCTETSTR to string. Args: binary_value: Binary value to convert Returns: result: String equivalent of binary_value """ # Convert and return result = ''.join( ['%0.2x' % ord(_) for _ in binary_value.decode('utf-...
def _PruneMessage(obj): """Remove any common structure in the message object before printing.""" if isinstance(obj, list) and len(obj) == 1: return _PruneMessage(obj[0]) elif isinstance(obj, dict) and len(obj) == 1: for v in obj.values(): return _PruneMessage(v) else: return obj
def crr_m(ksigma, msf, crr_m7p5): """Cyclic resistance ratio corrected for magnitude and confining stress""" return crr_m7p5 * ksigma * msf
def power(n, power): """Prints the power""" value = n ** power print("%s to the power of %s is %s" % (n, power, value)) return n, power, value
def divide(a, b): """ >>> divide(10, 2) 5.0 >>> divide(15, 3) 5.0 >>> divide(12, 3) 4.0 """ return a / b try: return float(a) / float(b) except ValueError: return "You can't divide that data type!" except ZeroDivisionError: return "You can't divide by zero!"
def _get_db_value(value): """ Convert value into db value. """ if isinstance(value, str): result = value.encode("UTF-8") elif isinstance(value, int): result = b"%d" % value elif isinstance(value, bytes): result = value else: assert False return result
def map_per_image(label, predictions, k: int = 5): """Computes the precision score of one image. Parameters ---------- label : string The true label of the image predictions : list A list of predicted elements (order does matter, k predictions allowed per image) k : int...
def extractImports(src): """ Extract the set of import statements in the given source code. We return a set object containing the import statements in the given source code. """ imports = set() for line in src.split("\n"): if line.startswith("import"): imports.add(li...
def respond_to(key=None): """ training sentences which the agent should have knowledge about """ respond = { "FACEBOOK_WELCOME": ['Greetings !, I am a weather robot glad to help you to find the forecast'], "NOT_FOUND": ["Sorry, I can't reach out this city !"], "GET_STARTED": ["Ho...
def make_dummy_notebook_name(fig_no): """ convert 1.11 to fig_1_11.ipynb """ return f"fig_{fig_no.replace('.','_')}.ipynb"
def get_scales(acc, scale): """Returns the item scales required to get the accumulator value given the global scale""" res = [] i = scale while acc > 0: if acc & 1: res.append(i) acc >>= 1 i -= 1 return res
def get_character_interactions(links, main_ch): """ Gets the interactions of all characters with the main character :param links: List of all links in the network :param main_ch: The assumes main character name :return: Dictionary of all characters and their interactions with the main character...
def patch_id(options): """Returns the review ID or the GitHub pull request number.""" return options['review_id'] or options['github']
def sequence_accuracy_score(y_true, y_pred): """ Return sequence accuracy score. Match is counted only when the two sequences are equal. :param y_true: true labels :param y_pred: predicted labels :return: sequence accuracy as a fraction of the sample (1 is prefect, 0 is all incorrect) """ ...
def _escape(s): """ Escape HTML characters and return an escaped string. """ s = s.replace('&', '&amp;') s = s.replace('<', '&lt;') s = s.replace('>', '&gt;') return s
def myround(x, base=5, integer=True, round_up=False): """ Round up values - mappable function for pandas processing NOTES: - credit: Alok Singhal """ # round_up=True # Kludge - always set this to True # round to nearest base number rounded = base * round(float(x)/base) if round_up:...
def pos_upper(num, string): """ Returns a string containing its first argument, and its second argument in upper case. :param num: int :param string: str :return: str """ return f'{num}:{string.upper()}'
def get_resource(row): """Get resource from STO query result row.""" resource_split_list = row.split('/') resource = '/'.join(resource_split_list[4:]) return resource
def count_ways(target_value, available_coins, currently_considered=0): """Returns number of ways in which a given `target_value` may be realized with the use of an infinite number of `available_coins` of given values.""" # If target == 0, then there is only one valid solution # (use 0 of each of the ava...
def set_line_style(color, width=3, line_style="solid"): """ Defines default styling of scatter graphs with some smoothing. Args: color: line_style: Returns: line_style dict parameters """ style = dict( color=color, width=width, # shape='spline', ...
def _digest_buffer(buf): """Debug function for showing buffers""" if not isinstance(buf, str): return ''.join(["\\x%02x" % c for c in buf]) return ''.join(["\\x%02x" % ord(c) for c in buf])
def _extract_values_json(obj, key): """Pull all values of specified key from nested JSON.""" arr = [] def extract(obj, arr, key): """Recursively search for values of key in JSON tree.""" if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, ...
def rgb(red, green, blue): """ Return the string HTML representation of the color in 'rgb(red, blue, green)' format. :param red: 0 <= int <= 255 :param green: 0 <= int <= 255 :param blue: 0 <= int <= 255 :return: str """ assert isinstance(red, int) assert 0 <= red < 256 ...
def make_passwd_line(claims): """Create an entry for /etc/passwd based on our claims. Returns a newline-terminated string. """ uname = claims["uid"] uid = claims["uidNumber"] pwline = "{}:x:{}:{}::/home/{}:/bin/bash\n".format(uname, uid, uid, uname) return pwline
def FormatLogMessage(msg,context,level): """ Generic log message formatter. This is a crude initial attempt: I'm sure we could do much better. msg - is message to be logged context - is a string describing the source of the message (can be used for filtering) level - indica...
def rgb_to_hsv(r, g, b): """ Convert a color from rgb space to hsv :param r: red composant of rgb color :param g: green composant of rgb color :param b: blue composant of rgb color :return: h, s, v composants """ maxc = max(r, g, b) minc = min(r, g, b) v = m...
def do_something(a, b, c=None): """Do something. """ return a + b if c else 0
def expandPrefix(prefix): """Expand prefix string by adding a trailing period if needed. expandPrefix(p) should be used instead of p+'.' in most contexts. """ if prefix and not prefix.endswith('.'): return prefix + '.' return prefix
def IsNumeric(value): """ * Determine if string is numeric. """ if not isinstance(value, str): raise Exception('value must be a string.') try: valtxt = value value = int(valtxt) value = float(valtxt) return True except: return False
def convert_to_binary(decimal) -> str: """ Converts Decimal numbers into Binanry Digits """ binary = bin(decimal).replace("0b", "") return binary
def clip_black_by_channels(color, threshold): """Replace any individual r, g, or b value less than threshold with 0. color: an (r, g, b) tuple threshold: a float """ r, g, b = color if r < threshold: r = 0 if g < threshold: g = 0 if b < threshold: b = 0 return (r, g, b)
def isproductofsmallprimes(num): """ CLFFT only supports array sizes which are products of primes <= 13; Is this integer a product of primes no greater than that? """ tmp = num*1 # make copy small_primes = [2,3,5,7,9,11,13] for p in small_primes: quotient, remainder = divmod(tmp, p) ...
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start/<start><br/>" f"/api/v1.0/start/<start>/end/<end>" )
def w_fct(stim, color_control): """function for word_task, to modulate strength of word reading based on 1-strength of color_naming ControlSignal""" # print('stim: ', stim) # print("Color control: ", color_control) return stim * (1 - color_control)
def is_command(meth): """ Return True if method is an exposed Lua command """ return getattr(meth, '_is_command', False)
def IsHash(git_hash): """Returns True iff git_hash is a full SHA-1 hash. Commits keyed by full git hashes are guaranteed to not change. It's unsafe to cache things that can change (e.g. `HEAD`, `master`, tag names) """ return git_hash.isalnum() and len(git_hash) == 40
def str_to_nat(s): """Convert string to natural number.""" return ord(s) - ord("a")
def display_value(value: float, thousands_separator: str = ',', decimal_separator: str = '.') -> str: """ Display a value as a string with specific format. Parameters ---------- value : float Value to display. thousands_separator : str The separator used to separate thousands. ...
def parse_url(url: str) -> str: """ Makes sure the URL starts with 'http://' """ # Replace HTTPS with HTTP (if exists) url = url.replace("https://", "http://") if url.startswith("http://"): return url return f"http://{url}"
def date(string): """Strip off the T from the datetime string""" return string.replace('T', ' ')
def split1d(Astart,Aend,Bstart,Bend): """For a 1-d pair of lines A and B: given start and end locations, produce new set of points for A, split by B. For example: split1d(1,9,3,5) splits the line from 1 to 9 into 3 pieces, 1 to 3 3 to 5 and 5 to 9 it returns these three ...
def format_card(note: str) -> str: """Formats a single org-mode note as an HTML card.""" lines = note.split('\n') if lines[0].startswith('* '): card_front = '<br />{}<br />'.format(lines[0][2:]) else: print('Received an incorrectly formatted note: {}'.format(note)) return '' ...
def os_ls(thepath="."): """Displays the content of the given directory. Default value is the current directory. Examples: >>> os_ls()\n ['temp.py', 'worksheet.py'] >>> os_ls('../..')\n ['ps1_files', 'sec_ops', 'pyplay', 'bashplay'] """ import os return os.listdir(...
def obter_pos_l(pos): """ obter_pos_l: posicao -> str Recebe uma posicao e devolve a componente linha da posicao. """ return pos['l']
def get_available_directions(character: dict, columns: int, rows: int) -> list: """ Get the list of available directions. :param character: a dictionary :param columns: an integer :param rows: an integer :precondition: character must be a dictionary :precondition: columns >= 0 :precondi...
def count_words(my_string): """ This function counts words :param my_string: str - A string of words or characters :return: int - length of words """ if not isinstance(my_string, str): raise TypeError("only accepts strings") special_characters = ['-', '+', '\n'] for character i...
def remove_leading_trailing_pipe(line): """ Remove optional leading and trailing pipe """ return line.strip('|')
def cookable_recipes(ings, recipes): """ # Takes in a list of ingredients and a dictionary # of recipes. Returns the recipes that are able to be # made. A recipe can be made if all the components # are in the ingredients list. >>> rec = {'Egg Fried Rice': ['egg', 'rice', 'msg'], \ 'Spag...
def _str_to_bool(s): """Convert either of the strings 'True' or 'False' to their Boolean equivalent""" if s == 'True': return True elif s == 'False': return False else: raise ValueError("Please specify either True or False")
def parse_int(val, name): """Parse a number to an integer if possible""" if val is None: return val try: return int(val) except ValueError: raise ValueError( f"Please provide a number for {name}, instead of {val}" )
def check_bit(val, offs): """Test bit at offset 'offs' in value.""" return True if val & (1 << offs) else False
def get_vector(vector, vulnerability): """Get a vector out of the CVSS definition (if present) for a vulnerability.""" vectors = [] # Some sources have metadata as { metadata: NVD: CVSSv3: Vectors: "..." } # and others have { metadata: CVSSv2: "..." } if 'metadata' in vulnerability: if 'NV...
def get_tag_list(itera): """ Multiple items has the name as a tag value, this includes directors and genres, this function creates a horizontal string list of the tag attribute from all objects in a list :param itera: iterable containing elements with a tag attribute :return: horizontal string...
def ping(): """Pinging back and example of function with types documented in the docstring. `PEP 484`_ type annotations are supported. If attribute, parameter, and return types are annotated according to `PEP 484`_, they do not need to be included in the docstring: Args: param1 (int): The f...
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/<start><br/>" f"/api/v1.0/<start>/<end><br/>" )
def validate_line(line): """ Validates ``line``. """ # if not VALID_PATTERN.match(line): # raise MalformedPacket("Got malformed packet: {}".format(line)) return True
def add_filters(input, output): """ This function is designed to filter output when using include, exclude, etc. :param input: Raw output string :param output: Raw output from command :return: Filtered string """ if "|" in input: newout = "" incmd = input.split("|")[1].st...
def format_node(cluster_name, node): """Formats a string representation of a node.""" return '<{0}[{1}]>'.format(cluster_name, node)
def _get_matched_row(rows, lookup): """ Return row that matches lookup fields. """ for index, row in enumerate(rows): matched = True for field, value in lookup.items(): if str(row.get(field, '')).strip() != value: matched = False break ...
def format_title(artist: str, title: str) -> str: """Removes artist name if "Genius" is in the artist name Args: artist (str): item artist. title (str): item title/name. Returns: str: formatted title. """ if "Genius" in artist: final_title = title else: ...
def get_null_value(value): """Gets None from null token""" if value.lower().strip(' ') == "null": return None else: return value
def transform_databases(values): """Transform the output of databases to something more manageable. :param list values: The list of values from `SHOW DATABASES` :rtype: dict """ output = {} for row in values: if row['name'] not in output: output[row['name']] = {} fo...
def str_to_list(str, def_val=[]): """ try to return a list of some sort """ ret_val = def_val try: ret_val = str.split(",") finally: try: if ret_val is None: ret_val = [str] except: pass return ret_val
def fname_remove_invalid_chars(fname: str, symbol='-') -> str: """ Takes a file name with potentially invalid characters, and substitutes the symbol in, in place of those invalid characters. Arguments: fname: str (name of file) symbol: str (symbol to substitute invalid characters to) ...
def listget(lst, ind, default=None): """ Returns `lst[ind]` if it exists, `default` otherwise. >>> listget(['a'], 0) 'a' >>> listget(['a'], 1) >>> listget(['a'], 1, 'b') 'b' """ if len(lst)-1 < ind: return default return lst[ind]
def _fix_axis_dim_pairs(pairs, name): """Helper function to make `pairs` a list if needed.""" if isinstance(pairs[0], int): pairs = [pairs] for pair in pairs: if len(pair) != 2: raise ValueError( '{} must consist of axis-value pairs, but found {}'.format( name, pair)) retur...
def package_in_installed(new_package, installed): """ Searches for new_package in the installed tree, returns error message (or empty string) (checks the root of the tree and walks the installed tree) """ conflict = "" if 'dependencies' in installed: previous = installed['dependencies'] ...
def search_st(ingroup: list, potential_rank: list, potential_group: list, subtrees): """ given the membership of the partition dictated by a snp, what subtree has that membership Parameters ---------- ingroup : list Itemized list of leaf members that either all have the ref ...
def _nested_splitchars(x, encoding): """Replace each string in a nested list with a list of char substrings.""" if isinstance(x, list): return [_nested_splitchars(v, encoding) for v in x] else: b = x.encode("utf-32-be") chars = zip(b[::4], b[1::4], b[2::4], b[3::4]) if str is bytes: return [...
def find_in_path(filenames): """Find file on system path.""" # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224 from os.path import exists, join, abspath from os import pathsep, environ search_path = environ["PATH"] paths = search_path.split(pathsep) for path in paths: f...
def timeToTuple(duration): """Converts time float to tuple Args: duration (float): converts duration to a tuple Returns: tuple: Duration split into hours, minutes, and seconds """ hours, rem = divmod(duration, 3600) minutes, rem2 = divmod(rem, 60) seconds, mseconds = div...
def format_commands_help(cmds): """ Helps format plugin commands for display. """ longest_cmd_name = max(cmds.keys(), key=len) help_string = "" for cmd in sorted(cmds.keys()): # For the top-level entry point, `cmds` is a single-level # dictionary with `short_help` as the values....
def generate_results_file_name(world_folder): """ Generate a filename to output results to, with no file extension. """ name = world_folder if world_folder[:9] == "tw_games/": if world_folder[-1:] == "/": name = world_folder[9:-1] else: name = world_folder[9:] els...
def get_mr_title(commit_prefix, source_branch): """Gets the title of the MR. If a prefix exists we add it to the URL. By default we add a prefix of WIP, so the MR doesn't get merged by accident. Args: commit_prefix (str): Prefix for the MR title i.e. WIP. source_branch (str): The source bra...
def edit_form_link(link_text='Submit edits'): """Return HTML for link to form for edits""" return f'<a href="https://docs.google.com/forms/d/e/1FAIpQLScw8EUGIOtUj994IYEM1W7PfBGV0anXjEmz_YKiKJc4fm-tTg/viewform">{link_text}</a>'
def _is_clustal_seq_line(line): """Returns True if line starts with a non-blank character but not 'CLUSTAL' Useful for filtering other lines out of the file. """ return line and (not line[0].isspace()) and\ (not line.startswith('CLUSTAL')) and (not line.startswith('MUSCLE'))
def point_in_polygon(point, polygon): """ Determines whether a [x,y] point is strictly inside a convex polygon defined as an ordered list of [x,y] points. :param point: the point to check :param polygon: the polygon :return: True if point is inside polygon, False otherwise """ x = point...
def extract_from_dictionary(ls_of_dictionaries, key_name): """ Iterates through a list of dictionaries and, based on the inserted key name, extracts that data. :param: ls_of_dictionaries: a list of dictionaries :param: key_name: a string with ('') that indexes which set of the dictionary you want to ex...
def height_human(float_inches): """Takes float inches and converts to human height in ft/inches""" feet = int(round(float_inches / 12, 2)) # round down inches_left = round(float_inches - feet * 12) result = f"{feet} foot, {inches_left} inches" return result
def iou(box_a, box_b, norm): """Apply intersection-over-union overlap between box_a and box_b """ xmin_a = min(box_a[0], box_a[2]) ymin_a = min(box_a[1], box_a[3]) xmax_a = max(box_a[0], box_a[2]) ymax_a = max(box_a[1], box_a[3]) xmin_b = min(box_b[0], box_b[2]) ymin_b = min(box_b[1], b...
def get_tex_label(fs): """Makes labels look nice. Parameters ---------- fs : string An annihilation final state for one of the models defined in hazma. Returns ------- label : string The LaTeX string to be used for labeling plots with the final state. """ tex_label ...
def z_score(x, mean, std): """z_score""" return (x - mean) / std
def unique(data): """ in python 3: TypeError: '<' not supported between instances of 'int' and 'str' need to keep the same Type of member in List """ data.sort() l = len(data) - 1 i = 0 while i < l: if (data[i] == data[i + 1]): del data[i] i -= 1 ...
def ned_enu_conversion(eta, nu): """Rotates from north-east-down to east-north-up Args: eta (array) : Drone position and rotation nu (array) : Twitch of the drone - angular and linear velocities Returns: Array: Rotated eta and nu """ # yaw velocity is wrong -> ask aksel why! retur...
def getBasePV(PVArguments): """ Returns the first base PV found in the list of PVArguments. It looks for the first colon starting from the right and then returns the string up until the colon. Takes as input a string or a list of strings. """ if type(PVArguments) != list: PVArguments = ...
def tinyurlFindUrlend( msg, urlstart ): """Finds the ends of URLs (Strips following punctuation)""" m = msg[urlstart:] index = m.find( " " ) if index == -1: index = len(m) while msg[index-1] in ( "?", ".", "!" ): index -= 1 return index + urlstart
def regular_polygon_area(perimeter, apothem): """Returns the area of a regular polygon""" # You have to code here # REMEMBER: Tests first!!! return (1/2) * perimeter * apothem
def bytearray_xor(b1, b2): """ xor 2 bytearray Args: b1 -- bytearray b2 -- bytearray return a bytearray """ result = bytearray() for x, y in zip(b1, b2): result.append(x ^ y) return result
def format_revision(sha): """ Return a shorter git sha """ return sha[:7]