content
stringlengths
42
6.51k
def seqtostr(value): """ Writes a sequence as a comma delimited string. """ output = ""; if not value: return output; for i in value: output += str(i) + ", "; # Trim the last two characters. return output[:-2];
def errorMessage(err, location = None): """ Generate a standard error message. Parameters ---------- err : str The error message. location : str, optional Where the error happens. E.g. CTL.funcs.funcs.errorMessage Returns ------- str The generated error ...
def roman(x): """Incomplete.""" tens = x // 10 rem = x % 10 repl = { 1: "I", 2: "II", 3: "III", 4: "IV", 5: "V", 6: "VI", 7: "VII", 8: "VIII", 9: "IX", 0: "", } return 'X' * tens + repl[rem]
def combine(x,y): """ Combines Testclasses X and Y Returns (NewElement or None, Delete X from Worklist, Delete Y from Worklist) Any Class that replaces an essential class is itself essential. """ deleteX = True deleteY = True merge = False workout = [] for i in range(len(x)): ...
def _format_badge_name(package_name, badge_name, commit_number): """Formats the badge name (assumes package_name is whitelisted).""" if badge_name: return badge_name if 'github.com' in package_name: return 'compatibility check (master)' else: return 'compatibility check (PyPI)'
def transform_bbox_s2s_to_coco(bbox): """Function that rearranges bbox annotations from Street2Shop format to COCO""" return [bbox["left"], bbox["top"], bbox["width"], bbox["height"]]
def get_source_tag (aligned_dict, src_word_tag_dict): """Get the aligned (source) tag for each word in each sentence of target language from a source language""" tar_tag_dict = {} # create a dict to store predicted tag for tar language print("get source") for sentence_cnt in aligned_dict.keys(): ...
def _none_to_dict(name, val, cache_manager=None): """Transform input kwarg to valid dict, handling sentinel value. Accepts a single kwarg. Args: name: the kwarg name val: the kwarg value to ensure is proper format for kwargs. cache_manager: if None, do nothing. If a value, add to k...
def min_int(la, lb, ia, ib, tol=0.01): """ Given two complete drillholes A, B (no gaps and up to the end of the drillhole), this function returns the smaller of two intervals la = FromA[ia] lb = FromB[ib] and updates the indices ia and ib. There are th...
def get(a, i): """Retrieve the i-th element or return None""" return a[i] if len(a) > i else None
def apply_ops(input, ops): """ Apply series of operations in order on input. `ops` is a list of methods that takes single argument as input (single argument functions, partial functions). The methods are called in the same order provided. """ output = input for op in ops: output = op...
def calculate_hounsfield_unit(mu, mu_water, mu_air): """ Given linear attenuation coefficients the function calculates the corresponding Hounsfield units. :param mu: Attenuation coefficient to determine corresponding Hounsfield unit. :param mu_water: Constant linear attenuation coefficient for water...
def is_int_even_v03(num): """ Use the modulo operator to evaluate whether an integer provided by the caller is even or odd, returning either True or False. Parameters: num (int): the integer to be evaluated. Returns: is_even (boolean): True or False depending on the modulo check ...
def crossunder(x, y): """ Last two values of X serie under over Y serie. """ return x[-1] < y[-1] and x[-2] > y[-2]
def split_n_parts(text, n = 2): """ Splits a given text into a list of sub texts of size n each Keyword arguments: text -- the text to be split n -- size of sub-text """ if n > text.__len__(): print("Error! Sub text size is greater than text!") return else: ...
def duplicate_encode(word): """ converts a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. :param word: a string input. :return: a new string with ...
def _findLine(comp, fileLines): """ Find a line number in the file""" # Line counter c = 0 # List of indices for found lines found = [] # Loop through all the lines for line in fileLines: if comp in line: # Append if found found.append(c) # Increse the...
def solution1(candidates, target): """ fn(candidates, target) if target < 0 -> None if target == 0 -> [] if target > 0 -> for each n in candidates, result is [n] + fn(candidate, target - n) """ def fn(candidates, target): allSum = sum(candidates) ans = set() ...
def prob_win_deuce(p: float) -> float: """Given probability, p, that server wins a point, returns the probability that the server will win deuce if it happens Args: p (float): probability server wins a point Returns: float: probability that server will win deuce """ # returns t...
def _ternary_search_domain(f, domain): """Trinary search: minimize f(x) over a domain (sequence). Works assuming f is quasiconvex and domain is ascending sorted. BUGGY, DO NOT USE >>> arr = np.concatenate([np.arange(10, 2, -1), np.arange(2, 20)]) >>> t1 = _ternary_search_domain(lambda t: arr[t], ...
def parse_args_and_kwargs(cmdline): """ cmdline: list returns tuple of: args (list), kwargs (dict) """ # Parse args and kwargs args = [] kwargs = {} if len(cmdline) > 1: for item in cmdline[1:]: if '=' in item: (key, value) = item.split('=', 1) ...
def add_nipsa_action(index, annotation): """Return an Elasticsearch action for adding NIPSA to the annotation.""" return { "_op_type": "update", "_index": index, "_type": "annotation", "_id": annotation["_id"], "doc": {"nipsa": True} }
def _complete_email(name): """If the name does not include '@', append '@chromium.org'.""" if '@' not in name: return name + '@chromium.org' return name
def normalize_alef_maksura_hsb(s): """Normalize all occurences of Alef Maksura characters to a Yeh character in a Habash-Soudi-Buckwalter encoded string. Args: s (:obj:`str`): The string to be normalized. Returns: :obj:`str`: The normalized string. """ return s.replace(u'\u00f...
def normalize_spec(spec): """Return the spec with all ranges normalized.""" # XXX finish! return spec
def number_to_digits(number, base): """Convert a positive number to its digit representation in base.""" digits = [] while number > 0: digits.insert(0, number % base) number = number // base return digits
def pretty_print(x, numchars): """Given an object `x`, call `str(x)` and format the returned string so that it is numchars long, padding with trailing spaces or truncating with ellipses as necessary """ s = str(x) if len(s) > numchars: return s[:(numchars - 3)] + '...' else: ...
def _map_args_test(x: float, y: float=2, z: float=3) -> float: """A test function for the map_args function. Returns the sum of x, y, z""" return x + y + z
def is_ptype(p): """Checks whether a parameter is in the form `p0`, `p1`, etc.""" return str(p)[0] == "p" and str(p)[1:].isdigit()
def common_from_start(sa, sb): """ returns the longest common substring from the beginning of sa and sb """ def _iter(): for a, b in zip(sa, sb): if a == b: yield a else: return return ''.join(_iter())
def _JSONToCString16(json_string_literal): """Converts a JSON string literal to a C++ UTF-16 string literal. This is done by converting \\u#### to \\x####. """ c_string_literal = json_string_literal escape_index = c_string_literal.find('\\') while escape_index > 0: if c_string_literal[escape_index + 1] ...
def get_old_and_new_values(change_type, message): """ Parses the payload and finds previous and current value of change_type.""" values_map = { 'assigned_to': 'users', 'status': 'status', 'severity': 'severity', 'priority': 'priority', 'milestone': 'milestone', 't...
def get_head_block_args(n_classes: int, num_feature_maps: int, avgpool_target_size=(1, 1), buffer_reduction=None): """ Wrap the args for the head block into a dict. Check Config classes for arg doc string :param n_classes: number of classes :param num_feature_maps: number of feature maps of the conv...
def normalize_file_path(path): """Remove '/' at the end of file path if necessary. """ return path.rstrip('/')
def aggregate_reviews(review_list): """Combine all reviews into one string.""" tokens = "" for i in review_list: tokens += i # print(i) return tokens
def gasKgKgMoistToDry(q,qh2o): """ Take Kg/Kg moist air to Kg/Kg dry air """ r = q/(1-qh2o) return r
def pureDependency(dependency:str) -> str: """ Get the name of package Parameters ---------- dependency : str package Returns ------- str a name of package without the version >>> pureDependency('package==1.2.3') 'package' """ dependency = dependency....
def render_items(items): """ Render a sequence of pairs or an `OrderedDict` as a HTML list. The function skips the items whose values are `None` or `False`. :param items: a sequence of items :type items: list or tuple or OrderedDict :return: rendered content :rtype: str """ if isin...
def highlander(iterable): """check only single True value in iterable""" # There Can Be Only One!!! i = iter(iterable) return any(i) and not any(i)
def order_slaves_on_gtid(slaves): """Function: order_slaves_on_gtid Description: Take a Slave array and sort them on their GTID positions, with the top(first) slave being the best Slave. Arguments: (input) slaves -> Slave instance array. (output) slave_list -> List of slaves in ...
def calc_sums(variable): """ Aggregates the instance dimension of the variable tensor object (see documentation in ../process_raw_data.py) by summing up the values of the instances. note: this function is called after the database check -> all values are available and valid. :param variable: data s...
def bit_low(value, bit): """ Returns whether the bit specified is set low in value e.g. bit_high(64, 6) == False (64 = 0b01000000, so bit 6 is high) bit_high(64, 2) == True """ return value & (1 << bit) == 0
def format_system_name(input): """ Format the given system data into a full name Args: input: A dictionary containing keys of SectorName, L1, L2, L3, MCode, N1 and N2 Returns: A string containing a system name of the form "Sector AB-C d1-23" or "Sector AB-C d1" """ if input is None: return None...
def float_array_to_str(array_of_floats): """ Convert a float numpy array to a string for printing purposes. """ str_float_array = '[' + ' '.join(['%.3f' %(val) for val in array_of_floats]) + ']' return str_float_array
def fewest_neighbors(node, neighbors): """Return the neighbor of this node with the fewest neighbors.""" edges = [(n, len(neighbors[n])) for n in neighbors[node]] edges.sort(key=lambda n: n[1]) return edges[0][0]
def isdouble(dtype): """Check if ``dtype`` is double precision. """ return dtype in ('float64', 'complex128')
def col_letter(col): """Return column letter for given column.""" return chr(ord("A") + col - 1)
def _insert_idxs(feature_centre, feature_size, dimensions): """Returns the indices of where to put the signal into the signal volume Parameters ---------- feature_centre : list, int List of coordinates for the centre location of the signal feature_size : list, int How big is the s...
def clamp(v, lo, hi): """Return v clamped to range [lo, hi]. >>> clamp(1, 2, 3) 2 >>> clamp(4, 0, 1) 1 >>> clamp(6, 5, 8) 6 """ assert lo <= hi if v < lo: return lo elif v > hi: return hi else: return v
def temperature(cell): """ Returns the temperature (in degrees Celsius) for the given integer index ``cell``. """ temperatures = { 1: 37.0, 2: 37.0, 3: 37.0, 4: 37.0, 5: 37.0 } return temperatures[cell]
def deposit_failed_ipn(path: str) -> tuple: """ **deposit_failed_ipn** :param path: organization_id :return: "OK", 200 """ return "OK", 200
def get_wanted_position(prefix='', rconn=None): """Return wanted Telescope RA, DEC as two floats in degrees On failure returns None""" if rconn is None: return try: wanted_ra = float(rconn.get(prefix+'wanted_ra').decode('utf-8')) wanted_dec = float(rconn.get(prefix+'wanted_dec...
def migrate_node(name, src, dest, dry_run=True, batchmode=True): """ Migrate a node from src NodeMeister to dest NodeMeister. If dry_run is True, only show a diff, do not make changes. If batchmode is True, don't show a diff or ask for input, just make the changes if possible, regardless of curren...
def xor(a, b): """Compute the xor of two arrays >>> xor([1,0,1], [0, 1, 0]) [1, 1, 1] """ assert len(a) == len(b) return [x ^ y for (x, y) in zip(a, b)]
def print_slot_predictions(distribution, slot_values, target_slot, threshold=0.05): """ Prints all the activated slot values for the provided predictions """ predicted_values = [] for idx, value in enumerate(slot_values): if distribution[idx] >= threshold: predicted_values += ((...
def slash_at_the_end(path, slash=0): """ slash_at_the_end: make sure there is (or not) a slash at the end of path name :param path: :param slash: :return: """ if slash == 0: if path[-1:] == '/': path = path[:-1] if slash == 1: if not path[-1:] == '/': ...
def humanReadableSize(sizeInBytes): """ from http://stackoverflow.com/questions/1392413/calculating-a-directory-size-using-python get size from bytes to human readable format :param sizeInBytes: siz in bytes :return: human readable string """ B = "B" KB = "KB" MB = "MB" GB = "GB"...
def generate_endpoints(dataset_key, system): """Generate Endpoints""" create_endpoint = "http" upload_endpoint = "http" if system == "production": create_endpoint += ( "s://databank.illinois.edu/api/dataset/" + dataset_key + "/datafile" ) upload_endpoint += "s://datab...
def mmat(st1, yt, t): """returns modified moving average for a t-period MMA and incremental value""" return (st1 * (t - 1) + yt ) / t
def rivers_with_station(stations): #sam """ Function that returns a set of names of rivers that have an associated monitoring station. """ List_of_rivers =set() #initialate a new empty set for s in stations: #loop in side the sta...
def mask_sequence(seq, maskchar, fpos, tpos): """Given a sequence, mask it with maskchar starting at fpos (including) and ending at tpos (excluding) """ if len(maskchar) > 1: raise RuntimeError("Internal error: more than one character given to mask_sequence") if fpos < 0: fpos = 0 ...
def build_person(first_name, last_name, age=None): """Return a dictionary of information about a person.""" person = {'first': first_name, 'last': last_name} if age: person['age'] = age return person
def reverse(s): """reverses the string """ result = '' for i in range(len(s)-1, -1, -1): result = result + s[i] return(result)
def trim_tokens_predtags(tokens, tags): """Remove the '[CLS]' token and corresponding tag as well as the everything starting from the first '[SEP]' token and corresponding tags. """ sep_idx = tokens.index("[SEP]") return tokens[1:sep_idx], tags[1:sep_idx]
def filter_spec(fw_spec): """Filter away internal parameters of a firework""" include_keys = [ '_fworker', '_category', '_preserve_fworker', ] new_dict = {} for key, value in fw_spec.items(): if (key in include_keys) or (not key.startswith('_')): new_dict[...
def collided_with_level(enemy_state, previous_position): """ Called whenever the player bumps into a wall. Usually, you just want to set enemy_state["position"] = previous_position :param enemy_state: Our state :param previous_position: Where were we before be bumped into the wall? :ret...
def dot_join(*keys): """remove Nones from the keys, but not '', """ _ = [k for k in keys if k is not None] if not _: return None return ".".join(_)
def default(val, default): """Default to a given value if another given value is falsy. Equivalent to Djangos' default. Args: val (mixed): A mixed value that is truthy or falsy. default (mixed): A default replacement value. Returns: mixed: The default given value, or the origi...
def compare(a, b): """ Return the # of characters of difference between the 2 strings """ return sum(1 for x,y in zip(a,b) if x!= y)
def encode_wsgi_path(s): """Encodes an URL path from internal format for use in WSGI""" bytestring = s.encode('utf-8', errors='surrogateescape') return bytestring.decode('latin-1')
def map_accum_right(function, accumulator, list): """The mapAccumRight function behaves like a combination of map and reduce; it applies a function to each element of a list, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new list....
def roll_uint8(value): """Roll given one-byte value, i.e. increment it such that the range is preserved. >>> roll_uint8(-10) ValueError: Acceptable range: 0 - 255 >>> roll_uint8(-1) ValueError: Acceptable range: 0 - 255 >>> roll_uint8(0) 1 >>> roll_uint8(10) 11 >>> roll_uint8...
def _isnone(x): """Convenience hack for checking if x is none; needed because numpy arrays will, at some point, return arrays for x == None.""" return type(x) == type(None)
def _issubclass(a, b): """Determines if ``a`` is a subclass of ``b``. Similar to issubclass, but returns False instead of an exception if `a` is not a class. """ try: return issubclass(a, b) except TypeError: return False
def find_between(in_str, start='>', end='<'): """ Find string between two search patterns. """ return in_str.split(start)[1].split(end)[0]
def parse_user_params(default_params=None, user_params=None): """ Parse a comma-separated list of key=value parameters, and populate a dictionary with the values. Enter: default_params: a dictionary with the default values. Only parameters listed in the dictionary are set. ...
def limit_signal(signal: int) -> int: """Limit the signal to a value in the possible range.""" return max(0, signal % 65536)
def get_files(submission_json): """ find the json files blob since in can be in several different places """ upload_fields = [ 'addendaUploads', 'optionalUploads', 'requiredUploads', 'uploads' ] uploads = [] submission_data = submission_json.get('data') for field ...
def tell_size(obj, word, suffix="s"): """Useful when you want to write a message to the user. :param obj: The object being described. :type obj: Anything that works with the len() function. :param word: Word to use to describe the object. :type word: ``str`` :param suffix: What to append to the...
def pack_size(size_str): """This function returns the pack size in bytes from a given string. A negative number will be returned on fail. """ if len(size_str)<3: return -1 multiplier = size_str[-2:] # KB, MB or GB try: size_base = float(size_str[:-2]) except ValueError: ...
def uniq(lst): """Return a list with unique elements (but preserved order).""" new = [] seen = set() for item in lst: if item not in seen: new.append(item) seen.add(item) return new
def clean_json_keys(jsonobj): """If metadata keys have periods in them, Clowder will reject the metadata. """ clean_json = {} for key in jsonobj.keys(): try: jsonobj[key].keys() # Is this a json object? clean_json[key.replace(".","_")] = clean_json_keys(jsonobj[key]) ...
def pronic(number) -> bool: """It will check whether the entered number is a pronic number.""" flag = 0 n = number for i in range(0, n): if(i*(i+1) == n): flag = 1 break if(flag == 1): return True else: return False
def use_processors(n_processes): """ This routine finds the number of available processors in your machine """ from multiprocessing import cpu_count available_processors = cpu_count() n_processes = n_processes % (available_processors+1) if n_processes == 0: n_processes = 1 print...
def tally(predicate, iterable): """Count how many times the predicate is true. Taken from the Python documentation. Under the PSF license. :param predicate: Predicate function. :param iterable: Iterable sequence. :returns: The number of times a predicate is true. """ return sum(map(pre...
def nearest_square(limit): """ Find the largest square number smaller than limit. """ answer = 0 while (answer+1)**2 < limit: answer += 1 return answer**2
def removeURL( s ): """Removes all URLs from the string s.""" keep = [] for w in s.split(): if ( not "http" in w ): keep.append(w) return " ".join(keep)
def _isFunction(v): """ A utility function to determine if the specified value is a function. """ return v is not None and hasattr(v, "__call__")
def lineDefinesNewIx(line): """Checks if a line of code in the game file defines an IFP object with a new index """ return ( " Thing(" in line or " Surface(" in line or " Container(" in line or " Clothing(" in line or " Abstract(" in line or " Key(" in line ...
def validate(config): """ Validate the beacon configuration """ vcfg_ret = True vcfg_msg = "Valid beacon configuration" if not isinstance(config, list): vcfg_ret = False vcfg_msg = "Configuration for imgadm beacon must be a list!" return vcfg_ret, vcfg_msg
def number_axles(num_axles): """Numbers the axles starting with 1.""" axle_num = [] for i in range(num_axles): axle_num.append(i+1) return axle_num
def _poa_sky_diffuse_pv(f_x, dhi, vf_shade_sky_integ, vf_noshade_sky_integ): """ Sky diffuse POA from integrated view factors combined for both shaded and unshaded parts of the surface. Parameters ---------- f_x : numeric Fraction of row slant height from the bottom that is shaded. [uni...
def unquoted_line(line): """ Unquotes an e-mail message line according to RFC 3676. :param line: The (possibly quoted) message line. :return: (unquoted line, quote depth). """ quote_depth = 0 while line.startswith('>'): line = line[1:] quote_depth += 1 return line, quote...
def probability_distribution(fd: dict): """ Takes a frequency distribution and converts it to a probability distribution. fd (dict): frequency distribution of characters in a text """ total = sum(fd[x] for x in fd) return {x: fd[x] / total for x in fd}
def int_or_zero(v): """ Convert object to int """ if isinstance(v, str): v = v.strip() try: return int(v) except (ValueError, TypeError): return 0
def get_nested_value(d, key): """Return a dictionary item given a dictionary `d` and a flattened key from `get_column_names`. Example: d = { 'a': { 'b': 2, 'c': 3, }, } key = 'a.b' will return: 2 """ if '.' not...
def CalcVersionValue(ver_str="0.0.0"): """Calculates a version value from the provided dot-formated string 1) SPECIFICATION: Version value calculation AA.BBB.CCC - major values: < 1 (i.e 0.0.85 = 0.850) - minor values: 1 - 999 (i.e 0.1.85 = 1.850) - micro values: >= 1000 (i.e 1.1...
def flatset(iterables): """Return a set of the items in a single-level flattening of iterables >>> flatset([1, 2], [2, 3]) set(1, 2, 3) """ return set(item for iterable in iterables for item in iterable)
def index_to_bytes(i): """ Map the WHATWG index back to the original BIG5 bytes. """ lead = i // 157 + 0x81 trail = i % 157 offset = 0x40 if trail < 0x3f else 0x62 return (lead, trail + offset)
def strip_headers(data): """ Strips headers from data #depreciate""" try: return data['items'] except (TypeError, KeyError) as e: print(e) return data