content
stringlengths
42
6.51k
def path_to_folders(path): """ Convert path to a standarised list of folder. If path is prepended with /, first element on the list will be special folder None denoting root. :param path: None or path string with folders '/' separated, e.g. /NAS/Music/By Folder/folder1/folder2 :returns: List of fo...
def make_list_if_string(item): """Put `item` into a list.""" if isinstance(item, str): return [item] return item
def escapeXml(raw): """Escape an XML string otherwise some media clients crash.""" # Note that we deliberately convert ampersand first so that it is not # confused for anything else. mapping = [ ("&", "&amp;"), ("<", "&lt;"), (">", "&gt;"), ('"', "&quot;"), ("'", ...
def stack_pixel(pixel_top, pixel_bottom): """ >>> stack_pixel(1, 0) 1 >>> stack_pixel(1, 1) 1 >>> stack_pixel(1, 2) 1 >>> stack_pixel(2, 0) 0 >>> stack_pixel(2, 1) 1 >>> stack_pixel(2, 2) 2 >>> stack_pixel(0, 0) 0 >>> stack_pixel(0, 1) 0 >>> stack_...
def generate_sess_end_map(sess_end, sessId, time): """ Generate map recording the session end time. :param sess_end: the map recording session end time, a dictionary see_end[sessId]=end_time :param sessId:session Id of new action :param time:time of new action :return: sess_end: the map recordin...
def create_success_response(return_data): """ Creates a standard success response used by all REST apis. """ count = 1 if isinstance(return_data, list): count = len(return_data) return { 'meta': { 'error': False, 'count': count }, 'data': retu...
def strfmoney(value): """ Take an atomic integer currency `value` and format a currency string (e.g. 410 => "4.10") """ if value is None: return '0.00' elif isinstance(value, int): s = str(float(value / 100)) if len(s.split('.', 1)[1]) == 1: s += '0' ...
def preprocess_parsed(parsed, keys_removed): """ Removes any key with a value of "_No response_" or in `keys_removed`. """ # First need to add some keys parsed["categories"] = "Publications" # Sanitize some keys parsed["shorthand"] = parsed["shorthand"].replace("/", "-") # Then, modif...
def binary_encoding(string, encoding="utf-8"): """ This helper function will allow compatibility with Python 2 and 3 """ try: return bytes(string, encoding) except TypeError: # We are in Python 2 return str(string)
def bitmask(bit: int, fill: bool = False) -> int: """ Returns a bitmask for the given bit length. :param int bit: Bit length. :param bool fill: If true, fill the mask with ones. :returns: bitmask. :rtype: int """ mask = (1 << bit) return (((mask - 1) << 1) | 1) if fill else m...
def normalize_dict(d): """removes datetime objects and passwords""" for k in d.keys(): if d.get(k).find('password') != -1: d[k] = 'xxxxx' return d
def parse_author(obj): """Parse the value of a u-author property, can either be a compound h-card or a single name or url. :param object obj: the mf2 property value, either a dict or a string :result: a dict containing the author's name, photo, and url """ result = {} if isinstance(obj, dic...
def get_linear_lr(base_lr, total_epoch, spe, lr_init, lr_end, warmup_epoch=0): """Get learning rates decay in linear.""" lr_each_step = [] total_steps = spe * total_epoch warmup_steps = spe * warmup_epoch for i in range(total_steps): if i < warmup_steps: lr = lr_init + (base_lr -...
def single_spaces(input): """ Workaround for https://github.com/github/codeql-coreql-team/issues/470 which causes some metadata strings to contain newlines and spaces without a good reason. """ return " ".join(input.split())
def strip(value): """Strips the string separators from the value.""" if value[0] in '"<' and value[-1] in '">': return value[1:-1] return value
def solve_slow(buses): """ slow, brute-force. Used this to test - whether i understood the problem - whether my faster solution works """ buses = [int(x.replace('x', '0')) for x in buses.split(',')] depart = -1 found = False highest = max(buses) while not found: depar...
def get_elo_score(old, exp, score, k=32): """ Calculate the new Elo rating for a player :param old: The previous Elo rating :param exp: The expected score for this match :param score: The actual score for this match :param k: The k-factor for Elo (default: 32) """ return int(old + k * (s...
def map_value(value, inmin, inmax, outmin, outmax): """Map the value to a given min and max. Args: value (number): input value. min (number): min input value. max (number): max input value. outmin (number): min output value. outmax (number): max output value. Return...
def booth(args): """ Name: Booth Global minimum: f(1.0,3.0) = 0.0 Search domain: -10.0 <= x, y <= 10.0 """ x = args[0] y = args[1] return (x + 2 * y - 7) ** 2 + (2 * x + y - 5) ** 2
def adder(collection): """Add the numbers supplied in collection. Return result.""" sum_of_collections = 0 for numbers in collection: sum_of_collections += numbers return sum_of_collections
def calculate_score(cards): """Take a list of cards and return the score calculated from the cards""" if sum(cards) == 21 and len(cards) == 2: return 0 if 11 in cards and sum(cards) > 21: cards.remove(11) cards.append(1) return sum(cards)
def chop(seq, size): """Chop a sequence into chunks of the given size.""" return [seq[i:i+size] for i in range(0,len(seq),size)]
def get_results(results): """ Returns a tuple of the value scored, possible, and a list of messages in the result set. """ out_of = 0 scored = 0 if isinstance(results, dict): results_list = results.values() else: results_list = results for r in results_list: i...
def latest(scores): """ return latest entry """ return scores[-1]
def get_api_url(job_id): """ Return the WDL PersecData API endpoint The endpoint returned by this module is: https://api.welldatalabs.com/persecdata/<job_id> Parameters ---------- job_id: str The job_id to search the PerSec API for Returns ------- url: str The...
def safe_division(number, divisor, ignore_overflow=False, ignore_zero_division=False): """ safe_division :param number: :param divisor: :param ignore_overflow: :param ignore_zero_division: :return: """ try: return number / divisor except OverflowError: if ignore_o...
def diagonal_distance(current_x, current_y, goal_x, goal_y): """ Diagonal distance current_node(current_x, current_y) goal_node(goal_x, goal_y) """ return max(abs(current_x - goal_x), abs(current_y - goal_y))
def _determine_educ_type(model_name): """Determine whether an education model is school, preschool or nursery. Args: model_name (str): name of the education model, e.g. educ_school_0. """ name_parts = model_name.split("_") msg = f"The name of your education model {model_name} does not " ...
def calc24hr(hour, period): """Converts given hour to 24hr format""" if not hour: return None hour = int(hour) if period == "pm" and hour <= 12: hour = 0 if hour == 12 else hour + 12 if hour > 23: hour = 8 return hour
def fast_replace(t, sep, sub=None): """ Replace separators (sep) with substitute char, sub. Many-to-one substitute. "a.b, c" SEP='.,' :param t: input text :param sep: string of chars to replace :param sub: replacement char :return: text with separators replaced """ result = [] ...
def recursive_map(func, data): """Recursively applies a map function to a list and all sublists.""" if isinstance(data, list): return [recursive_map(func, elem) for elem in data] else: return func(data)
def paeth_predictor(a, b, c): """ The "paeth predictor" used for paeth filter. :param a: left :param b: above :param c: upper-left :return: predicted value """ p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: return a e...
def syntactic_roles_to_semantic_match(syntactical_sentence, voice_is_active=True): """ Selects which elements of the syntactical sentence must match the verb, agent and patient, respectively. Args: syntactical_sentence: a list of tuples (symbol, attributes) ...
def traslate(points: list, dx: float, dy: float): """Traslate each point of a list of dx and dy length. It's a differential traslation, not absoluta at point. The traslation action will be performed on the actual points of the Shape, that is on the last its transformation """ # Perform traslati...
def serialize_forma_latest(analysis, type): """Convert the output of the forma250 analysis to json""" return { 'id': None, 'type': type, 'attributes': { 'latest': analysis.get('latest', None) } }
def replace_wildcard(input_list): """Method to replace a wildcard `-` in the input values. This method will replace the wildcard `-` in the input list; the returned two lists have different values on the position of `-`. Example: ['0', '-', '1'] => (['0', '0', '1'], ['0', '1', '1']) Parameters ...
def parse_int_set(nputstr=""): """ return a set of selected values when a string in the form: 1-4,6 would return: 1,2,3,4,6 as expected... Taken from https://stackoverflow.com/a/712483 """ if isinstance(nputstr, int): return set([nputstr]) selecti...
def search_before(position, text, pattern): """ Search for the parameter before the given position in the given text. """ # Find the first open parenthesis before the given position. seed_search = position - 2 # because of the parenthesis ")" par_count = 1 get_paranthesis_body = "" whil...
def dBW_to_watts(dbw): """Convert log-power from dBW to watts.""" return 10 ** (dbw / 10)
def pts_from_rect_inside(r): """ returns start_pt, end_pt where end_pt is _inside_ the rectangle """ return (r[0], r[1]), ((r[0] + r[2] - 1), (r[1] + r[3] - 1))
def calc_total_fuel_for_mass(mass:int) -> int: """Calculates the total amount of fuel needed for a given mass, including its needed fuel mass.""" fuel = (mass // 3) - 2 if fuel <= 0: return 0 return fuel + calc_total_fuel_for_mass(fuel)
def pop_tuple_keys_for_next_level(tuple_key_list): """ Function takes list of tuple keys (TYPE, NAME) Returns list of selected tuple keys """ poped_nks = [] key_level_separator_found = False if not tuple_key_list: return poped_nks, key_level_separator_found while True: ...
def tag(tag): """Select a single tag.""" return {'tag': tag}
def racecar_name_to_agent_name(racecars_info, racecar_name): """ Given the racecars_info as list and the racecar_name and racecar_name get the agent name Arguments: racecars_info (list): List of racecars_info racecar_name (str): Racecar name """ return 'agent' if len(racecars_info) ...
def sort(records): """ Function to sort records by time_last :param records: List (of dictionaries) :return: List (of dictionaries) """ from operator import itemgetter sorted_results = sorted(records, key=itemgetter("time_last"), reverse=True) return sorted_results
def tupleify_state(state): """ Returns the state as a tuple """ temp = [] for row in state: temp.append(tuple(row)) return tuple(temp)
def cls_name(instance): """Return the name of the class of the instance. >>> cls_name({}) 'dict' >>> cls_name(AttributeError('attr')) 'AttributeError' """ return instance.__class__.__name__
def _to_list(val): """Return the variable converted to list type.""" if isinstance(val, list): return val else: return [val]
def set_source_display( n_interval, meas_triggered, knob_val, old_source_display_val, swp_start, swp_stop, swp_step, mode_choice, swp_on, ): """"set the source value to the instrument""" # Default answer answer = old_source_display_val if mode_choice is False: ...
def most_repeated_element(array): """ Fins the most repeated element and its frequency in an array using a hash table. Time complexity: O(n + m). :param array: is the array to find the most repeated element in. :return: a tuple containing the most repeated element and its frequency. """ tab...
def to_xyz(xy): """Convert a two-tuple (x, y) coordinate into an (x, y, 0) coordinate.""" x, y = xy return (x, y, 0)
def generate_spreadsheet_from_occurrences(occurrences): """Generate spreadsheet data from a given booking occurrence list. :param occurrences: The booking occurrences to include in the spreadsheet """ headers = ['Room', 'Booking ID', 'Booked for', 'Reason', 'Occurrence start', 'Occurrence end'] row...
def set_bits(register: int, value, index, length=1): """ Set selected bits in register and return new value :param register: Input register value :type register: int :param value: Bits to write to register :type value: int :param index: Start index (from right) :type index: int :par...
def replace_multiple_caracters(string, caracters, replacement): """ Take a string you want to replace, a string of caracters you want to replace and the caracter of replacement of these caracters Replace the caracters by their replacement. """ for caracter in caracters: string = string.replace(caracter, repla...
def changed_code_config(child_config): """Create a child config with a changed dimension""" child_config['metadata']['VCS']['HEAD_sha'] = 'new_test' return child_config
def wp_darkmatter(rp): """best fit power-law for MDR1 z=1 (pimax=50)""" r0, alpha = (41.437187675742656, -0.832326251664125) return (rp/r0)**alpha
def reverse_string(text): """ Reverse the provided string of characters""" return text[::-1]
def set_initial_params(size: int) -> tuple: """ Set initial parameters: line, spiral, direction, coordinate, done :param size: :return: """ spiral: list = list() while len(spiral) != size: line: list = [0] * size spiral.append(line) direction: str = 'right' coordinate: dict = { ...
def sanitise_text(text): """When we process text before saving or executing, we sanitise it by changing all CR/LF pairs into LF, and then nuking all remaining CRs. This consistency also ensures that the files we save have the correct line-endings depending on the operating system we are running on. ...
def eq2 (A, B, T): """Chemsep equation 2 :param A: Equation parameter A :param B: Equation parameter B :param T: Temperature in K""" return A + B*T
def char_count(word): """Return a dictionary with the incidence of each character.""" rdict = {} chars = list(word) # turn string into list for c in chars: if c in rdict: rdict[c] += 1 else: rdict[c] = 1 return rdict
def timesastring (num,string,sep): """num= number of times to repeat a string; string=word or string to be repeated; sep=separator""" return(num*(string+sep))[:-1]
def list_to_str(list_arg, delim=' '): """Convert a list of numbers into a string. Args: list_arg: List of numbers. delim (optional): Delimiter between numbers. Returns: List converted to string. """ ret = '' for i, e in enumerate(list_arg): if i > 0: r...
def encryptMessage(key, message): """ >>> encryptMessage(6, 'Harshil Darji') 'Hlia rDsahrij' """ cipherText = [""] * key for col in range(key): pointer = col while pointer < len(message): cipherText[col] += message[pointer] pointer += key return "".joi...
def _compare_time(f_time, interval): """ Compares time with interval less than interval Args: f_time ([type]): [description] interval ([type]): [description] Returns: [type]: [description] """ if f_time < interval: f_time = interval elif f_time % interval !=...
def fibi(n: int) -> int: """Fibonacci numbers saving just two previous values >>> fibi(20) 6765 >>> fibi(1) 1 >>> fibi(2) 1 >>> fibi(3) 2 """ if n == 0: return 0 if n == 1: return 1 f_n2, f_n1 = 1, 1 for _ in range(3, n+1): f_n2, f_n1 = f_...
def get_gug_file(condition): """ Get the filename of which saves grammatical and ungrammatical items of a specific grammar :param condition: "RE" or "CFG" :type condition: string :return: a filename :rtype: string """ if condition == "RE": return "materials/re_gug.txt" elif c...
def get_file_id(string): """ Returns file_id from a information string like Ferrybox CMEMS: <file_id> :param string: :return: """ return string.split(':')[-1].strip()
def j_map_to_dict(m): """Converts a java map to a python dictionary.""" if not m: return None r = {} for e in m.entrySet().toArray(): k = e.getKey() v = e.getValue() r[k] = v return r
def adjacentElementsProduct(inputArray): """ Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. -> int """ iter = len(inputArray) - 1 maxProd = inputArray[0]*inputArray[1] for i in...
def base26int(s, _start=1 - ord('A')): """Return string ``s`` as ``int`` in bijective base26 notation. >>> base26int('SPAM') 344799 """ return sum((_start + ord(c)) * 26**i for i, c in enumerate(reversed(s)))
def get_elem_str(A: set): """ 1 column only, may use more in the futre """ return '\n'.join(map(str,A))
def is_status_valid(status): """Checks if the status value is valid""" if isinstance(status, str): res = status in ["UNKNOWN", "SLEEPING", "WAITING", "RUNNING", "TERMINATED", "DONE"] elif isinstance(status, int): res = 0 <= status <= 5 else: return False return res
def contains(array_name, item): """ Returns True if the given array contains the given item. Otherwise, returns False. """ try: return array_name.index(item) except ValueError: return False
def float_or_str(x): """ Return *x* converted to float or *x* if that fails. """ try: return float(x) except: return x
def stringize(data): """Given data for a citizen where integers are really integers and such, make them all into strings.""" for field in data.keys(): if field == 'birth_date': data[field] = data[field].strftime("%d/%m/%Y") # strftime always zero-pads, the dump doesn't, so g...
def determinize_tree(determinization, ppddl_tree, index = 0): """ Replaces all probabilistic effects with the given determinization. Variable "determinization" is a list of determinizations, as created by "get_all_determinizations_effect". This function will visit the PPDDL tree in pre-order traversal...
def to_camel_case(snake_case): """ convert a snake_case string to camelCase """ components = snake_case.split('_') return components[0] + "".join(x.title() for x in components[1:])
def hex_to_int(ch): """function to process hex characters. Just convert to ints.""" return int(ch,16)
def remove_suffix(text, suffix): """ If a particular suffix exists in text string, This function removes that suffix from string and then returns the remaining string """ if suffix and text.endswith(suffix): return text[:-len(suffix)] return text
def link_fedora_file(sid): """ Creates an html link tag to a file in Fedora. :param sid: a file id :return: link to the file content """ return '<a href="http://easy01.dans.knaw.nl:8080/fedora/objects/{}/datastreams/EASY_FILE/content" target="_blank">{}</a>'\ .format(sid, sid)
def get_songs_names(playlist): """Get names of songs in playlist to search on YT.""" songs = [] for song in playlist: song = song['track'] name = '' for artist in song['artists']: name += artist['name'] + ', ' name = name[:-2] name += ' - ' + song['name'] ...
def sign(number): """ Returns the sign of the number (-1, 0 or 1) Arg1: float Returntype: int """ if number > 0: return 1 elif number < 0: return -1 else: return 0
def edges_from_matchings(matching): """ Identify all edges within a matching. Parameters ---------- matching : list of all matchings returned by matching api Returns ------- edges : list of all edge tuples """ edges = [] nodes = [] # only address highest...
def version_to_string(version): """Turn a version tuple into a string.""" return ".".join([str(x) for x in version])
def DeepSupervision(criterion, xs, y): """DeepSupervision""" loss = 0. for x in xs: loss += criterion(x, y) return loss
def get_value(data, key): """Get value of data Args: data : Description key : Description Returns: value mapped to key in the data """ try: return data[key] except Exception: return None
def _process_relations(relations): """extract relation indices from a relation list""" result = [] for rel_type, rels in relations.items(): for rel in rels: result.append((rel_type, rel.from_object.title, rel.to_object.title)) result.sort() return result
def cast_uint(value): """ Cast value to 32bit integer Usage: cast_int(1 << 31) == 2147483648 """ value = value & 0xffffffff return value
def generateMatrix(n): """ This function generates an N * N matrix and writes the results to two files matrixA.txt and matrixB.txt as row col values """ #open files for writing file_a = open("matrix.txt", 'w+') matrix = [[0 for i in range(int(n))] for j in range(int(n))] #create ...
def std_ref_form(ref_string): """ Deletes unnecessary chars from the string. Seperates combined references. returns the refernces in a list. """ if ' corr.' in ref_string: ref_string = ref_string.replace(' corr.','') while ',' in ref_string: ref_string = ref_string.repla...
def _replace_comments(s): """Replaces matlab comments with python arrays in string s.""" s = s.replace('%', '#') return s
def how_related(Z0, Z1, Z2, PI_HAT): """Based on assign_relatedness.R from Salih Tuna""" z0, z1, z2, pi_hat = [round(float(i) / 0.25) * 0.25 for i in [Z0, Z1, Z2, PI_HAT]] # Check relationship # Idenical: if z0 == 0 and z1 == 0 and z2 == 1 and pi_hat == 1: relationship = "Duplicate or MZ tw...
def collect_data(key, *args): """ Collects all items corresponding to key argument in *args. It realizes a depth-first travel of the dictionary, calling itself recursively on the structures.""" collection = set() if args: for arg in args: if key in arg: collectio...
def is_even(number): """ Check if `number` is even. Parameters ---------- number : integer The integer to be checked Returns ------- boolean Returns True of `number` is even, False otherwise. """ return number % 2 == 0
def inMSet(c,n): """ inMSet takes in c for the update step of z = z**2+c n, the maximum number of times to run that step Then, it should return False as soon as abs(z) gets larger than 2 True if abs(z) never gets larger than 2 (for n iterations) """ z = 0 for...
def azure_file_share_name(sdv, sdvkey): # type: (dict, str) -> str """Get azure file share name :param dict sdv: shared_data_volume configuration object :param str sdvkey: key to sdv :rtype: str :return: azure file share name """ return sdv[sdvkey]['azure_file_share_name']
def ftoi(num): """ Float to int if it has no decimal 1.0 -> 1 """ return int(num) if int(num) == num else num
def file_is_gamess(file): """ Check first line of file for 'rungms' string """ with open(file, "r") as f: return "rungms" in f.readline()
def isleap(year: int): """Returns True if year entered is a leap year.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)