content
stringlengths
42
6.51k
def calculate_q_debye_linear(eps_fluid, lambda_d, zeta): """ Calculate the charge accumulated in the Debye layer (Adjari, 2006) units: Coulombs Notes: """ q = -eps_fluid * zeta / lambda_d return q
def sqrt(x): """ Calculate the square root of argument x. """ # Check that x is positive if x < 0: print("Error: Negative value supplied") return -1 else: print ("The number is positive") #Initial guess for the sqaure root z = x / 2.0 counter = 1 #Continuously improve the guess while abs(x - (z*z)) > .0000001: z -= (z*z - x) / (2*z) counter += 1 print(z) # print(counter) # return counter return z
def missing_num(nums): """ :param nums: array :return: missing number """ left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == mid: left = mid + 1 else: if nums[mid - 1] == mid - 1: return mid right = mid - 1 return left
def has_won(board): """Checking if three of their marks in a horizontal, vertical, or diagonal row and return True, player winning marks (X or O), the number of full mark line (from 0 to 7) and a message that mark X or O won, otherwise return False, None, -1, None. Full mark lines: 0 - top horizontal, 1 - middle horizontal, 2 - bottom horizontal, 3 - left vertical, 4 - middle vertical, 5 - right vertical, 6 - left diagonal, 7 - right diagonal.""" lines = [[board[0][0], board[0][1], board[0][2]], [board[1][0], board[1][1], board[1][2]], [board[2][0], board[2][1], board[2][2]], [board[0][0], board[1][0], board[2][0]], [board[0][1], board[1][1], board[2][1]], [board[0][2], board[1][2], board[2][2]], [board[0][0], board[1][1], board[2][2]], [board[0][2], board[1][1], board[2][0]]] players = ["X", "O"] for player in players: line_no = 0 for line in lines: if line.count(player) == 3: message = '\033[36m' + f"The player \"{player}\" has won!!!" + '\033[0m' return True, player, line_no, message line_no += 1 return False, None, -1, None
def getSystemEventID(element): """Returns the systemEventID of a given event""" return element["systemEventID"]
def replace_value_with_key(s, replace_dict): """In string s values in the dict get replaced with their key""" for key in replace_dict: s = s.replace(replace_dict[key], key) return s
def get_max_draw_down(ts_vals): """ @summary Returns the max draw down of the returns. @param ts_vals: 1d numpy array or fund list @return Max draw down """ MDD = 0 DD = 0 peak = -99999 for value in ts_vals: if (value > peak): peak = value else: DD = (peak - value) / peak if (DD > MDD): MDD = DD return -1*MDD
def FormatKey(key): """Normalize a key by making sure it has a .html extension, and convert any '.'s to '_'s. """ if key.endswith('.html'): key = key[:-5] safe_key = key.replace('.', '_') return safe_key + '.html'
def rec_pow(a, b): """Compute a**b recursively""" if b == 0: return 1 if b == 1: return a return (rec_pow(a,b//2)**2) * (a if b % 2 else 1)
def convert_to_unicode(input_text, encoding="utf-8"): """Converts intput_text to Unicode. Input must be utf-8.""" if isinstance(input_text, str): return input_text elif isinstance(input_text, bytes): return input_text.decode(encoding, "ignore")
def imatch(a: str, b: str) -> bool: """ return True if the given strings are identical (without regard to case) """ return a.lower() == b.lower()
def acc(gt, est): """ Calculate the accuracy of (agreement between) two interger valued list. """ if len(gt) < 1: return 1 else: return sum([(g == e) for (g, e) in zip(gt, est)]) / len(gt)
def convex_hull(points): """Computes the convex hull of a set of 2D points. Implements `Andrew's monotone chain algorithm <http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_. The algorithm has O(n log n) complexity. Credit: `<http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain>`_ Parameters ---------- points : list of tuples An iterable sequence of (x, y) pairs representing the points. Returns ------- Output : list A list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest coordinates. """ # Sort the points lexicographically (tuples are compared lexicographically). # Remove duplicates to detect the case we have just one unique point. points = sorted(set(points)) # Boring case: no points or a single point, possibly repeated multiple times. if len(points) <= 1: return points # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product. # Returns a positive value, if OAB makes a counter-clockwise turn, # negative for clockwise turn, and zero if the points are collinear. def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) # Build lower hull lower = [] for p in points: while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0: lower.pop() lower.append(p) # Build upper hull upper = [] for p in reversed(points): while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0: upper.pop() upper.append(p) # Concatenation of the lower and upper hulls gives the convex hull. # Last point of each list is omitted because it is repeated at the beginning of the other list. return lower[:-1] + upper
def get_freq(n=-21): """ Generate a frequency from an 'n'. Based on an equation: https://www.intmath.com/trigonometric-graphs/music.php """ return 440.0 * 2.0 ** (n / 12.0)
def p(x, threshold=0.5): """Predicts whether a probability falls into class 1. :param x: Probability that example belongs to class 1. :type x: obj :param threshold: point above which a probability is deemed of class 1. :type threshold: float :returns: Binary value to denote class 1 or 0 :rtype: int """ prediction = None if x >= threshold: prediction = 1 else: prediction = 0 return prediction
def _join(c): """Return `str` with one element of `c` per line.""" return '\n'.join(str(x) for x in c)
def unpack(value, number=2, default=None): """Unpack given `value` (item/tuple/list) to `number` of elements. Elements from `value` goes first, then the rest is set to `default`.""" if not isinstance(value, list): if isinstance(value, tuple): value = list(value) else: value = [value] assert len(value) <= number for _ in range(number - len(value)): value.append(default) return value
def _format_explanation(explanation): """This formats an explanation Normally all embedded newlines are escaped, however there are three exceptions: \n{, \n} and \n~. The first two are intended cover nested explanations, see function and attribute explanations for examples (.visit_Call(), visit_Attribute()). The last one is for when one explanation needs to span multiple lines, e.g. when displaying diffs. """ raw_lines = (explanation or '').split('\n') # escape newlines not followed by {, } and ~ lines = [raw_lines[0]] for l in raw_lines[1:]: if l.startswith('{') or l.startswith('}') or l.startswith('~'): lines.append(l) else: lines[-1] += '\\n' + l result = lines[:1] stack = [0] stackcnt = [0] for line in lines[1:]: if line.startswith('{'): if stackcnt[-1]: s = 'and ' else: s = 'where ' stack.append(len(result)) stackcnt[-1] += 1 stackcnt.append(0) result.append(' +' + ' '*(len(stack)-1) + s + line[1:]) elif line.startswith('}'): assert line.startswith('}') stack.pop() stackcnt.pop() result[stack[-1]] += line[1:] else: assert line.startswith('~') result.append(' '*len(stack) + line[1:]) assert len(stack) == 1 return '\n'.join(result)
def distance(point1, point2): """ Returns the Euclidean distance of two points in the Cartesian Plane. >>> distance([3,4],[0,0]) 5.0 >>> distance([3,6],[10,6]) 7.0 """ return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)**0.5
def convert_secret_hex_to_bytes(secret): """ Convert a string secret to bytes. """ return int(secret, 16).to_bytes(32, byteorder="big")
def compute_rgb(data, var): """a wacky way to compute three different color ranges""" bcol = {'ch4_gwp': 20, 'n2o_gwp': 60}.get(var, 100) return [[(255-bcol*2), 150 + 100*(1-d), bcol*2.5] for d in data]
def max_path_sum_in_triangle(triangle): """ Finds the maximum sum path in a triangle(tree) and returns it :param triangle: :return: maximum sum path in the given tree :rtype: int """ length = len(triangle) for _ in range(length - 1): a = triangle[-1] b = triangle[-2] for y in range(len(b)): b[y] += max(a[y], a[y + 1]) triangle.pop(-1) triangle[-1] = b return triangle[0][0]
def get_coord_limits(coord): """get cooordinate limits""" lower_limit = float('.'.join([str(coord).split('.')[0], str(coord).split('.')[1][:2]])) if lower_limit > 0: upper_limit = lower_limit + 0.01 else: tmp = lower_limit - 0.01 upper_limit = lower_limit lower_limit = tmp return lower_limit, upper_limit
def det_prob_query(p1: float, k: int, l: int) -> float: """ Compute the probability of finding point q < cR Parameters ---------- p1 P_1 as determined with Union[floky.stats.collision_prob_cosine, floky.stats.collision_prob_l2] k Number of hash digits. l Number of hash tables. Returns ------- Pq Prob. of finding point q < cR """ return 1.0 - (1.0 - p1 ** k) ** l
def match_module_end(names): """ """ if len(names) < 3: return "" if names[0]=="END" and names[1]=="MODULE": return names[2] return ""
def hsv_to_rgb(h, s, v): """Taken from https://github.com/python/cpython/blob/3.7/Lib/colorsys.py and tweaked a bit""" h = (h % 360) / 360 if s == 0.0: return int(v * 255), int(v * 255), int(v * 255) i = int(h*6.0) f = (h*6.0) - i p = v*(1.0 - s) q = v*(1.0 - s*f) t = v*(1.0 - s*(1.0-f)) i = i%6 if i == 0: return int(v * 255), int(t * 255), int(p * 255) if i == 1: return int(q * 255), int(v * 255), int(p * 255) if i == 2: return int(p * 255), int(v * 255), int(t * 255) if i == 3: return int(p * 255), int(q * 255), int(v * 255) if i == 4: return int(t * 255), int(p * 255), int(v * 255) if i == 5: return int(v * 255), int(p * 255), int(q * 255) # Cannot get here
def update(x, *maps, **entries): """Update a dict or an object with slots according to entries. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20) """ for m in maps: if isinstance(m, dict): entries.update(m) else: entries.update(m.__dict__) if isinstance(x, dict): x.update(entries) else: x.__dict__.update(entries) return x
def chan_list_to_mask(chan_list): # type: (list[int]) -> int """ Function taken from mcc118 example github. https://github.com/mccdaq/daqhats/tree/master/examples/python/mcc118 This function returns an integer representing a channel mask to be used with the MCC daqhats library with all bit positions defined in the provided list of channels to a logic 1 and all other bit positions set to a logic 0. Args: chan_list (int): A list of channel numbers. Returns: int: A channel mask of all channels defined in chan_list. """ chan_mask = 0 for chan in chan_list: chan_mask |= 0x01 << chan return chan_mask
def auto_int(x): """ Convert a string (either decimal number or hex number) into an integer. """ # remove leading zeros as this doesn't work with int(), issue 20 # but only for integers (023), not for hex (0x23) if not ('x' in x): x = x.lstrip('0') return int(x, 0)
def reorder_log_file(logs: list) -> list: """Reorder a list of logs""" digits = [] letters = [] # Classifiy digits and letters. for log in logs: if log.split()[1].isdigit(): digits.append(log) else: letters.append(log) # Sort the letters letters.sort(key=lambda x: (x.split()[1], x.split()[0])) return letters + digits
def numJewelsInStones(jewels, stones): """ :type jewels: str :type stones: str :rtype: int """ count = 0 for j in jewels: count += stones.count(j) return count
def formatExc (exc): """ format the exception for printing ARGUMENTS: ---------- exc: Exception RETURN: ------ String: Either the text desription of the Exception, or The <Non-recognized Exception> string. """ try: return f"<{exc.__class__.__name__}>: {exc}" except: return '<Non-recognized Exception>'
def pt_display_label(lower_label: str = "T", upper_label: str = "") -> str: """ Generate a pt display label without the "$". Args: lower_label: Subscript label for pT. Default: "T" upper_label: Superscript label for pT. Default: "" Returns: Properly formatted pt string. """ return r"p_{\text{%(lower_label)s}}^{\text{%(upper_label)s}}" % { "lower_label": lower_label, "upper_label": upper_label, }
def is_palindrome(head): """ Given a singly linked list, determine if it is a palindrome :param head: head node of given linked list :type head: ListNode :return: whether or not given linked list is palindrome :rtype: bool """ if head is None or head.next is None: return True # find middle node slow = head fast = head.next while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next # reverse right-half of linked list curr = slow.next slow.next = None prev = None while curr is not None: tmp = curr.next curr.next = prev prev = curr curr = tmp # check palindrome right_head = prev while right_head is not None and head is not None: if right_head.val != head.val: return False right_head = right_head.next head = head.next return True
def is_palindrome1(w): """Create slice with negative step and confirm equality with w.""" return w[::-1] == w
def _check(edges): """Check consistency""" res = True for src, dsts in edges.items(): for dst in dsts: if dst not in edges: print('Warning: edges[%d] contains %d, which is not in edges[]' % (src, dst)) res = False return res
def sort_streams_on_efficiency(stream_array): """ sorts an array of streams decending on cost = [3] """ return sorted(stream_array, key=lambda l: l[3])
def model(p, x): """ Evaluate the model given an X array """ return p[0]*x + p[1]
def date_comparison(input_series, output_series): """ Compare the start and end dates for the input and output series and obtain the dates that completes the output series :param input_series: :param output_series: :return: """ first_input = input_series['data']['first'] last_input = input_series['data']['last'] first_output = output_series['data']['first'] last_output = output_series['data']['last'] # if output series is not left aligned, something happened and the series # must be re insert if first_input != first_output: ans = {'first': first_input, 'last': last_input} else: ans = {'first': last_output, 'last': last_input} return ans
def create_pytest_param_str_id(f): # type: (...) -> str """ Returns an id that can be used as a pytest id, from an object. :param f: :return: """ if callable(f) and hasattr(f, '__name__'): return f.__name__ else: return str(f)
def getFalarmTime(segs): """ This function calculates the aggregate false alarm time generated by the speaker diarization system. Inputs: - segs: the list of ground truth and diarization segments after removing segments within the collars Outputs: - falarmTime: the aggregate false alarm time generated by the speaker diarization system in seconds, form: "0" """ falarmTime = 0 for row in segs: if row['name']['oname'] == [] and row['name']['dname'] != []: falarmTime += row['tend'] - row['tbeg'] #falarmTime = round(falarmTime, 3) return falarmTime
def has_external_choices(json_struct): """ Returns true if a select one external prompt is used in the survey. """ if isinstance(json_struct, dict): for k, v in json_struct.items(): if k == "type" and isinstance(v, str) and v.startswith("select one external"): return True elif has_external_choices(v): return True elif isinstance(json_struct, list): for v in json_struct: if has_external_choices(v): return True return False
def list_of_timeframe_dicts(timeframes): """ Parameters ---------- timeframes : list of TimeFrame objects Returns ------- list of dicts """ return [timeframe.to_dict() for timeframe in timeframes]
def get_apid_from_raw_space_packet(raw_packet: bytes) -> int: """Retrieve the APID from the raw packet. :param raw_packet: :raises ValueError: Passed bytearray too short :return: """ if len(raw_packet) < 6: raise ValueError return ((raw_packet[0] & 0x7) << 8) | raw_packet[1]
def _remove_keys(keys, keys_to_remove): """Remove given keys from list of keys. Args: keys: List of keys to subtract from. keys_to_remove: List of keys to remove. Returns: A list of keys after subtraction. """ return list(set(keys) - set(keys_to_remove))
def access(value, key): """Gets a specified key out of a specified collection.""" # if the collection is a list and the key is an index, make sure we don't go out of bounds if isinstance(value, list): key %= len(value) return value[key]
def format_value(value): """Handles side effects of json.load function""" if value is None: return 'null' if type(value) is bool: return 'true' if value else 'false' if type(value) is str: return f'\'{value}\'' if type(value) is dict \ or type(value) is list: return '[complex value]' else: return value
def cast_to_str(labels, nested=False): """ Convert every label to str format. If nested is set to True, a flattened version of the input list is also returned. Args: labels: list Input labels nested: bool Indicate if the input list contains (or may contain) sublists. False by default. If True, a flattened version of the list is also returned. Results: labels_str: list Labels converted to str format labels_str_flat: list Flattened list of labels. Only returned if nested is set to True. """ if not nested: labels_str = [str(x) for x in labels] return labels_str else: labels_str = [] labels_str_flat = [] for x in labels: if isinstance(x, list): sublist = [] for xx in x: labels_str_flat.append(str(xx)) sublist.append(str(xx)) labels_str.append(sublist) else: labels_str_flat.append(str(x)) labels_str.append(str(x)) return labels_str, labels_str_flat
def isint(f, tol=.00000001): """ Takes in a float F, and checks that it's within TOL of floor(f). """ # we're casting to float before the comparison with TOL # so that decimal Fs work return abs(float(f) - int(f)) <= .00000001
def rank_scores(points): """Sort and rank teams according to league points Parameters ---------- points : dict str->int Team names as keys, league points as value Returns ------- ranking_output : list of (ranking, team, points_score) tuples ranking : int team : str points_score : int Notes ----- Sorted by score and alphabetically if rankings are tied. """ # Sort first by the league points (input dict's values), but negative to # sort descending, then by team name using the `sorted` builtin's `key` # argument sorted_rankings = sorted( points.items(), key=lambda item: (-item[1], item[0])) ranking = 1 prev_score = None prev_ranking = 1 ranking_output = [] for i, (team, points_score) in enumerate(sorted_rankings, 1): if points_score == prev_score: ranking = prev_ranking else: ranking = i prev_score = points_score prev_ranking = ranking ranking_output.append((ranking, team, points_score)) return ranking_output
def substr_count(s): """copied from hackerank""" tot = 0 count_sequence = 0 prev = '' for i,v in enumerate(s): count_sequence += 1 if i and (prev != v): j = 1 while ((i-j) >= 0) and ((i+j) < len(s)) and j <= count_sequence: if s[i-j] == prev == s[i+j]: tot += 1 j += 1 else: break count_sequence = 1 tot += count_sequence prev = v return tot
def strip_comments(line, comment_char='#', quote_char='"'): """Returns the string after removing comments.""" cut = 0 while cut < len(line): pos = line[cut:].find(comment_char) # no real comment in line if pos < 0: return line # do we have even number quotes before it? If so this is real comment if line[:cut + pos].count(quote_char) % 2 == 0: return line[:cut + pos] cut = cut + pos + 1 return line
def construct_identifier(*args, username_prefix='@'): """ Create a post identifier from comment/post object or arguments. Examples: :: construct_identifier('username', 'permlink') construct_identifier({'author': 'username', 'permlink': 'permlink'}) """ if len(args) == 1: op = args[0] author, permlink = op['author'], op['permlink'] elif len(args) == 2: author, permlink = args else: raise ValueError( 'construct_identifier() received unparsable arguments') fields = dict(prefix=username_prefix, author=author, permlink=permlink) return "{prefix}{author}/{permlink}".format(**fields)
def fprime_to_jsonable(obj): """ Takes an F prime object and converts it to a jsonable type. :param obj: object to convert :return: object in jsonable format (can call json.dump(obj)) """ # Otherwise try and scrape all "get_" getters in a smart way anonymous = {} getters = [attr for attr in dir(obj) if attr.startswith("get_")] for getter in getters: # Call the get_ functions, and call all non-static methods try: func = getattr(obj, getter) item = func() # If there is a property named "args" it needs to be handled specifically unless an incoming command if ( getter == "get_args" and not "fprime_gds.common.data_types.cmd_data.CmdData" in str(type(obj)) ): args = [] for arg_spec in item: arg_dict = { "name": arg_spec[0], "description": arg_spec[1], "value": arg_spec[2].val, "type": str(arg_spec[2]), } if arg_dict["type"] == "Enum": arg_dict["possible"] = arg_spec[2].keys() args.append(arg_dict) # Fill in our special handling item = args anonymous[getter.replace("get_", "")] = item except TypeError: continue return anonymous
def space_pad(number, length): """ Return a number as a string, padded with spaces to make it the given length :param number: the number to pad with spaces (can be int or float) :param length: the specified length :returns: the number padded with spaces as a string """ number_length = len(str(number)) spaces_to_add = length - number_length return (' ' * spaces_to_add) + str(number)
def make_FFTdir_name(dss, year, doy): """ """ src = "%02d" % (year - 2000) if dss == 14: src += "g" elif dss == 43: src += "c" elif dss == 63: src += "m" else: raise Exception("%s is not a valid 70-m antenna", dss) src += "%03d/" % doy return src
def _get_provider_category(row): """ determine provider category from lead art provider """ if row['lead_art_provider']: if 'courtesy of' in row['lead_art_provider'].lower(): return 'Courtesy' elif 'for npr' in row['lead_art_provider'].lower(): return 'For NPR' else: return row['lead_art_provider'] else: return None
def dfs(graph, vertex, explored=None, path=None): """ Depth first search to compute length of the paths in the graph starting from vertex """ if explored == None: explored = [] if path == None: path = 0 explored.append(vertex) len_paths = [] for w in graph[vertex]: if w not in explored: new_path = path + 1 len_paths.append(new_path) len_paths.extend(dfs(graph, w, explored[:], new_path)) return len_paths
def conj_phrase(list_, cond='or'): """ Joins a list of words using English conjunction rules Args: list_ (list): of strings cond (str): a conjunction (or, and, but) Returns: str: the joined cconjunction phrase References: http://en.wikipedia.org/wiki/Conjunction_(grammar) Example: >>> list_ = ['a', 'b', 'c'] >>> result = conj_phrase(list_, 'or') >>> print(result) a, b, or c Example1: >>> list_ = ['a', 'b'] >>> result = conj_phrase(list_, 'and') >>> print(result) a and b """ if len(list_) == 0: return '' elif len(list_) == 1: return list_[0] elif len(list_) == 2: return ' '.join((list_[0], cond, list_[1])) else: condstr = ''.join((', ' + cond, ' ')) return ', '.join((', '.join(list_[:-2]), condstr.join(list_[-2:])))
def elem_L(w, L): """ Simulation Function: -L- Returns the impedance of an inductor Kristian B. Knudsen ([email protected] || [email protected]) Inputs ---------- w = Angular frequency [1/s] L = Inductance [ohm * s] """ return 1j * w * L
def get_test_model(ema_model, model, use_ema): """ use ema model or test model """ if use_ema: test_model = ema_model.ema test_prefix = "ema" else: test_model = model test_prefix = "" return test_model, test_prefix
def _py_while_loop(loop_cond, loop_body, init_state, opts): """Overload of while_loop that executes a Python while loop.""" del opts state = init_state while loop_cond(*state): state = loop_body(*state) return state
def normalize_tag(tag: str) -> str: """ Drop the namespace from a tag and converts to lower case. e.g. '{https://....}TypeName' -> 'TypeName' """ normalized = tag if len(tag) >= 3: if tag[0] == "{": normalized = tag[1:].split("}")[1] return normalized.lower()
def occ(s1,s2): """occ (s1, s2) - returns the number of times that s2 occurs in s1""" count = 0 start = 0 while True: search = s1.find(s2,start) if search == -1: break else: count +=1 start = search+1 return count
def remove_from_list(l, item): """Remove the first occurence of `item` from list `l` and return a tuple of the index that was removed and the element that was removed. Raises: ValueError : If `item` is not in `l`. """ idx = l.index(item) item = l.pop(idx) return (idx, item)
def make_slider_min_max_values_strings(json_content): """ Turns min/max int values into strings, because the iOS app expects strings. This is for backwards compatibility; when all the iOS apps involved in studies can handle ints, we can remove this function. """ for question in json_content: if 'max' in question: question['max'] = str(question['max']) if 'min' in question: question['min'] = str(question['min']) return json_content
def check_redundant(model_stack: list, stack_limit: int) -> bool: """[summary] :param model_stack: [description] :type model_stack: list :param stack_limit: [description] :type stack_limit: int :return: [description] :rtype: bool """ stop_recursion = False if len(model_stack) > stack_limit: # rudimentary CustomUser->User->CustomUser->User detection, or # stack depth shouldn't exceed x, or # we've hit a point where we are repeating models if ( (model_stack[-3] == model_stack[-1]) or (len(model_stack) > 5) or (len(set(model_stack)) != len(model_stack)) ): stop_recursion = True return stop_recursion
def get_neighbor(r, c): """Return the neighbors assuming no diag movement""" return [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]
def create_summary_document_for_es(data): """ This function will create document structure appropriate for es :param data: data to parse :return: part of document to be inserted into es """ results = list() for k, v in data.items(): results.append({ "name": k, "value": v }) return results
def get_user_item_interaction(dataset): """ """ user_item_id_dict = {} item_user_id_dict = {} cnt = 0 for uid in dataset.keys(): cnt += 1 if (cnt % 1000 == 0): print ("DEBUG: Output Cnt %d" % cnt) item_ids = dataset[uid]['positive'] # uid-item_id user_item_id_dict[uid] = item_ids for item_id in item_ids: if item_id in item_user_id_dict.keys(): item_user_id_dict[item_id].append(uid) else: item_user_id_dict[item_id] = [uid] print ("DEBUG: Generating User Item Id Dict Size %d" % len(user_item_id_dict)) print ("DEBUG: Generating Item User Id Dict Size %d" % len(item_user_id_dict)) return user_item_id_dict, item_user_id_dict
def get_nm(ltag): """Return the value of the NM tag.""" for tag in ltag: if tag[0] == "NM": return tag[1] return None
def replace_name_token_cased(tokens): """ :param tokens: tokens output by the cased BertTokenizer :return: tokens with the sequence 164('['), 1271('name'), 166(']') replaced by 104 ('[NAME]') """ while 1271 in tokens: i = tokens.index(1271) if i - 1 >= 0 and i + 1 < len(tokens) and tokens[i - 1] == 164 and tokens[i + 1] == 166: tokens[i - 1] = 104 del tokens[i + 1] del tokens[i] else: tokens[i] = 105 for i in range(len(tokens)): if tokens[i] == 105: tokens[i] = 1271 return tokens
def normalize(tokens, case=False): """ Lowercases and turns tokens into distinct words. """ tokens = [ str(t).lower() if not case else str(t) for t in tokens ] tokens = [t.strip() for t in tokens if len(t.strip()) > 0] return tokens
def v4_is_anagram(word1, word2): """Return True if the given words are anagrams. Normalizing the words by lower-casing them. """ word1, word2 = word1.lower(), word2.lower() return sorted(word1) == sorted(word2)
def middle(t): """Returns alll but first and last elements of t. t: list returns: new list """ return t[1:-1]
def sum_eo(n, t): """Sum even or odd numbers in range. Return the sum of even or odd natural numbers, in the range 1..n-1. :param n: The endpoint of the range. The numbers from 1 to n-1 will be summed. :param t: 'e' to sum even numbers, 'o' to sum odd numbers. :return: The sum of the even or odd numbers in the range. Returns -1 if `t` is not 'e' or 'o'. """ if t == "e": start = 2 elif t == 'o': start = 1 else: return -1 return sum(range(start, n, 2))
def compare_lists(list1, name1, list2, name2): """compare two lists and check for different or missing entries print out missing or different entries in list 2 compared to list 1 Parameters ---------- list1: list name1: str - name to be printed in comparison list2: second list name2: str - name to be printed in comparison Returns ------- passed: boolean, returns True if files match """ no_match = [x for x in list2 if x not in list1] missing = [x for x in list1 if x not in list2] passed = True if len(no_match) > 0: for x in no_match: print('{0} is in {2} but not in {1}'.format(x, name1, name2)) passed = False elif len(missing) > 0: for x in missing: print('{0} is missing in {2} compared to {1}'.format(x, name1, name2)) passed = False else: print('lists match: {0}, {1}'.format(name1, name2)) return passed
def tell_pod_deploy_name(s): """ >>> tell_pod_deploy_name('dummy-web-dev-7557696ddf-52cc6') 'dummy-web-dev' >>> tell_pod_deploy_name('dummy-web-7557696ddf-52cc6') 'dummy-web' """ return s.rsplit('-', 2)[0]
def sliced(seq, idx): """ Possibly slice object if index is not None. """ if idx is None: return seq else: try: return seq[idx] except KeyError: raise IndexError(f"invalid index: {idx}")
def abi_get_element_by_name(abi, name): """ Return element of abi (return None if fails to find) """ if (abi and "abi" in abi): for a in abi["abi"]: if ("name" in a and a["name"] == name): return a return None
def thru_op(*args, **kws): """ This is a thru-op. It returns everything passed to it. """ if len(args) == 1 and kws == dict(): return args[0] elif len(args) == 1 and kws != dict(): return args[0], kws elif len(args) == 0: return kws else: return args, kws
def check_name_size(name): """Check size name""" size_name = len(name) return size_name
def visible_vars(vrs): """Slice dictionary `vrs`, omitting keys matching `_*`. @type vrs: `dict` @rtype: `dict` """ return {k: v for k, v in vrs.items() if not k.startswith('_')}
def hexadecimal_to_decimal(hex): """Convert Hexadecimal to Decimal. Args: hex (str): Hexadecimal. Returns: int: Return decimal value. """ return sum(['0123456789ABCDEF'.find(var) * 16 ** i for i, var in enumerate(reversed(hex.upper()))])
def sanitize_path(path: str) -> str: """Sanitized a path for hash calculation. Basically makes it lowercase and replaces slashes with backslashes. Args: path (str): input path Returns: str: sanitized path """ return path.lower().replace("/", "\\")
def calcHedgeRatio(betaHat: float, sigmaHat: float) -> float: """Calculates the hedge ratio. Parameters ---------- betaHat : float Beta hat of two assets. sigmaHat : float Sigma hat of two assets. Returns ------- float Returns the hedge ratio. """ return betaHat * (1 + 0.5 * sigmaHat)
def infinity_norm(x): """ Compute infinity norm of x. :param x: rare matrix represented as dictionary of dictionaries of non zero values :return max_value: maximum value of x """ max_value = None for line in x.keys(): for column in x[line].keys(): if not max_value or max_value < x[line][column]: max_value = x[line][column] return max_value
def listed_list(list_list): """Return presentable string from given list """ return '{} and {}'.format(', '.join(list_list[:-1]), list_list[-1]) if ( len(list_list) > 1) else list_list[0]
def filename_safe(id): """ Remove all characters other than letters, digits, hyphen, underscore, and plus. """ ans = [] for c in id: if c.isalnum() or c in "+-_": ans.append(c) return "".join(ans)
def is_3d_model(url): """Is the link (probably) to a 3D model?""" return url.startswith("/object/3d")
def cskv_to_dict(option): """Convert kwargs into dictionary.""" opts = {} option_list = option.split(',') for opt in option_list: # skip items that aren't kvs if len(opt.split('=')) != 2: continue key = opt.split('=')[0] value = opt.split('=')[1] opts[key] = value return opts
def bounded_word_reward(score, reward, bound): """ bound = L_predict L_predict could be: 1) length_src * alpha 2) average length_tgt * beta 3) model predicted length * gamma """ length_tgt = len(score) bounded_length = min(length_tgt, bound) return sum(score) - reward * bounded_length
def pad_word_chars(words): """ Pad the characters of the words in a sentence. Input: - list of lists of ints (list of words, a word being a list of char indexes) Output: - padded list of lists of ints - padded list of lists of ints (where chars are reversed) - list of ints corresponding to the index of the last character of each word """ max_length = max([len(word) for word in words]) char_for = [] char_rev = [] char_pos = [] for word in words: padding = [0] * (max_length - len(word)) char_for.append(word + padding) char_rev.append(word[::-1] + padding) char_pos.append(len(word) - 1) return char_for, char_rev, char_pos
def padding(index_list, max_len): """ pad 0 to the index_list INPUT: index_list: an integer list with length <= max_len max_len: integer --maximum number of entries in the list OUTPUT: an integer list with length == max_len """ return [0] * (max_len - len(index_list)) + index_list
def add_two_numbers(a, b): """[summary] add two numbers and return the sum Args: a ([int or float]): [addand] b ([int or float]): [addand] """ sum = a + b # addition return sum
def convert_to_hex(num, bits): """ Converts number to hexadecimal :param num: int :param bits: int :return: str """ if not isinstance(num, int): raise ValueError("Invalid number type, num must be of type int.") return f'{num:0{int(bits / 4)}x}'.upper()
def get_tot_th(x): """Takes a list of T2 strings, returns num_tot, num_th""" tot_count = 0 th_count = 0 for y in x: testval = y.split(':') testval = testval[0][-1] if testval == "9": tot_count += 1 elif testval == "1": th_count +=1 else: continue return tot_count,th_count
def dec(a): """ Function that converts percent to decimal """ a = float(a) return a / 100
def calculate_power(action, power): """Should the bulb be on or off?""" desired_power = power if 'power' in action: if action['power'] == 'toggle': # This could probably be simplified, given it's either 1 or 0 if power > 0: desired_power = 0 else: desired_power = 1 else: desired_power = int(action['power']) return desired_power
def form_json_data(formset, questions: list) -> list: """ For each ``form`` in ``formset``, extracts the user's answer_choice and adds the question details along with its attributes as a dictionary. This is the actual data that is stored in the database as answer, after passing necessary validation. """ json_data = [] for form, question in zip(formset, questions): valid_dict = { 'answer_choice': int(form.cleaned_data.get('answer_choice')), 'question': { 'subclass': question['subclass'], 'factor': question['factor'], 'number': question['number'] } } json_data.append(valid_dict) json_data = json_data return json_data