code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def resolve(self, dependency): if isinstance(dependency, str): name = dependency else: name = dependency._giveme_registered_name return DeferredProperty( partial(self.get, name) )
Resolve dependency as instance attribute of given class. >>> class Users: ... db = injector.resolve(user_db) ... ... def get_by_id(self, user_id): ... return self.db.get(user_id) When the attribute is first accessed, it will be resolved from the corresponding dependency function
def _fetch_itemslist(self, current_item): if current_item.is_root: html = requests.get(self.base_url).text soup = BeautifulSoup(html, 'html.parser') for item_html in soup.select(".row .col-md-6"): try: label = item_html.select_one("h2").text except Exception: continue yield API(label, blob=item_html) else: # parameter = current_item.parent # data = requests.get(parameter.url) for resource in current_item.json["resource"]: label = u"{}, {}".format(resource["title"], resource["summary"]) yield SMHIDataset(label, blob=resource)
Get a all available apis
def _get_example_csv(self): station_key = self.json["station"][0]["key"] period = "corrected-archive" url = self.url\ .replace(".json", "/station/{}/period/{}/data.csv"\ .format(station_key, period)) r = requests.get(url) if r.status_code == 200: return DataCsv().from_string(r.content) else: raise Exception("Error connecting to api")
For dimension parsing
def batch(iterable, length): source_iter = iter(iterable) while True: batch_iter = itertools.islice(source_iter, length) yield itertools.chain([batch_iter.next()], batch_iter)
Returns a series of iterators across the inputted iterable method, broken into chunks based on the inputted length. :param iterable | <iterable> | (list, tuple, set, etc.) length | <int> :credit http://en.sharejs.com/python/14362 :return <generator> :usage |>>> import projex.iters |>>> for batch in projex.iters.batch(range(100), 10): |... print list(batch) |[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] |[20, 21, 22, 23, 24, 25, 26, 27, 28, 29] |[30, 31, 32, 33, 34, 35, 36, 37, 38, 39] |[40, 41, 42, 43, 44, 45, 46, 47, 48, 49] |[50, 51, 52, 53, 54, 55, 56, 57, 58, 59] |[60, 61, 62, 63, 64, 65, 66, 67, 68, 69] |[70, 71, 72, 73, 74, 75, 76, 77, 78, 79] |[80, 81, 82, 83, 84, 85, 86, 87, 88, 89] |[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
def group(iterable): numbers = sorted(list(set(iterable))) for _, grouper in itertools.groupby(numbers, key=lambda i, c=itertools.count(): i - next(c)): subset = list(grouper) yield subset[0], subset[-1]
Creates a min/max grouping for the inputted list of numbers. This will shrink a list into the group sets that are available. :param iterable | <iterable> | (list, tuple, set, etc.) :return <generator> [(<int> min, <int> max), ..]
def plural(formatter, value, name, option, format): # Extract the plural words from the format string. words = format.split('|') # This extension requires at least two plural words. if not name and len(words) == 1: return # This extension only formats numbers. try: number = decimal.Decimal(value) except (ValueError, decimal.InvalidOperation): return # Get the locale. locale = Locale.parse(option) if option else formatter.locale # Select word based on the plural tag index. index = get_plural_tag_index(number, locale) return formatter.format(words[index], value)
Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} There are 10 items.
def get_choice(value): if value is None: return 'null' for attr in ['__name__', 'name']: if hasattr(value, attr): return getattr(value, attr) return str(value)
Gets a key to choose a choice from any value.
def choose(formatter, value, name, option, format): if not option: return words = format.split('|') num_words = len(words) if num_words < 2: return choices = option.split('|') num_choices = len(choices) # If the words has 1 more item than the choices, the last word will be # used as a default choice. if num_words not in (num_choices, num_choices + 1): n = num_choices raise ValueError('specify %d or %d choices' % (n, n + 1)) choice = get_choice(value) try: index = choices.index(choice) except ValueError: if num_words == num_choices: raise ValueError('no default choice supplied') index = -1 return formatter.format(words[index], value)
Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4) u'other'
def list_(formatter, value, name, option, format): if not format: return if not hasattr(value, '__getitem__') or isinstance(value, string_types): return words = format.split(u'|', 4) num_words = len(words) if num_words < 2: # Require at least two words for item format and spacer. return num_items = len(value) item_format = words[0] # NOTE: SmartFormat.NET treats a not nested item format as the format # string to format each items. For example, `x` will be treated as `{:x}`. # But the original tells us this behavior has been deprecated so that # should be removed. So SmartFormat for Python doesn't implement the # behavior. spacer = u'' if num_words < 2 else words[1] final_spacer = spacer if num_words < 3 else words[2] two_spacer = final_spacer if num_words < 4 else words[3] buf = io.StringIO() for x, item in enumerate(value): if x == 0: pass elif x < num_items - 1: buf.write(spacer) elif x == 1: buf.write(two_spacer) else: buf.write(final_spacer) buf.write(formatter.format(item_format, item, index=x)) return buf.getvalue()
Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: >>> fruits = [u'apple', u'banana', u'coconut'] >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits) u'apple, banana, and coconut' >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits[:2]) u'apple and banana'
def add_seconds(datetime_like_object, n, return_date=False): a_datetime = parser.parse_datetime(datetime_like_object) a_datetime = a_datetime + timedelta(seconds=n) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime
Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。
def add_months(datetime_like_object, n, return_date=False): a_datetime = parser.parse_datetime(datetime_like_object) month_from_ordinary = a_datetime.year * 12 + a_datetime.month month_from_ordinary += n year, month = divmod(month_from_ordinary, 12) # try assign year, month, day try: a_datetime = datetime( year, month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) # 肯定是由于新的月份的日子不够, 所以肯定是月底, # 那么直接跳到下一个月的第一天, 再回退一天 except ValueError: month_from_ordinary += 1 year, month = divmod(month_from_ordinary, 12) a_datetime = datetime( year, month, 1, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) a_datetime = add_days(a_datetime, -1) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime
Returns a time that n months after a time. Notice: for example, the date that one month after 2015-01-31 supposed to be 2015-02-31. But there's no 31th in Feb, so we fix that value to 2015-02-28. :param datetimestr: a datetime object or a datetime str :param n: number of months, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N月之后的时间。
def add_years(datetime_like_object, n, return_date=False): a_datetime = parser.parse_datetime(datetime_like_object) # try assign year, month, day try: a_datetime = datetime( a_datetime.year + n, a_datetime.month, a_datetime.day, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond, tzinfo=a_datetime.tzinfo, ) except ValueError: # Must be xxxx-02-29 a_datetime = datetime( a_datetime.year + n, 2, 28, a_datetime.hour, a_datetime.minute, a_datetime.second, a_datetime.microsecond) if return_date: # pragma: no cover return a_datetime.date() else: return a_datetime
Returns a time that n years after a time. :param datetimestr: a datetime object or a datetime str :param n: number of years, value can be negative :param return_date: returns a date object instead of datetime **中文文档** 返回给定日期N年之后的时间。
def _floor_to(dt, hour, minute, second): new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt <= dt: return new_dt else: return new_dt - timedelta(days=1)
Route the given datetime to the latest time with the hour, minute, second before it.
def _round_to(dt, hour, minute, second): new_dt = dt.replace(hour=hour, minute=minute, second=second) if new_dt == dt: return new_dt elif new_dt < dt: before = new_dt after = new_dt + timedelta(days=1) elif new_dt > dt: before = new_dt - timedelta(days=1) after = new_dt d1 = dt - before d2 = after - dt if d1 < d2: return before elif d1 > d2: return after else: return before
Route the given datetime to the latest time with the hour, minute, second before it.
def round_to(dt, hour, minute, second, mode="round"): mode = mode.lower() if mode not in _round_to_options: raise ValueError( "'mode' has to be one of %r!" % list(_round_to_options.keys())) return _round_to_options[mode](dt, hour, minute, second)
Round the given datetime to specified hour, minute and second. :param mode: 'floor' or 'ceiling' .. versionadded:: 0.0.5 message **中文文档** 将给定时间对齐到最近的一个指定了小时, 分钟, 秒的时间上。
def _log(self, content): self._buffer += content if self._auto_flush: self.flush()
Write a string to the log
def reset(self): self._buffer = '' self._chars_flushed = 0 self._game_start_timestamp = datetime.datetime.now()
Erase the log and reset the timestamp
def logpath(self): name = '{}-{}.catan'.format(self.timestamp_str(), '-'.join([p.name for p in self._players])) path = os.path.join(self._log_dir, name) if not os.path.exists(self._log_dir): os.mkdir(self._log_dir) return path
Return the logfile path and filename as a string. The file with name self.logpath() is written to on flush(). The filename contains the log's timestamp and the names of players in the game. The logpath changes when reset() or _set_players() are called, as they change the timestamp and the players, respectively.
def flush(self): latest = self._latest() self._chars_flushed += len(latest) if self._use_stdout: file = sys.stdout else: file = open(self.logpath(), 'a') print(latest, file=file, flush=True, end='') if not self._use_stdout: file.close()
Append the latest updates to file, or optionally to stdout instead. See the constructor for logging options.
def log_game_start(self, players, terrain, numbers, ports): self.reset() self._set_players(players) self._logln('{} v{}'.format(__name__, __version__)) self._logln('timestamp: {0}'.format(self.timestamp_str())) self._log_players(players) self._log_board_terrain(terrain) self._log_board_numbers(numbers) self._log_board_ports(ports) self._logln('...CATAN!')
Begin a game. Erase the log, set the timestamp, set the players, and write the log header. The robber is assumed to start on the desert (or off-board). :param players: iterable of catan.game.Player objects :param terrain: list of 19 catan.board.Terrain objects. :param numbers: list of 19 catan.board.HexNumber objects. :param ports: list of catan.board.Port objects.
def log_player_roll(self, player, roll): self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else ''))
:param player: catan.game.Player :param roll: integer or string, the sum of the dice
def log_player_buys_road(self, player, location): self._logln('{0} buys road, builds at {1}'.format( player.color, location ))
:param player: catan.game.Player :param location: string, see hexgrid.location()
def log_player_buys_settlement(self, player, location): self._logln('{0} buys settlement, builds at {1}'.format( player.color, location ))
:param player: catan.game.Player :param location: string, see hexgrid.location()
def log_player_buys_city(self, player, location): self._logln('{0} buys city, builds at {1}'.format( player.color, location ))
:param player: catan.game.Player :param location: string, see hexgrid.location()
def log_player_trades_with_port(self, player, to_port, port, to_player): self._log('{0} trades '.format(player.color)) # to_port items self._log('[') for i, (num, res) in enumerate(to_port): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to port {0} for '.format(port.type.value)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n')
:param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)]
def log_player_trades_with_other_player(self, player, to_other, other, to_player): self._log('{0} trades '.format(player.color)) # to_other items self._log('[') for i, (num, res) in enumerate(to_other): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log(' to player {0} for '.format(other.color)) # to_player items self._log('[') for i, (num, res) in enumerate(to_player): if i > 0: self._log(', ') self._log('{0} {1}'.format(num, res.value)) self._log(']') self._log('\n')
:param player: catan.game.Player :param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param other: catan.board.Player :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)]
def log_player_plays_knight(self, player, location, victim): self._logln('{0} plays knight'.format(player.color)) self.log_player_moves_robber_and_steals(player, location, victim)
:param player: catan.game.Player :param location: string, see hexgrid.location() :param victim: catan.game.Player
def log_player_plays_road_builder(self, player, location1, location2): self._logln('{0} plays road builder, builds at {1} and {2}'.format( player.color, location1, location2 ))
:param player: catan.game.Player :param location1: string, see hexgrid.location() :param location2: string, see hexgrid.location()
def log_player_plays_year_of_plenty(self, player, resource1, resource2): self._logln('{0} plays year of plenty, takes {1} and {2}'.format( player.color, resource1.value, resource2.value ))
:param player: catan.game.Player :param resource1: catan.board.Terrain :param resource2: catan.board.Terrain
def log_player_plays_monopoly(self, player, resource): self._logln('{0} plays monopoly on {1}'.format( player.color, resource.value ))
:param player: catan.game.Player :param resource: catan.board.Terrain
def log_player_ends_turn(self, player): seconds_delta = (datetime.datetime.now() - self._latest_timestamp).total_seconds() self._logln('{0} ends turn after {1}s'.format(player.color, round(seconds_delta))) self._latest_timestamp = datetime.datetime.now()
:param player: catan.game.Player
def _log_board_terrain(self, terrain): self._logln('terrain: {0}'.format(' '.join(t.value for t in terrain)))
Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects
def _log_board_numbers(self, numbers): self._logln('numbers: {0}'.format(' '.join(str(n.value) for n in numbers)))
Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects.
def _log_board_ports(self, ports): ports = sorted(ports, key=lambda port: (port.tile_id, port.direction)) self._logln('ports: {0}'.format(' '.join('{}({} {})'.format(p.type.value, p.tile_id, p.direction) for p in ports)))
A board with no ports is allowed. In the logfile, ports must be sorted - ascending by tile identifier (primary) - alphabetical by edge direction (secondary) :param ports: list of catan.board.Port objects
def _log_players(self, players): self._logln('players: {0}'.format(len(players))) for p in self._players: self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat))
:param players: list of catan.game.Player objects
def _set_players(self, _players): self._players = list() _players = list(_players) _players.sort(key=lambda p: p.seat) for p in _players: self._players.append(p)
Players will always be set in seat order (1,2,3,4)
def _SetGuide(self, guideName): if(guideName == epguides.EPGuidesLookup.GUIDE_NAME): self._guide = epguides.EPGuidesLookup() else: raise Exception("[RENAMER] Unknown guide set for TVRenamer selection: Got {}, Expected {}".format(guideName, epguides.EPGuidesLookup.GUIDE_NAME))
Select guide corresponding to guideName Parameters ---------- guideName : string Name of guide to use. Note ---------- Supported guide names are: EPGUIDES
def _GetUniqueFileShowNames(self, tvFileList): showNameList = [tvFile.fileInfo.showName for tvFile in tvFileList] return(set(showNameList))
Return a list containing all unique show names from tvfile.TVFile object list. Parameters ---------- tvFileList : list List of tvfile.TVFile objects. Returns ---------- set The set of show names from the tvfile.TVFile list.
def _GetShowInfo(self, stringSearch): goodlogging.Log.Info("RENAMER", "Looking up show info for: {0}".format(stringSearch)) goodlogging.Log.IncreaseIndent() showInfo = self._GetShowID(stringSearch) if showInfo is None: goodlogging.Log.DecreaseIndent() return None elif showInfo.showID is None: goodlogging.Log.DecreaseIndent() return None elif showInfo.showName is None: showInfo.showName = self._db.SearchTVLibrary(showID = showInfo.showID)[0][1] goodlogging.Log.Info("RENAMER", "Found show name: {0}".format(showInfo.showName)) goodlogging.Log.DecreaseIndent() return showInfo else: goodlogging.Log.DecreaseIndent() return showInfo
Calls GetShowID and does post processing checks on result. Parameters ---------- stringSearch : string String to look up in database or guide. Returns ---------- tvfile.ShowInfo or None If GetShowID returns None or if it returns showInfo with showID = None then this will return None, otherwise it will return the showInfo object.
def _CreateNewSeasonDir(self, seasonNum): seasonDirName = "Season {0}".format(seasonNum) goodlogging.Log.Info("RENAMER", "Generated directory name: '{0}'".format(seasonDirName)) if self._skipUserInput is False: response = goodlogging.Log.Input("RENAMER", "Enter 'y' to accept this directory, 'b' to use base show directory, 'x' to skip this file or enter a new directory name to use: ") response = util.CheckEmptyResponse(response) else: response = 'y' if response.lower() == 'b': return '' elif response.lower() == 'y': return seasonDirName elif response.lower() == 'x': return None else: return response
Creates a new season directory name in the form 'Season <NUM>'. If skipUserInput is True this will be accepted by default otherwise the user can choose to accept this, use the base show directory or enter a different name. Parameters ---------- seasonNum : int Season number. Returns ---------- string or None If the user accepts the generated directory name or gives a new name this will be returned. If it the user chooses to use the base directory an empty string is returned. If the user chooses to skip at this input stage None is returned.
def _CreateNewShowDir(self, showName): stripedDir = util.StripSpecialCharacters(showName) goodlogging.Log.Info("RENAMER", "Suggested show directory name is: '{0}'".format(stripedDir)) if self._skipUserInput is False: response = goodlogging.Log.Input('RENAMER', "Enter 'y' to accept this directory, 'x' to skip this show or enter a new directory to use: ") else: response = 'y' if response.lower() == 'x': return None elif response.lower() == 'y': return stripedDir else: return response
Create new directory name for show. An autogenerated choice, which is the showName input that has been stripped of special characters, is proposed which the user can accept or they can enter a new name to use. If the skipUserInput variable is True the autogenerated value is accepted by default. Parameters ---------- showName : string Name of TV show Returns ---------- string or None Either the autogenerated directory name, the user given directory name or None if the user chooses to skip at this input stage.
def get_api_publisher(self, social_user): def _post(owner_id=None, **kwargs): api = self.get_api(social_user, owner_id) return api.post('{}/feed'.format(owner_id or 'me'), params=kwargs) return _post
message: <str> image: <file> as object_attachment owner_id: <str>
def catch(ignore=[], was_doing="something important", helpfull_tips="you should use a debugger", gbc=None): exc_cls, exc, tb=sys.exc_info() if exc_cls in ignore: msg='exception in ignorelist' gbc.say('ignoring caught:'+str(exc_cls)) return 'exception in ignorelist' ex_message = traceback.format_exception_only(exc_cls, exc)[-1] ex_message = ex_message.strip() # TODO: print(ex_message) error_frame = tb while error_frame.tb_next is not None: error_frame = error_frame.tb_next file = error_frame.tb_frame.f_code.co_filename line = error_frame.tb_lineno stack = traceback.extract_tb(tb) formated_stack = [] for summary in stack: formated_stack.append({ 'file': summary[0], 'line': summary[1], 'func': summary[2], 'text': summary[3] }) event = { 'was_doing':was_doing, 'message': ex_message, 'errorLocation': { 'file': file, 'line': line, 'full': file + ' -> ' + str(line) }, 'stack': formated_stack #, #'time': time.time() } try: #logging.info('caught:'+pformat(event)) gbc.cry('caught:'+pformat(event)) print('Bubble3: written error to log') print('Bubble3: tips for fixing this:') print(helpfull_tips) except Exception as e: print('Bubble3: cant log error cause of %s' % e)
Catch, prepare and log error :param exc_cls: error class :param exc: exception :param tb: exception traceback
def from_name(api_url, name, dry_run=False): return DataSet( '/'.join([api_url, name]).rstrip('/'), token=None, dry_run=dry_run )
doesn't require a token config param as all of our data is currently public
def secured_clipboard(item): expire_clock = time.time() def set_text(clipboard, selectiondata, info, data): # expire after 15 secs if 15.0 >= time.time() - expire_clock: selectiondata.set_text(item.get_secret()) clipboard.clear() def clear(clipboard, data): """Clearing of the buffer is deferred this only gets called if the paste is actually triggered """ pass targets = [("STRING", 0, 0) ,("TEXT", 0, 1) ,("COMPOUND_TEXT", 0, 2) ,("UTF8_STRING", 0, 3)] cp = gtk.clipboard_get() cp.set_with_data(targets, set_text, clear)
This clipboard only allows 1 paste
def get_active_window(): active_win = None default = wnck.screen_get_default() while gtk.events_pending(): gtk.main_iteration(False) window_list = default.get_windows() if len(window_list) == 0: print "No Windows Found" for win in window_list: if win.is_active(): active_win = win.get_name() return active_win
Get the currently focused window
def get(self): # get all network quota from Cloud Provider. attrs = ("networks", "security_groups", "floating_ips", "routers", "internet_gateways") for attr in attrs: setattr(self, attr, eval("self.get_{}()". format(attr)))
Get quota from Cloud Provider.
def join_css_class(css_class, *additional_css_classes): css_set = set(chain.from_iterable( c.split(' ') for c in [css_class, *additional_css_classes] if c)) return ' '.join(css_set)
Returns the union of one or more CSS classes as a space-separated string. Note that the order will not be preserved.
def _init_middlewares(self): self.middleware = [DeserializeMiddleware()] self.middleware += \ [FuncMiddleware(hook) for hook in self.before_hooks()] self.middleware.append(SerializeMiddleware())
Initialize hooks and middlewares If you have another Middleware, like BrokeMiddleware for e.x You can append this to middleware: self.middleware.append(BrokeMiddleware())
def _init_routes_and_middlewares(self): self._init_middlewares() self._init_endpoints() self.app = falcon.API(middleware=self.middleware) self.app.add_error_handler(Exception, self._error_handler) for version_path, endpoints in self.catalog: for route, resource in endpoints: self.app.add_route(version_path + route, resource)
Initialize hooks and URI routes to resources.
def _error_handler(self, exc, request, response, params): if isinstance(exc, falcon.HTTPError): raise exc LOG.exception(exc) raise falcon.HTTPInternalServerError('Internal server error', six.text_type(exc))
Handler error
def _get_server_cls(self, host): server_cls = simple_server.WSGIServer if netutils.is_valid_ipv6(host): if getattr(server_cls, 'address_family') == socket.AF_INET: class server_cls(server_cls): address_family = socket.AF_INET6 return server_cls
Return an appropriate WSGI server class base on provided host :param host: The listen host for the zaqar API server.
def listen(self): msgtmpl = (u'Serving on host %(host)s:%(port)s') host = CONF.wsgi.wsgi_host port = CONF.wsgi.wsgi_port LOG.info(msgtmpl, {'host': host, 'port': port}) server_cls = self._get_server_cls(host) httpd = simple_server.make_server(host, port, self.app, server_cls) httpd.serve_forever()
Self-host using 'bind' and 'port' from the WSGI config group.
def _create_map(self): # at state i is represented by the regex self.B[i] for state_a in self.mma.states: self.A[state_a.stateid] = {} # Create a map state to state, with the transition symbols for arc in state_a.arcs: if arc.nextstate in self.A[state_a.stateid]: self.A[state_a.stateid][arc.nextstate].append(self.mma.isyms.find(arc.ilabel)) else: self.A[state_a.stateid][arc.nextstate] = [self.mma.isyms.find(arc.ilabel)] if state_a.final: self.A[state_a.stateid]['string'] = ['']
Initialize Brzozowski Algebraic Method
def get_promise(self): if self._promise is None: promise = [] if self.read: promise.append(TDOPromise(self._chain, 0, self.bitcount)) else: promise.append(None) if self.read_status: promise.append(TDOPromise(self._chain, 0, self.dev._desc._ir_length)) else: promise.append(None) self._promise = promise return self._promise
Return the special set of promises for run_instruction. Run Instruction has to support multiple promises (one for reading data, and one for reading back the status from IR. All other primitives have a single promise, so fitting multiple into this system causes some API consistencies. This should be reviewed to see if a more coherent alternative is available.
def return_primitive(fn): @wraps(fn) def wrapped_fn(x): if isinstance(x, PRIMITIVE_TYPES): return x return fn(x) return wrapped_fn
Decorator which wraps a single argument function to ignore any arguments of primitive type (simply returning them unmodified).
def _get_dataset(self, dataset, name, color): global palette html = "{" html += '\t"label": "' + name + '",' if color is not None: html += '"backgroundColor": "' + color + '",\n' else: html += '"backgroundColor": ' + palette + ',\n' html += '"data": ' + self._format_list(dataset) + ',\n' html += "}" return html
Encode a dataset
def _format_list(self, data): dataset = "[" i = 0 for el in data: if pd.isnull(el): dataset += "null" else: dtype = type(data[i]) if dtype == int or dtype == float: dataset += str(el) else: dataset += '"' + el + '"' if i < len(data) - 1: dataset += ', ' dataset += "]" return dataset
Format a list to use in javascript
def status(self, status, headers=None): ''' Respond with given status and no content :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule ''' self.response = _Response(status, headers) return self status(self, status, headers=None): ''' Respond with given status and no content :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule ''' self.response = _Response(status, headers) return self
Respond with given status and no content :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule
def text(self, text, status=200, headers=None): ''' Respond with given status and text content :type text: str :param text: text to return :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule ''' self.response = _Response(status, headers, text.encode('utf8')) return self text(self, text, status=200, headers=None): ''' Respond with given status and text content :type text: str :param text: text to return :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule ''' self.response = _Response(status, headers, text.encode('utf8')) return self
Respond with given status and text content :type text: str :param text: text to return :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response :returns: itself :rtype: Rule
def json(self, json_doc, status=200, headers=None): ''' Respond with given status and JSON content. Will also set ``'Content-Type'`` to ``'applicaion/json'`` if header is not specified explicitly :type json_doc: dict :param json_doc: dictionary to respond with converting to JSON string :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response ''' headers = headers or {} if 'content-type' not in headers: headers['content-type'] = 'application/json' return self.text(json.dumps(json_doc), status, headersf json(self, json_doc, status=200, headers=None): ''' Respond with given status and JSON content. Will also set ``'Content-Type'`` to ``'applicaion/json'`` if header is not specified explicitly :type json_doc: dict :param json_doc: dictionary to respond with converting to JSON string :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response ''' headers = headers or {} if 'content-type' not in headers: headers['content-type'] = 'application/json' return self.text(json.dumps(json_doc), status, headers)
Respond with given status and JSON content. Will also set ``'Content-Type'`` to ``'applicaion/json'`` if header is not specified explicitly :type json_doc: dict :param json_doc: dictionary to respond with converting to JSON string :type status: int :param status: status code to return :type headers: dict :param headers: dictionary of headers to add to response
def matches(self, method, path, headers, bytes=None): ''' Checks if rule matches given request parameters :type method: str :param method: HTTP method, e.g. ``'GET'``, ``'POST'``, etc. Can take any custom string :type path: str :param path: request path including query parameters, e.g. ``'/users?name=John%20Doe'`` :type bytes: bytes :param bytes: request body :returns: ``True`` if this rule matches given params :rtype: bool ''' return self._expectation.matches(method, path, headers, bytesf matches(self, method, path, headers, bytes=None): ''' Checks if rule matches given request parameters :type method: str :param method: HTTP method, e.g. ``'GET'``, ``'POST'``, etc. Can take any custom string :type path: str :param path: request path including query parameters, e.g. ``'/users?name=John%20Doe'`` :type bytes: bytes :param bytes: request body :returns: ``True`` if this rule matches given params :rtype: bool ''' return self._expectation.matches(method, path, headers, bytes)
Checks if rule matches given request parameters :type method: str :param method: HTTP method, e.g. ``'GET'``, ``'POST'``, etc. Can take any custom string :type path: str :param path: request path including query parameters, e.g. ``'/users?name=John%20Doe'`` :type bytes: bytes :param bytes: request body :returns: ``True`` if this rule matches given params :rtype: bool
def start(self): ''' Starts a server on the port provided in the :class:`Server` constructor in a separate thread :rtype: Server :returns: server instance for chaining ''' self._handler = _create_handler_class(self._rules, self._always_rules) self._server = HTTPServer(('', self._port), self._handler) self._thread = Thread(target=self._server.serve_forever, daemon=True) self._thread.start() self.running = True return self start(self): ''' Starts a server on the port provided in the :class:`Server` constructor in a separate thread :rtype: Server :returns: server instance for chaining ''' self._handler = _create_handler_class(self._rules, self._always_rules) self._server = HTTPServer(('', self._port), self._handler) self._thread = Thread(target=self._server.serve_forever, daemon=True) self._thread.start() self.running = True return self
Starts a server on the port provided in the :class:`Server` constructor in a separate thread :rtype: Server :returns: server instance for chaining
def stop(self): ''' Shuts the server down and waits for server thread to join ''' self._server.shutdown() self._server.server_close() self._thread.join() self.running = Falsf stop(self): ''' Shuts the server down and waits for server thread to join ''' self._server.shutdown() self._server.server_close() self._thread.join() self.running = False
Shuts the server down and waits for server thread to join
def assert_no_pending(self, target_rule=None): ''' Raises a :class:`PendingRequestsLeftException` error if server has target rule non-resolved. When target_rule argument is ommitted raises if server has any pending expectations. Useful in ``tearDown()`` test method to verify that test had correct expectations :type target_rule: Rule :param target_rule: will raise if this rule is left pending :raises: :class:`PendingRequestsLeftException` ''' if target_rule: if target_rule in self._rules: raise PendingRequestsLeftException() elif self._rules: raise PendingRequestsLeftException(f assert_no_pending(self, target_rule=None): ''' Raises a :class:`PendingRequestsLeftException` error if server has target rule non-resolved. When target_rule argument is ommitted raises if server has any pending expectations. Useful in ``tearDown()`` test method to verify that test had correct expectations :type target_rule: Rule :param target_rule: will raise if this rule is left pending :raises: :class:`PendingRequestsLeftException` ''' if target_rule: if target_rule in self._rules: raise PendingRequestsLeftException() elif self._rules: raise PendingRequestsLeftException()
Raises a :class:`PendingRequestsLeftException` error if server has target rule non-resolved. When target_rule argument is ommitted raises if server has any pending expectations. Useful in ``tearDown()`` test method to verify that test had correct expectations :type target_rule: Rule :param target_rule: will raise if this rule is left pending :raises: :class:`PendingRequestsLeftException`
def build(path, query=None, fragment=''): url = nstr(path) # replace the optional arguments in the url keys = projex.text.findkeys(path) if keys: if query is None: query = {} opts = {} for key in keys: opts[key] = query.pop(key, '%({})s'.format(key)) url %= opts # add the query if query: if type(query) is dict: mapped_query = {} for key, value in query.items(): mapped_query[nstr(key)] = nstr(value) query_str = urllib.urlencode(mapped_query) else: query_str = nstr(query) url += '?' + query_str # include the fragment if fragment: url += '#' + fragment return url
Generates a URL based on the inputted path and given query options and fragment. The query should be a dictionary of terms that will be generated into the URL, while the fragment is the anchor point within the target path that will be navigated to. If there are any wildcards within the path that are found within the query, they will be inserted into the path itself and removed from the query string. :example |>>> import skyline.gui |>>> skyline.gui.build_url('sky://projects/%(project)s', | {'project': 'Test', 'asset': 'Bob'}) |'sky://projects/Test/?asset=Bob' :param path | <str> query | <dict> || None fragment | <str> || None :return <str> | url
def parse(url): result = urlparse.urlparse(nstr(url)) path = result.scheme + '://' + result.netloc if result.path: path += result.path query = {} # extract the python information from the query if result.query: url_query = urlparse.parse_qs(result.query) for key, value in url_query.items(): if type(value) == list and len(value) == 1: value = value[0] query[key] = value return path, query, result.fragment
Parses out the information for this url, returning its components expanded out to Python objects. :param url | <str> :return (<str> path, <dict> query, <str> fragment)
def register(scheme): scheme = nstr(scheme) urlparse.uses_fragment.append(scheme) urlparse.uses_netloc.append(scheme) urlparse.uses_params.append(scheme) urlparse.uses_query.append(scheme) urlparse.uses_relative.append(scheme)
Registers a new scheme to the urlparser. :param schema | <str>
def coerce(self, value): if isinstance(value, compat.basestring): return value return str(value)
Convert any value into a string value. Args: value (any): The value to coerce. Returns: str: The string representation of the value.
def coerce(self, value): if not isinstance(value, compat.basestring): value = str(value) if not self._re.match(value): raise ValueError( "The value {0} does not match the pattern {1}".format( value, self.pattern, ) ) return value
Convert a value into a pattern matched string value. All string values are matched against a regex before they are considered acceptable values. Args: value (any): The value to coerce. Raises: ValueError: If the value is not an acceptable value. Returns: str: The pattern matched value represented.
def get_payload(self, *args, **kwargs): if not kwargs: kwargs = self.default_params else: kwargs.update(self.default_params) for item in args: if isinstance(item, dict): kwargs.update(item) if hasattr(self, 'type_params'): kwargs.update(self.type_params(*args, **kwargs)) return kwargs
Receive all passed in args, kwargs, and combine them together with any required params
async def read_frame(self) -> DataFrame: if self._data_frames.qsize() == 0 and self.closed: raise StreamConsumedError(self.id) frame = await self._data_frames.get() self._data_frames.task_done() if frame is None: raise StreamConsumedError(self.id) return frame
Read a single frame from the local buffer. If no frames are available but the stream is still open, waits until more frames arrive. Otherwise, raises StreamConsumedError. When a stream is closed, a single `None` is added to the data frame Queue to wake up any waiting `read_frame` coroutines.
def read_frame_nowait(self) -> Optional[DataFrame]: try: frame = self._data_frames.get_nowait() except asyncio.QueueEmpty: if self.closed: raise StreamConsumedError(self.id) return None self._data_frames.task_done() if frame is None: raise StreamConsumedError(self.id) return frame
Read a single frame from the local buffer immediately. If no frames are available but the stream is still open, returns None. Otherwise, raises StreamConsumedError.
def pluck(obj, selector, default=None, skipmissing=True): if not selector: return obj if selector[0] != '[': selector = '.%s' % selector wrapped_obj = pluckable(obj, default=default, skipmissing=skipmissing, inplace=True) return eval("wrapped_obj%s.value" % selector)
Alternative implementation of `plucks` that accepts more complex selectors. It's a wrapper around `pluckable`, so a `selector` can be any valid Python expression comprising attribute getters (``.attr``) and item getters (``[1, 4:8, "key"]``). Example: pluck(obj, "users[2:5, 10:15].name.first") equal to: pluckable(obj).users[2:5, 10:15].name.first.value
def readProfile(filename): p = profile_parser.Parser() accu = TermSet() file = open(filename,'r') s = file.readline() while s!="": try: accu = p.parse(s,filename) except EOFError: break s = file.readline() return accu
input: string, name of a file containing a profile description output: asp.TermSet, with atoms matching the contents of the input file Parses a profile description, and returns a TermSet object.
def _param_deprecation_warning(schema, deprecated, context): for i in deprecated: if i in schema: msg = 'When matching {ctx}, parameter {word} is deprecated, use __{word}__ instead' msg = msg.format(ctx = context, word = i) warnings.warn(msg, Warning)
Raises warning about using the 'old' names for some parameters. The new naming scheme just has two underscores on each end of the word for consistency
def check(schema, data, trace=False): if trace == True: trace = 1 else: trace = None return _check(schema, data, trace=trace)
Verify some json. Args: schema - the description of a general-case 'valid' json object. data - the json data to verify. Returns: bool: True if data matches the schema, False otherwise. Raises: TypeError: If the schema is of an unknown data type. ValueError: If the schema contains a string with an invalid value. If the schema attempts to reference a non-existent named schema.
def has_perm(self, user, perm, obj=None, *args, **kwargs): try: if not self._obj_ok(obj): if hasattr(obj, 'get_permissions_object'): obj = obj.get_permissions_object(perm) else: raise InvalidPermissionObjectException return user.permset_tree.allow(Action(perm), obj) except ObjectDoesNotExist: return False
Test user permissions for a single action and object. :param user: The user to test. :type user: ``User`` :param perm: The action to test. :type perm: ``str`` :param obj: The object path to test. :type obj: ``tutelary.engine.Object`` :returns: ``bool`` -- is the action permitted?
def permitted_actions(self, user, obj=None): try: if not self._obj_ok(obj): raise InvalidPermissionObjectException return user.permset_tree.permitted_actions(obj) except ObjectDoesNotExist: return []
Determine list of permitted actions for an object or object pattern. :param user: The user to test. :type user: ``User`` :param obj: A function mapping from action names to object paths to test. :type obj: callable :returns: ``list(tutelary.engine.Action)`` -- permitted actions.
def validate(self,options): if not options.port: self.parser.error("'port' is required") if options.port == options.monitor_port: self.parser.error("'port' and 'monitor-port' must not be the same.") if options.buffer_size <= 0: self.parser.error("'buffer_size' must be > 0.") try: codecs.getencoder(options.char_encoding) except LookupError: self.parser.error("invalid 'char-encoding' %s" % options.char_encoding) if not options.host: options.host = socket.gethostname()
Validate the options or exit()
def list(self, name, platform='', genre=''): data_list = self.db.get_data(self.list_path, name=name, platform=platform, genre=genre) data_list = data_list.get('Data') or {} games = data_list.get('Game') or [] return [self._build_item(**i) for i in games]
The name argument is required for this method as per the API server specification. This method also provides the platform and genre optional arguments as filters.
def list(self): data_list = self.db.get_data(self.list_path) data_list = data_list.get('Data') or {} platforms = (data_list.get('Platforms') or {}).get('Platform') or [] return [self._build_item(**i) for i in platforms]
No argument is required for this method as per the API server specification.
def games(self, platform): platform = platform.lower() data_list = self.db.get_data(self.games_path, platform=platform) data_list = data_list.get('Data') or {} return [Game(self.db.game, **i) for i in data_list.get('Game') or {}]
It returns a list of games given the platform *alias* (usually is the game name separated by "-" instead of white spaces).
def remove_none_dict_values(obj): if isinstance(obj, (list, tuple, set)): return type(obj)(remove_none_dict_values(x) for x in obj) elif isinstance(obj, dict): return type(obj)((k, remove_none_dict_values(v)) for k, v in obj.items() if v is not None) else: return obj
Remove None values from dict.
def update_history(cloud_hero): user_command = ' '.join(sys.argv) timestamp = int(time.time()) command = (user_command, timestamp) cloud_hero.send_history([command])
Send each command to the /history endpoint.
def get_scenfit(instance, OS, FP, FC, EP): '''returns the scenfit of data and model described by the ``TermSet`` object [instance]. ''' sem = [sign_cons_prg, bwd_prop_prg] if OS : sem.append(one_state_prg) if FP : sem.append(fwd_prop_prg) if FC : sem.append(founded_prg) if EP : sem.append(elem_path_prg) inst = instance.to_file() prg = sem + scenfit + [inst] coptions = '--opt-strategy=5' solver = GringoClasp(clasp_options=coptions) solution = solver.run(prg,collapseTerms=True,collapseAtoms=False) opt = solution[0].score[0] os.unlink(inst) return opf get_scenfit(instance, OS, FP, FC, EP): '''returns the scenfit of data and model described by the ``TermSet`` object [instance]. ''' sem = [sign_cons_prg, bwd_prop_prg] if OS : sem.append(one_state_prg) if FP : sem.append(fwd_prop_prg) if FC : sem.append(founded_prg) if EP : sem.append(elem_path_prg) inst = instance.to_file() prg = sem + scenfit + [inst] coptions = '--opt-strategy=5' solver = GringoClasp(clasp_options=coptions) solution = solver.run(prg,collapseTerms=True,collapseAtoms=False) opt = solution[0].score[0] os.unlink(inst) return opt
returns the scenfit of data and model described by the ``TermSet`` object [instance].
def validate_implementation_for_auto_decode_and_soupify(func): arg_spec = inspect.getargspec(func) for arg in ["response", "html", "soup"]: if arg not in arg_spec.args: raise NotImplementedError( ("{func} method has to take the keyword syntax input: " "{arg}").format(func=func, arg=arg) )
Validate that :func:`auto_decode_and_soupify` is applicable to this function. If not applicable, a ``NotImplmentedError`` will be raised.
def check(a, b): aencrypt = encrypt(a) bencrypt = encrypt(b) return a == b or a == bencrypt or aencrypt == b
Checks to see if the two values are equal to each other. :param a | <str> b | <str> :return <bool>
def decodeBase64(text, encoding='utf-8'): text = projex.text.toBytes(text, encoding) return projex.text.toUnicode(base64.b64decode(text), encoding)
Decodes a base 64 string. :param text | <str> encoding | <str> :return <str>
def decrypt(text, key=None): if key is None: key = ENCRYPT_KEY bits = len(key) text = base64.b64decode(text) iv = text[:16] cipher = AES.new(key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(text[16:]))
Decrypts the inputted text using the inputted key. :param text | <str> key | <str> :return <str>
def decryptfile(filename, key=None, outfile=None, chunk=64 * 1024): if key is None: key = ENCRYPT_KEY if not outfile: outfile = os.path.splitext(filename)[0] with open(filename, 'rb') as input: origsize = struct.unpack('<Q', input.read(struct.calcsize('Q')))[0] iv = input.read(16) cipher = AES.new(key, AES.MODE_CBC, iv) with open(outfile, 'wb') as output: while True: data = input.read(chunk) if len(data) == 0: break data = cipher.decrypt(data) data = unpad(data) output.write(data) output.truncate(origsize)
Decrypts a file using AES (CBC mode) with the given key. If no file is supplied, then the inputted file will be modified in place. The chunk value will be the size with which the function uses to read and encrypt the file. Larger chunks can be faster for some files and machines. The chunk MUST be divisible by 16. :param text | <str> key | <str> outfile | <str> || None chunk | <int>
def encodeBase64(text, encoding='utf-8'): text = projex.text.toBytes(text, encoding) return base64.b64encode(text)
Decodes a base 64 string. :param text | <str> encoding | <str> :return <str>
def encrypt(text, key=None): if key is None: key = ENCRYPT_KEY bits = len(key) text = pad(text, bits) iv = Random.new().read(16) cipher = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(text))
Encrypts the inputted text using the AES cipher. If the PyCrypto module is not included, this will simply encode the inputted text to base64 format. :param text | <str> key | <str> :return <str>
def encryptfile(filename, key=None, outfile=None, chunk=64 * 1024): if key is None: key = ENCRYPT_KEY if not outfile: outfile = filename + '.enc' iv = Random.new().read(16) cipher = AES.new(key, AES.MODE_CBC, iv) filesize = os.path.getsize(filename) with open(filename, 'rb') as input: with open(outfile, 'wb') as output: output.write(struct.pack('<Q', filesize)) output.write(iv) while True: data = input.read(chunk) if len(data) == 0: break data = pad(data, len(key)) output.write(cipher.encrypt(data))
Encrypts a file using AES (CBC mode) with the given key. If no file is supplied, then the inputted file will be modified in place. The chunk value will be the size with which the function uses to read and encrypt the file. Larger chunks can be faster for some files and machines. The chunk MUST be divisible by 16. :param text | <str> key | <str> outfile | <str> || None chunk | <int>
def generateKey(password, bits=32): if bits == 32: hasher = hashlib.sha256 elif bits == 16: hasher = hashlib.md5 else: raise StandardError('Invalid hash type') return hasher(password).digest()
Generates a new encryption key based on the inputted password. :param password | <str> bits | <int> | 16 or 32 bits :return <str>
def generateToken(bits=32): if bits == 64: hasher = hashlib.sha256 elif bits == 32: hasher = hashlib.md5 else: raise StandardError('Unknown bit level.') return hasher(nstr(random.getrandbits(256))).hexdigest()
Generates a random token based on the given parameters. :return <str>
def pad(text, bits=32): return text + (bits - len(text) % bits) * chr(bits - len(text) % bits)
Pads the inputted text to ensure it fits the proper block length for encryption. :param text | <str> bits | <int> :return <str>
def Client(version=__version__, resource=None, provider=None, **kwargs): versions = _CLIENTS.keys() if version not in versions: raise exceptions.UnsupportedVersion( 'Unknown client version or subject' ) if provider is None: raise exceptions.ProviderNotDefined( 'Not define Provider for Client' ) support_types = CONF.providers.driver_mapper.keys() if provider.type not in support_types: raise exceptions.ProviderTypeNotFound( 'Unknow provider.' ) resources = _CLIENTS[version].keys() if not resource: raise exceptions.ResourceNotDefined( 'Not define Resource, choose one: compute, network,\ object_storage, block_storage.' ) elif resource.lower() not in resources: raise exceptions.ResourceNotFound( 'Unknow resource: compute, network,\ object_storage, block_storage.' ) LOG.info('Instantiating {} client ({})' . format(resource, version)) return _CLIENTS[version][resource]( provider.type, provider.config, **kwargs)
Initialize client object based on given version. :params version: version of CAL, define at setup.cfg :params resource: resource type (network, compute, object_storage, block_storage) :params provider: provider object :params cloud_config: cloud auth config :params **kwargs: specific args for resource :return: class Client HOW-TO: The simplest way to create a client instance is initialization:: >> from calplus import client >> calplus = client.Client(version='1.0.0', resource='compute', provider=provider_object, some_needed_args_for_ComputeClient)
def accession(self): accession = None if self.defline.startswith('>gi|'): match = re.match('>gi\|\d+\|[^\|]+\|([^\|\n ]+)', self.defline) if match: accession = match.group(1) elif self.defline.startswith('>gnl|'): match = re.match('>gnl\|[^\|]+\|([^\|\n ]+)', self.defline) if match: accession = match.group(1) elif self.defline.startswith('>lcl|'): match = re.match('>lcl\|([^\|\n ]+)', self.defline) if match: accession = match.group(1) return accession
Parse accession number from commonly supported formats. If the defline does not match one of the following formats, the entire description (sans leading caret) will be returned. * >gi|572257426|ref|XP_006607122.1| * >gnl|Tcas|XP_008191512.1 * >lcl|PdomMRNAr1.2-10981.1
def format_seq(self, outstream=None, linewidth=70): if linewidth == 0 or len(self.seq) <= linewidth: if outstream is None: return self.seq else: print(self.seq, file=outstream) return i = 0 seq = '' while i < len(self.seq): if outstream is None: seq += self.seq[i:i+linewidth] + '\n' else: print(self.seq[i:i+linewidth], file=outstream) i += linewidth if outstream is None: return seq
Print a sequence in a readable format. :param outstream: if `None`, formatted sequence is returned as a string; otherwise, it is treated as a file-like object and the formatted sequence is printed to the outstream :param linewidth: width for wrapping sequences over multiple lines; set to 0 for no wrapping