content
stringlengths
42
6.51k
def derivative_tanh(tanh_output): """ Compute derivative of Tanh function """ return 1 - tanh_output**2
def collect_not_null_kwargs(**kwargs) -> dict: """ Collect not null key value pair from keyword arguments. .. versionadded:: 1.0.1 """ return { k: v for k, v in kwargs.items() if v is not None }
def ordinal(i): """Returns i + the ordinal indicator for the number. Example: ordinal(3) => '3rd' """ i = int(i) if i % 100 in (11,12,13): return '%sth' % i ord = 'th' test = i % 10 if test == 1: ord = 'st' elif test == 2: ord = 'nd' elif test == 3: ord = 'rd' return '%s%s' % (i, ord)
def str_product(string): """ Calculate the product of all digits in a string """ product = 1 for i in string: product *= int(i) return product
def solution(n, array): """ Returns n counters after the increment and max operations coded in array. It iterates over array once and over the counters once, thus the time complexity is O(n + m) """ counters = [0] * n # Current greatest value calculated so far max_count = 0 # Value in max when the last max operation was found in array last_max_value = 0 for i in range(len(array)): if array[i] == n + 1: # when a max operation is demanded, we simply save the current max value # to use it in future increments last_max_value = max_count else: if counters[array[i] - 1] < last_max_value: # As we don't update all counters when we find a max operation, # we have to increment considering last_max_value counters[array[i] - 1] = last_max_value + 1 else: counters[array[i] - 1] += 1 # To avoid calculating max(), we update the max value at each step if counters[array[i] - 1] > max_count: max_count = counters[array[i] - 1] # As we don't update all counters when we find a max operation, # we have to make sure to update all counters we didn't already update return [max(i, last_max_value) for i in counters]
def choose(n: int, k: int) -> int: """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0
def _roundsf(x, n): """ Round to n significant digits """ return float('{:.{p}g}'.format(x, p=n))
def valid_num_brackets(expression: list) -> int and int: """Check the brackets in the expression. Returns: int and int: number of open brackets and number of close brackets. """ brackets = 0 for item in expression: if item == '(': brackets += 1 elif item == ')': brackets -= 1 if brackets < 0: return False return brackets == 0
def revcompSeq(seq): """ Get reverse complementary sequence """ return seq.translate(str.maketrans("ACGTN", "TGCAN"))[::-1]
def read_values(xs, sep, *values): """Read values from a string. Args: xs (str): Values as one string. sep (str): Separator separating the values in the string. *values (str): Names of the values. Returns: dict: Naming of the values mapping to the values. """ xs = [x.strip() for x in xs.split(sep)] if len(xs) != len(values): raise ValueError(f"Expected {len(values)} values, but got {len(xs)}.") return {v: int(x) for v, x in zip(values, xs)}
def strip_punctuation_space(value): """ Strip excess whitespace prior to punctuation using recursion """ if (value == None): return None elif (type(value) == list): # List, so recursively strip elements for i in range(0, len(value)): value[i] = strip_punctuation_space(value[i]) return value else: try: value = value.replace(" .", ".") value = value.replace(" :", ":") value = value.replace("( ", "(") value = value.replace(" )", ")") return value except(AttributeError): return value
def iob_iobes(tags): """ IOB -> IOBES """ new_tags = [] for i, tag in enumerate(tags): if tag == "O": new_tags.append(tag) elif tag.split("-")[0] == "B": if i + 1 != len(tags) and tags[i + 1].split("-")[0] == "I": new_tags.append(tag) else: new_tags.append(tag.replace("B-", "S-")) elif tag.split("-")[0] == "I": if i + 1 < len(tags) and tags[i + 1].split("-")[0] == "I": new_tags.append(tag) else: new_tags.append(tag.replace("I-", "E-")) else: raise Exception("Invalid IOB format!") return new_tags
def _capture_callback(x): """Validate the passed options for capturing output.""" if x in [None, "None", "none"]: x = None elif x in ["fd", "no", "sys", "tee-sys"]: pass else: raise ValueError("'capture' can only be one of ['fd', 'no', 'sys', 'tee-sys'].") return x
def mapz(function, list_of_args): """Just the *map* function with the *list* function applied afterwards. Ah, GwR...""" return list(map(function, list_of_args))
def gen_urdf_visual(geom, material, origin): """ Generates (as a string) the complete urdf element sequence for a `visual` child of a `link` element. This is essentially a string concatenation operation. :param geom: urdf element sequence for the geometry child of a visual element, ``str`` :param material: urdf element sequence for the material child of a visual element, ``str`` :param origin: urdf element sequence for the origin child of a visual element, ``str`` :returns: urdf element sequence for the `visual` child of a `link` element, ``str`` """ return '<visual>{0}{1}{2}</visual>'.format(geom, material, origin)
def get_embedded_items(result_collection): """ Given a result_collection (returned by a previous API call that returns a collection, like get_bundle_list() or search()), return a list of embedded items with each item in the returned list considered a result object. 'result_collection' a JSON object returned by a previous API call. The parameter 'embed_items' must have been True when the result_collection was originally requested.May not be None. Returns a list, which may be empty if no embedded items were found. """ # Argument error checking. assert result_collection is not None result = [] embedded_objects = result_collection.get('_embedded') if embedded_objects is not None: # Handle being passed a non-collection gracefully. result = embedded_objects.get('items', result) return result
def get_bool(env, name, default=False): """Get a boolean value from the environment If ``name`` is not found in ``env``, return ``True`` if ``default`` evaluates to ``True``, otherwise return ``False``. The following values are considered ``False``: * ``'False'`` * ``'false'`` * ``'Off'`` * ``'off'`` * ``'0'`` * ``'No'`` * ``'no'`` * ``''`` Any other value is considered ``True``. """ if name not in env: return bool(default) value = env[name] if value in ['False', 'false', 'Off', 'off', '0', 'No', 'no', '']: return False return True
def cutoff(s, length): """Truncates a string after a certain number of characters. :type s: str :param s: string to be truncated :type length: int :param length: max number of characters :rtype: str :return: truncated string""" if len(s) < length-2: return s return "%s.." % s[0:length-2]
def getConditionInZoneConditions(zone_condition, zone_conditions_data): """ Parses the zone conditions definition YAML files to find the condition that match both the zone condition passed in. """ condition = {} for c in zone_conditions_data['conditions']: if zone_condition != c['name']: continue condition['type'] = c['type'] properties = [] for p in c['properties']: property = {} property['property'] = p['property'] property['interface'] = p['interface'] property['path'] = p['path'] property['type'] = p['type'].lower() property['value'] = str(p['value']).lower() properties.append(property) condition['properties'] = properties return condition
def formatColorfa(a): """float array to #rrggbb""" return '#%02x%02x%02x' % (int(round(a[0]*255)),int(round(a[1]*255)),int(round(a[2]*255)))
def ssh_cmd_container_instance(detail) -> str: """SSH command to access a ecs2 instance by id.""" return f"TERM=xterm ssh {detail['ec2InstanceId']}"
def extract_user_info(client_config): """ Extract user info from the client config specified. Returns a dict that includes system key information. """ # test if there isn't a system user or if there isn't a name for that # user, return None if ('system user' not in client_config or 'name' not in client_config['system user']): return None user_info = dict() user_info['system_key'] = dict( user=client_config['system user']['name'], access_key=client_config['system user']['access key'], secret_key=client_config['system user']['secret key'], ) return user_info
def jupyter_config_json( package_name: str, enabled: bool = True ) -> dict: """Creates a Jupyter Config JSON file with one package defined.""" return { "NotebookApp": { "nbserver_extensions": { package_name: enabled } } }
def orthogonal(vector): """ :return: A new vector which is orthogonal to the given vector """ return vector[1], -vector[0]
def SIRD_model(t, y, b, g, l, N): """Gives the derivative of S, I, R, and D with respect to time at some t Parameters: t - The time at which the derivative is to be calculated y - Value of S, I, R, and D at t b - Parameter beta in the ODEs g - Parameter gamma in the ODEs l - Parameter lambda in the ODEs (see Q3 pdf) N - Size of the population Returns: List of derivatives at time t for S, I, R, and D (in that order) """ s, i, r, d = y return [-b*s*i/N, b*s*i/N - g*i - l*i, g*i, l*i]
def mappingIndexItemToName(index): """ Return the itemCode from itemID :param index: int :return: string, itemCode """ if index == 0: return 'R11' elif index == 1: return 'R12' elif index == 2: return 'R13' elif index == 3: return 'R14' elif index == 4: return 'R21' elif index == 5: return 'R22' elif index == 6: return 'R23' elif index == 7: return 'R31' elif index == 8: return 'R32' elif index == 9: return 'R41'
def bytes_to_str(s): """Convert bytes to str.""" if isinstance(s, bytes): return s.decode(errors='replace') return s
def hard_retype(value): """ tries to converts value to relevant type by re-typing :param value: value to be converted :type value: str (unicode) :return: re-typed value :rtype: int, float, bool, str """ try: return int(value) except ValueError: try: return float(value) except ValueError: if value.lower() in ('true', 'false'): return value.lower() == 'true' return value
def remove_comments(s): """removes the comments starting with # in the text.""" pos = s.find("#") if pos == -1: return s return s[0:pos].strip()
def _long_to_bytes(n, length, byteorder): """Convert a long to a bytestring For use in python version prior to 3.2 Source: http://bugs.python.org/issue16580#msg177208 """ if byteorder == 'little': indexes = range(length) else: indexes = reversed(range(length)) return bytearray((n >> i * 8) & 0xff for i in indexes)
def dotp(a, b): """Dot product of two equal-dimensioned vectors""" return sum(aterm * bterm for aterm,bterm in zip(a, b))
def get_value(dict, key, default=None): """Set value to value of key if key found in dict, otherwise set value to default.""" value = dict[key] if key in dict else default return value
def _shape_from_resolution(resolution): """ Calculate the shape of the global Earth relief grid given a resolution. Parameters ---------- resolution : str Same as the input for load_earth_relief Returns ------- shape : (nlat, nlon) The calculated shape. Examples -------- >>> _shape_from_resolution('60m') (181, 361) >>> _shape_from_resolution('30m') (361, 721) >>> _shape_from_resolution('10m') (1081, 2161) """ minutes = int(resolution[:2]) nlat = 180*60//minutes + 1 nlon = 360*60//minutes + 1 return (nlat, nlon)
def scaleto255(value): """Scale to Home-Assistant value.""" return max(0, min(255, round((value * 255.0) / 100.0)))
def find_numbers(data): """ Recursively find numbers in JSON data except dicts with "red" value """ if isinstance(data, int): return [data] numbers = [] if isinstance(data, list): for dat in data: numbers.extend(find_numbers(dat)) elif isinstance(data, dict): if "red" not in data.values(): for key in data: if isinstance(key, int): numbers.append(key) numbers.extend(find_numbers(data[key])) return numbers
def find_dict_in_list_from_key_val(dicts, key, value): """ lookup within a list of dicts. Look for the dict within the list which has the correct key, value pair Parameters ---------- dicts: (list) list of dictionnaries key: (str) specific key to look for in each dict value: value to match Returns ------- dict: if found otherwose returns None """ for dict in dicts: if key in dict: if dict[key] == value: return dict return None
def valid(bo, pos, num): """ Returns if the attempted move is valid :param bo: 2d list of ints :param pos: (row, col) :param num: int :return: bool """ # Check row for i in range(0, len(bo)): if bo[pos[0]][i] == num and pos[1] != i: return False # Check Col for i in range(0, len(bo)): if bo[i][pos[1]] == num and pos[1] != i: return False # Check box box_x = pos[1]//3 box_y = pos[0]//3 for i in range(box_y*3, box_y*3 + 3): for j in range(box_x*3, box_x*3 + 3): if bo[i][j] == num and (i,j) != pos: return False return True
def pair(pairstr): """Convert NxN or N,N to tuple.""" return tuple(int(_s) for _s in pairstr.replace('x', ',').split(','))
def get_user_choice(choices, choice_type, default_value=""): """ A common method to take user choice from a list of choices Args: (list) choices - list of choices (str) choice_type - Type of choice (boolean) default_value - Return default value in case wrong input Returns: (str) - User selected choice """ print("\n\n{}\n".format(choice_type)) # Display the choices to user for i in range(len(choices)): print("{}. {}".format(i + 1, choices[i].capitalize())) # User input for number for choice selection while True: try: # Input prompt for Choice choice = input("\nEnter your choice: ") # Convert input text in lowercase choice_lower = choice.lower() # Check if choice text match in list if choice_lower in choices: # Display corrected selection print("\nYou selected: {}".format(choice_lower.capitalize())) return choice_lower elif choice_lower.isdigit(): # Check if user used number for selection # Check if number choice has value in list choice_value = choices[int(choice_lower) - 1] # Display corrected selection print("\nYou selected: {}".format(choice_value.capitalize())) return choice_value else: if len(default_value) > 0: # Check for default value, if yes return that in wrong input event return default_value else: # Display input error message print("\nPlease enter a valid choice (text or number).") except KeyboardInterrupt: # Keyboard Interrupt need to handled so program can exit properly print("Exiting..") # Make sure we are passing the exception to chain raise except: if len(default_value) > 0: # Check for default value, if yes return that in wrong input event return default_value else: print("\nPlease enter a valid choice (1,2,3,...) or text.")
def maximumProduct(nums): """ :type nums: List[int] :rtype: int """ nums = sorted(nums) first_option=nums[0]*nums[1]*nums[-1] second_option=nums[-3] * nums[-2] * nums[-1] return first_option if first_option > second_option else second_option
def col_shade(s): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'rgba(0,0,0,0.5)' return 'background-color: {}'.format(color)
def gameLogic(compChoice, userChoice): """ This is the main game logic function which takes computers choice and user's choice as input. This function can retrun three variables based on status of winning, losing or tie.""" #If computer chooses rock if compChoice == 'r': if userChoice == 'r': # If user too selects rock then it is a tie return 't' elif userChoice == 'p': # If user selects paper then user wins return 'w' elif userChoice == 's': # If user selects scissor then user looses return 'l' else: print("Invalid Choice!") #If computer chooses paper elif compChoice == 'p': if userChoice == 'r': # If user selects rock then the user looses return 'l' elif userChoice == 'p': # If user too selects paper then it is a tie return 't' elif userChoice == 's': # If user selects scissors then the user wins return 'w' else: print("Invalid Choice!") #If computer chooses scissors elif compChoice == 's': if userChoice == 'r': # If user selects rock then the user wins return 'w' elif userChoice == 'p': # If user selects paper then the user looses return 'l' elif userChoice == 's': # If user too selects scissors then it is a tie return 't' else: print("Invalid Choice!") else: print("Kuch toh gadbad hai bhaiya!")
def fibonacci(n): """Compute the nth fibonacci number recursively.""" if n == 1 or n == 2: return 1 return fibonacci(n-1) + fibonacci(n-2)
def split_list(category_list): """ Split list of ranges into intervals and single char lists. :return: List of interval starting points, interval lengths and single chars """ unicode_category_interval_sps = [] unicode_category_interval_lengths = [] unicode_category_chars = [] for element in category_list: interval_length = element[1] - element[0] if interval_length == 0: unicode_category_chars.append(element[0]) elif (interval_length > 255): for i in range(element[0], element[1], 256): length = 255 if (element[1] - i > 255) else (element[1] - i) unicode_category_interval_sps.append(i) unicode_category_interval_lengths.append(length) else: unicode_category_interval_sps.append(element[0]) unicode_category_interval_lengths.append(element[1] - element[0]) return unicode_category_interval_sps, unicode_category_interval_lengths, unicode_category_chars
def get_class_methods(cls): """ Get a list of non-private class methods. """ return [getattr(cls, func) for func in dir(cls) if not func.startswith("__") and callable(getattr(cls, func))]
def normalise_email(email): """ The local part of an email address is case-sensitive, the domain part isn't. This function lowercases the host and should be used in all email handling. """ clean_email = email.strip() if '@' in clean_email: local, host = clean_email.rsplit('@', 1) return local + '@' + host.lower() return clean_email
def read_until(steg_bytes: bytes, offset: int, ending: str): """ Read the bytes of the steg_bytes from the offset until the ending byte sequence is found. Return the bytes read and the offset of the ending byte sequence. """ # Create a variable to hold the bytes read bytes_read = b"" # Loop through the steg_bytes while offset < len(steg_bytes): # Check if the current byte is the ending byte sequence if steg_bytes[offset:offset + len(ending)] == ending.encode(): # Return the bytes read and the offset of the ending byte sequence return bytes_read, offset # Read the next byte bytes_read += steg_bytes[offset:offset + 1] offset += 1
def text_progress_bar(iteration, num_iteration): """Displays a progress bar with the print function""" return print('|' * (iteration + 1) + '.' * (num_iteration - iteration - 1) + ' %.1f %%' % ((iteration + 1) / num_iteration * 100), end='\r')
def partition_to_color(partitions): """ Creates a dictionary with for every item in partition for every partition in partitions the index of partition in partitions. Parameters ---------- partitions: collections.abc.Sequence[collections.abc.Iterable] As returned by :func:`make_partitions`. Returns ------- dict """ colors = dict() for color, keys in enumerate(partitions): for key in keys: colors[key] = color return colors
def build_json(image_content): """Builds a json string containing response from vision api.""" json_data = { 'requests': [{ 'image': { 'content': image_content }, 'features': [{ 'type': 'FACE_DETECTION', 'maxResults': 1, }] }] } return json_data
def split_names(output): """ Designed to split up output from -o=name into a simple list of qualified object names ['kind/name', 'kind/name', ...] :param output: A single string containing all of the output to parse :return: A list of qualified object names """ if output is None: return [] return [x.strip() for x in output.strip().split("\n") if x.strip() != ""]
def task_request_statistics(contributions): """ Returns a list of task requests. """ task_requests = [] for contribution in contributions: # If contribution wasn't staff picked skip it if "task" in contribution["category"]: task_requests.append(contribution) return {"task_requests": task_requests}
def check_bbox_in_image(bbox, img_shape): """Ensure that all annotations are in the image and start at pixel 1 at a minimum Args: bbox (list) : list of [x_min, y_min, x_max, y_max] img_shape (tup) : shape of image in the form: (y, x, channels) Returns: bbox (list) : list of cleaned [x_min, y_min, x_max, y_max] """ # check to be sure all coordinates start at at least pixel 1 (required by faster rcnn) for i in range(len(bbox)): if bbox[i] <= 1.0: bbox[i] = 1.0 # check that the x_max and y_max are in the photo's dimensions if bbox[2] >= img_shape[1]: # x_max bbox[2] = img_shape[1]-1 if bbox[3] >= img_shape[0]: # y_max bbox[3] = img_shape[0]-1 return bbox
def _dec(A): """ >>> _dec([]) 0 >>> _dec([1]) 1 >>> _dec([1, 0, 1]) 5 """ sum = 0 for i, a in enumerate(A): sum += a*(1 << i) return sum
def conv_time(s): """ Convert seconds into readable format""" one_min = 60 one_hr = 60 * 60 one_day = 24 * 60 * 60 try: s = float(s) except: raise ValueError("Can't convert %s" % s) if s < one_min: return "%.2fs" % s elif s < one_hr: mins = int(s) / 60 secs = int(s % 60) return "%sm %ss" % (mins, secs) elif s < one_day: s = int(s) hours = s / one_hr mins = (s % one_hr) / 60 # secs = int(s - (hours * 60 * 60) - (mins * 60)) return "%sh %sm" % (hours, mins) else: s = int(s) days = s / one_day hours = (s % one_day) / one_hr mins = ((s % one_day) % one_hr) / one_min return "%sd %sh %sm" % (days, hours, mins)
def has_palindrome(i, start, length): """Checks if the string representation of i has a palindrome. i: integer start: where in the string to start length: length of the palindrome to check for """ s = str(i)[start:start+length] return s[::-1] == s
def is_power2(num): """ Returns true if a number is a power of two """ return num != 0 and ((num & (num - 1)) == 0)
def check_for_overlap(a, b): """ Returns true if two sets are not overlaping. Used here to check if two stems share a common residue. If they do, returns False. """ # https://stackoverflow.com/questions/3170055/test-if-lists-share-any-items-in-python # return True is the is no overlap, else False return(set(a).isdisjoint(b))
def sort_donors(donor_dict): """Sort the list of donors by total amount donated. Returns a list of only the donors' names. """ return sorted(list(donor_dict), key=lambda x: -sum(donor_dict[x]))
def _get_engine_names(job_name): """Return the (engine display name, engine name) for the job.""" if job_name.startswith('afl_'): return 'AFL', 'afl' if job_name.startswith('libfuzzer_'): return 'libFuzzer', 'libFuzzer' return 'Unknown', 'Unknown'
def readable_time(time_difference): """Convert a float measuring time difference in seconds into a tuple of (hours, minutes, seconds)""" hours = time_difference // 3600 minutes = (time_difference // 60) % 60 seconds = time_difference % 60 return hours, minutes, seconds
def insert_at(list_a: list, position: int, item): """Problem 21: Insert element at a given position into a list. Parameters ---------- list_a : list The input list position : int The position where the inserted element should be item The element to insert to the list Returns ------- list A list with an inserted element at the proper position Raises ------ TypeError If the given argument is not of `list` type ValueError If the given `k` is not valid. """ if not isinstance(list_a, list): raise TypeError('The argument given is not of `list` type.') if position < 0 or len(list_a) < position: raise ValueError('The value of `n` is not valid.') list_a.insert(position - 1, item) return list_a
def mk_var_expr(name): """ returns a variable expression of name NAME where NAME is a string """ return {"type" : "var" , "name" : (name, 0)}
def get_time_segments(sensor, segments): """ Function to extract the start timestamps and end timestamps sorted from early to late from a feature segment :param sensor: sensor dimension of segment (int) :param segments: feature segments to extract the timestamps for :returns: starts and ends in sorted lists """ starts = [] ends = [] for _, segment in segments: if segment[0] == sensor: starts.append(segment[1]) ends.append(segment[2]) starts_sorted = [start for start, _ in sorted(zip(starts, ends))] ends_sorted = [end for _, end in sorted(zip(starts, ends))] return starts_sorted, ends_sorted
def strip_extension(name: str) -> str: """ Remove a single extension from a file name, if present. """ last_dot = name.rfind(".") if last_dot > -1: return name[:last_dot] else: return name
def _send_not_success_response(status_code): """ Function to be called when the response is not 200 """ return { "status": status_code, "data": None }
def get_ax_lim(ax_min, ax_max, base=10): """ Get axis limit Parameters ---------- ax_min : float ax_max : float base : int, default = 10 Returns ------- ax_min : float ax_max : float """ from math import ceil, floor ax_min = floor(ax_min * base) / base ax_max = ceil(ax_max * base) / base return ax_min, ax_max
def total(): """Returns the total number of grains on the chessboard.""" return 2**64 - 1
def get_video_id_by_number(number, results): """Get video id by its number from the list of search results generated by search_by_keyword function call. Videos are numbered from 1 to maxResults (optional search parameter, set by default to 5, see https://developers.google.com/youtube/v3/docs/search/list) as in results list. Args: number (int): number of video whose id is requested results (list): list of search results generated by search_by_keyword function call Returns: string: youtube video id """ return results[number-1]['id']['videoId']
def weighted_gap_penalty(col, seq_weights): """ Calculate the simple gap penalty multiplier for the column. If the sequences are weighted, the gaps, when penalized, are weighted accordingly. """ # if the weights do not match, use equal weight if len(seq_weights) != len(col): seq_weights = [1.] * len(col) gap_sum = 0. for i in range(len(col)): if col[i] == '-': gap_sum += seq_weights[i] return 1 - (gap_sum / sum(seq_weights))
def match_candidates_by_order(images_ref, images_cand, max_neighbors): """Find candidate matching pairs by sequence order.""" if max_neighbors <= 0: return set() n = (max_neighbors + 1) // 2 pairs = set() for i, image_ref in enumerate(images_ref): a = max(0, i - n) b = min(len(images_cand), i + n) for j in range(a, b): image_cand = images_cand[j] if image_ref != image_cand: pairs.add(tuple(sorted((image_ref, images_cand)))) return pairs
def is_valid_boolean(val): """ Checks if given value is boolean """ values = [True, False] return val in values
def g_diode(f, f_diode, alpha): """Theoretical model for the low-pass filtering by the PSD. See ref. 2, Eq. (11). """ return alpha ** 2 + (1 - alpha ** 2) / (1 + (f / f_diode) ** 2)
def _plus(arg1, arg2): """int plus""" return str(int(arg1) + int(arg2))
def contains(text, pattern): """Return a boolean indicating whether pattern occurs in text.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) # kind of self explanatory if pattern in text: return True else: return False
def make_window(n, k = 1000, l = 100): """bin n numbers into windows, k points per window with l overlap """ op = [[i-l, i+k+l] for i in range(0, n, k)] op[0][0] = 0 op[-1][1] = n if (len(op) > 1 and op[-1][1]-op[-1][0] < k/2 + l): op.pop() op[-1][1] = n return op
def normalize_color_tuple(h :int, s:int, x:int) -> tuple: """ Normalize an HSV or HSL tuple. Args: h: `int` in {0, ..., 360} corresponding to hue. s: `int` in {0, ..., 100} corresponding to saturation. x: `int` in {0, ..., 100} corresponding to light or value. Returns:l The corresponding normalized tuple. """ return (h / 360, s / 100, x / 100)
def name_to_crate_name(name): """Converts a build target's name into the name of its associated crate. Crate names cannot contain certain characters, such as -, which are allowed in build target names. All illegal characters will be converted to underscores. This is a similar conversion as that which cargo does, taking a `Cargo.toml`'s `package.name` and canonicalizing it Note that targets can specify the `crate_name` attribute to customize their crate name; in situations where this is important, use the compute_crate_name() function instead. Args: name (str): The name of the target. Returns: str: The name of the crate for this target. """ for illegal in ("-", "/"): name = name.replace(illegal, "_") return name
def _get_formatted_size(bytes): """ formats the supplied bytes """ if bytes < 1000: return '%i' % bytes + ' B' elif 1000 <= bytes < 1000000: return '%.1f' % (bytes / 1000.0) + ' KB' elif 1000000 <= bytes < 1000000000: return '%.1f' % (bytes / 1000000.0) + ' MB' elif 1000000000 <= bytes < 1000000000000: return '%.1f' % (bytes / 1000000000.0) + ' GB' else: return '%.1f' % (bytes / 1000000000000.0) + ' TB'
def first_down(items): """Return True if the first item is down.""" return items[0] == '-'
def convert_string(string, chars=None): """Remove certain characters from a string.""" if chars is None: chars = [',', '.', '-', '/', ':', ' '] for ch in chars: if ch in string: string = string.replace(ch, ' ') return string
def get_bool_param(param): """Return bool param value.""" if isinstance(param, bool): return param return True if param.strip().lower() == 'true' else False
def searchsorted(arr, x, N=-1): """N is length of arr """ if N == -1: N = len(arr) L = 0 R = N - 1 done = False eq = False m = (L + R) // 2 while not done: xm = arr[m] if xm < x: L = m + 1 elif xm > x: R = m - 1 elif xm == x: L = m eq = True done = True m = (L + R) // 2 if L > R: done = True return L, eq
def value_to_zero_or_one(s): """Convert value to 1 or 0 string.""" if isinstance(s, str): if s.lower() in ("true", "t", "yes", "y", "1"): return "1" if s.lower() in ("false", "f", "no", "n", "0"): return "0" if isinstance(s, bool): if s: return "1" return "0" raise ValueError("Cannot covert {} to a 1 or 0".format(s))
def _find_and_replace(text, start_string, end_string, replace_fn): """Remove everything found between instances of start_string and end_string. Replace each such instance with replace_fn(removed_text) e.g. _find_and_replace(u"the [[fat]] cat [[sat]]", u"[[", u"]]", lambda x: x) = u"the fat cat sat" Args: text: a unicode string start_string: a unicode string end_string: a unicode string replace_fn: a unary function from unicode string to unicode string Returns: a string """ ret = u"" current_pos = 0 while True: start_pos = text.find(start_string, current_pos) if start_pos == -1: ret += text[current_pos:] break ret += text[current_pos:start_pos] end_pos = text.find(end_string, start_pos + len(start_string)) if end_pos == -1: break ret += replace_fn(text[start_pos + len(start_string):end_pos]) current_pos = end_pos + len(end_string) return ret
def _methodProperties(methodDesc, schema, name): """Get properties of a field in a method description. Args: methodDesc: object, fragment of deserialized discovery document that describes the method. schema: object, mapping of schema names to schema descriptions. name: string, name of top-level field in method description. Returns: Object representing fragment of deserialized discovery document corresponding to 'properties' field of object corresponding to named field in method description, if it exists, otherwise empty dict. """ desc = methodDesc.get(name, {}) if "$ref" in desc: desc = schema.get(desc["$ref"], {}) return desc.get("properties", {})
def generate_extension_to_string_mapping(extensions): """Returns mapping function from extensions to corresponding strings.""" function = 'const char* ExtensionToString(Extension extension) {\n' function += ' switch (extension) {\n' template = ' case Extension::k{extension}:\n' \ ' return "{extension}";\n' function += ''.join([template.format(extension=extension) for extension in extensions]) function += ' };\n\n return "";\n}' return function
def helper_capitalize(text): """ (string) -> string proprely capitalize course titles """ capitalized = '' for char in text: if char.isalpha(): capitalized += char.upper() else: capitalized += char return capitalized
def get_id(vmfObject, idPropName='id'): """ Returns the ID of the given VMF object. """ return int(vmfObject[idPropName])
def response_creator(text, card): """ Builds a response with speech part and Alexa appcard contents :param text: text to be spoken :param card: text for the app card :return: JSON object to be returned """ text_item = {"type": "PlainText", "text": text} card_item = {"type": "Simple", "title": "Stop Info", "content": card} reprompt = { "outputSpeech": {"text": "Which stop do you want to know about?", "type": "PlainText"}} response = {"version": "1.0", "response": {"outputSpeech": text_item, "card": card_item, "reprompt": reprompt, "shouldEndSession": True}} return response
def quality_check(data): """ Expects string, returns tuple with valid data or False when data was invalid """ if data != False: if "RAWMONITOR" in data: data = data.replace("RAWMONITOR","") data = data.split("_") frequency = int(data[0]) temperature = int(data[1]) / 10 return "{0},{1:.1f}".format(frequency, temperature) else: return False
def get_headers(referer): """Returns the headers needed for the transfer request.""" return { "Content-Type": "application/json; charset=UTF-8", "X-Requested-With": "XMLHttpRequest", "Referer": referer }
def _format_probability(prob): """ Format prediction probability for displaying INPUT prob: raw model probability, float OUTPUT label : cleaned probability, str """ return f'{round(100 * prob, 2)}%'
def get_dhm(timediff): """Format time in a human-readable format.""" d = int(timediff / 86400) timediff %= 86400 h = int(timediff / 3600) timediff %= 3600 m = int(timediff / 60) return f"{d}`{h:02}:{m:02}"
def segmentation_blocks_test_a(band_pass_signal_hr, sb, sh, dim): """THIS SECTION REMAINS FOR TESTING PURPOSES Function used for the segmentation of the signal into smaller parts of audio (blocks). This implementation has been modified in order to make a simpler version of the original one. After the tests, it has been proven that this algorithm is way faster than the original, it reduces some uncertainty and the number of blocks remains the same in most cases. Also, it treats the void that leaves the standard in blocks that have samples that ar out of bounds. Parameters ---------- band_pass_signal_hr: numpy.array Time signal values of the input signal. sb: int Block size. sh: int Hop size. dim: int Signal dimensions. Returns ------- block_array: List[List[float]] Array list of blocks in which the signal has been segmented. """ # Creation of the Array list of blocks with a specific block size (sb) and hop size (sh) block_array = [ band_pass_signal_hr[block_s : block_s + sb] for block_s in range(0, len(band_pass_signal_hr), sh) ] return block_array
def ensure_list(config): """ ensure_list Ensure that config is a list of one-valued dictionaries. This is called when the order of elements is important when loading the config file. (The yaml elements MUST have hyphens '-' in front of them). Returns config if no exception was raised. This is to keep the same format as ensure_dictionary, and allowed possible config file repairs in the future without breaking the API. """ if not isinstance(config, list): raise TypeError("config is not a list. Did you forget some '-' "+ "in your configuration file ?\n" + str(config)) for element in config: if isinstance(element, str): continue if not isinstance(element, dict): raise ValueError("Parsing error in the configuration file.\n" + str(element)) if len(element) != 1: raise ValueError("Parsing error in the configuration file.\n" + str(element)) return config
def separate_file_from_parents(full_filename): """Receives a full filename with parents (separated by dots) Returns a duple, first element is the filename and second element is the list of parents that might be empty""" splitted = full_filename.split('.') file = splitted.pop() parents = splitted return file, parents
def to_string(value): """ Convert a boolean to on/off as a string. """ if value: return "On" else: return "Off"
def nbi_calci(red, nir, swir): """ new build-up index """ return (swir * red)/nir
def _method_info_from_argv(argv=None): """Command-line -> method call arg processing. - positional args: a b -> method('a', 'b') - intifying args: a 123 -> method('a', 123) - json loading args: a '["pi", 3.14, null]' -> method('a', ['pi', 3.14, None]) - keyword args: a foo=bar -> method('a', foo='bar') - using more of the above 1234 'extras=["r2"]' -> method(1234, extras=["r2"]) @param argv {list} Command line arg list. Defaults to `sys.argv`. @returns (<method-name>, <args>, <kwargs>) """ import json import sys if argv is None: argv = sys.argv method_name, arg_strs = argv[1], argv[2:] args = [] kwargs = {} for s in arg_strs: if s.count('=') == 1: key, value = s.split('=', 1) else: key, value = None, s try: value = json.loads(value) except ValueError: pass if key: kwargs[key] = value else: args.append(value) return method_name, args, kwargs