content
stringlengths
42
6.51k
def rescale_x(x,min_x,max_x): """ Rescale or nornalize value from 0 to 1 with defined limits Args: x (float) : value to be rescaled min_x (float) : lower limit of range max_x (float) : upper limit of range Returns: float: Value between 0 and 1 representing a...
def linear_search(array, element): """ Linear Search Complexity: O(N) """ indices = [] for i in range(len(array)): if element == array[i]: indices.append(i) return indices
def one_hot_encode(label): """One-Hot Encoding. This function given a label - "red", "green", or "yellow", returning a one-hot encoded label. One-Hot Encode of "red" return: [1, 0, 0] One-Hot Encode of "yellow" return: [0, 1, 0] One-Hot Encode of "green" return: [0, 0, 1] """ # Init ...
def convert_list_to_tuple(shp): """Check the type of the shape, if is list, convert to tuple""" if not isinstance(shp, (list, tuple)): raise ValueError(f"The shape variable should be a list or tuple, but got {type(shp)}") if isinstance(shp, list): shp = tuple(shp) return shp
def objectId(item): """ Create a string id for a database derived object that can be used to identify the object in application code """ if item == None: return None if "__table__" not in dir(item): return None return ( item.__class__.__name__ + "_" +...
def round_freqs(frequencies, num_dp): """ round frequency estimates to useful precision (reduces file size) """ return [round(x, num_dp) for x in frequencies]
def clean_backticks(msg): """Prevents backticks from breaking code block formatting""" return msg.replace("`", "\U0000ff40")
def megapipe_query_sql(ra, dec, size): """ Return SQL query command of CFHT megapipe Parameters: ra (float): in degree dec (float): in degree size (float): in degree Returns: url (str): The query URL, need to be opened by `wget` or `curl`. """ return ("htt...
def try_del_key_case_insensitive(d, key_name): """ Look in a dictionary for all keys with the given key_name, without concern for case. If found, delete them from the dictionary. """ to_delete = [] for name, value in d.items(): if name.lower() == key_name.lower(): to_delete.a...
def _distSQR(a,b): """return the square of distance between point a and point b (3 dimension)""" return (a[0]-b[0])**2 +(a[1]-b[1])**2 + (a[2]-b[2])**2
def c_ah_lookup(ah_lut, t_lo, t_hi, temp, rh): """ Fixed point implementation (for C conversion) The only non-fixed point aspect is the final division by 1000. for comparison with the floating point version """ if rh == 0: return 0 rh = int(rh * 1000) norm_humi = (rh * 82) >> 13 tem...
def cmake_cache_option(name, boolean_value, comment=""): """Generate a string for a cmake configuration option""" value = "ON" if boolean_value else "OFF" return 'set(%s %s CACHE BOOL "%s")\n\n' % (name,value,comment)
def join_values(values): """Return the values as a space-delimited string.""" return " ".join((str(v) for v in values))
def predicate_contains_hello(x): """Predicate True when 'hello' is in value.""" return 'hello' in x
def fv_f(pv, r, n): """ Objective: Estimate future value Formula: fv = pv * (1 + r) ^ n fv: future value pv: present value r : discount periodic rate n : number of periods """ return pv * (1 + r)**n
def get_cheapest_path(paths): """ looks for cheapest path. if multiple match, takes quickest """ lowest_val = min([x[1] for x in paths]) cheapest = [x[0] for x in paths if x[1] == lowest_val] if len(cheapest) == 0: return False elif len(cheapest) > 1: quickest = min([len(x) for x in ...
def lz77_compression(src): """ Compress the given string. Replace similar occurences with #copy,steps_back# """ # MAX_BUFFER = 65536 # MAX_BUFFER = 32768 MAX_BUFFER = 4096 # MAX_BUFFER = 2048 # MAX_BUFFER = 100 MAX_COPY_LEN = 10 packed_message = '' run_idx = 0 main_...
def parse_record1(raw_record): """Parse raw record and return it as a set of unique symbols without \n""" return set(raw_record) - {"\n"}
def ellipse(lst, max_display=5, sep='|'): """ Like join, but possibly inserts an ellipsis. :param lst: The list to join on :param int max_display: the number of items to display for ellipsing. If -1, shows all items :param string sep: the delimiter to join on """ # copy the list (or ...
def clear_builtins(attrs): """ Clears the builtins from an ``attrs`` dict Returns a new dict without the builtins """ new_attrs = {} for key in attrs.keys(): if not(key.startswith('__') and key.endswith('__')): new_attrs[key] = attrs[key] return new_attrs
def make_igv_tracks(name, file_list): """Return a dict according to IGV track format.""" track_list = [] for track in file_list: track_list.append({"name": name, "url": track, "min": 0.0, "max": 30.0}) return track_list
def to_quil_complex_format(num) -> str: """A function for outputting a number to a complex string in QUIL format.""" cnum = complex(str(num)) return f"{cnum.real}+{cnum.imag}i"
def parse_int_set(nputstr): """Utilty funciton to parse integer sets and ranges https://stackoverflow.com/questions/712460/interpreting-number-ranges-in-python/712483 """ selection = set() invalid = set() # tokens are comma seperated values tokens = [x.strip() for x in nputstr.split(",")] ...
def shift_bit_length(x): """ Find the closest power of 2 that is superior or equal to the number x. Parameters ---------- x : scalar Returns ------- y : scalar the closest power of 2 that is superior or equal to the number x Examples -------- >>> maa...
def QVariantHack(*args): """Hack when sip.setapi('QVariant') is 2""" if len(args) == 0: return None elif len(args) == 1: return args[0] else: raise NotImplementedError(str(args))
def lockerNumDigits (lockerNum, theDictionary): """Adds leading zeroes as needed to lockerNum. End number of digits of lockerNum (leading zeroes and the num) is equivalent to number of digits of length of theDictionary. :param str lockerNum: The locker number to ensure has sufficient digits ...
def has_registered_slaves(mesos_state): """ Return a boolean indicating if there are any slaves registered to the master according to the mesos state. :param mesos_state: the mesos state from the master :returns: a boolean, indicating if there are > 0 slaves """ return len(mesos_state.get('slave...
def _represents_int(num_str: str) -> bool: """Check if a string is a number""" try: int(num_str) return True except ValueError: return False
def calculate_largest_square_filled_space_optimized1(matrix): """ A method that calculates the largest square filled with only 1's of a given binary matrix (space-optimized 1/2). Problem description: https://practice.geeksforgeeks.org/problems/largest-square-formed-in-a-matrix/0 time complexity: O(n...
def flatten_conf(cl): """ Takes configuration space and returns list of dictionary values for each config. In: [({"a": 1, "b": 1}, {"a": 2, "b": 1}), ({"a": 2, "b": 2}, {"a": 3, "b": 1})] Out: [[1, 1, 2, 1], [2, 2, 3, 1]] """ r = list() for ct in cl: tmp = list() ...
def get_transformers(train_dataset): """Get transformers applied to datasets.""" transformers = [] #transformers = [ # dc.trans.LogTransformer(transform_X=True), # dc.trans.NormalizationTransformer(transform_y=True, # dataset=train_dataset)] return transformers
def _list_to_and_str(lyst): """Convert a list to a command delimited string with the last entry being an and :param lyst: The list to turn into a str :type lyst: list :return: The nicely formatted string :rtype: str """ res = "{most} and {last}".format(most=", ".join(lyst[:-1]), last=ly...
def capword(s): """ >>> capword('foo') 'Foo' """ return s[0].upper() + s[1:]
def dotstar_color_wheel(wheel_pos): """Color wheel to allow for cycling through the rainbow of RGB colors.""" wheel_pos = wheel_pos % 255 if wheel_pos < 85: return 255 - wheel_pos * 3, 0, wheel_pos * 3 elif wheel_pos < 170: wheel_pos -= 85 return 0, wheel_pos * 3, 255 - wheel_po...
def flannel_network_spec(network_id, network_name): """ Returns hard coded specification of the flannel network specification """ spec = { 'port_security_enabled': True, 'provider:network_type': u'vxlan', 'id': network_id, 'type': 'bridge', 'status': 'ACTIVE', ...
def truncatewords(base, length, ellipsis="..."): """Truncate a string by words""" # do we need to preserve the whitespaces? baselist = base.split() lenbase = len(baselist) if length >= lenbase: return base # instead of collapsing them into just a single space? return " ".join(baseli...
def safe_decode(hex_encoded_string): """ :param hex_encoded_string: :return: """ if hex_encoded_string.startswith("0x"): return bytes.fromhex(hex_encoded_string[2:]) else: return bytes.fromhex(hex_encoded_string)
def calculate_delta_s(dis, prec, et): """Calculates the storage change for all days""" dS = prec - dis - et return dS
def get_filename(metallicity=0.0, dust=0.0, age=1.0): """Generates the standard filename we use to access the files Parameters: metallicity (float): log(Z) in solar units (so 0.0 is solar metallicity) dust (float): dust parameter age (float): current age of stellar population in Gyr Returns: ...
def index_to_position(index, strides): """ Converts a multidimensional tensor `index` into a single-dimensional position in storage based on strides. Args: index (array-like): index tuple of ints strides (array-like): tensor strides Return: int : position in storage """ ...
def main(x, y): """ Evaluation. @ In, x, float, value @ In, y, float, value @ Out, ans, float, value """ val = 1.0 - (x+y)/2.0 return val
def as_property(fact): """Convert a fact name to the name of the corresponding property.""" return f'is_{fact}'
def find_version(s, epoch, release): """ Given a package version string, return the version """ try: es = '{0!s}:'.format(epoch) e = s.index(es) + len(epoch) + 1 except ValueError: e = 0 try: rs = '-{0!s}'.format(release) r = s.index(rs) except ValueError:...
def MIN(strArg, composList, atomDict): """ *Calculator Method* calculates the minimum value of a descriptor across a composition **Arguments** - strArg: the arguments in string form - compos: the composition vector - atomDict: the atomic dictionary **Returns** a float """...
def options_not_in_config(cfg, options): """ Returns a list of :py:class:`~enrich2.plugins.options.Options` objects with keys in *options* not seen in the *cfg* dictionary, typically parsed from an external configuration file. Parameters ---------- cfg : dict options : :py:class:`~enric...
def _clean(x): """Auxiliary function to clean a string Series.""" return x.replace(";", " ").replace(",", " ").replace(" ", " ").strip()
def quat_real(quaternion): """Return real part of quaternion. >>> quat_real([3, 0, 1, 2]) 3.0 """ return float(quaternion[0])
def csv_to_json(csv_data): """Converts a Matrix to an Array of Json's""" json_records = [] try: json_keys=csv_data[0] for csv_row in csv_data[1:]: csv_dict = dict() index = 0 for key in json_keys: if not csv_row[index]: ...
def recall(c, tweets): """Computes recall for class `c` on the specified test data.""" tp = 0 fn = 0 for tweet in tweets: if c in tweet['tags']: if c in tweet['predictions']: tp+=1 else: fn+=1 if tp+fn == 0: return float('nan...
def vhost_get_default_server(config, default): """Get vhost default directive which makes it the default vhost.""" if default: if config['server'] == 'nginx': # The leading space is required here for the template to # separate it from the port directive left to it. re...
def do_any_are_in(candidates, bucket): """ :param candidates: [] of * List of objects :param bucket: [] of * List of objects :return: bool True iff any object of the first list is in bucket """ for candidate in candidates: if candidate in bucket: retu...
def get_icon_detail(icon_details): """ Iterate over icon details from response. This method is used in "risksense-get-apps" command. :param icon_details: Icon details from response. :return: List of required icon detail dictionary. """ return [{ 'Type': icon_detail.get('type', ''), ...
def get_model_name(model): """Return .name or ._name or 'dummy_model_name'""" if hasattr(model, 'name'): return model.name if hasattr(model, '_name'): return model._name return 'dummy_model_name'
def format_trace_id(trace_id: int) -> str: """Format the trace id for Datadog.""" return str(trace_id & 0xFFFFFFFFFFFFFFFF)
def bitpos_from_mask(mask, lsb_pos=0, increment=1): """ Turn a decimal value (bitmask) into a list of indices where each index value corresponds to the bit position of a bit that was set (1) in the mask. What numbers are assigned to the bit positions is controlled by lsb_pos and increment, as explai...
def format_time(total_seconds, hours_fmt=False, precise=False, hours_pad=True): """ Convert total_seconds float into a string of the form "02:33:44". total_seconds amounts greater than a day will still use hours notation. Output is either in minutes "00:00" formatting or hours "00:00:00" formatting. ...
def chunkIt(seq, num): """Divide list 'seq' into 'num' (nearly) equal-sized chunks. Returns a list of lists; some empty lists if num is larger than len(seq).""" # Copied directly from: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python avg = len(seq) / float...
def is_point_in_bbox(point, bbox): """ :param point: array of x,y :param bbox: array of xmin,ymin,xmax,ymax """ x = point[0] y = point[1] xmin = bbox[0] ymin = bbox[1] xmax = bbox[2] ymax = bbox[3] #print ("{}, {}".format(point, bbox)) return x >= xmin and x <= xmax and y >= ymin and y <= ymax
def check_fields(passport: dict) -> bool: """check if a passport contains all the required fields""" required_fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"] for required_field in required_fields: if required_field not in passport.keys(): return False elif passport[req...
def get_chunk_num(size, chunk_size=1048576): """ get_chunk_num Args: size: name chunk_size Returns: chunk_num """ if size % chunk_size == 0: return size // chunk_size return size // chunk_size + 1
def remove_bullet(body_line: str) -> str: """Remove line bullet if exist. Ex: get `* Fix bugs` return `Fix bugs`. Args: body_line (str): The single line of message body. Returns: str: The message without non-alpha characters at the beginning of the line. """ content = "" i...
def choose_weapon(decision, weapons): """Chooses a weapon from a given list based on the decision.""" choice = [] for i in range(len(weapons)): if i < decision: choice = weapons[i] return choice
def make_card_field(name, order): """Create common card field struct with given name and order number.""" return { 'name': name, 'media': [], 'sticky': False, 'rtl': False, 'ord': order, 'font': 'Arial', 'size': 20 }
def _env_to_bool(val): """ Convert *val* to a bool if it's not a bool in the first place. """ if isinstance(val, bool): return val val = val.strip().lower() if val in ("1", "true", "yes"): return True return False
def __repeat_to_length(string_to_expand: str, length: int) -> str: """ Repeat a string to a given times. :param string_to_expand: The string to repeat. :type string_to_expand: str :param length: The times to repeat. :type length: int :return: Formatted String. :rtype: str """ re...
def fibrecur(n): """Write a recursive function to compute the Fibonacci sequence. How does the performance of the recursive function compare to that of an iterative version?""" if n <= 1: return n return fibrecur(n-1) + fibrecur(n-2)
def phone_number(pstr): """ Extract the extension from the phone number if it exists. """ if ';' in pstr: # In one case we have multiple phone numbers separated by a # semi-colon. We simply pick the first one. Note this means we're # "throwing away" the other phone numbers. pstr...
def clean_tag(tag): """clean up tag.""" if tag is None: return None t = tag if t.startswith('#'): t = t[1:] t = t.strip() t = t.upper() return t
def flatten(a_list_of_keys): """flatten a list of keys where items in list can be str or tuple of str. Used when checking for keys that are not""" flattened = [] for str_or_tuple_key in a_list_of_keys: if type(str_or_tuple_key) == str: flattened.append(str_or_tuple_key) e...
def count_true(seq, pred=lambda x: x): """How many elements is ``pred(elm)`` true for? With the default predicate, this counts the number of true elements. This is equivalent to the ``itertools.quantify`` recipe, which I couldn't get to work. """ ret = 0 for x in seq: if pred(x): ...
def days_in_month_365(month, year=0): """Days of the month (365 days calendar). Parameters ---------- month : int numerical value of the month (1 to 12). year : int, optional (dummy value). Returns ------- out : list of int days of the month. Notes ----...
def adj_stormwater_rate_cap(rate: float, maxcap: float, efficiency: float, verbose: bool=True) -> list: """Adjust the stormwater rate and capacity by the stormwater efficiency. """ adj_rate = rate*efficiency adj_cap = maxcap*efficiency results = [adj_...
def _trim_name(image): """Remove the slash at the end of the filename.""" return image[:-1] if image[-1] == '/' else image
def cleanup_code(content): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` return content.strip('` \n')
def write_dict(data, delims="{}"): """Writes a formatted string from a dictionary. The format of the output is as for a standard python dictionary, {keyword[0]: arg[0], keyword[1]: arg[1],..., keyword[n]: arg[n]}. Note the space after the commas, and the use of curly brackets. Args: data: The v...
def collection_add_widget(addon, condensed=False): """Displays 'Add to Collection' widget""" return {'addon': addon, 'condensed': condensed}
def format_rolls(rolls): """Return a string representing the given *rolls* and their sum, in the form `"1 2 3 4 = 10"`.""" rolls = list(rolls) if not rolls: return 'no rolls' return '\x02{}\x02 = {}'.format( ' '.join(str(r) for r in sorted(rolls)), sum(rolls))
def validate_ecoli(seq_list, metadata_reports): """ Checks if the uidA marker, hlyA marker and vt markers are present in the combinedMetadata sheets and stores True/False for each SeqID. Values are stored as tuples: (uida_present, verotoxigenic, hlya_present) :param seq_list: List of OLC Seq IDs :pa...
def merge(know, information): """Merge two set of information""" return know # result = [] # for i in range(len(know)): # a = know[i] # b = information[i] # r = [] # for j in range(2): # if a[j] != '?': # r.append(a[j]) # elif b[j] ...
def findTheDifference(string1: str, string2: str) -> str: """ Determines which letter(s) in string1 are not in string2. :param string1: The string that has one (or more) letters than string2 :param string2: The string that has fewer letters than string1 :return: The letters that are in string1 and n...
def f_eq_zero(x,prec,ref=1.): """ Checks whether x is zero with precision prec*(ref+1.) """ return abs(x) <= prec * (abs(ref) + 1.)
def split_str_to_list(input_str, split_char=","): """Split a string into a list of elements. Args: input_str (str): The string to split split_char (str, optional): The character to split the string by. Defaults to ",". Returns: (list): The string split into a list "...
def int2byte(i): """ Integer to two bytes. """ i1 = i % 256 i2 = int(i/256) return chr(i1) + chr(i2)
def dict_contains(keys: tuple, check_dict: dict) -> bool: """ Check if a dictionary contains all of the desired keys. """ for key in keys: if not key in check_dict: return False return True
def find_next_available(fields, existing): """iterate until a fields does not conflic with an item in existing""" i = 1 orig = tuple(fields) while fields in existing: fields = tuple("%s-%d" % (f, i) for f in orig) i += 1 return tuple(fields)
def calc_Ti(Te, Tg, n): """Calcuate the infectious period""" return (Tg - Te) * 2.0 * n / (n + 1.0)
def psqlize_int_list(int_list): """Formats int_list as a list for the postgres "IN" operator. `See postgres documentation for what constitutes as a list for this operator. <https://www.postgresql.org/docs/9/functions-comparisons.html>`_ :param list[int] int_list: List to format :return: Format...
def dot(A, b): """Dot product between a 2D matrix and a 1D vector""" return [sum([aij * bj for aij, bj in zip(ai, b)]) for ai in A]
def generate_new_board(grid, word_data): """ Given a board and a chosen word (with sequence of coords.) generate a new board (simulating letters falling) grid: the current grid as a list of row-strings word_data: tuple of (word, array of coordinates for choosing the letters from grid) R...
def previous_status_percentage(status_list, index): """ Sums the status_percentage of the status in status_list before index. This is for finding the length of invisible progress bars in stat boxes """ previous_percentage = 0 for status in status_list[:index]: previous_percentage += stat...
def make_ssh_conn(hostname): """ This function creates a connections dict used when creating a new Device instance. The returned dict will only contain an SSH connection. For more details on connection schema, see this doc: https://pubhub.devnetcloud.com/media/pyats/docs/topology/schema.html#produ...
def trim(s): """ Add any globle filtering rules here """ s = s.replace( "Python Enhancement Proposals!", "") s = s.replace( "PEP ", "PEP-") return s
def strToBool(s, default=False): """ Try to interpret string (or unicode) s as boolean, return default if string can't be interpreted """ if s is None: return default # Try to interpret as integer try: return int(s) != 0 except ValueError: # No...
def str_to_version(version_str): """Return the tuple (major, minor, patch) version extracted from the str.""" version_ids = version_str.split(".") if len(version_ids) != 3 or "-" in version_str: raise ValueError( "Could not convert the {} to version. Format should be x.y.z".format( version...
def decode_ber(ber): """ Decodes a ber length byte array into an integer return: (length, bytes_read) - a tuple of values """ ber = bytearray(ber) length = ber[0] bytes_read = 1 if length > 127: bytes_read += length & 127 # Strip off the high bit length = 0 for i ...
def _deepmerge_append_list_unique(config, path, base, nxt): """A list strategy to append unique elements of nxt.""" if len(base) == 0: return nxt if len(nxt) == 0: return base if isinstance(base[0], dict) or isinstance(nxt[0], dict): return [item for item in base] + [item for ite...
def sum_args(*nums: int) -> int: """ Return the sum of the specified numbers as arguments Parameters: nums (*int): Numbers Returns: result (int): Sum of the arguments """ result = sum(nums) return result
def version_encode_bdc(s: str): """ :return: The return value is in binary coded decimal with a format of 0xJJMN where JJ is the major version number, M is the minor version number and N is the sub minor version number. e.g. USB 2.0 is reported as 0x0200, USB 1.1 as 0x0110 and USB 1.0 as...
def beat_division(a,b): """ Integer division protected that returns 0 for n/0. """ if b == 0: return 0 return a // b
def sum_lists(list1, list2): """Sums the elements of each list, returns a new list. This function is used in MPI reduce commands, but could be used elsewhere too.""" assert len(list1) == len(list2) return [list1[i] + list2[i] for i in range(len(list1))]