content
stringlengths
42
6.51k
def _texture_path(texture_bricks_name): """ Parameter --------- texture_bricks_name : str name of the world main texture Return ------ texture_path: (str) path corresponding to the texture_bricks_name Raises ------ ValueError : raised if texture_bricks_name is unkwnonw """ if texture_bricks_name == 'minecraft': return '/textures/texture_minecraft.png' elif texture_bricks_name == 'graffiti': return '/textures/texture_graffiti.png' elif texture_bricks_name == 'colours': return '/textures/texture_colours.png' else : raise ValueError('Unknown texture name '+ texture_bricks_name + ' in loading world')
def eval_files(prec: str = "50") -> list: """Obtain a list of pre-processed dataset file patterns for evaluation. Args: prec (str, optional): The percentage here should match with train_files. Returns: list: The TFRecord file patterns for evaluation during training. """ return ["gs://motherbrain-pause/data/{}p/eval/*".format(prec)]
def remove_whitespace(text): # type: (str) -> str """strips all white-space from a string""" if text is None: return "" return "".join(text.split())
def listi(list_, elem, default=None): """ Return the elem component in a list of lists, or list of tuples, or list of dicts. If default is non-None then if the key is missing return that. Examples: l = [("A", "B"), ("C", "D")] listi(l, 1) == ["B", "D"] l = [{"A":1, "B":2}, {"A":3, "B", 4}, {"Q": 5}] listi(l, "B", default=0) == [2, 4, 0] """ ret = [] for i in list_: if isinstance(i, dict): if elem in i: ret += [i[elem]] elif default is not None: ret += [default] else: raise KeyError("Missing elem in list of dicts") else: if 0 <= elem < len(i): ret += [i[elem]] elif default is not None: ret += [default] else: raise KeyError("Missing elem in list of lists") return ret
def make_key(element_name, element_type, namespace): """Return a suitable key for elements""" # only distinguish 'element' vs other types if element_type in ('complexType', 'simpleType'): eltype = 'complexType' else: eltype = element_type if eltype not in ('element', 'complexType', 'simpleType'): raise RuntimeError("Unknown element type %s = %s" % (element_name, eltype)) return (element_name, eltype, namespace)
def get_player_url(playerid): """ Gets the url for a page containing information for specified player from NHL API. :param playerid: int, the player ID :return: str, https://statsapi.web.nhl.com/api/v1/people/[playerid] """ return 'https://statsapi.web.nhl.com/api/v1/people/{0:s}'.format(str(playerid))
def _to_short_string(text: str, max_length: int = 75) -> str: """Caps the string at 75 characters. If longer than 75 it's capped at max_length-3 and '...' is appended Arguments: text {str} -- A text string Keyword Arguments: max_length {int} -- The maximum number of characters (default: {75}) Returns: str -- The capped string """ if len(text) < max_length: return text return text[0:72] + "..."
def store_on_fs(data, file_name): """ Store data in file named `file_name` """ if data: with open(file_name, "w") as f: f.write(str(data)) return True
def aggregate_function(a, b, func): """Function to implement aggregate functions.""" return_val = False if func == "max": a[func] = max(a[func], b) elif func == "min": a[func] = min(a[func], b) elif func == "sum": a[func] = a[func]+b elif func == "avg": a[func][0] = a[func][0]+b a[func][1] = a[func][1]+1 else: return_val = True return return_val
def merge_nested_dict(dicts): """ Merge a list of nested dicts into a single dict """ merged_dict = {} for d in dicts: for key in d.keys(): for subkey in d[key].keys(): if key not in list(merged_dict.keys()): merged_dict[key] = {subkey: {}} merged_dict[key][subkey] = d[key][subkey] return merged_dict
def __tokenize_text(text): """Convert text to lowercase, replace periods and commas, and split it into a list. >>> __tokenize_text('hi. I am, a, sentence.') ['hi', 'i', 'am', 'a', 'sentence'] """ return text.lower().replace(',', '').replace('.', '').split()
def _to_basestring(value): """Converts a string argument to a subclass of basestring. This comes from `Tornado`_. In python2, byte and unicode strings are mostly interchangeable, so functions that deal with a user-supplied argument in combination with ascii string constants can use either and should return the type the user supplied. In python3, the two types are not interchangeable, so this method is needed to convert byte strings to unicode. """ if isinstance(value, str): return value if not isinstance(value, bytes): raise TypeError("Expected bytes, unicode, or None; got %r" % type(value)) return value.decode("utf-8")
def _get_ascii_token(token): """Removes non-ASCII characters in the token.""" chars = [] for char in token: # Try to encode the character with ASCII encoding. If there is an encoding # error, it's not an ASCII character and can be skipped. try: char.encode('ascii') except UnicodeEncodeError: continue chars.append(char) return ''.join(chars)
def one_ribbon(l, w, h): """Compute needed ribbon for one present. Arguments l, w, and h are expected to be sorted for a correct result. """ return 2 * (l + w) + l * w * h
def fp_find_omega(omega_r, omega_theta, omega_phi, em, kay, en, M=1): """ Uses Boyer frequencies to find omega_mkn Parameters: omega_r (float): radial boyer lindquist frequency omega_theta (float): theta boyer lindquist frequency omega_phi (float): phi boyer lindquist frequency em (int): phi mode kay (int): theta mode en (int): radial mode Keyword Args: M (float): mass of large body Returns: omega (float): frequency of motion """ return en * omega_r + em * omega_phi + kay * omega_theta
def polylineAppendCheck(currentVL, nextVL): """Given two polyline vertex lists, append them if needed. Polylines to be appended will have the last coordinate of the first vertex list be the same as the first coordinate of the second vertex list. When appending, we need to eliminate one of these coordinates. Args: currentVL (list): First of two lists of vertexes to check. nextVL (list): Second of two lists of vertexes to check. Returns: tuple: Tuple: 1. ``True`` if the vertexes were appended, otherwise ``False``. 2. New vertex list if appended (otherwise ignored). """ wasAppended = False appendedList = [] # In a polyline, the last coord of the first list will be the # first coord of the new list last = currentVL[-1] first = nextVL[0] if (last[0] == first[0]) and (last[1] == first[1]) and (last[2] == first[2]): # It is to be appended wasAppended = True appendedList = currentVL[:-1] + nextVL return (wasAppended, appendedList)
def get_leg_swing_offset_for_pitching(body_pitch, desired_incline_angle): """Get the leg swing zero point when the body is tilted. For example, when climbing up or down stairs/slopes, the robot body will tilt up or down. By compensating the body pitch, the leg's trajectory will be centered around the vertical direction (not perpendicular to the surface). This helps the robot to generate thrust when going upwards, and braking when going downwards. Args: body_pitch: Float. Current body pitch angle. desired_incline_angle: Float. The desired body pitch angle. Returns: The stance and swing leg swing offset. """ kp = 0.2 return -((1 - kp) * body_pitch + kp * desired_incline_angle)
def factors(n): """returns the factors of n""" return [i for i in range(1, n // 2 + 1) if not n % i] + [n]
def split_config(raw): """Split configuration into overall and per-stage. Args: raw (list[dict]): pipeline configuration. Returns: - dict: overall settings under "overall" key. - list[dict]: per-stage configurations. """ for (i, entry) in enumerate(raw): if "overall" in entry: del raw[i] return entry["overall"], raw return {}, raw
def apply(f, *args, **kwargs): """Apply a function to arguments. Parameters ---------- f : callable The function to call. *args, **kwargs **kwargs Arguments to feed to the callable. Returns ------- a : any The result of ``f(*args, **kwargs)`` Examples -------- >>> from toolz.curried.operator import add, sub >>> fs = add(1), sub(1) >>> tuple(map(apply, fs, (1, 2))) (2, -1) Class decorator >>> instance = apply >>> @instance ... class obj: ... def f(self): ... return 'f' ... >>> obj.f() 'f' >>> issubclass(obj, object) Traceback (most recent call last): ... TypeError: issubclass() arg 1 must be a class >>> isinstance(obj, type) False See Also -------- unpack_apply mapply """ return f(*args, **kwargs)
def _get_in_out_shape(x_shape, y_shape, n_classes, batch_size=None): """Returns shape for input and output of the data feeder.""" x_is_dict, y_is_dict = isinstance( x_shape, dict), y_shape is not None and isinstance(y_shape, dict) if y_is_dict and n_classes is not None: assert isinstance(n_classes, dict) if batch_size is None: batch_size = list(x_shape.values())[0][0] if x_is_dict else x_shape[0] elif batch_size <= 0: raise ValueError('Invalid batch_size %d.' % batch_size) if x_is_dict: input_shape = {} for k, v in list(x_shape.items()): input_shape[k] = [batch_size] + (list(v[1:]) if len(v) > 1 else [1]) else: x_shape = list(x_shape[1:]) if len(x_shape) > 1 else [1] input_shape = [batch_size] + x_shape if y_shape is None: return input_shape, None, batch_size def out_el_shape(out_shape, num_classes): out_shape = list(out_shape[1:]) if len(out_shape) > 1 else [] # Skip first dimension if it is 1. if out_shape and out_shape[0] == 1: out_shape = out_shape[1:] if num_classes is not None and num_classes > 1: return [batch_size] + out_shape + [num_classes] else: return [batch_size] + out_shape if not y_is_dict: output_shape = out_el_shape(y_shape, n_classes) else: output_shape = dict([ (k, out_el_shape(v, n_classes[k] if n_classes is not None and k in n_classes else None)) for k, v in list(y_shape.items()) ]) return input_shape, output_shape, batch_size
def featurizeDoc(doc): """ get key : value of metadata """ doc_features = [] for key in doc: doc_features.append("{0}: {1}".format(key, doc[key])) return doc_features
def to_bool_str(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possible True values: 1, True, "1", "TRue", "yes", "y", "t" Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ... """ if str(value).lower() in ("yes", "y", "true", "t", "1"): return "1" if str(value).lower() in ("no", "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return "0" raise Exception('Invalid value for boolean conversion: ' + str(value))
def insertion_sort(x): """ Goals: The goal is to sort the an array by starting with the left most element and moving left to right move an element back if it is less than the previous element until the list is completely ordered. Variables: x is the array inputed into the function. Assign counts when ever an index is moved or when two elements are switched. Condition counts everytime two elements are compared. n is the lengh of the array. i is the pointer to which element of the array is being looked at. Output: Array of... first is sorted array second is amount of conditionals called thris is the number of assignments """ Assign = 0 Condition = 0 for i in range (1, len(x)): # pass through the array skipping the 0 element Assign +=1 # assignment of i Condition +=1 # while loop condition while x[i] < x[i-1]: x[i], x[i-1] = x[i-1], x[i] Assign +=2 # the swapping of two elements i = i-1 Assign +=1 # I changing by 1 Condition +=1 # If condition for i if i == 0: break return x, Assign, Condition
def check_not_present(context, raw_data, raw_field): """ Verifies that a specified field is not present in a raw data structure. Args: context (str): The context of the comparison, used for printing error messages. raw_data (dict): Raw data structure we're checking a field from. raw_field (str): Name of the raw field we're verifying is not present. Returns: True if the field was not present, False if it was. """ if raw_field not in raw_data: return True print(f"field value {raw_field} should be absent from {context}, but is not") return False
def time_convert(sec): """ Converts seconds into hours, minutes and seconds :param sec: Seconds as a int :return: A good formatted time string """ mins = sec // 60 sec = sec % 60 hours = mins // 60 mins = mins % 60 return "{0}:{1}:{2}".format(int(hours), int(mins), sec)
def set_bit(num, offset): """ Set bit to at the given offset to 1 """ mask = 1 << offset return num | mask
def assignGroupToURI(uri: str) -> str: """Returns a group for a URI e.g. science museum, v&a, wikidata. Should operate on the normalised URI produced by `normaliseURI`.""" if "collection.sciencemuseumgroup" in uri: return "Science Museum Group Collection" elif "blog.sciencemuseum.org.uk" in uri: return "Science Museum Blog" elif "journal.sciencemuseum.ac.uk" in uri: return "Science Museum Journal" elif ("collections.vam.ac.uk" in uri) or ( "api.vam.ac.uk/v2/objects/search?" in uri ): return "V&A collection" elif "http://www.wikidata.org/entity/" in uri: return "Wikidata" else: return "Literal (raw value)"
def _repair_snr(snr): """ SNR in Octave ommits zeros at the end :return: """ snr = "{:.4f}".format(snr) while snr.endswith('0'): snr = snr[:-1] if snr.endswith('.'): snr = snr[:-1] return snr
def is_scalar(arg) -> bool: """ Return True if the arg is a scalar. """ return isinstance(arg, int) or isinstance(arg, float)
def get_file_type(extensions: list, filename: str) -> str: """ Checks if the extension of a given file matches a set of expected extensions. Args: extensions (list): a set of expected file extensions filename (str): a file name to test is extension is expected Raises: ValueError: given file does not match an expected extension Returns: str: the matched extension """ for ext in extensions: if filename.endswith(ext): return ext raise ValueError(f"'{filename}' is not an accepted result file. Accepted extensions: {', '.join(extensions)}")
def paginate(text: str): """Simple generator that paginates text.""" last = 0 pages = [] appd_index = 0 curr = 0 for curr in range(0, len(text)): if curr % 1980 == 0: pages.append(text[last:curr]) last = curr appd_index = curr if appd_index != len(text) - 1: pages.append(text[last:curr]) return list(filter(lambda a: a != '', pages))
def _check_shape_compile(shape): """check the shape param to match the numpy style inside the graph""" if not isinstance(shape, (int, tuple, list)): raise TypeError( f"only int, tuple and list are allowed for shape, but got {type(shape)}") if isinstance(shape, int): shape = (shape,) if isinstance(shape, list): shape = tuple(shape) return shape
def find_place(lines, size_x): """ Finds the highest place at the left for a panel with size_x :param lines: :param size_x: :return: line with row, col, len """ for line in lines: if line['len'] >= size_x: return line
def parse_commit_message(message): """Given the full commit message (summary, body), parse out relevant information. Mimiron generates commit messages, commits, and pushes changes tfvar changes to remote. These generated commit messages contain useful information such as the service that was bumped, the person that bumped, environment etc. Args: message (str): The full git commit message Returns: Optional[dict]: A dictionary of useful information, None otherwise """ data = {} for line in message.split('\n'): if not line: continue key, _, value = line.partition(':') if key == 'committed-by': name, _, email = value.strip().partition('<') data['author_name'] = name.strip() data['author_email'] = email.rstrip('>') or None return data or None
def checkSyntax(value): """Check the syntax of a `Python` expression. :Parameters value: the Python expression to be evaluated """ if value[0] in ("'", '"'): # Quotes are not permitted in the first position return False try: eval(value) except (ValueError, SyntaxError): return False else: return True
def sort_lists(sorted_indices, list_to_sort): """ given a list of indices and a list to sort sort the list using the sorted_indices order :param sorted_indices: a list of indices in the order they should be e.g. [0,4,2,3] :param list_to_sort: the list which needs to be sorted in the indice order from sorted_indices :return: sorted list """ return [list_to_sort[i] for i in sorted_indices]
def mongodb_str_filter(base_field, base_field_type): """Prepare filters (kwargs{}) for django queryset for mongodb where fields contain strings are checked like exact | startswith | contains | endswith >>> mongodb_str_filter(21, '1') '21' >>> mongodb_str_filter(21, '2') {'$regex': '^21'} >>> mongodb_str_filter(21, '3') {'$regex': '.*21.*'} >>> mongodb_str_filter(21, '4') {'$regex': '21$'} """ q = '' base_field = str(base_field) if base_field != '': if base_field_type == '1': # Equals q = base_field if base_field_type == '2': # Begins with q = {'$regex': str('^' + base_field)} if base_field_type == '3': # Contains q = {'$regex': str('.*' + base_field + '.*')} if base_field_type == '4': # Ends with q = {'$regex': str(base_field + '$')} return q
def remove_return_string(line): """Helper method for subtokenizing comment.""" return line.replace('@return', '').replace('@ return', '').strip()
def data_format_to_shape( batch_length=None, sequence_length=None, channel_length=None, data_format='channels_first' ): """.""" shape = [batch_length, None, None] channel_axis = 1 if data_format == 'channels_first' else 2 sequence_axis = 2 if data_format == 'channels_first' else 1 shape[sequence_axis] = sequence_length shape[channel_axis] = channel_length return tuple(shape)
def flip_end_chars(txt): """Flip the first and last characters if txt is a string.""" if isinstance(txt, str) and txt and len(txt) > 1: first, last = txt[0], txt[-1] if first == last: return "Two's a pair." return "{}{}{}".format(last, txt[1:-1], first) return "Incompatible."
def reset_op_debug_level_in_soc_info(level): """ :param level: op_debug_level, if level is 3 or 4, replace it with 0 :return: op_debug_level """ if level in ("3", "4"): level = "0" return level
def valid_user_input(ui: str) -> bool: """Determines if the passed string is a valid RPS choice.""" if ui == "rock" or ui == "paper" or ui == "scissors": return True return False
def slice_expr(collection, start, count): """ Lookup a value in a Weld vector. This will add a cast the start and stop to 'I64'. Examples -------- >>> slice_expr("v", 1, 2).code 'slice(v, i64(1), i64(2))' """ return "slice({collection}, i64({start}), i64({count}))".format( collection=collection, start=start, count=count)
def sort_format(src): """ format 1-2-3... to 00001-00002-00003... src should be convertable to int """ src_list= src.split('-') res_list= [] for elm in src_list: try: res_list.append('%05d' % int(elm)) except: res_list.append(elm) res= '-'.join(res_list) return res
def smart_truncate(content, length=100, suffix='...'): """ function to truncate anything over a certain number of characters. pretty much stolen from: http://stackoverflow.com/questions/250357/smart-truncate-in-python """ if not content or len(content) <= length: return content else: return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix
def get_list_from_interval(input_interval, month_interval=True): """ Created 20180619 by Magnus Wenzer Updated 20180620 by Magnus Wenzer Takes an interval in a list and returns a list with the gange of the interval. Example: [2, 7] => [2, 3, 4, 5, 6, 7] """ if not input_interval: return None elif not len(set([type(i) for i in input_interval])) == 1: return None if input_interval and len(input_interval) == 2: output_list = [] value = input_interval[0] while value != input_interval[-1]: output_list.append(value) value += 1 if input_interval and value == 13: value = 1 return [i for i in range(input_interval[0], input_interval[-1]+1)] else: output_list = [] for item in input_interval: output_list.append(get_list_from_interval(item, month_interval=month_interval)) return output_list
def dialog_response(attributes, endsession): """ create a simple json response with card """ return { 'version': '1.0', 'sessionAttributes': attributes, 'response':{ 'directives': [ { 'type': 'Dialog.Delegate' } ], 'shouldEndSession': endsession } }
def get_state_transitions_direct(actions): """ get the next state @param actions: @return: tuple (current_state, action, nextstate) """ state_transition_pairs = [] for action in actions: current_state = action[0] next_state = action[1][0] state_transition_pairs.append((current_state, action[1], next_state)) return state_transition_pairs
def format_num(num): """Return num rounded to reasonable precision (promille).""" if num >= 1000.0: res = "{:,}".format(round(num)) elif num >= 100.0: res = str(round(num, 1)) # res = "{:,.1f}".format(num) elif num >= 10.0: res = str(round(num, 2)) # res = "{:,.2f}".format(num) elif num >= 1.0: res = str(round(num, 3)) # res = "{:,.3f}".format(num) else: res = str(num) # res = "{:,}".format(num) return res
def get_colored_for_soi_columns(value_list): """ """ list_output = [] if value_list: for each_ in value_list: dictionary = {} dictionary['if'] = {"column_id":each_} dictionary['backgroundColor'] = "#3D9970" dictionary['color'] = 'black' list_output.append(dictionary) return list_output else: return None
def is_task_complete(task, task_runs, redundancy, task_id_field='id', task_run_id_field='task_id', error=None): """ Checks to see if a task is complete. Slightly more optimized than doing: len(get_task_runs()) :param task: input task object :type task: dict :param task_runs: content from task_run.json :type task_runs: list :param redundancy: number of times a task must be completed :type redundancy: int :param task_id_field: the key used to get the unique task identifier :type task_id_field: str :param task_run_id_field: the key used to get the unique task_run identifier :type task_run_id_field: str :param error: the value that is returned when an error is encountered :type error: any :rtype: bool|None """ # Validate input if redundancy <= 0: return error # Loop and check count = 0 task_id = task[task_id_field] for tr in task_runs: tr_id = tr[task_run_id_field] if task_id == tr_id: count += 1 if count >= redundancy: return True return False
def get_percent(value, minimum, maximum): """ Get a given value's percent in the range. :param value: value :param minimum: the range's minimum value :param maximum: the range's maximum value :return: percent float """ if minimum == maximum: # reference from qprogressbar.cpp # If max and min are equal and we get this far, it means that the # progress bar has one step and that we are on that step. Return # 100% here in order to avoid division by zero further down. return 100 return max(0, min(100, (value - minimum) * 100 / (maximum - minimum)))
def indexer(cell): """utility function to return cells in the format the frontend expects""" col, row = (cell) return [row, col]
def is_leap_year(year): """ if year is a leap year return True else return False """ if year % 100 == 0: return year % 400 == 0 return year % 4 == 0
def molm2_to_molec_cm2(spc_array): """ Convert moles/m2 to molec/cm2 """ avo_num = 6.0221409e23 molec_per_m2 = spc_array * avo_num molec_per_cm2 = molec_per_m2 * 1e4 return molec_per_cm2
def filter(arr:list, func) -> list: """Filters items from a list based on callback function return Args: arr ( list ) : a list to iterate func ( function ) : a callback function Examples: >>> array = Array(1, 2, 3, 4) >>> array.filter(lambda item, index: item % 2 == 0) [2, 4] """ _arr = [] for index in range(len(arr)): if func(arr[index], index): _arr.append(arr[index]) return _arr
def prepend_to_line(text, token): """Prepends a token to each line in text""" return [token + line for line in text]
def select(items, container, *, ctor=None): """ Returns `items` that are in `container`. :param ctor: Constructor for returned value. If `None`, uses the type of `items`. Use `iter` to return an iterable. """ if ctor is None: ctor = type(items) return ctor( i for i in items if i in container )
def count_fillin(graph, nodes): """How many edges would be needed to make v a clique.""" count = 0 for v1 in nodes: for v2 in nodes: if v1 != v2 and v2 not in graph[v1]: count += 1 return count / 2
def get_password_from_file(passfile_path, hostname, port, database, username): """ Parser for PostgreSQL libpq password file. Returns None on no matching entry, otherwise it returns the password. For file format see: http://www.postgresql.org/docs/current/static/libpq-pgpass.html """ if not hostname or not port or not database or not username: return None with open(passfile_path, 'r', encoding="utf-8", errors="ignore") as passfile: for line in passfile: pw = _match_line(line.strip(), hostname, port, database, username) if pw: return pw return None
def filter_logs(logs, project, config): """ When given a list of log objects, returns only those that match the filters defined in config and project. The filters in project take priority over config. :param logs: A list of log objects. Logs must be in the format returned by winlogtimeline.util.logs.parse_record. :param project: A project instance. :param config: A config dictionary. :return: A list of logs that satisfy the filters specified in the configuration. """ # config = [('event_id', '=', 5061)] query = 'SELECT * FROM logs WHERE ' for constraint in config: query += '{} {} {} AND '.format(*constraint) query = query[:-5] print(query) # cur = project._conn.execute(query) # logs = cur.fetchall() return logs
def get_current_players_cards(player_number, player_hands): """ Return the hand from the list of player_hands which corresponds to the player number. :param: player_number, player_hands (list of Hand objects) :return: Hand(obj) """ for tup in enumerate(player_hands, 1): if tup[0] == player_number: current_players_hand = tup[1] return current_players_hand
def simplify3(string): """[1,2..4]+[6] -> [1,2..4,6]""" string = string.replace("]+[",",") return string
def check_min_permission_length( permission, minchars=None ): # pylint: disable=missing-function-docstring """ Adapted version of policyuniverse's _check_permission_length. We are commenting out the skipping prefix message https://github.com/Netflix-Skunkworks/policyuniverse/blob/master/policyuniverse/expander_minimizer.py#L111 """ if minchars and len(permission) < int(minchars) and permission != "": # print( # "Skipping prefix {} because length of {}".format( # permission, len(permission) # ), # file=sys.stderr, # ) return True return False
def month(day): """ Given a the number of days experienced in the current year it returns a month :param day: Current number of days in the year :return: str, month """ if 1 >= day <= 31: return "January" elif 31 >= day <= 59: return "February" elif 60 >= day <= 90: return "March" elif 91 >= day <= 120: return "April" elif 121 >= day <= 151: return "May" elif 152 >= day <= 181: return "June" elif 182 >= day <= 212: return "July" elif 213 >= day <= 243: return "August" elif 244 >= day <= 273: return "September" elif 274 >= day <= 304: return "October" elif 305 >= day <= 334: return "November" else: return "December"
def find_aliased_pin(pin, model, pin_aliases): """ Searches for aliased pins in the timing model. The check is done using data from pin_aliases dictionary. The dictionary has an entry for each aliased pin. Each entry has two fields: * names : a list of all the possible aliases * is_property_related: a flag saying if the alias is in fact pin name combined with BEL property (e.g. Q[LH] pins in FF - in this case the pin name is Q [original name], but is named Q[LH] in the timing model. The suffix determines polarity of the FF's set/reset input). If is_property_related is set the function returns the original pin name, aliased name is returned otherwise. Parameters ---------- pin: str Pin name to look for model: str Timing model pin_aliases: dict A dict of list of aliases for given bel/site Returns ------- bool, str The first bool value is set to true if pin is found in the timing model, false otherwise. The second returned value is found pin name. If pin is not found None is returned >>> find_aliased_pin("a", "a_b_some_test_string", None) (False, None) >>> find_aliased_pin("d", "din_dout_setup", {"D": {"names" : ["din"], "is_property_related" : False}}) (True, 'din') >>> find_aliased_pin("d", "din_dout_setup", {"D": {"names" : ["din"], "is_property_related" : True}}) (True, 'd') >>> find_aliased_pin("d", "din_dout_setup", {"D": {"names" : ["notdin"], "is_property_related" : True}}) (False, None) """ if (pin_aliases is not None) and (pin.upper() in pin_aliases): for alias in pin_aliases[pin.upper()]['names']: single_word_alias = (len(alias.split('_')) == 1) pin_alias = alias.lower() if single_word_alias: model_to_check = model.split('_') else: model_to_check = model if pin_alias in model_to_check: if pin_aliases[pin.upper()]['is_property_related']: return True, pin.lower() else: return True, pin_alias return False, None
def personal_top_three(scores): """ Return top three score from the list. if there are less than 3 scores then return in a decending order the all elements """ # sorted the list in a decending order sorted_scores = sorted(scores, reverse=True) # check if there are at least 3 elements if len(scores) >= 3: # if so, return the first three top scores return sorted_scores[:3] # else return in a decending order return sorted_scores[:len(scores)]
def create_node_str(node_id): """Creates node for the GML file :param node_id: The id of the node """ node_str = "\tnode\n\t[\n\t\tid " + str(node_id) + "\n\t]\n" return node_str
def get_color_file_html_new_color(scope, color, dashed): """ return new color """ if scope != "": scope_infos = "SCOPE: "+scope else: scope_infos = "" if dashed: class_added = "dashed" else: class_added = "" colorText = "#lorem ipsum<br/>! = >< Delec<br/>Rum altese %" html = "<div class=\""+class_added+"\" title=\""+scope_infos+"\" style=\"background-color:"+color+";\"><br/><span>"+color+"</span></div>\n" # html = "<div style=\"color:"+color+";\"><br/><span>"+colorText+"</span></div>\n" return html
def klass(obj) -> str: """ returns class name of the object. Might be useful when rendering widget class names Args: obj: any python class object Returns: str: name of the class >>> from tests.test_app.models import Author >>> klass(Author) 'ModelBase' """ return obj.__class__.__name__
def create_section_data_block(data_length): """Create a block of data to represend a section Creates a list of the given size and returns it. The list will have every byte set to 0xff. This is because reserved bits are normally set to 1 Arguments: data_length -- amount of bytes needed for the data block Returns: A list of bytes of the desired length with zero in every byte """ data = [0xff] * data_length return data
def check_equal(list): """ Determines whether two lists are equal """ return list[1:] == list[:-1]
def invert_dictionary(dictionary): """ Invert a dictionary :param dictionary: :return inverted_dictionary: """ inverted_dictionary = dict() for k, v in dictionary.items(): inverted_dictionary[v] = k return inverted_dictionary
def conditions(ctx): """ Tests for registers to verify that our glitch worked """ if ctx['regs']['rax'] == 0: return True else: return False
def lcm(num1, num2, limit=10): """lcm: finds the least common multiple of two numbers Args: num1 (int): First number to calculate lcm of num2 (int): Second number to calculate lcm of Returns: int: the least common multiple (lcm) of num1 and num2 """ num1ls = [num1] num2ls = [num2] mult = list(range(2, limit + 1)) for x in mult: num1ls.append(num1 * x) num2ls.append(num2 * x) if num1ls[-1] in num2ls: return num1ls[-1] elif num2ls[-1] in num1ls: return num2ls[-1] else: continue return
def sub_extension(fname, ext): """Strips the extension 'ext' from a file name if it is present, and returns the revised name. i.e. fname='datafile.dat', ext='.dat' returns 'datafile'. See: add_extension """ if fname.endswith(ext): return fname[:-len(ext)] else: return fname
def isHostile(movement): """ Parameters ---------- movement : dict Returns ------- is hostile : bool """ if movement['army']['amount']: return True for mov in movement['fleet']['ships']: if mov['cssClass'] != 'ship_transport': return True return False
def _recover_type(v): """ recover "17" to 17. recover "[]" to []. recover "datetime(2020,1,1)" to datetime(2020,1,1). keep "abc" as str. :param v: str. :return: Any. """ try: nv = eval(v) except (NameError, SyntaxError): nv = v if callable(nv): nv = v return nv
def get_func_definition(sourcelines): """Given a block of source lines for a method or function, get the lines for the function block. """ # For now return the line after the first. count = 1 for line in sourcelines: if line.rstrip().endswith(':'): break count += 1 return sourcelines[:count], sourcelines[count:]
def get_geo_url(geo_list): """ :param geo_list: list of (geo, geo_id) pair (smallest first) e.g. [(block%20group, *), (state, 01), (county, 02), (track, *), ] :return: url for geo query """ total_level = len(geo_list) url = "" for i in range(total_level): level, val = geo_list[i] if i == 0: url += "&for=%s:%s" % (level, val) else: url += "&in=%s:%s" % (level, val) return url
def square_is(location, query, board): """Checks if the piece at location equals query. Returns false if location is out of bounds.""" x, y = location if y < 0 or y >= len(board): return False if x < 0 or x >= len(board[y]): return False return board[y][x] is query
def peptide_isoforms(peptide, m, sites, prev_aa, next_aa): """ Parameters ---------- peptide : list Peptide sequence m: modification label to apply sites : set Amino acids eligible for modification Returns ------- set of lists """ isoforms = [] if ('N-term' in sites or 'Protein N-term' in sites and prev_aa == '-') and len(peptide[0]) == 1 and peptide[0] not in sites: isoforms.append((m + peptide[0],) + tuple(peptide[1:])) if ('C-term' in sites or 'Protein C-term' in sites and next_aa == '-') and len(peptide[-1]) == 1 and peptide[-1] not in sites: isoforms.append(tuple(peptide[:-1]) + (m + peptide[-1],)) for ind, a in enumerate(peptide): if a in sites: isoforms.append(tuple(peptide[:ind]) + (m + a,) + tuple(peptide[ind + 1:])) return isoforms
def read_file_to_string(filepath): """ Read entire file and return it as string. If file can't be read, return "Can't read <filepath>" :param str filepath: Path of the file to read :rtype: str :return: Content of the file in a single string, or "Can't read <filepath>" if file can't be read. """ try: with open(filepath) as f: return f.read() except Exception as e: return "Can't read {0}. Exception thrown: {1}".format(filepath, e)
def zero_prefix_int(num): """ zero_prefix_number(int) -> str\n Puts a zero in fron of 1 digit numbers.\n otherwise just returns the int """ strnum = str(num) if len(strnum) == 1: return '0'+strnum return strnum
def bubsort (a): """bubble sorter""" need = True while need: need = False for i in range(len(a)-1): if a[i] > a[i+1]: a[i], a[i+1] = a[i+1], a[i] need = True return a
def tuple_filter(tuple_obj, index): """Returns tuple value at the given index""" # Force typecast index into integer try: index = int(index) except ValueError: return None # Verify if tuple_obj is a tuple if isinstance(tuple_obj, tuple): try: return tuple_obj[index] except IndexError: return None else: return None
def filter_priority(clouds): """Returns the cloud with the hightes priority""" priority = int(clouds[0]['priority']) qualified_cloud = clouds[0] for cloud in clouds: if int(cloud['priority']) < priority: priority = int(cloud['priority']) qualified_cloud = cloud return qualified_cloud
def cyclic_index_i_plus_1(i: int, length: int, ) -> int: """A helper function for cyclic indexing rotor scans""" return i + 1 if i + 1 < length else 0
def life_counter(field): """ returns quanity of living squares """ hype = 0 for y in range(len(field)): for x in range(len(field[y])): if field[y][x] == 'o': hype += 1 return hype
def compute_M0_nl(formula, abundance): """Compute intensity of the first isotopologue M0. Handle element X with specific abundance. Parameters ---------- formula : pyteomics.mass.Composition Chemical formula, as a dict of the number of atoms for each element: {element_name: number_of_atoms, ...}. abundance : dict Dictionary of abundances of isotopes: {"element_name[isotope_number]": relative abundance, ..}. Returns ------- float Value of M0. Notes ----- X represents C with default isotopic abundance. """ M0_intensity = ( abundance["C[12]"]**formula["C"] * abundance["X[12]"]**formula["X"] * abundance["H[1]"]**formula["H"] * abundance["N[14]"]**formula["N"] * abundance["O[16]"]**formula["O"] * abundance["S[32]"]**formula["S"] ) return M0_intensity
def recursive_for_default_attributes(attributes): """ Method to extract attributes from kind desctiption and complete the missing ones in the resource description """ att_http = list() for key in attributes.keys(): if type(attributes[key]) is dict: items = recursive_for_default_attributes(attributes[key]) for item in items: if not (item.find('{')): att_http.append(key + item) else: att_http.append(key + "." + item) else: attributes = [""] return attributes final_att = list() for item in att_http: if item.endswith('.'): final_att.append(item[:-1]) else: final_att.append(item) return final_att
def proj4_str_to_dict(proj4_str): """Convert PROJ.4 compatible string definition to dict Note: Key only parameters will be assigned a value of `True`. """ pairs = (x.split('=', 1) for x in proj4_str.replace('+', '').split(" ")) return dict((x[0], (x[1] if len(x) == 2 else True)) for x in pairs)
def _startswithax(item): """ Helper function to filter tag lists for starting with xmlns:ax """ return item.startswith('xmlns:ax')
def subsequenceMatch(uctext, ucterm): """ #returns array of the indices in uctext where the letters of ucterm were found. # EG: subsequenceMatch("nothing", "ni") returns [0, 4]. subsequenceMatch("nothing", "a") # returns null. #simple subsequence match """ hits = [] texti = -1 termi = 0 while termi < len(ucterm): texti = uctext.find(ucterm[termi], texti + 1) #search for character & update position if texti == -1: #if it's not found, this term doesn't match the text return None hits.append(texti) termi += 1 return hits
def get_cache_file(fm): """Generate proper filename based on fumen.""" # strip version str, strip ?, replace / with _ to make it safe for filenames # note: on windows filenames are case insensitive so collisions could occur, but this probably will never happen clean = fm.replace("v115@", "").replace("?", "").replace("/", "_").replace("*", "_") #return working_dir / (clean + ".txt") return clean + ".txt"
def create_bin_permutations(length): """Return sorted list of permutations of 0, 1 of length. I.e, 2 --> ['00', '01', '10', '11'] """ output = [] for num in range(0, length**2): perm = f'{num:b}' perm = perm.zfill(length) return output
def contains_three_consecutive_letters(password: str) -> bool: """ Return True if the password has at least one occurrence of three consecutive letters, e.g. abc or xyz, and False if it has no such ocurrences. """ characters = [ord(char) for char in password] return any( (a + 1) == b and (b + 1) == c for a, b, c in [characters[x : x + 3] for x in range(len(password) - 2)] )
def update_state_dict(original_state_dict, dataparallel=False): """ Add or keep 'module' in name of state dict keys, depending on whether model is using DataParallel or not """ sample_layer = [k for k in original_state_dict.keys()][0] state_dict = {} if not dataparallel and 'module' in sample_layer: for key, value in original_state_dict.items(): # remove module. from start of layer names state_dict[key[7:]] = value elif dataparallel and 'module' not in sample_layer: for key, value in original_state_dict.items(): # add module. to beginning of layer names state_dict['module.{}'.format(key)] = value else: state_dict = original_state_dict return state_dict
def is_integer(val): """ Helper function that returns True if the provided value is an integer. """ try: int(val) except ValueError: return False return True