content
stringlengths
42
6.51k
def get_forecast_pct(lprice, fprice): """ Return the forecasted percentage price change Args: Double: Last price Double: Forecast price Returns: Double: Forecasted percentage change """ if lprice != 0 and lprice is not None: lpf = float(lprice) fpf = float(fprice) result = (fpf - lpf)/lpf else: result = 0 return result
def recognize_genshin_server(uid: int) -> str: """Recognize which server a Genshin UID is from.""" server = { "1": "cn_gf01", "2": "cn_gf01", "5": "cn_qd01", "6": "os_usa", "7": "os_euro", "8": "os_asia", "9": "os_cht", }.get(str(uid)[0]) if server: return server raise ValueError(f"UID {uid} isn't associated with any server")
def nernst(temperature): """ Description: Calculates the value of the temperature dependent term of the Nernst equation to provide the link between measured electrode potentials and concentration. For use with the THSPH L2 data products (THSPHHC, THSPHHS, THSPHPH), all of which use electrodes to provide the raw data. The temperature to be used is specified in the DPSs to be THSPHTE-TH. Implemented by: 2014-07-08: Russell Desiderio. Initial Code. Usage: e_nernst = nernst(temperature) where e_nernst = value of the temperature dependent term of the Nernst equation [V] temperature = temperature near sample inlet THSPHTE-TH_L1 [deg_C] """ # e_nernst = ln(10) * (gas constant) * (temperature, Kelvin)/(Faraday's constant) # = 2.30259 * 8.31446 [J/mole/K] / 96485.3 [coulombs/mole] * (T + 273.15) return 1.9842e-4 * (temperature + 273.15)
def _key_is_valid(dictionary, key): """Test that a dictionary key exists and that it's value is not blank.""" if key in dictionary: if dictionary[key]: return True return False
def _get_file_prefix_and_postfix(filepath): """ Get file prefix and postfix from the filepath If the file name in the filepath has not file extension the file is supposed to be a binary file :param filepath: File name and full path :return: prefix, postfix """ prefix = filepath.split('.')[0] postfix = filepath.split('.')[-1].lower() # If no "." is found in the filepath if postfix == prefix: postfix = "bin" return prefix, postfix
def insertion_sort(arr): """ Insertion sort algoritm """ # Comparisons comp = 0 # Move through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move els of [0, i-1] that are greater than key 1 pos ahead # Move the key to the pos where it is bigger than the prev num(j+1) j = i - 1 while j >= 0: if arr[j] > key: arr[j+1] = arr[j] j -= 1 comp += 1 else: comp += 1 break arr[j+1] = key return comp
def constructor_method_name_is_false_positive(constructor: str, line: str) -> bool: """Decides whether given constructor method is false positive. if method does not contain "." in it (for example `getS()`) then it must be before it (`.getS()`) if method contains "." then before it should not be alpha but " " or "(" (for example `Cipher.getInstance(`) """ # method needs to be prefixed with . if "." not in constructor: return f".{constructor}" not in line found_index = line.find(constructor) # constructor not found if found_index < 0: return True # method with class prefix needs to be prefixed by something not alpha numerical (space, bracket etc) return found_index != 0 and (line[found_index-1].isalnum() or line[found_index-1] in ["_", "."])
def addDicts(dict1, dict2): """Add dicts together by value. i.e. addDicts({"a":1,"b":0}, {"a":2}) == {"a":3,"b":0}.""" result = {k:v for k,v in dict1.items()} for k,v in dict2.items(): if k in result: result[k] += v else: result[k] = v return result
def to_usd(my_price): """ Converts a numeric value to usd-formatted string, for printing and display purposes. Param: my_price (int or float) like 4000.444444 Example: to_usd(4000.444444) Returns: $4,000.44 """ return f"${my_price:,.2f}"
def escape_xml_characters(data): """Return copy of string with XML special characters escaped. This replaces the characters <, > and & with the XML escape sequences &lt;, &gt; and &amp;. It also replaces double quotes with &quot;. This could be replaced in future by the 'xml.sax.saxutils.escape' function.""" return str(data).replace("&","&amp;").replace("<","&lt;").replace(">","&gt;").replace('"',"&quot;")
def construct_server_name(params, server_name_prefix): """ Construct and return a server name for the given prefix :param params: The params dict containing the server base name :param server_name_prefix: A string prefix to apply to the server base name :return: Server name string """ return '%s-%s' % (str(server_name_prefix), params['server_base_name'])
def pbits(num: int, pad: int = 32) -> str: """Return the bits of `num` in binary with the given padding.""" return bin(num)[2:].zfill(pad)
def reverse_bytes(hex_string): """ This function reverses the order of bytes in the provided string. Each byte is represented by two characters which are reversed as well. """ #print 'reverse_bytes(' + hex_string + ')' chars = len(hex_string) if chars > 2: return reverse_bytes(hex_string[chars/2:]) + reverse_bytes(hex_string[:chars/2]) else: return hex_string[1] + hex_string[0]
def divisor_extract(row): """returns the quotient of the only evenly divisible numbers in the list. This assumes that they exist""" for num in row: for divisor in row: if num % divisor == 0 and num != divisor: return num / divisor raise ValueError("Row does not have even divisor pair")
def hide_highlight() -> dict: """Hides any highlight.""" return {"method": "DOM.hideHighlight", "params": {}}
def make_params(vars): """quick hacky way to build body params vars is locals() passed from each api endpoint, eg query_database(). This function copies every var if - it's not 'self' or 'kw' - not start with '_': in case any api endpoint code need local var, it should start with _ - not end with '_id': all url params are also defined in api endpoint functions they all like '*_id', eg page_id, block_id etc The goal is to minimize api endpoint code, easier to read and match to official document. This is less hacky than using inspect :D and still kind of readable/maintainable and api endpoint code is minimal enough. """ params = { name: vars[name] for name in vars if name not in ('self', 'kw') # skip self and kw and name[0] != '_' # skip possible local use vars and not name.endswith('_id') # skip url params if vars.get(name) is not None } if 'kw' in vars: # copy everything under 'kw' params.update(vars['kw']) return params
def merge_cluster(cluster_list, cluster_temp): """Code to merge a cluster into a cluster list """ cluster_list.append(cluster_temp) merged_index = [] for i, cluster in reversed(list(enumerate(cluster_list))): if bool(cluster.intersection(cluster_temp)): cluster_temp = cluster_temp | cluster cluster_list[i] = cluster_temp merged_index.append(i) if len(merged_index) > 1.5: del cluster_list[merged_index[0]] del merged_index[0] elif len(merged_index) > 1.5: print("Somethings wrong with the cluster merging") return cluster_list
def daisy_replicator(alpha, alphag, beta, gamma): """Calculate the rate of change of a replicator (daisies). The formula is: a*[ag*b-g] which describes a logistic growth and constant death within a limited resource system over time t. Arguments --------- alpha : float alpha -- the fraction of surface covered by daisies. alphag : float alpha_g -- The fraction of available bare ground. beta : float beta -- the birth rate. gamma : float gamma -- the death rate. """ return alpha*(alphag*beta-gamma)
def nice_string(ugly_string, limit=100): """Format and trims strings""" return (ugly_string[:limit] + '..') if len(ugly_string) > limit else ugly_string
def read_file( file_path ): """ Read data from file_path Return non-None on success Return None on error. """ try: fd = open( file_path, "r" ) except: return None buf = None try: buf = fd.read() except: fd.close() return None try: fd.close() except: return None return buf
def _format_list(param_name, list1, datadict, **kwargs): """Concatenate and format list items. This is used to prepare substitutions in user-supplied args to the various test invocations (ie: the location of flash). Args: @param param_name: The name of the item in `datadict`. @param list1: A list of items to prepend to the list item from datadict. @param datadict: A dictionary of per-test parameters. @param **kwargs: Values to pass to the format function. Returns: list[str] """ return [x.format(**kwargs) for x in list1 + datadict.pop(param_name, [])]
def append_list(n): """ >>> append_list(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] """ s = [] for i in range(n): s.append(i) return s
def Drop(x, **unused_kwargs): """Drops one element.""" del x # Just for the compiler. return ()
def is_instance(list_or_dict) -> list: """Converts dictionary to list""" # I use this because it make a data structures the same, no isinstance(), cuts down on code if isinstance(list_or_dict, list): make_list = list_or_dict else: make_list = [list_or_dict] return make_list
def moduleNeedsTests(modulename): """ Determine whether a module is a is a special module. like __init__ """ return not modulename.split(".")[-1].startswith("_")
def rgb2hex(rgb): """Convert RGB to Hex color.""" h = '#%02x%02x%02x' % (int(rgb[0]*255),int(rgb[1]*255),int(rgb[2]*255)) return h
def v3_uniques_only(iterable): """Return iterable in the same order but with duplicates removed. We can make this faster by using a set... Sets rely on hashes for lookups so containment checks won't slow down as our hash grows in size. Notice we're building up both a list and a set but we're checking only the set for containment and returning only the list. We still need to make a list in addition to our set because sets are unordered by nature and we want the order of first appearance of each item to be maintained. """ seen = set() items = [] for item in iterable: if item not in seen: items.append(item) seen.add(item) return items
def calc_distance(x1: float, y1: float, x2: float, y2: float) -> float: """Calculate the distance between two points""" return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
def compare_json(json1,json2): """Compare Two JSON data structs to check if they're identical. Args: json1 (dict): json data json2 (dict): json data Returns: (boolean): True if identical, False if not """ # Iterate Through First for key, value in json1.items(): if key not in json2: return False else: if value != json2[key]: return False # Iterate Through Last for key, value in json2.items(): if key not in json1: return False else: if value != json1[key]: return False # Must be identical return True
def p_selection(p_init, it, num_iter): """ Piece-wise constant schedule for p (the fraction of pixels changed on every iteration). """ it = int(it / num_iter * 10000) if 10 < it <= 50: return p_init / 2 elif 50 < it <= 200: return p_init / 4 elif 200 < it <= 500: return p_init / 8 elif 500 < it <= 1000: return p_init / 16 elif 1000 < it <= 2000: return p_init / 32 elif 2000 < it <= 4000: return p_init / 64 elif 4000 < it <= 6000: return p_init / 128 elif 6000 < it <= 8000: return p_init / 256 elif 8000 < it <= 10000: return p_init / 512 else: return p_init
def external_question_xml(question_url): """Return AMT-formatted XML for external question. See: https://docs.aws.amazon.com/AWSMechTurk/latest/AWSMturkAPI/ ApiReference_ExternalQuestionArticle.html """ question_xml = ( '<?xml version="1.0" encoding="UTF-8"?>' '<ExternalQuestion xmlns="http://mechanicalturk.amazonaws.com/' 'AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd">' '<ExternalURL>{0}</ExternalURL>' '<FrameHeight>0</FrameHeight>' '</ExternalQuestion>' ).format(question_url) return question_xml
def ee_bands(collection): """ Earth Engine band names """ dic = { 'Sentinel2_TOA': ['B1','B2','B3','B4','B5','B6','B7','B8A','B8','B11','B12'], 'Landsat7_SR': ['B1','B2','B3','B4','B5','B6','B7'], 'Landsat8_SR': ['B1','B2','B3','B4','B5','B6','B7','B10','B11'], 'CroplandDataLayers': ['landcover', 'cropland', 'land', 'water', 'urban'], 'NationalLandCoverDatabase': ['impervious'] } return dic[collection]
def normalize_whitespace(text): """ Remove redundant whitespace from a string. """ text = text.replace('"', '').replace("'", '') return ' '.join(text.split())
def extractHash(val, typ="crc32c"): """ extract the crc32 from the string returned by an ls -L command Args: ---- type: flag ['crc32c','md5'] """ if ' Hash (crc32c):' in val and typ=="crc32c": return val.split(' Hash (crc32c): ')[-1].split('\\\\n')[0].split('\\n')[0] elif ' Hash (md5):' in val and typ == "md5": return val.split(' Hash (md5): ')[-1].split('\\\\n')[0].split('\\n')[0] else: return None
def reverse(text): """<string> -- Reverses <string>.""" return text[::-1]
def p2f(x): """Convert percent string to float. """ return float(x.strip('%')) / 100.
def clean_line(line): """ Cleans a single line """ ret = line.replace('-', ' ').replace('.', '. ').strip() return ret
def format_name(movie_name): """Format movie name to use in file name Input ------- movie_name: the name of a movie Output ------- formatted file name """ return "_".join([x.lower() for x in movie_name .replace(".", "") .replace(":", "") .replace("(", "") .replace(")", "") .replace("]", "") .replace("[", "") .replace("-", "") .replace("'", "") .replace("&", "") .replace("!", "") .replace(",", "") .split()])
def ParseSize(s): """ The reverse of SmartSize, this returns an integer based on a value. """ scaler = { 'k' : 1024, 'm' : 1024 * 1024, 'g' : 1024 * 1024 * 1024, 't' : 1024 * 1024 * 1024 * 1024 } try: if s[-1] in list("kKmMgGtT"): suffix = s[-1].lower() return int(s[:-1]) * scaler[suffix] else: return int(s) except: return 0
def dec2hex(d): """return a two character hexadecimal string representation of integer d""" return "%02X" % d
def currency_to_float(value): """Converte de R$ 69.848,70 (str) para 69848.70 (float).""" try: cleaned_value = value.replace("R$", "").replace(".", "").replace(",", ".") return float(cleaned_value) except ValueError: pass return
def times_until_out_of_gp(gp: float) -> int: """Returns how often you can buy from the enchanted_armoire given some budget. \f :param gp: :return: """ enchanted_armoire_price = 100 times: float = gp / enchanted_armoire_price return int(times)
def uniq(objectSequence): """ returns a list with no duplicates""" d = {} for o in objectSequence: d[id(o)] = o return list(d.values())
def maybe_quote(value): """ Quote a value for InfluxDB if necessary. """ if value[0] == "'" and value[-1] == "'": return value return "'{}'".format(value)
def _make_it_list(args: list) -> list: """ Make it list return all args element as list in a list. :param list args: list of the argument to return as list :return list: list of the args that are now list """ r = [] for x in args: if x is None: r.append([]) elif not isinstance(x, list): r.append(list(x)) else: r.append(x) return r
def generate_unused_secgroup_entry(security_group: dict) -> dict: """ Generates a dictionary from an unused security group to the analysis response """ unused_group = { 'GroupName': security_group['GroupName'], 'GroupId': security_group['GroupId'], 'Description': security_group['Description'], 'VpcId': security_group.get('VpcId') or 'no-vpc', } return unused_group
def get_host_batchid_map(workspec_list): """ Get a dictionary of submissionHost: list of batchIDs from workspec_list return {submissionHost_1: {batchID_1_1, ...}, submissionHost_2: {...}, ...} """ host_batchid_map = {} for workspec in workspec_list: host = workspec.submissionHost batchid = workspec.batchID if batchid is None: continue batchid_str = str(batchid) # backward compatibility if workspec.batchID does not contain ProcId if '.' not in batchid_str: batchid_str += '.0' try: host_batchid_map[host].append(batchid_str) except KeyError: host_batchid_map[host] = [batchid_str] return host_batchid_map
def getPreviousMatchlen(cigarOps, currOffset): """ This takes in a vector of cigar operations (reduced instruction set; MID only) and returns the length of the match needed to consume bases 0..currOffset in the string """ if not cigarOps: return currOffset off = 0 # recompute the current substring position in the read for cig in cigarOps: if cig.op != 'D': off += cig.size # and return the amount needed to be consumed... return currOffset - off
def list2str(list_obj): """ Args: list_obj(list): Returns: str: List converted to a prettier string than the default str(list). """ out = "[ " for item in list_obj: out += "{}, ".format(item) out = out[:-1][:-1] out += " ]" return out
def scale(data, min_screen, max_screen, min_data, max_data): """ get the scaled data with proportions min_data, max_data relative to min and max screen dimentions """ return ((data - min_data) / (max_data - min_data)) * (max_screen - min_screen) + min_screen
def do_center(value, width=80): """ Centers the value in a field of a given width. """ return value.center(width)
def usefulness_minus_target(k, num_attributes, num_tuples, target_usefulness=5, epsilon=0.1): """Usefulness function in PrivBayes. Parameters ---------- k : int Max number of degree in Bayesian networks construction num_attributes : int Number of attributes in dataset. num_tuples : int Number of tuples in dataset. target_usefulness : int or float epsilon : float Parameter of differential privacy. """ if k == num_attributes: print('here') usefulness = target_usefulness else: usefulness = num_tuples * epsilon / ((num_attributes - k) * (2 ** (k + 3))) # PrivBayes Lemma 3 return usefulness - target_usefulness
def generate_notes_file_name(year, month, day): """Generate note's file name for a particular date Args: year (int): Year month (int): Month day (int): Day Returns: Note name """ return "{}-{}-{}".format(year, month, day)
def __is_const_str(data: str) -> bool: """ Returns true if predicate is a constant string. Note: supports constant strings starting with a lowercase letter or a number """ # common case: string starts with a lowercase letter test_str = data[0].islower() # special case: string starts with a number. see '16_bit_one's_complement' test_num = data[0].isnumeric() and not data.isnumeric() return (test_str or test_num) and not '@' in data
def param_first(key, params): """Search 'params' for 'key' and return the first value that occurs. If 'key' was not found, return None.""" for k, v in params: if key == k: return v return None
def get_doc_info(result): """Get the index, doc_type, and id associated with a document. Parameters ---------- result : dict A document from an Elasticsearch search result. Returns ------- dict A dictionary with keys 'index', 'doc_type', and 'id', containing the name of the index in which the document resides, the doc_type of the document, and its id. """ return { 'index': result['_index'], 'doc_type': result['_type'], 'id': result['_id'] }
def matchWallTime(walltime, resource_ad): """True if `walltime` <= MaxWallTime in `resource_ad`, or if MaxWallTime is undefined or 0 """ max_wall_time = resource_ad.get('MaxWallTime', 0) if not max_wall_time: return True else: return (int(max_wall_time) >= walltime)
def get_positions(start_idx, end_idx, length): """ Get subj/obj position sequence. """ return list(range(-start_idx, 0)) + [0]*(end_idx - start_idx) + \ list(range(1, length-end_idx+1))
def bytes2MiB(bytes): """ Convert bytes to MiB. :param bytes: number of bytes :type bytes: int :return: MiB :rtype: float """ return bytes/(1024*1024)
def is_valid_id(id_: str) -> bool: """If it is not nullptr. Parameters ---------- id_ : str Notes ----- Not actually does anything else than id is not 0x00000 Returns ------- bool """ return not id_.endswith("0x0000000000000000")
def agent_grounding_matches(agent): """Return an Agent matches key just based on grounding, not state.""" if agent is None: return None return str(agent.entity_matches_key())
def _basename(p): """Returns the basename (i.e., the file portion) of a path. Note that if `p` ends with a slash, this function returns an empty string. This matches the behavior of Python's `os.path.basename`, but differs from the Unix `basename` command (which would return the path segment preceding the final slash). Args: p: The path whose basename should be returned. Returns: The basename of the path, which includes the extension. """ return p.rpartition("/")[-1]
def bubble_sort_across_lists(dictionary): """ >>> d = {'he': [0, 2.5, 0, 1.3846153846153846, 0, 1.0, 5.3478260869565215], ... 'she': [10.25, 0, 28.75, 0, 14.266666666666667, 0, 0], ... 'book': ['a', 'b', 'd', 'f', 'g', 'h', 'i']} >>> bubble_sort_across_lists(d) {'he': [5.3478260869565215, 2.5, 1.3846153846153846, 1.0, 0, 0, 0], 'she': [0, 0, 0, 0, 10.25, 14.266666666666667, 28.75], 'book': ['i', 'b', 'f', 'h', 'a', 'g', 'd']} :param dictionary: containing 3 different list values. Note: dictionary keys MUST contain arguments 'he', 'she', and 'book' :return dictionary sorted across all three lists in a specific method: 1) Descending order of 'he' values 2) Ascending order of 'she' values 3) Corresponding values of 'book' values """ lst1 = dictionary['he'] lst2 = dictionary['she'] lst3 = dictionary['book'] r = range(len(lst1) - 1) p = True # sort by lst1 descending for j in r: for i in r: if lst1[i] < lst1[i + 1]: # manipulating lst 1 temp1 = lst1[i] lst1[i] = lst1[i + 1] lst1[i + 1] = temp1 # manipulating lst 2 temp2 = lst2[i] lst2[i] = lst2[i + 1] lst2[i + 1] = temp2 # manipulating lst of authors temp3 = lst3[i] lst3[i] = lst3[i + 1] lst3[i + 1] = temp3 p = False if p: break else: p = True # sort by lst2 ascending for j in r: for i in r: if lst2[i] > lst2[i + 1]: # manipulating lst 1 temp1 = lst1[i] lst1[i] = lst1[i + 1] lst1[i + 1] = temp1 # manipulating lst 2 temp2 = lst2[i] lst2[i] = lst2[i + 1] lst2[i + 1] = temp2 # manipulating lst of authors temp3 = lst3[i] lst3[i] = lst3[i + 1] lst3[i + 1] = temp3 p = False if p: break else: p = True d = {} d['he'] = lst1 d['she'] = lst2 d['book'] = lst3 return d
def single_number3(nums): """ :type nums: List[int] :rtype: List[int] """ # isolate a^b from pairs using XOR ab = 0 for n in nums: ab ^= n # isolate right most bit from a^b right_most = ab & (-ab) # isolate a and b from a^b a, b = 0, 0 for n in nums: if n & right_most: a ^= n else: b ^= n return [a, b]
def construct_traceview_url(args): """ Construct url using artifacts """ url = "{host}:{port}/{app}/traceviewer.html?trace={trc}&alignmentset={aln}&subreads={sset}&holen={zmw}" url = url.format(host=args['--server_host'], port=args['--server_port'], app=args['--app_path'], trc=args['--trc'], aln=args['--aset'], sset=args['--sset'], zmw=args['--zmw']) # log.info("Opening up {url} in the browser".format(url)) return url
def _SplitOption(text): """Split simple option list. @type text: string @param text: Options, e.g. "foo, bar, baz" """ return [i.strip(",").strip() for i in text.split()]
def find_indices(text, expr): """Identify indices where search expression (expr) occurs in base expression (text)""" places = [] i = text.find(expr) while i>=0: places.append(i) i = text.find(expr, i + 1) return places
def dict_string_to_nums(dictionary): """ turns all strings that are numbers into numbers inside a dict :param dictionary: dict :return: dict """ for i, j in dictionary.items(): if isinstance(j, str) and j.replace(".", "", 1).isnumeric(): num = float(j) if num.is_integer(): num = int(num) dictionary[i] = num return dictionary
def arraylike(thing): """Is thing like an array?""" return isinstance(thing, (list, tuple))
def encode_attribute(att, desc, targ): """ Encode the 'role' of an attribute in a model. This is an important function, since here resides the precise encoding. If this is changed, a whole lot of other things will change too. Since everything that relies on the encoding should refer here, everything should proceed normally. `Role` means: - Descriptive attribute (input) - Target attribute (output) - Missing attribute (not relevant to the model) """ check_desc = att in desc check_targ = att in targ code_int = check_targ * 2 + check_desc - 1 return code_int
def filter_octects(ip_address): """functional approach filters the list""" terms = ip_address.split(".") if not len([*filter(lambda octet: octet.isdecimal(), terms)])==4: return False elif not len([*filter(lambda octet: 0<=int(octet)<=255, terms)])==4: return False else: return True
def clean_boxes_metadata(boxes_metadata): """ Get unique boxes metadata :param boxes_metadata: :return: """ boxes_names = {b['name']: 0 for b in boxes_metadata} new_boxes_metadata = [] for bb in boxes_metadata: if bb['name'] in boxes_names and boxes_names[bb['name']] == 0: boxes_names[bb['name']] += 1 new_boxes_metadata.append(bb) return new_boxes_metadata
def correlate_service(method, service_objects): """ Returns the service containing the appropriate service path for the provided method, if a match is found """ service_segment = method["rmtSvcIntName"].lower().split(".")[-1] for service in service_objects: service_path = service["servicePath"].lower().replace("/", "") if ( service_segment in service_path or service_path in service_segment ): return service return None
def is_illegal_char(char: int) -> bool: """True if char is the base-26 representation of one of i, o, l.""" if char in [8, 11, 14]: # i, l, o return True return False
def empty_when_none(_string=None): """If _string if None, return an empty string, otherwise return string. """ if _string is None: return "" else: return str(_string)
def dim(shape): """Given shape, return the number of dimension""" d = 1 for size in shape: d *= size return d
def pusher(lst): """ A Helper Function that takes all non zero numbers and pushes them to the front of the list. """ sorted_list = [] for dummy_num in range(len(lst)): if lst[dummy_num] != 0: sorted_list.append(lst[dummy_num]) for dummy_i in range((len(lst)) - (len(sorted_list))): sorted_list.append(0) return sorted_list
def make_constructed_utts(utt_tokens): """ Converts utterances into correct form for composition Args: utt_tokens: List of utterances (utterance = list of tokens) Returns: utts: List of utterances for individual tokens and compositions compose_idx: List of indices in utts to be composed [["green", "-ish"]] => [["#start#", "green", "#end#"], ["#start#", "-ish", "#end#"], ["#start#", "green", "-ish", "#end#"]], [(0,2)] """ START = "#start#" END = "#end#" utts = [] compose_idx = [] for utt in utt_tokens: compose_idx.append((len(utts), len(utts)+len(utt))) # [start, end) for tok in utt: utts.append([START, tok, END]) utts.append([START] + utt + [END]) return utts, compose_idx
def average(lst): """ calculate average of a list (of numbers) """ return sum(lst) / len(lst)
def create_output_path(output_template, datacombination, parameter, algorithm_name): """ Where does he want his results? """ output = output_template output = output.replace("@@name@@", algorithm_name) output = output.replace("@@trainOn@@", datacombination["trainOn"]) output = output.replace("@@estimate@@", datacombination["estimate"]) if parameter != None: output = output.replace("@@filenameext@@", parameter["filenameext"]) else: output = output.replace("@@filenameext@@", "") output = output.replace(".csv", "") output = output + ".csv" return output
def convolve(X, Y): """ Convolves two series. """ N = len(X) ss = [] for n in range(0, len(Y)): s = 0 for l in range(0, len(X)): s += X[l].conjugate()*Y[(n+l)%len(Y)] ss.append(s) return ss
def blank_to_NA(it): """ Converts blank fields to NAs in some list it it: list Return value: list with blank fields represented as NAs """ return [(el if el else 'NA') for el in it]
def _fix_endpoint(endpoint: str) -> str: """ Remove all text before "http". Workaround because the endpoint is automatically prefixed with the data folder. However this does not make sense for a sparql endpoint. :param endpoint: :return: """ idx = endpoint.find('http') return endpoint[idx:]
def dottedQuadToNum(ip): """ Convert decimal dotted quad string to long integer >>> int(dottedQuadToNum('1 ')) 1 >>> int(dottedQuadToNum(' 1.2')) 16777218 >>> int(dottedQuadToNum(' 1.2.3 ')) 16908291 >>> int(dottedQuadToNum('1.2.3.4')) 16909060 >>> dottedQuadToNum('1.2.3. 4') 16909060 >>> dottedQuadToNum('255.255.255.255') 4294967295L >>> dottedQuadToNum('255.255.255.256') Traceback (most recent call last): ValueError: Not a good dotted-quad IP: 255.255.255.256 """ # import here to avoid it when ip_addr values are not used import socket, struct try: return struct.unpack('!L', socket.inet_aton(ip.strip()))[0] except socket.error: # bug in inet_aton, corrected in Python 2.3 if ip.strip() == '255.255.255.255': return 0xFFFFFFFF else: raise ValueError('Not a good dotted-quad IP: %s' % ip) return
def iterate_mandelbrot(iterate_max, c, z = 0): """Calculate the mandelbrot sequence for the point c with start value z""" for n in range(iterate_max + 1): z = z * z + c if abs(z) > 2: return n return None
def is_iterable(x): """Checks if an object x is iterable. It checks only for the presence of __iter__, which must exist for container objects. Note: we do not consider non-containers such as string and unicode as `iterable'; this behavior is intended. """ return hasattr(x, "__iter__")
def transcribe(dna): """ return the dna string as rna string """ return dna.replace('T', 'U')
def string_to_tuple(version): """Convert version as string to tuple Example: >>> string_to_tuple("1.0.0") (1, 0, 0) >>> string_to_tuple("2.5") (2, 5) """ return tuple(map(int, version.split(".")))
def get_num_bytes(i): """Get the minimum number of bytes needed to represent a given int value. @param i (int) The integer to check. @return (int) The number of bytes needed to represent the given int. """ # 1 byte? if ((i & 0x00000000FF) == i): return 1 # 2 bytes? if ((i & 0x000000FFFF) == i): return 2 # 4 bytes? if ((i & 0x00FFFFFFFF) == i): return 4 # Lets go with 8 bytes. return 8
def EditDistance(string1, string2): """ Edit Distance for given string1 and string2 """ if len(string1) > len(string2): string1, string2 = string2, string1 distances = range(len(string1) + 1) for index2, char2 in enumerate(string2): newDistances = [index2 + 1] for index1, char1 in enumerate(string1): if char1 == char2: newDistances.append(distances[index1]) else: newDistances.append(1 + min((distances[index1], distances[index1 + 1], newDistances[-1]))) distances = newDistances return distances[-1]
def dfdz_ReLU(z): """Derivative of the rectified linear unit function... Args: z (np.array) Returns: df(z)/dz = 1 if x > 0 else 0 (np.array) """ return (z > 0)
def get_with_prefix(d, k, default=None, delimiter=":"): """\ Retrieve a value from the dictionary, falling back to using its prefix, denoted by a delimiter (default ':'). Useful for cases such as looking up `raven-java:logback` in a dict like {"raven-java": "7.0.0"}. """ if k is None: return default prefix = k.split(delimiter, 1)[0] for key in [k, prefix]: if key in d: return d[key] key = key.lower() if key in d: return d[key] return default
def normalize(item): """ lowercase and remove quote signifiers from items that are about to be compared """ item = item.lower().rstrip('_') return item
def index_1d(row, col): """For a given row and column in a grid world, return the row that cell would appear on in the transition matrix. Parameters ---------- row : int The row number. Indexing starts at 0. col : int The column number. Indexing starts at 0. Returns ------- transition_row : int The row on the transition matrix the row and column would appear on. """ max_cols = 9 return row * max_cols + col
def get_manhattan_distance(x, y): """Calculate Manhattan distance of x, y to the 0, 0 point.""" return abs(x) + abs(y)
def filter_stopwords(str): """ Stop word filter returns list """ STOPWORDS = ['a', 'able', 'about', 'across', 'after', 'all', 'almost', 'also', 'am', 'among', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'because', 'been', 'but', 'by', 'can', 'cannot', 'could', 'dear', 'did', 'do', 'does', 'either', 'else', 'ever', 'every', 'for', 'from', 'get', 'got', 'had', 'has', 'have', 'he', 'her', 'hers', 'him', 'his', 'how', 'however', 'i', 'if', 'in', 'into', 'is', 'it', 'its', 'just', 'least', 'let', 'like', 'likely', 'may', 'me', 'might', 'most', 'must', 'my', 'neither', 'no', 'nor', 'not', 'of', 'off', 'often', 'on', 'only', 'or', 'other', 'our', 'own', 'rather', 'said', 'say', 'says', 'she', 'should', 'since', 'so', 'some', 'than', 'that', 'the', 'their', 'them', 'then', 'there', 'these', 'they', 'this', 'tis', 'to', 'too', 'twas', 'us', 'wants', 'was', 'we', 'were', 'what', 'when', 'where', 'which', 'while', 'who', 'whom', 'why', 'will', 'with', 'would', 'yet', 'you', 'your'] return [t for t in str.split() if t.lower() not in STOPWORDS]
def GetAtxCertificateSubject(cert): """Parses and returns the subject field from the given AvbAtxCertificate struct.""" CERT_SUBJECT_OFFSET = 4 + 1032 # Format version and public key come before subject CERT_SUBJECT_LENGTH = 32 return cert[CERT_SUBJECT_OFFSET:CERT_SUBJECT_OFFSET + CERT_SUBJECT_LENGTH]
def ms2mph(ms: float) -> float: """ Convert meters per second to miles per hour. :param float ms: m/s :return: speed in mph :rtype: float """ if not isinstance(ms, (float, int)): return 0 return ms * 2.23693674
def str_to_c_string(string): """Converts a Python str (ASCII) to a C string literal. >>> str_to_c_string('abc\x8c') '"abc\\\\x8c"' """ return repr(string).replace("'", '"')
def currency_to_int(s: str) -> int: """ Just remove a colon. """ return int(s[:len(s)-3] + s[len(s)-2:])