content
stringlengths
42
6.51k
def version_less(vstr1, vstr2): """Order for sorting versions in the format a.b.c""" return vstr1.split(".") < vstr2.split(".")
def quick_sort(arr, low=None, high=None): """Sort given items in place by partitioning items in range `[low...high]` around a pivot item and recursively sorting each remaining sublist range. Best case running time: O(nlogn) because your unsort list gets smaller and smaller with each recursive call Worst...
def converter(value,format_t2,def_value): """Returns the input value on the specified format Parameters ---------- value : float-str Parameter to be written format_t2 : dictionary Contains the format and default values for every variable def_value : bool True in case the default values is used Note -...
def IsImageFile(ext): """IsImageFile(ext) -> bool Determines if the given extension corresponds to an image file (jpg, bmp, or png). arguments: ext string corresponding to extension to check. returns: bool corresponding to whether it is an image file. ...
def before_query_sdel(sdel_query, *args, **kwargs): """Called immediately before Nova's session.Query.soft_delete, it prepares the expected kwargs (as in the original method). """ # Ensure the arguments expected by Query.soft_delete if 'synchronize_session' not in kwargs: kwargs['synchronize...
def _destringize_numbers(header): """Convert string values in `header` that work as numbers back into ints and floats. """ with_numbers = {} for key, val in header.items(): try: val = int(val) except: try: val = float(val) except: ...
def sort_dict_by_key(dictionary): """ Returns the dictionary sorted as list [(), (),]. """ return sorted(dictionary.items()) if dictionary else None
def tinyurlFindUrlstart( msg, start = 0 ): """Finds the beginnings of URLs""" index = -1 if start < 0 or start >= len(msg): return index for prefix in ( "http://", "https://", "ftp://", "ftps://" ): index = msg.find( prefix, start ) if index > -1: break return index
def convert_spectral_kernel_quad(sequences, list_seq_to_id): """ Return a list seq of nb of time the seq in list_seq_to_id appear in sequence""" final = [] for j in range(len(sequences)): sequence = sequences[j] dico_appear = {seq: 0 for seq in list_seq_to_id} for i in range(len(sequ...
def get_position(index, shape, strides): """Return the index (pos) of one-dimensional dimensionality reduced array that corresponds to the given index of the original array. """ d = len(shape) if d == 0: return 0 elif d == 1: return index[0] * strides[0] elif d == 2: ...
def is_leap_year(year): """Returns True if the year is a leap year, False otherwise. Parameters ---------- year: int The year to check. Returns ------- bool Is the year a leap year? """ return (((year % 4 == 0) and ((year % 100 > 0) or (year % 400 == 0))))
def binary_search(arr, val): """Takes in a sorted list and a value. Preforms the Binary Search algorythem to see if the value is in the lsit.""" # Set the values to the end of the list left,right = 0,len(arr) while not right <= left: mid = (right + left) // 2 if val > arr[mid]: left = mid+1 ...
def beautify_parameter_name(s: str) -> str: """Make a parameter name look better. Good for parameter names that have words separated by _ . 1. change _ by spaces. 2. First letter is uppercased. """ new_s = " ".join(s.split("_")) return new_s.capitalize()
def create_payload_for_request(template_data, user_input_dict, existing_data=None): """ This function creates the payload using the user provided input based on the respective template data and the existing data template_data dict which contains the data required for the resource(security rule,...
def google_docstring(param1, param2): """Summary line. Extended description of function. Args: param1 (int): The first parameter. param2 (str): The second parameter. Returns: bool: Description of return value """ if len(param2) == param1: return True else: ...
def translate_delta(mat, dx, dy): """ Return matrix with elements translated by dx and dy, filling the would-be empty spaces with 0. I feel this method may not be the most efficient. """ rows, cols = len(mat), len(mat[0]) # Filter out simple deltas if (dx == 0 and dy == 0): return m...
def get_maxrate(size_height): """ Maxrate equivalent to total bitrate 1000 kbps for 720p, with 128 kbps audio """ #720, v872, a128 # guide variables constant_size_height = 720 constant_video_maxrate = 872 constant_audio_quality = 128 constant_video_quality = \ (constant_...
def with_commas(val): """Formats the provided number with commas if it is has more than four digits.""" return '{:,}'.format(int(val))
def traverse_list_rev(tail): """Prints all elements from tail to head in reverse direction""" if tail is None: return -1 curr = tail arr = [] while curr.prev != tail: arr.append(curr.data) curr = curr.prev arr.append(curr.data) return " ".join(map(str, arr))
def uint_to_int(val, octals): """compute the 2's compliment of int value val for negative values""" bits=octals<<2 if( (val&(1<<(bits-1))) != 0 ): val = val - (1<<bits) return val
def normalize_nested_dict(d, denom): """Normalize values in a nested dict by a given denominator. Examples: >>> d = {"one": 1.0, "two": {"three": 3.0, "four": 4.0}} >>> normalize_nested_dict(d, 2.0) {'one': 0.5, 'two': {'three': 1.5, 'four': 2.0}} """ result = dict() for key, value in ...
def parseActiniaAsyncStatusResponse(resp, key): """ Method to parse any actinia_core response. Args: resp: (requests.models.Response): response object key: (string): key to return. If not root node, use notation like "a.b.c" Returns: result: (dict, string, ...): Value of requested key """ ...
def exponentiation(num1,num2): """Returns the value obtained by raising num1 to the power of num2.""" return (num1**num2)
def parse_helm_repo_list_output(helm_repo_list_output): """ Function will perform a manipulation on a string output from the 'helm repo list' command Returns an array of dicts with installed repos names and urls as strings as [{'repo_name': 'some_repo_name', 'repo_url': 'some_repo_url'}] by valida...
def escape_zoho_characters_v2(input_string) -> str: """ Note: this is only needed for searching, as in the yield_from_page method. This is an example :param input_string: :return: """ if r'\(' in input_string or r'\)' in input_string: # don't repeatedly escape return input_string el...
def get_data(tweet): """ :param tweet: scraped tweet gained by APIs :return data: return date and text from the input object """ data = { 'created_at': tweet['created_at'], 'text': tweet['text'] } return data
def Sn(i, length): """Convert an int to a binary string.""" s = '' while i != 0: digit = i & 0xff i >>= 8 s += chr(digit) if len(s) > length: raise Exception("Integer too big to fit") while len(s) < length: s += chr(0) return s
def getOutShape(input_dim,layersList): """ params: input_dim : input dimension of the data to the sequential network. A tupple (in_channels,H_in,W_in) layersList : A list of dictionaries for each layer. Refer the example to know more. """ in_ch, H_in, W_in = input_dim out_ch_prev = in_ch ...
def calculate_slice_for_rank(myrank, nranks, arraysz): """Calculate the slice indices for array processing in MPI programs. Return (low, high), a tuple containing the range of indices in an array of size arraysz, to be processed by MPI rank myrank of a total nranks. We assure as equitable a distributio...
def clamp_value(value, minimum, maximum): """Clamp a value to fit within a range. * If `value` is less than `minimum`, return `minimum`. * If `value` is greater than `maximum`, return `maximum` * Otherwise, return `value` Args: value (number or Unit): The value to clamp minimum (nu...
def format_cluster(cluster_results): """Drop footer, just include results""" cluster_results = [x for x in cluster_results if x[0] != 'footer'] cluster_results.sort(key=lambda x: x[0]) return cluster_results
def get_variation(variation_key, variations_dict, defaults_dict): """Convert a string to a tuple of integers. If the passed variation_key doesn't follow this pattern '0 100', it will return default values defined in defaults_dict. This is currently used for defining the variation data of the A/B e...
def raiseExceptionWhenNotImplemented(doRaise=None): """ Return value of this function used in L{raiseNotImplemented}. @type doRaise: bool @param doRaise: If specified, sets whether L{raiseNotImplemented} is to raise an exception. @rtype: bool @return: True when L{raiseNotImplemented} is to r...
def u_func(mahalanobis_dist, huber_denom, c_square): """ Huber's loss function :param mahalanobis_dist: Mahalanobis distance :param huber_denom: A constant in num_features (number of features) :param c_square: A constant in num_features and quantile (trade-off variable) :return: weight of sample...
def _normalize_tags(chunk): """ (From textblob) Normalize the corpus tags. ("NN", "NN-PL", "NNS") -> "NN" """ ret = [] for word, tag in chunk: if tag == 'NP-TL' or tag == 'NP': ret.append((word, 'NNP')) continue if tag.endswith('-TL'): ret...
def _GetImage(name): """Return the image path that appears in the expected output.""" return "/path/to/" + name + ".img"
def _sum(array): """ Recursively find the sum of array""" count = 0 while array: count += array[-1] array.pop() print(array) return count
def in_nrw(residence): """ Checks if the given residence is in NRW """ return ( residence["geolocation-street"]["street-gemeinde"]["gemeinde-kreis"][ "kreis-bundesland" ]["bundesland-name"] == "Nordrhein-Westfalen" )
def flatten(seq): """Concatenates the elements of seq. Given a list of lists, returns a new list that concatentes the elements of (seq). This just does one level of flattening; it is not recursive. """ return sum(seq, [])
def _bisearch(ucs, table, ubound): """ Auxiliary function for binary search in interval table. :arg int ucs: Ordinal value of unicode character. :arg list table: List of starting and ending ranges of ordinal values, in form of ``[(start, end), ...]``. :rtype: int :returns: 1 if ordinal ...
def bytes_to_bits(buf): """Converts a string of bytes to a list of bits""" return [b >> i & 1 for b in map(ord, buf) for i in range(7, -1, -1)]
def parse_symbol_type(symbol): """ parse_symbol_type It parse the symbol to Rockwell Spec :param symbol: the symbol associated to a tag :return: A tuple containing information about the tag """ pass return None
def is_letter(_code : int) -> bool: """ Detect letter """ lower : bool = _code >= 65 and _code <= 90 upper : bool = _code >= 97 and _code <= 122 #space_lowdash : bool = _code == 95 or _code == 32 space : bool = _code == 32 if lower or upper or space: return True return False
def _pad_hex(hexed: str) -> str: """Pad odd-length hex strings.""" return hexed if not len(hexed) & 1 else "0" + hexed
def resize_to_multiple(shape, multiple, length): """Modify a given shape so each dimension is a multiple of a given number. This is used to avoid dimension mismatch with patch training. The return shape is always larger then the initial shape (no cropping). Args: shape (tuple or list): Initial shap...
def complete_url(string): """Return complete url""" return "http://www.enterkomputer.com/" + string
def get_daytime(time, response): """ :param time: timestamp in unix seconds :param response: response from weather api :return: str day/evening-morning/night """ if response['sys']['sunrise'] < time <= response['sys']['sunset'] - 3600: return 'day' elif response['sys']['sunrise'] - 3...
def _get_path(toml_config, path): """ :param config: Dict with the configuration values :type config: dict :param path: Path to the value. E.g. 'path.to.value' :type path: str :returns: Value stored at the given path :rtype: double, int, str, list or dict """ for section in path.spl...
def create_graph(num_islands, bridge_config): """ Helper function to create graph using adjacency list implementation """ adjacency_list = [list() for _ in range(num_islands + 1)] for config in bridge_config: source = config[0] destination = config[1] cost = config[2] ...
def stateWeight(state): """ To ensure consistency in exploring states, they will be sorted according to a simple linear combination. The maps will never be larger than 20x20, and therefore this weighting will be consistent. """ x, y = state return 20*x + y
def ARPES_PVextras(name): """ used to get the PV associated with a given pnuemonic used with ARPES_PVmotor only have to change PVs in a single place name = "SES_slit", "TA", "TB", tey1", "tey2" """ dict={ "SES_slit":"29idc:m8.RBV", "TA":"29idARPES:LS335:TC1:IN1", "TB":"...
def sort_words_by_frequency(some_string): """ takes a single string of space-delimited word and returns a list of words they contain from most to least frequent """ # convert the string to a python list words = some_string.split() # assign a rank to each word based on frequency ranked_words = [[word...
def nfiles_str(nfiles: int) -> str: """Format `n files`.""" if nfiles == 0: return "no files" elif nfiles == 1: return "1 file" else: return f"{nfiles} files"
def dict_intersection(a: dict, b: dict): """Elements that are the same in a and b""" return {k: v for k, v in a.items() if k in b and b[k] == v}
def unstuff_line(line): """ Unstuffs an e-mail message line according to RFC 3637. :param line: The (possibly stuffed) message line. :return: The unstuffed message line. """ if line.startswith(' '): return line[1:] return line
def validate_completes_end_station(transport, route): """ Sanity check that the route is complete """ expected_end_station = transport.get("endStationId") expected_arrival_time = transport.get("plannedArrivalTimeEndStation") end_station = route[-1].get("stationId") arrival_time = route[-1].g...
def sameSevenCharStartPredicate(field): """return first seven charactesr""" if len(field) < 7: return () return (field[:7], )
def oneHotEncode_EventType_simple(x): """ This function one hot encodes the input for the event types cascade, tracks, doubel-bang """ # define universe of possible input values onehot_encoded = [] universe = [1, 2, 3] for i in range(len(universe)): if x == universe[i]: ...
def yesno(value): """Converts logic value to 'yes' or 'no' string.""" return "yes" if value else "no"
def deep_update(original, new_dict, new_keys_allowed, whitelist): """Updates original dict with values from new_dict recursively. If new key is introduced in new_dict, then if new_keys_allowed is not True, an error will be thrown. Further, for sub-dicts, if the key is in the whitelist, then new subkeys ...
def partition_esps_and_esms(filelist): """Split filelist into separate lists for esms and esps, retaining order.""" esm_files = [] esp_files = [] for filename in filelist: ext = filename[-4:].lower() if ext == ".esp": esp_files.append(filename) elif ext == ".esm": ...
def find_column_index(header, fields): """Find the corresponding column indices of given fields.""" indices = [] for txt in fields: for idx, col in enumerate(header): if col.find(txt) >= 0: indices.append(idx) break return indices
def integer_product(num1, num2): """Solution to exercise C-4.12. Give a recursive algorithm to compute the product of two positive integers, m and n, using only addition and subtraction. """ def recurse(num1, idx): if idx == 0: return 0 # Base case return num1 + recurs...
def print_version(version, is_quiet=False): """ """ if not is_quiet: print("version: {0}".format(version)) return 0
def replace_word_choice(sentence: str, old_word: str, new_word: str) -> str: """ :param sentence: str a sentence to replace words in. :param new_word: str replacement word :param old_word: str word to replace :return: str input sentence with new words in place of old words """ return sente...
def is_cmp(op): """ Tests whether an operation requires comparing two types. """ return op in ['<', '<=', '==', '!=', '>', '>=']
def non_exp_repr(x): """Return a floating point representation without exponential notation. Result is a string that satisfies: float(result)==float(x) and 'e' not in result. >>> non_exp_repr(1.234e-025) '0.00000000000000000000000012339999999999999' >>> non_exp_repr(-1.234e+018) '-1234...
def get_win_prob(elos): """Given a list of elos, return a list of the expected scores.""" #based on https://stats.stackexchange.com/q/66398 q = [] for elo in elos: q.append(10 ** (elo / 400)) expected_scores = [] for i in range(len(elos)): expected_scores.append(q[i]/sum(q)) return...
def trapezoid(ptr, data, dt): """I tried Simpson's rule but the noise in the accelerometer output made the output less accurate than a simple trapezoid integral. This also made the 3-element array for Altitude ( s[] ) moot but it is easier """ return (data[ptr - 1] + data[ptr]) / 2.0 * dt
def calc_epa_conversion(pm, rh): """Applies the EPA calibration to Purple's PM2.5 data. We floor it to 0 since the combination of very low pm2.5 concentration and very high humidity can lead to negative numbers. """ if pm < 2: return pm return max(0, 0.534 * pm - 0.0844 * rh + 5.604)
def le(h): """ Little-endian, takes a 16b number and returns an array arrange in little endian or [low_byte, high_byte]. """ h &= 0xFFFF # make sure it is 16 bits return [h & 0xFF, h >> 8]
def find_longest_common_substring(x: str, y: str) -> str: """ Finds the longest common substring between the given two strings in a bottom-up way. :param x: str :param y: str :return: str """ # Check whether the input strings are None or empty if not x or not y: return '' ...
def all_unique(iterable): """ Returns True if all items in an iterable are unique. """ seen = set() return not any(x in seen or seen.add(x) for x in iterable)
def parse_adapter_name(seq): """ Parse an adapter given as 'name=adapt' into 'name' and 'adapt'. """ fields = seq.split('=', 1) if len(fields) > 1: name, seq = fields name = name.strip() else: name = None seq = seq.strip() return name, seq
def _convert_int_to_i64(val): """Convert integer to signed int64 (i64)""" if val > 0x7FFFFFFFFFFFFFFF: val -= 0x10000000000000000 return val
def merge(items1, items2): """Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. Running time: O(n) Passes over each element once Memory usage: O(n) Makes a new list for all the elements """ ind_1, ind_2 = 0, 0 ...
def checkBSVictory(hit_board, opposing_board): """ Replace all Xs in the hit board with 0s and simply check if the hit board from one team matches the ship board of the other team match """ for z in hit_board: for i in z: if i is 'X': i = 0 if hit_boar...
def _external_dep_name_from_bazel_dependency(bazel_dep): """Returns name of dependency if external bazel dependency is provided or None""" if bazel_dep.startswith('@com_google_absl//'): # special case for add dependency on one of the absl libraries (there is not just one absl library) prefixlen ...
def obj_to_dict(obj): """ Used for converting objects from Murmur.ice into python dict. """ rv = {'_type': str(type(obj))} if isinstance(obj, (bool, int, float, str)): return obj if type(obj) in (list, tuple): return [obj_to_dict(item) for item in obj] if type(obj) == dict...
def prepare_text(text): """Remove unnecessary spaces and lowercase the provided string""" return text.strip().lower()
def gather_trainable_weights(trainable, sub_layers, extra_variables): """Lists the trainable weights for an object with sub-layers. Args: trainable: Whether the object collecting the variables is trainable. sub_layers: A flat list of Layer objects owned by this object, to collect variables from. ...
def create_parent_of(n_nodes, is_leaves, children_left, children_right,left_value=0,right_value=1): """Outputs a list which provides the index of the parent of a given node.""" parentOf = {} for i in range(n_nodes): if not is_leaves[i]: parentOf[children_left[i]] = (i,left_value) ...
def tickDiff(t1, t2): """ Returns the microsecond difference between two ticks. t1:= the earlier tick t2:= the later tick ... print(pigpio.tickDiff(4294967272, 12)) 36 ... """ tDiff = t2 - t1 if tDiff < 0: tDiff += (1 << 32) return tDiff
def ensure_filepath(f_path): """ Definition: Ensures the filepath has a slash at the end of the string. Args: f_path: Required. The string filepath. Returns: The filepath with a slash at the end. """ if f_path[-1] != '/': f_path = f_path + '/' return f_path
def partition(l, condition): """Returns a pair of lists, the left one containing all elements of `l` for which `condition` is ``True`` and the right one containing all elements of `l` for which `condition` is ``False``. `condition` is a function that takes a single argument (each individual e...
def get_rates(actives, scores): """ :type actives: list[sting] :type scores: list[tuple(string, float)] :rtype: tuple(list[float], list[float]) """ tpr = [0.0] # true positive rate fpr = [0.0] # false positive rate nractives = len(actives) nrdecoys = len(scores) - len(actives) ...
def rotate(string, n): """Rotate characters in a string. Expects string and n (int) for number of characters to move. """ if n > 0: return (string[n:]+string[0:n]) return (string[-abs(n):]+string[0:len(string)-abs(n)])
def match_word(encoded_word, words_list): """ Find first probably correct word based on list of words and given encoded word. """ results = [] for word in words_list: #skip all items with different first and last char if word[0] != encoded_word[0] or word[-1] != encoded_word[-1]:...
def pack_offset(plane_index, offset=None): """ Get MSR value that writes (or read) offset to given plane :param plane: voltage plane index :param offset: voltage offset as hex string (omit for read) :return value as long int ready to write to register # Write >>> from undervolt import pack_...
def addr_little_endian(addr, n_bytes): """`to_bytes(4, byteorder='little')` was buggy for some reason""" mask = 0xff ans = [] for i in range(n_bytes): x = addr & mask for j in range(i): x = x >> 8 ans.append(x.to_bytes(1, byteorder='big')) mask = mask << 8 ...
def create_utterance(intent, utterance, *labels): """ Add an example LUIS utterance from utterance text and a list of labels. Each label is a 2-tuple containing a label name and the text within the utterance that represents that label. Utterances apply to a specific intent, which must be specified....
def rpartition(L, sep, key=None): """\ partition(list, sep, key) -> (head, sep, tail) Search for the separator sep in list, starting at the end of list, and return the part before it, the separator itself, and the part after it. If the separator is not found, return an empty list, None, and the list. key specifi...
def normalize(number): """ Clamps a number to be -1, 0, or 1. """ if number == 0: return int(number) return int(number / abs(number))
def max_nonadjacent_sum(values): """Finds the maximum sum of nonadjacent values.""" taken = skipped = 0 for val in values: taken, skipped = skipped + val, max(taken, skipped) return max(taken, skipped)
def dataset_size_for_mode(mode): """Returns the number of training examples in the input dataset.""" if mode == 'test': return 50000 elif mode == 'train': return 1281167 elif mode == 'l2l_valid': return 50046 elif mode == 'l2l_train': return 1281167 - 50046 else: raise ValueError('Invali...
def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. """ try: return str(e) except UnicodeError: pass try: return repr(e) except UnicodeError: pass return u'Unrecoverably corrupt eval...
def expected(a, b): """ Calculate expected score of A in a match against B :param a: Elo rating for player A :param b: Elo rating for player B """ return 1 / (1 + 10 ** ((b - a) / 400))
def height_from_nipple_width(segment_length): """ Calculates body height based on the horizontal distance between nipples args: segment_length (float): horizontal distance between nipples Returns: float: total body height """ if segment_length <= 0: raise ValueError('se...
def rotations(T): """ This method returns a list of rotations for a string T""" ## Take twice the string then slide a window of len(string) TT = T*2 return [ TT[i:i+len(T)] for i in range(0, len(T))]
def mag2flux(mag): """ Convert from magnitude to flux using scaling relation from aperture photometry. This is an estimate. Parameters: mag (float): Magnitude in TESS band. Returns: float: Corresponding flux value """ return 10**(-0.4*(mag - 20.54))