content
stringlengths
42
6.51k
def create_vreddit_url(submission, reddit): """Read video url from reddit submission""" try: return str(submission.media['reddit_video']['fallback_url']) except Exception as e: # Submission is a crosspost try: crosspost_id = submission.crosspost_parent.split('_')[1] s = reddit.submission(crosspost_id) return s.media['reddit_video']['fallback_url'] except Exception as f: print(f) print("Can't read vreddit url, skipping") return ""
def humantime(seconds, ndigits=2, one_hour_digit=False): """Format a duration as a human readable string. The duration in seconds (a nonnegative float) is formatted as ``HH:MM:SS.frac``, where the number of fractional digits is controlled by `ndigits`; if `ndigits` is 0, the decimal point is not printed. The number of hour digits (``HH``) can be reduced to one with the `one_hour_digits` option. Parameters ---------- seconds : float Duration in seconds, must be nonnegative. ndigits : int, optional Number of digits after the decimal point for the seconds part. Default is 2. If 0, the decimal point is suppressed. one_hour_digit : bool, optional If ``True``, only print one hour digit (e.g., nine hours is printed as 9:00:00.00). Default is ``False``, i.e., two hour digits (nine hours is printed as 09:00:00.00). Returns ------- human_readable_duration : str Raises ------ ValueError: If `seconds` is negative. Examples -------- >>> humantime(10.55) '00:00:10.55' >>> humantime(10.55, ndigits=1) '00:00:10.6' >>> humantime(10.55, ndigits=0) '00:00:11' >>> humantime(10.55, one_hour_digit=True) '0:00:10.55' >>> # two hours digits for >= 10 hours, even if one_hour_digit is >>> # set to True >>> humantime(86400, one_hour_digit=True) '24:00:00.00' >>> humantime(-1) Traceback (most recent call last): ... ValueError: seconds=-1.000000 is negative, expected nonnegative value """ # pylint: disable=invalid-name if seconds < 0: raise ValueError("seconds=%f is negative, " "expected nonnegative value" % seconds) hh = int(seconds) // 3600 # hours mm = (int(seconds) // 60) % 60 # minutes ss = seconds - (int(seconds) // 60) * 60 # seconds hh_str = "%01d" % hh if one_hour_digit else "%02d" % hh mm_str = "%02d" % mm if ndigits == 0: ss_str = "%02d" % round(ss) else: ss_format = "%0{0}.{1}f".format(ndigits + 3, ndigits) ss_str = ss_format % ss return "%s:%s:%s" % (hh_str, mm_str, ss_str)
def get_all_files_of_same_type(experiments, filtered_csvs): """ Returns ------- dict_holding_files_and_run_types: dict A dictionary of different experiment types as keys along with the paths to experimental results for that key across different seeds. """ dict_holding_files_and_run_types = {} for a_run_type in experiments: all_files_of_run_type = [] for csv_file in filtered_csvs: if a_run_type in csv_file: all_files_of_run_type.append(csv_file) dict_holding_files_and_run_types[a_run_type] = all_files_of_run_type return dict_holding_files_and_run_types
def _get_cores_and_type(config, fc_dir, run_info_yaml, numcores=None, paralleltype=None): """Return core and parallelization approach from commandline. Prefers passed commandline parameters over pre-configured, defaulting to a local run on a single core. """ config_cores = config["algorithm"].get("num_cores", None) if config_cores: try: config_cores = int(config_cores) if numcores is None: numcores = config_cores except ValueError: if paralleltype is None: paralleltype = config_cores if paralleltype is None: paralleltype = "local" if numcores is None: numcores = 1 return paralleltype, int(numcores)
def max_digits(x): """ Return the maximum integer that has at most ``x`` digits: >>> max_digits(4) 9999 >>> max_digits(0) 0 """ return (10 ** x) - 1
def remote_bazel_options(crosstool_top): """Returns bazel options for the "remote" execution strategy.""" k8 = [ "--cpu=k8", "--host_cpu=k8", "--crosstool_top=" + crosstool_top, "--define=EXECUTOR=remote", ] return k8 + [ "--spawn_strategy=remote", "--genrule_strategy=remote", ]
def truedicts(all): """ Generates a pair of dictionairies containg all true tail and head completions. :param all: A list of 3-tuples containing all known true triples :return: """ heads, tails = {(p, o) : [] for _, p, o in all}, {(s, p) : [] for s, p, _ in all} for s, p, o in all: heads[p, o].append(s) tails[s, p].append(o) return heads, tails
def get_obs_projects(): """ Return a list of strings with the names of observations projects. Please keep this list up to date, or replace it with something more sensible. Returns --------- list Returns a list of strings of the various types of observational data. """ obs_projects = [ 'obs4mips', ] return obs_projects
def demo_app_name(name): """ Returns a capitalized title for the app, with "Dash" in front.""" return 'Dash ' + name.replace('app_', '').replace('_', ' ').title()
def _sort_string_value(sort_type: int) -> str: """ Returns the string corresponding to the sort type integer :param sort_type: :return: """ if sort_type not in {0, 1, 2, 3}: raise ValueError(f"Sort Number '{sort_type}' Is Invalid -> Must Be 0, 1, 2 or 3") else: sort_dict = {0: 'project', 1: 'dueDate', 2: 'title', 3: 'priority'} return sort_dict[sort_type]
def lfnToPFN( path, tfcProt = 'rfio'): """Converts an LFN to a PFN. For example: /store/cmst3/user/cbern/CMG/TauPlusX/Run2011A-03Oct2011-v1/AOD/V2/PAT_CMG_V2_4_0/H2TAUTAU_Nov21 -> root://eoscms//eos/cms/store/cmst3/user/cbern/CMG/TauPlusX/Run2011A-03Oct2011-v1/AOD/V2/PAT_CMG_V2_4_0/H2TAUTAU_Nov21?svcClass=cmst3&stageHost=castorcms This function only checks path, and does not access the storage system. If the path is in /store/cmst3, it assumes that the CMST3 svcClass is to be used. Otherwise, is uses the default one. ??? what is tfcprot? """ if path.startswith("/store/"): path = path.replace("/store/","root://eoscms.cern.ch//eos/cms/store/") elif path.startswith("/pnfs/psi.ch/cms/trivcat/"): path = path.replace("/pnfs/psi.ch/cms/trivcat/","root://t3se01.psi.ch//") if ":" in path: pfn = path else: pfn = "file:"+path return pfn
def sublist_indices(sub, full): """ Returns a list of indices of the full list that contain the sub list :param sub: list :param full: list :return: list >>> sublist_indices(['Felix'], ['De', 'kat', 'genaamd', 'Felix', 'eet', 'geen', 'Felix']) [[3], [6]] >>> sublist_indices( ['Felix', 'Maximiliaan'], ['De', 'kat', 'genaamd', 'Felix', 'Maximiliaan', 'eet', 'geen', 'Felix'] ) [[3, 4]] """ if sub == []: return [] if full == []: return [] found = [] for idx, item in enumerate(full): if item == sub[0]: if len(sub) == 1: found.append([idx]) else: match = True for i, s in enumerate(sub[1:]): if len(full) > idx + i + 1: if s != full[idx + i + 1]: match = False else: match = False if match: found.append(list(range(idx, idx + len(sub)))) return found
def add_zero(number): """ Add a zero if the value doesn't have 2 digits behind it's decimal point """ if number == '': return '' else: list_number = list(str(number)) if len(list_number[list_number.index('.') + 1:]) < 2: list_number.append('0') return ''.join(list_number)
def time_to_frame(time_s, fs=250): """Convert time in second to frame""" return int(round(time_s * fs))
def fit_text(width, text, center=False): """Fits text to screen size Helper function to fit text within a given width. Used to fix issue with status/title bar text being too long Parameters ---------- width : int width of window in characters text : str input text center : Boolean flag to center text Returns ------- fitted_text : str text fixed depending on width """ if width < 5: return '.' * width if len(text) >= width: return text[:width-5] + '...' else: total_num_spaces = (width - len(text) - 1) if center: left_spaces = int(total_num_spaces/2) right_spaces = int(total_num_spaces/2) if(total_num_spaces % 2 == 1): right_spaces = right_spaces+1 return ' ' * left_spaces + text + ' ' * right_spaces else: return text + ' ' * total_num_spaces
def repr_args(args, dlim=", ", start=None): """ Represent arguments. Parameters ---------- args : Iterable[Any] Arguments. dlim : str, optional Delimiter. The default is ", ". start : str, optional Start of return value. Defaults to delimiter value. Examples -------- >>> repr_args([1, 2]) ', 1, 2' >>> repr_args([1, 2], start="") '1, 2' """ if args: return (start if start is not None else dlim) + dlim.join([repr(value) for value in args]) else: return ""
def is_dict_like(obj, attr=('keys', 'items')): """test if object is dict like""" for a in attr: if not hasattr(obj, a): return False return True
def flatten(array): """Flattens a list of lists. e.g. [[1, 2, 3], [4, 5, 6]] --> [1, 2, 3, 4, 5, 6] """ flat = [] for element in array: flat.extend(element) return flat
def normalize_upload(upload): """ For Recipe System v2.0, upload shall now be a list of things to send to fitsstore. E.g., $ reduce --upload metrics <file.fits> <file2.fits> $ reduce --upload metrics, calibs <file.fits> <file2.fits> $ reduce --upload metrics, calibs, science <file.fits> <file2.fits> Result in upload == ['metrics'] upload == ['metrics', 'calibs'] upload == ['metrics', 'calibs', 'science'] :parameter upload: upload argument received by the reduce command line. :type upload: <list> :return: list of coerced or defaulted upload instructions. :rtype: <list> """ if upload and isinstance(upload, list): splitc = upload if len(upload) > 1 else upload[0].split(',') return [c.lower() for c in splitc] elif upload is None: pass else: raise TypeError("upload must be None or a list") return
def FormatSeconds(secs): """Formats seconds for easier reading. @type secs: number @param secs: Number of seconds @rtype: string @return: Formatted seconds (e.g. "2d 9h 19m 49s") """ parts = [] secs = round(secs, 0) if secs > 0: # Negative values would be a bit tricky for unit, one in [("d", 24 * 60 * 60), ("h", 60 * 60), ("m", 60)]: (complete, secs) = divmod(secs, one) if complete or parts: parts.append("%d%s" % (complete, unit)) parts.append("%ds" % secs) return " ".join(parts)
def search(f): """Return the smallest non-negative integer x for which f(x) is a true value.""" x = 0 while True: if f(x): return x x += 1
def next_player(player_id): """ Determine who should play next based on current player. """ if player_id == 1: return 2 return 1
def subdivise(tiles, zoom_current, zoom_target): """ Subdivise a list of tiles at level zoom_current into tiles at level zoom_target. """ coords = list() ratio = 2 ** (zoom_target - zoom_current) for x, y in tiles: for X in range(ratio): for Y in range(ratio): coords.append((x * ratio + X, y * ratio + Y, zoom_target)) return coords
def is_serial_increased(old, new): """ Return true if serial number was increased using RFC 1982 logic. """ old, new = (int(n) for n in [old, new]) diff = (new - old) % 2**32 return 0 < diff < (2**31 - 1)
def reverse(s): """Return the sequence string in reverse order.""" letters = list(s) letters.reverse() return ''.join(letters)
def is_url(word): """ Lazy check if a word is an url. True if word contains all of {':' '/' '.'}. """ return bool(set('./:').issubset(word))
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def interpret_line(line, splitter=','): """ Split text into arguments and parse each of them to an appropriate format (int, float or string) Args: line: text line splitter: value to split by Returns: list of arguments """ parsed = [] elms = line.split(splitter) for elm in elms: try: # try int el = int(elm) except ValueError as ex1: try: # try float el = float(elm) except ValueError as ex2: # otherwise just leave it as string el = elm.strip() parsed.append(el) return parsed
def histogram_flat ( flatness, q_min, q_max, h ): """Returns a signal that the histogram is sufficiently flat.""" # We only look at the histogram in the range of q visited during the run # The flatness parameter should be in (0,1), higher values corresponding to flatter histograms import numpy as np assert flatness > 0.0 and flatness < 1.0, 'Flatness error' avg = np.average(h[q_min:q_max+1]) assert avg >= 0.0, 'Error in h' return np.amin(h[q_min:q_max+1]) > flatness*avg
def _compress_condition_keys_only(data: dict) -> dict: """ a function that merges a condition key node with its only child (a token that has an int value) """ # this has been found heuristically. There's no way to explain it, just follow the test cases. # there's probably a much easier way, f.e. by using a separate token schema. if "tree" in data and data["tree"] is not None and data["tree"]["type"] == "condition_key": return { "token": {"value": data["tree"]["children"][0]["token"]["value"], "type": "condition_key"}, "tree": None, } if ( "token" in data and data["token"] is None and "tree" in data and data["tree"] is not None and "children" in data["tree"] ): data["tree"]["children"] = [_compress_condition_keys_only(child) for child in data["tree"]["children"]] if "type" in data and data["type"] is not None and "children" in data and data["children"] is not None: data["children"] = [_compress_condition_keys_only(child) for child in data["children"]] return data
def build_s3_url(filenames, bucket): """ convert filenames to AWS S3 URLs params: bucket: string, AWS S3 bucket name filenames: list of strings, AWS S3 filenames """ s3_urls = [] for f in filenames: s3_urls.append('https://{}.s3.amazonaws.com/{}'.format(bucket, f)) return s3_urls
def truncate_to_significant_bits(input_x: int, num_significant_bits: int) -> int: """ Truncates the number such that only the top num_significant_bits contain 1s. and the rest of the number is 0s (in binary). Ignores decimals and leading zeroes. For example, -0b011110101 and 2, returns -0b11000000. """ x = abs(input_x) if num_significant_bits > x.bit_length(): return x lower = x.bit_length() - num_significant_bits mask = (1 << (x.bit_length())) - 1 - ((1 << lower) - 1) if input_x < 0: return -(x & mask) else: return x & mask
def array_to_string(s): """gets a printable string for a string array.""" return ", ".join(s)
def sanitize_webscrape_name(name): """ Sanitizes webscrape powerplant names by removing unwanted strings (listed in blacklist), applying lower case, and deleting trailing whitespace. Parameters ---------- name: str webscrape plant name Returns ------- name: str sanitized name for use with fuzzywuzzy """ blacklist = ['nuclear', 'power', 'plant', 'generating', 'station', 'reactor', 'atomic', 'energy', 'center', 'electric'] name = name.lower() for blacklisted in blacklist: name = name.replace(blacklisted, '') name = name.strip() name = ' '.join(name.split()) return name
def problem1(individual): """ Implements the first test problem ("bi-objetive Sphere Model"). Variables = 2 Objetives = 2 f(x) = (x'x, (x - a)'(x - a))' with a = (0, 1)' and a, x element of R^2. Bounds [0, 1] @author Cesar Revelo """ a = [0,1] f1 = (individual[0] ** 2) + (individual[1] ** 2) f2 = ((individual[0] - a[0]) ** 2) + ((individual[1] - a[1]) ** 2) return f1, f2
def normalized_value(xs): """ normalizes a list of numbers :param xs: a list of numbers :return: a normalized list """ minval = min(xs) maxval = max(xs) minmax = (maxval-minval) * 1.0 return [(x - minval) / minmax for x in xs]
def hexcolor_to_rgbcc(hexcolor): """ Converts an Hex color to its equivalent Red, Green, Blue Converse = hexcolor = (r << 16) + (g << 8) + b """ r = (hexcolor >> 16) & 0x7F g = (hexcolor >> 8) & 0x7F b = hexcolor & 0x7F return r, g, b
def is_randomized(key): """ Helper to determine if the key in the state_dict() is a set of parameters that is randomly initialized. Some weights are not randomly initalized and won't be afffected by seed, particularly layer norm weights and biases, and bias terms in general. """ # regexes for components that are not randomized print(key) if key.endswith("bias") or "ln" in key: return False else: return True
def normalize_TD_data(data, data_zero, data_one): """ Normalizes measured data to refernce signals for zero and one """ return (data - data_zero) / (data_one - data_zero)
def batch_eval(k_function, batch_iterable): """ eval a keras function across a list, hiding the fact that keras requires you to pass a list to everything for some reason. """ return [k_function([bx]) for bx in batch_iterable]
def ascii_lower(string): """Lower-case, but only in the ASCII range.""" return string.encode('utf8').lower().decode('utf8')
def L90_indicator(row): """ Determine the indicator of L90 as one of five indicators """ if row < 32: return "Excellent" elif row < 42: return "Good" elif row < 53: return "Fair" elif row <= 79: return "Poor" else: return "Hazard"
def find_max_occupancy_node(dir_list): """ Find node with maximum occupancy. :param list_dir: list of directories for each node. :return number: number node in list_dir """ count = 0 number = 0 length = 0 for dirs in dir_list: if length < len(dirs): length = len(dirs) number = count count += 1 return number
def build_response_params(params, ens_params): """Combine member strings with the parameter list""" out = [] for param in params: for ens in ens_params: if ens == 'm0': out.append(param) else: out.append('{}-{}'.format(param, ens)) return out
def unlink(text): """Find a link in a text string, and replaces it with RST-equiv.""" A_HREF = '<a href="' A_HREF_CLOSE = '">' A_HREF_TAG_CLOSE = '</a>' find_a_href = text.find(A_HREF) if find_a_href == -1: return text find_a_href_close = text.find(A_HREF_CLOSE) if find_a_href_close == -1: raise Exception('unlink', "'%s' is missing a '%s'" % (text, A_HREF_CLOSE)) find_a_href_close_end = find_a_href_close + len(A_HREF_CLOSE) find_a_href_tag_close = text.find(A_HREF_TAG_CLOSE) if find_a_href_tag_close == -1: raise Exception('unlink', "'%s' is missing a '%s'" % (text, A_HREF_TAG_CLOSE)) find_a_href_tag_close_end = find_a_href_tag_close + len(A_HREF_TAG_CLOSE) open = text[0:find_a_href] link = text[find_a_href_close_end:find_a_href_tag_close] close = text[find_a_href_tag_close_end:] new_text = "%s`%s`__%s" % (open, link, close) # Recursive in case there are more return unlink(new_text)
def speech_response_with_card(title, output, cardcontent, endsession): """ create a simple json response with card """ return { 'card': { 'type': 'Simple', 'title': title, 'content': cardcontent }, 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'shouldEndSession': endsession }
def ffs(num): """Find the lowest order bit that is set Args: num: the number to search Returns: The 0-based index of the lowest order bit that is set, or None if no bits are set """ if num == 0: return None i = 0 while (num % 2) == 0: i += 1 num = num >> 1 return i
def rotate_letter(letter, n): """Rotates a letter by n places. Does not change other chars. letter: single-letter string n: int Returns: single-letter string """ if letter.isupper(): start = ord('A') elif letter.islower(): start = ord('a') else: return letter c = ord(letter) - start i = (c + n) % 26 + start return chr(i)
def filter_separate(pred, seq): """Generic filter function that produces two lists, one for which the predicate is true, and the other elements.""" inlist = [] outlist = [] for e in seq: if pred(e): inlist.append(e) else: outlist.append(e) return inlist, outlist
def check_not_finished_board(board: list): """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', \ '*?????*', '*?????*', '*2*1***']) False >>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215', \ '*35214*', '*41532*', '*2*1***']) True >>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215', \ '*35214*', '*41532*', '*2*1***']) False """ for elem in board: if '?' in elem: return False return True
def _try_pydatetime(x): """Opportunistically try to convert to pandas time indexes since plotly doesn't know how to handle them. """ try: x = x.to_pydatetime() except AttributeError: pass return x
def set_intersection(list1, list2): """ Using the built-in 'intersection()' method form a 'set()' element. 'intersection()' can have as parameters more than two sets. :param list1: :param list2: :return: """ set1 = set(list1) set2 = set(list2) return list(set1.intersection(set2))
def calculate_manhattan_dist(idx, value, n): """calculate the manhattan distance of a tile""" ### STUDENT CODE GOES HERE ### if not value: return 0 cur_row_idx = idx // n + 1 cur_col_idx = idx % n + 1 goal_row_idx = value // n + 1 goal_col_idx = value % n + 1 return abs(cur_row_idx - goal_row_idx) + abs(cur_col_idx - goal_col_idx)
def merge_dicts(x, y, z=None): """Given two dicts, merge them into a new dict as a shallow copy.""" # https://stackoverflow.com/a/26853961 a = x.copy() a.update(y) if z is not None: a.update(z) return a
def IsMultiPanel(hcuts, vcuts) -> bool: """ Check if the image is multi-panel or not. Could have more logic. """ return bool(hcuts or vcuts)
def bad_argument(*args, **kwargs) -> dict: """ Bad Option exception response :return: OpenC2 response message - dict """ return dict( status=501, status_text="Option not supported" )
def negate(signal): """ negate the signal """ negated_signal = signal * (-1) return negated_signal
def _check_can_broadcast_to(shape, target_shape): """Determines if shape can be broadcast to target_shape.""" ndim = len(shape) ndim_target = len(target_shape) if ndim > ndim_target: return False for i, j in zip(reversed(shape), reversed(target_shape)): if i not in (1, j): return False return True
def calculate_fitness(info): """Calculates a fitness score based on Gym information""" return info['distance']
def escape(s): """Taken from python's html library in 3.x escapes the html for python Replace special characters "&", "<" and ">" to HTML-safe sequences. Also translates the double quote and single quote chars, as well as performs a simple nl2br operation. """ escapeMap = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;', ord('"'): '&quot;', ord('\''): '&#x27;', ord('\n'): '<br> '} return s.translate(escapeMap)
def s_to_hms(seconds): """ Get tuple (hours, minutes, seconds) from total seconds """ h, r = divmod(seconds, 3600) m, s = divmod(r, 60) return h, m, s
def get_name(name, list_of_name, size=1): """ :param name: (string) the param name :param list_of_name: (string) the list of param name :param size: (int) the size of the name used :return: (string) the param name selected """ if name[0:size] not in list_of_name: return name[0:size] elif name[0:size].upper() not in list_of_name: return name[0:size].upper() else: return get_name(name, list_of_name, size=size + 1)
def get_config_params(subject_id, table): """Inserts subject_id to the top of the table Parameters ---------- subject_id : String Subject_id table : List 2d table that will go into QA report Outputs ------- table : List """ table.insert(0,['subject_id',subject_id]) return table
def f1(a1): """ @type a1: str @precondition: len(a1) > 2 @rtype: basestring @postcondition: len(result) == len(a1) + 3 """ if a1 == "bad output": return 17 elif a1 == "bad postcondition": return "def" else: return "%sdef" % a1
def get_process_command(cmd_args): """Get command-line text for task process.""" # Join arguments into command string, escaping any with spaces. cmd = '' for arg_index, arg in enumerate(cmd_args): if arg_index > 0: cmd += ' ' if ' ' in arg: cmd += '"' + arg + '"' else: cmd += arg return cmd
def pad(source: str, pad_len: int, align: str) -> str: """Return a padded string. :param source: The string to be padded. :param pad_len: The total length of the string to be returned. :param align: The alignment for the string. :return: The padded string. """ return "{s:{a}{n}}".format(s=source, a=align, n=pad_len)
def array_dtype(a): """Element data type of an array or array-like object""" if hasattr(a,"dtype"): return a.dtype if not hasattr(a,"__len__"): return type(a) if len(a) == 0: return float # If 'a' is a list, it may contain element of different data type. # Converting it to an array, make numpy select a common data type that # is appropriate for all elements. from numpy import ndarray,array if not isinstance(a,ndarray): a = array(a) return a.dtype
def _bucket_boundaries(max_length, min_length=8, length_bucket_step=1.1): """A default set of length-bucket boundaries.""" assert length_bucket_step > 1.0 x = min_length boundaries = [] while x < max_length: boundaries.append(x) x = max(x + 1, int(x * length_bucket_step)) return boundaries
def get_tag_val(tag, xml_str, match=None): """ quick access to tag values via string splitting FIXME: use regex... """ def get_tag_content(stri): # string starts within a tag def, like ab='23' c='2'>foo</tag> # we return 'foo' return stri.split('</', 1)[0].split('>', 1)[1] if not match: return get_tag_content(xml_str.split('<%s' % tag, 1)[1]) for tag_line in xml_str.split('<%s' % tag): tag_line = tag_line.split('</%s' % tag)[0] if match in tag_line: return get_tag_content(tag_line)
def get_muted_layers(layers): """Given a list of layers, return only those that are muted :param layers: list of layers to filter :type layers: list :return: list of layers that are muted. :rtype: list """ return [layer for layer in layers if layer.get_muted()]
def time_str(uptime): """ converts uptime in seconds to a time string """ if not isinstance(uptime, int): return "" mins = (uptime/60) % 60 hours = (uptime/60/60) % 24 days = (uptime/24/60/60) % 365 years = uptime/365/24/60/60 if years == 0: if days == 0: if hours == 0: return "%sm" % mins return "%sh %sm" % (hours, mins) return "%sd %sh %sm" % (days, hours, mins) return "%sy %sd %sh %sm" % (years, days, hours, mins)
def parse_line(self, line): """ Split line into command and argument. :param line: line to parse :return: (command, argument) """ command, _, arg = line.strip().partition(" ") return command, arg.strip()
def beautify(name): """ make file name looks better """ return name.replace('_', ' ').replace('-', ' ').title()
def even_evens(some_list): """ Give a list 'some_list', return a list of only the even numbers from the even indices of 'some_list'. """ return [x for x in some_list[::2] if x % 2 == 0]
def create_leaf_node(stats): """ Creates a leaf node :param stats: stats on the partition :return: a leaf node in the form ['Leaves', ['yes', 4, 10, 40%],...] """ tree = ['Leaves'] for row in stats: if (row[1] > 0): tree.append(row) return tree
def like_list(field, values, case="", condition="OR"): """Make a `<field> LIKE '%value%'` string for list of values. Args: field (str): field to use in LIKE statement; may need to be quoted values (iterable): values to convert to LIKE query condition (str): 'AND' or 'OR' (default 'OR') case (str): optionally convert values to title, upper, or lower Returns joined string. Usage: >>> like_list('"Subdivision"', ["Ranch", "Apple"], case="upper") 'Subdivision" LIKE \'%RANCH%\' OR "Subdivision" LIKE \'%APPLE%\'"' """ cond = " {} ".format(condition) if case.lower() == 'title': values = [v.title() for v in values] elif case.lower() == 'upper': values = [v.upper() for v in values] elif case.lower() == 'lower': values = [v.lower() for v in values] q = cond.join(["{} LIKE '%{}%'".format(field, v) for v in values]) return q
def order_json_objects(obj): """ Recusively orders all elemts in a Json object. Source: https://stackoverflow.com/questions/25851183/how-to-compare-two-json-objects-with-the-same-elements-in-a-different-order-equa """ if isinstance(obj, dict): return sorted((k, order_json_objects(v)) for k, v in obj.items()) if isinstance(obj, list): return sorted(order_json_objects(x) for x in obj) return obj
def metaclass_instance_name_for_class(classname): """Return the name of the C++ metaclass instance for the given class.""" if '::' in classname: return None return classname + '::gMetaClass'
def split_list_into_n_lists(l, n): """Split a list into n lists. Args: l: List of stuff. n: Number of new lists to generate. Returns: list: List of n lists. """ return [l[i::n] for i in range(n)]
def get_positive_axis(axis, ndims, axis_name="axis", ndims_name="ndims"): """Validate an `axis` parameter, and normalize it to be positive. If `ndims` is known (i.e., not `None`), then check that `axis` is in the range `-ndims <= axis < ndims`, and return `axis` (if `axis >= 0`) or `axis + ndims` (otherwise). If `ndims` is not known, and `axis` is positive, then return it as-is. If `ndims` is not known, and `axis` is negative, then report an error. Args: axis: An integer constant ndims: An integer constant, or `None` axis_name: The name of `axis` (for error messages). ndims_name: The name of `ndims` (for error messages). Returns: The normalized `axis` value. Raises: ValueError: If `axis` is out-of-bounds, or if `axis` is negative and `ndims is None`. """ if not isinstance(axis, int): raise TypeError("%s must be an int; got %s" % (axis_name, type(axis).__name__)) if ndims is not None: if 0 <= axis < ndims: return axis elif -ndims <= axis < 0: return axis + ndims else: raise ValueError("%s=%s out of bounds: expected %s<=%s<%s" % (axis_name, axis, -ndims, axis_name, ndims)) elif axis < 0: raise ValueError("%s may only be negative if %s is statically known." % (axis_name, ndims_name)) return axis
def get_users(metadata): """ Pull users, handles hidden user errors Parameters: metadata: sheet of metadata from mwclient Returns: the list of users """ users = [] for rev in metadata: try: users.append(rev["user"]) except (KeyError): users.append(None) return users
def cell_cube_coord(c): """ Returns a tuple with the cube coordinates corresponding to the given axial coordinates. """ x = c[0] z = c[1] return (x, -x-z, z)
def get_times(ts_full, ts_system, len_state, sys_position, sys_length): """ This is a function specifically designed for TEDOPA systems. It calculates the proper 'ts' and 'subsystems' input lists for :func:`tmps.evolve` from a list of times where the full state shall be returned and a list of times where only the reduced state of the system in question shall be returned. ts then basically is a concatenation of ts_full and ts_system, while subsystems will indicate that at the respective time in ts either the full state or only a reduced density matrix should be returned. Args: ts_full (list[float]): List of times where the full state including environment chain should be returned ts_system (list[float]): List of times where only the reduced density matrix of the system should be returned len_state (int): The length of the state sys_position (int): The position of the system (first site would be 0) sys_length (int): Length of the system, i.e. number of sites the system is comprised of Returns: tuple(list[float], list[list[int]]): Times and subsystems in the form that has to be provided to :func:`tmps.evolve` """ ts = list(ts_full) + list(ts_system) subsystems = [[0, len_state]] * len(ts_full) + \ [[sys_position, sys_position + sys_length]] * len(ts_system) return ts, subsystems
def get_table_display_properties(request, default_items=25, default_sort_column = "id", default_sort_descending = True, default_filters = {}): """Extract some display properties from a request object. The following parameters (with default values) are extracted. Andy of the defaults can be overridden by passing in values. items: 25 (the number of items to paginate at a time) sort_column: id (the column to sort by) sort_descending: True (the sort order of the column) filters: {} (key, value pairs of filters to apply) """ items = default_items sort_column = default_sort_column sort_descending = default_sort_descending # odd, for some reason pass-by-reference can confuse the default types here filters = default_filters.copy() # if no request found, just resort to all the defaults, but # don't fail hard. if request: # extract from request if "items" in request.GET: try: items = int(request.GET["items"]) except Exception: # just default to the above if we couldn't # parse it pass if "sort_column" in request.GET: sort_column = request.GET["sort_column"] if "sort_descending" in request.GET: # a very dumb boolean parser sort_descending_str = request.GET["sort_descending"] if sort_descending_str.startswith("f"): sort_descending = False else: sort_descending = True found_filters = {} for param in request.GET: if param.startswith('filter_'): # we convert 'filter_x' into 'x' (the name of the field) field = param.split('_',1)[-1] found_filters[str(field)] = request.GET[param] if found_filters: filters = found_filters return (items, sort_column, sort_descending, filters)
def find_base_match(char, matrix): """Return list of coordinates wherein char matched inside matrix. Args: char (str): A single-length string matrix (list): A list containing lines of string. row_length (int): An integer which represents the height of the matrix. column_length (int): An integer which represents the horizontal length of the matrix. Returns: list: Returns a coordinate list. """ base_matches = [(row_index, column_index) for row_index, row in enumerate(matrix) for column_index, column in enumerate(row) if char == column] return base_matches
def check_draw(board): """ Checks for a draw """ return ' ' not in board
def build_resilient_url(host, port): """ build basic url to resilient instance :param host: host name :param port: port :return: base url """ return "https://{0}:{1}".format(host, port)
def signed_mod(a: int, b: int) -> int: """ Signed modulo operation for level top10 encryption/decryption. """ a = a & 0xFFFF r = a % b if a > 0x7FFF: return -b + (r - 0x10000) % b return r
def hashpjw(s): """A simple and reasonable string hash function due to Peter Weinberger""" val = 0 for c in s: val = (val << 4) + ord(c) tmp = val & 0xf0000000 if tmp != 0: val = val ^ (tmp >> 24) val = val ^ tmp return val
def translate(numpoints, refcoords, center_, mode): """Translate a molecule using equally weighted points. :param numpoints: number of points :type numpoints: int :param refcoords: list of reference coordinates, with each set a list of form [x,y,z] :type: list :param center: center of the system :type center: [float, float, float] :param mode: if 1, center will be subtracted from refcoords; if 2, center will be added to refcoords :return: moved refcoords relative to refcenter :rtype: [[float, float, float]] """ relcoords = [] modif = 0 if mode == 1: modif = -1 elif mode == 2: modif = 1 for i in range(numpoints): relcoords.append([]) relcoords[i].append(refcoords[i][0] + modif * center_[0]) relcoords[i].append(refcoords[i][1] + modif * center_[1]) relcoords[i].append(refcoords[i][2] + modif * center_[2]) return relcoords
def binary_search(list_obj, value, low, high): """ Recursive Binary Search Algoirthm: Using Divide and Conquer design paradigm to reduce the complexity and increase the efficiency Arguments: list_obj: represent list object value: an object where it's value that we are looking for in the list low: an integer object it default to first index of the list high: an integer object it default to last index of the list """ if low == high: return list_obj[low] == value middle = (low + high) // 2 if value == list_obj[middle]: return True elif value > list_obj[middle]: return binary_search(list_obj, value, middle + 1, high) else: return binary_search(list_obj, value, low, middle - 1) return False
def get_ucr_class_name(id): """ This returns the module and class name for a ucr from its id as used in report permissions. It takes an id and returns the string that needed for `user.can_view_report(string)`. The class name comes from corehq.reports._make_report_class, if something breaks, look there first. :param id: the id of the ucr report config :return: string class name """ return 'corehq.reports.DynamicReport{}'.format(id)
def format_path(plot_root: str, variant: str) -> str: """ Format path. Convert representation of variant to a path. :param plot_root: root path can be url :param variant: variant :return: path of variant resource """ return f"{plot_root}{variant}.png"
def round_up(n: int, div: int): """Round up to the nearest multiplier of div.""" return ((n + div - 1) // div) * div
def _is_bonded(item): """Determine if the item refers to a bonded port.""" for attribute in item['attributes']: if attribute['attributeTypeKeyName'] == 'NON_LACP': return False return True
def json_facts_filtered(returned_json, filter_fields=['manufacturer', 'boardassettag', 'memorysize', 'memoryfree']): """Create a nested dict, nodes-to-facts, indexed by certname(node_name), sub-index fact_name. Creates the dict from the returned_json, Use filter_fields to only included the listed facts on the dict.""" dict_filtered = {} # Index per certname for record in returned_json: if isinstance(record, dict): if 'name' in record.keys(): if record['name'] in filter_fields: if record['certname'] in dict_filtered.keys(): dict_filtered[record['certname']][record['name']] = record['value'] else: dict_filtered[record['certname']] = {} dict_filtered[record['certname']][record['name']] = record['value'] return dict_filtered
def get_geom(lines, geom_type='xyz', units='angstrom'): """ Takes the lines of an orca output file and returns its last geometry in the specified format """ start = '' end = '\n' if geom_type == 'xyz' and units == 'angstrom': start = 'CARTESIAN COORDINATES (ANGSTROEM)\n' elif geom_type == 'zmat' and units == 'angstrom': start = 'INTERNAL COORDINATES (ANGSTROEM)\n' elif geom_type == 'xyz' and units == 'bohr': start = 'CARTESIAN COORDINATES (A.U.)\n' elif geom_type == 'zmat' and units == 'bohr': start = 'INTERNAL COORDINATES (A.U.)\n' else: print("Invalid format or units") return '' geom_start = -1 # Iterate backwards until the start of the last set of coordinates is found for i in reversed(list(range(len(lines)))): if start == lines[i]: geom_start = i + 2 break if geom_start == -1: print("Could not find start of geometry") return '' geom_end = -1 for i in range(geom_start, len(lines)): if end == lines[i]: geom_end = i break if geom_end == -1: return '' if geom_type == 'xyz' and units == 'bohr': geom_start += 1 geom = lines[geom_start: geom_end] return geom
def calc_median(nums): """Calculate the median of a number list.""" N = len(nums) nums.sort() if N % 2 == 0: m1 = N / 2 m2 = (N / 2) + 1 m1 = int(m1) - 1 m2 = int(m2) - 1 median = (nums[m1] + nums[m2]) / 2 else: m = N / 2 m = int(m) - 1 median = nums[m] return median
def _GetShardKeyName(name, index): """Gets a key name for a partition on a given shard. Args: name: Str name of the shard. index: Int partitin number. Returns: Str key name for the given partition. """ return 'CounterShard_%s_%d' % (name, index)
def compute_shape(coords, reshape_len=None, py_name=""): """ Computes the 'shape' of a coords dictionary. Function used to rearange data in xarrays and to compute the number of rows/columns to be read in a file. Parameters ---------- coords: dict Ordered dictionary of the dimension names as a keys with their values. reshape_len: int (optional) Number of dimensions of the output shape. The shape will ony compute the corresponent table dimensions to read from Excel, then, the dimensions with length one will be ignored at first. Lately, it will complete with 1 on the left of the shape if the reshape_len value is bigger than the length of shape. Will raise a ValueError if we try to reshape to a reshape_len smaller than the initial shape. py_name: str Name to print if an error is raised. Returns ------- shape: list Shape of the ordered dictionary or of the desired table or vector. Note ---- Dictionaries in Python >= 3.7 are ordered, which means that we could remove dims if there is a not backward compatible version of the library which only works in Python 3.7+. For now, the dimensions list is passed to make it work properly for all the users. """ if not reshape_len: return [len(coord) for coord in coords.values()] # get the shape of the coordinates bigger than 1 shape = [len(coord) for coord in coords.values() if len(coord) > 1] shape_len = len(shape) # return an error when the current shape is bigger than the requested one if shape_len > reshape_len: raise ValueError( py_name + "\n" + "The shape of the coords to read in a " + " external file must be at most " + "{} dimensional".format(reshape_len) ) # complete with 1s on the left return [1] * (reshape_len - shape_len) + shape