content
stringlengths
42
6.51k
def median(lst): """ Return a list's median :param lst: List (sorted or not) of int :return: int """ lst.sort() length = len(lst) if length == 0: return None elif length % 2 == 0: # Even number of elements return (lst[int((length+1)/2 - 1)] + lst[i...
def validate_environment_state(environment_state): """ Validate response type :param environment_state: State of the environment :return: The provided value if valid """ valid_states = [ "ENABLED", "DISABLED" ] if environment_state not in valid_states: raise ValueErro...
def get_command(data): """ Figure out what is the command being run from request data :param dict data: :return str: """ return data.get("command")
def _add_exposed_ports(exposed_ports, **kwargs): """Return Dockerfile EXPOSE instruction to expose ports. Parameters ---------- exposed_ports : str, list, tuple Port(s) in the container to expose. """ if not isinstance(exposed_ports, (list, tuple)): exposed_ports = [exposed_port...
def concat_annotations(annotations): """ Glues the shapes of a list of annotations together :param annotations: A list of tuples, where the first is the shape of the annotations, and the second is its label :type annotations: list of (str, str) :return: The combined shape of...
def get_data_format_and_size(data, data_type): """ Internal function to convert data_type to the corresponding struct.pack format string as per https://docs.python.org/2/library/struct.html#format-characters Function contributed by awm102 on GitHub. Amy moved this to DroneSensorParser to be more g...
def scalePixelData(pixelData, rInt, rSlope): """Scales pixel image values linearly by rescale values""" scaledPixelData = [] for pixelRow in pixelData: scaledPixelRow = [] for pixelValue in pixelRow: pixelScale = (rSlope * pixelValue) + rInt scaledPixelRow.append(pixelScale) s...
def clamp(value, mn=0, mx=255): """Clamp the value to the the given minimum and maximum.""" return max(min(value, mx), mn)
def NormalizeTargetPath(target): """Normalizes the target path. Adds leading slash if needed, strips ending slashes. Args: target: The target path (fusion db publish point). Returns: Normalized target path. """ if not target: return target target = target.strip() target = target.rstrip("/"...
def copy_and_fill(m, v): """ Return a vector with the same component as m, filled with v """ result = {} for (name, foo) in m.items(): result[name] = v return result
def clean_m3u_from_extended_tag(content: str) -> str: """Remove #EXTM3U and empty lines.""" clean_content = content.strip() if clean_content[:8] == "#EXTM3U\n": clean_content = clean_content[len("#EXTM3U\n"):] return clean_content.strip()
def HaystackSearch(needle, haystack): """ Return the index of the needle in the haystack Parameters: needle: any iterable haystack: any other iterable Returns: the index of the start of needle or -1 if it is not found. Looking for a sub-list of a list is actually a tricky thing. This approach uses th...
def print_palindromes(palindrome_dict): """ Given a dictionary with palindrome positions as keys, and lengths as first element of the value, print the positions and lengths separated by a whitespace, one pair per line. """ for key, value in palindrome_dict.items(): print(key, value[0]) ...
def from_hex(string): """This function is the inverse of `to_hex`.""" return bytes.fromhex(string.replace(":", ""))
def _only_if_true(value): """ _only_if_true Returns either (None, True) or (None, None) """ if value is False: value = None return None, value
def add_to_leftmost(branch, val): """adds value to the leftmost part of the branch and returns the modified branch and 0. OR returns unchanged change and val if the val cannot be added""" if val == 0: return branch, val if type(branch) is int: return branch + val, 0 # add to children...
def unpack_flags(flags_hex): """Unpacks 4-digit hexadecimal flags string. Args: flags_hex (str): Hexadecimal flags string. Returns: int: Object type. int: Near Earth Object indicator. int: If object is 1-km (or larger) Near Earth Object. int: 1-opposition object see...
def fis_smf(x:float, a:float, b:float): """S-Shaped membership function""" m = ((a + b) / 2.0) t = (b - a) if a >= b: return float(x >= m) if x <= a: return 0.0; if x <= m: t = (x - a) / t return (2.0 * t * t) if x <= b: t = (b - x) / t return ...
def parse_atrv(v): """ Parses the battery voltage and returns it in [Volt] as float with 1 decimal place :param str v: e.g. "12.3V" :return float: """ try: return float(v.replace('V', '')) except ValueError: return float('nan')
def scale_to_control(x, axis_scale=350., min_v=-1.0, max_v=1.0): """Normalize raw HID readings to target range.""" x = x / axis_scale x = min(max(x, min_v), max_v) return x
def replace_letters(string, encrypted, standard): """ Given a string, replace each encrypted letter with its equivalent frequency plaintext letter @param string is the string in which to replace characters @param encrypted is the encrypted letter alphabet @param standard is the standard languag...
def _get_bifpn_output_node_names(fpn_min_level, fpn_max_level, node_config): """Returns a list of BiFPN output node names, given a BiFPN node config. Args: fpn_min_level: the minimum pyramid level (highest feature map resolution) used by the BiFPN. fpn_max_level: the maximum pyramid level (lowest fea...
def bin2string (arr): """ Converts the binary number array 'arr' to string format """ bin_string = '' for bits in arr: bin_string += str(int(bits)) return bin_string
def _command_exists(command): """Check whether the given command exists and can be executed.""" from subprocess import getstatusoutput return getstatusoutput("which " + command)[0] == 0
def _merge_list_groups(group_1, group_2): """ Mergers the two list groups. Merging groups is a pre-operation of difference calculation, so copying is not required. Parameters ---------- group_1 : `None`, `list` of `Any` The first group to merge. group_2 : `None`, `list` of ...
def get_key(val, search_dict): """ Gets dict key from supplied value. val: Value to search search_dict : Dictionary to search value for """ for key, value in search_dict.items(): if val in value: return key
def list2dict(obj): """ Converting a list of pairs into a dictionary. >>> data = list2dict([("first-name", "Agatha"), ("surname", "Christie")]) >>> data['first-name'] 'Agatha' >>> data['surname'] 'Christie' """ assert isinstance(obj, list) and all([(isinstance(entry, tuple) or isins...
def take_while(predicate, list): """Returns a new list containing the first n elements of a given list, passing each value to the supplied predicate function, and terminating when the predicate function returns false. Excludes the element that caused the predicate function to fail. The predicate functio...
def encode_sentences(sentences, lexicon_dictionary): """ Change words in sentences into their one-hot index. :param sentences: A list of sentences where all words are in lexicon_dictionary :param lexicon_dictionary: A dictionary including all the words in the dataset sentences are being drawn...
def is_rem_policy(policy): """ Checks if the current policy action is a patch-on-delete action. """ return 'setIamPolicy' in policy['action'] and 'metadata' in policy
def copy_img(img): """ Returns copy of the provided image EXAMPLE USES from CSEPixelArt import * # Return new image where red filter is applied # to the provided image, on even rows, thus # creating a red stripe effect. def red_filter_stripes(img): red_img = copy...
def str2ord(string): """ returns the ord() of each character of a string as a list """ return [ord(c) for c in string]
def plugin_id(name, version): """Creates an ID for the plugins. Parameters ---------- name: str A string identifying the plugin. version: int A version number for the plugin. """ if not isinstance(version, int) or version < 0: raise ValueError("version must be a non ...
def long_strings(data: bytes) -> list: """ returns the long strings in the data (separated by newlines) May not be a distuinguishing criteria as non-malwares may have long strings too threshold length:50 Args: data: strings data read from "Strings.txt" file Returns: List o...
def lower_conductance(cell, mutant_str): """ Returns a lower limit for the conductance of the cell with the given integer index ``cell``. """ # # Guesses for lower conductance # if mutant_str == 'WT': lower_conductances = { 1: 0.114, 2: 0.108, ...
def _partition_fold(v,data): """ partition the data ready for cross validation Inputs: v: (int) cross validation parameter, number of cross folds data: (np.array) training data Outputs: list of partitioned indicies """ partition = [] for i in range(v): if i...
def u16b(x): """Unpacks a 2-byte string into an integer (big endian)""" import struct return struct.unpack('>H', x)[0]
def _sort_widgets(selected_widgets, widget_positions): """Sort widgets based on their positions. Args: selected_widgets (list): A list of widgets that we have selected to display. widget_positions (dict): A dictionary mapping widget IDs to their ordinals. Returns: ...
def get_percentage_values(total_pages, present_flag, any_flag): """Calculate width of the bar plot in percentage ratio format :param total_pages: the total number of pages for process :param present_flag: dict formed by get_flags_count(data, column) function. {0: <number of swapped pages>, 1: <number of pr...
def fix_annotate(bboxes): """ Fix annotations to format followed by mindspore. :param bboxes: in [label, x_min, y_min, w, h, truncate, difficult] format :return: annotation in [x_min, y_min, w, h, label, truncate, difficult] format """ for bbox in bboxes: tmp = bbox[0] bbox[0] = ...
def descrFromDoc(obj): """ Generate an appropriate description from docstring of the given object """ if obj.__doc__ is None or obj.__doc__.isspace(): return None lines = [x.strip() for x in obj.__doc__.split("\n") if x and not x.isspace()] return " ".join(l...
def get_mgmt_interface_devname_cmd(ip_addr): """ Generate the VIOS command to find VIOS/IVM management interface device name. Be aware, ioscli lstcpip -interface will be a slow command (about 1 second per configured interface). The alternative is to use lstcpip -stored to do AIX config database quer...
def _get_module_name(file_name): # type: (str) -> str """Return the python module name for the given file. Args: file_name: The file name of a python file. Returns: Converts the file name to a python-style module and returns the name. """ return file_name[:-3].replace("/", ".")
def is_root_organization(obj): """ Check whether this object(organization) is the root organization This check is performed based on whether this org's parent org is None According to current design, only root organization's parent org could not None :param obj: object to check :return: True...
def _parse_github_access_token(content): """Super hackish way of parsing github access token from request""" # FIXME: Awful parsing w/ lots of assumptions # String looks like this currently # access_token=1c21852a9f19b685d6f67f4409b5b4980a0c9d4f&token_type=bearer return content.split('&')[0].split('...
def diff_2nd_xx(fp, f0, fm, eps): """Evaluates an on-diagonal 2nd derivative term""" return (fp - 2.0*f0 + fm)/eps**2
def negate_columns(decision_matrix, optimization_type): """ negate columns of decision matrix in case optimization type is 1 (minimize) """ for j in range(len(optimization_type)): if optimization_type[j] == 1: for i in range(len(decision_matrix)): decision_matrix[i][j] = deci...
def _round3(n): """Rounds to nearest thousandth.""" return round(n, 3)
def classify_contour(elev, contour_interval): """Classify a contour by elevation. :param elev: elevation level :type elev: float :param contour_interval: contour interval to be used (usually 2.5 or 5.0) :type contour_interval: float :returns: Type of the contour :rtype: str """ if elev % (contour_interval *...
def _revoke_security_group_response(rule_type): """ Generate a response for revoke security group requests. @param rule_type: The type of rule @return: Response. """ if rule_type == 'ingress': rule_type = 'RevokeSecurityGroupIngressResponse' elif rule_type == 'egress': rule_...
def create_wordy_phrase(input_csi_str): """ Summarise input comma separated integer """ input_int_str = (str(input_csi_str)).replace(',', '') input_len = len(input_int_str) if (input_len > 3 and input_len < 7): temp = round((int(input_int_str)/1000), 1) return str(temp) + "K" elif (input_len >= 7 ...
def max_sum_sub_array(arr, k): """Sliding Window""" n = len(arr) if n < k: return -1 max_sum = -float("inf") # 1st window window_sum = 0 for i in range(k): window_sum = window_sum + arr[i] # Start from k and slide the window # to get new sums. Store max and return ...
def triangular_number(n): """Returns the `n`th triangular number `n * (n + 1) // 2`""" return n * (n + 1) // 2
def _gen_append_str(list_out=None): """ Just helper function to generate string expected to be added for an input (see testdata) for testing. :param list list_out: None, [0], [1], [0,1] - no more expected vals, which represents what macros should be appended ...
def division(x, y): """Function to perform division""" if y == 0: raise ValueError("Can;t divide by zero") return x / y
def get_attack_details(ipal_entry): """ Parse the attack-details IPAL field. The field is expected to have the format "<attack category>;<attack type>". Example: "2;12". """ split = ipal_entry["attack-details"].split(";") assert ( len(split) == 2 ), "'attack-details' field in IP...
def _reverse_intervals(intervals): """Reverse intervals for traversal from right to left and from top to bottom.""" return [((b, a), indices, f) for (a, b), indices, f in reversed(intervals)]
def binary_mask_to_str(m): """Given an iterable or list of 1s and 0s representing a mask, this returns a string mask with '+'s and '-'s.""" m = list(map(lambda x: "-" if x == 0 else "+", m)) return "".join(m)
def redis_hash_to_dict(redis_hash): """convert redis hash to python dict. Args: redis_hash: redis hash object, a dict with all keys and values in byte. Return: a python dict with all keys and values in string. """ return {k.decode("utf-8"): v.decode("utf-8") if v else "" ...
def _broadcast_tuples(tup1, tup2): """ Broadcast two 1D tuples to the same length, if inputs are ints, convert to tuples first. """ tup1 = (tup1,) if isinstance(tup1, int) else tup1 tup2 = (tup2,) if isinstance(tup2, int) else tup2 if not isinstance(tup1, (tuple, list)) or not isinstance(tup...
def to_bin(arr, bytelen=8): """Converts an iterable object containing ascii codes to a string of the joint binary representation of each item where each of them is of length bytelen Args: arr (iterable): The array to be converted bytelen (int, optional): The length of the to-be-created binary s...
def index_to_column(idx): """Turns an index into a letter representing a spreadsheet column.""" letter = chr(65 + idx % 26) q = idx // 26 if q == 0: return letter else: return index_to_column(q-1) + letter
def obfuscate_vars(inventory): """ Remove sensitive variables when dumping inventory out to stdout or file """ stars = "*"*14 splunkVars = inventory.get("all", {}).get("vars", {}).get("splunk", {}) if splunkVars.get("password"): splunkVars["password"] = stars if splunkVars.get("pass4...
def url_to_fn(url): """ Convert `url` to filename used to download the datasets. ``http://kitakitsune.org/xe`` -> ``kitakitsune.org_xe``. Args: url (str): URL of the resource. Returns: str: Normalized URL. """ url = url.replace("http://", "").replace("https://", "") ur...
def get_idx(prefix, itf): """ Gets the index of an interface string >>> get_idx('et', 'et12') 12 >>> get_idx('ap', 'ap32') 32 """ return int(itf[len(prefix) :])
def copy_dict(other_dict): """ Returns a copy of the dictionary, separate from the original. This separation is only at the top-level keys. If you delete a key in the original, it will not change the copy. >>> d1 = dict(a=1, b=2) >>> d2 = dict(**d1) >>> del d1['a'] >>> 'a' in d1 False >>> 'a' in d2 True ...
def matrix_shape(matrix): """ Return the shape of a matrix returns a tuple with each index having the number of corresponding elements """ ans = [] while (isinstance(matrix, list)): ans.append(len(matrix)) matrix = matrix[0] return ans
def _is_str_or_list_str(s): """ Return boolean whether `s` is a string or list of strings. """ return isinstance(s, str) or \ (isinstance(s, list) and all(isinstance(x, str) for x in s))
def convert_title_case(text): """ Upper case the first character of each sentence. text: input string to be converted Return: converted string which first character is uppercase """ output = text.capitalize() return output
def returnLongestIterable(iterable_list): """assumes iterables_list is a list of iterables returns the longest iterable in iterables_list, if iterable_list has at least one element with lenght note: if there is a tie, will return the 1st element of that lenght encountered else returnes None""" m...
def remove_forbidden_characters(name): """ A function that will remove all the forbidden characters from the string. The forbidden characters are the ones that are not allowed to be used in the names of windows files. Those are --> r'/*=:<>"|\'. Parameters: name : string Returns ...
def first_peak(peaks): """Get the first non-placeholder peak in a list of peaks Parameters ---------- peaks : Iterable of FittedPeak Returns ------- FittedPeak """ for peak in peaks: if peak.intensity > 1 and peak.mz > 1: return peak
def norm_psql_cmd_string(s): """ Simple function to reduce down a multi-line string written for readability to a single line. :param s: Single or multi-line string with inconsistant white-space. :type s: str :return: Single-line string. :rtype: str """ return ' '.join(s.split())
def roh_air( dem, tempka): """ calculates the Atmospheric Air Density. This is found in Bastiaanssen (1995). /* Atmospheric Air Density * Requires Air Temperature and DEM*/ """ b = (( tempka - (0.00627 * dem )) / tempka ) result = 349.467 * pow( b , 5.26 ) / tempka if (result > 1.5): result = -999.99 elif ...
def _Bez3step(b, r, alpha): """Cubic bezier step r for interpolating at parameter alpha. Steps 1, 2, 3 are applied in succession to the 4 points representing a bezier segment, making a triangular arrangement of interpolating the previous step's output, so that after step 3 we have the point that is...
def split(separator, string): """Splits a string into an array of strings based on the given separator""" return string.split(separator)
def turn_anticlockwise(direction): """ Given a direction, returns the next direction around anticlockwise. """ return (direction - 1) % 4
def mestotext(mes): """ Regresa texto si se le envia numero de mes y viceversa """ meses = { 'January': '1', 'February': '2', 'March': '3', 'April': '4', 'May': '5', 'June': '6', 'July': '7', 'August': '8', 'September': '9', 'October': '10', 'November': '11', ...
def isBipartite(graph): """ Determine if a given graph is bipartite or not. Parameters ---------- graph : List[List[int]] The graph to study. Returns ------- bool Whether the graph is bipartite or not. """ white_vertices = set() black_vertices = set() ve...
def parse_command_line_args(args): """Group the arguments into a dictionary: parameter-name -> value""" parameters = {} values = [] argument_stack = list(args) while len(argument_stack): token = argument_stack.pop() if token.startswith('--'): parameter_name = token[2:] ...
def determine_filter_name(raw_filter): """ Generate the final filter name to be used for an observation. Parameters ---------- raw_filter : string filters component one exposure from an input observation visit Returns ------- filter_name : string final filter name ...
def position(mouse_x, mouse_y, length, width): """ Get the position on the board representing the mouse click :param mouse_x: horizontal position of mouse click :param mouse_y: vertical position of mouse click :param length: length of the board :param width: width of the board :return: posit...
def headerFA(block_size,extended=True): """ Creates the header list . \n Paramenters: \n \t blocks \n \t block_size \n Return dictionary list with the header """ if(extended): header =["Address","Tag","Real Address"] else: header =["Address"] for x in ...
def kaiser_beta(a): """Compute the Kaiser parameter `beta`, given the attenuation `a`. Parameters ---------- a : float The desired attenuation in the stopband and maximum ripple in the passband, in dB. This should be a *positive* number. Returns ------- beta : float ...
def step(step_type, action_on_failure, properties, name=None, additional_files=None): """ Create step :param step_type: the type of step :type step_type: Enum {'Java','Streaming','Hive','Pig', 'Spark'} :param action_on_failure :type actionOnFailure: Enum {'Continue','TerminateCluster','CancelA...
def first(collection, callback): """ Find the first item in collection that, when passed to callback, returns True. Returns None if no such item is found. """ return next((item for item in collection if callback(item)), None)
def remove_once(gset, elem): """Remove the element from a set, lists or dict. >>> L = ["Lucy"]; S = set(["Sky"]); D = { "Diamonds": True }; >>> remove_once(L, "Lucy"); remove_once(S, "Sky"); remove_once(D, "Diamonds"); >>> print L, S, D [] set([]) {} Returns the element if ...
def harmonic_series_tcr(n): """tail-call recursive""" def aux(n, acc): if not isinstance(n, int): raise TypeError("n must be an integer") elif n < 1: raise ValueError("n must be positive") elif n == 1: return acc else: return aux(n - 1, 1/n + acc) return aux(n, 1)
def _SanitizeBaseName(base_name): """Make sure the base_name will be a valid resource name. Args: base_name: Name of a template file, and therefore not empty. Returns: base_name with periods and underscores removed, and the first letter lowercased. """ # Remove periods and underscores. san...
def format_batch_score(batch: int, loss: float) -> str: """Formats the current result withitn batch processing in a string used for logging. Args: batch (int): current batch loss (float): current associated loss Returns: str: formatted string """ return f"Batch {batch}:...
def identical(iterable): """Check that all elements of an iterable are identical.""" return len(set(iterable)) <= 1
def version_len(version_str): """ Method to return the length of a version string without dots and build information >>> version_len("1.0.0") 3 >>> version_len("2.1.800.5") 6 >>> version_len("1.2.0-beta1") 3 >>> version_len("1.3.0.beta1") 3 :param version_str: Versio...
def invcdf_uniform(val: float, lb: float, ub: float) -> float: """Returns the inverse CDF lookup of a uniform distribution. Is constant time to call. Args: val: Value between 0 and 1 to calculate the inverse cdf of. lb: lower bound of the uniform distribution ub: upper bound of ...
def checkIntersection(bbox1, bbox2): """ Checks whether two bounding boxes are intersecting Input: bbox1: List of bounding box coordiantes (top left and bottom right x/y) bbox2: List of bounding box coordiantes (top left and bottom right x/y) Output: Boolean """ ret...
def replace_invalid_chars(s): """replaces chars unsuitable for a python name with '_' """ return ''.join([c if c.isalnum() or c == '_' else '_' for c in s])
def toSize(toPad,size): """ Adds spaces to a string until the string reaches a certain length Arguments: input - A string size - the destination size of the string Return: the expanded string of length <size> """ padded = toPad + " " * (size - len(toPad)) return padded.ljust(size," ")
def rst_title(title, symbol="="): """ ===== title ===== """ stroke = symbol * len(title) return "\n".join([stroke, title, stroke])
def args_init(args=None, demx=False, trim=False, align=False, call_peak=False): """Inititate the arguments, assign the default values to arg """ if isinstance(args, dict): pass elif args is None: args = {} # init dictionary else: raise Exceptio...
def compare_message_with_file(message, file_name): """ Compare message with file """ result_flag = False with open(file_name, 'r') as file_handler: lines = [line.strip() for line in file_handler] if message in lines: result_flag = True else: result_fla...
def _make_square(x, y, w, h): """Force the x, y slices into a square by expanding the smaller dimension. If the smaller dimension can't be expanded enough and still fit in the maximum allowed size, the larger dimension is contracted as needed. Args: x, y: slice objects w, h: the (width...