content
stringlengths
42
6.51k
def make_csv(tiles, width): """ Takes a list of tiles and a width and returns a string of comma-separated values """ csv = "" for i in range(0, len(tiles), width): csv += ",".join(str(t) for t in tiles[i:i+width]) if i + width < len(tiles): csv += ',\n' else: csv += '\n' return csv
def ek_WT(cell): """ Returns the WT reversal potential (in mV) for the given integer index ``cell``. """ reversal_potentials = { 1: -91.6, 2: -92.8, 3: -95.1, 4: -92.3, 5: -106.1 } return reversal_potentials[cell]
def check_int(_, candidate): """Checks whether candidate is <int>.""" try: int(candidate) return True except: return False
def str_convert_beforeprint(x): """ #Before writing/output to printer put in utf-8 """ try: return x.encode("utf-8") except: return x
def conv_fmt(flag): """convective formatter""" if flag<0.5: return 's' if flag>0.5: return 'c' return ''
def mult(num1, num2=1): """ Multiplies two numbers Args: `num1`: The first number `num2`: The second number, default `1` Returns: The result of the **multiplication** process """ return (num1*num2)
def h(data): """ A small helper function to translate byte data into a human-readable hexadecimal representation. Each byte in the input data is converted into a two-character hexadecimal string and is joined to its neighbours with a colon character. This function is not essential to driver-building but is a great help when debugging, logging and writing doctests. >>> from boltkit.bytetools import h >>> h(b"\x03A~") '03:41:7E' Args: data: Input byte data as `bytes` or a `bytearray`. Returns: A textual representation of the input data. """ return ":".join("{:02X}".format(b) for b in bytearray(data))
def lookupName(n, names): """Check if name is in list of names Parameters ---------- n : str Name to check names : list List of names to check in Returns ------- bool Flag denoting if name has been found in list (True) or not (False) """ if n in names: return True else: return False
def has_identical_list_elements(list_): """Checks if all lists in the collection have the same members Arguments: list_: collection of lists Returns: true if all lists in the collection have the same members; false otherwise """ if not list_: return True for i in range(1, len(list_)): if list_[i] != list_[i - 1]: return False return True
def shift(register, feedback, output): """GPS Shift Register :param list feedback: which positions to use as feedback (1 indexed) :param list output: which positions are output (1 indexed) :returns output of shift register: """ # calculate output out = [register[i - 1] for i in output] if len(out) > 1: out = sum(out) % 2 else: out = out[0] # modulo 2 add feedback fb = sum([register[i - 1] for i in feedback]) % 2 # shift to the right for i in reversed(range(len(register[1:]))): register[i + 1] = register[i] # put feedback in position 1 register[0] = fb return out
def convert_by_interpolation(integer: int) -> str: """ Converts an integer to a string using string interpolation. :param integer: an integer :return: the integer as a string """ return "%s" % integer
def edge_args(start, dest, direction, label, qos): """ Compute argument ordering for Edge constructor based on direction flag. @param direction str: 'i', 'o', or 'b' (in/out/bidir) relative to start @param start str: name of starting node @param start dest: name of destination node """ edge_args = [] if direction in ['o', 'b']: edge_args.append((start, dest, label, qos)) if direction in ['i', 'b']: edge_args.append((dest, start, label, qos)) return edge_args
def extract_str(input_: str) -> str: """Extracts strings from the received input. Args: input_: Takes a string as argument. Returns: str: A string after removing special characters. """ return ''.join([i for i in input_ if not i.isdigit() and i not in [',', '.', '?', '-', ';', '!', ':']]).strip()
def clamp(v, low, high): """clamp v to the range of [low, high]""" return max(low, min(v, high))
def removeSubsets(sets): """ Removes all subsets from a list of sets. """ final_answer = [] # defensive copy sets = [set(_set) for _set in sets] sets.sort(key=len, reverse=True) i = 0 while i < len(sets): final_answer.append(sets[i]) for j in reversed(range(i+1, len(sets))): if sets[j].issubset(sets[i]): del sets[j] i += 1 return final_answer
def dict_to_sse_arg(d): """ Converts a dictionary to the argument syntax for this SSE """ # Dictionary used to convert argument values to the correct type types = {bool:"bool", int:"int", float:"float", str:"str"} # Output string s = "" # Format into the required syntax for k, v in d.items(): if v is None: s = s + str(k) + "=None, " else: s = s + str(k) + "=" + str(v) + "|" + types[type(v)] + ", " return s[:-2]
def avg_stdev(lst): """Return average and standard deviation of the given list""" avg = sum(lst)/len(lst) sdsq = sum((x-avg) ** 2 for x in lst) stdev = (sdsq / (len(lst) -1)) ** 0.5 return avg, stdev
def longest_common_prefix(string1, string2): """get the longest common prefix in two strings""" i = 0 while i < len(string1) and len(string2) and string1[1] == string2[i]: i += 1 return string1[:i]
def jmp(amount: str, pos: int) -> int: """ jmp jumps to a new instruction relative to itself. The next instruction to execute is found using the argument as an offset from the jmp instruction; for example, jmp +2 would skip the next instruction, jmp +1 would continue to the instruction immediately below it, and jmp -20 would cause the instruction 20 lines above to be executed next. Args: pos: amount: Returns: """ return pos + int(amount.strip('+'))
def _padright(width, s): """Flush left. >>> _padright(6, u'\u044f\u0439\u0446\u0430') == u'\u044f\u0439\u0446\u0430 ' True """ fmt = u"{0:<%ds}" % width return fmt.format(s)
def _any_not_none(*args): """Returns a boolean indicating if any argument is not None""" for arg in args: if arg is not None: return True return False
def move_idx_to_top(gra, idx1, idx2): """ move indexing for atm at idx1 to idx2 """ atms, bnds = gra newatms = {} newbnds = {} for key in atms: if key == idx1: newatms[idx2] = atms[key] elif idx2 <= key < idx1: newatms[key + 1] = atms[key] else: newatms[key] = atms[key] for key in bnds: atm1, atm2 = list(key) if atm1 == idx1: key1 = idx2 elif idx2 <= atm1 < idx1: key1 = atm1 + 1 else: key1 = atm1 if atm2 == idx1: key2 = idx2 elif idx2 <= atm2 < idx1: key2 = atm2 + 1 else: key2 = atm2 newkey = [key1, key2] newkey.sort() newkey = frozenset(newkey) newbnds[newkey] = bnds[key] return (newatms, newbnds)
def valid_field(field): """ Check if a field is valid """ return field and len(field) > 0
def split_array(ranges, threshold): """ Args: ranges: Output from laserscan threshold: Threshold for deciding when to start a new obstacle Returns: obstacles_1D: List of list of ranges """ obstacles_1D = [[ranges[0]]] current_obstacle_index = 0 for i in range(len(ranges)-1): if abs(ranges[i] - ranges[i+1]) > threshold: obstacles_1D.append([]) current_obstacle_index +=1 obstacles_1D[current_obstacle_index].append(ranges[i+1]) return obstacles_1D
def is_key_suitable_for_name(key_name): """Check if a key is suitable for name input.""" return len(key_name) == 1 and key_name.isalnum() or key_name in ['-', '_']
def multiset(target, key, value): """ Set keys multiple layers deep in a target dict. Parameters ------------- target : dict Location to set new keys into key : str Key to set, in the form 'a/b/c' will be available as target[a][b][c] = value value : any Will be added to target dictionary Returns ------------ target : dict The original dict object """ keys = key.split('/') current = target for i, key in enumerate(keys): last = i >= len(keys) - 1 if key not in current: if last: current[key] = value else: current[key] = {} current = current[key] return target
def getUriParent(uri): """Return URI of parent collection with trailing '/', or None, if URI is top-level. This function simply strips the last segment. It does not test, if the target is a 'collection', or even exists. """ if not uri or uri.strip() == "/": return None return uri.rstrip("/").rsplit("/", 1)[0] + "/"
def x_times(a): """ Multiply the given polinomial a, x times. """ return (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def event_converter(event): """ Converts event to string format that shows the event's portait on Reddit. """ if event["monsterType"] == "DRAGON": event = event["monsterSubType"] else: event = event["monsterType"] if event == "BARON_NASHOR": return "[B](#mt-barons)" elif event == "RIFTHERALD": return "[H](#mt-herald)" elif event == "FIRE_DRAGON": return "[I](#mt-infernal)" elif event == "EARTH_DRAGON": return "[M](#mt-mountain)" elif event == "WATER_DRAGON": return "[O](#mt-ocean)" else: return "[C](#mt-cloud)"
def duplicates(L): """ Return a list of the duplicates occurring in a given list L. Args: L (list): an input list Returns: a sorted list (possibly empty) of the elements appearing more than once in input list L. Examples: >>> duplicates([1, 2, 1, 3, 1, 4, 2, 5]) [1, 2] """ dupes = set() seen = set() for x in L: if x in seen: dupes.add(x) seen.add(x) return sorted(list(dupes))
def generate_INCLUDE_GET_READY_OUTPUT_CHAR_REPR(total_number_parameters): """Generate on the model: number_remaining_parameters = 1; """ return("number_remaining_parameters = " + str(total_number_parameters) + ";")
def normalize_by_mean(nodes, edges, feature_list, sequence_info): """ Normalize over all existing edges in the batch """ normalizing_feature_names = [feature for feature in feature_list if feature+"_MNORM_" in feature_list] for feature in normalizing_feature_names: data = edges[feature].clone() maximum = data.max() edges[feature + "_MNORM_"] = data / (maximum + 0.0001) return edges
def egcd(a, b): """Extended Euclid's algorithm for the modular inverse calculation. """ if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y)
def pad_text_batch(data_batch, vocab2int): """Pad text with <PAD> so that each text of a batch has the same length""" max_text = max([len(text) for text in data_batch]) return [text + [vocab2int['<PAD>']] * (max_text - len(text)) for text in data_batch]
def find_subclasses(cls): """ Finds subclasses of the given class""" classes = [] for subclass in cls.__subclasses__(): classes.append(subclass) classes.extend(find_subclasses(subclass)) return classes
def sm_name(section): """:return: name of the submodule as parsed from the section name""" section = section.strip() return section[11:-1]
def reorder(rules): """ Set in ascending order a list of rules, based on their score. """ return(sorted(rules, key = lambda x : x.score))
def __url_path_format(version_id: str, resource_name: str, method_name: str) -> str: """ Function makes the method path using specific format. :param version_id: Version of API :param method_name: Name of method :param resource_name: Name of resource :return: str """ return f"/{version_id}/{resource_name}.{method_name}"
def is_true ( val ): """ Returns true if input is a boolean and true or is a string and looks like a true value. """ return val == True or val in [ 'True', 'true', 'T', 't' ]
def value_in(resource, value): """ check for field in resource :param resource: :param value: :return: True | False """ if value in resource: if isinstance(resource[value], dict): if resource[value] == {}: return False else: return True elif isinstance(resource[value], list) or isinstance(resource[value], str): if len(resource[value]) == 0: return False else: return True else: return False
def top_sentences(query, sentences, idfs, n): """ Given a `query` (a set of words), `sentences` (a dictionary mapping sentences to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the `n` top sentences that match the query, ranked according to idf. If there are ties, preference should be given to sentences that have a higher query term density. """ def qtd(sentence, query): """ calculates the query term density. That is, proportion of terms in sentence that are also in query. """ query = set(query) count = sum([1 if word in query else 0 for word in sentence.split()]) return count / len(sentence.split()) ranked = {} for sentence, wordlist in sentences.items(): ranked[sentence] = 0 for word in query: if word in wordlist: ranked[sentence] += idfs.get(word, 0) ranked = dict(sorted(ranked.items(), key=lambda x: x[1], reverse=True)) ranked = list(ranked.items())[:n] # Tie breaker using query term density for index in range(n - 1): if ranked[index][1] == ranked[index+1][1]: left = qtd(ranked[index][0], query) right = qtd(ranked[index][0], query) if right > left: ranked[index], ranked[index + 1] = ranked[index + 1], ranked[index] ranked = [item[0] for item in ranked] return ranked
def identify_climate_scenario_run(scen_info, target_scen): """Identify the first matching run for a given climate scenario. Returns ---------- * str or None, run id """ for scen in scen_info: if target_scen in scen_info[scen]['climate_scenario']: return scen # End for return None
def poly(coefs,z): """Evaluate a polynomial at z given its coefficient vector""" result = 0j for c in reversed(coefs): result = result*z + c return result
def stringify_list(list_: list, quoted: bool = False ) -> str: """Converts a list to a string representation. Accepts a list of mixed data type objects and returns a string representation. Optionally encloses each item in single-quotes. Args: list_: The list to convert to a string. quoted: Indicates if the items in the list should be in quotes. Returns: A string representation of the list. """ if quoted: string_ = ', '.join(f"'{i}'" for i in list_) else: string_ = ', '.join(f'{i}' for i in list_) return string_
def format_artist(index, data): """Returns a formatted line of text describing the artist.""" return "{}. {artist}\n".format(index, **data)
def _B36Check(b36val): """ Verify that a string is a valid path base-36 integer. >>> _B36Check('aa') 'aa' >>> _B36Check('.') Traceback (most recent call last): ... ValueError: invalid ... """ int(b36val, 36) return str(b36val).lower()
def is_iterable(obj): """Return True if the object is a list or a tuple. Parameters ---------- obj : list or tuple Object to be tested. Returns ------- bool True if the object is a list or a tuple. """ return isinstance(obj, list) or isinstance(obj, tuple)
def build_tt_message(event, params): """Given an event and dictionary containing parameters, builds a TeamTalk message. Also preserves datatypes. inverse of parse_tt_message""" message = event for key, val in params.items(): message += " " + key + "=" # integers aren't encapsulated in quotes if isinstance(val, int) or isinstance(val, str) and val.isdigit(): message += str(val) # nor are lists elif isinstance(val, list): message += "[" for v in val: if isinstance(v, int) or isinstance(v, str) and v.isdigit(): message += str(v) + "," else: message += '"' + v + '",' # get rid of the trailing ",", if necessary if len(val) > 0: message = message[:-1] message += "]" else: message += '"' + val + '"' return message
def format_datetime(value, context=None): """Formats a value as an iso8601 date/time. Formatting preserves timezone information if present. """ if not value: return value return value.isoformat()
def nested_dict_lookup(key, var): """Searches a nested dictionary for a key and returns the first key it finds. Returns None if not found. Warning: if key is in multiple nest levels, this will only return one of those values.""" o = None if hasattr(var, 'iteritems'): for k, v in var.items(): if k == key: o = v break if isinstance(v, dict): result = nested_dict_lookup(key, v) if result: o = result return o
def get_key_name_as_convention(desired_name: str): """ :param desired_name: The name you would like to convert :return: The key name as a personal convention I'm using for brightness.ini """ return desired_name.lower().replace(" ", "").replace(":", "")
def any_exist(paths): """Return True if any path in list exists.""" return any([path.exists() for path in paths])
def filter_response(response, filter_fields): """Filter PowerFlex API response by fields provided in `filter_fields`. Supports only flat filtering. Case-sensitive. :param response: PowerFlex API response :param filter_fields: key-value pairs of filter field and its value :type filter_fields: dict :return: filtered response :rtype: list """ def filter_func(obj): for filter_key, filter_value in filter_fields.items(): try: response_value = obj[filter_key] response_value, filter_value = map( lambda value: [value] if not isinstance(value, (list, tuple)) else value, [response_value, filter_value]) if not set(response_value).intersection(filter_value): return False except (KeyError, TypeError): return False return True return list(filter(filter_func, response))
def _clean_protocol_metadata(protocol_metadata: dict) -> dict: """Replace confusing '|' (reserved for separation btw elements) with space. Only 1 manufacturer with this apparently but... """ return { k: v.replace("|", " ") if isinstance(v, str) else v # there are some None (not str) for k, v in protocol_metadata.items() }
def getkey(dict_, key, default=None): """Return dict_.get(key, default) """ return dict_.get(key, default)
def rundescriptor_in_dsname(dsname): """Returns (str) run-descriptor flom dsname, e.g. "6-12" from dsname="exp=xcsx35617:run=6-12". """ for fld in dsname.split(':'): if fld[:4]=='run=': return fld.split('=')[-1] return None
def decode_media_origin(hex_str: str) -> str: """ Decode a string encoded with encode_media_origin() and return a string. """ return bytes.fromhex(hex_str).decode()
def get_weekdays(first_weekday=0): """Get weekdays as numbers [0..6], starting with first_weekday""" return list(list(range(0, 7)) * 2)[first_weekday: first_weekday + 7]
def missing_explanation(json): """Returns false if all recommendations have an explanation. Returns errormessage and status code if not.""" for recommendations in json.values(): for rec in recommendations: if 'explanation' not in rec: return 'Recommendations must include explanation.', 400 return False
def get_metadata_from_attributes(Object, skip_attributes = None, custom_classes = None): """ Get metadata dict from attributes of an object. Parameters ---------- Object : object from which the attributes are. skip_attributes : list, optional If given, these attributes are skipped (next to the methods of the class of Object). The default is None. custom_classes : dict, optional Dict where keys are classes and values are functions that specify how objects of this class should be stored in metadata_dict. The default is None. Returns ------- metadata_dict : dict dict where keys-values are attributes from Object. """ if skip_attributes is None: skip_attributes = [] skip_attributes += dir(type(Object)) # methods of class will be skipped as attributes if custom_classes is None: custom_classes = {} metadata_dict = {} for a in dir(Object): if a not in skip_attributes: a_val = getattr(Object,a) if a_val is None: metadata_dict[a] = "None" elif type(a_val) in custom_classes: # treat class as specified in custom_classes dict metadata_dict[a] = custom_classes[type(a_val)](a_val) elif callable(a_val): # only get docstrings from callables metadata_dict[a] = a_val.__doc__ else: metadata_dict[a] = a_val return metadata_dict
def aero_dat(Re, Ma, Kn, p_inf, q_inf, rho_inf, gamma_var, Cd_prev, Cl_prev): """ Constant aerdynamic coefficients - space shuttle example """ C_d = 0.84 C_l = 0.84 C_s = 0.0 return [C_d, C_l, C_s]
def sol_rad_island(et_radiation): """ Estimate incoming solar (or shortwave) radiation, *Rs* (radiation hitting a horizontal plane after scattering by the atmosphere) for an island location. An island is defined as a land mass with width perpendicular to the coastline <= 20 km. Use this method only if radiation data from elsewhere on the island is not available. **NOTE**: This method is only applicable for low altitudes (0-100 m) and monthly calculations. Based on FAO equation 51 in Allen et al (1998). :param et_radiation: Extraterrestrial radiation [MJ m-2 day-1]. Can be estimated using ``et_rad()``. :return: Incoming solar (or shortwave) radiation [MJ m-2 day-1]. :rtype: float """ return (0.7 * et_radiation) - 4.0
def shout(word): """Return a string with three exclamation marks""" # Concatenate the strings: shout_word shout_word = word + '!!!' # Replace print with return return shout_word
def expected_p_t(step: int, p0: float, c_lambda: float, model_type: str) -> float: """ Computes expected value of transition probability according to theoretical results. :param step: :param p0: :param c_lambda: :param model_type: :return: """ if model_type == 'success_punished': e = (2 * c_lambda - 1) ** step * p0 + (1 - (2 * c_lambda - 1) ** step) / 2 if c_lambda != 0.5 else 0.5 elif model_type == 'success_rewarded': e = p0 elif model_type == 'success_punished_two_lambdas': e = 0 elif model_type == 'success_rewarded_two_lambdas': e = 0 else: raise Exception(f'Unexpected walk type: {model_type}') return e
def get_el_feedin_tariff_chp(q_nom, el_feedin_epex=0.02978, vnn=0.01): """ Calculates feed-in tariff for CHP-produced electricity. Parameters ---------- q_nom : nominal thermal power of chp in kW el_feedin_epex : epex price for electricity in Euro/kWh vnn : avoided grid charges ("vermiedenes Netznutzungsentgelt") in Euro/kWh Returns ------- feed-in tariff in EUR/kWh """ # KWKG 2016 revenues for el. feed-in + feedin price from epex + avoided grid charges if q_nom < 50: return 0.08+el_feedin_epex+vnn # Euro/kWh, only paid for 60.000 flh elif 50 <= q_nom < 100: return 0.06+el_feedin_epex+vnn # Euro/kWh, only paid for 30.000 flh elif 100 <= q_nom < 250: return 0.05+el_feedin_epex+vnn # Euro/kWh, only paid for 30.000 flh elif 250 <= q_nom < 2000: return 0.044+el_feedin_epex+vnn # Euro/kWh, only paid for 30.000 flh else: # q_nom > 2000: return 0.031+el_feedin_epex+vnn
def post_games(match_id='POST'): """Create a game. Return game details and status.""" # If game_id then something is wrong # If match_id then create a new game in that match # If no match_id then create a new game with no match result = '{"game_id":"POST", "match_id":"'+str(match_id)+'"}' return result
def make_text(words): """Return textstring output of get_text("words"). Word items are sorted for reading sequence left to right, top to bottom. """ line_dict = {} # key: vertical coordinate, value: list of words words.sort(key=lambda w: w[0]) # sort by horizontal coordinate for w in words: # fill the line dictionary y1 = round(w[3], 1) # bottom of a word: don't be too picky! word = w[4] # the text of the word line = line_dict.get(y1, []) # read current line content line.append(word) # append new word line_dict[y1] = line # write back to dict lines = list(line_dict.items()) lines.sort() # sort vertically return "\n".join([" ".join(line[1]) for line in lines])
def isXPathNonVar(var): """Returns true iff var is a string ("foo" or 'foo') or a number.""" if (var.startswith("'") and var.endswith("'")) or \ (var.startswith('"') and var.endswith('"')): return True # list from XPathToCode, below if var.lower() in ["count", "empty", "true", "false", "null", "and", "or", \ "like", "not"]: return True try: t=int(var) return True except TypeError as e: pass except ValueError as e: pass return False
def instancegroup_config(id, instanceCount): """ create instance_group :param id: id :type id: string :param instanceCount: instanceCount :type instanceCount: int :return: instancegroup_config """ instancegroup_config = { 'id': id, 'instanceCount': instanceCount } return instancegroup_config
def gc_sandstone(Vp, B=0.80416, C=-0.85588): """ Vs from Vp using Greenberg-Castagna sandstone coefficients. Vs = A*Vp**2.0 + B*Vp + C """ Vs = B*Vp + C return Vs
def ms_to_strtime(timems): """Convert Milliseconds to ASS string time""" s, ms = divmod(timems, 1000) m, s = divmod(s, 60) h, m = divmod(m, 60) cs, ms = divmod(ms, 10) return '{:01d}:{:02d}:{:02d}.{:02d}'.format(h, m, s, cs)
def overlay_configs(*configs): """Non-recursively overlay a set of configuration dictionaries""" config = {} for overlay in configs: config.update(overlay) return config
def _get_mean(list): """calculates and returns average from list of floats also works for 1-dimmensional numpy arrays """ ave = 0.0 for n in list: ave += n return ave / len(list)
def ID_to_int(s_id): """ Converts a string id to int falls back to assuming ID is an Int if it can't process Assumes string IDs are of form "[chars]-[int]" such as mp-234 """ if isinstance(s_id, str): return int(str(s_id).split("-")[-1]) elif isinstance(s_id, (int, float)): return s_id else: raise Exception("Could not parse {} into a number".format(s_id))
def format_speed(bps): """ Formats a string to display a transfer speed utilizing :py:func:`fsize`. This is code has been copied from :py:meth:`deluge's format_speed <deluge.ui.console.utils.format_utils.format_speed>`. :param int bps: bytes per second. :returns: a formatted string representing transfer speed :rtype: str **Usage** >>> format_speed( 43134 ) '42.1 KiB/s' """ fspeed_kb = bps / 1024.0 if fspeed_kb < 1024: return "%.1f KiB/s" % fspeed_kb fspeed_mb = fspeed_kb / 1024.0 if fspeed_mb < 1024: return "%.1f MiB/s" % fspeed_mb fspeed_gb = fspeed_mb / 1024.0 return "%.1f GiB/s" % fspeed_gb
def convert_dec_to_hex_string(decimal_value): """ This function converts a decimal value into 8-byte hex string and reverses the order of bytes. """ hex_str = '{:016x}'.format(decimal_value) reversed_hex = [] index = len(hex_str) while index > 0: reversed_hex += hex_str[index - 2:index].capitalize() + ' ' index = index - 2 return ''.join(reversed_hex)
def convert_dtype(contents): """ Take the parsed TSV file and convert columns from string to float or int """ # Convert contents to array contents_arr = contents[1:] cols = list(zip(*contents_arr)) # Iterate over every column in array for idx in range(len(cols)): # Get column col = cols[idx] # Determine if column contains float/integer/string # Check if first element is a float if '.' in col[0]: # Try to convert to float try: col = [float(x) for x in col] except ValueError: pass # Else try and convert column to integer else: # Convert to integer try: col = [int(x) for x in col] # Otherwise leave as string except ValueError: pass # Check if column only contains 'F'/'M' # if so, convert to 'Female'/'Male' if set(col).issubset({'F', 'M', 'O'}): # Iterate over column, replace col = list(col) for idxxx, item in enumerate(col): if item == 'F': col[idxxx] = 'female' elif item == 'M': col[idxxx] = 'male' elif item == 'O': col[idxxx] = 'other' else: continue ### Take converted column and place back into the content list for idxx in range(len(contents[1:])): contents[idxx+1][idx] = col[idxx] return contents
def count_frequency(samples, target): """ Calculate how frequent an target attribute appear in a list Arguments: samples (list): Input list. Its elements must be hashable. target (object): The target element. Returns: float: The frequency that target appears in samples. Must be in between 0 and 1. """ count = 0 for ele in samples: if ele == target: count += 1 return count / len(samples)
def get_column_reference(headers, name): """Make an Excel-style column reference.""" return chr(ord('A') + headers.index(name))
def charIdx_to_tokenIdx(spans, ans_text, ans_start): """ Convert answer 'char idx' to 'token idx' for one single record """ # Convert answer 'char idxs' to 'token idxs' for one single record if ans_start != -999: ans_end = ans_start + len(ans_text) - 1 ans_token_idxs = [] for token_idx, span in enumerate(spans): if span[0] < ans_end and span[1] > ans_start: ans_token_idxs.append(token_idx) y1, y2 = ans_token_idxs[0], ans_token_idxs[-1] else: y1, y2 = -999, -999 return y1, y2
def get_write_param_value(mode, memory, ptr): """Returns the value of the paramter at memory[ptr] based on the mode, for a writing parameter""" # position mode if mode == 0: return memory[ptr] # immediate mode elif mode == 1: # immediate mode is not supported raise Exception else: raise Exception
def slice_to_list(sl, max_len): """ Turn a slice object into a list Parameters ---------- sl: slice The slice object max_len: int Max length of the iterable Returns ------- list The converted list """ if sl.start is None: start = 0 elif sl.start < 0: start = max_len + sl.start else: start = sl.start if sl.stop is None: stop = max_len elif sl.stop < 0: stop = max_len + sl.stop else: stop = sl.stop if sl.step is None: step = 1 else: step = sl.step return list(range(start, stop, step))
def custom_format(template, **kwargs): """ Custom format of strings for only those that we provide :param template: str - string to format :param kwargs: dict - dictionary of strings to replace :return: str - formatted string """ for k, v in kwargs.items(): template = template.replace('{%s}' % k, v) return template
def is_safe(func_str): """ Verifies that a string is safe to be passed to exec in the context of an equation. :param func_str: The function to be checked :type func_str: string :returns: Whether the string is of the expected format for an equation :rtype: bool """ # Remove whitespace func_str = func_str.replace(' ', '') # Empty string is safe if func_str == '': return True # These are all safe and can be stripped out if 'np' in func_str: np_funcs = ['np.exp', 'np.cos', 'np.sin', 'np.tan', 'np.pi'] for s in np_funcs: func_str = func_str.replace(s, '') # Store valid symbols for later symbols = ['**', '/', '*', '+', '-'] # Partition on outer brackets if '(' in func_str: if ')' not in func_str: # Number of brackets don't match return False # Split string "left(centre)right" left, remainder = func_str.split('(', 1) centre, right = remainder.split(')', 1) # Handle nested brackets while centre.count('(') != centre.count(')'): tmp, right = right.split(')', 1) centre = centre + ')' + tmp # If left is non-empty it should end with a symbol if left != '': left_ends_with_symbol = False for sym in symbols: if left.endswith(sym): left = left.strip(sym) left_ends_with_symbol = True break if left_ends_with_symbol is False: return False # If right is non-empty it should start with a symbol if right != '': right_starts_with_symbol = False for sym in symbols: if right.startswith(sym): right = right.strip(sym) right_starts_with_symbol = True break if right_starts_with_symbol is False: return False # Centre should not be empty if centre == '': return False # Return True if all sub parts are safe return is_safe(left) and is_safe(centre) and is_safe(right) # Split on a symbol and recurse for sym in symbols: if sym in func_str: left, right = func_str.split(sym, 1) # Symbol should not be at start or end of string (unless it's a -) if (left == '' and sym != '-') or right == '': return False # Return True if both sub parts are safe return is_safe(left) and is_safe(right) # Floating points are acceptable try: float(func_str) return True except ValueError: pass # Ints are acceptable try: int(func_str) return True except ValueError: pass # Only remaining acceptable strings are variables if func_str[0].isalpha() and func_str.isalnum(): return True # Unparsed output remains return False
def find_index(text, pattern): """Return the starting index of the first occurrence of pattern in text, or None if not found. C++ way of checking the chars in the string method used. Run time: O(n*m), n is length of the string, m is for if statement to check match is found. Space Complexity: O(1) because I am accessing the array indexes, it takes O(1) and doesn't create a new memory as opposed to pyhton slicing. declaring 3 variable takes constant space in the memory""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) if pattern == "": return 0 starter = 0 # the starting index of the patterin in the text index = 0 # index for text subindex = 0 # index for pattern while index <= len(text) - 1: if text[index] == pattern[subindex]: index += 1 subindex +=1 if subindex == len(pattern): # check for if we checked all index of patter # starter index of the text where pattern occured 1st time return starter else: # mismatch found starter += 1 # shift the starter to next index index = starter subindex = 0 # reset the subindex return None
def flatten_dict(d, prefix=''): """ Recursively flattens nested dictionaries. Warning: Eliminates any lists! """ result = {} for key in d: if isinstance(d[key], str): result[prefix + key] = d[key] elif isinstance(d[key], dict): prefix = key + '_' subdict_flattened = flatten_dict(d[key], prefix=prefix) result.update(subdict_flattened) return result
def _format_as_index(indices): """ (from jsonschema._utils.format_as_index, copied to avoid relying on private API) Construct a single string containing indexing operations for the indices. For example, [1, 2, "foo"] -> [1][2]["foo"] """ if not indices: return "" return "[%s]" % "][".join(repr(index) for index in indices)
def map(function, iterator): """ Our own version of map (returns a list rather than a generator) """ return [function(item) for item in iterator]
def percent_g(seq): # checked """Returns the percentage of G bases in sequence seq""" return float("%.2f"%((seq.count("G") / float(len(seq))) * 100))
def iss(ary): """Sorts an array in a nondecreasing order""" ary_len = len(ary) for i in range(ary_len): j = i while ary[j] < ary[j - 1] and j > 0: ary[j], ary[j - 1] = ary[j - 1], ary[j] j -= 1 return ary
def remove_v(ss,v): """ removes from ss those that have value v""" s = [] for i in range(len(ss)): if ss[i] == v: continue else: s = s + [ss[i]] return s
def check(ans, temp_ans, input_ch): """ Check if the user guessed the right letter. :param ans: The correct word string. :param temp_ans:Every temporarily answer when the user guess a letter. :param input_ch: The character the user input. :return: return to the temporarily answer when the user do a new guess. """ for i in range(len(ans)): if input_ch in ans[i]: temp_ans = temp_ans[:i] + ans[i] + temp_ans[i+1:] return temp_ans
def skip_add(n): """ Takes a number n and returns n + n-2 + n-4 + n-6 + ... + 0. >>> skip_add(5) # 5 + 3 + 1 + 0 9 >>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0 30 >>> # Do not use while/for loops! >>> from construct_check import check >>> # ban iteration >>> check(this_file, 'skip_add', ... ['While', 'For']) True """ if n <= 0: return 0 else: return n + skip_add(n - 2)
def set_trainable_params(params): """ Freeze positional encoding layers and exclude it from trainable params for optimizer. """ trainable_params = [] for param in params: if param.name.endswith('position_enc.embedding_table'): param.requires_grad = False else: trainable_params.append(param) return trainable_params
def oooc_to_ooow(formula): """Convert (proprietary) formula from calc format to writer format. Arguments: formula -- str Return: str """ prefix, formula = formula.split(":=", 1) assert "oooc" in prefix # Convert cell addresses formula = formula.replace("[.", "<").replace(":.", ":").replace("]", ">") # Convert functions formula = formula.replace("SUM(", "sum ").replace(")", "") return "ooow:" + formula
def is_ltriangular(A): """Tells whether a matrix is an lower triangular matrix or not. Args ---- A (compulsory) A matrix. Returns ------- bool True if the matrix is an lower triangular matrix, False otherwise. """ for i in range(len(A)): for j in range(len(A[0])): try: if A[i][j] != 0 and i < j: return False except IndexError: #Would happen if matrix is not square. return False return True
def concatenate_authors(list_of_authors): """Concatenate a list of authors into a string seperated by commas, and with the last author preceded by 'and'.""" if not isinstance(list_of_authors, list) or len(list_of_authors) == 0: return None elif len(list_of_authors) == 1: return list_of_authors[0] elif len(list_of_authors) < 10: author_string = ", ".join(list_of_authors[:-1]) return f"{author_string} and {list_of_authors[-1]}" # Only cite the first author (especially important for particle physics publications with 100+ authors). else: return f"{list_of_authors[0]} et al."
def average_rate(instantaneous_rate_primary, instantaneous_rate_secondary): """Returns the average achievable rate for SNR value in dB. Arguments: instantaneous_rate_primary -- instantaneous achievable rate of the primary user. instantaneous_rate_secondary -- instantaneous achievable rate of the secondary user. Return: avr_rate -- average achievable rate in bits/s/Hz """ # Calculating of average achievable rate of the system avr_rate = ( instantaneous_rate_primary + instantaneous_rate_secondary ) / 2 # Average achievable rate in bits/s/Hz return avr_rate
def remove_newline(string, n=1): """Remove up to `n` trailing newlines from `string`.""" # Regex returns some weird results when dealing with only newlines, # so we do this manually. # >>> import re # >>> re.sub(r'(?:\r\n|\n\r|\n|\r){,1}$', '', '\n\n', 1) # '' for _ in range(n): if string.endswith("\r\n") or string.endswith("\n\r"): string = string[:-2] elif string.endswith("\n") or string.endswith("\r"): string = string[:-1] else: break return string
def backslash_escape(data): """ This encoding is used in JSON: Double quotes become: \" Single quotes become: \' """ return data.replace(u'"', u'\\"').replace(u"'", u"\\'")