content
stringlengths
42
6.51k
def _dict(value): """ A dictionary """ return isinstance(value, dict)
def filter_Graph(G,filter_set): """ This allows us to apply a set of filters encoded as closures/first-order functions that take a graph as input and return a graph as output. """ graph = G.copy() for f in filter_set: graph = f(graph) return graph
def calculate1dios(s1, s2): """ Calculate intersection over smallest """ res = 0 i_b = max((s1[0], s2[0])) # intersection begin i_e = min((s1[1], s2[1])) # intersection end if i_b < i_e: smallest = min((s1[1] - s1[0], s2[1] - s2[0])) res = (i_e - i_b) / smallest return ...
def make_aggregate(docs, aggregations): """ Given `docs` and `aggregations` return a single document with the aggregations applied. """ new_doc = dict(docs[0]) for keyname, aggregation_function in aggregations: new_doc[keyname] = aggregation_function(docs) return new_doc
def leap_year(year, calendar='standard'): """Determine if year is a leap year""" leap = False if ((calendar in ['standard', 'gregorian', 'proleptic_gregorian', 'julian']) and (year % 4 == 0)): leap = True if ((calendar == 'proleptic_gregorian') and ...
def str_to_seconds(tstring): """ Convert time strings to seconds. Strings can be of the form: <int> (ninutes) <int>m (minutes) <int>h (hours) <int>d (days) <int>y (years) Args: tstring (str): An integer followed by an (optional) '...
def parse_mac_address(mac_address): """ This function parses raw SNMP MAC address into pretty hexadecimal format. Positional Argument: - mac_address -- SNMP raw MAC address string Returns: - mac_address -- string hexadecimal MAC address """ mac_address = ['{:02x}'.format(int(ord(val)))...
def trap_exception(e, f, default=None): """ Call f(), trapping e, default to default (which might be callable) """ try: # pragma: no cover return f() except e: # pragma: no cover if callable(default): return default(e) else: return default
def BLACK(obj): """Format an object into string of black color in console. Args: obj: the object to be formatted. Returns: None """ return '\x1b[1;30m' + str(obj) + '\x1b[0m'
def shutdown(application): """Invoke to shutdown the InfluxDB collector, writing any pending measurements to InfluxDB before stopping. :param tornado.web.Application application: the application to install the collector into. :rtype: tornado.concurrent.TracebackFuture or None """ colle...
def escape_regex(p, white=''): # type: (str, str) -> str """Escape string for use within a regular expression.""" # what's up with re.escape? that code must be neglected or something return ''.join(c if c.isalnum() or c in white else ('\\000' if c == '\000' else '\\' + c) ...
def generate_list(name): """ Make sure parameters xmltodict generates is a list. :param name: The dict/list that xmltodict gives :return: Guaranteed a list :rtype: list """ if not name: return [] elif isinstance(name, list): return name else: return [name]
def move_up(loc): """increments the location for upward movement. """ return (loc[0], loc[1] + 1)
def is_number(s): """ Test whether a given string can be parsed as a float """ try: float(s) return True except ValueError: return False
def diviseur(n): """ premier diviseur premier de n """ i = 2 while i * i <= n: q, r = divmod(n, i) if r == 0: return i i += 1 return n
def first(seq): """Returns the first item in the sequence. Returns None if the sequence is empty.""" return next(iter(seq), None)
def _format_host_port_alias(host, port, alias): """Format a host, port, and alias so it can be used for comparison or display.""" if alias: return f"{alias}@{host}:{port}" return f"{host}:{port}"
def predicted_rb_number(modelA, modelB): """ Prediction of RB number based on estimated (A) and target (B) models """ #TEMPORARILY disabled b/c RB analysis is broken #from ..extras.rb import theory as _rbtheory return -1.0
def fizz_buzz_three( start, end ): """ Returns the fizzbuzz string for a given range using an inner function and a list comprehension. """ def int_to_fizzbuzz(i): """ Output the 'fizzbuzz' string for a single number. """ entry = '' if i%3 == 0: # if i divided by 3 has no rema...
def dd_poly_f(x, c): """Derivative of d_poly_f""" ddf_x = 0 for i in range(2, len(c)): ddf_x += pow(x, i - 2) * c[i] * i * (i - 1) return ddf_x
def onCircle_elements(nelx,nely): """ return a list of the element centroid located on the border of a circle of radius nelx """ list = [] for x in range(nelx): for y in range(nely): if abs(((x-(nelx-1)/2.0)**2+(y-(nely-1)/2.0)**2)**.5 - (nelx-1)/2.0) < .5 : l...
def html_table(list_of_lists): """ Overridden list class which takes a 2-dimensional list of the form [[1,2,3],[4,5,6]], and renders an HTML Table in IPython Notebook. Taken from: http://calebmadrigal.com/display-list-as-table-in-ipython-notebook/ """ html = ["<table>"] for row in list_o...
def threeSum(nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) < 2: return [] nums.sort() triplets = [] for i in range(len(nums) -2): if i > 0 and nums[i] == nums[i-1]: continue target = -nums[i] small = i +1 ...
def list_partial_circuits(circuit): """ List the partial sub-circuits of `circuit`. The "parital circuits" are defined as the slices `circuit[0:n]` for `0 <= n <= len(circuit)`. Parameters ---------- circuit : tuple of operation labels or Circuit The circuit to act upon. Retur...
def getUriName(uri): """Return local name, i.e. last segment of URI.""" return uri.strip("/").split("/")[-1]
def add_zero(number, size): """add_zero.""" out = str(number) for i in range(size - len(out)): out = "0" + out return out
def parselog(loglines, fields): """ Parse a subset of a zeek logfile's contents. Each line's fields are put into a hash with the retrieved field names as the key. Each of those hashed entries are appended to a list of hashed entries. That list is returned to the caller. """ zeekcomm = [] # Hashed communic...
def filter_loan_to_value(loan_to_value_ratio, bank_list): """Filters the bank list by the maximum loan to value ratio. Args: loan_to_value_ratio (float): The applicant's loan to value ratio. bank_list (list of lists): The available bank loans. Returns: A list of qualifying bank loa...
def _find_all_subclasses(cls): """ Recursively find all subclasses """ subclasses = set(cls.__subclasses__()) for sub in cls.__subclasses__(): subclasses = subclasses | _find_all_subclasses(sub) return subclasses
def api_get_manageable_snapshots(*args, **kwargs): """Replacement for cinder.volume.api.API.get_manageable_snapshots.""" snap_id = 'ffffffff-0000-ffff-0000-ffffffffffff' snaps = [ {'reference': {'source-name': 'snapshot-%s' % snap_id}, 'size': 4, 'extra_info': 'qos_setting:high', ...
def filepath_exist_cmd(path): """Checks if filepath exists.""" return " ".join(["test", "-e", path])
def fibonacci(n: int) -> int: """ The Fibonacci sequence is a list of numbers where the subsequent number is the sum of the previous two. :param n: The number of items requested for the Fibonacci sequence. :return: The Fibonacci number at position n """ if n <= 0: raise ValueError("The n...
def getFibonacciIterative(n: int) -> int: """ Calculate the fibonacci number at position n iteratively """ a = 0 b = 1 for i in range(n): a, b = b, a + b return a
def table_drop(name: str) -> str: """Return command to drop a table from a PostgreSQL database. :param str name: name of table to drop :returns: command to remove table from database :rtype: str """ return 'DROP TABLE if EXISTS {name} CASCADE;'.format(name=name)
def getLetterGrade(score): """ Method to return the letter grade schollar of a student. :param score: A integer with the final grade schollar of a student. :return: return the final letter grade schollar. """ if score >= 90: finalScore = 'A' elif score >= 80: finalSc...
def get_unspecified_default_args(user_args, user_kwargs, all_param_names, all_default_values): """ Determine which default values are used in a call, given args and kwargs that are passed in. :param user_args: list of arguments passed in by the user :param user_kwargs: dictionary of kwargs passed in by...
def tamper(payload, **kwargs): """ Escapes a char encoded payload Tested against: * This is just a proof of concept but used for SQL injection against MySQL 5.7.25 via a GraphQL query Notes: * Useful when passing a char unicode encoded payload as part of the GraphQL query as ...
def change_possible(part): """Check if there is anything to permute""" if ':' not in part or (part.count(':') == 1 and ('http:' in part or 'https:' in part)): return False else: return True
def version_tuple_to_str(version, sep='.'): """Join the version components using '.' and return the string.""" return sep.join([str(x) for x in version])
def fix_msg(msg, name): """Return msg with name inserted in square brackets""" b1 = msg.index('[')+1 b2 = msg.index(']') return msg[:b1] + name + msg[b2:]
def get_dotted(data, path): """access nested dict by dotted helper""" parts = path.split('.') if len(parts) == 1: return data.get(parts[0]) if (parts[0] in data) and isinstance(data[parts[0]], dict): return get_dotted(data[parts[0]], '.'.join(parts[1:])) return None
def icv(p): """Returns interval-class vector of pcset.""" l = [] c = 1 n = len(p) while c < n: for x in p: for y in range(c, n): k = (x-p[y])%12 if k > 6: k = 12 - k l.append(k) c += 1 return [l....
def quadratic(mu, c, i0=1.0): """ Calculates the intensity of a given cell in the stellar surface using a quadratic limb-darkening law. Parameters ---------- mu (``float`` or ``numpy.ndarray``): Cosine of the angle between a line normal to the stellar surface and the line of sig...
def power(base, exp): """ Write a program to find x to power y using recursion :param base: :param exp: :return: """ if exp == 0: return 1 if exp != 0: return base * power(base, exp - 1)
def __get_pivots(diameter, x, y): """ Get the x-intercepts and y-intercepts of the circle and return a list of pivots which the coin lies on. """ pivots = [] radius = diameter / 2 sqval = radius**2 - y**2 if sqval > 0: # no imaginary numbers! sqrt = sqval**(0.5) piv...
def get_args_tuple(args, kwargs, arg_names, kwargs_defaults): """Generates a cache key from the passed in arguments.""" args_list = list(args) args_len = len(args) all_args_len = len(arg_names) try: while args_len < all_args_len: arg_name = arg_names[args_len] if arg_...
def cpu_profile(func, repetitions=1): """Profile the function `func`. """ import cProfile import pstats profile = cProfile.Profile() profile.enable() success = True for _ in range(repetitions): success = func() if not success: break profile.disable() #...
def time_handling(year1, year1_model, year2, year2_model): """ This function is responsible for finding the correct files for the needed timespan: year1 - the start year in files year1_model - the needed start year of data year2 - the last year in files year2_model - the needed last year o...
def get_key_and_value_by_key_match(key_value_map, key_to_try, default_key="any"): """ This method looks for a key in a dictionary. If it is not found, an approximate key is selected by checking if the keys match with the end of the wanted key_to_try. The method is intended for use where the key is a relativ...
def seqhasattr( z, attr ): """like hasattr, but on sequences checks all their elements.""" if hasattr( z, '__iter__') and not hasattr( z, '__cdms_internals__'): return all([ seqhasattr( w, attr ) for w in z ]) else: return hasattr( z, attr )
def _int_to_rgba(omero_val): """ Helper function returning the color as an Integer in RGBA encoding """ if omero_val < 0: omero_val = omero_val + (2**32) r = omero_val >> 24 g = omero_val - (r << 24) >> 16 b = omero_val - (r << 24) - (g << 16) >> 8 a = omero_val - (r << 24) - (g << 16) -...
def _clean_identifier(arg): """ Our class property names have an appended underscore when they clash with Python names. This will strip off any trailing underscores, ready for serialisation. :type arg: str :rtype: str >>> _clean_identifier('id_') 'id' >>> _clean_identifier('id') '...
def html_escape(text: str) -> str: """ Return the text with all HTML characters escaped. """ for character, html_code in [('&', '&amp;'), ('"', '&quot;'), ("'", '&#39;'), (">", '&gt;'), ("<", '&lt;')]: text = text.replace(character, html_code) return text
def char_count( text, ignore_spaces=True): """ Function to return total character counts in a text, pass the following parameter `ignore_spaces = False` to ignore whitespaces """ if ignore_spaces: text = text.replace(" ", "") return len(text)
def is_completions_display_value(x): """Enumerated values of ``$COMPLETIONS_DISPLAY``""" return x in {"none", "single", "multi"}
def _axes_to_sum(child, parent): """Find the indexes of axes that should be summed in `child` to get `parent`""" return tuple(child.index(i) for i in child if i not in parent)
def get_human_ccy_mask(ccy): """Function that convert exchange to human-readable format""" # {"ccy":"USD","base_ccy":"UAH","buy":"24.70000","sale":"25.05000"} return "{} / {} : {} / {}".format(ccy["ccy"], ccy["base_ccy"], ccy["buy"], ccy["sale"])
def gf_degree(f): """Returns leading degree of f. """ return len(f)-1
def kv(d): """ Pretty Print the dictionary. """ return '(' + ','.join(['%s: %s'%(k, d[k]) for k in sorted(d.keys()) if k[0] != "_"]) + ')'
def seek_for_mark(x, y, marks, w, h): """ Seek for a mark existence in a WxH neighbourhood around (x,y) coordinate """ for mark in marks: x_range = range(x - int(w/2), x + int(w/2)+1) y_range = range(y - int(h/2), y + int(h/2)+1) for yy in y_range: for xx in x_range: ...
def set_equal(one, two): """Converts inputs to sets, tests for equality.""" return set(one) == set(two)
def isFileGzip(fileName): """ Inputs a file name and returns a boolean of if the input file is gzipped """ if fileName[-3:] == ".gz": return True else: return False
def get_apps_hr(app_detail): """ Prepare human readable json for command 'risksense-get-apps' command. :param app_detail: response from host command. :return: None """ return { 'ID': app_detail.get('id', ''), 'Address': app_detail.get('uri', ''), 'Name': app_detail.get('...
def getLowerUpperSab(temp): """ gets moderator S(a,b) data bounding library strings from a temperature """ baselib = 'gre7' # endf7 graphite if temp < 600.: raise Exception('temp not implemented. ask gavin') temps = [600.,700.,800.,1000.,1200.,1600.,2000.] libnames =['12t','16t','18t','...
def sort_dict_name_by_number(part): """this is the sort function used for sorting the names within a group""" count = 0 for character in part['NAME']: if character.isdigit(): count += 1 if count == 0: return 0 else: return int(''.join(character for character ...
def makeaxisdivs(start, finish, divs, rounded=-1): """ Creates an axis, or vector, from 'start' to 'finish' with 'divs' divisions. :type start: float :param start: First value of the axis. :type finish: float :param finish: Last value of the axis. :type divs: int ...
def measure_memory_deterministic(shots, hex_counts=True): """Measure test circuits reference memory.""" targets = [] if hex_counts: # Measure |00> state targets.append(shots * ['0x0']) # Measure |01> state targets.append(shots * ['0x1']) # Measure |10> state t...
def _read_formula(Line): """ Helper function for output2acceptingstates(..) """ formula = str(Line.split(":")[1].strip()) return formula # minimization is very expensive if formula in ["FALSE","TRUE"]: return formula formula = PyBoolNet.BooleanLogic.minimize_espresso(formula...
def get_snapshots_list(response, is_aurora): """ Simplifies list of snapshots by retaining snapshot name and creation time only :param response: dict Output from describe_db_snapshots or describe_db_cluster_snapshots :param is_aurora: bool True if output if from describe_db_cluster_snapshots, False othe...
def get_protocol(protocol): """Return the protocol (tcp or udp).""" if str(protocol).lower() == 'tcp': return 'tcp' if str(protocol).lower() == 'http': return 'tcp' if str(protocol).lower() == 'udp': return 'udp' else: return None
def _check_trip_stack_has_tripleg(temp_trip_stack): """ Check if a trip has at least 1 tripleg. Parameters ---------- temp_trip_stack : list list of dictionary like elements (either pandas series or python dictionary). Contains all elements that will be aggregated into a trip R...
def tertiary_spherical(rho, phi): """Zernike tertiary spherical.""" return 70 * rho**8 - 140 * rho**6 + 90 * rho**4 - 20 * rho**2 + 1
def create_idea(idea_str): """ Given a string, returns a dictionary entry. Arguments: idea_str: A string, representing the idea the user has. Returns: idea_dict: {"text": idea_str} """ return {"text": idea_str}
def bytetohex(bytearray): """ Returns hexadecimal string representation of byte array Copied from StackOverflow https://stackoverflow.com/questions/19210414/byte-array-to-hex-string """ return ''.join('{:02x}'.format(x) for x in bytearray)
def pretty_size_print(num_bytes): """ Output number of bytes in a human readable format Parameters ---------- num_bytes: int number of bytes to convert returns ------- output: str string representation of the size with appropriate unit scale """ if num_bytes is ...
def middle(l): """ Return a new list containing all but first and last element of a given list. """ new_l = l[:] del new_l[::len(new_l)-1] return new_l
def find_between(s: str, before: str, after: str): """Searches string S and finds the first substring found between the BEFORE and AFTER substrings, if they are found. Returns the indexes of the start and end of the found substring, such that s[start:end] would be the substring. (first character, last character +...
def _has_project(link: str) -> bool: """HELPER: check if the link in oracc, and has a project :param link: an oracc project link :type link: str :return: true if the link is in oracc with project, false otherwise :rtype: bool """ return ("oracc.org" in link.lower() or "oracc.museum.upenn.e...
def bubble_sort(unsorted_list): """Iterate through an unsorted list and swap elements accordingly.""" # make a copy of the list unsorted_copy = unsorted_list[:] for index in range(len(unsorted_list) - 1): if unsorted_copy[index] > unsorted_copy[index + 1]: a, b = unsorted_copy[inde...
def build_word_list(in_file): """Processes a list of words stored in file, placing them in a list of lists where the outer list index is the number of characters in each word of the corresponding inner list file -> str set list """ word_list = list() for word in in_file: word = word....
def get_overlap(a, b): """ Computes the amount of overlap between two intervals. Returns 0 if there is no overlap. The function treats the start and ends of each interval as inclusive, meaning that if a = b = [10, 20], the overlap reported would be 11, not 10. Args: a: Fi...
def is_pow_two(val: int) -> bool: """ Test if input integer is power of two by summing the bits in its binary expansion and testing for 1. :param val: Input value :type val: int :return: Indicate whether x is a power-of-two. :rtype: bool """ return val > 0 and not (val & (val - 1))
def _normalize_function_name(function): """ Given a C++ function name, convert it to a nicely formatted Python function name. For example "SetPositions" becomes "set_positions". """ name = function[0].lower() for i,l in enumerate(function[1:]): if l.isupper(): name += '...
def transpose(m): """ >>> transpose([[1, 2, 3], [4, 5, 6]]) [[1, 4], [2, 5], [3, 6]] """ return [list(i) for i in zip(*m)]
def format_size(num): """http://stackoverflow.com/a/1094933 """ for x in ['bytes', 'KB', 'MB', 'GB']: if num < 1024.0 and num > -1024.0: return "%3.1f%s" % (num, x) num /= 1024.0 return "%3.1f%s" % (num, 'TB')
def parsePos(text): """ parse a string of format chr:start-end:strand and return a 4-tuple Strand defaults to + and end defaults to start+23 """ if text!=None and len(text)!=0 and text!="?": fields = text.split(":") if len(fields)==2: chrom, posRange = fields stra...
def flipcoords(xcoord, ycoord, axis): """ Flip the coordinates over a specific axis, to a different quadrant :type xcoord: integer :param xcoord: The x coordinate to flip :type ycoord: integer :param ycoord: The y coordinate to flip :type axis: string :param axis: The axis...
def toSigned32(n): """https://stackoverflow.com/a/37095855""" n = n & 0xffffffff return (n ^ 0x80000000) - 0x80000000
def gss(f, a, b, c, tau=1e-3): """ Python recursive version of Golden Section Search algorithm tau is the tolerance for the minimal value of function f b is any number between the interval a and c """ goldenRatio = (1 + 5 ** 0.5) / 2 if c - b > b - a: x = b + (2 - goldenRatio) * (c...
def is_numeric(s): """test if a string is numeric""" for c in s: if c in "1234567890-.": return True else: return False
def get_title(event: dict): """Returns the title for the event.""" context = event.get("context", {}) if ( event["event_source"] == "server" and isinstance(context, dict) and context.get("path", {}) == event["event_type"] ): return "ServerEventModel" # The title of b...
def m3sectoCFM(Vm3sec): """ Convertie le debit volumique en m3/sec vers CFM Conversion: 1 m3/sec = 2 118.88 [CFM] :param Vm3sec: Debit volumique [m3/sec] :return VCFM: Debit volumique [CFM] """ VCFM = Vm3sec * 2118.8799727597 return VCFM
def generate_role_with_colon_format(content, defined_role, generated_role): """Generate role data with input as Compute:ComputeA In Compute:ComputeA, the defined role 'Compute' can be added to roles_data.yaml by changing the name to 'ComputeA'. This allows duplicating the defined roles so that hardware...
def parse_known_rooms(rooms): """ Parse a known rooms string (token:room@conf.host:nick [...]) to a Python dictionary Keys are tokens, values are nested dicts of room JIDs and associated user nicks :param: rooms string :return: dict """ known_rooms = {} for pairs in rooms.split(' '): ...
def adj_dict_to_lists(xs, ys, d): """Convert a dictionary of x -> y to a list of lists, where each x corresponds to a list of indices of y.""" M = [] for x, y_list in d.items(): M.append( [ list(ys).index(y) for y in y_list ] ) return M
def isfloat(x): """ determine if a string can be converted to float """ try: a = float(x) except ValueError: return False except TypeError: return False else: return True
def format_args(args, kwargs, arg_names, ignore=set()): """Format args Args: args (tuple): kwargs (dict): arg_names (List[str]): Returns: str: """ def items(): for i, name in enumerate(arg_names): if name in ignore: continue ...
def requestParser(requestStr): """ accept request string, return dictionary returning None indicates parsing error """ requestStr = requestStr.strip() #According to the RFC, the body starts after a \r\n\r\n sequence headerBodySplit = requestStr.split("\r\n\r\n".encode(), 1) reqlineAndHeaders = headerBod...
def mcd(nums): """MCD: step good for different blocksizes""" res = min(nums) while res > 0: ok = 0 for n in nums: if n % res != 0: break else: ok += 1 if ok == len(nums): break res -= 1 return res if res ...
def get_hq_start_end(seq, is_hq_f): """ ..doctest: >>> def f(c): return c.isupper() >>> get_hq_start_end('', f) (0, 0) >>> get_hq_start_end('GC', f) (0, 2) >>> get_hq_start_end('aGCc', f) (1, 3) """ start, end = 0, 0 i = 0 while i < len(seq): if is_hq_f(seq[i]...