content
stringlengths
42
6.51k
def to_list(x, allow_tuple=False): """Normalizes a list/tensor into a list. If a tensor is passed, we return a list of size 1 containing the tensor. # Arguments x: target object to be normalized. allow_tuple: If False and x is a tuple, it will be converted into a list ...
def get_nameservice(hdfs_site): """ Multiple nameservices can be configured for example to support seamless distcp between two HA clusters. The nameservices are defined as a comma separated list in hdfs_site['dfs.nameservices']. The parameter hdfs['dfs.internal.nameservices'] was introduced in Hadoop 2.6 to d...
def parse_grid(data): """Parses the string representation into a nested list""" return [list(row) for row in data.strip().split("\n")]
def pretty_user_story(story): """Pretty up a user story""" story['acceptance criteria'] = '\n'.join(story['acceptance criteria']) return story
def multiply_scalar(x, scalar): """multiply_scalar matrix multiply scalar for each element :param x: matrix :param scalar: scalar to multiply matrix :return: matrix after multiplying scalar """ for i in range(len(x)): for j in range(len(x[0])): x[i][j] = scalar * x[i][j] ...
def truncate_string(string, max_len=100): """Shorten string s to at most n characters, appending "..." if necessary. """ if string is None: return None if len(string) > max_len: string = string[:max_len-3] + '...' return string
def _decode(line): """ Decoding input, depending on the file extension """ try: line = line.decode('utf-8') except AttributeError: pass return line
def yields_from_leung_nomoto_2020(feh): """ Supernova data source: Leung & Nomoto, 2020, ApJ, Vol 888, Issue 2, Id 80 The seven datasets are provided for Z/Zsun values of 0, 0.1, 0.5, 1, 2, 3 and 5. Using Zsun = 0.0169 the corresponding FeH values are -1, -0.301, 0.0, 0.301, 0.4771 and 0.69897. We u...
def construct(sub, dom): """ Makes a form data for processing by our lord and savior tld list. Requires arguments: subdomain, tld """ csrf = "42f662721815dbcb75ffc4481330c401cb9754c23c7d1f5d9a" csrf += "156b8007eb7d9068c1ffba80ccea2e7b1b922545117bad" return {"csrf": csrf, "subdomain": su...
def format_tag(something): """ if *something* is None, return "!None". Otherwise, return *something*. """ if something is None: return '!None' else: return something
def test_break_in_orelse_deep2(): """should rise a useless-else-on-loop message, as the break statement is only for the inner for loop """ for _ in range(10): if 1 < 2: for _ in range(3): if 3 < 2: break else: print("all...
def select_dataset_file_for_each_worker(files, f_start_id, worker_num, worker_index): """ Spliting the train file according to the worker index. """ num_files = len(files) if worker_num > num_files: remainder = worker_num % num_files data_fil...
def format_range(obj, min_val=None, max_val=None): """Formats the given object to a valid range. If `min_val` or `max_val` is provided, both the starting value and the end value will be clamped to range `[min_val, max_val]`. NOTE: (a, b) is regarded as a valid range if and only if `a <= b`. Args:...
def get_bit(number: int, position: int) -> bool: """ Returns the nth bit of an integer as a boolean. 0 refers to the LSB, aka 1s place. """ return bool((number >> position) & 1)
def team_points_allowed_fn(points_allowed): """Return fantasy points scored by a defense based on the number of points they allowed. Based on point scale found on https://fantasydata.com/developers/fantasy-scoring-system/nfl """ if points_allowed == 0: return 10 elif points_allowed < 7: ...
def LSet(var, value): """Do a VB LSet Left aligns a string within a string variable, or copies a variable of one user-defined type to another variable of a different user-defined type. LSet stringvar = string LSet replaces any leftover characters in stringvar with spaces. If string is longe...
def calculate_stretch_factor(array_length_samples, overlap_ms, sr): """Determine stretch factor to add `overlap_ms` to length of signal.""" length_ms = array_length_samples / sr * 1000 return (length_ms + overlap_ms) / length_ms
def _prop_var(p, n): """ Calculate variance of proportion. var(X/n) = 1/(n^2)var(X) = (npq)/(n^2) = pq/n """ return p * (1 - p) / n
def expand(x, *args, **kwds): """ EXAMPLES:: sage: a = (x-1)*(x^2 - 1); a (x^2 - 1)*(x - 1) sage: expand(a) x^3 - x^2 - x + 1 You can also use expand on polynomial, integer, and other factorizations:: sage: x = polygen(ZZ) sage: F = factor(x^12 - 1); F ...
def curve_between( coordinates, start_at, end_at, start_of_contour, end_of_contour): """Returns indices of a part of a contour between start and end of a curve. The contour is the cycle between start_of_contour and end_of_contour, and start_at and end_at are on-curve points, and the return value is...
def zero_out_of_bounds(records): """"Set waveforms to zero out of pulse bounds """ if not len(records): return records samples_per_record = len(records[0]['data']) for r in records: end = r['pulse_length'] - r['record_i'] * samples_per_record if end < samples_per_record: ...
def correct_move(gameboard, streets, added_pieces): """ Method to check whether the planned move is correct. A move is correct if all items of the gameboard are still there and only the added values are new. Additionally, each list must contain 3 or more items :param gameboard: Gameboard before the ...
def _IsValidTestPathPattern(test_path_pattern): """Checks whether the given test path pattern string is OK.""" if '[' in test_path_pattern or ']' in test_path_pattern: return False # Valid test paths will have a Master, bot, and test suite, and will # generally have a chart name and trace name after that. ...
def qualifying_prefix(modname, qualname): """ Returns a new string that is used for the first half of the mangled name. """ # XXX choose a different convention for object mode return '{}.{}'.format(modname, qualname) if modname else qualname
def create_table(src, dst): """Create a translation table from two strings. Given strings src="ABC" and dst="abc", this returns a table which maps 'A' to 'a', 'B' to 'b', and 'C' to 'c'. The strings must be of equal length. """ assert len(src) == len(dst) return {ord(from_): ord(to) for (f...
def calc_gamma(c: int) -> float: """ Calculates the gamma factor (2*odd(n))/(3*odd(n)-1) odd(n) - means the closest odd number to n that is not lager then n. :param c: The number of agents. :return: The Gamma factor >>> calc_gamma(3) 0.75 >>> calc_gamma(30) 0.6744186046511628 >>...
def is_nonneg_int(num_str): """ Args: num_str (str): The string that is checked to see if it represents a nonneg integer Returns: bool """ assert isinstance(num_str, str) return num_str.isdigit()
def set_brackets(pathway): """ Function defines levels of all brackets in expression. The output will be used by function <check_brackets> Example 1: expression: A B (C,D) levels: -1,-1,-1,-1,0,-1,-1,-1,0 Example 2: expression: (A B (C,D)) levels: 0,-1,-1,-1,-1,1,-1,-1,...
def filter(organisms, threshold=-1, require=None): """Filter out organisms with less than threshold marker sequences.""" new = {} for organism, markers in organisms.items(): if threshold > 0 and len(markers) < threshold: continue if require and not set(require).issubset(markers):...
def parse_op_and_node(line): """Parse a line containing an op node followed by a node name. For example, if the line is " [Variable] hidden/weights", this function will return ("Variable", "hidden/weights") Args: line: The line to be parsed, as a str. Returns: Name of the parsed op type. N...
def unique_string_list(element_list, only_string=True): """Return a unique list of strings from an element list. Parameters ---------- element_list : only_string : (Default value = True) Returns ------- """ if element_list: if isinstance(element_list, list): ...
def get_ancestor_of_type(ast_node, reference_type): """get the ancestor""" tmp = ast_node try: while tmp is not None: tmp = tmp.parent if isinstance(tmp, reference_type): return tmp except AttributeError: return None
def calculate_beta(weight_gap, weight_reference, weight_sample, gamma_gap, gamma_reference, gamma_sample): """ Calculates the factor \(\\beta\) that is needed to calculate the compensated moment of a sample. """ return ((weight_reference*gamma_reference)-(weight_sample*gamma_sample))/(weight_gap*gamma_g...
def foo2_with_docs(bar='hello', baz='world'): """This is a function foo! It has some docs, isn't this cool! Parameters ---------- bar: str This is a parameter. """ return bar + ' ' + baz
def make_url(region, bucket_name, obj_path, version=None): """ This link describes the format of Path Style URLs http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro """ base = "https://s3.amazonaws.com" if region and region != "us-east-1": base = "...
def direction(from_cell, to_cell): """ Determine which direction to move\n @param from_cell -> Current cell occupied\n @param to_cell -> Destination cell\n @returns -> Direction to move\n """ dx = to_cell[0] - from_cell[0] dy = to_cell[1] - from_cell[1] if dx == 1: return '...
def iptoint(ipaddr): """ Convert ip address into integer """ spl = ipaddr.split(".") if len(spl): return ((int(spl[0])<<24)+ (int(spl[1])<<16) + (int(spl[2])<<8) + int(spl[3])) return 0
def qint_add_primitive(q1, s1, q2, s2): """ Adds two quantized values q1 and q2 where qi = xi / si Here xi is the floating point representation of the value Args: q1: The quantized integer code of value 1 s1: The scale of value 1 q2: The quantized integer code of value 2 ...
def is_value_categorical(value): """Return if a value is categorical""" return type(value) == str
def get_format(value): """ >>> get_format("1e-5") '%.0e' >>> get_format("1e5") '%.0e' >>> get_format("0.") '%.0f' >>> get_format("0.5") '%.1f' >>> get_format("0.5") '%.1f' >>> get_format("0.50") '%.2f' >>> get_format('5') """ value = value.lower() ...
def substitute_file_extension(filename, extension): """Substitutes file extension, respecting known shader extensions. foo.vert -> foo.vert.[extension] [similarly for .frag, .comp, etc.] foo.glsl -> foo.[extension] foo.unknown -> foo.[extension] foo -> foo.[extension] """ if filename[-5:] n...
def transform_entity(org_name, app_name, collection_name, entity_data, source_client, target_client, attempts=0): """ This is an example handler function which can transform an entity. Multiple handler functions can be used to process a entity. The response is an entity which will get passed to the next ha...
def get_from_dict( d, **kw ): """ crea un nuevo dicionario usando el kw la llave del kw es la llave del dicionario y el valor de kw es el nombre de la nueva llave Parameters ========== d: dict kw: dict Examples ======== >>>origin = { 'a': 'a', 'b': 'b': 'c': 'c' } >>>ge...
def create_match_query(table, return_key, match_key, match_val): """Summary Args: table (TYPE): Description return_key (TYPE): Description match_key (TYPE): Description match_val (TYPE): Description Returns: TYPE: Description """ return """ S...
def n2AA(n): """ >>> n2AA(1) 'A' >>> n2AA(25) 'Y' >>> n2AA(26) 'Z' >>> n2AA(27) 'AA' >>> n2AA(52) 'AZ' >>> n2AA(55) 'BC' """ s = '' while n != 0: n -= 1 v = n % 26 n = n // 26 s = chr(ord('A') + v) + s return s
def VecSub(a, b): """Return vector a-b. Args: a: n-tuple of floats b: n-tuple of floats Returns: n-tuple of floats - pairwise subtraction a-b """ n = len(a) assert(n == len(b)) return tuple([a[i] - b[i] for i in range(n)])
def has_tags(word, tags): """Verify if word has tag. """ tag = word.split('/')[-1] return tag in tags
def get_bit(num, position): """Get the bit located at [position] in [num] """ return (num >> position) & 0b1
def _get_file_mimetype(filedata: bytes) -> str: """ Gets the mimetype of a file based on file signature. Args: filedata: The file data to process. Returns: The mimetype of the file. """ if filedata.startswith((b"GIF87a", b"GIF89a")): return "image/gif" elif filedat...
def entity_data_cleanse(entity: str, type: str, term: str, ): """ Ignores twitter handles, quantity, date, original search term, links """ return "@" not in entity and \ type != "QUANTITY" and \ type != "DATE" and \ entity != term.lower() and \ "http:" not in ...
def unit2str(units): """ Transform units dictionary format to dictionary """ str_units = "" for u in units.keys(): p = units[u]['pow'] ut = units[u]['units'] if p == 1: str_units += ut+' ' else: str_units += ut+'^'+str(p)+' ' return st...
def format_minutes(mins): """ Formats minutes in the form "X hours, Y minutes" """ hours = max(0, int(mins / 60)) hours_s = "s" if hours != 1 else "" mins = max(0, int(mins % 60)) mins_s = "s" if mins != 1 else "" if hours <= 0: return "{} minute{}".format(mins, mins_s) ret...
def _r_long(int_bytes): """Convert 4 bytes in little-endian to an integer. XXX Temporary until marshal's long function are exposed. """ x = int_bytes[0] x |= int_bytes[1] << 8 x |= int_bytes[2] << 16 x |= int_bytes[3] << 24 return x
def get_filename(filename): """get file name function""" return filename.upper()
def get_datasource_for(suffix: str, datasources: list) -> dict: """Extract a single datasource from the list of all. Args: suffix: a string representing the app name in the config datasources: a list of datasources Returns: a datasource config dict """ return [d for d in dat...
def index2state(lookup, actions, nStates): """ Converts state indexes back to tuples. Args: lookup (dict): Dictionary containing state-index pairs actions (list): List of actions (state indexes) to convert nStates (int): Number of states Returns sequence (list...
def Confirm(text, default='N'): """Asks the user to confirm something. Args: text(str): the text of the question. default(str): set the accepted value if user just hits Enter. Possible values: 'Y' or 'N' (the default). Returns: bool: True if the user confirms, False otherwise. """ print(tex...
def calc_tree_depth(n_features, max_depth=5): """Calculate tree depth Args: n_features (int): Number of features max_depth (int, optional): Max depth tree. Defaults to 15. Returns: [int]: Final depth tree """ # Designed using balls-in-bins probability. See the paper for detai...
def filter_for_ascii(text, placeholder="_"): """Some unicode characters are used in the eCalendar, and some command line consoles don't like this, so this script replaces characters that give Exceptions placeholder is '_' by default """ result = "" for letter in text: try: result += ...
def parser_metadata_Descriptor(data,i,length,end): """\ parser_metadata_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "metadata", "contents" : unparsed_descriptor_contents } (Defined in ETS...
def get_test(date): """get the file name of the test data""" ret = date + 'pred.csv' return ret
def is_valid_iyr(issue_year): """Checks for valid Issue Year.""" if issue_year.isdigit() and (2010 <= int(issue_year) <= 2020): return True else: return False
def _is_tuple_of_dyads(states): """Check if the object is a tuple or list of dyads """ def _is_a_dyad(dd): return len(dd) == 2 ret = False for st in states: if _is_a_dyad(st): ret = True else: ret = False break r...
def parse(address): """Parses the given MAC address and transforms it into "xx:xx:xx:xx:xx:xx" form. This form of expressing MAC addresses is the most standard one. In general, the "address" parameter accepts three forms of MAC address i input: - '1234567890af', - '12-34-56-78-90-a...
def remove_non_ascii(text:str): """ Removes non ASCII characters""" return ''.join(i for i in str(text) if ord(i)<128)
def is_composed_of_unique_characters(input_string: str) -> bool: """ Determine if all elements in string are unique (i.e. present only 1 time) Args: input_string: string to examine Return: True, if string is composed from only unique elements. Otherwise - False """ return len(set(i...
def complete_url(string): """Return complete url""" return "http://www.waroengkom.com/" + string
def resta_complejos(num1:list,num2:list) -> list: """ Funcion que realiza la resta de dos numeros complejos. :param num1: lista que representa primer numero complejo :param num2: lista que representa segundo numero complejo :return: lista que representa la resta de los numeros complejos. "...
def add_url_path(base_url: str, *args: str) -> str: """add path url""" base_url = base_url.rstrip('/') for arg in args: base_url += '/' + str(arg).strip('/') return base_url
def _char_to_hex(one_char): """ 'a' => '61' """ return format(ord(one_char), "x")
def fib(x): """Calculate fibonacci numbers.""" if x == 0 or x == 1: return 1 return fib(x - 1) + fib(x - 2)
def given_energy(n, ef_energy): """ Calculate and return the value of given energy using given values of the params How to Use: Give arguments for ef_energy and n parameters *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERS...
def create_plain_text(name, label, variant): """ Create a plain text field for the settings. Args: (String) name - unique name for switch. (String) label - Display text. (String) variant - plain text variant. I have no idea why they call it that way. But, ...
def word_sentiment_feature(word): """ Given a word, it returns a dictonary of the first letter of the word""" first_l = word[0] last_l = word[-1] # features is of the dictionary type having only one feature features = {"first letter": first_l, "last letter": last_l} return features
def conv_output_dim(input_size, kernel_size, stride=1, padding=0, dilation=1, **kwargs): """Calculate the output dimension of a convolutional layer """ from math import floor return floor((input_size + 2*padding - dilation*(kernel_size-1) - 1)/stride + 1)
def ShortOverLong(lengths): """ A measure of how cubic a molecules is. 0 means either a needle or plate shape. 1 means perfect cube ShortOverLong = Shortest / Longest """ return lengths[0]/lengths[2]
def make_divisible(v, divisible_by, min_value=None): """ This function is taken from the original tf repo. https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py """ if min_value is None: min_value = divisible_by new_v = max(min_value, int(v + divisibl...
def getFeaturesLen(geoJson): """ Return the number of items returned by a quick-search response params: geoJson -> quick-search dict response """ return len(geoJson["features"])
def manhattan_distance(x1: float, x2: float, y1: float, y2: float) -> float: """ Calculates Manhattan distance (sum of distance in x and y directions) between (x1, y1) and (x2, y2). Parameters ---------- x1 : float x-coordinate of the first point. x2 : float x-coordinate of ...
def addNums(a: int, b: int) -> int: """calculate sum""" # add definition return a + b
def parse_dotparen(structure): """ Parses the given dot-paren structure, returning a dict of the bound nucleotides. """ strand_structs = structure.split("+") bond_dict = {} stack = [] for strand_num, strand_struct in enumerate(strand_structs): i = 0 for char in strand_struct: loc = (strand_...
def calc_cop_burner(Q_load_W, Q_design_W): """ This function calculates efficiency of gas burners supplying heat directly to the high temperature generators in double effect absorption chillers. :param Q_load_W: Load of time step :type Q_load_W: float :type Q_design_W: float :param Q_design_...
def pr_contributors_list(lst): """ Returns unique contributors list. Parameters: list (list) Returns: list (list): returning value """ pr_contributors_unique=[] for x in lst: for y in x: if y not in pr_contributors_unique: pr_contributo...
def _sanitize_name(old_name: str) -> str: """Sanitized the names for printing and linking just in case Args: old_name (str): raw name Returns: str: sanitized string """ old_name = old_name.split("[")[0] old_name = old_name.split("==")[0] return old_name
def return_positions_of_Ns(sequence): """For a given sequence (e.g. scaffold / contig / gene) this function will return a set holding all indices (1-) Args: sequence: Returns: """ return {(i+1) for i, base in enumerate(sequence) if base == "N"}
def populate_extra_info(ref_type_id, arg_name, arg_value): """Populate the extra_info dictionary for this ref type.""" extra_info = {} def _unpack_str(to_key, value): if value is not None: extra_info[to_key] = value def _unpack_int(to_key, value): if value is not None: ...
def _make_static_axis_non_negative(axis, ndims): """Convert possibly negatively indexed axis to non-negative. Args: axis: Iterable over Python integers. ndims: Number of dimensions into which axis indexes. Returns: A list of non-negative Python integers. Raises: ValueError: If values in `ax...
def make_class_name(file_name: str) -> str: """Format file name to class name""" return file_name.replace(r".py", "").replace("_", " ").title().replace(" ", "")
def aggregate_sign(sig1, sig2): """ aggregate signatures """ sig11 , sig12 = sig1 sig21 , sig22 = sig2 assert sig11 == sig21 return (sig11, sig12+sig22)
def fahrenheit_to_celsius(fahrenheit): """Covert fahrenheit to celsius.""" celsius = (fahrenheit - 32) * 5.0/9.0 return celsius
def interpolate(offset,array): """Interpolate a 0-1 offset across an array of value""" if offset <= 0: return array[0] if offset >= 1: return array[-1] scale = len(array) - 1 scaled_offset = offset * scale integer_part = int(scaled_offset) decimal_part = scaled_offset - integer_part return array...
def list_remove_none(l): """ Removes None from the list l. Args: l: list, initial list to process. Returns: list, final list, without None. """ return [item for item in l if item is not None]
def mylen(a): """ If a is a scalar (or object with no length) return 1, otherwise len(a). Slight generalization of built-in len(). """ if '__len__' in dir(a): return len(a) else: return 1
def calculate(number): """Returns the sum of the digits in the factorial of the specified number""" factorial = 1 for permutation in range(1, number + 1): factorial *= permutation answer = sum(list(map(int, str(factorial)))) return answer
def filterLargeClusters(clusters, input_size, cluster_fraction_thresh): """ Remove big clusters which have more points than a given fraction of total points in the input data. Arguments: clusters: [list] a python list containing found clusters in the reachability diagram plot (optional) - ...
def strip_ptms(sequence): """ Removes all post-translation modifications (i.e. phosphorylation, glycosylation, etc) from a sequence. Parameters ---------- sequence : str Returns ------- str """ return sequence.upper()
def transform_response_to_context_format(data: dict, keys: list) -> dict: """ Transform API response data to suitable XSOAR context data. Remove 'x-ms' prefix and replace '-' to '_' for more readable and conventional variables. Args: data (dict): Data to exchange. keys (list): Keys to fi...
def frame_index_to_pts(frame: int, start_pt: int, diff_per_frame: int) -> int: """ given a frame number and a starting pt offset, compute the expected pt for the frame. Frame is assumed to be an index (0-based) """ return start_pt + frame * diff_per_frame
def trim_short_sentences(text: list): """ Trims short sentences from a list of sentences. """ text = [t for t in text if len(t) > 120] return text
def _calculate_votes(issue): """Get votes per issue from counts of Reactions A THUMBS_DOWN and CONFUSED counts as "-1", the rest as "+1". """ # First, count *all* reactions as "+1" score = issue['reactions']['totalCount'] # Then change the negative ones from "+1" to "-1" # (subtract 2 for ...