content
stringlengths
42
6.51k
def define_columns(debug=False): """ Define the columns to use in the csv file """ columns = ['Vorf', 'Vorfanz', 'Stellen', 'Post', 'Fragl', 'Offen', 'Hinweis', 'sum_rank', 'ranks'] if debug: # vus_stellen is just too much for spreadsheet programs - so ignore it. #colu...
def deg2dms(deg, delim=':', doSign=False, nPlaces=2): """ Convert a float in degrees to 'dd mm ss' format. """ try: angle = abs(deg) sign=1 if angle!=0: sign = angle/deg # Calcuate the degrees, min and sec dd = int(angle) rmndr = 60.0*(angle - dd...
def count_unique_data_points_groupby_point_forall_traffic(reader): """ Process 5-min traffic flow data and execute a breakdown of the data to each different ingress/egress member ASN. Files format: ".avro.point=egress.ipv=4.svln=all.txt.gz" ".avro.point=ingress.ipv=4.svln=all.txt.gz" ingre...
def count_possible_passwords(start, end, validators): """Count possible passwords from start to end, fulfilling validators.""" count = 0 for number in range(start, end + 1): if all(validator(number) for validator in validators): count += 1 return count
def update_state(state, update, expected=False): """Generates a new state based on the specified update dict; @updates: Dict of update function. value can be: constant (to add), or a function taking a 'state' dictionary @returns copy of state with updated values. note: this does not attenuate (cla...
def get_metadata_url(url, type): """ A wrapper to get different timestamps. :param url: The url to get the timestamp :param type: The type of services (e.g. osm) :return: The timestamp as a string. """ if type in ["wcs", "wms", "wmts"]: return "{0}?request=GetCapabilities".format(url...
def probar_fin_juego(casillas_jugadas, casillas_ocupadas): """Permite probar si el juego ha terminado o no""" if len(casillas_ocupadas - casillas_jugadas) == 0: print("Bravo. El juego ha terminado !") return True return False
def _build_response(rpc_id, result): """ Build a JSON response Args: rpc_id (int): The request id result : Json serializable data Returns: dict the json_rpc success response as dict """ resp = { 'jsonrpc': '2.0', 'id': rpc_id, 'result': result ...
def mirror_dict(source: dict) -> dict: """ Creates a dictionary with all values as keys and all keys as values. """ source.update({value: key for key, value in source.items()}) return source
def bottom_row_movement(next_row_only, n): """Defines movement logic and returns results of 3 actions RLU""" movement_states={} for state in next_row_only: empty_R=['0']*n; empty_L=['0']*n a_index=list(state[:n]).index('1') if a_index==0: empty_R[1]='1'; right=''.join(emp...
def del_none(d): """ Delete dict keys with None values, and empty lists, recursively. """ for key, value in d.items(): if value is None or (isinstance(value, list) and len(value) == 0): del d[key] elif isinstance(value, dict): del_none(value) return d
def str2int(cha): """Representation of a char as an integer""" if 'a' <= cha <= 'z': return ord(cha) - ord('a') elif 'A' <= cha <= 'Z': return ord(cha) - ord('A') + 26 elif cha.isdigit(): return ord(cha) - ord('0') + 52
def right_pad(string, size): """Add zeros to the end of a string to reach a certain length.""" return string.ljust(size, '0')
def convert_task_id_to_name_of_log_file(id_): """Convert task to id to name of log file. If one passes the complete task id as the log file name, Stata would remove parent directories and cut the string at the double colons for parametrized task. Here is an example: .. code-block:: none C...
def get_region_for_chip(x, y, level=3): """Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the sp...
def box_area(xmin, xmax, ymin, ymax): """ INPUT: 2-tuple of cubics (given by control points) OUTPUT: boolean """ return (xmax - xmin)*(ymax - ymin)
def map_dictionary_keys(d, map_function): """ Maps the keys of a provided dictionary given a mapping function :param d: dictionary to map the keys of :param map_function: function to apply to each of the keys. Should accept a single string parameter and return the mapped string :return: dictiona...
def keys_exist(element, *keys): """ Check if *keys (nested) exists in `element` (dict). """ _element = element for key in keys: try: _element = _element[key] except KeyError: return False return True
def _calc_source_bounding_box(bbox, source_shape): """Calculates the bounding of the source image to crop. The data of the image within this source bounding is extracted for cropping. Args: bbox (tuple[slice]): The len==3 bounding box of the cropping. The start of the slice could b...
def hailstone(n): """Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ "*** YOUR CODE HERE ***" count = 1 if (n == 1): print(1) return 1 while n!= 1: print(n) ...
def is_dict_type(value): """Treat any dict, MergeDict, MultiDict instance as dict type""" # Check by class name to avoid importing Django MergeDict or # Werkzeug MultiDict return isinstance(value, dict) or \ value.__class__.__name__ in ('MergeDict', 'MultiDict')
def factorial_pythonic(number: int) -> int: """Factorial with reduce function (pythonic approach). Examples: >>> assert factorial_pythonic(0) == 1 >>> assert factorial_pythonic(1) == 1 >>> assert factorial_pythonic(2) == 2 >>> assert factorial_pythonic(3) == 6 """ return...
def flat(l): """ Returns the flattened version of a '2D' list. List-correlate to the a.ravel()() method of NumPy arrays. Usage: flat(l) """ newl = [] for i in range(len(l)): for j in range(len(l[i])): newl.append(l[i][j]) return newl
def _find_run_id(traces, trace_type, item_id): """Find newest run_id for a script or automation.""" for trace in reversed(traces): if trace["domain"] == trace_type and trace["item_id"] == item_id: return trace["run_id"] return None
def ref_compress(references): """>>> ref_compress([(2, 2), (5, 3), (0, 2)]) [(0, 4), (5, 3)] Used for shortening calls to glDrawArrays and glDrawRangeElements""" r = [] chain = False references = sorted(references, key=lambda x: x[0] + x[1]) for ref, next_ref in zip(references, references[1:]): ...
def make_newick(struct): """ Converts a structure of nested lists into Newick string. """ if not type([]) in [type(x) for x in struct]: return "(%s)" % ",".join(struct) if len(struct) > 1 else struct[0] else: return "(%s)" % ",".join([make_newick(substruct) for substruct in struct])
def circularlerp(value, start, end): """ Circular Lerp interpolation Wraps around to get closest path (0.0 = 1.0) """ shortest_path = ((end-start)+0.5)%1.0 -0.5 result = (start+shortest_path*value)%1.0 return result
def miles_to_kilometers(miles): """Convert miles to kilometers PARAMETERS ---------- miles : float A distance in miles RETURNS ------- distance : float """ # apply formula return miles*1.609344
def complete_sequence(adj_seq): """If 'N' is present iin the sequence, kmer is undefined""" return not ('N' in adj_seq or 'n' in adj_seq)
def default_calculate_debounced_passing(recent_results, debounce=0): """ `debounce` is the number of previous failures we need (not including this) to mark a search as passing or failing Returns: True if passing given debounce factor False if failing """ if not recent_results: ...
def max_profit_optimized(price_arr: list) -> int: """ 1) Create a table profit[0..n-1] and initialize all values in it 0. 2) Traverse price[] from right to left and update profit[i] such that profit[i] stores maximum profit achievable from one transaction in subarray price[i..n-1] 3) Trave...
def str2int(s): """Convert an octet string to an integer. Octet string assumed to represent a positive integer.""" r = 0 for c in s: r = (r << 8) | ord(c) return r
def concat_to_pair_list(pair_list, prefix='', suffix=''): """ Add prefix and suffix to the strings in a a list of 2-tuple str. Parameters ---------- pair_list: list of 2-tuples of str prefix: str suffix: str Returns ------- formatted_pair_list: list of 2-tuples of str """ ...
def is_true_sequence(values): """Are card values in sequence?""" for i, j in zip(values, values[1:]): if i - 1 != j: return False return True
def summarized_content_match(text: str, ctx_word: str, ctx_len: int) -> str: """ Summarize a line of text by leaving ctx_len characters around the ctx_word and trimming the rest """ i = text.find(ctx_word) if i == -1: return text start = max(0, i - ctx_len) end = min(len(text), i...
def epsilon_to_kappa(r_k, epsilon, delta=0.16): """Convert frequency r_k and strain epsilon to corresponding r_k and kappa as consumed by functions in `latticegeneration`. Returns ------- r_k2 : float kappa : float See also -------- latticegeneration.generate_ks """ ret...
def filter_captions(images_with_sd): """Remove images that already have captions from recommendations.""" recs = {} for i in images_with_sd: if images_with_sd[i]['sd'] != 'exists': recs[i] = images_with_sd[i] return recs
def getmaxbyindex(inputlist,indexlist): """can get PIF calcs using flox data and crossvals note that cross ref of indexlist with Ti vs Te timestamps is needed for segregation of the data """ maxbyindexlist=[max(inputlist[indexlist[i]:indexlist[i+1]]) for i in range(len(indexlist)-1)] ...
def extract_token_nested_fields(target_obj: dict): """ Extract nested objects from the token graphql query """ new_dict = {} for key in target_obj.keys(): if key in ["event", "owner"]: for nested_key in target_obj[key].keys(): new_dict[f"{key}_{nested_key}"] = tar...
def projective(nodes): """Identifies if a tree is non-projective or not.""" for leaf1 in nodes: v1,v2 = sorted([int(leaf1.id), int(leaf1.parent)]) for leaf2 in nodes: v3, v4 = sorted([int(leaf2.id), int(leaf2.parent)]) if leaf1.id == leaf2.id:continue if (v1 <...
def euclidean_distance(x1, y1, x2, y2): """ Returns Euclidean distance between two points rounded to the nearest integer. """ return int(((x2-x1)**2 + (y2-y1)**2)**0.5 + 0.5)
def remove_white_space(input): """Remove all types of spaces from input""" input = input.replace(u"\xa0", u" ") # remove space # remove white spaces, new lines and tabs return " ".join(input.split())
def get_price(dict): """ This function is used to get the price of a manuscript. """ price = dict["price"] return price
def insertStyles(htmlCode, stylesheet, name): """We break up the HTML code into a list""" """and insert the styles.""" htmlList = htmlCode.split('\n') preamble = [ '<!DOCTYPE html>', '<html>', '<head>', '<link rel="stylesheet" href="' + stylesheet + '"/>', '<title>' + name + '</...
def damped_update(old, new, damping_onset, inertia): """ Update an old value given a new one, damping the change. The parameter inertia can be thought of loosely as the index of the change in a number of update iterations, where damping_onset specifies the damping-behavior. Both damping_onset and inert...
def get_padding(dimension_size, sectors): """ Get the padding at each side of the one dimensions of the image so the new image dimensions are divided evenly in the number of *sectors* specified. Parameters ---------- dimension_size : int Actual dimension size. sectors : int ...
def poly_lr(epoch, max_epochs, initial_lr, exponent=0.9): """Learning rate policy used in nnUNet.""" return initial_lr * (1 - epoch / max_epochs)**exponent
def wait(s: int=1) -> int: """ The purpose of this function is only to show that the miltithreading is supported by your API server ! :D Go to your terminal and write: ```bash for i in 1 2 3 4 5; do curl "http://localhost:8888/wait?s=5" & done ``` All the 5 should be...
def findNonFollowers(followers, followings): """ Find non followers by set difference :param followers: List of followers :param followings: List of followings :return: Set of non followers """ followerset = set(followers) followingset = set(followings) return followingset.difference...
def comparison_header(name_a, name_b, relative): """ Generates an appropriate header string based on `name_a` of `matrix_a` and `name_b` of `matrix_b`. """ header = f"||{name_a} - {name_b}||_F" if relative: header += f"/||{name_a}||_F" return header
def connack_string(state): """Return mqtt connection string.""" states = [ "Connection successful", "Connection refused - incorrect protocol version", "Connection refused - invalid client identifier", "Connection refused - server unavailable", "Connection refused - bad us...
def get_service_state_name(state): """ Translate a Windows service run state number to a friendly service run state name. """ return { 1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending',...
def divide(n, iterable): """Divide the elements from *iterable* into *n* parts as lists, maintaining order. Taken from more-itertools with minor modification.""" if n < 1: raise ValueError('n must be at least 1') try: iterable[:0] except TypeError: seq = tuple(iterable) e...
def json_ld_get_normalized_exchange_locations(data): """The exchanges location strings are not necessarily the same as those given in the process or the master metadata. Fix this inconsistency. This has to happen before we transform the input data from a dictionary to a list of activities, as it uses the ``loc...
def calc_number_on(x, y): """ >>> calc_number_on(1, 1) 1 >>> calc_number_on(2, 2) 5 >>> calc_number_on(6, 1) 16 >>> calc_number_on(1, 6) 21 >>> calc_number_on(4, 3) 18 >>> calc_number_on(3, 4) 19 """ return 1 + ((y - 1) * y + (x - 1) * x) // 2 + x * (y - 1)
def seasonFromDate(date): """ Returns the value of season from month and day data of the timestamp Parameters ---------- date : String Timestamp or date string in format of YYYY-MM-DD or followed by timestamp Returns ------- season : STRING Season corresponding to the d...
def is_in_list(list_one, list_two): """Check if any element of list_one is in list_two. Parameters ---------- list_one : list List containing a set of items. list_two : list List containing a set of items that may be in list_one. Returns ------- True or...
def fitness_func(individual): """Evaluate the fitness of an individual using hamming distance to [1,1, ... , 1]. returns value within [0,1] """ # ideal vector target = [1] * len(individual) # hamming distance to ideal vector distance = sum([...
def _get_project_service_account_mapping(registered_service_accounts): """ Return a dict with google projects as keys and a list of service accounts as values. Example: { 'project_a': [ 'service_acount_a@email.com', 'service_acount_b@email.com' ], 'pr...
def match(line,keyword): """If the first part of line (modulo blanks) matches keyword, returns the end of that line. Otherwise returns None""" line=line.lstrip() length=len(keyword) if line[:length] == keyword: return line[length:] else: return None
def minibatch_list(graph_list, max_batch_size=32): """ Return minibatch indices list so that each minibatch contains element with same seq length. """ indices = sorted(range(len(graph_list)), key=lambda k: graph_list[k].y.shape[0]) graph_list = list(graph_list) graph_list.sort(key=lambda x: ...
def parse_var_line(line): """ This regex works only if spaces are not used ^(\w*)=?*(['|"].*?['|"|])$ """ k = line.split("=", maxsplit=1)[0].strip() v = line.split("=", maxsplit=1)[1].replace('"', "").strip("\n").strip() return k, v
def source_desti_field_chk(base_field, base_field_type, field_name): """Prepare filters (kwargs{}) for django queryset where fields contain string are checked like exact | startswith | contains | endswith >>> source_desti_field_chk(21, '1', 'contact') {'contact__exact': 21} >>> source_de...
def strip_dep_version(dependency: str) -> str: """Strip a possible version suffix, e.g. types-six>=0.1.4 -> types-six.""" dep_version_pos = len(dependency) for pos, c in enumerate(dependency): if c in "=<>": dep_version_pos = pos break return dependency[:dep_version_pos]
def ncoeffs(degree): """ Calculate the number of coefficients in a bivarite polynomail. Parameters: * degree : int The degree of the polynomial Returns: * n : int The number of coefficients Examples: >>> ncoeffs(1) 3 >>> ncoeffs(2) 6 >>> ncoeffs(3) ...
def update_dataframe(df1, df2): """Update df1 with the contents of df2 This operation: - returns df1 if df2 is None, - adds new columns in df1 (initialized to 0), if columns in df2 exist that are not already in df1, - overwrites rows in df1 with rows from df2, or adds rows in df1 from ...
def tuple_converter(x): """Convert input to tuple of floats.""" return tuple(float(xx) for xx in x)
def make_index(datalist, key): """Returns dict indexed on the provided key field.""" idx = {} for row in datalist: if key in row: idx.setdefault(row[key], []) idx[row[key]].append(row) else: idx.setdefault('with_key_missing', []) idx['with_key_...
def seconds_to_min_sec(seconds): """ seconds_to_min_sec(int) --> int,int Converts seconds to minutes and seconds >>> seconds_to_min_sec(5) (0, 5) >>> seconds_to_min_sec(60) (1, 0) >>> seconds_to_min_sec(125) (2, 5) """ sec = seconds % 60 min = seconds / 60 return min...
def MsgToBinary(msg): """ Convert string to binary Args: msg ([str]): [str to convert] Returns: [binary]: [str converted] """ res = "".join(format(ord(i), "08b") for i in msg) return res
def to_unicode(text, encoding='utf8', errors='strict'): """Convert a string (bytestring in `encoding` or unicode), to unicode.""" if isinstance(text, str): return text return text.decode('utf8')
def calculate_driver_ability(calculated_data): """Calculates the relative driver ability for a team using driver zscores. calculated_data is the calculated data for the team being calculated.""" agility_weight = 0.65 speed_weight = 0.35 driver_ability = calculated_data['agilityZScore'] * agility_we...
def force_hashable(obj, recursive=True): """Force frozenset() command to freeze the order and contents of mutables and iterables like lists, dicts, generators Useful for memoization and constructing dicts or hashtables where keys must be immutable. FIXME: Rename function because "hashable" is misleading. ...
def get_custom_image_url(http_url, os_type, server_serial_number): """This function is to generate URL for the custom OS ISO file based on the type of OS and server serial number Arguments: http_url {string} -- HTTP server base URL os_type {string} -- Type of the op...
def print_scale(skill, points): """Return TeX lines for a skill scale.""" lines = ['\\cvskill{'] lines[0] += skill lines[0] += '}{' lines[0] += str(points) lines[0] += '}\n' return lines
def get_word_index(trans_data_pages): """ Builds dictionary containing unique words as keys and number of occurences of these words as values. @param trans_data_pages: List of pages. Each page is a list containing TransData objects for each word. @return: Dictionary of format {'word' => occurences of '...
def get_underlying_type_name(parameter_type: str) -> str: """Get the underlying type name of the given type. Strip away information from type name like brackets for arrays, leading "struct ", etc. leaving just the underlying type name. """ return parameter_type.replace("struct ", "").replace("[]", ...
def format_indent_line(items, spaces, indent, backslash, is_last): """Returns elements separated by commas. The line can be indented. This function is for internal use and is not available in templates. :param list items: a list of items. :param int spaces: indentation spaces :param bool indent: in...
def constrain_to_range(s, min_val, max_val): """ Make sure that a value lies in the given (closed) range. :param s: Value to check. :param min_val: Lower boundary of the interval. :param max_val: Upper boundary of the interval. :return: Point closest to the input value which lies in the given r...
def flatten_stmts(stmts): """Return the full set of unique stms in a pre-assembled stmt graph. The flattened list of of statements returned by this function can be compared to the original set of unique statements to make sure no statements have been lost during the preassembly process. Parameters...
def parse_content_type_header(content_type): """ Parse and normalize request content type and return a tuple with the content type and the options. :rype: ``tuple`` """ if ';' in content_type: split = content_type.split(';') media = split[0] options = {} for pai...
def process_list(string): """ Create list from string with items separated by commas Helper for get_sorted_emails. """ # Remove all spaces no_spaces = "".join(string.split()) # Split at commas split_lst = no_spaces.split(",") # Remove empty strings and return return list(filte...
def concatenate(*a, **kw): """ helper function to concatenate all arguments with added (optional) newlines """ newline = kw.get('newline', False) string = '' for item in a: if newline: string += item + '\n' else: string += item return string
def time_representation(hours, minutes, seconds): """Conversion of readable to internal time representation. Parameters ---------- hours : float or array, shape (n_steps,) Hours since start minutes : float or array, shape (n_steps,) Minutes since start seconds : float or array...
def admin2_it(x, county_d): """Add admin2 (County Name for US)""" if x[1] == "United States": return county_d.get(x[0], "None") else: return "None"
def have_mpeg_extension(l): """Check if .mpeg extension is present""" if ".mpeg" in str(l): return 1 else: return 0
def find(function, iterable): """ Returns the first item in the list for which function(item) is True, None otherwise. """ for x in iterable: if function(x) == True: return x
def wxToGtkLabel(s): """ The message catalog for internationalization should only contain labels with wx style ('&' to tag shortcut character) """ return s.replace("&", "_")
def physical_products(productname): """Return the matching product resource""" physical_products = {} physical_products['name'] = productname physical_products['price'] = 0.5 return str(physical_products)
def multi_ws_to_single_ws(txt: str) -> str: """Convert multiple whitespaces to single space.""" return ' '.join(txt.split())
def getPosUntilRoot(object): """ Go through the hierarchy of the object until reaching the top level, increment the position to get the transformation due to parents. @type object: hostObject @param object: the object @rtype: list @return: the cumulative translation along the ...
def depth_estimation(x_left, x_right, f=33.4, d=114): """ Calculation the people depth :param x_left: left image x point :param x_right: right image x point :param f: focal length :param d: two camera distance :return: """ depth = abs(f * d / ((x_left - x_right) / 72 * 2.54)) / 100 #...
def hexa_to_rgb(color): """Convert hexadecimal color to RGB.""" r = int(color[1:3], 16) g = int(color[3:5], 16) b = int(color[5:7], 16) if len(color) == 7: return r, g, b elif len(color) == 9: return r, g, b, int(color[7:9], 16) else: raise ValueError("Invalid hexadec...
def removeDuplicates(seq): """ Order preserving duplicate removal """ checked = [] for entry in seq: if entry not in checked: checked.append(entry) return checked
def integer(number): """Returns an integer whatever the input value If the input is invalid returns 0 >>> integer("tonsils") 0 >>> integer(4.5) 4 >>> integer(32) 32 >>> integer("-15.1") -15 >>> integer(22.499999999) 22 >>> integer("22.5") 22 >>> integer(...
def _any_is_float(data): """ are any of the items floats """ for item in data: if isinstance(item, float): return True return False
def manh(x, y): """Compute Manhattan distance.""" return sum(abs(i - j) for i, j in zip(x, y))
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if len(ints) == 0: return None max_val = - float("inf") min_val = float("inf") for int in ints: if int >...
def resolve_deps(graph): """ Resolve dependency for a dict-based graph using recursion. Parameters ---------- graph : dict Each key is a variable name, and the corresponding value is the list of variables the key depends on. Returns ------- list A list of initia...
def is_leap_year(year: int) -> bool: """Checks if a given year is, was, or will be a leap year. Args: year: An integer representing a common-era year, e.g. 1984 CE. Returns: ``True`` if ``year`` is a leap year, meaning it contains one additional day in February, for a total of 366 ...