content
stringlengths
42
6.51k
def get_same_padding(kernel_size): """Return SAME padding size for convolutions.""" if isinstance(kernel_size, tuple): assert len(kernel_size) == 2, 'invalid kernel size: %s' % kernel_size p1 = get_same_padding(kernel_size[0]) p2 = get_same_padding(kernel_size[1]) return p1, p2 ...
def get_section_coordinates(row, cell): """ returns all the cells in the section that contains row, cell, without returning row, cell without returning any cells in row or cell """ return_coordinates = [] row_start = int(row / 3) * 3 cell_start = int(cell / 3) * 3 ...
def update(existing_aggregate, new_value): """ # for a new value new_value, compute the new count, new mean, the new M2. # mean accumulates the mean of the entire dataset # M2 aggregates the squared distance from the mean # count aggregates the number of samples seen so far """ (count, mean,...
def get_biased_probs(n: int, idx: int = -1, prob: float = 0.5) -> list: """ get_biased_probs [summary] Calculate the biased probability for all elements of an array so that the <idx> value has <prob> probability of being drawn in respect to the remaining values. https://github.com/int-br...
def u1u2(u1): """ mm to inch, all strings """ return str(round(float(u1)/25.4, 2))
def leftrotate_64(x, c): """ Left rotate the number x by c bytes, for 64-bits numbers.""" x &= 0xFFFFFFFFFFFFFFFF return ((x << c) | (x >> (64 - c))) & 0xFFFFFFFFFFFFFFFF
def substitute_entry(dict_list, new_entry, criteria, allowed_addition=False): """substitute a dic entry in a _dict_list_ with *new_entry* using *criteria* key as an index if *allowed_addition* the new entry will be added if *criteria* value does not exists""" entry_exists = len([X for X in dict_list if X[cr...
def wcs(i, crpix, crval, cdelt): """calculate coordinates from WCS data""" return crval + (float(i + 1) - crpix) * cdelt
def multiply(a, b): """Multiply x and y""" b += 1 print (a, b) pepe = a * b print (pepe) return pepe
def text_cleaner(text: str): """ Removes \r and \n from a text string. :param text: (str) the text you want cleaned. :returns: (str) the cleaned text """ text = text.replace("\r", "") text = text.replace("\n", " ") return text
def has_other_useful_output(content_text): """Returns whether |content_text| has other useful output. Namely, console errors/warnings & alerts/confirms/prompts. """ prefixes = ('CONSOLE ERROR:', 'CONSOLE WARNING:', 'ALERT:', 'CONFIRM:', 'PROMPT:') def is_useful(line): retu...
def subtract(x, y): """Sub two numbers""" return (y-x)
def bitset(bits, bset): """Checks if all bits are set in bset or bits is zero.""" return bits == (bits & bset)
def mean(num_list): """ Computes the mean of a list Parameters ---------------- num_list: list List to calculate mean of Returns ---------------- mean: float Mean of list of numbers """ #Check that input is type list if not isinstance(num_list, list): ...
def process_tweet(text, target): """Check it's ok and remove some stuff""" if (text.startswith("RT ") or "@" in text or "#" in text or "http" in text): return None text_lower = text.lower() if target.lower() not in text_lower: return None exclude...
def parse_cmd(line): """ Parses a command """ tokens = [t.strip() for t in line.split()] return tokens[0], tokens[1:]
def create_monitored(monitor): """Create a dictionary for monitoring""" # Build a structure for monitored variables monitored = {} for k in monitor: monitored[k] = list() return monitored
def search(position, data, service): """Find the correct value in the json data file. Args: position: The position ID number. data: The JSON list which is requested from the API. service: Type of dataclass. Returns: The value that corresponds to the specified position. ...
def get_epochs_with_optional_tqdm(tqdm_mode, nepochs): """Get epochs with optional progress bar. Args: tqdm_mode (str): Progress bar mode. nepochs (int): Number of epochs. Returns: iterable: Epochs. """ if tqdm_mode == "tqdm": from tqdm import tqdm epochs =...
def get_alphas(revision_str): """Return a tuple of the first non-digit characters of a revision (which may be empty) and the remaining characters.""" # get the index of the first digit for i, char in enumerate(revision_str): if char.isdigit(): if i == 0: return '', re...
def filter_values(function, dictionary): """Filter ``dictionary`` by its values using ``function``.""" return {k: v for k, v in dictionary.items() if function(v)}
def sanity_check(): """ Perform an initial sanity check before doing anything else in a given workflow. This function can be used to verify importing of modules that are otherwise used much later, but it is better to abort the pilot if a problem is discovered early. :return: exit code (0 if all...
def getDimension(data, dim): """ Read in first element of a netcdf dimension...if there's an exception return False. We have some optional dimension data, this makes the code cleaner """ haveIt = False try: data.getDimensionValue(dim, 0) haveIt = True except:...
def convertToAnyBase(n, base): """ Converts n to whichever base is indicated. Algorithm can be found here: https://en.wikipedia.org/wiki/Negative_base#Calculation """ characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" i = 0 s = '' if n > 0: while n != 0: remainder = n % base n //= base if r...
def _pressure_factor(pressure_units_in: str, pressure_units_out: str) -> float: """helper method for convert_pressure""" factor = 1.0 if pressure_units_in == 'psf': pass elif pressure_units_in == 'psi': factor *= 144 elif pressure_units_in == 'Pa': factor /= 47.880172 eli...
def parse_version(version): """ _parse_version_ Parse semantic major.minor.micro version string :param version: X.Y.Z format version string :returns: dictionary containing major, minor, micro versions as integers """ split = version.split('.', 2) return { 'major': int(spl...
def HV(in_: list): """ Outputs H-V, computes difference of first 2 elements of a list. """ out = in_[0] - in_[1] return out
def evaluate(x, *args, **kwargs): """Evaluates a callable or constant value. Args: x: Either a callable or a constant value. *args: Positional arguments passed to `x` if `x` is callable. **kwargs: Keyword arguments passed to `x` if `x` is callable. Returns: Either the result of calling `x` if `x...
def hash_route(route): """ Given a route as a list of stops and times, compute a silly hash for it""" # Empirically, sometimes you can get the same route multiple times # with slightly different times, for the hash, just check the start time # along with the stops for the remainder # # Original ...
def stress_score(wap, threshold_power, duration): """Stress Score Parameters ---------- wap : number WAP or xPower threshold_power : number FTP or CP duration : int Duration in seconds Returns ------- ss """ ss = (duration / 3600) * (wap / threshold...
def remove_duplicates(datatype, input_list): """Remove duplicates from list""" if datatype == "stocks": return input_list if datatype == "currency": currencies = [] output_list = [] # get unique currencies for temp_loop in input_list: currencies.append(te...
def float2sci(num): """mpl has a better way of doing this?""" _, exnt = '{:.0e}'.format(num).split('e') exnt = int(exnt) if exnt == 0: # 10 ** 0 = 1 retv = '' else: retv = r'$10^{{{:d}}}$'.format(exnt) return retv
def isDecimalPalindrome(num): """assumes num is an integer returns True if num in decimal form is a palindrome, else False""" return str(num) == str(num)[::-1]
def restrict(d, languages=['en', 'de']): """Restrict a dictionary with the labels or aliases to the specified languages only""" # lang = ['en', 'de', 'zh', 'hi', 'es', 'fr', 'ar', 'bn', 'ru', 'pt', 'id'] return dict((k, v) for (k, v) in d.items() if k in languages)
def convert_perm(perm): """If the perm is a int it will first convert it to a string and back to an oct int. Else it just converts it to oct. """ if isinstance(perm, int): return int(bytes(perm), 8) else: return int(perm, 8)
def col_full(nblocks, optlevel): """Compute the optimizations to be done for full indexes.""" optmedian, optstarts, optstops, optfull = (False,) * 4 # Full case if nblocks <= 1: if 0 < optlevel <= 3: optmedian = True elif 3 < optlevel <= 6: optmedian, optstarts ...
def get_center_and_radius(points): """ Calculate bounding box of points in polyline and return center and diameter of fitting circle :param points: Points in the polyline :return: center of circle (x,y) and radius """ x_coordinates, y_coordinates = zip(*points) x_min = min(x_coordinates) ...
def _max_len(tree_list): """Calculates max length of tree's strings""" max_len = 0 for row in tree_list: if len(row) > max_len: max_len = len(row) return max_len
def completions_sorting_key(word): """key for sorting completions This does several things: - Lowercase all completions, so they are sorted alphabetically with upper and lower case words mingled - Demote any completions starting with underscores to the end - Insert any %magic and %%cellmagic...
def parse_args(args): """Parse command line parameters Args: args (List[str]): command line parameters as list of strings (for example ``["--help"]``). Returns: :obj:`argparse.Namespace`: command line parameters namespace """ keys = [] values = [] for asset in args: ...
def extract_frags_gemid(gem_list): """ Extract necessary information from input gem. Args: gem_list (list): list with 10 items as encoded in PlinePgem file Returns: frags (list of list): [chrom,start,end] for each fragment gem_id (string): GEM ID """ raw_frags = gem_list[4...
def find_all_copies(tofind,data): """ Finds all occurences of a string in a longer string Arguments: tofind - the string to find data - contains the data to look for all occurences of 'tofind' Return: An array with all locations """ position = 0 positions = [] searchstringlen = len(tofind) maxlen = len(da...
def _isinstance_listlike(x): """Returns True if x is an iterable which can be transformed into a pandas Series, False for the other types of possible values of a `hover_data` dict. A tuple of length 2 is a special case corresponding to a (format, data) tuple. """ if ( isinstance(x, str) ...
def decode(bytestring): """ Decode a bytestring if possible, return str if not. Only bytestring has .decode() method. This utility provides a way to homogenize values that may be bytestring or unicode string (such as the attributes in h5py v2.x and v3.x). """ try: return bytestring.dec...
def Color(red, green, blue, white = 0): """Convert the provided red, green, blue color to a 24-bit color value. Each color component should be a value 0-255 where 0 is the lowest intensity and 255 is the highest intensity. """ return (white << 24) | (red << 16)| (green << 8) | blue
def time_to_sample_number(seconds, frequency): """ Convert time to sample number. Parameters ---------- seconds : int, float The input time in seconds. frequency : int, float The input frequency. Returns ------- float The converted sample number. """ ...
def transform_mem(values): """Transform the output of lists to something more manageable. :param list values: The list of values from `SHOW MEM` :rtype: dict """ output = {} for value in values: output[value['name']] = {k: v for (k, v) in value.items() ...
def csv(options): """Format TikZ options. Parameters ---------- options : dict TikZ options, where spaces in keys are represented by underscores. Returns ------- str Comma-separated key-value pairs in TikZ format. """ return ', '.join(key.replace('_', ' ') +...
def gasMassForFloat(currentAltitude, floatingAltitude, gasMassAtInflation, gasMassAtFloatingAltitude, ventStart=500): """ Returns the gas mass profile to simulate the valves venting air to reach floating conditions. This method should only be used for floating flights. Parameters ---------...
def _make_even(n): """Return largest even integer less than or equal to `n`.""" return (n >> 1) << 1
def array_from_shitstring_floats(shitstring) -> list: """ Returns a list of numbers from a nasty formatted copied-from-Webassign string (same as above, just raw string as input) """ string = shitstring.strip() string_array = string.split() number_array = [] for number in string_array: ...
def get_ubids(chip_specs): """ Return all ubids from supplied chip-specs """ return [ts['ubid'] for ts in chip_specs]
def simulation_paths(sim_id, conf): """ Get paths to simulation files. :param sim_id: the simulation id :param conf: configuration """ return {'log_path' : conf['logs_path'] + '/' + sim_id + '.log' , 'json_path' : conf['jobs_path'] + '/' + sim_id + '.json', 'state_p...
def effective_energy(n, gv_energy): """ Calculate and return the value of effective energy using given values of the params How to Use: Give arguments for n and gv_energy parameters *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD T...
def slowest_speed(speed_list): """ Compute the derived speed by finding the slowest object in the speed_list. :param speed_list: A list of objects with a speed_mb attribute. :returns: Speed as an integer. """ speed_mb = 0 if speed_list: for obj in speed_list: if not spee...
def limit_offset_query(query, limit=None, offset=None): """Apply limit and offset to the query. :param query: SQLAlchemy Query :type query: sqlalchemy.orm.Query :param limit: Limit number of Items returned, defaults to None :type limit: int, optional :param offset: Specify the offset of the fir...
def round_to_two_places(num): """Return the given number rounded to two decimal places. >>> round_to_two_places(3.14159) 3.14 """ # Replace this body with your own code. # ("pass" is a keyword that does literally nothing. We used it as a placeholder # because after we begin a code bloc...
def calc_recall(tp: int, fn: int) -> float: """Calculate recall. Args: tp (int): amount of TP. fn (int): amount of FN. Returns: float: recall for the given amounts of TP and FN. """ if tp + fn != 0: recall = float(tp / (tp + fn)) else: # prevent zero div...
def Pretty(path): """Removes 'end_snippet.' prefix if present. Args: path: the path to remove prepended 'end_snippet' from. Returns: The path de-cluttered with informationless 'end_snippet' prefix. """ if path.startswith("end_snippet."): path = path[len("end_snippet."):] return path
def add_leading_zeroes(num, numdigits): """Returns a stringified num with zeros prepended until it is at least numdigits digits long.""" return str(num).zfill(numdigits)
def get_filename(problem): """Returns filename in the form `001.py`""" return '{:03d}.py'.format(problem)
def _parseBioBy(l): """Return a list of biographies.""" bios = [] biosappend = bios.append tmpbio = [] tmpbioappend = tmpbio.append joiner = ' '.join for line in l: if line[:4] == 'BG: ': tmpbioappend(line[4:].strip()) elif line[:4] == 'BY: ': if tmpbi...
def get_surt_association_script(surt, sheet): """Creates the beanshell script for a SURT->Sheet association.""" return "appCtx.getBean(\"sheetOverlaysManager\").addSurtAssociation(\"%s\", \"%s\" );" % (surt, sheet)
def updateGlobals(newGlobals, oldGlobals): """ Compare the old globals against the new ones and returns the old globals with the new globals that did not existed previously :param newGlobals: All new globals :param oldGlobals: All old globals :return: A list of globals as strings. """ if...
def inner_join(predicate, xs, ys): """Takes a predicate pred, a list xs, and a list ys, and returns a list xs' comprising each of the elements of xs which is equal to one or more elements of ys according to pred. pred must be a binary function expecting an element from each list. xs, ys, and xs' are...
def write_sim_output(t, sim_out, env, measurements, estimate, cmd, rover_state): """ Writes the state of the simulation over time for convenient post-processing and visualization. Currently stores :param t: Simulation time, seconds :param sim_out: Prior sim_out dictionary. Use None for initialization ...
def astuple(x): """Returns x or (x,)""" return x if isinstance(x,tuple) else (x,)
def compare_version(ver1, ver2): """ Compare two version. Args: ver1: (tuple) version number's list 1. ver2: (tuple) version number's list 2. Returns: -1: ver1 < ver2 0: ver1 == ver2 1: ver1 > ver2 """ if not ver1 or not ver2: return 0 if ver...
def next_path(path, grid_len): """ Finds the next step through a lattice grid. """ while len(path) > 0: x, y = path.pop() # Pop back one step if len(path) == 0: return False, [] _x, _y = path[-1] if _x == grid_len or _y == grid_len: # Wall. Only 1 choice available....
def get_payment_request_with_no_contact_info(payment_method: str = 'CC', corp_type: str = 'CP', filing_type_code: str = 'SERCH', future_effective: bool = False): """Return a payment request object.""" return { 'paymentInfo': { 'methodOfPayment': p...
def _as_list_of_str(columns): """Return none, one or more columns as a list.""" columns = columns if columns else [] if isinstance(columns, str): columns = [columns] return columns
def precision(ground_truth_permutated, **kwargs): """ Calculate the precision at k @param ground_truth_permutated: Ranked results with its judgements. """ rank = ground_truth_permutated limit = kwargs.get('limit', len(ground_truth_permutated)) if len(rank) < limit: # 0-padding ...
def unlistify(list_:list): """ Given a list it returns the list or the value if the length is 1 Arguments: list_ (list): List of values Returns: A list if the length is greater than 1 if not returns the first element """ if len(list_) == 1: return list_[0] else: ...
def sizeof_fmt(num): """Print size of a byte number in human-readable format. Args: num: Filesize in bytes. Return: Filesize in human-readable format. """ for unit in ["B", "K", "M", "G", "T", "P", "E", "Z"]: if abs(num) < 1024.0: if abs(num) < 100: ...
def HMStime(s): """ Given the time in seconds, an appropriately formatted string. """ if s < 60.: return '%.3f s' % s elif s < 3600.: return '%d:%.3f' % (int(s / 60 % 60), s % 60) else: return '%d:%d:%.3f' % (int(s / 3600), int(s / 60 % 60), s % 60)
def api_headers(api_key): """ Return API request header""" return { "Content-Type": "Application/JSON", "x-access-token": api_key }
def filter_rows(input_str): """ Filter matching rows, i.e. strings containing <row> XML elements. :param input_str: row possibly containing a <row> XML element (could also contain their root element, e.g. <post>) :return: """ return input_str.lstrip().startswith('<row')
def anal_mvd(data_dict): """ Function for parsing the MVD1 + MVD2 out of the raw data dictionary. Takes the full dictionary as input, and returns the relativistic contributions to the energy. """ return data_dict["rel"]["relativistic"]
def ParseXMLElement(code:str, tag): """ The ParseXMLElement function parses a given XML element from the code. It takes two arguments: 1) The code to be parsed, and 2) The tag of the XML element to be parsed. It returns a string containing the text within that particul...
def mode(nums): """Return most-common number in list. For this function, there will always be a single-most-common value; you do not need to worry about handling cases where more than one item occurs the same number of times. >>> mode([1, 2, 1]) 1 >>> mode([2, 2, 3, 3, 2]) ...
def to_unicode(data_str, encoding): """Convert a str object to unicode using the encoding given Characters that cannot be converted will be converted to '\ufffd' (the unicode replacement character). """ return data_str.decode(encoding, 'w3lib_replace')
def FibNth(n): """ Question: The Fibonacci sequence is defined as follows: the first number of the sequence is 0, the second number is 1, and the nth number is the sum of the (n - 1)th and (n - 2)th numbers. Write a function that takes in an integer n and returns the nth Fibonacci number. ""...
def _vecabs2(v): """Computes vec.(vec.conj)""" out = 0. for i in range(len(v)): out = out + v[i].real**2 + v[i].imag**2 return out
def determine_input_arg(arg_val, default_arg_val): """ if arg_val exists, use it, else return default_arg_val """ if arg_val: return arg_val else: return default_arg_val
def compose_capability_list(caps): """Returns a string containing a braced list of capabilities as enums. Arguments: - caps: a sequence of capability names Returns: a string containing the braced list of SpvCapability* enums named by caps. """ return '{' + ', '.join(['SpvCapab...
def extract_data_from_array(input_x, input_n=None): """trans [input_x, input_n] to seq_list""" if input_n is None: return [list(x) for x in input_x] elif isinstance(input_n, int): return [list(x[0: input_n]) for x in input_x] else: return [list(x[0:n]) for x, n in zip(inpu...
def invert_dict(d): """ Makes the keys the values and the values the keys .. warning:: No guarantee of dictionary structure if mappings are not unique :param d: dictionary to be inverted :rtype: dict """ return dict((y, x) for x, y in d.items())
def _convert_mac(mac): """convert a mac to a lower, cleansed value.""" using = mac.lower() for c in [":", "-"]: using = using.replace(c, "") return using
def get_slice(index, length, pad): """ Given the index at which we are it returns the slice of the next img. (the operation is the same for width and height). """ slice_ret = slice(pad * index, (pad * index) + length) return slice_ret
def sum_series(n): """Calculate sum of n+(n-2)+(n-4)...""" return n if n < 2 else n + sum_series(n - 2)
def group(*choices: str) -> str: """ Convenience function for creating grouped alternatives in regex """ return f"({'|'.join(choices)})"
def _try_convert(value): """Return a non-string from a string or unicode, if possible. ============= ===================================================== When value is returns ============= ===================================================== zero-length '' 'None' None 'True' ...
def map_int(x_coord, in_min, in_max, out_min, out_max): """ Map input from one range to another. """ return int((x_coord - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
def _is_punctuation(word): """ Determine if a word is a punctuation token. """ return word in '.,!?;:'
def current_yellow(before, after): """ Checks if the yellow light works well. :param before: has to be None, "red" or blink :param after: has to be None, "red", "green" or "left green" :return: if any constraints not met will return False else True Additional Constraint: 1. Colours be...
def getFrameSize(fs, timeSize=20): """ Read audio file, get sampling rate, return frame size. :param file: music file (only WAV for now) :param timeSize: frame length in milliseconds (default: 20ms) :returns: number of samples per frame """ return int(fs*timeSize/1000)
def s_curve_saturation(x, alpha, gamma): """ x = array alpha = shape gamma = inflection """ return x**alpha / (x ** alpha + gamma ** alpha)
def from_std(x, y, height, width, Sto): """ Function which translates Left-Upper corner coordinate system coordinates to Sto coordinate system Width and Height of game field required :param x: input X :param y: input Y :param height: field height :param width: field width :param Sto: ou...
def bit_set(bit,bits): """ NAME: bit_set PURPOSE: check whether a bit in a bitmask is set INPUT: bit - check whether this bit is set bits - bitmask OUTPUT: True if bit is set in bits HISTORY: 2014-08-19 - Written - Bovy (IAS) """ return (bits & 2...
def isEOSDir( path ): """Returns True if path is either: /store/... or /eos/cms/store/... or root://eoscms.cern.ch//eos/cms/ Otherwise, returns False. """ return path.startswith('/eos') or path.startswith('/store') or path.startswith('root://eoscms.cern.ch//eos/cms/') or path.starts...