content
stringlengths
42
6.51k
def csv_row_station_bssid(row): """ Provide associated bssid of given station. :param row: list of strings representing one row of csv file generated by airodump-ng during scanning :return: string bssid """ return row[5].strip()
def many_to_one(input_dict): """Convert a many-to-one mapping to a one-to-one mapping""" return dict((key, val) for keys, val in input_dict.items() for key in keys)
def __get_sourceforge_url(pkg_info): """ Get git repo url of package """ url = pkg_info["src_repo"] return url
def _get_by_path_kw(pathlist): """ Used by :meth:`get_by_path` to create the required kwargs for Node.objects.get(). Might be a starting point for more sophisticated queries including paths. Example:: ifi = Node.objects.get(**Node._get_by_path_kw(['uio', 'ifi'])) :param pathlist: A list of node-names, like ``['uio', 'ifi']``. """ kw = {} key = 'short_name' for short_name in reversed(pathlist): kw[key] = short_name key = 'parentnode__' + key return kw
def get_multiline_actions(a_string): """ Transforms the multiline command string provided into a list of single-line commands. :param a_string: :return: a list of action strings """ def _procline(l): # remove spaces on the left l = l.strip() # remove comments try: cmt_idx = l.index('#') l = l[:cmt_idx] except: pass # finally remove trailing spaces return l.rstrip() lines = [_procline(l) for l in a_string.splitlines()] return [l for l in lines if len(l) > 0]
def solve(n, mp, q, queries): """ Solve the problem here. :return: The expected output. """ def set_transform(s): return {mp[i] - 1 for i in s} def stringify(tup): return ','.join(map(str, tup)) answer = [-1 for _ in range(n-1)] + [0] current = {i for i in range(n)} visited = set() steps = 0 while stringify(tuple(sorted(current))) not in visited: visited |= {stringify(tuple(sorted(current)))} current = set_transform(current) steps += 1 if answer[len(current)-1] == -1: answer[len(current)-1] = steps return [answer[z-1] for z in queries]
def validate_bool(val): """ Convert b to a boolean or raise a ValueError. """ if type(val) is str: val = val.lower() if val in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): return True elif val in ('f', 'n', 'no', 'off', 'false', '0', 0, False): return False else: raise ValueError('Could not convert "%s" to boolean!' % val)
def exercise_1(inputs): # DO NOT CHANGE THIS LINE """ This functions receives the input in the parameter 'inputs'. Change the code, so that the output is sqaure of the given input. p, q, r = inputs p => ['t101', 't102', 't103'] q => ['s101', 's102', 's103'] r => { 'l101':['t101': ['s101', 's102']], 'l102': ['s101', 's102', 's103']] } p = Person() s = Student() t = Teacher() l = Lecture() output = { 1: [Person, p], 2: [Teacher, Student, t, s], 3: [Lecture, l], 4: [Lecture, l], 5: [Lecture, Student, l, s], 6: [Teacher, Student, t, s] } """ output = inputs return output # DO NOT CHANGE THIS LINE
def build_person(first_name, last_name, age=None): """Return a dictionary of infotmation about a person.""" person = {'first': first_name, 'last': last_name} if age: person['age'] = age return person
def is_in_list(list_one, list_two): """Check if any element of list_one is in list_two.""" for element in list_one: if element in list_two: return True return False
def max_subseq(n, t): """ Return the maximum subsequence of length at most t that can be found in the given number n. For example, for n = 20125 and t = 3, we have that the subsequences are 2 0 1 2 5 20 21 22 25 01 02 05 12 15 25 201 202 205 212 215 225 012 015 025 125 and of these, the maxumum number is 225, so our answer is 225. >>> max_subseq(20125, 3) 225 >>> max_subseq(20125, 5) 20125 >>> max_subseq(20125, 6) # note that 20125 == 020125 20125 >>> max_subseq(12345, 3) 345 >>> max_subseq(12345, 0) # 0 is of length 0 0 >>> max_subseq(12345, 1) 5 """ "*** YOUR CODE HERE ***" # base need to understand if n == 0 or t == 0: return 0 with_last = max_subseq(n // 10, t - 1) * 10 + n % 10 without_last = max_subseq(n // 10, t) return max(with_last, without_last)
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. The code should run in O(n) time. Do not use Python's inbuilt functions to find min and max. Args: ints(list): list of integers containing one or more integers """ min_value = ints[0] max_value = ints[0] for value in ints[1:]: # no need to check first element if value > max_value: max_value = value if value < min_value: min_value = value return min_value, max_value
def invert(d): """ Take in dictionary d Returns a new dictionary: d_inv Values in it are a list Flips value and keys """ d_Inv = {} for i in d.keys(): temp = d[i] # Need the if statement to assign, or add to a list! if temp not in d_Inv: d_Inv[temp] = [i] else: d_Inv[temp].append(i) return d_Inv
def all_unique(lst: list) -> bool: """Check if a given list has duplicate elements""" return len(lst) == len(set(lst))
def fibonacci_comprehension(limit): """fibonacci sequence using a list comprehension.""" sequence = [0, 1] [sequence.append(sequence[i] + sequence[i - 1]) for i in range(1, limit)] return sequence[-1]
def getnameinfo(sockaddr, flags): """Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending on the settings of *flags*, the result can contain a fully-qualified domain name or numeric address representation in *host*. Similarly, *port* can contain a string port name or a numeric port number.""" return ('', 0)
def deformat_var_key(key: str) -> str: """ deformat ${key} to key :param key: key :type key: str :return: deformat key :rtype: str """ return key[2:-1]
def cleana(tagged): """clean tags and new lines out of single attribute""" if tagged: untagged = (tagged.text) # strip tags # strip newlines stripped = (untagged .replace('\n\n+', ' ') .replace('\n', ' ') .replace('\r', ' ')) nolines = (stripped.strip()) # strip trailing spaces else: nolines = "None" return nolines
def selectArea(arr, x1, y1, x2, y2): """Selects a specified area from a 2D array and fills a 1D arr with the values""" areaArr = [] for row in range(y1, y2): for col in range(x1, x2): areaArr.append(arr[row][col]) return areaArr
def changeSecurityListToStr(securityList:list): """ This function will convert a list of string into a single string. """ securityListFormed = [i+',' for i in securityList] return "".join(securityListFormed).strip(',')
def fist_visible_seat(seats, pos: tuple, shift: tuple): """Return the first visible seat by continously applying the same shift. >>> fist_visible_seat(["...L.#.#.#.#."], (0, 0), (0, 1)) 'L' >>> fist_visible_seat([".....#.#.#.#."], (0, 4), (0, 1)) '#' """ row, column = pos rshift, cshift = shift while 0 <= row < len(seats) and 0 <= column < len(seats[0]): seat = seats[row][column] if seat != ".": return seat row += rshift column += cshift return None
def filterSplit(p, values): """ Function filters a list into two sub-lists, the first containing entries satisfying the supplied predicate p, and the second of entries not satisfying p. """ satp = [] notp = [] for v in values: if p(v): satp.append(v) else: notp.append(v) return (satp,notp)
def check_input(string, char_set): """checks if a string is 5 chars long and only contains chars from a given set""" return len(string) == 5 and not (set(string) - char_set)
def _product(a,scalar): """ multiply iterable a by scalar """ return tuple([scalar*x for x in a])
def make_sepset_node_name(node_a_name, node_b_name): """ Make a standard sepset node name using the two neighboring nodes. :param str node_a_name: The one node's name. :param str node_b_name: The other node's name. :return: The sepset's name :rtype: str """ return "sepset__" + "__".join(sorted([node_a_name, node_b_name]))
def to_bool(val): """Converts true, yes, y, 1 to True, False otherwise.""" if val: strg = str(val).lower() if (strg == 'true' or strg == 'y' or strg == 'yes' or strg == 'enabled' or strg == '1'): return True else: return False else: return False
def read(path, mode='rt'): """Read a file and return its content.""" try: with open(path, mode) as fp: return fp.read() except Exception as e: return f'FILE ERROR: {e}, path {path!r}'
def email_sent_ipn(path: str) -> tuple: """ **email_sent_ipn** Delivered ipn for mailgun :param path: organization_id :return: OK, 200 """ # NOTE: Delivered ipn will end up here if path == "delivered": pass elif path == "clicks": pass elif path == "opens": pass elif path == "failure": pass elif path == "spam": pass elif path == "unsubscribe": pass return "OK", 200
def code_event(event): """get the event code""" if event == 'tracker': return 5 elif event == 'acc on': return 6 elif event == 'acc off': return 7 elif event == 'help me': return 1 elif event == 'speed': return 2 elif event == 'ac alarm': return 9 else: return None
def username_to_oci_compatible_name(username): """ To generate a safe username this method can be used and we'll strip out characters that would typically appear in an email which don't help with a username Args: * username : uncleansed username e.g. the user's email address **Returns** The cleansed username """ if (username != None): username = username.replace(".com", "") username = username.replace(".org", "") username = username.replace("@", "-") username = username.replace(".", "-") username = username.replace(" ", "") return username
def hass_to_lox(level): """Convert the given HASS light level (0-255) to Loxone (0.0-100.0).""" return (level * 100.0) / 255.0
def ical_escape (victim): """ iCal has weird escaping rules. Implement them. iCal also has weird block formatting rules. Ugh. """ if not victim: return "EMPTY STRING PROVIDED TO ICAL_ESCAPE" # https://stackoverflow.com/questions/18935754/how-to-escape-special-characters-of-a-string-with-single-backslashes return victim.translate( str.maketrans({ "," : r"\,", ";" : r"\;", "\\": r"\\", "\n": r"\n", "\r": r"", }))
def get_slope_intercept(point1 , point2): """ :param point1: lower point of the line :param point2: higher point of the line :return: slope and intercept of this line """ slope = (point1[1] - point2[1]) / (point1[0] - point2[0]) # slope = ( y2-y1 ) / ( x2-x1 ) . intercept = point1[1] - slope * point1[0] # y = m*x + b return slope , intercept
def Shift(xs, shift): """Adds a constant to a sequence of values. Args: xs: sequence of values shift: value to add Returns: sequence of numbers """ return [x+shift for x in xs]
def filter_channels_by_server(channels, server): """Remove channels that are on the designated server""" chans = [] for channel in channels: sv, chan = channel.split(".", 1) if sv == server: chans.append(chan) return chans
def steering3(course, power): """ Computes how fast each motor in a pair should turn to achieve the specified steering. Compared to steering2, this alows pivoting. Input: course [-100, 100]: * -100 means turn left as fast as possible (running left * backwards) * -50 means quick turn, left stopped * 0 means drive in a straight line, and * 50 means quick turn, right stopped * 100 means turn right as fast as possible (right backwards) * If >100 power_right = -power * If <100 power_left = power power: the power that should be applied to the outmost motor (the one rotating faster). The power of the other motor will be computed automatically. Output: a tuple of power values for a pair of motors. Example: for (motor, power) in zip((left_motor, right_motor), steering(50, 90)): motor.run_forever(speed_sp=power) """ abscourse = min(abs(course), 100) outer = power inner = (abscourse - 50)/50*power if course >= 0: power_left = outer power_right = inner else: power_right = outer power_left = inner return (int(power_left), int(power_right))
def _is_batch_all(batch, predicate): """ Implementation of is_symbolic_batch() and is_numeric_batch(). Returns True iff predicate() returns True for all components of (possibly composite) batch. Parameters ---------- batch : any numeric or symbolic batch. This includes numpy.ndarray, theano.gof.Variable, None, or a (nested) tuple thereof. predicate : function. A unary function of any non-composite batch that returns True or False. """ # Catches any CompositeSpace batches that were mistakenly hand-constructed # using nested lists rather than nested tuples. assert not isinstance(batch, list) # Data-less batches such as None or () are valid numeric and symbolic # batches. # # Justification: we'd like # is_symbolic_batch(space.make_theano_batch()) to always be True, even if # space is an empty CompositeSpace. if batch is None or (isinstance(batch, tuple) and len(batch) == 0): return True if isinstance(batch, tuple): subbatch_results = tuple(_is_batch_all(b, predicate) for b in batch) result = all(subbatch_results) # The subbatch_results must be all true, or all false, not a mix. assert result == any(subbatch_results), ("composite batch had a " "mixture of numeric and " "symbolic subbatches. This " "should never happen.") return result else: return predicate(batch)
def _strtobool(val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. .. note:: copied from distutils.util """ val = val.lower() if val in ("y", "yes", "t", "true", "on", "1"): return 1 elif val in ("n", "no", "f", "false", "off", "0"): return 0 else: raise ValueError("invalid truth value {!r}".format(val))
def _safe_decode(output_bytes: bytes) -> str: """ Decode a bytestring to Unicode with a safe fallback. """ try: return output_bytes.decode( encoding='utf-8', errors='strict', ) except UnicodeDecodeError: return output_bytes.decode( encoding='ascii', errors='backslashreplace', )
def Area_Perimeter(a,b,ch=1): """ a(int): Length of the rectangle b(int): Breadth of the rectangle ch(int): choice ch==1>>Area ch==2>>Perimeter Returns area or perimeter of the rectangle. """ if ch==1: return 'Area is '+str(a*b) elif ch==2: return 'Perimeter is '+str(2*(a+b)) else: return 'Invalid choice.'
def check_if_string_in_file(file_name, string_to_search): """ Check if any line in the file contains given string """ # Open the file in read only mode with open(file_name, 'r') as read_obj: # Read all lines in the file one by one for line in read_obj: # For each line, check if line contains the string if string_to_search in line: return True return False
def is_field_selected(model, field, spec): """Apply field_specs to tell if model.field is to be included >>> specs = lambda s: parse_field_specs(s) Basic direct usage ------------------ If explicitely selected:: >>> is_field_selected('bar', 'f1', specs('bar:f1')) True Default is to select so:: >>> is_field_selected('bar', 'f1', {}) True And if explicitely unselected:: >>> is_field_selected('bar', 'f1', specs('bar:-f1')) False Of course the spec must be targetting the correct model:: >>> is_field_selected('bar', 'f1', specs('foo:-f1')) True Or the correct field:: >>> is_field_selected('bar', 'f1', specs('bar:-f2')) True Wildcards --------- '*' on models should hit all models:: >>> is_field_selected('bar', 'f1', specs('*:-f1')) False '*' on fields should hit all fields:: >>> is_field_selected('bar', 'f1', specs('bar:-*')) False But wildcards have less priority than direct spec:: >>> is_field_selected('bar', 'f1', specs('*:-f1;bar:f1')) True >>> is_field_selected('bar', 'f1', specs('*:-*;bar:f1')) True >>> is_field_selected('bar', 'f1', specs('bar:-*;bar:f1')) True >>> is_field_selected('bar', 'f1', specs('bar:-*;bar:-*,f1')) True """ field_spec = spec.get('*', {}).copy() field_spec.update(spec.get(model, {})) default = field_spec.get('*', True) return field_spec.get(field, default)
def box_volume_UPS(a=13, b=11, c=2): """Returns the volume of a box with edge lengths a, b and c. Default values are a = 13 inches, b = 11 inches and c = 2 inches""" return a * b * c
def forcedir(path): """Ensure the path ends with a trailing forward slash :param path: An FS path >>> forcedir("foo/bar") 'foo/bar/' >>> forcedir("foo/bar/") 'foo/bar/' """ if not path.endswith('/'): return path + '/' return path
def fix_sign(x, N=360 * 60 * 10): """ Convert negative tenths of arcminutes *x* to positive by checking bounds and taking the modulus N (360 degrees * 60 minutes per degree * 10 tenths per 1). """ if x < 0: assert x > -N x += N assert x < N return x % N
def get_steps_to_exit(data, strange=False): """ Determine the number of steps to exit the 'maze' Starting at the first element, move the number of steps based on the value of the current element, and either bump it by one, or if 'strange' is True and the value is over three, decrease it by one. If the new position is outside the current list of elements, we can exit Returns the number of steps it takes to exit """ jumps = 0 idx = 0 while 0 <= idx < len(data): new_idx = idx + data[idx] if strange and data[idx] >= 3: data[idx] -= 1 else: data[idx] += 1 jumps += 1 idx = new_idx return jumps
def evaluate(coeffs, x0): """evaluate polynomial represented by 'coeffs' at x = x0""" p_x0 = 0 for c_k in reversed(coeffs): p_x0 = p_x0*x0 + c_k return p_x0
def tidy_participation_url(url: str) -> str: """ >>> tidy_participation_url( ... "https://test.connpass.com/event/123456/participation/") 'https://test.connpass.com/event/123456/participation/' >>> tidy_participation_url( ... "https://test.connpass.com/event/123456/participation") 'https://test.connpass.com/event/123456/participation/' >>> tidy_participation_url("https://test.connpass.com/event/123456/") 'https://test.connpass.com/event/123456/participation/' >>> tidy_participation_url("https://test.connpass.com/event/123456") 'https://test.connpass.com/event/123456/participation/' """ if not url.endswith("/"): url += "/" if not url.endswith("participation/"): url += "participation/" return url
def make_key(x,y): """ function to combine two coordinates into a valid dict key """ return f'{x}, {y}'
def rep_newlines_with_space(string: str) -> str: """Removes newlines and replaces them with spaces. Also reduces double spaces to single spaces. """ return string.replace("\n", " ").replace(" ", " ")
def get_max_len_word(_list): """Return max len word from list""" return max(len(item) for item in _list if type(item) != int)
def extract_words(all_words): """ Product title contains some preposition words. The words after preposition word usually indicate components, materials or intended usage. Therefore, there is no need to find brand and product name in the words after preposition. There is one exception: the preposition word appears in the first place. """ prepositions = ['for','with','from','of','by','on'] MODE = 0 if all_words[0] in prepositions else 1 if MODE: words = [] for word in all_words: if word not in prepositions: words.append(word) else: words = all_words return words
def scan_square(row, col, matrix): """ Scan the current position for a square of odd sides. Args: row - integer for row position col - column position matrix - multi-dimensional list of 0's and 1's Returns a tuple describing the biggest square's center coordinates and the dimensions of the cell. e.g (2, 3, 5) is a size 5 centered at (2, 3) (r, c, s) Return None if none is found. """ if (matrix[row][col] == 0): return None rows_no = len(matrix) cols_no = len(matrix[0]) if (((row + 2) > rows_no - 1) or ((col + 2) > cols_no - 1)): return None sq = None found = True lmt = rows_no if rows_no < cols_no else cols_no for inc in range(2, lmt, 2): if (found is False): break r1 = row + inc c1 = col + inc if (r1 > rows_no - 1 or c1 > cols_no - 1): break for i in range(row, r1 + 1): if (found is False): break for j in range(col, c1 + 1): if (matrix[i][j] == 0): found = False break if found: sq = ((row + r1)/2, (col + c1)/2, r1-row + 1) return sq
def normalize_cell(string, length): """Format string to a fixed length.""" return string + ((length - len(string)) * ' ')
def scaling_constant(n0, n1, nr, p): """ Determine the scaling constant. """ h0 = 0.5 ** (n0 * p) h1 = 0.5 ** (n1 * p) hr = 0.5 ** (nr * p) y = (h0 - hr) / (h1 - hr) return y
def log_error(error, log): """ - error: string - log: None or list of string RETURN: error string """ if log is not None: log.append(error) return error
def _option_boolean(arg): """Copied from matplotlib plot_directive.""" if not arg or not arg.strip(): # no argument given, assume used as a flag return True elif arg.strip().lower() in ('no', '0', 'false'): return False elif arg.strip().lower() in ('yes', '1', 'true'): return True else: raise ValueError('"%s" unknown boolean' % arg)
def format_size(size): """ Convert size to XB, XKB, XMB, XGB :param size: length value :return: string value with size unit """ units = ['B', 'KB', 'MB', 'GB'] unit = '' n = size old_n = n value = size for i in units: old_n = n x, y = divmod(n, 1024) if x == 0: unit = i value = y break n = x unit = i value = old_n return str(value)+unit
def get_in_turn_repetition(pred, is_cn=False): """Get in-turn repetition.""" if len(pred) == 0: return 1.0 if isinstance(pred[0], str): pred = [tok.lower() for tok in pred] if is_cn: pred = "".join(pred) tri_grams = set() for i in range(len(pred) - 2): tri_gram = tuple(pred[i:i + 3]) if tri_gram in tri_grams: return 1.0 tri_grams.add(tri_gram) return 0.0
def std_value(x: float, m_x: float, s_x: float) -> float: """ This function computes standardized values of a sequence value given its mean and standard deviation. """ return (x - m_x) / s_x
def quadratic(x, a, b, c): """General quadratic function""" return a*x**2 + b*x + c
def finding_gitlab_forks(fork_user): """ fork_user: Takes a repository to user_count dictionary map purpose: calculates how much gitlab forks are there among all the forks """ total_forks = 0 gitlab_forks = 0 gitlab_url = [] for fu in fork_user: total_forks += 1 if 'https://gitlab.com/' in fu: gitlab_url.append(fu) gitlab_forks += 1 return total_forks, gitlab_forks, gitlab_url
def plot(ax, interval, valid, tmpf, lines, mydir, month): """ Our plotting function """ if len(lines) > 10 or len(valid) < 2 or (valid[-1] - valid[0]) < interval: return lines if len(lines) == 10: ax.text(0.5, 0.9, "ERROR: Limit of 10 lines reached", transform=ax.transAxes) return lines delta = (valid[-1] - valid[0]).total_seconds() i = tmpf.index(min(tmpf)) mylbl = "%s\n%id%.0fh" % (valid[0].year, delta / 86400, (delta % 86400) / 3600.) x0 = valid[0].replace(month=1, day=1, hour=0, minute=0) offset = 0 if mydir == 'below' and valid[0].month < 7 and month == 'all': offset = 366. * 86400. seconds = [((v - x0).total_seconds() + offset) for v in valid] lines.append(ax.plot(seconds, tmpf, lw=2, label=mylbl.replace("\n", " "))[0]) lines[-1].hours = round((valid[-1] - valid[0]).seconds / 3600., 2) lines[-1].days = (valid[-1] - valid[0]).days lines[-1].mylbl = mylbl lines[-1].period_start = valid[0] lines[-1].period_end = valid[-1] ax.text(seconds[i], tmpf[i], mylbl, ha='center', va='center', bbox=dict(color=lines[-1].get_color()), color='white') return lines
def get_antibody_type(antibody_type_string): """Generate mcf line for antibodyType""" if antibody_type_string in ['Nanobody', 'Nanobody (VNAR)']: return 'antibodyType: dcs:NanobodyAntibody' if antibody_type_string == 'Bispecific': return 'antibodyType: dcs:BispecificAntibody' if antibody_type_string == 'Bispecific, Nanobody': return 'antibodyType: dcs:NanobodyAntibody,dcs:BispecificAntibody' # antibody_type_string == 'Darpin': return 'antibodyType: dcs:DarpinAntibody'
def _profile_tag_from_conditions(conditions): """ Given a list of conditions, return the profile tag of the device rule if there is one """ for c in conditions: if c['kind'] == 'device': return c['profile_tag'] return None
def get_output(digit_list): """ >>> get_output([1,2,3]) '123' """ return ''.join([str(i) for i in digit_list])
def myadd(first, last): """Create column headings""" if 'regression' in first: output = first else: output = first + ' (' + last + ')' return output
def _num_extracted_rows_and_columns( image_size: int, patch_size: int, stride: int, num_scales: int, scale_factor: int, ) -> int: """The number of rows or columns in a patch extraction grid.""" largest_patch_size = int(patch_size * (scale_factor**(num_scales - 1))) residual = image_size - largest_patch_size return (residual // stride) + 1
def removeElt(items, i): """ non-destructively remove the element at index i from a list; returns a copy; if the result is a list of length 1, just return the element """ result = items[:i] + items[i + 1:] if len(result) == 1: return result[0] else: return result
def build_uniform_beliefs(num_agents): """ Build uniform belief state. """ return [i/(num_agents - 1) for i in range(num_agents)]
def three_measurement_window_sum(list_int): """ This function calculates the sums of all three-measurement sliding windows in the list. This is part of the answer to the second puzzle. Parameters: list_int (list): list of measurements(integers) Returns: new_list (list): list of sums of all three-measurement sliding windows (integers). """ new_list = [] for i in range(len(list_int) - 2): window_value = list_int[i] + list_int[i + 1] + list_int[i + 2] new_list.append(window_value) return new_list
def center_of_points_list(points: list) -> tuple: """Calculates the center (average) of points in a list.""" # Extract all x coordinates from list of points (odd list positions) coordinates_x = points[::2] # Extract all y coordinates from list of points (even list positions) coordinates_y = points[1::2] return sum(coordinates_x) / len(coordinates_x), sum(coordinates_y) / len(coordinates_y)
def build_first_number_with(digits_sum): """ Build the smallest number (f_value) with given digits sum. :param digits_sum: :return: list of digits in reverse order for digits sum 20 returns: [9, 9, 2], for digits_sum 45 returns : [9, 9, 9, 9, 9] """ n9, d = divmod(digits_sum, 9) result = [9] * n9 if d != 0: result += [d] return result
def parse_lod_value(lod_key: str) -> str: """Extract the LoD value from an LoD parameter key (eg. lod13). For example 'lod13' -> '1.3' """ pos = lod_key.lower().find('lod') if pos != 0: raise ValueError(f"The key {lod_key} does not begin with 'lod'") value = lod_key[3:] if len(value) == 1: return value elif len(value) == 2: return f"{value[0]}.{value[1]}" else: raise ValueError(f"Invalid LoD value '{value}' in key {lod_key}")
def get_upper(somedata): """ Handle Python 2/3 differences in argv encoding """ result = "" try: result = somedata.decode("utf-8").upper() except: result = somedata.upper() return result
def _1_add_profile_uuid(config): """Add the required values for a new default profile. * PROFILE_UUID The profile uuid will be used as a general purpose identifier for the profile, in for example the RabbitMQ message queues and exchanges. """ for profile in config.get('profiles', {}).values(): from uuid import uuid4 profile['PROFILE_UUID'] = uuid4().hex return config
def get_chart_parameters(prefix='', rconn=None): """Return view, flip and rotate values of the control chart""" if rconn is None: return (100.0, False, 0.0) try: view = rconn.get(prefix+'view').decode('utf-8') flip = rconn.get(prefix+'flip').decode('utf-8') rot = rconn.get(prefix+'rot').decode('utf-8') except: return (100.0, False, 0.0) return float(view), bool(flip), float(rot)
def get_model_config(model): """Returns hyper-parameters for given mode""" if model == 'maml': return 0.1, 0.5, 5 if model == 'fomaml': return 0.1, 0.5, 100 return 0.1, 0.1, 100
def AsQuotedString(input_string): """Convert |input_string| into a quoted string.""" subs = [ ('\n', '\\n'), ('\t', '\\t'), ("'", "\\'") ] # Go through each substitution and replace any occurrences. output_string = input_string for before, after in subs: output_string = output_string.replace(before, after) # Lastly wrap the string in quotes. return "'%s'" % output_string
def _has_unclosed_parens(line): """ Assumes there's no more than one pair of parens (or just one "("), which is reasonable for import lines. """ if '(' in line: _, rest = line.split('(') return ')' not in rest return False
def _type_name(value): """ :param value: The value to get the type name of :return: A unicode string of the name of the value's type """ value_cls = value.__class__ value_module = value_cls.__module__ if value_module in set(['builtins', '__builtin__']): return value_cls.__name__ return '%s.%s' % (value_module, value_cls.__name__)
def chop_array(arr, window_size, hop_size): """chop_array([1,2,3], 2, 1) -> [[1,2], [2,3]]""" return [arr[i - window_size:i] for i in range(window_size, len(arr) + 1, hop_size)]
def std_action_map(sourceidx, action, labels): """Standard graphziv attributes used for visualizing actions. Computes the attributes for a given source, action index and action labeling. :param stateidx: The index of the source-state. :type stateidx: int :param action: The index of the action. :type destidx: int :param labels: labeling of the action. :type labels: set label :rtype: dict""" return { "node" : { "label" : "%s\n%s" % (action, "".join(labels)), "color" : "black", "shape" : "rectangle", "fontsize" : "18pt"}, "edge" : { "color" : "black", "dir" : "none" } }
def euler_problem_80(bound=100, keep_digits=100): """ It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all. The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is 475. For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots. """ # idea: one could get to 100 digits easily with binary search. # here however... just use decimal. from decimal import Decimal, getcontext from math import log # make sure that the decimals have enough significant digits getcontext().prec = 5 + keep_digits + int(log(bound, 10)) def solve(): total_sum = 0 for num in range(1, bound + 1): decimal_sqrt = Decimal(num).sqrt() if decimal_sqrt != int(decimal_sqrt): digits_that_count = str(decimal_sqrt).replace(".", "")[:keep_digits] total_sum += sum(list(map(int, list(digits_that_count)))) return total_sum return solve()
def _solve_method_2(N, queries): """ This section right here uses some Pythonic optimizations, but they still don't cut on speed. This at least is much faster I think, assuming each of these operations is atomic. """ arr = [0] * N largest = -1 for query in queries: from operator import add difference = abs(query[0] - (query[1]+1)) temp_arr = [query[2]] * difference temp_arr_2 = arr[query[0]-1:query[1]] arr[query[0]-1:query[1]] = list(map(add, temp_arr_2, temp_arr)) return max(arr)
def writefile(filename, data, mode=None, encoding=None): """mode: None=datatype (default), 'b'=binary data, 't'=text data """ if mode is None: mode = 't' if isinstance(data, str) else 'b' if mode != 't' and mode != 'b': raise ValueError('Unexpected mode {0!r}, expected \'b\' or \'t\''.format(mode)) args = () if encoding is None else (encoding,) with open(filename, 'w{0}+'.format(mode), *args) as f: count = f.write(data) f.flush() return count
def sarray2iarray(S): """Convert an string array/list to iarray, replace non-int by""" out=[] for s in S: try: r=int(float(s)) except: r=None out.append(r) return out
def find_delta(a, b, c): """ Function that returns the delta of a quadratic equation. """ if a == 0: raise ValueError("a is 0! [y = ax^2 + bx + c , a != 0]") delta = b**2 - 4*a*c return delta
def format_buttons(buttons): """ In the typical Facebook response message, it sends back pressable buttons. We don't really care that much about that for the testing(for now). We just want to be sure that we're sending pictures/text properly. Returns a list. """ if not buttons: return [] formatted_buttons = [] for button in buttons: postback = button.url if button.type == 'web_url' else button.payload button_object = { "text": button.title, "type": button.type, "postback": postback } formatted_buttons.append(button_object) return formatted_buttons
def stuff(string,symbol,number): """ Add number copies of symbol to string Returns modified string. """ for i in range(number): string += symbol string += " " return string
def parse_task_full_content(full_content): """ Return a tuple (title, content) extracted from the content found in a file edited through `todo edit` or `todo add [<title>] --edit` """ title, content = '', None state = 'title' lines = full_content.splitlines(keepends=True) for i, line in enumerate(lines): if state == 'title' and line.startswith('==='): state = 'content' continue if state == 'title': title += line elif state == 'content': if content is None: content = '' content += line # Removes blank characters at the right of the title (newline leading to # settext heading underlining and potential newline added by text editors) title = title.rstrip() return title, content
def color_to_pixel(color): """Turns RGB color value to pixel value.""" red = color[0] green = color[1] blue = color[2] alpha = 0 if len(color) == 4: alpha = color[3] return ((((red)) << 24) | # noqa: W504 (((green)) << 16) | # noqa: W504 (((blue)) << 8) | # noqa: W504 ((alpha))) # noqa: W504
def bounding_box2D(pts): """ Rectangular bounding box for a list of 2D points. Args: pts (list): list of 2D points represented as 2-tuples or lists of length 2 Returns: x, y, w, h (floats): coordinates of the top-left corner, width and height of the bounding box """ dim = len(pts[0]) # should be 2 bb_min = [min([t[i] for t in pts]) for i in range(dim)] bb_max = [max([t[i] for t in pts]) for i in range(dim)] return bb_min[0], bb_min[1], bb_max[0] - bb_min[0], bb_max[1] - bb_min[1]
def Prime_Factorization(x): """ Gives the list of all prime factors of the number. """ lst=[] cycle=2 while cycle<=x: if x%cycle==0: x/=cycle lst.append(cycle) else: cycle+=1 return lst
def get_price(sellers,formula,total_we_profit=0): """ sellers is a list of lists where each list contains follwing item in order 1. Seller Name 2. Number of cores 3. Price of each core If formula is 1 then curernt total profit should be subtracted from numberator total_we_profit is the "curernt total profit" to be subtracted return the price of 1 core to be charged from buyer by we """ total_price=0 available_resource_cnt=0 for i in sellers: #the product gives the price of sellers total core total_price+=i[1]*i[2] available_resource_cnt+=i[1] return max((float(total_price-(formula*total_we_profit))/available_resource_cnt),1)
def sort_shares_by_status(shares): """Sorts shares by status and returns a dict key'd by status type. :returns: tuple with the first part being the dictionary of shares keyed by their status, the second part being the auth users share. Example: ( {'ACCEPTED': [...], 'PENDING': [...]} ) """ share_by_status = {} for share in shares: if share.status in share_by_status: share_by_status[share.status].append(share) else: share_by_status[share.status] = [share] return share_by_status
def linear(a, b, c): """exec a * b + c""" print('exec linear') ret = a * b + c print('linear: %s * %s + %s = %s' % (a, b, c, ret)) return ret
def myfloat(value, prec=4): """ round and return float """ if value is None: return 0 return round(float(value), prec)
def pcall(func, *args, **kwargs): """ Calls a passed function handling any exceptions. Returns either (None, result) or (exc, None) tuple. """ try: return None, func(*args, **kwargs) except Exception as e: return e, None
def _check_native(tbl): """ Determine if Python's own native implementation subsumes the supplied case folding table """ try: for i in tbl: stv = chr(i) if stv.casefold() == stv: return False except AttributeError: return False return True