content
stringlengths
42
6.51k
def setup_config(config): """ This method is called so the config may be modified after it has been populated from the config file + env variables but before the connections/states are created. """ config['optional_1'] = 'optional_value_1' return config
def any_id2key(record_id): """ Creates a (real_id: int, thing: str) pair which allows ordering mixed collections of real and virtual events. The first item of the pair is the event's real id, the second one is either an empty string (for real events) or the datestring (for virtual ones) :param record_id: :type record_id: int | str :rtype: (int, str) """ if isinstance(record_id, int): return record_id, u'' (real_id, virtual_id) = record_id.split('-') return int(real_id), virtual_id
def reverse_bit(num): """Turn an LSB byte to an MSB byte, and vice versa. Used for SPI as it is LSB for the PN532, but 99% of SPI implementations are MSB only!""" result = 0 for _ in range(8): result <<= 1 result += (num & 1) num >>= 1 return result
def backslash(dir): """ Add '/' to the end of a path if not already the last character. Adds '/' to end of a path (meant to make formatting of directory path `dir` consistently have the slash). **Parameters** **dir** : string Path to a directory. **Returns** **out** : string Same as `dir`, with '/' appended to the end if not already there. """ if dir[-1] != '/': return dir + '/' else: return dir
def validateFilename(value): """ Validate filename. """ if 0 == len(value): raise ValueError("Filename for spatial database not specified.") return value
def rotation(r=0): """Set the display rotation Valid values: 0 90 180 270""" global _rotation if r in [0, 90, 180, 270]: _rotation = r return True else: raise ValueError('Rotation must be 0, 90, 180 or 270 degrees')
def messageCollector(collectedMessages, printMessages=False) : """Return a natsListener message collector to collect NATS messages into the `collectedMessages` dict provided. NATS messages stored in an list associated with each distinct message subject. """ if collectedMessages is None : return None if not isinstance(collectedMessages, dict) : return None async def collectMessage(aSubject, theSubject, theMessage) : """Collect all messages from all subjects for later analysis. Messages are collected into a list for each distinct theSubject. """ if hasattr(collectedMessages, 'unSettle') : await collectedMessages.unSettle() if printMessages : print("-------------------------------------------------------") print(aSubject) print(theSubject) print(theMessage) if theSubject not in collectedMessages : collectedMessages[theSubject] = [] theSubjectMessages = collectedMessages[theSubject] theSubjectMessages.append(theMessage) return collectMessage
def parse_asterisk(sequence, composites): """ parses a string like '*/*' and returns all available variants with '*' being replaced by composite names in 'composites'. """ sequences = [] for k in range(len(sequence)): if sequence[k] == '*': for c in composites: sequences += parse_asterisk(sequence[: k] + [c.name] + sequence[k + 1:], composites) if not sequences: sequences.append(sequence) return sequences
def tokenize(s): """Tokenize a string.""" ret = [] add = False digraph = False for c in s: if c in '[]<>$(){}=@~*': if digraph: ret[-1] += c digraph = False else: ret.append(c) add = False elif c == '|': if digraph: ret[-1] += c else: ret.append(c) digraph = True elif c.isspace(): add = False digraph = False elif add: ret[-1] += c else: ret.append(c) add = True return ret
def calculateFrameTime(speed, ratio): """ Calculates the frame time interval from chopper parameters. Chopper speed in rpm given, but calculations are in Hz. The interval is the time between pulses of chopper 5 because chopper 5 has only 2 slits returns the frame time in s """ speed /= 60.0 if speed == 0: return 0.052 # 2 * speed since we have 2 identical slits in chopper 5 return ratio / (2 * speed)
def exception_message(x, *args): """ """ x = x.replace('\n', ' ').replace('\t', '') return x.format(*args) if args else x
def interleave(list1, list2): """Convert two lists to a single interleaved list""" if len(list1) != len(list2): raise ValueError("Lists are not the same length") return [val for pair in zip(list1, list2) for val in pair]
def get_fraction(interval,bore_dict): """ calculate the clay fraction for a borehole. :param interval: a tuple (from_depth, to_depth ) :param bore_dict: dictionary {(from_depth, to_depth): lithology_type} :return: clay fraction for a bore hole in a specific interval """ clay_amount = 0 interval_len = interval[0]-interval[1] for bore_depth in bore_dict.keys(): if bore_dict[bore_depth] =="clay": if bore_depth[0] >= interval[0] and bore_depth[1] <= interval[1]: # cover the whole interval clay_amount = interval_len break elif bore_depth[1] >= interval[0] or bore_depth[0] <= interval[1]: # this segment is not in the interval continue elif bore_depth[0] <= interval[0] and bore_depth[1] >= interval[1]: # inside the interval clay_amount = clay_amount+(bore_depth[0]-bore_depth[1]) continue elif bore_depth[0] <= interval[0] and bore_depth[1] <= interval[1]: # partially overlapping, upper part of borehole is overlapping clay_amount = clay_amount + (bore_depth[0]-interval[1]) continue else: clay_amount += (interval[0]-bore_depth[1]) return clay_amount/interval_len
def normalize(bbox): """ Normalise EPSG:4326 bbox order. Returns normalized bbox, and whether it was flipped on horizontal axis. """ flip_h = False bbox = list(bbox) while bbox[0] < -180.0: bbox[0] += 360.0 bbox[2] += 360.0 if bbox[0] > bbox[2]: bbox = (bbox[0], bbox[1], bbox[2] + 360, bbox[3]) # bbox = (bbox[2],bbox[1],bbox[0],bbox[3]) if bbox[1] > bbox[3]: flip_h = True bbox = (bbox[0], bbox[3], bbox[2], bbox[1]) return bbox, flip_h
def duplicate(list_a: list): """Problem 14: Duplicate the Elements of a list. Parameters ---------- list_a : list The input list Returns ------- list A list of duplicated elements in order Raises ------ TypeError If the given argument is not of `list` type """ if not isinstance(list_a, list): raise TypeError('The argument given is not of `list` type.') duplicated = [] for x in list_a: duplicated.extend([x, x]) return duplicated
def strip_html(text): """ removes anything enclosed in and including <> """ import re return re.compile(r'<.*?>').sub('', text)
def format_references(section): """Format the "References" section.""" def format_item(item): return ' - **[{0}]** {1}'.format(item[0], item[1].strip()) return '!!! attention "References"\n{0}'.format('\n'.join( map(format_item, section)))
def remove_dup(words): """ remove duplicated words """ words = words.split(" ") prev_word = words[0] sentence = [prev_word] for w_idx in range(1, len(words)): cur_word = words[w_idx] if cur_word == prev_word: continue else: sentence.append(cur_word) prev_word = cur_word return " ".join(sentence)
def firewall_policy_payload(passed_keywords: dict) -> dict: """Create a properly formatted firewall policy payload. Supports create and update operations. Single policy only. { "resources": [ { "clone_id": "string", "description": "string", "name": "string", "platform_name": "Windows", } ] } """ returned_payload = {} resources = [] item = {} keys = ["clone_id", "description", "name", "platform_name"] for key in keys: if passed_keywords.get(key, None): item[key] = passed_keywords.get(key, None) resources.append(item) returned_payload["resources"] = resources return returned_payload
def check_candidates_against_protected(candidates, protected): """ use sets to check whether there is any common membership """ if bool(set(candidates) & set(protected)): return True else: return False
def prolog_escape(word): """escape Prolog meta characters""" return word.replace("\\","\\\\").replace("'","\\'")
def _slice_extent_axis(ext_min, ext_max, fctr): """Slice an extent into multiple extents along an axis.""" strd = (ext_max - ext_min) / fctr return [(ext_min + i * strd, ext_max - (fctr - i - 1) * strd) for i in range(fctr)]
def search(input, search_term="id", results=None): """Search through an input dictionary and return all the matches corresponding to a search term Parameters ---------- input: Dict The input dictionary. In the context of the Workflow Manager, this will probably be a json.dump of a workflow file search_term: Any Anything that can be used as a dictionary key results: List, optional A list storing the current results. Used when search is called recursively e.g. for a dict which has dicts as values. """ if not results: # Initial empty results list results = [] if isinstance(input, dict): for key, val in input.items(): if key == "id": results.append(val) # Search sub-iterables. Note: Don't search stings (even though # they are iterables!) if isinstance(val, (dict, list, set, tuple)): results = search(val, search_term, results) elif isinstance(input, (list, set, tuple)): for val in input: results = search(val, search_term, results) return results
def td_lambda(rewards, n_step, gamma): """ paper : ... + low variance - high bias """ return list(map( lambda i: sum(map(lambda t_r: t_r[1] * gamma**t_r[0], enumerate(rewards[i:i+n_step]))), range(len(rewards))))
def clean_append(part_1, part_2): """ Safely append 2 parts together, handling None :param part_1: :param part_2: :return: """ if part_1: if part_2: return part_1 + part_2 return part_1 return part_2
def conjugate(p): """ Find the conjugate of a partition. E.g. len(p) = max(conjugate(p)) and vice versa. """ result = [] j = len(p) if j <= 0: return result while True: result.append(j) while len(result) >= p[j-1]: j -= 1 if j == 0: return result
def int_to_little_endian(n, length): """endian_to_little_endian takes an integer and returns the little-endian byte sequence of length""" # use the to_bytes method of n return n.to_bytes(length, "little")
def michaelis_menten_eq(x, a, b): """Michaelis Mentent equation""" return a * x / (b + x)
def way_roy(routing, start, end): """Return the route from the start to the end as a list for the Roy-Warshall algorithm""" route = [] current_node = start while current_node != end: route.append(current_node) current_node = routing[current_node][end] # Follow the routing matrix route.append(end) return route
def format_cmd(cmd): """Return command in a valid format.""" if isinstance(cmd, str): cmd = [cmd] elif not isinstance(cmd, list): raise ValueError( "Command should be a list or a string and not {}".format(type(cmd)) ) return cmd
def __splitDegreeMinutes__(value): """ Transform DDDMM.MM to DDD, MM.MM """ val = str(value).split('.') val_min = val[0][-2] + val[0][-1] + '.' + val[1] val_deg = '' for i in range(len(val[0])-2): val_deg = val_deg + val[0][i] return int(val_deg), float(val_min)
def num_to_alpha(integ): """takes a numeral value and spits out the corresponding letter.""" translator = { 1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14: 'N', 15: 'O', 16: 'P', 17: 'Q', 18: 'R', 19: 'S', 20: 'T', 21: 'U', 22: 'V', 23: 'W', 24: 'X', 25: 'Y', 26: 'Z' } return translator[integ]
def make_get_bits(name, bits, shift): """ return a bool for single bits, signed int otherwise """ signmask = 1 << (bits - 1 + shift) lshift = bits + shift rshift = bits if bits == 1: return "bool(%s & 0x%x)" % (name, signmask) else: return "intmask(%s << (LONG_BIT-%d)) >> (LONG_BIT-%d)" % (name, lshift, rshift)
def normalize_dict(d): """Turn the dictionary values into percentages""" total = sum(d.values()) for k in d: d[k] = d[k] / total return d
def pixelscale_nyquist(wave, f_number): """Compute the output plane sampling which is Nyquist sampled for intensity. Parameters ---------- wave : float Wavelength in meters f_number : float Optical system F/# Returns ------- float Sampling in meters """ return f_number * wave / 2
def _is_subrange(rng1, rng2): """Return True iff rng1 is wholly inside rng2""" # Nonpolymers should have an empty range if rng1 == (None, None) or rng2 == (None, None): return rng1 == rng2 else: return rng1[0] >= rng2[0] and rng1[1] <= rng2[1]
def collinear(coordinates): """ Passing thru one pt with some fixed slope \implies must exist only one such line Rmk. If we are to use slope, we must deal separately with one particular case: Vertical line. """ def slope(A, B, epsilon=1e-10): denominator = A[0] - B[0] numerator = A[1] - B[1] if abs(denominator) < epsilon: return (numerator / epsilon) * (-1 if denominator < 0 else 1) else: return numerator / denominator A, B, C = coordinates if A[0] == B[0] == C[0]: return True print(f"A = {A}") print(f"B = {B}") print(f"C = {C}") epsilon = 1e-10 slope_AB = slope(A, B) slope_AC = slope(A, C) print(f"max(B[0] - A[0], epsilon) = {max(B[0] - A[0], epsilon)}") print(f"max(C[0] - A[0], epsilon) = {max(C[0] - A[0], epsilon)}") print(f"slope_AB = {slope_AB}") print(f"slope_AC = {slope_AC}") if abs(slope_AB - slope_AC) < epsilon: return True else: return False
def date_grouppings(date_read): """Extract date grouppings for given date.""" if date_read: year = date_read.year month = date_read.date().replace(day=1) else: year = None month = None return year, month
def _denormalize_mac(mac): """Takes a normalized mac address (all lowercase hex, no separators) and converts it to the TpLink format. Example:: _denormalize_mac('abcdef123456') == 'ab-cd-ef-12-34-56' """ return '-'.join((mac[i] + mac[i+1] for i in range(0, 12, 2)))
def dmp_zero(u): """ Return a multivariate zero. Examples ======== >>> from sympy.polys.densebasic import dmp_zero >>> dmp_zero(4) [[[[[]]]]] """ r = [] for i in range(u): r = [r] return r
def _latex_float(f, format=".3g"): """ http://stackoverflow.com/a/13490601 """ float_str = "{{0:{0}}}".format(format).format(f) if "e" in float_str: base, exponent = float_str.split("e") return r"{0}\times 10^{{{1}}}".format(base, int(exponent)) else: return float_str
def index_map(i, d): """ The index map used mapping the from 2D index to 1D index Parameters ---------- i : int, np.array the index in the 2D case. d : int the dimension to use for the 2D index. Returns ------- int, np.array 1D index. """ return 2 * i + d
def gini(sub_set): """Calculate the gini impurity.""" sub_set_len = len(sub_set) good = 0 for set_row in sub_set: if set_row[-1] > 6: good = good + 1 gini_impurity = 1 - (good / sub_set_len) ** 2 - ((sub_set_len - good) / sub_set_len) ** 2 return gini_impurity
def _mergeDiceDicts(d1, d2): """ A helper method, generally to be used with the "diceDict" method defined elsewhere. """ assert isinstance(d1, dict) and isinstance(d2, dict), "Invalid argument to mergeDiceDicts!" if len(d1) == 0: return d2 if len(d2) == 0: return d1 newDict = dict() for k1 in d1.keys(): for k2 in d2.keys(): newK = k1 + k2 # new key newV = d1[k1] * d2[k2] # number of ways of making newK # from the two given keys newDict[newK] = newDict.get(newK, 0) + newV # create/update # the new key in # the result return newDict
def escape_apply_kwargs(val): """Replace {} as {{}} so that val is preserved after _apply_kwargs.""" return val.replace('{', "{{").replace('}', "}}")
def render_field(field): """ Use this need tag to get more control over the layout of your forms {% raw %}{% render_field form.my_field %} {% endraw %} """ return {'field': field}
def fuseinterval(intervals, dist): """ Check if two intervals are adjacent if they are fuse it and return only one interval Args: intervals a list of intervals Return a list of intervals """ # if we have only one interval return it if len(intervals) == 1: return intervals # sort based on the coordinate of the end of the interval intervals = sorted(intervals, key=lambda interval: interval[1]) # go through interval, fuse the one that are adjacent fuseintervals = [] previnterval = intervals[0] # check adjacent intervals and merge them, return a list of intervals for interval in intervals[1:]: # adjacency: end of previous + 1 = start of current interval if int(previnterval[1]+50) >= int(interval[0]): previnterval[1] = interval[1] else: fuseintervals.append(previnterval) previnterval = interval # last element has to be appended too fuseintervals.append(previnterval) # reverse sort the interval, so that by # removing the vector sequence, the coordinates are # still actual. fuseintervals = sorted(fuseintervals, key=lambda interval: interval[1], reverse=True) # check how many intervals return fuseintervals
def doppler_shift(frequency, relativeVelocity): """ DESCRIPTION: This function calculates the doppler shift of a given frequency when actual frequency and the relative velocity is passed. The function for the doppler shift is f' = f - f*(v/c). INPUTS: frequency (float) = satlitte's beacon frequency in Hz relativeVelocity (float) = Velocity at which the satellite is moving towards or away from observer in m/s RETURNS: Param1 (float) = The frequency experienced due to doppler shift in Hz AFFECTS: None EXCEPTIONS: None DEPENDENCIES: ephem.Observer(...), ephem.readtle(...) Note: relativeVelocity is positive when moving away from the observer and negative when moving towards """ return (frequency - frequency * (relativeVelocity/3e8))
def version_id_kw(version_id): """Helper to make versionId kwargs. Not all boto3 methods accept a None / empty versionId so dictionary expansion solves that problem. """ if version_id: return {"VersionId": version_id} else: return {}
def make_desc_dict(ecfp): """ Format tuple of fingerprint information into dictionary :param ecfp: Tuple of fingerprint features and values :return: dictionary of fingerprint features and values """ ecfp_feat, ecfp_val = zip(*ecfp) return ecfp_feat, ecfp_val
def get_url(path, scheme="http"): """ Return the full InfoQ URL """ return scheme + "://www.infoq.com" + path
def make_patch_instructions(source_list: dict, target_list: dict): """ possible combinations file in both and same ignore file in both and different copy file only in target delete file only in source copy """ files_source = set(source_list) files_target = set(target_list) files_common = files_source.intersection(files_target) files_source_only = files_source - files_target files_target_only = files_target - files_source files_common_same = set(f for f in files_common if source_list[f] == target_list[f]) files_common_different = files_common - files_common_same files_copy = files_common_different.union(files_source_only) files_delete = files_target_only return {"copy": sorted(list(files_copy)), "delete": sorted(list(files_delete))}
def remove_duplicates(values): """ remove duplicate value in a list :param values: input list :return: no duplicate entry list """ output = [] seen = set() for value in values: # If value has not been encountered yet, # ... add it to both list and set. if value not in seen: output.append(value) seen.add(value) return output
def exif_image_needs_rotation(exif_tags): """ Returns True if EXIF orientation requires rotation """ return 'Image Orientation' in exif_tags \ and exif_tags['Image Orientation'].values[0] != 1
def tablefy_users(users): """ Build matrix that can be printed as table along with headers and urls Mimics the tablefy utility for the user model. Hard to use the other tablefy utility since we did not subclass user model """ headers = [] matrix = [] urls = [] if not users: return (None, None, None) # Build the headers headers = ['Name', 'First Name', 'Last Name', 'Email', 'Phone Number'] # Build the matrix and urls for user in users: urls.append('/cyuser/' + str(user.id)) matrix.append([ user.username, user.first_name, user.last_name, user.email, user.get_profile().phone_number ]) return (headers, matrix, urls)
def string_is_int(string): """ Returns true if a string can be cast to an int returns false otherwise """ try: int(string) return True except ValueError: return False
def logged_dict_update(log_func, left, right): """Update a dict with any changes tracked via `log_func`.""" for k, v in right.items(): if k in left and left[k] != v: log_func( f"entry changed" f" {k} {left[k]} -> {v}") left[k] = v return left
def name_to_components(name, factor=1, delimiter="_") -> dict: """Converts composition string to dictionary example: "MA_Pb0.5_Sn0.5_I3" -> {"MA":1, "Pb":0.5, "Sn":0.5, "I":3} Args: name (str): delimited string of composition factor (int, optional): factor by which to scale all component amounts. Defaults to 1. delimiter (str, optional): Defaults to "_". Returns: [dict]: Dictionary with key:value = component:amount """ components = {} for part in name.split(delimiter): species = part count = 1.0 for l in range(len(part), 0, -1): try: count = float(part[-l:]) species = part[:-l] break except: pass components[species] = count * factor return components
def getChange(current, previous): """Get the Percentage Change. Parameters: current (int): Current value previous (int): Previous value Returns: int: Percentage Change """ if current == previous: return 0 try: return ((current - previous) / previous) * 100.0 except ZeroDivisionError: return float('inf')
def quantize(x: int, q: int) -> int: """ Will quantize a continuous or discrete range into steps of q where anything between 0 and q will be clipped to q. """ return q * (x // q) if not 0 < x <= q else q
def get_percentage(position: int, length: int) -> str: """Format completion percentage in square brackets.""" percentage_message = f"{position * 100 // length}%".rjust(4) return f"[{percentage_message}]"
def split(n): """ Split string or Array >>> split("hello") ['he', 'llo'] >>> split([1,2,3,1,2,4]) [[1, 2, 3], [1, 2, 4]] """ return [ n[:len(n)//2:], n[len(n)//2::] ]
def kelvin(value): """ Convert Celsius to Kelvin """ return round(value + 273.15, 1)
def _between(input, values): """Checks if the given input is between the first two values in the list :param input: The input to check :type input: int/float :param values: The values to check :type values: :func:`list` :returns: True if the condition check passes, False otherwise :rtype: bool """ try: return input >= values[0] and input <= values[1] except IndexError: return False
def _gutenberg_simple_parse(raw_content): """Clean a project Gunteberg file content.""" content = raw_content # *** START OF THIS PROJECT GUTENBERG EBOOK THE RED BADGE OF COURAGE *** starts = [ '*** START OF THIS PROJECT GUTENBERG EBOOK', '***START OF THE PROJECT GUTENBERG EBOOK', '*** START OF THE PROJECT GUTENBERG EBOOK', '*END*THE SMALL PRINT! FOR PUBLIC DOMAIN', '*END THE SMALL PRINT! FOR PUBLIC DOMAIN', 'This etext was prepared by', 'This Etext was prepared by', 'This etext was provided by', 'This Etext prepared by ', '***START OF THIS PROJECT GUTENBERG EBOOK', ] # *** END OF THIS PROJECT GUTENBERG EBOOK THE RED BADGE OF COURAGE *** ends = [ '*** END OF THIS PROJECT GUTENBERG EBOOK', '***END OF THE PROJECT GUTENBERG EBOOK', '*** END OF THE PROJECT GUTENBERG EBOOK', 'End of Project Gutenberg Etext', 'End of this Project Gutenberg Etext', 'End of the Project Gutenberg Etext', 'End of The Project Gutenberg Etext', 'End of the Project Gutenberg etext', 'End of Project Gutenberg\'s Etext of ', 'END OF PROJECT GUTENBERG ETEXT OF ', '***END OF THIS PROJECT GUTENBERG EBOOK', ] has_start = any([s in content for s in starts]) has_end = any([e in content for e in ends]) if not has_start or not has_end: return None start_index = max([content.rfind(s) for s in starts]) end_index = min([content.find(e) % len(content) for e in ends]) # Strip the prefix: '*** START OF THIS PROJECT GUTENBERG EBOOK ***' _, content = content[start_index:end_index].split('\n', 1) return content
def shift_rows(state): """ Section 5.1.2: ShiftRows() Transformation !!! FUN FACT ALERT !!! Rotating a row by one position to the left is equivalent to polynomial multiplication by {01}x^3 + {00}x^2 + {00}x^1 + {00}x^0, modulo x^4 + 1 >>> shift_rows(b"ABCDefghIJKLmnop") bytearray(b'AfKpeJoDInChmBgL') """ s2 = bytearray(4 * 4) for i in range(4): row = state[i : 4 * 4 : 4] s2[i : 4 * 4 : 4] = row[i:] + row[:i] return s2
def sex2int(x): """ Converti sesso""" try: return int(x=='male') except: return -1
def __f_get_dictionary_file( home_profile_path ): """ Get the file path of the 3 stored statistic information dictionaries """ return home_profile_path + '/stat_info_ref.json', \ home_profile_path + '/stat_info_home.json', \ home_profile_path + '/stat_info_start.json'
def parse(input): """Simplified to return list of lists of ints""" return [[int(val) for val in row] for row in input]
def abs(x): """ Assuems x is an int Returns x if x>= 0 and -x otherwise """ if x < -1: return -x else: return x
def nth_triangle_number(n): """ Compute the nth triangle number """ return n * (n + 1) // 2
def get_task_and_ann_id(ex): """ single string for task_id and annotation repeat idx """ return "%s_%s" % (ex["task_id"], str(ex["repeat_idx"]))
def handle_most_used_outputs(most_used_x): """ :param most_used_x: Element or list (e.g. from SQL-query output) which should only be one element :return: most_used_x if it's not a list. The first element of most_used_x after being sorted if it's a list. None if that list is empty. """ if isinstance(most_used_x, list): if len(most_used_x) == 0: return None most_used_x.sort() return most_used_x[0] else: return most_used_x
def order(lst): """ Returns a new list with the original's data, sorted smallest to largest. """ ordered = [] while len(lst) != 0: smallest = lst[0] for i in range(len(lst)): if lst[i] < smallest: smallest = lst[i] ordered.append(smallest) lst.remove(smallest) return ordered
def conjugatePartition(p): """ Find the conjugate of a partition. E.g. len(p) = max(conjugate(p)) and vice versa. D. Eppstein, August 2005. """ p = sorted(filter(lambda x: x > 0, p), reverse=True) result = [] j = len(p) if j <= 0: return result while True: result.append(j) while len(result) >= p[j-1]: j -= 1 if j == 0: return result
def ten(hour_or_deg, minute=0.0, second=0.0): """ Converts a sexagesimal number to decimal IDL version can process string, but not in this version If h/d, m, and s are all scalar, the result is scalar, else an ndarray ** For negative value, h/d, m, and s MUST all be negative ** :param hour_or_deg: :param minute: :param second: :return: decimal value(s) """ return hour_or_deg + minute / 60.0 + second / 3600.0
def percent_conv(val): """Convert an actual percentage (0.0-1.0) to 0-100 scale.""" if val is None: return None return round(val * 100.0, 1)
def taxe(solde, pourcentage): """Affiche la somme de la taxe en fonction du pourcentage """ taxe = dict() taxe["taxe"] = solde * pourcentage taxe["new solde"] = solde - taxe["taxe"] return taxe
def int_or_float(s): """ Modbus can't handle decimals, so we multiply any float by 10. :param s: string representation of a numeric value. :return: int """ try: return int(s) except ValueError: # if we have a float, # protocol requires multiply by 10 and cast to int return int(float(s) * 10)
def line_intersection(line1, line2): """ get intersection of two lines :param line1: x1, y1 :param line2: x2, y2 :return: x, y of the intersection """ # https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines/20679579 xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) def det(a, b): return a[0] * b[1] - a[1] * b[0] div = det(xdiff, ydiff) if div == 0: raise Exception('lines do not intersect') d = (det(*line1), det(*line2)) x = det(d, xdiff) / div y = det(d, ydiff) / div return x, y
def get_errno(e): """ Return the errno of an exception, or the first argument if errno is not available. :param e: the exception object """ try: return e.errno except AttributeError: return e.args[0]
def one_obj_or_list(seq): """If there is one object in list - return object, otherwise return list""" if len(seq) == 1: return seq[0] return seq
def if_(*args): """Implements the 'if' operator with support for multiple elseif-s.""" for i in range(0, len(args) - 1, 2): if args[i]: return args[i + 1] if len(args) % 2: return args[-1] else: return None
def pyintbitcount(a): """Return number of set bits (1s) in a Python integer. >>> pyintbitcount(0b0011101) 4""" cnt = 0 while a: a &= a - 1 cnt += 1 return cnt
def checksum(number): """Calculate the checksum over the number. A valid number should have a checksum of 0.""" return (sum((9 - i) * int(n) for i, n in enumerate(number[:-1])) - int(number[-1])) % 11
def gettext(nodelist): """ get text data from nodelist """ result = "" for node in nodelist: if node.nodeType == node.TEXT_NODE or node.nodeType == node.CDATA_SECTION_NODE: stripped = node.data.strip() if stripped: result += stripped return result
def isMAGPYABS(filename): """ Checks whether a file is ASCII DIDD (Tihany) format. """ try: temp = open(filename, 'rt') line = temp.readline() line = temp.readline() except: return False if not line.startswith('Miren'): return False return True
def compareThresh(value,threshold,mode,inclusive, *, default=False): """Returns a boolean only if value satisfies the threshold test. In case of failure of any sort, returns the default value (which defaults to 'False'). Accepted mode values are '<', '>', '<=' and '>='.""" #normalizing input if inclusive: if mode == ">": mode = ">=" elif mode == "<": mode = "<=" if mode == "<": return value < threshold elif mode == ">": return value > threshold elif mode == "<=": return value <= threshold elif mode == ">=": return value >= threshold return default
def model_set(model): """Converts a model from a dictionary representation to a set representation. Given a ``model`` represented by a dictionary mapping atoms to Boolean values, this function returns the *set* of atoms that are mapped to ``True`` in the dictionary. Paramters --------- model : A dictionary mapping atoms to Boolean values. Example ------- >>> p,q,r = [eb.parse_formula(letter) for letter in "pqr"] >>> eb.model_set({p: True, q: False, r: True}) set([p, r]) """ return set([atom for atom in model if model[atom] == True])
def negative_exist(arr: list) -> int: """ >>> negative_exist([-2,-8,-9]) -2 >>> [negative_exist(arr) for arr in test_data] [-2, 0, 0, 0, 0] """ arr = arr or [0] max = arr[0] for i in arr: if i >= 0: return 0 elif max <= i: max = i return max
def conv_alphapos(pos, num_cols): """ Converts a position to a letter and number pos: int """ col = pos % num_cols row = pos // num_cols return "{}{}".format(chr(ord("a") + col), row + 1)
def _list_type(output, searchresults): """for each key in searchresults, format output for key and val list""" for key, val in searchresults.items(): output += '\t{}\n'.format(key) for v in val: output += '\t\t{}\n'.format(v) return output
def sort_by_index(a, idx, reverse=False): """ Sort an array of array by index Input: a: a 2D array, e.g., [[1, "a"], [2, "b"]] idx: the index to sort the arrays inside the array, e.g., 0 """ return sorted(a, key=lambda t: t[idx], reverse=reverse)
def format_number(number): """standardizes numbers in contacts""" chars_to_remove = " ()-" for char in chars_to_remove: number = number.replace(char, "") if number[0:2] != '+1': number = '+1' + number return number
def split_every_n_characters(n: int, s: str) -> list: """Split a string every `n` characters. :param n: the number that determines the length of output strings :param s: any string :return: a list of strings where all of them are `n` characters long (except the last one) :link: https://stackoverflow.com/a/9475354 """ return [s[i:i+n] for i in range(0, len(s), n)]
def numDecodings(s): """ :type s: str :rtype: int """ if s == '': return 1 if s[0] == '0': return 0 if len(s) == 1: return 1 dp = [0] * (len(s) - 1) for i in range(1, len(s)): if s[i] == '0' and (s[i - 1] > '2' or s[i - 1] == '0'): return 0 elif s[i] == '0' and (s[i - 1] == '2' or s[i-1] == '1'): dp[i - 1] = dp[i - 2] if i == 1 and s[:i + 1] <= '26': dp[0] = 2 elif i == 1 and s[:i+1] > '26': dp[0] = 1 if i > 1 and '10' <= s[i - 1:i+1] <= '26': dp[i - 1] = dp[i - 2] + 1 elif i > 1 and s[i-1:i+1] < '10' or s[i-1:i+1] > '26': dp[i - 1] = dp[i - 2] return dp
def ascii_pattern(value): """ Build an "object" that indicates that the ``pattern`` is an ASCII string """ return {'type':'ascii', 'value':value}
def _eval_meta_as_summary(meta): """some crude heuristics for now most are implemented on bot-side with domain whitelists""" if meta == '': return False if len(meta)>500: return False if 'login' in meta.lower(): return False return True
def encode_uvarint(number: int) -> bytes: """Pack `number` into varint bytes""" buf = b"" while True: towrite = number & 0x7F number >>= 7 if number: buf += bytes((towrite | 0x80,)) else: buf += bytes((towrite,)) break return buf
def solution(string) -> str: """ reverses the string value passed into it :param string: :return: """ return string[::-1]