content
stringlengths
42
6.51k
def yellow_bold(payload): """ Format payload as yellow. """ return '\x1b[33;1m{0}\x1b[39;22m'.format(payload)
def invert_board_state(board_state): """Returns the board state inverted, so all 1 are replaced with -1 and visa-versa Args: board_state (tuple of tuple of ints): The board we want to invert Returns: (tuple of tuple of ints) The board state for the other player """ return tuple(tuple...
def parse_submit_output_for_job_id( output ): """ output should contain something like the following Submitted batch job 291041 """ jobid = None L1 = output.strip().split( "Submitted batch job", 1 ) if len(L1) == 2: L2 = L1[1].strip().split() if len(L2) > 0 and L2[0]: ...
def smooth(values, factor): """smooth non zero values (by factor) towards 0th element.""" new_values = [0] * len(values) for i in reversed(range(len(values))): if values[i] != 0: smoothed_value = values[i] j = 0 while True: if i-j < 0: break new_values[i-j] += smoothed_value ...
def config_items(section_name): """ Return list of item expected for a specific section. """ if section_name == 'Demo': return ['username'] return []
def initialize_counts_sampling_optimization(shots, hex_counts=True): """Sampling optimization counts""" if hex_counts: return [{'0x0': shots/2, '0x2': shots/2}] else: return [{'0x00': shots/2, '0x10': shots/2}]
def is_callable(v): """Returns True if v has __call__.""" try: return hasattr(v, "__call__") except Exception: return False
def no_null(x): """Ensure text does not contain a null character.""" return "\0" not in x
def positive_negative(dic, va): """ :param dic: dict :param va: value of the key :return: a list of keys with the value choosen """ l=[] for key in dic.keys(): val = dic[key] if val==va: l.append(key) return l
def is_int(value): """Check if given value is integer Copied from dcase_util/utils.py Parameters ---------- value : variable Returns ------- bool """ if value is not None: try: int(value) return True except ValueError: ret...
def is_leap_year(year): """returns true if Year is Leap Year""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def mean(my_list): """!Calculate the mean of the list. @param my_list: list of python objects that can be summed (float, int, etc.) @return: Mean of my_list (float) """ return sum(my_list) / len(my_list)
def find_equivalent(elem, find_list): """Returns the element from the list that is equal to the one passed in. For remove operations and what not, the exact object may need to be provided. This method will find the functionally equivalent element from the list. :param elem: The original element. ...
def db2mag(xdb): """Convert decibels (dB) to magnitude .. doctest:: >>> from spectrum import db2mag >>> db2mag(-20) 0.1 .. seealso:: :func:`pow2db` """ return 10.**(xdb/20.)
def lorentzian(x, p): """ Generalized Lorentzian function. (**WARNING**: for n != 2 the function is no more normalized!) Args: x: (non-zero) frequencies. p[0]: x0 = peak central frequency. p[1]: gamma = FWHM of the peak. p[2]: value of the peak at x = x0. ...
def run_side_effect(*args, **kwargs): """ side_effect for run() with example output for irods commands. """ # Session.run() returns (stdout, stderr) if args[0] == 'ils': return ( 'wwwHydroProx 0 hydroshareReplResc 7 2018-08-06.18:05 & tmpBktX04', '')
def get_color_name_RGB(r, g, b): """ get color name based on RGB distance RGB values of colors are acquired from: https://among-us.fandom.com/wiki/Category:Colors :param r: red :param g: green :param b: blue :return: The color closest to the given RGB values based on RGB distance ""...
def quadratic_session_score(i, length): """Function penalizes old elements in sequence more than the new events. The past elements have much smaller weights than the new ones. It follows a quadratic function. Parameters ---------- i : int Element position, i+1 must be less than length. ...
def camel_to_snake(string): """Convert camel to snake style. :param string: camel string :type string: str :return: snake style string :rtype: str """ string = "".join([(x.replace(x, '_' + x.lower() if x.isupper() else x)) for x in list(string)]) if string.startswi...
def get_headers(data): """Loop through the data and collect any headers. :param data list[dict]: :rtype: set[str] :returns: set of headers """ return {k for row in data for k, _ in row.iteritems()} if data is not None else None
def get_playing_player(players_count, key): """ Return the player ID corresponding to the used key. """ if players_count == 3: one = {"a", "z", "q"} two = {"o", "p", "m", "l"} three = {"x", "c", "v"} if key in one: return 1 elif key in two: ...
def decode_punycode(punycode_domain): """ decodes a punycode 'xn--' domain into regular utf-8 returns u """ try: domain = punycode_domain.encode('utf-8').decode('idna') except UnicodeError as e: domain = e.args[2].decode('utf-8') return domain
def comp(current_command): """Return comp Mnemonic of current C-Command""" #remove the dest part of command if exists (part before =) command_without_dest = current_command.split("=")[-1] #remove jump part of command if exists (part after ;) comp_command = command_without_dest.split(";")[0] return comp_command
def _pack_64b_int_arg(arg): """Helper function to pack a 64-bit integer argument.""" return ((arg >> 56) & 0xff), ((arg >> 48) & 0xff), ((arg >> 40) & 0xff), ((arg >> 32) & 0xff), \ ((arg >> 24) & 0xff), ((arg >> 16) & 0xff), ((arg >> 8) & 0xff), (arg & 0xff)
def Crossing1Files(fileName, ind=None): """ Takes a filename of the structure used for the Crossing 1 videos - YYYMMDD_hhmmss-suffix.mkv Retrieves the datetime of the start of the video Input: fileName: Name of the file ind: Indicator of whether it is the left or right crop of the video...
def multi_total_clicks_reward(all_responses): """Calculates the total number of clicks from a list of responses. Args: responses: A list of IEResponse objects Returns: reward: A float representing the total clicks from the responses """ reward = 0.0 for responses in all_responses : for r in res...
def _hex(list=None): """Format the return value in list into hex.""" list = list or [] if list: list.reverse() return int(''.join(list), 16) return 0
def minmax(vec_x, vec_y): """Calculates the minmax similarity of two vectors. Calculates minmax similarity of two vectors vec_x and vec_y. Formula: minmax(X, Y) = sum(min(Xi, Yi))/sum(max(Xi, Yi)) This baseline method will be used for further evaluation. """ minsum = 0 maxsum = 0 for ...
def hourglassSum(arr): """ -9 -9 -9 1 1 1 0 -9 0 4 3 2 -9 -9 -9 1 2 3 0 0 8 6 6 0 0 0 0 -2 0 0 0 0 1 2 4 0 """ hourglass = [] for row in range(4): for column in range(4): hourglass_arr = arr[row][column:column + 3] + arr[ row + 1][column:column + 3] + a...
def set_pk_params(data: dict, list_table_exceptions: list, list_col_exceptions: list): """ "name": "", "description": "", "columns": [...], "partitions": [...], "measures": [...], "annotations": [...] """ print() print(79 * '*') print(f"Configuring parameters in {(data['model...
def get_reversed_board(board: list): """ Transpose a given board, so that the columns become rows and rows become columns. >>> get_reversed_board(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', ... '*2*1***']) ['*44****', '*125342', '*23451*', '2413251', '154213*', '*35142*', '**...
def sql_like_decorate( pattern ): """ wrap the given string with '%' if it is not already there """ if '%' not in pattern: pattern = '%' + pattern + '%' return pattern
def _generateOptionsData(finalState, students, numberOptions, mode): """"Function to generate dictionary with the final results""" results = [] if mode: for studentId in range(len(students)): studentAverageMark = students[studentId]['averageMark'] optionsForStudent = [] ...
def get_player_colors(white_id, user_id): """Returns a tuple of colors in the order (user, opponent).""" return ('White', 'black') if white_id == user_id else ('Black', 'white')
def parse_dependency_line(line): """ >>> parse_dependency_line("ABC==EFG") ('ABC', '==EFG') >>> parse_dependency_line("ABC>=EFG") ('ABC', '>=EFG') >>> parse_dependency_line("ABC<=EFG") ('ABC', '<=EFG') >>> parse_dependency_line("ABC~=EFG") ('ABC', '~=EFG') >>> parse_dependenc...
def split_header(task, lines): """ Returns if the task file has a header or not. Only for GLUE tasks. """ if task in ["CoLA"]: return [], lines elif task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI"]: return lines[0:1], lines[1:] else: raise ...
def get_total_price(receipt): """ given receipt of products outputs sum of their prices """ return sum(price for name, price in receipt)
def LoadBins( fname ): """Read in bin information from summary file (written by analsim)""" stat_start = {} stat_end = {} stat_nbins = {} with open( fname ) as inf: firstline = inf.readline().rstrip() parts = firstline.split(' ') header = inf.readline() ...
def single_cond_prob_to_str(grid_idx, val, num_indices = 6): """Generate the string representing the probability: Pr(o_i = val) ex: For Pr(o_2 = 1), we'd have the string '21' NB we're 1-indexing here """ assert grid_idx >= 1 and grid_idx <= num_indices return str(grid_idx) + st...
def is_win(board, symbol): """ This way of calculating wins is purely so it looks nice. It is not fast and could be done faster using less python hacky methods and such. But it looks nice!""" matches = [ # Win checks in tic tac toe board[0:3], # [0 1 2] board[3:6], # [3 4 5] board[6:9], ...
def __as_key(k1, k2): """ Creates a key (tuple) out of the two specified. The key is always ordered. If k2 < k1, then (k2, k1), else, (k1, k2). :param k1: Key (string). :param k2: Key (string). :return: (k1, k2) or (k2, k1). """ keys = sorted([k1, k2]) return keys[0], keys[1]
def sort_orders_by_product(orders): """Sort Orders by their Products.""" sorted_orders = {} for order in orders: if order.product in sorted_orders.keys(): sorted_orders[order.product].append(order) else: sorted_orders[order.product] = [order] return sorted_orders
def strip_digits(text): """Removes digits (number) charaters. """ return "".join(c for c in text if not c.isdigit())
def minutes_to_military(minutes): """converts no.of minutes since day began to 'military format'(ex:'1243')""" h = minutes / 60 m = minutes % 60 tmp = "%2d%2d" % (h, m) tmp = tmp.replace(" ","0") return tmp
def find_digits_cast(n): """I hope this wins, it makes me happy.""" return [int(c) for c in str(n)]
def _get_class_by_name(kls): """Imports and returns a class reference for the full module name specified in regular Python import format""" # The following code taken from http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname parts = kls.split('.') module = "."....
def get_max_widths(lines): """find the max width of a list""" max_width = len(lines[0]) for line in lines: if len(line) > max_width: max_width = len(line) return max_width
def get_unique_list_of_option_args(all_args): """ Returns a unique list of option args. """ ret = [] ret_names = [] for arg in all_args: if arg['name'] not in ret_names: ret.append(arg) ret_names.append(arg['name']) return ret
def str2bits(str_in): """ Convert string input to bits. :param str_in: input string :return: bits array """ result = [] for c in str_in: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return result
def AmOppCr(_cmp, e87482, e87487, e87492, e87497): """American Opportunity Credit 2009+; Form 8863""" """ This function calculates American Opportunity Credit for up to four eligible students """ # Expense should not exceed the cap of $4000. if _cmp == 1: c87482 = max(0.,...
def parse_message_id(value, **kwargs): """Parse a Message-ID: header.""" return value.strip('\n')
def create_chunks(cases, n): """ Create n chunks from a list """ x = [cases[i : i + n] for i in range(0, len(cases), n)] return x
def no_interference(value): """ to avoir sql injection """ value = str(value) return "'" not in value and '"' not in value
def are_points_with_errors_adjacent(points, errs): """Returns whether a given set of points are adjacent when taking their errors into account.""" for i in range(len(points) - 1): point = points[i] err_right = errs[0][i] next_point = points[i + 1] next_err_left = errs[1][i + 1] ...
def _toggle_selected(selected_data, value): """Add or remove value from the selected data set. Parameters ---------- selected_data : set Set of selected data points to be modified. value : int Index of point to add or remove from selected data set. Returns ------- set ...
def in_or_none(x, L): """Check if item is in list of list is None.""" return (L is None) or (x in L)
def generate_comment(inst: str, comments: dict, args: list): """ Generate comment after the instruction. """ if inst not in comments: return "\n" return "; " + comments[inst] + " " + str(args).replace("[", "").replace("]", "") + "\n"
def changeByOne(coords): """ Changes coordinates by 1 on the x axis (to move the plane forward 1) """ for i in range(0, len(coords)): coords[i][0] = coords[i][0] + 1 return coords
def reduce_inter(args, gap_size=-1): """ gap_size : :obj:`int` Gaps of this size between adjacent peptides is not considered to overlap. A value of -1 means that peptides with exactly zero overlap are separated. With gap_size=0 peptides with exactly zero overlap are not separated, ...
def is_empty_macro(path): """Returns True if the given macro file only has empty lines and/or Attribute settings.""" with open(path, "rb") as fp: for line in fp: # if the line is empty keep moving if line.strip() == b"": continue # or if it starts wit...
def compare_extension(filename: str, expected_extension: str): """ Compare the extension of the given file with the expected extension """ return filename.endswith(expected_extension)
def _num_frame_valid(nsp_src, nsp_win, len_hop): """Computes the number of frames with 'valid' setting""" return (nsp_src - (nsp_win - len_hop)) // len_hop
def _filter_by_list(data, wordlist): """Helper for loading larger dictionary-based resources: memory will be freed by only keeping the words relevant for the given session""" new_data = {} for i in wordlist: if i in data: new_data[i] = data[i] return new_data
def _make_pretty_examples(examples): """ Makes the examples description pretty and returns a formatted string if `examples` starts with the example prefix. Otherwise, returns None. Expected input: Examples: > SELECT ...; ... > SELECT ...; ... Expe...
def getalphabet(a): """ Given a string, returns the sorted alphabet in the form of a string """ S="".join(sorted( list( set( list(a) ) ) ) ) return S
def calc_num_weights(num_inputs, layer_sizes, num_outputs): """ calculate total number of weights (and biases), i.e. the dimensionality of the inference problem """ #no hidden layers if len(layer_sizes) == 0: return (num_inputs + 1) * num_outputs n = (num_inputs + 1) * layer_sizes[0] for i in range(1, len(la...
def i_growth(i_simple,g): """ variables: g=rate of growth """ return (1+i_simple)/(1+g)-1
def fitparams_for_update(fitparams): """ Extracts a dictionary of fitparameters from modelmiezelb.io.ContrastData.fitparams for updating e.g. a sqe model via modelmiezelb.sqe_model.SqE.update_params Parameters ---------- fitparams : modelmiezelb.io.ContrastData.fitparam Return -...
def is_dict(val: dict) -> dict: """Assertion for a dictionary type value. Args: val: check value (expect dict type) Returns: Same value to input. Raises: Assertion Error: if a value not match a dict type. """ assert isinstance(val, dict), f"Must be a Dioctonary type va...
def compute_time_serie(time_serie, operation): """Given a time series in the form [(x, 10), (y, 20), (z, 15)] and an operation of the form lambda v1: v1 * 2 return [(x, 20), (y, 40), (z, 30)] """ return [tuple((pair[0], operation(pair[1]))) for pair in time_seri...
def nr_mins_to_formatted(duration): """Take a duration in minutes, and return an HH:MM formatted string.""" hours = int(duration / 60) minutes = duration % 60 return "%02d:%02d" % (hours, minutes)
def getESELSeverity(esel): """ Finds the severity type in an eSEL from the User Header section. @param esel - the eSEL data @return severity - e.g. 'Critical' """ # everything but 1 and 2 are Critical # '1': 'recovered', # '2': 'predictive', # '4': 'unrecoverable', #...
def connect_char(words): # pragma: no cover """connect and switch to list type""" result = [] buffer = "" for w in words: w = w.strip() if len(w) > 1: if len(buffer) > 0: result.append(buffer) buffer = "" result.append(w) ...
def reorder_paths(paths, order_strs): """reorder a list of paths, using a list of strings. Returns a new list of the paths, re-ordered so that the first path will have the first string in it, the second path will have the second string in it, and so on. Parameters ---------- paths : list ...
def parse_num(maybe_num): """parses number path suffixes, returns -1 on error""" try: return int(maybe_num) except ValueError: return -1
def seconds_into_day(time): """Takes a time in fractional days and returns number of seconds since the start of the current day. Parameters ---------- time: float The time as a float. Returns ------- int The day's duration in seconds. """ return(int(round(86400....
def _merge_closest_intervals(intervals): """ Get the closest interval and merge those two """ diff = [y[0]-x[1] for x, y in zip(intervals, intervals[1:])] argmin = diff.index(min(diff)) new_interval = [intervals[argmin][0], intervals[argmin+1][1]] return intervals[:argmin] + [new_interval] + interv...
def create_delete_marker_msg(id): """ Creates a delete marker message. Marker with the given id will be delete, -1 deletes all markers Args: id (int): Identifier of the marker Returns: dict: JSON message to be emitted as socketio event """ return...
def largest_subarray_sum(numbers): """ Finds the largest subarray sum from a list of integers. It uses Kadane's algorithm to do this. Same as max sum subarray Parameters ---------- numbers : list a list of integers Returns ------- int the largest subarray sum ...
def _solve_method_1(a): """Literally did this first and was surprised when it didn't work on any other test case, and then found out about the problem inputs.""" first_d = a[0][0] + a[1][1] + a[2][2] second_d = a[0][2] + a[1][1] + a[2][0] return abs(first_d - second_d)
def claims_match(value, claimspec): """ Implement matching according to section 5.5.1 of http://openid.net/specs/openid-connect-core-1_0.html. The lack of value is not checked here. Also the text doesn't prohibit having both 'value' and 'values'. :param value: single value or list of values :p...
def setup(query): """setup is successful if an empty list is returned. Use this function if you need the user to provide you data """ results = [] return results
def make_weights_map(jax_names): """Create a dictionary mapping jax variable name to keras variable name.""" results = {} for name in jax_names: # Handle head: if name.startswith("head"): results.update({name: f"{name}:0"}) # Handle pre-head layer norm: if name....
def _is_s3(string): """Checks if the given string is a s3 path. Returns a boolean.""" return "s3://" in string
def get_external_internal_ip(project_id, ip_name, external_ip_name, internal_ip_name, region, subnet): """ Generate an external IP resource. """ resource = { ...
def print_log(title, values): """Print Formating for log files""" stri = "="*40 + "\n" + title + "\n" + "="*40 stri += "\n" + values return stri
def solve_captcha(captcha): """ Method for trying to solve the captcha. """ solution = 0 prev_digit = captcha[-1] for digit in captcha: if prev_digit == digit: solution += int(digit) prev_digit = digit return solution
def iterator_to_list(iterator): """ Transform the input iterator into a list. :param iterator: :iterator type: """ liste = [elem for elem in iterator] return liste
def _to_range(row, col, sheet=None): """returns an Excel range string, e.g. 0, 0 => A1""" cell = "" while col >= 26: cell = "%s%s" % (chr(ord("A") + (col % 26)), cell) col = (col // 26) - 1 cell = "%s%s" % (chr(ord("A") + (col % 26)), cell) cell += "%d" % (row + 1) if sheet is n...
def getStructName(sig): """Get the class name from a signature or '', if signature is not a class.""" sig = sig.strip() #pos1 = sig.rfind(' ') #if pos1 < 0: return "" #while (pos1 > 0) and (sig[pos1] == ' '): pos1 -= 1 #if ((pos1 >= 5) and (sig[pos1-5:pos1+1] == 'struct')) or ((pos1 >...
def posixToNtSlashes(filepath): """ Replaces all occurrences of Posix slashes (/) in provided filepath with NT ones (\) >>> posixToNtSlashes('C:/Windows') 'C:\\\\Windows' """ return filepath.replace('/', '\\') if filepath else filepath
def findFirst(arr, a): """ Unlike binary search, cannot return in the loop. The purpose of while loop is to narrow down the search range. Can combine two conditions: `arr[m] >= a` """ if not arr: return -1 l, r = 0, len(arr) - 1 # exit loop when l + 1 == r, i.e. consecutive while l + 1 < r: # av...
def get_rows(rows, header): """ takes the rows and header and returns a dict for each row with { key : <td> } """ header = [x.text_content().strip() for x in header] keyed_rows = [] for r in rows: dict_row = {} for k,v in zip(header, r.xpath('td')): dict_row.update({k...
def sum_tail_recursion(ls): """ :type ls: List[int] :rtype: int, the sum of the input list. """ def helper(ls, acc): if len(ls) == 0: return acc # this is a tail recursion because the final instruction is a recursive call. return helper(ls[1:], ls[0] + acc) ...
def pagination_range(obj, current=1, limit=10): """ Used with pagination page_range object when you have a lot of pages > obj = range(100) > pagination_limit(obj, 1) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > pagination_limit(obj, 6) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > pagination_limit(obj, 7) ...
def prepare_params_dict(urlparams: dict) -> dict: """Prepare dictionary of URL parameter.""" if isinstance(urlparams, dict): params = urlparams else: params = {} return params
def compare_json_data(source_data_a, source_data_b): """ Compares specified JSON structures by structure and contents, cf. http://bit.ly/2A2yMTA. """ def compare(data_a, data_b): # comparing lists if (type(data_a) is list): # is [data_b] a list and of same length as [data...
def strip_comments(l: str) -> str: """ Strip any ``#`` comments from a line. :param str l: A string line, which may contain ``#`` comments :return str clean_line: The line ``l`` - stripped of any comments and excess whitespace. """ return l.split('#', 1)[0].strip()
def _lang2suffix(lang): """ Convert a language name to a suffix. When "lang" is empty or None C is assumed. Returns a tuple (lang, suffix, None) when it works. For an unrecognized language returns (None, None, msg). Where: - lang = the unified language name - suffix = the suffix, ...
def calc_alpha(alpha0, alpha1, d): """alpha0+alpha1/d """ return alpha0+alpha1/d