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 ...
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(...
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_...
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> ...
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 = ...
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} ...
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 ...
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 an...
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:{}...
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: ...
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 negat...
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_dat...
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) aft...
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 ...
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: f...
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(t...
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:...
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}'.f...
: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...
: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.showI...
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...
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' ...
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. Ret...
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...
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. Par...
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...
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): ...
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(): ...
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_{}(...
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, reso...
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 serve...
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(ho...
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 sel...
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...
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. ...
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 +...
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) ...
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 ...
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 t...
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...
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...
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 incl...
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'`` ...
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...
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...
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 v...
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...
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)...
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 f...
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, ...
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, se...
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. ...
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'): ...
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) ...
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` corou...
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...
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")...
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, Warnin...
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. ...
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 ...
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 ...
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.Act...
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("'buf...
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...
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 ...
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)...
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: " "{...
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 = in...
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 div...
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, 'r...
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 div...
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( ...
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: sp...
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('>gn...
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...
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 line...