content
stringlengths
42
6.51k
def Cdf(_input_array, x): """ Compute the CDF value of input samples using left tail computation Attributes: _input_array: list of data points x: current K value Return: value of cdf """ # left tail count = 0.0 for vi in _input_array: if vi <= x: coun...
def _get_component_dropout(dropout_schedule, data_fraction): """Retrieve dropout proportion from schedule when data_fraction proportion of data is seen. This value is obtained by using a piecewise linear function on the dropout schedule. This is a module-internal function called by _get_dropout_proporti...
def getThrusterFiringIntervalAfter(tfIndices, minDuration=10): """Get range of points between first two thruster firings in input Thruster firings tend to cluster, so we don't just want the first pair of firings in the array. Better is the first pair of firings that are separated by a minimum number of...
def _format_time(seconds): """Render the integer number of seconds as a string. Returns a string. """ hours, remainder = divmod(seconds, 3600) minutes, seconds = divmod(remainder, 60) hours = int(hours) minutes = int(minutes) if hours > 0: return "%sh %sm %ss" % (hours, minutes, s...
def parse_config(config: dict) -> dict: """ parses the dictionary so that restructure function can understand it :param config: unparsed raw dictionary of details :return: parsed dictionary of details """ parsed_object = {} for key in config: for template in config[key]: ...
def get_request_string(args, kwargs): """ Given ``args``, ``kwargs`` of original function, returns request string. """ return args[1] if len(args) > 1 else kwargs.get('request_string')
def DropStringPrefix(s, prefix): """If the string starts with this prefix, drops it.""" if s.startswith(prefix): return s[len(prefix):] else: return s
def select_anchors_except_2d(tmp_ips_dict, mode): """ If the selected localization mode is not 2D, anchor selection is done under this module. """ selected_id = list() selected_anchors_dict = dict() anchor_id_list = list(tmp_ips_dict['AnchorID']) x_list = list(tmp_ips_dict['x']) y_l...
def get_sorted_labels(column_label_map): """ Sort labels using their corresponding column names. .. function: get_sorted_labels(column_label_map) :param column_label_map: The column-name-to-label map. :type column_label_map: dict(str, str) :return: The sorted labels. :rtype: lis...
def derivative_from_polycoefficients(coeff, loc): """ Return derivative of a polynomial of the form f(x) = coeff[0] + coeff[1]*x + coeff[2]*x**2 + ... at x = loc """ derivative = 0. for n, c in enumerate(coeff): if n == 0: continue derivative += n*c*loc**(n-...
def show_slave_delays(slaves, args_array): """Method: show_slave_delays Description: Stub holder for mysql_rep_failover.show_slave_delays func. Arguments: (input) slaves (input) args_array """ status = True if slaves and args_array: status = True return statu...
def learning_rate_decay(initial_learning_rate: float, epoch_no: int) -> float: """ param intial_learning_rate: the learning rate in the previous epoch param epoch_no: current epoch_no >>> lr = learning_rate_decay(1, 2) >>> lr 0.0001 """ decay_rate = 0.01 new_learning_rate = initial...
def fib(n): """ This function calculate fib number. Example: >>> fib(10) 55 >>> fib(-1) Traceback (most recent call last): ... ValueError """ if n < 0: raise ValueError('') return 1 if n<=2 else fib(n-1) + fib(n-2)
def lower(message: str) -> str: """Convert alphas in lowercase in the message. Args: message (str): the message to format. Returns: str: the formatted message. """ return message.lower()
def filter_annotation_list(annotation_list, key, value_list, filter=True): """ Returns annotation list filtered to entries where _key_ is in _value_list_ """ if filter: return [x for x in annotation_list if x[key] in value_list] else: return [x for x in annotation_list if x[key] not ...
def _get_dhcpv6_msgtype(msg_index): """Return DHCPv6 message type string. :param msg_index: Index of message type. :return: Message type. :type msg_index: int :rtype msg_str: str """ dhcp6_messages = { 1: "SOLICIT", 2: "ADVERTISE", 3: "REQUEST", 4: "CONFIRM",...
def _get_spliceregion(data): """ This is a plugin for the Ensembl Variant Effect Predictor (VEP) that provides more granular predictions of splicing effects. Three additional terms may be added: # splice_donor_5th_base_variant : variant falls in the 5th base after the splice donor junction (5' end o...
def make_header(text, size=80, symbol="-"): """Unified way to make header message to CLI. :param text: what text to write :param size: Length of header decorative line :param symbol: What symbol to use to create header """ header = symbol * size + "\n" header += "%s\n" % text header += ...
def remove_spaces(string): """ Substitutes spaces for %20 which can be encoded properly in url """ return '%20'.join(string.split(' '))
def Color(red, green, blue): """Convert the provided red, green, blue color to a 24-bit color value. Each color component should be a value 0-255 where 0 is the lowest intensity and 255 is the highest intensity. """ return (red << 16) | (green << 8) | blue
def flatten_list(list_to_flatten): """Flatten a list of lists in one single list. Parameters ---------- list_to_flatten : List of list. To flatten. Returns ------- flatted_list : List. Single list. """ flatted_list = [item for sublist in list_to_flatten for item in sublist] re...
def encode_file_path(s): """Encodes an URL path from internal format for use in disk filenames""" # This doesn't change the string. # But, if we ever change the internal representation of paths, we'll # need to change the 3 functions here that deal with it return s
def check(row): """ Checks for human intervention in a plot """ if row['DSTRBCD1'] == 80.0: return True if row['DSTRBCD2'] == 80.0: return True if row['DSTRBCD3'] == 80.0: return True if row['TRTCD1'] == 10.0: return True if row['TRTCD1'] == 30.0: ...
def not_full_fieldofview(nx, ny, cellsize, fov): """ This has been raised as an interesting test, as if the full field of view (FOV) has not been imaged we may want to image the full dataset. The imaged FOV information can be estimated using the number of pixels and the size of the pixels. :par...
def _flatten_list(l): """ convert multiple remotes of obs (each from multiple envs) to 1 list of obs """ assert isinstance(l, (list, tuple)) assert len(l) > 0 assert all([len(l_) > 0 for l_ in l]) return [l__ for l_ in l for l__ in l_]
def dynamodb_prewrite_empty_str_in_dict_to_null_transform(d: dict) -> dict: """DynamoDB will break if you try to provide an empty string as a String value of a key that is used as an index. It requires you to provide these attributes as None rather than the empty string. It _used_ to break if any attri...
def make_photo_dict(filename, media): """Generate a photo dict (filename, url) as in the ODKA JSON export.""" if filename and filename in media: return dict(filename=filename, url=media[filename]) else: return None
def mac_address_formatter(mac_address): """Formats MAC address into Cisco MAC Address format and returns string""" if '.' not in mac_address: x = mac_address.replace(':', '').replace('-', '') return f'{x[0:4]}.{x[4:8]}.{x[8:12]}' else: return mac_address
def _check_quantiles(quantiles): """Validate quantiles. Parameters ---------- quantiles : str, list, tuple or None Either a string or list/tuple of strings indicating the pandas summary functions ("mean", "min", "max", "median", "sum", "skew", "kurtosis", "var", "std", "mad", "s...
def check_all_columns(A): """ Check if all columns in 2-dimensional matrix don't have more than one queen """ for col_inx in range(len(A)): # compute sum of column col_inx col_sum = 0 for row_inx in range(len(A)): col_sum += A[row_inx][col_inx] if col_sum > 1:...
def ae_level (val=None): """ Set or get auto exposure level """ global _ae_level if val is not None: _ae_level = val return _ae_level
def calculate_compared_width(y_base, poly): """ Calculate the width of each polygon according to the baseline Input y_base: y coordinate of the base line poly: a set of vertices of a polygon Ouput width: the width of a polygon """ width = 0 width_xs = [] for i in ra...
def str_to_color(s): """Convert hex string to color value.""" if len(s) == 3: s = ''.join(c + c for c in s) values = bytes.fromhex(s) # Scale from [0-255] to [0-1] return [c / 255.0 for c in values]
def is_al_num(string): """ Little utility to check if a string contains only letters and numbers (a-z,A-Z,0-9) :param string: The string to be processed :return: Result """ for i in string.lower(): cond = ord('a') <= ord(i) <= ord('z') cond = cond or (ord('0') <= ord(i) <= ord('...
def adapt_cmake_command_to_platform(cmake_command, platform): """ Adapt CMake command to MS Windows platform. """ if platform == 'win32': pos = cmake_command.find('cmake') s = ['set %s &&' % e for e in cmake_command[:pos].split()] s.append(cmake_command[pos:]) return ' '....
def get_api(kind): """Determine the apiVersion for different kinds of resources Args: kind (string): The name of the resource Returns: string: the apiVersion for the matching resource Raises: ValueError: If apiVersion cannot be determined from Kind """ # supported work...
def mock_ssh(host, command): """Avoid network connection.""" return ["/bin/sh", "-c", command]
def userfunc(say='Hi'): """Test func with one parameter.""" return 'SKPAR says {}'.format(say)
def binary_search(items, item): """Return True if items includes the item, otherwise False. Assume the items are in non-decreasing order. Assume item and items are all of the same type. """ first = 0 last = len(items) - 1 while first <= last: # Base case: the item is in the middle. ...
def list2cmdline(seq): """ Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single ...
def xml_safe(s): """Returns the XML-safe version of a given string. """ new_string = s.replace("&", "&amp;").replace("<", "&lt;") new_string = new_string.replace("\r", "").replace("\n", "<br/>") return new_string
def split_checkpoint_step(checkpoint_dir): """Helper function to return the checkpoint index number. Args: checkpoint_dir: Path directory of the checkpoints Returns: checkpoint_id: An int representing the checkpoint index """ checkpoint_name = checkpoint_dir.split('/')[-1] ret...
def video_sort(videos, key, keyType=str, reverse=False): """ Given a list of video records that are dotty dictionaries return back a sorted version that is sorted based on the provided key. The keys will be converted using the given key type during the sort for comparison purposes. This is a very ...
def is_connection_error(error): """Returns true if the error is caused connection issues.""" msg = str(error) return 'Unhealthy connection' in msg or 'No connection exists' in msg
def is_around_angle(test, angle, offset): """ Checks if a test angle is close to the angle or not. Parameters ---------- test : float Angle to test in Degrees. angle : float Angle to compare in Degrees. offset : float Tolerance around 'angle' in degrees. ...
def reverse(s): """return the str that be reversed""" if len(s) == 0: # basic case return "" return reverse(s[1:]) + s[0]
def ip4_hex(arg, delimiter=""): """ Convert an IPv4 address to Hexadecimal notation """ numbers = list(map(int, arg.split("."))) return "{0:02x}{sep}{1:02x}{sep}{2:02x}{sep}{3:02x}".format( *numbers, sep=delimiter )
def token_from_http_body(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this functi...
def megahex_count(radius): """ counts from zero, so megahex radius 1 -> 6 Computes the maximum number on a given level Computation based on the sequence of Hex (or centered hexagonal) numbers: 3*n*(n+1)+1 """ return 3*radius*(radius+1)
def f1_score(real_labels, predicted_labels): """ Information on F1 score - https://en.wikipedia.org/wiki/F1_score :param real_labels: List[int] :param predicted_labels: List[int] :return: float """ assert len(real_labels) == len(predicted_labels) # F1-score = 2 * (precision * recall) / (...
def my_lcs(string, sub): """ Calculates longest common subsequence for a pair of tokenized strings :param string : list of str : tokens from a string split using whitespace :param sub : list of str : shorter string, also split using whitespace :returns: length (list of int): length of the longest common subsequenc...
def interpret_conf_limits(conf, name_prefix, info=None): """ Parses general parms for rate limits looking for things that start with the provided name_prefix within the provided conf and returns lists for both internal use and for /info :param conf: conf dict to parse :param name_prefix: prefix...
def filefrac_to_year_monthday_fracday(filefracday): """ split the name as YYYY, MM,DD, FFFFFF FFFFFF (fraction in the day)""" return filefracday[:4], filefracday[4:6], filefracday[6:8],filefracday[8:]
def get_palette(num_cls): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ n = num_cls palette = [0] * (n * 3) for j in range(0, n): lab = j palette[j * 3 + 0] = 0 palett...
def choose(paragraphs, select, k): """Return the Kth paragraph from PARAGRAPHS for which SELECT called on the paragraph returns True. If there are fewer than K such paragraphs, return the empty string. Arguments: paragraphs: a list of strings select: a function that returns True for par...
def bytes2MiB(bytes): """ Convert bytes to MiB. :param bytes: number of bytes :type bytes: int :return: MiB :rtype: float """ return bytes / (1024 * 1024)
def areaTriangulo(base, altura): """Function that finds the area of a triangle given its width and height Args: base (float): the value for the width of the triangle altura (float): the value for the height of the triangle Returns: float: The area of the triangle """ return...
def _trimDict(row, column, evelist): """ function used to get only desired values form dictionary """ temdict = {k: row[column].get(k, None) for k in evelist} dictout = {k: v for k, v in temdict.items() if not v is None} return dictout
def Question2(a): """Given a string a, find the longest palindromic substring contained in a. Your function definition should look like question2(a), and return a string.""" if len(a) == 0: return "No String found" s='$*'+'*'.join(a)+'*#' p=[0]*len(s) mirr,C,R,maxLPSIndex,maxLPS=0,0,0,0,0 #...
def deployment_option_validator(x): """ Property: DeploymentStyle.DeploymentOption """ valid_values = ["WITH_TRAFFIC_CONTROL", "WITHOUT_TRAFFIC_CONTROL"] if x not in valid_values: raise ValueError( "Deployment Option value must be one of: %s" % ", ".join(valid_values) ) ...
def obj2vl(spec): """reverse operator for vl2obj""" vl_spec = {} for f in spec: if f == "encoding": vl_spec[f] = {} for l in spec[f]: enc = l.copy() channel = enc.pop("channel", None) vl_spec[f][channel] = enc else: vl_spec[f] = spec[f] return vl_spec
def not_none(seq): """Returns True if no item in seq is None.""" for i in seq: if i is None: return False return True
def bytes_to_int_big_endian(data: bytes) -> int: """Converts bytes to integer in big endian mode""" res = 0 for x in data: res = (res << 8) | x return res
def get_3x3_homothety(x,y,z): """return a homothety 3x3 matrix""" a= [x,0,0] b= [0,y,0] c= [0,0,z] return [a,b,c]
def _make_barrons_translation(x): """Apply function for a custom mapping of a text Barron's field to a number""" bar_dict = { "Most Competitive+": 1, "Most Competitive": 2, "Highly Competitive": 3, "Very Competitive": 4, "Competitive": 5, "Less Compet...
def normalise_paths(paths): """Test normalising paths. NB Paths on difference platforms might look different, so this makes them comparable. """ return {pth.replace("/", '.').replace("\\", ".") for pth in paths}
def slice2limits(slices): """ Create a tuple of minimum, maximum limits from a set of slices. Parameters ---------- slices : list List of slice objects which return points between limits Returns ------- limits: tuple, (ndarray, ndarray) Two tuple consisting of array of ...
def bc(val): """ Convert bool to single letter T or F """ if val is True: return "T" return "F"
def levenshtein(s1: str, s2: str) -> int: """ Pythonic levenshtein math to quickly determine how many "edits" two strings are differently than one another. Code snippet by Halfdan Ingvarsson :param s1: String to compare :param s2: String to compare :return: int - number of edits required (...
def passed(test_list): """find number of passed tests from a list [testsRuns, testFailures, testErrors]""" return test_list[0] - (test_list[1] + test_list[2])
def float2str(flt, separator=".", precision=None, prefix=None, suffix=None): """ Converts a floating point number into a string. Contains numberous options on how the output string should be returned including prefixes, suffixes, floating point precision, and alternative decimal separators. P...
def calcular_distancia_entre_puntos(x1, x2, y1, y2): """ Calcular la distancia entre dos puntos param: x1: longitud punto 1 param: x2: longitud punto 2 param: y1: latitud punto 1 param: y2: latitud punto 2 """ xi = (x2 - x1) ** 2 yi = (y2 - y1) ** 2 return (xi + yi) ** (1/2)
def multi_column_fields(fields, form): """ Return a dict with the number of columns per field... This is usually 1, but may, in the context of some record in the form, be more for a List (multiple choice) field. """ selected = {} for name, field in fields: selected[name] = set() ...
def config_id(c): """ Generates a unique name for each configuration Parameters ---------- c: dict A valid configuration for FastTextHandler Returns ------- A name for the input configuration `c` """ h = sorted(c.items(), key=lambda x: x[0]) return "_"...
def apply_label(row, labels, is_fabs): """ Get special rule labels for required or type checks for FABS submissions. Args: row: the dataframe row to get the label for labels: the list of labels that could be applied in this rule is_fabs: a boolean indicating if the submi...
def containedin(passwd, chars): """ See if all of the characters in the password are contained in this list of chars """ for p in passwd: if not p in chars: return False return True
def bin(x, digits=0): """Get the binary for a decimal input. Args: x: Decimal input digits: Number of digits for padding. Returns: A binary string, padded if necessary. """ # 2020-10-13 KWS Python 3 returns octal numbers with a prefix of 'o'. Need to remove this. oct2bi...
def KK_RC23_fit(params, w, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params["Rs"] R1 = params["R1"] R2 = params["R2"] R3 = params["R3"] R4 = params["R4"] R5 = params["R5"] R6 = params["R6"] ...
def _unpack_uint32(data): """Convert 4 bytes in little-endian to an integer.""" assert len(data) == 4 return int.from_bytes(data, 'little')
def _get_laser_bias(time, campaigns, bias): """ Map time (yr) to campaign to correction. """ camp = [ca for (t1, t2, ca) in campaigns if t1 <= time < t2] # ['c']|[] laser = camp[0][:2] if camp else None return bias[laser]
def merge_rules(a, b): """Merge two rules.""" c = a.copy() c.update(b) return c
def _valid_color(col): """Checks whether an rgba value is a valid color or not.""" for c in col: if c < 0 or c > 1: return False return True
def has_id(obj): """ Checks if the object has a getID method. :param obj: Object to check :return: <Boolean> """ if 'getID' in dir(obj): return True else: return False
def get_setup(job=None): """ Return the resource specific setup. :param job: optional job object. :return: setup commands (list). """ setup_commands = ['source /ccs/proj/csc108/athena_grid_env/setup.sh', 'source $MODULESHOME/init/bash', 'tmp_dirname=...
def _normalize_name(name): """ Return normalized event/function name. """ if '(' in name: return name[:name.find('(')] return name
def _bunch(x, cls): """ Recursively transforms a dictionary into a Bunch via copy. >>> b = _bunch({'urmom': {'sez': {'what': 'what'}}}, BunchDict) >>> b.urmom.sez.what 'what' bunchify can handle intermediary dicts, lists and tuples (as well as their subclasses), but ymmv on...
def _fixops(x): """Rewrite raw parsed tree to resolve ambiguous syntax which cannot be handled well by our simple top-down parser""" if not isinstance(x, tuple): return x op = x[0] if op == 'parent': # x^:y means (x^) : y, not x ^ (:y) # x^: means (x^) :, not x ^ (:) ...
def _matplotlib_list(interval_list): """ Returns lists for matplotlib ``fill`` command from a list of bounding rectangular intervals """ xlist = [] ylist = [] if len(interval_list): for intervals in interval_list: intervalx = intervals[0] intervaly = intervals...
def linear(mu, c, i0=1.0): """ Calculates the intensity of a given cell in the stellar surface using a linear 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 sight. ...
def encode_rle(input): """ Gets a stream of data and compresses it under a Run-Length Encoding. :param input: The data to be encoded. :return: The encoded string. """ if not input: return "" encoded_str = "" prev_ch = "" count = 1 for ch in input: # Check I...
def to_camel_case(text): """Convert to camel case. >>> to_camel_case('example_code') 'exampleCode' Args: - text: str Retrun: camel case of str """ split = text.split('_') return split[0] + "".join(x.title() for x in split[1:])
def get_outer_grid(coordinate_list): """Get the boundaries of the outer grid for ease of plotting""" x_coordinates = list(sorted(i[0] for i in coordinate_list)) y_coordinates = list(sorted(i[1] for i in coordinate_list)) min_x = x_coordinates[0] - 2 max_x = x_coordinates[-1] + 2 min_y = y_...
def _list_to_string(l, s): """Concatenates list items into a single string separated by `s`. Args: l: List with items to be concatenated into a single string. s: String or char that will be concatenated in between each item. Returns: String that has all items in list `l` concatenated with `s...
def _solve_method_2(a): """Use a dictionary.""" d = dict() for item in a: if not item in d: d[item] = 1 else: d[item] += 1 for k, v in d.items(): if v == 1: return k
def lower_keys(x): """Recursively make all keys lower-case""" if isinstance(x, list): return [lower_keys(v) for v in x] if isinstance(x, dict): return dict((k.lower(), lower_keys(v)) for k, v in x.items()) return x
def get_quartile_data(number_of_simulations): """ Take in the number of simulations and output the quartile line numbers. """ std_increment = round(number_of_simulations/100) lower_quartile = round(std_increment*25) middle_quartile = round(std_increment*50) upper_quartile = round((std_increment*75))...
def dedupList(seq): """De-duplicate list""" seqset = set(seq) return list(seqset)
def to_bool(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possible True values: 1, True, "1", "TRue", "yes", "y", "t" Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ... URL: http://stackoverflow.com/que...
def ListUnion(list_1, list_2): """Returns the union of two lists. Python sets can have a non-deterministic iteration order. In some contexts, this could lead to TensorFlow producing two different programs when the same Python script is run twice. In these contexts we use lists instead of sets. This function is ...
def parenthesis_aware_split(string, delim=',', open_par='(', close_par=')'): """ Split outside of parenthesis (i.e. ignore delimiters within parenthesis.""" out = [] s = '' open_parenthesis=0 for c in string: if c == open_par: open_parenthesis+=1 if c == close_par and op...