content
stringlengths
42
6.51k
def _buildGetterOrSetter( prefix, varName ): """Utility function used by getterName and setterName.""" if varName[0] == '_' : varName = varName[1:] return prefix + varName[0].upper() + varName[1:]
def plugins_filter(plugins, function_name): """ Usage inside of generate_context: from plugins import plugins_filter for plugin in plugins_filter(plugins, "cookies"): context = plugin(context) """ return [x for x in plugins if x.cookiecutter_function == function_nam...
def segment_times(timeseries, max_gap): """ Returns an N-D array where each row represents a separate segmentation of continuous data with no gaps greater than the max gap. """ time_segments = [] is_contiguous = False arr_n = -1 for i, t in enumerate(timeseries): if not is_contig...
def get_point(inputs, x, y): """return point[x][y] if in the boundary, return None if not""" if x < 0 or y < 0 or x >= len(inputs) or y >= len(inputs[0]): return None return inputs[x][y]
def get_name(fname): """Get the elements of the file name we need Params: fname -- String: The file name c9_c8_c176_IC12_s4_l_t Returns: The image's component number, scan number, and hemisphere 12, 4, L """ if fname.endswith('.nii.gz'): fname = fnam...
def getNumChannel(name): """retourne l'id du salon""" index = name.find("_") numRaid = int(name[:index]) #assert(numRaid > 0) return numRaid
def get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): """Returns the URL and token for a CAPTCHA challenge issued by the server. Args: http_body: str The body of the HTTP response from the server which contains the CAPTCHA challenge. captcha_base_url: str Thi...
def is_almost_subset(set1, set2, min_set_diff = 2): """ Return True, if no more than min_set_diff members of set2 are contained in set1. i.e, set2 is almost a subset of set1. See example for clarity: Example ------- >>> is_almost_subset(set(["A","B","C","D"]), set(["A", "K"]), 2) ...
def _P_2bc(h): """Define the boundary between Region 2b and 2c, P=f(h) >>> "%.3f" % _P_2bc(3516.004323) '100.000' """ return 905.84278514723-0.67955786399241*h+1.2809002730136e-4*h**2
def sn(ok): """converts boolean value to +1 or -1 """ if ok: return 1 else: return -1
def popcount(n: int) -> int: """Popcount. Args: n (int): an 64-bit signed or unsigned integer. Returns: int: popcount := count of active binary bits. Complexity: time: O(1) space: O(1) Examples: >>> popcount(0b1010) 2 >>> po...
def circular_between(start, bet, end): """Finds if bet is in between start and end Arguments: start {Integer} bet {Integer} end {Integer} Returns: Boolean -- True if it is in between, else False """ if end > start: return (bet > start and bet < end) ...
def nameAndVersion(aString): """Splits a string into the name and version number. Name and version must be seperated with a hyphen ('-') or double hyphen ('--'). 'TextWrangler-2.3b1' becomes ('TextWrangler', '2.3b1') 'AdobePhotoshopCS3--11.2.1' becomes ('AdobePhotoshopCS3', '11.2.1') 'Microsoft...
def list2cmdline_patch(seq): """ # windows compatible Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is ...
def create_futures_regex(input_symbol: str) -> str: """Creates a regular expression pattern to match the standard futures symbology. To create the regular expression pattern, the function uses the fact that within the ICE consolidated feed all the standard futures contracts are identified by the root s...
def commonLeader(data, i, j): """Get the number of common leading elements beginning at data[i] and data[j].""" l = 0 try: while l < 255+9 and data[i+l] == data[j+l]: l += 1 except IndexError: pass # terminates return l
def squares(num): """Squares Arguments: num {int} -- Upper bound for the list of squares to generate Returns: dict -- The squares dictionary """ squares = {} if num <= 0: return squares for n in range(1, num + 1): squares[n] = n * n return squar...
def guess_species(known_species, frame_id): """Returns a guess at a species based frames of known species and the frame with a detection having unknown species. # Arguments known_species: Dict mapping frame to species names. frame_id: Frame number of unknown species. # Returns ...
def glsl_type(socket_type: str): """Socket to glsl type.""" if socket_type in ('RGB', 'RGBA', 'VECTOR'): return 'vec3' else: return 'float'
def factorization(fib): """ Numeric factorization for a fibonacci number """ print(f"initializing factorization for {fib}") divisor = 2 values = [] # save unfactorizable values if fib <= 5: values.append(str(fib)) else: while fib != 1: # finding divisors ...
def hex_to_rgb(value): """ Return (red, green, blue) values Input is hexadecimal color code: #rrggbb. """ lv = len(value) out = tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) out = tuple([x/256.0 for x in out]) return out
def op_signum(x): """Returns the sign of this mathematical object.""" if isinstance(x, list): return [op_signum(a) for a in x] else: m = abs(x) if m: x /= m return x
def _round_up_time(time, period): """ Rounds up time to the higher multiple of period For example, if period=5, then time=16s will be rounded to 20s if time=15, then time will remain 15 """ # If time is an exact multiple of period, don't round up if time % period == 0: return time ...
def enumerate_keyed_param(param, values): """ Given a param string and a dict of values, returns a flat dict of keyed, enumerated params. Each dict in the values list must pertain to a single item and its data points. Example: param = "InboundShipmentPlanRequestItems.member" values = [ ...
def hr_min_sec_to_secs(hour: int, mins: int, second: int): """ Converts hours, mins and seconds and returns consolidated seconds. Used with datetime.now() object, and its hour, minutes and seconds attributes :param hour: int :param mins: int :param second: int :return: int """ hour_to_seconds = hour...
def elm2ind(el, m): """Same as pyssht.elm2ind, but will broadcast numpy arrays""" return el * el + el + m
def etag(obj): """Return the ETag of an object. It is a known bug that the S3 API returns ETags wrapped in quotes see https://github.com/aws/aws-sdk-net/issue/815""" etag = obj['ETag'] if etag[0]=='"': return etag[1:-1] return etag
def _get_name_py_version(typed): """Gets the name of the type depending on the python version Args: typed: the type of the parameter Returns: name of the type """ return typed._name if hasattr(typed, "_name") else typed.__name__
def get_chunked_dim_size(dim_size, split_size, idx): """ Computes the dim size of the chunk for provided ``idx`` given ``dim_size`` and ``split_size``. Args: dim_size(int): Size of the dimension being chunked. split_size(int): The chunk size for each chunk of ``dim_size``. idx(i...
def calculateDifferenceBetweenTimePeriod(time1: str, time2: str) -> str: """ Calculates difference between two times given in input and returns difference >>> calculateDifferenceBetweenTimePeriod("00:00:00","23:59:59") '23:59:59' """ # Change below this l1 = time1.split(':') l2 = tim...
def build_experiment_url(base_url: str) -> str: """ Build the URL for an experiment to be published to. """ return '/'.join([base_url, 'experiment'])
def wordcount(text): """ Return the number of words in the given text. """ if type(text) == str: return len(text.split(" ")) elif type(text) == list: return len(text) else: raise ValueError("Text to count words for must be of type str or of type list.")
def divisors(integer): """ Create a function that takes an integer n > 1 and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime'. """ if type(integer) is not int: ...
def get_stage_list(n_stages, stage_ratios): """Get stage label.""" if n_stages == 3: return [0, 1, 2] stage_values = [] stage = 0 threshold = stage_ratios[stage] * n_stages for x in range(n_stages): if x >= threshold: stage += 1 threshold += stage_ratios[s...
def _channel_name(row, prefix="", suffix=""): """Formats a usable name for the repeater.""" length = 16 - len(prefix) name = prefix + " ".join((row["CALL"], row["CITY"]))[:length] if suffix: length = 16 - len(suffix) name = ("{:%d.%d}" % (length, length)).format(name) + suffix return...
def getopts(argv): """Parse arguments passed and add them to dictionary :param argv: arguments must be url and threads :return: dictionary of arguments """ opts = {} # Empty dictionary to store key-value pairs. while argv: # While there are arguments left to parse... if argv[0][0] == '...
def compare(context, object_field, raw_data, raw_field): """ Compare an object field value against the raw field value it should have come from. Args: context (str): The context of the comparison, used for printing error messages. object_field (Any): The value of the object field being comp...
def xtype_from_derivation(derivation): """Returns the script type to be used for this derivation.""" if derivation.startswith("m/84'"): return 'p2wpkh' elif derivation.startswith("m/49'"): return 'p2wpkh-p2sh' else: return 'standard'
def format_punctuation(txt: str) -> str: """Remove or add spaces around the punctuation signs. Args: txt (str): stores the original text Returns: str: returns formatted text """ punctuation = (",", ".", "!", "?") for i in range(len(txt)-1): if txt[i] in punctuation: ...
def not_found(error): """Error to catch page not found""" return {"status": 404, "error": "Resource not found!"}, 404
def fahrenheit(celsius): """ Convert tempature celsius into farenheit """ return ((9 * celsius) / 5) + 32
def default_range(start, stop): """[start, start + 1, ..., stop -1]""" return range(start, stop)
def any_of(possibilities, to_add=''): """ Helper function for regex manipulation: Construct a regex representing "any of" the given possibilities :param possibilities: list of strings representing different word possibilities :param to_add: string to add at the beginning of each possibility (optiona...
def interp(x, in_min, in_max, out_min, out_max): """Linear interpolation""" return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def email_address_stix_pattern_producer(data): """Convert an email address from TC to a STIX pattern.""" return f"[email-addr:value = '{data.get('summary')}']"
def parse_args(args): """Splits comma separated argument into size and rel attribute.""" parts = args.split(",") arg = parts[0] rel = len(parts) > 1 and parts[1] or None if rel: rel_attr = ' rel="%s"' % rel else: rel_attr = '' return (arg, rel_attr)
def sliding_window(image_width,image_height, patch_w,patch_h,adj_overlay_x=0,adj_overlay_y=0): """get the subset windows of each patch Args: image_width: width of input image image_height: height of input image patch_w: the width of the expected patch patch_h: the height of the e...
def poly_to_box(poly): """Convert a list of polygons into an array of tight bounding boxes.""" x0 = min(min(p[::2]) for p in poly) x1 = max(max(p[::2]) for p in poly) y0 = min(min(p[1::2]) for p in poly) y1 = max(max(p[1::2]) for p in poly) boxes_from_polys = [x0, y0, x1, y1] return boxes_fr...
def _parse_tfnone(dic): """ Replace dictionary values of 'none', 'true' and 'false' by their python types. """ formatter = {'none':None, 'true':True, 'false':False} out = {} for k,v in dic.items(): try: v=formatter[v.lower()] except KeyError: pass o...
def getIso639LangCode(android_lang_code): """Convert language code to google api supported language code See https://cloud.google.com/translate/docs/languages """ if android_lang_code == 'zh-rTW': return 'zh-TW' elif android_lang_code == 'zh-rCN': return 'zh-CN' elif android_lan...
def shift_leftward(n, nbits): """Shift positive left, or negative right. Same as n * 2**nbits""" if nbits < 0: return n >> -nbits else: return n << nbits
def radix_sort(vals): """Return sorted list as copy.""" if len(vals) <= 1: return vals[:] digits = len(str(max(vals))) for power in range(digits): buckets = [[] for _ in range(10)] for val in vals: trunc_val = val % (10 ** (power + 1)) idx = trunc_val /...
def drop_placeholders_parallel(peaks, otherpeaks): """Given two parallel iterables of Peak objects, `peaks` and `otherpeaks`, for each position that is not a placeholder in `peaks`, include that Peak object and its counterpart in `otherpeaks` in a pair of output lists. Parameters ---------- pea...
def hexKeyToBin(counts, n_qubits): """Generates binary representation of a hex based counts Derived from https://sarangzambare.github.io/jekyll/update/2020/06/13/quantum-frequencies.html Args: counts (dict): dictionary with hex keys n_qubits (int): number of qubits Returns: dict...
def compute_gcd(x, y): """Compute gcd of two positive integers x and y""" if x < y: return compute_gcd(y, x) residual = x % y if residual == 0: return y if residual == 1: return 1 return compute_gcd(y, residual)
def non_zero_mean_difference(own_team_scores, enemy_team_scores, neutral_scores, assassin_scores, weights=(1, 1, 1, 1)): """ Calculates the difference between the mean of own_team_scores and the mean of the combination of enemy_team_scores, neutral_scores and assassin_scores. """ own_team_scores, enemy_team_scores, n...
def getMonth(month): """ returns the number of the month if given a string and returns the name of the month if given and int """ # months = ['January', 'February', 'March', 'April', 'May', 'June', # 'July', 'August', 'September', 'October' 'November', # 'December...
def checkInt(n): """ To check if the string can be converted to int type """ try: int(n) return True except ValueError: return False
def get_barcode(item_scanned): """ (str) -> str Returns the type of item that has been scanned based on the UPC of the item that has been scanned i.e. the "item_scanned" parameter >>>get_barcode('111111') 'SINGLES' >>>get_barcode('666666') 'SMALL' >>>get_barcode('242424') 'LARGE'...
def get_recursively(search_dict, field): """ Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided, returning a list of the values. """ fields_found = [] for key, value in search_dict.items(): if key == field: fields_found.append(val...
def chunk_script_section(sd, n): """ Split simply on period. Problematic for string like 'Dr.' and abbreviations like 'D.M.Z.' Params: sd (dict) -- {'title': section title (str), 'level': level (int), 'text': section text (str)} n (int) -- chunk...
def concat_imports(values, sep='.'): """Combine import statements. Parameters ---------- values : list-like The values to be concatenated sep : string The value between the statements Returns ------- str The concatenated string """ if len(values) >= 1: ...
def linspace(start, stop, num): """Custom version of numpy's linspace to avoid numpy depenency.""" if num == 1: return stop h = (stop - start) / float(num) values = [start + h * i for i in range(num+1)] return values
def ddpg(loss): """ paper : https://arxiv.org/abs/1509.02971 + effective to use with replay buffer - using grads from critic not from actual pollicy ( harder to conv ) """ grads = loss return loss
def isnum(a): """True if a is an integer or floating-point number.""" if isinstance(a, (int, float)): return 1 else: return 0
def relative(p1, p2, r): """pass""" x = p1[0] + r*(p2[0] - p1[0]) y = p1[1] + r*(p2[1] - p1[1]) return x, y
def _permutation_worker(k: int, items: list) -> list: """The kth Johnson-Trotter permutation of all items.""" n = len(items) if n <= 1: return items else: group = k // n item = k % n position = n - item - 1 if group % 2 == 0 else item dummy = _permutation_worker(g...
def filter_credit_score(credit_score, bank_list): """Filters the bank list by the mininim allowed credit score set by the bank. Args: credit_score (int): The applicant's credit score. bank_list (list of lists): The available bank loans. Returns: A list of qualifying bank loans. ...
def sigma(alpha, n): """ Clauset et al 2007 equation 3.2: sigma = (alpha-1)/sqrt(n) """ return (alpha-1.) / n**0.5
def convert_inds_to_text(inds, ind2word, preprocess=False): """ convert the given indexes back to text """ words = [ind2word[word] for word in inds] return words
def get_adjacent_seat_positions(row, column, max_row, max_column): """Get positions of the seats adjacent to the seat with row and column.""" positions = [] for cur_row in range(row - 1, row + 2): for cur_column in range(column - 1, column + 2): if cur_row == row and cur_column == column...
def build_mask(items, predicate, d=None, c=None): """ Applies the predicate to each item, taking the disjunction of the results. Will add d as a disjunct, and then finally will take that in conjunction with c. Returns the value. """ q = None for i in items: if q is None: ...
def prob_downsample(local_d: int, target_d: int, outlier_d: int): """ Given local, target and outlier density (as estimated by KNN) calculate the probability of retaining the event. If local density is less than or equal to the outlier density, returns a probabili...
def bin2hex(x): """ Convert binary string to hexadecimal string. For instance: '11010' -> '1a' """ return hex(int(x, 2))[2:]
def _remove_dups(elems, txids_seen): """API data has duplicate transaction data. Clean it.""" out = [] for elem in elems: txid = elem["txhash"] if txid in txids_seen: continue out.append(elem) txids_seen.add(txid) return out
def is_valid_file(ext, argument): """ Checks if file format is compatible """ formats = { 'input_ligand_path': ['pdb'], 'output_ligand_path': ['pdbqt'], 'input_receptor_path': ['pdb'], 'output_receptor_path': ['pdbqt'], 'input_ligand_pdbqt_path': ['pdbqt'], 'input_receptor_pdbqt_path': ['pdbqt'], 'input...
def construct_none_displayer(entries, placeholder='-'): """Return a string to be used as a placeholder for an empty option. The length of the placeholder is based on the length of the longest option in a list of entries. """ # Convert to string as a precaution to figure out length. entries...
def str_to_bool(boolstr, default=False): """Convert a string to a boolean.""" boolstr = boolstr.lower() if boolstr in ("true", "yes", "on", "1"): return True elif boolstr in ("false", "no", "off", "0"): return False else: return default
def get_biggest_value_less_or_equal_to(iter: list or range, value): """Returns the biggest element from the list that is less or equal to the value. Return None if not found """ if type(iter) == list: i = [x for x in iter if x <= value] return max(i) if i else None elif type(iter) == ra...
def replace_month(json_str): """Replace month number by its name.""" json_str = json_str.replace('-01"', '-Ene"') json_str = json_str.replace('-02"', '-Feb"') json_str = json_str.replace('-03"', '-Mar"') json_str = json_str.replace('-04"', '-Abr"') json_str = json_str.replace('-05"', '-May"') ...
def max_length(x, y): """ This function can be passed to a reduce to determine the maximum length of a list within a list of lists. """ if type(x) == list and type(y) == list: return max(len(x), len(y)) elif type(x) == list and type(y) == int: return max(len(x), y) elif type(...
def find_contiguous_ids(job_ids): """Return the contiguous job ids in the given list. Returns ------- contiguous_job_ids : str The job ids organized in contiguous sets. """ import operator import itertools contiguous_job_ids = [] for k, g in itertools.groupby(enumerate(jo...
def parse_attributes(attribute_string): """Returns region of attribute string between first pair of double quotes""" attribute_string = attribute_string[attribute_string.find('"')+1:] if '"' in attribute_string: attribute_string = attribute_string[:attribute_string.find('"')] return attribute_st...
def get_object_instances(predictions, target, confidence): """ Return the number of instances of a target class. """ targets_identified = [ pred for pred in predictions if pred['label'] == target and float(pred['confidence']) >= confidence] return len(targets_identified)
def getSquareSegmentDistance(p, p1, p2): """ Square distance between point and a segment """ x = p1[0] y = p1[1] dx = p2[0] - x dy = p2[1] - y if dx != 0 or dy != 0: t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy) if t > 1: x = p2[0] ...
def millis_to_srt(millis): """Convert milliseconds time to the SRT subtitles format time string.""" result = '' # milliseconds milliseconds = millis % 1000 result = ('%03d' % milliseconds) + result millis = (millis - milliseconds) / 1000 # seconds seconds = millis % 60 result = ('%02...
def progress_report(current, previous): """Display the change in progress from previous to current.""" context = { 'current': current, 'previous': previous, 'scope_change': None, 'complete_change': None, } if current and previous: if current.total < previous.tot...
def generate_storage_options(args): """ Generate stoage options from args :param args: :return: """ if (not args.azure_tenant_id or not args.azure_storage_account_name or not args.azure_client_id or not args.azure_client_secret): return {} else: ...
def splitIndex(index): """Normalize a casual index like "one, two, 3,four" to canonical form like ["one", "two", 3, "four"].""" out = [x.strip() for x in index.split(",")] for i in range(len(out)): try: out[i] = int(out[i]) except ValueError: pass return out
def parse_results_for_matching_tag(output, image_tag): """This function is extremely reliant on the output format of resnet_18/classify_images.py""" match = False if image_tag in output: top_match = output.split("\n")[1] if image_tag in top_match: match = True return ...
def split_ver_str(ver_str): """Split version string into numeric components. Return list of components as numbers additionally checking that all components are correct (i.e. can be converted to numbers). """ ver_list = [] for c in ver_str.split('.')[0:3]: if not c.isdecimal(): ...
def applyAprioriPrinciple(itemSets, selectedItemSets): """ Apply apriori principle 'if an item set is frequent, then all of its subsets must also be frequent.' """ if len(selectedItemSets) == 0: return [] returnItemSets = [] subsetLen = None for s in itemSets: ...
def hex_to_rgb(hex_str): """ translate tkinter hex color code #ffffff to rgb tuple of integers https://stackoverflow.com/a/29643643/6929343 """ h = hex_str.lstrip('#') return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
def is_prime_slow(n): """ Slow trial division primality testing algorithm (Always correct) """ if n <= 1: return False x = 2 while x * x <= n: if n % x == 0: return False x += 1 return True
def checkanswer(possible, guess): """ Case insensitive check of answer. Assume inputs are in the correct format, since takeQuiz() accounts for Args: possible (list): List of possible answers for question. guess (string): User's guess for question. Returns: bool: True if guess...
def _get_received_date(received_header): """ Helper function to grab the date part of a Received email header. """ received_header = received_header.replace('\r', '').replace('\n', '') date = received_header.split(';') try: return date[-1] except: ''
def has_any_letters(text): """ Check if the text has any letters in it """ # result = re.search("[A-Za-z]", text) # works only with english letters result = any( c.isalpha() for c in text ) # works with any letters - english or non-english return result
def time_to_string(seconds): """Return a readable time format""" if seconds == 0: return '0 seconds' h, s = divmod(seconds, 3600) m, s = divmod(s, 60) if h != 1: h_s = 'hours' else: h_s = 'hour' if m != 1: m_s = 'minutes' else: m_s = 'minute' ...
def bit(b): """Internal use only""" # return bit b on return 2**b
def to_float(string): """ Convert string to float >>> to_float("42.0") 42.0 """ try: number = float(string) except: number = 0.0 return number