content
stringlengths
42
6.51k
def get_plot_linestyles(n): """ https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/linestyles.html """ linestyle_tuple = [ ('solid', (0, ())), ('dotted', (0, (1, 1))), # Same as (0, (1, 1)) or '.' ('densely dotted', (0, (1, 1))), ('dashed', (0, (5, 5))), ('less ...
def _isArray(val): """ Actually array is list in Python, for now we do not treat tuple as an array type. """ return isinstance(val, list)
def pollen_to_cryptonote(float_amount): """ :param float_amount: Pollen amount :return: CryptoNote integer """ float_string = str(float_amount) power_accumulator = 0 if '.' in float_string: point_index = float_string.index('.') power_accumulator = len(float_string) - point_i...
def getPublicAttributes(obj): """Return a list of public attribute names.""" attrs = [] for attr in dir(obj): if attr.startswith('_'): continue try: getattr(obj, attr) except AttributeError: continue attrs.append(attr) return attrs
def is_isbn_or_key(word): """ Return if the `word` is `isbn` number or `keyword`. :param word: query keywords to get HTTP response :type word: string :return: `isbn` or `key` :rtype: string """ isbn_or_key = 'key' if '-' in word: short_word = word.replace('-', '') e...
def get_error_message(err, def_val=None): """ return error message from an OTP error object {'error': {'msg': 'Origin is within a trivial distance of the destination.', 'id': 409}} """ ret_val = def_val try: ret_val = err.error.msg except: try: ret_val = err['erro...
def getMarkerColor(colorStr): """Given a color ID string returns the RGB tuple from the color ID String.""" if colorStr == 'blue': return (255, 0, 0) elif colorStr == 'red': return (0, 0, 255) elif colorStr == 'green': return (0, 255, 0) elif colorStr == 'cyan': retur...
def perm_octal2str(perm_octal): """Convert octal permission int to permission string Args: perm_octal (int): octal-based file permissions specifier Returns: str: rwx--- type file permission string """ perm_str = "" # add to perm_str starting with LSB and working to MSB whil...
def diff(a, b): """ Return set difference of lists a,b as list """ b = set(b) return [aa for aa in a if aa not in b]
def filter_aws_headers(response): """Removes the amz id, request-id and version-id from the response. This can't be done in filter_headers. """ for key in ["x-amz-id-2", "x-amz-request-id", "x-amz-version-id"]: if key in response["headers"]: response["headers"][key] = [f"mock_{key}"]...
def obs_label(obs, subobs, differentials=False, full_cumulants=False): """ Return a formatted label for the given observable. """ if obs.startswith('d') and obs.endswith('_deta'): return (r'$d{}/d\eta$' if differentials else '${}$').format( {'Nch': r'N_\mathrm{ch}', 'ET': r'E_T'}[ob...
def camelize(src, delim=' '): """ Convert all keys of a dictionary (or list of dictionaries) to CamelCase (with capital first letter) :type src: ``dict`` or ``list`` :param src: The dictionary (or list of dictionaries) to convert the keys for. (required) :type delim: ``str`` ...
def turn_down(value: int) -> int: """ Turn down cells in the given region, i.e. decrease brightness by 1. """ return 0 if value == 0 else value - 1
def parse_requirements_file(filename: str) -> list: """ Parse a Requirements File Into Package Dependency List while ignoring comments (on their own line or after the dependency) and empty lines """ requirements_list = [] try: with open(filename, "r", encoding="utf-8") as text_stream...
def _cleanstr(doc): """Clean up a docstring by removing quotes @param doc: docstring to clean up """ return doc.replace('"', ' ').replace("'", ' ')
def find_changes(vals, threshold=None, change_pct=0.02, max_interval=None): """Returns an array of index values that point at the values in the 'vals' array that represent signficant changes. 'threshold' is the absolute amount that a value must change before being included. If 'threshold' is None, 'c...
def isCloseError(err: IOError) -> bool: """ if (err && !isEmpty(err.message)) { return err.message.indexOf("[-1] write closed") >= 0; } """ # if err is True and return False
def normalize_timestamp(value, ndigits=1): """ Round timestamps to the given number of digits. This helps to make the test suite less sensitive to timing issues caused by multitasking, processor scheduling, etc. """ return '%.2f' % round(float(value), ndigits=ndigits)
def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ #...
def filter(pred, seq): """Keeps elements in seq only if they satisfy pred. >>> filter(lambda x: x % 2 == 0, [1, 2, 3, 4]) [2, 4] """ return [x for x in seq if pred(x)]
def coordinate(latitude, longitude): """Coordinate data model. Parameters ---------- latitude : float Decimal degree coordinate in EPSG:4326 projection. longitude : float Decimal degree coordinate in EPSG:4326 projection. Returns ------- coordinate : dict Coordi...
def apply_projection(document, projection): """ Apply a Mongo-style projection to a document and return it. :param document: the document to project :type document: dict :param projection: the projection to apply :type projection: Union[dict,list] :return: the projected document :rtyp...
def format_inmate_id(inmate_id): """Format FBOP inmate IDs.""" try: inmate_id = int(str(inmate_id).replace("-", "")) except ValueError as exc: raise ValueError("inmate ID must be a number (dashes are okay)") from exc inmate_id = "{:08d}".format(inmate_id) if len(inmate_id) != 8: ...
def unique(scope, source): """ Returns a copy of the given list in which all duplicates are removed such that one of each item remains in the list. :type source: string :param source: A list of strings. :rtype: string :return: The cleaned up list of strings. """ return list(dict([...
def _isMinimumSVNVersion(version, major, minor, patch=0): """Test for minimum SVN version, internal method""" if not version: return False if (version['major'] > major): return True elif (version['major'] < major): return False if (version['minor'] > minor): return True elif (version['mino...
def dice_coefficient2(a, b, case_insens=True): """ :type a: str :type b: str :type case_insens: bool duplicate bigrams in a word should be counted distinctly (per discussion), otherwise 'AA' and 'AAAA' would have a dice coefficient of 1... https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/D...
def thermalConductivity(T, tCP): """ thermalConductivity(T, tCP) thermalConductivity (W/m/K) = A + B*T + C*T^2 Parameters T, temperature in Kelvin tCP, A=tCP[0], B=tCP[1], C=tCP[2] A, B, and C are regression coefficients Returns thermal conductivity in W/m/K at T ...
def tryint(s): """ Function to test whether a str can be rendered as a int. Useful when retreiving experimental parameters that were stored within the filename. Parameters: text (str) Returns: int or text """ try: return int(s) except: return s
def COUNTBLANK(count_list): """Count the blank instances in a list. Parameters ---------- count_list : list or array list or array that will be counted for blanks. Returns ------- numeric or int The total count of blank instances """ if type(count_list) == list: ...
def find_peaks(xs, rs, threshold): """Finds maximal (disjoint) peak regions in a sequence of real numbers. Each value that is at least as large as the threshold constitutes the center of a peak with radius according to its position. In the output all overlapping peaks are merged into maximal peaks. ...
def _match(seq1, seq2, mismatches): """ Test if sequence seq1 and seq2 are sufficiently similar. Parameters ---------- seq1 : str First sequence. seq2 : str Second sequence. mismatches : int Number of allowed mismatches between given sequences. Returns -----...
def last_index(list_, value): """ last_index(list, value) -> integer Analogous to list.index, but returns the last index rather than the first Raises ValueError if the value is not present. """ found = None for index, val in enumerate(list_): if val == value: found = index ...
def validateGroupStructure(struct): """ Validate structure and transform it into a canonical form """ newStruct = {} if not isinstance(struct, dict): raise RuntimeError(f"{struct} is not a dictionary") for key, value in struct.items(): if not isinstance(key, str): rai...
def multiple_inputs_and_outputs(cube_ai, rt_ai, num): """ add input num, default is one input output """ # 1. expand raw input/output cube_ai *= num rt_ai *= num # 2. replace default index(1) with true index for i in range(1, num): cube_ai[2*i] = cube_ai[2*i].replace("1", str(i+1)) ...
def bytes_to_GB(val, decimal=2): """A byte-to-Gigabyte converter, default using binary notation. :param val: X bytes to convert :return: X' GB """ return round(val / (1024 * 1024 * 1024), decimal)
def _is_png(filename): """Determine if a file contains a PNG format image. Args: filename: string, path of the image file. Returns: boolean indicating if the image is a PNG. """ # File list from: # https://github.com/cytsai/ilsvrc-cmyk-image-list return filename.endswith('png')
def PrettifyFrameInfo(frame_indices, functions): """Return a string to represent the frames with functions.""" frames = [] for frame_index, function in zip(frame_indices, functions): frames.append('frame #%s, "%s"' % (frame_index, function.split('(')[0])) return '; '.join(frames)
def is_power_of_two(n): """ Desc: Given a positive integer, write a function to find if it is a power of two or not. Naive solution: In naive solution we just keep dividing the number by two unless the number becomes 1 and every time we do so we check that remainder after division is always 0. ...
def mag_cut(mag, low, high): """ Define a high and low value and flag the values that fall within those boundaries """ isGood = 0 if mag <= high and mag >= low: isGood = 1 return isGood
def to_crs(epsg): """CRS dict from EPSG code.""" return {'init': 'epsg:{}'.format(epsg)}
def merge_clients(first_client: list, second_client: list) -> list: """Receives two clients of the form [L, D, N] and merges them together into one client. It is assumed that they share the same dislikes. Args: first_client (list): A client list in the form of [L, D, 1] where one represents the num...
def x_ian(x, word): """ Given a string x, returns True if all the letters in x are contained in word in the same order as they appear in x. >>> x_ian('srini', 'histrionic') True >>> x_ian('john', 'mahjong') False >>> x_ian('dina', 'dinosaur') True >>> x_ian('pangus', 'angus') ...
def cep_check_message(cep_number: str): """Return cep help message.""" return f"CEP {cep_number} Test Failed! | More info: https://simspace.github.io/cep/ceps/{cep_number}/#requirements"
def _name_add(name): """Add '+' to the front of positive values. Also keeps the '-' in front of negative values. """ name = str(float(name)) if name[0] != '-': name = '+' + name return name
def event_message(iden, event): """Return an event message.""" return {"id": iden, "type": "event", "event": event}
def kwargs_from_keyword(from_kwargs,to_kwargs,keyword,clean_origin=True): """ Looks for keys of the format keyword_value. And return a dictionary with {keyword:value} format Parameters: ----------- from_kwargs : dict Original dictionary to_kwargs : dict Dictionary where the items will be appended key...
def calc_first_number(n: int) -> int: """ Calculate first number in the row :param n: :return: """ return (n * (n - 1)) + 1
def parse_connection_string_libpq(connection_string): """parse a postgresql connection string as defined in http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING""" fields = {} while True: connection_string = connection_string.strip() if not connection_string:...
def get_lst_same_for_dicts(want, have, lst): """ This function generates a list containing values that are common for list in want and list in have dict :param want: dict object to want :param have: dict object to have :param lst: list the comparison on :return: new list object with values w...
def is_url(txt): """Return true if the given string is an URL.""" return txt.startswith('http')
def convert_point_input(string, sep=' '): """converts separated coordinate points, e.g. (1,2) to a list of tuples sep: character separating each set of points""" lst = string.split(sep) for i in range(len(lst)): tup = tuple(lst[i].split(',')) res = float(tup[0][1:]), float(tup[1][:-1]) ...
def singleval(seq, sep=', '): """ Convert an object to a single value. If the object has no length it is returned as-is. If the object is a sequence or set of length 1 the first value is returned. If the object is a sequence or set of length > 1 a string concatenation using `sep` is ret...
def num_shifts_in_stack(params): """Calculate how many time points (shifts) will be used in loss functions. Arguments: params -- dictionary of parameters for experiment Returns: max_shifts_to_stack -- max number of shifts to use in loss functions Side effects: None """ ma...
def string_list_to_hdf5(string_list): """ converts string lists (incl unicode) to h5py-compatible """ return [v.encode("utf8") for v in string_list]
def is_valid_port(port): """Checks a port number to check if it is within the valid range Args: port - int, port number to check Returns: bool, True if the port is within the valid range or False if not """ if not isinstance(port, int): return False return 1024 < port <...
def zero_pad(num, digits): """ for 34, 4 --> '0034' """ str_num = str(num) while (len(str_num) < digits): str_num = '0' + str_num return str_num
def get_edge_score(ref_que_conn_scores): """Return ref_gene: que_genene: score dict.""" ret = {} for edge, scores in ref_que_conn_scores.items(): max_score = max(scores) ret[edge] = max_score return ret
def replaceSymbols(s): """ Strip a string from /, *, (, ), [, ], - and , @param s The string to remove the symbols from """ s = s.replace("/","").replace("*","").replace("(","").replace(")","").replace("[", "_").replace("]","_").replace("-", "_").replace(",", "_") return s
def _auth_type_from_header(header): """ Given a WWW-Authenticate or Proxy-Authenticate header, returns the authentication type to use. We prefer NTLM over Negotiate if the server suppports it. """ if 'ntlm' in header: return 'NTLM' elif 'negotiate' in header: return 'Negotiat...
def flatten_penalties(penalties): """ Flatten a penalty dictionary into a list """ return [penalty for sublist in penalties.values() for penalty in sublist]
def recursively_replace(original, replacements, include_original_keys=False): """Clones an iterable and recursively replaces specific values.""" # If this function would be called recursively, the parameters 'replacements' and 'include_original_keys' would have to be # passed each time. Therefore, a h...
def sf2metadata_record_to_dict(record): """Helper function to convert a record from the sf2metadata table to a dict""" return { "pid": record[5], "st": record[6], "ctp": record[7], "nsl": record[8], "di": record[9], "na": record[10], "hp": record[11], ...
def get_veth_slot_info_cmd(lpar_id, slotnum): """ get virtual ethernet slot information For IVM, vswitch field is not supported. :param lpar_id: LPAR id :param slotnum: veth slot number :returns: A HMC command to get the virtual ethernet adapter information. """ return ("lshwres -r virt...
def generate_sample_fov_tiling_entry(coord, name): """Generates a sample fov entry to put in a sample fovs list for tiling Args: coord (tuple): Defines the starting x and y point for the fov name (str): Defines the name of the fov Returns: dict: ...
def _trim_front(strings): """ Trims zeros and decimal points """ trimmed = strings while len(strings) > 0 and all(x[0] == ' ' for x in trimmed): trimmed = [x[1:] for x in trimmed] return trimmed
def clean_text(text): """Removing spaces and converting the text into lowercase""" return text.strip().lower()
def _is_cmyk(filename): """Determine if file contains a CMYK JPEG format image. Args: filename: string, path of the image file. Returns: boolean indicating if the image is a JPEG encoded with CMYK color space. """ # File list from: # https://github.com/cytsai/ilsvrc-cmyk-image-list...
def fix_filename(filename): """Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg :param filename: :type filename: str :return: :rtype: str """ parts = filename.split('.') ...
def arg(*args, **kwargs): """Utility function used in defining command args.""" return ([*args], kwargs)
def _read_input_sql(input_sql): """ Read SQL input from the command line """ if input_sql: if len(input_sql) > 1: return " ".join(input_sql) else: return input_sql[0] else: return ""
def piff(val, sample_rate, chunk_size): """Return the power array index corresponding to a particular frequency.""" return int(chunk_size * val / sample_rate)
def blank_tiles(input_word): """Searches a string for blank tile characters ("?" and "_"). Args: input_word: the user supplied string to search through Returns: a tuple of: input_word without blanks integer number of blanks (no points) integer number of ...
def partition_by_alliance(elements): """Partition elements into a dict from alliance color to relevant elements.""" d = {} for e in elements: d.setdefault(e.alliance, []).append(e) return d
def by_value(dc: dict, val) -> list: """ Return key from ``dc`` if its value is equal to ``val``. """ return list(dc.keys())[list(dc.values()).index(val)]
def get_full_name(parent, child): """Return full dotted path of a child field.""" return ("".join([parent, ".", child]))
def sanitizeTreeName(name): """sanitizeTreeName(name) takes all the nasty characters out of a newickTree and returns a str that is more amenable to being a file (or directory) name. """ name = name.replace(' ','') name = name.replace(',','') name = name.replace(':','-') name = name.replace('...
def floyd_warshall(adjacency_weight_matrix): """ Finds the shortest path between all pairs of vertecies in a graph with no negative cycles. :param adjacency_weight_matrix: An n*n matrix representing the edge weights in an n-vertex directed graph. AWM[i][j] denotes the egde weight from vertex i to vert...
def fibonacci(n): """Calculates the Fibonacci number. :param n: The input for which the Fibonacci number is calculated. :type n: Integer :return: The Fibonacci number. :rtype: Integer """ if n < 0 or not isinstance(n, int): raise ValueError("%s is not a natural number. Only natural ...
def combine_strings(one: str, two: str) -> str: """Combine strings eliminating duplicate blank lines.""" if len(one) > 2 and one[-2:] == '\n\n' \ and len(two) >= 1 and two[0] == '\n': # String one has a trailing blank line, and string two has a prefixed # blank line. Strip the dupli...
def volume_id_from_cli_create(output): """Scrape the volume id out of the 'volume create' command The cli for Patron automatically routes requests to the volumes service end point. However the patron api low level commands don't redirect to the correct service endpoint, so for volumes commands (eve...
def COSP(N, DATA, TABLE, M, K): """ COSP: compute kth value of either the COSine transform or sine transform. (COSine decomPosition ?) p.61 """ J = 0 C = 0.0 KK = K - 1 MM = M + M - 1 MMM = MM - 1 for I in range(N): # print((I, J, KK, MM)) C += DATA...
def _adjust_for_clashing_subs(combined_subs, working_sub, exclude): """ Helper function for the append code. Looking for overlapping subtitles and make adjustments """ # If we haven't got a set of subs to check against early return if not combined_subs or not exclude: return working_sub, No...
def normalize_typename(typename: str) -> str: """ Drop the namespace from a type name and converts to lower case. e.g. 'tows:parks' -> 'parks' """ normalized = typename if ":" in typename: normalized = typename.split(":")[1] return normalized.lower()
def check_format(board): """ make sure that the board is well-formatted """ try: assert len(board) == 9, "board must have 9 rows, found %d" % len(board) for row in board: assert len(row) == 9, "each row must have 9 numbers" for possible_values in row: ...
def grad_refactor_3(a): """ if_test """ if a > 3: return 0 return 3 * a
def is_non_empty_string(str_): """checks if a string is not an empty string, True if not empty""" return bool(str_ != '')
def partition(array, low, high): """ Returns the index of the sorted pivot (which is the array indexed at the high index), with everything prior in the list being less then pivot and everything after being greater then pivot. """ pivot = array[high] i = low - 1 for j in range(low, high): ...
def build_issue_url(org, repo, number): """Return a url in the form https://github.com/{owner}/{repo}/issues/{number} Args: org: The organization that owns the issue repo: The repo that owns the issue number: The issue number Returns: owner, repo, number """ return f"https://github.com/{org}...
def get_message(course_name, time_not_active): """ Format the message that needs to be send. :param course_name: The name of the course. :type course_name: str :param time_not_active: Time that a student has not been active. :type time_not_active: int :return: Message to be send to users. ...
def get_studies_without_attribute(attribute_name, attribute_dict): """Get identifiers of studies whose metadata lacks the given attribute_name. Parameters ---------- attribute_name : str The name of an attribute to check against attribute_dict in order to identify studies missing/withou...
def request_type(request): """ If the request is for multiple addresses, build a str with separator """ if isinstance(request, list): # If the list is ints convert to string. to_string = ''.join(str(e) for e in request) # Finally build one string of the list. request = ",".join(t...
def analytical_err_simple(X,sigma=0.1): """ Function 'analytical_err_simple' produces a d18O-cellulose record which takes into account measurement precision and errors. Input Arguments: 1. data vector field, final output of sensor and archive model 2. sigma (assumed precisio...
def add_builtin(varlist, builtin, model_name): """ this adds the builtin information to the variables for statistical purposes :param varlist: list of dicts with variables :param builtin: list with builtins :param model_name: str with model name :return: list of dicts with builtin information a...
def create_select_list(l): """ Create a string containing all elements in the list l: '("l[0]", "l[1]", ... , "l[-1]")' Used for conditional selects in Sqlite """ s = '(' for idx, cat in enumerate(l): if idx > 0: if type(cat) is str: s += ",'{0}'".form...
def isascii(s): """Check if the characters in string s are in ASCII, U+0-U+7F.""" return len(s) == len(s.encode())
def is_int(text): """ Return true if s is an integer """ try: int(text) return True except ValueError: return False
def power(x, a, b): """Power model - used in fitting.""" return a*x**b
def parametrized_test_case(cls): """ A decorator that marks the specified TestCase as parametrized. When a class is marked as parametrized, the interpreter searches for methods marked with the @parametrized decorator. For each method that's found as being marked with @parametrized, a stub test met...
def _xbrli_string_item_type_validator(value): """Returns python str if value can be converted""" errors = [] try: value = str(value) except: # if type(value).__name__ not in ["str", "unicode"]: errors.append("'{}' is not a valid string value.".format(value)) return value, erro...
def chunk_str_list(fat_list, max_chars_per_list): """ Splits a string list into multiple lists based on max_chars_per_list for processing over size-limited MT APIs """ text_len = 0 parent_list = [] starting_point = 0 for (index, text) in enumerate(fat_list): text_len += len(text) ...