content
stringlengths
42
6.51k
def opt_to_kwargs(opt): """Get kwargs for seq2seq from opt.""" kwargs = {} for k in ['numlayers', 'dropout', 'bidirectional', 'rnn_class', 'lookuptable', 'decoder', 'numsoftmax', 'attention', 'attention_length', 'attention_time', 'input_dropout']: if k in op...
def manhattan_distance(start, end): """ Calculate the shorest distance between two set of coordiantes. Reference: https://dataaspirant.com/2015/04/11/five-most-popular-similarity-measures-implementation-in-python/ """ return sum(abs(a - b) for a, b in zip(start, end))
def parse_key_value_config(config_value): """ Parses out key-value pairs from a string that has the following format: key: value, key2: value, key3: value :param string config_value: a string to parse key-value pairs from :returns dict: """ if not config_value: return {} ...
def _objc_provider_framework_name(path): """Returns the name of the framework from an `objc` provider path. Args: path: A path that came from an `objc` provider. Returns: A string containing the name of the framework (e.g., `Foo` for `Foo.framework`). """ return path.rpartition("/")[2].partition...
def toline(iterable): """Convert an iterable into a line.""" return ' '.join(str(x) for x in iterable) + '\n'
def get_attribute(attrs, name, default=None): """ Get div attribute :param attrs: attribute dict :param name: name field :param default: default value :return: value """ if 'data-'+name in attrs: return attrs['data-'+name] else: return default
def ascetime(sec): """return elapsed time as str. Example: return `"0h33:21"` if `sec == 33*60 + 21`. """ h = sec / 60**2 m = 60 * (h - h // 1) s = 60 * (m - m // 1) return "%dh%02d:%02d" % (h, m, s)
def threshold(ypixel, xpixel, color): """Return a threshold above which to choose peak pixels based on position. """ if color is 'Red': return 10000 elif color is 'Blue': if 1100 < xpixel < 3100: if 0 < ypixel <= 100: return 500 elif 100 < ypixel ...
def connected_components(graph): """ Given an undirected graph (a 2d array of indices), return a set of connected components, each connected component being an (arbitrarily ordered) array of indices which are connected either directly or indirectly. Args: graph: a list reprenting the co...
def bulk_docs(docs, **kwargs): """Create, update or delete multiple documents. http://docs.couchdb.org/en/stable/api/database/bulk-api.html#post--db-_bulk_docs :param list docs: The sequence of documents to be sent. :param kwargs: (optional) Arguments that :meth:`requests.Session.request` takes. :...
def get_track_start(line): """ Return the track start time Indicates an index (position) within the current FILE. The position is specified in mm:ss:ff (minute-second-frame) format. There are 75 such frames per second of audio. In the context of cue sheets, "frames" refer to CD sectors, despite a d...
def mean(sample): """ Computes the mean for the univariate sample. :param sample: (list(float)) univariate sample. :return: (float) the mean. """ return sum(sample) / len(sample)
def is_callable_default(x): """Checks if a value is a callable default.""" return callable(x) and getattr(x, "_xonsh_callable_default", False)
def test_header(calver, exp_type): """Create a header-like dict from `calver` and `exp_type` to support testing. """ header = { "META.INSTRUMENT.NAME" : "SYSTEM", "REFTYPE" : "CRDSCFG", "META.CALIBRATION_SOFTWARE_VERSION" : calver, "META.EXPOSURE.TYPE" : exp_type, ...
def identidadmatriz(filas, columnas): """Funcion que realiza la matriz identidad para determinado numero de filas y columnas, el proposito de esta funcion es ayudar all desarrollo de isUnitaria (int, int) -> list 2D""" c = [] for i in range(filas): fila = [] for j in range(columnas): ...
def base_count(DNA): """Counts number of Nucleotides""" return DNA.count('A'), DNA.count('T'), DNA.count('G'), DNA.count('C')
def add_padding(encoded: str) -> str: """Add padding to base64 encoded bytes. Parameters ---------- encoded : `str` A base64-encoded string, possibly with the padding removed. Returns ------- result : `str` A correctly-padded version of the encoded string. """ under...
def update_schema(schema_old, schema_new): """ Given an old BigQuery schema, update it with a new one. Where a field name is the same, the new will replace the old. Any new fields not present in the old schema will be added. Arguments: schema_old: the old schema to update schema_ne...
def get_position_label(i, words, tags, heads, labels, ents): """Return labels indicating the position of the word in the document. """ if len(words) < 20: return "short-doc" elif i == 0: return "first-word" elif i < 10: return "early-word" elif i < 20: return "mid...
def task7(a: float, b: float) -> str: """ Function that calculates an area of a right triangle with two sides - a and b (just like Pitagoras triangle). Return the area as string that has two numbers after comma. Input: a,b -> int numbers Output: area of triangle as string such as: "1.23" """ ...
def normalize_min_max(x, x_min, x_max): """Normalized data using it's maximum and minimum values # Arguments x: array x_min: minimum value of x x_max: maximum value of x # Returns min-max normalized data """ return (x - x_min) / (x_max - x_min)
def parseDeviceInfo(device_info): """ Parses Vendor, Product, Revision and UID from a Setup API entry :param device_info: string of device information to parse :return: dictionary of parsed information or original string if error """ # Initialize variables vid = '' pid = '' rev = '' ...
def has_numbers(input_str: str): """ Check if a string has a number character """ return any(char.isdigit() for char in input_str)
def difference(d1, d2): """Return a dictionary with items from *d1* not contained in *d2*. If a key is present both in *d1* and *d2* but has different values, it is included into the difference. """ result = {} for key in d1: if key not in d2 or d1[key] != d2[key]: result[ke...
def basename(path: str) -> str: """ get '17asdfasdf2d_0_0.jpg' from 'train_folder/train/o/17asdfasdf2d_0_0.jpg Args: path (str): [description] Returns: str: [description] """ return path.split("/")[-1]
def _pdf_url_to_filename(url: str) -> str: """ Convert a PDF URL like 'https://www.mass.gov/doc/weekly-inmate-count-4202020/download' into a filename like 'weekly-inmate-count-4202020.pdf' """ name_part = url[25:-9] return f"{name_part}.pdf"
def format_watershed_title(watershed, subbasin): """ Formats title for watershed in navigation """ max_length = 30 watershed = watershed.strip() subbasin = subbasin.strip() watershed_length = len(watershed) if watershed_length > max_length: return watershed[:max_length-1].strip()...
def to_camel_case(name: str, separator: str ='_'): """Converts passed name to camel case. :param name: A name as specified in ontology specification. :param separator: Separator to use in order to split name into constituent parts. :returns: A string converted to camel case. """ r = '' if ...
def samplevar_dataset_to_varcope(samplevar_dataset, sample_size): """Convert "sample variance of the dataset" (variance of the individual observations in a single sample) to "sampling variance" (variance of sampling distribution for the parameter). Parameters ---------- samplevar_dataset : arra...
def add_me_to_the_queue(express_queue, normal_queue, ticket_type, person_name): """Add a person to the 'express' or 'normal' queue depending on the ticket number. :param express_queue: list - names in the Fast-track queue. :param normal_queue: list - names in the normal queue. :param ticket_type: int -...
def normalize_ipam_config_key(key): """Normalizes IPAM config keys returned by Docker API to match Ansible keys. :param key: Docker API key :type key: str :return Ansible module key :rtype str """ special_cases = { 'AuxiliaryAddresses': 'aux_addresses' } return special_cases...
def to_unicode(string, encoding='ascii'): """ Safely converts a string to a unicode representation on any Python version. """ if hasattr(string, 'decode'): return string.decode(encoding, 'ignore') return string
def remove_strip_punctuation(line, punctuation): """Returns the line without start and end punctuation Param: line (unicode) Returns: line without start and end punctuation """ return_line = line.strip(punctuation) if return_line != line: return True, return_line els...
def _isinstance_of_namedtuple(arg): """Check if input *arg* is instance of namedtuple""" typ = type(arg) base = typ.__bases__ if len(base) != 1 or base[0] != tuple: return False fields = getattr(typ, '_fields', None) if not isinstance(fields, tuple): return False return all(i...
def event_to_topic_name(slack_event_type, app): """Name the SQuaRE Events Kafka topic for a given Slack event type. Parameters ---------- slack_event_type : `str` The name of the Slack event. This should be an item from `KNOWN_SLACK_EVENTS`. app : `aiohttp.web.Application` or `dict`...
def isPalindrome(s): """Assumes s is a str Returns True if s is a palindrome; False otherwise. Punctuation marks, blanks, and capitalization are ignored.""" def toChars(s): s = s.lower() letters = '' for c in s: if c in 'abcdefghijklmnopqrstuvwxyz': letters =...
def parse_label_from_image_name(image_name): """Parses the label from the file name of a testing image. Args: image_name: A file name string of the following format. <testing_image_id>_<training_image_label> where training_image_id is a unique integer amongst testing images and training_image_label is a v...
def get_error_angle(target, heading): """Calculate error angle between -180 to 180 between target and heading angles If normalized is True then the result will be scaled to -1 to 1 """ error = heading - target abs_error = abs(target - heading) if abs_error == 180: return abs_error ...
def longest_palindrome(input_string): """ Return the first """ # ============================== # could be more universal version: # wrap input into list # check if eny string is palindrome # else continue # keep removing char from the end and beginning of the string # after eac...
def jsearchone(json,sfld,search,rfld): """ return the first search result of a column based search """ for j in json: if j[sfld]==search: try: element = j[rfld].strip() except: element = "" return element
def cbool(bool): """ Convert Python bool to string "true" or "false" """ return "true" if bool else "false"
def parse_token(response): """ parse the responses containing the tokens Parameters ---------- response : str The response containing the tokens Returns ------- dict The parsed tokens """ items = response.split("&") items = [item.split("=") for item in items...
def best_length_match(ref_l, cand_l): """Find the closest length of reference to that of candidate.""" least_diff = abs(cand_l - ref_l[0]) best = ref_l[0] for ref in ref_l: if abs(cand_l - ref) < least_diff: least_diff = abs(cand_l - ref) best = ref return best
def get_merged_segments(pivot_segment, n_segments): """ """ merged_segments = [] if pivot_segment[1] > pivot_segment[0]: merged_segments += list(range(pivot_segment[0], pivot_segment[1])) else: merged_segments += list(range(pivot_segment[0], n_se...
def latex_safe(s): """Make string latex safe Parameters ---------- s : str """ return s.replace('&', '\&').replace('$', '\$').replace('#', '\#')
def amount_2decimal(amount): """Usually generated floats can be generated up to many decimal places. We just need two. Convert to 2 decimal places. Args: amount (float) : transaction amount, but can be any float that we want to convert to only 2 decimal places """ return float("%.2f" % amou...
def get_subside_result_prefix(result_prefix, subject_name, side): """Return a result prefix based on subject ID and side Used to force output central surfaces to have a unique name, so they can later all be moved to the same folder containing a data .xml parameter file to be input to the Deformetrica s...
def str_to_float(argument): """Infer numeric type from string.""" out = argument try: if argument.lower() == 'true': out = True if argument.lower() == 'false': out = False elif ('.' in argument) or ('e' in argument.lower()): out = float(argument) ...
def get_prefixed_subdict(token, dict): """Returns the sub-dictionary of the given dictionary, creating an empty one if necessary.""" # Example: DELTET/DELTA_T_A = 32.184 # Look up or create the DELTET sub-dictionary try: subdict = dict[token] if type(subdict) == type({}): ...
def rotations(num): """ Get all rotations of a number """ # abc => bca, cab s = str(num) st = s*2 return [int(st[i:i+len(s)]) for i in range(1,len(s))]
def row_col2box(row_num, col_num): """ Converts the row and column number into the corresponding box number :param row_num: Int :param col_num: Int :return box_num: Int """ row_group_num = row_num // 3 col_group_num = col_num // 3 box_num = 3 * row_group_num + col_group_...
def tanimoto_dense(list1, list2): """! Calculate the tanimoto coefficient for a pair of dense vectors @param list1 list: List of positions that have a 1 in first compound fingerprint @param list2 list: List of positions that have a 1 in second compound fingerprint @return Returns float """ c...
def repr_iterable_kw_index(iterable, token='\n'): """Return a token separated string of joined iterables keywords with index""" return '\n'.join('#{}. [{}] {}'.format(index, key, value) for index, (key, value) in enumerate(iterable.items()))
def hex_to_rgb(rgb): """Convert a 6-digit hexadecimal RGB number to an RGB tuple. Args: rgb (:obj:`int`): 6-digit hex number to convert to a tuple. Returns: Tuple[ :obj:`int`]: RGB tuple. Note: This function converts an int into a tuple of ints. To parse strings, check :obj:`~...
def _make_style_str(styledict): """ Make an SVG style string from the dictionary. See also _parse_style_str also. """ s = '' for key in styledict.keys(): s += "%s:%s;"%(key, styledict[key]) return s
def merge_endpoints(defaults, additions): """ Given an existing set of endpoint data, this will deep-update it with any similarly structured data in the additions. :param defaults: The existing endpoints data :type defaults: dict :param defaults: The additional endpoints data :type default...
def has_to_unicode(value): """Check if an object has a to_unicode attribute. :param value: a value for which we test membership of the attribute :returns: True if the value has the attribute """ return hasattr(value, 'to_unicode')
def _sanitize_git_config_value(value: str) -> str: """Remove quotation marks and whitespaces surrounding a config value.""" return value.strip(" \n\t\"'")
def add_dicts(a, b): """Add two dictionaries together and return a third.""" c = a.copy() c.update(b) return c
def _inputs_swap_needed(mode, shape1, shape2): """ If in 'valid' mode, returns whether or not the input arrays need to be swapped depending on whether `shape1` is at least as large as `shape2` in every dimension. This is important for some of the correlation and convolution implementations in th...
def rpl_helper(_original, _replacement): """ Given a list `_original` that contains '0', '1', or 'X', replace the occurrences of 'X' in `_original` with chronological values from `_replacement`. :param _original: A list of '0', '1' or 'X'. :param _replacement: A list of '0', or ...
def is_a_mobile_phone(number): """ Return True if the number is a number for a mobile phone """ if not isinstance(number, str): raise TypeError("parameter 'number' must be a string (type: '" + str(type(number)) + "')") return number.startswith(('06','07'))
def csort(objs, key): """Order-preserving sorting function.""" idxs = dict((obj, i) for (i, obj) in enumerate(objs)) return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))
def topdownsegment(sequence, create_segment, compute_error, max_error, seq_range=None): """ Return a list of line segments that approximate the sequence. The list is computed using the bottom-up technique. Parameters ---------- sequence : sequence to segment create_segment : a func...
def _cmp(a,b): """3-way comparison like the cmp operator in perl""" if a is None: a = '' if b is None: b = '' return (a > b) - (a < b)
def parse_template(template): """ Takes the text of a template and returns the template's name and a dict of the key-value pairs. Unnamed parameters are given the integer keys 1, 2, 3, etc, in order. """ d, counter = dict(), 1 pieces = [x.strip() for x in template.strip('{}').split('|')] ...
def format_precincts_percent(num): """ Format a percentage for precincts reporting """ if num > 0 and num < 1: return '<1' if num > 99 and num < 100: return '>99' else: return int(round(num))
def build_param(value, arg): """ Used in connection with Django's add_preserved_filters Usage: - {% build_param 'lang' 'de' as lang_param %} - {% build_param 'template' 17 as templ_param %} - {% build_param 'template' <var_name> as templ_param %} use only for admin view ...
def reformat_pb_content(pb_request_content): """[Restucture content from packetbeat] Arguments: pb_request_content {[dict]} -- [statistic content get json request's json data Example: { "start": "2019-6-6,18:23:23.1", "end": "2019-6-6,18:23:24.9", "st...
def dB2amplitude(x, db_gain=0): """ Transform data in dB scale into amplitude A gain (db_gain) could be added at the end. Parameters ---------- x : array-like or scalar data in dB to rescale in amplitude db_gain : scalar, optional, default is 0 Gain that was a...
def intersection(k1, k2): """ Intersection distance :param k1: kmer counts for sequence 1 :param k2: kmer counts for sequence 2 :return: float, pairwise distance """ res = 0 for km in set(k1.keys()).intersection(set(k2.keys())): res += 2 * min(k1[km], k2[km]) return res / ...
def generate_first_run_metadata( schema_name, schema_group, version='1.0.0', ): """generate basic metadata frame for first_run case. Broken out as test-helper Args: schema_name (str): name of data source schema_group (str): group for data source version (str): s...
def opsworks_instance_name_targets_for_instances(ilist): """ Generate targets list by opwsorks instance name """ oin_nodes = {} for i in ilist: if i.tags is None: continue for tag in i.tags: if tag['Key'] == 'opsworks:instance': name = tag['Va...
def cmake_cache_entry(name, value, comment=""): """Generate a string for a cmake cache variable""" return 'set(%s "%s" CACHE PATH "%s")\n\n' % (name, value, comment)
def check_brack_c(inp, brack, count): """ Help funktion for balance brackets """ if inp == brack: if count != 1: print("No match") return 0 else: count -= 1 return 1
def is_related_field(field): """ Returns true if the field created as a related field from another model. """ return hasattr(field, 'related_name')
def to_bool(value): """ Converts value to boolean. Raises exception for invalid formats. """ if str(value).lower() == 'true': return True if str(value).lower() == 'false': return False raise Exception('Invalid value for boolean conversion: ' + str(value))
def parse_home_guid_team(d): """ Used to parse GUID of team. """ return str(d.get("tTGUID", "BVBL0000XXX 1")).replace(" ", "+")
def contfrac_float(x): """ Returns the continued fraction of the floating point number x, computed using the continued fraction procedure, and the sequence of partial convergents. Input: x -- a floating point number (decimal) Output: list -- the continued fraction [a0, a1, .....
def repeatsDigits(n): """Return True if n has repeat digits or a 0, True otherwise""" s = str(n) alreadySeen = [True] for i in range(9): alreadySeen.append(False) for c in s: if(alreadySeen[int(c)]): return True else: alreadySeen[int(c)] = True ret...
def find_minimum_rotated_sorted_1(arr): """ :param arr: rotated sorted array :return: minimum and value """ min = arr[0] for i in range(1, len(arr)): if arr[i] < min: min = arr[i] break return min
def reason_is_ne(field: str, expected, got) -> str: """ Create a string that is describes two values being unequal Args: field: the name of the mismatched field expected: the expected value got: the actual value """ return f'{field} mismatch: expected {expected}, got {got}'
def inversePowLawFunc(ys, a, b): """ The reverse pow law is used for randomly generating the network :param ys: y values :param a: alpha :param b: beta :param c: c scaling constant :return: x's """ xs = [] for y in ys: xs += [(y)**(1/a) - b] return xs
def str_to_bytes(str_arr): """ 'hello' -> b'hello' :param str_arr: str :return: bytes """ return bytes(str_arr, 'utf-8')
def _parse_chunk_path(path: str): """Returns x,y chunk coords and pyramid level from string key""" level, ckey = path.split("/") y, x, _ = map(int, ckey.split(".")) return x, y, int(level)
def strings_differ(string1: str, string2: str) -> bool: """Check whether two strings differ while avoiding timing attacks. This function returns True if the given strings differ and False if they are equal. It's careful not to leak information about *where* they differ as a result of its running time,...
def durationHuman(seconds): """ Turn number of seconds into human readable string """ seconds = int(round(seconds)) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) years, days = divmod(days, 365.242199) syears = str(years) ...
def renew_order(order, icon): """Returns the new order with the contracted indices removed from it.""" return [i for i in order if i not in icon]
def _mock_config_get(_, param): """Handle test configuration options.""" if param == 'coverage.fuzzer-testcases.bucket': return 'test-coverage-testcases' return None
def fix_ext(name, ext): """Add extension if it is missing""" if not ext[0] == '.': ext = '.' + ext if not name[-len(ext):].lower() == ext.lower(): name = name + ext return name
def string2xmihex(value_string): """ SaltXMI files store each value attribute twice (i.e. as a string and as a HEX value with some weird padded string in front of it that I still need to decode, e.g.:: <labels xsi:type="saltCore:SFeature" namespace="salt" name="SNAME" value="ACED000...
def is_caffe_layer(node): """The node an actual layer """ if node.startswith('caffe_layer_'): return True return False
def estimate_text_size(text): """ Provide a text size estimate based on the length of the text Parameters ---------- text: string Text meant to print on the IWP plot Returns ------- fontsize: float Estimated best fontsize """ fontsize = 12 if len(text) > 50: ...
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215',\ '*35214*', '*41532*', '*2*1***']) True >>> check_uniqu...
def sum_product(array: list) -> dict: """ BIG-O Notation: This will take O(N) time. The fact that we iterate through the array twice doesn't matter. :param array: list of numbers :return: """ total_sum = 0 total_product = 1 for i in array: total_sum += i for i in array: ...
def parse_original_im_name(im_name, parse_type='id'): """Get the person id or cam from an image name.""" assert parse_type in ('id', 'cam') if parse_type == 'id': parsed = -1 if im_name.startswith('-1') else int(im_name[:4]) else: parsed = int(im_name[4]) if im_name.startswith('-1') \ ...
def unique(sequence: list): """Returns all the unique items in the list while keeping order (which set() does not) Args: sequence (list): The list to filter Returns: list: List with only unique elements """ seen = set() return [x for x in sequence if not (x in seen or seen.add(...
def single_defcom_extract(start_from, srcls, is_class_begin=False): """ to extract a def function/class/method comments body Args: start_from(int): the line num of "def" header srcls(list): the source file in lines is_class_begin(bool): whether the start_from is a beginning a class....
def arrange_flights(flights, source): """Arranges flight legs in order. Finds source, moves to trip. Sets the next one in line as the source, moves to trip. Continues""" trip = [] while len(flights) > 0: for leg in flights: if leg[0] == source: source = leg[1] ...
def has_key_true(adjustspec, key): """ Checks if the key is in the adjustspec and if the key is True. return: :bool: if the key is set and is True """ if (key in adjustspec) and adjustspec[key] is True: return True else: return False