func_code_string
stringlengths
52
1.94M
func_documentation_string
stringlengths
1
47.2k
def SaveAvatarToFile(self, Filename, AvatarId=1): s = 'USER %s AVATAR %s %s' % (self.Handle, AvatarId, path2unicode(Filename)) self._Owner._DoCommand('GET %s' % s, s)
Saves user avatar to a file. :Parameters: Filename : str Destination path. AvatarId : int Avatar Id.
def SetBuddyStatusPendingAuthorization(self, Text=u''): self._Property('BUDDYSTATUS', '%d %s' % (budPendingAuthorization, tounicode(Text)), Cache=False)
Sets the BuddyStaus property to `enums.budPendingAuthorization` additionally specifying the authorization text. :Parameters: Text : unicode The authorization text. :see: `BuddyStatus`
def StreamWrite(stream, *obj): stream.Write(base64.encodestring(pickle.dumps(obj)))
Writes Python object to Skype application stream.
def close(self): try: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() except socket.error: pass
Closes the tunnel.
def ApplicationReceiving(self, app, streams): # we should only proceed if we are in TCP mode if stype != socket.SOCK_STREAM: return # handle all streams for stream in streams: # read object from the stream obj = StreamRead(stream) ...
Called when the list of streams with data ready to be read changes.
def ApplicationDatagram(self, app, stream, text): # we should only proceed if we are in UDP mode if stype != socket.SOCK_DGRAM: return # decode the data data = base64.decodestring(text) # open an UDP socket sock = socket.socket(type=stype) # s...
Called when a datagram is received over a stream.
def chop(s, n=1, d=None): spl = s.split(d, n) if len(spl) == n: spl.append(s[:0]) if len(spl) != n + 1: raise ValueError('chop: Could not chop %d words from \'%s\'' % (n, s)) return spl
Chops initial words from a string and returns a list of them and the rest of the string. The returned list is guaranteed to be n+1 long. If too little words are found in the string, a ValueError exception is raised. :Parameters: s : str or unicode String to chop from. n : int Nu...
def args2dict(s): d = {} while s: t, s = chop(s, 1, '=') if s.startswith('"'): # XXX: This function is used to parse strings from Skype. The question is, # how does Skype escape the double-quotes. The code below implements the # VisualBasic technique ("" ...
Converts a string or comma-separated 'ARG="a value"' or 'ARG=value2' strings into a dictionary. :Parameters: s : str or unicode Input string. :return: ``{'ARG': 'value'}`` dictionary. :rtype: dict
def _CallEventHandler(self, Event, *Args, **KwArgs): if Event not in self._EventHandlers: raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__)) args = map(repr, Args) + ['%s=%s' % (key, repr(value)) for key, value in KwArgs.items()] self.__Lo...
Calls all event handlers defined for given Event, additional parameters will be passed unchanged to event handlers, all event handlers are fired on separate threads. :Parameters: Event : str Name of the event. Args Positional arguments for the...
def RegisterEventHandler(self, Event, Target): if not callable(Target): raise TypeError('%s is not callable' % repr(Target)) if Event not in self._EventHandlers: raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__)) if Target in s...
Registers any callable as an event handler. :Parameters: Event : str Name of the event. For event names, see the respective ``...Events`` class. Target : callable Callable to register as the event handler. :return: True is callable was successfully registere...
def UnregisterEventHandler(self, Event, Target): if not callable(Target): raise TypeError('%s is not callable' % repr(Target)) if Event not in self._EventHandlers: raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__)) if Target in...
Unregisters an event handler previously registered with `RegisterEventHandler`. :Parameters: Event : str Name of the event. For event names, see the respective ``...Events`` class. Target : callable Callable to unregister. :return: True if callable was succe...
def _SetEventHandlerObject(self, Object): self._EventHandlerObject = Object self.__Logger.info('set object: %s', repr(Object))
Registers an object as events handler, object should contain methods with names corresponding to event names, only one object may be registered at a time. :Parameters: Object Object to register. May be None in which case the currently registered object will be ...
def _AddEvents(cls, Class): def make_event(event): return property(lambda self: self._GetDefaultEventHandler(event), lambda self, Value: self._SetDefaultEventHandler(event, Value)) for event in dir(Class): if not event.startswith('_'): ...
Adds events based on the attributes of the given ``...Events`` class. :Parameters: Class : class An `...Events` class whose methods define events that may occur in the instances of the current class.
def _Alter(self, AlterName, Args=None): return self._Owner._Alter('CHAT', self.Name, AlterName, Args, 'ALTER CHAT %s' % (AlterName))
--- Prajna bug fix --- Original code: return self._Owner._Alter('CHAT', self.Name, AlterName, Args, 'ALTER CHAT %s %s' % (self.Name, AlterName)) Whereas most of the ALTER commands echo the command in the reply, the ALTER CHAT commands strip the <chat_id>...
def AddMembers(self, *Members): self._Alter('ADDMEMBERS', ', '.join([x.Handle for x in Members]))
Adds new members to the chat. :Parameters: Members : `User` One or more users to add.
def SendMessage(self, MessageText): return ChatMessage(self._Owner, chop(self._Owner._DoCommand('CHATMESSAGE %s %s' % (self.Name, tounicode(MessageText))), 2)[1])
Sends a chat message. :Parameters: MessageText : unicode Message text :return: Message object :rtype: `ChatMessage`
def SetPassword(self, Password, Hint=''): if ' ' in Password: raise ValueError('Password mut be one word') self._Alter('SETPASSWORD', '%s %s' % (tounicode(Password), tounicode(Hint)))
Sets the chat password. :Parameters: Password : unicode Password Hint : unicode Password hint
def CanSetRoleTo(self, Role): t = self._Owner._Alter('CHATMEMBER', self.Id, 'CANSETROLETO', Role, 'ALTER CHATMEMBER CANSETROLETO') return (chop(t, 1)[-1] == 'TRUE')
Checks if the new role can be applied to the member. :Parameters: Role : `enums`.chatMemberRole* New chat member role. :return: True if the new role can be applied, False otherwise. :rtype: bool
def Connect(self, Skype): self._Skype = Skype self._Skype.RegisterEventHandler('CallStatus', self._CallStatus) del self._Channels[:]
Connects this call channel manager instance to Skype. This is the first thing you should do after creating this object. :Parameters: Skype : `Skype` The Skype object. :see: `Disconnect`
def CreateApplication(self, ApplicationName=None): if ApplicationName is not None: self.Name = tounicode(ApplicationName) self._App = self._Skype.Application(self.Name) self._Skype.RegisterEventHandler('ApplicationStreams', self._ApplicationStreams) self._Skype.Regis...
Creates an APP2APP application context. The application is automatically created using `application.Application.Create` method. :Parameters: ApplicationName : unicode Application name. Initial name, when the manager is created, is ``u'CallChannelManager'``.
def SendTextMessage(self, Text): if self.Type == cctReliable: self.Stream.Write(Text) elif self.Type == cctDatagram: self.Stream.SendDatagram(Text) else: raise SkypeError(0, 'Cannot send using %s channel type' & repr(self.Type))
Sends a text message over channel. :Parameters: Text : unicode Text to send.
def TextToAttachmentStatus(self, Text): conv = {'UNKNOWN': enums.apiAttachUnknown, 'SUCCESS': enums.apiAttachSuccess, 'PENDING_AUTHORIZATION': enums.apiAttachPendingAuthorization, 'REFUSED': enums.apiAttachRefused, 'NOT_AVAILABLE': enums.a...
Returns attachment status code. :Parameters: Text : unicode Text, one of 'UNKNOWN', 'SUCCESS', 'PENDING_AUTHORIZATION', 'REFUSED', 'NOT_AVAILABLE', 'AVAILABLE'. :return: Attachment status. :rtype: `enums`.apiAttach*
def TextToBuddyStatus(self, Text): conv = {'UNKNOWN': enums.budUnknown, 'NEVER_BEEN_FRIEND': enums.budNeverBeenFriend, 'DELETED_FRIEND': enums.budDeletedFriend, 'PENDING_AUTHORIZATION': enums.budPendingAuthorization, 'FRIEND': enums.budFri...
Returns buddy status code. :Parameters: Text : unicode Text, one of 'UNKNOWN', 'NEVER_BEEN_FRIEND', 'DELETED_FRIEND', 'PENDING_AUTHORIZATION', 'FRIEND'. :return: Buddy status. :rtype: `enums`.bud*
def add_composite_field(self, name, field): self.composite_fields[name] = field self._init_composite_field(name, field)
Add a dynamic composite field to the already existing ones and initialize it appropriatly.
def get_composite_field_value(self, name): field = self.composite_fields[name] if hasattr(field, 'get_form'): return self.forms[name] if hasattr(field, 'get_formset'): return self.formsets[name]
Return the form/formset instance for the given field name.
def _init_composite_fields(self): # The base_composite_fields class attribute is the *class-wide* # definition of fields. Because a particular *instance* of the class # might want to alter self.composite_fields, we create # self.composite_fields here by copying base_composite_fi...
Setup the forms and formsets.
def full_clean(self): super(SuperFormMixin, self).full_clean() for field_name, composite in self.forms.items(): composite.full_clean() if not composite.is_valid() and composite._errors: self._errors[field_name] = ErrorDict(composite._errors) for f...
Clean the form, including all formsets and add formset errors to the errors dict. Errors of nested forms and formsets are only included if they actually contain errors.
def media(self): media_list = [] media_list.append(super(SuperFormMixin, self).media) for composite_name in self.composite_fields.keys(): form = self.get_composite_field_value(composite_name) media_list.append(form.media) return reduce(lambda a, b: a + b,...
Incooperate composite field's media.
def save(self, commit=True): saved_obj = self.save_form(commit=commit) self.save_forms(commit=commit) self.save_formsets(commit=commit) return saved_obj
When saving a super model form, the nested forms and formsets will be saved as well. The implementation of ``.save()`` looks like this: .. code:: python saved_obj = self.save_form() self.save_forms() self.save_formsets() return saved_obj ...
def save_form(self, commit=True): return super(SuperModelFormMixin, self).save(commit=commit)
This calls Django's ``ModelForm.save()``. It only takes care of saving this actual form, and leaves the nested forms and formsets alone. We separate this out of the :meth:`~django_superform.forms.SuperModelForm.save` method to make extensibility easier.
def save_formsets(self, commit=True): saved_composites = [] for name, composite in self.formsets.items(): field = self.composite_fields[name] if hasattr(field, 'save'): field.save(self, name, composite, commit=commit) saved_composites.appe...
Save all formsets. If ``commit=False``, it will modify the form's ``save_m2m()`` so that it also calls the formsets' ``save_m2m()`` methods.
def get_prefix(self, form, name): return '{form_prefix}{prefix_name}-{field_name}'.format( form_prefix=form.prefix + '-' if form.prefix else '', prefix_name=self.prefix_name, field_name=name)
Return the prefix that is used for the formset.
def get_initial(self, form, name): if hasattr(form, 'initial'): return form.initial.get(name, None) return None
Get the initial data that got passed into the superform for this composite field. It should return ``None`` if no initial values where given.
def get_kwargs(self, form, name): kwargs = { 'prefix': self.get_prefix(form, name), 'initial': self.get_initial(form, name), } kwargs.update(self.default_kwargs) return kwargs
Return the keyword arguments that are used to instantiate the formset.
def get_form(self, form, name): kwargs = self.get_kwargs(form, name) form_class = self.get_form_class(form, name) composite_form = form_class( data=form.data if form.is_bound else None, files=form.files if form.is_bound else None, **kwargs) re...
Get an instance of the form.
def get_kwargs(self, form, name): kwargs = super(ModelFormField, self).get_kwargs(form, name) instance = self.get_instance(form, name) kwargs.setdefault('instance', instance) kwargs.setdefault('empty_permitted', not self.required) return kwargs
Return the keyword arguments that are used to instantiate the formset. The ``instance`` kwarg will be set to the value returned by :meth:`~django_superform.fields.ModelFormField.get_instance`. The ``empty_permitted`` kwarg will be set to the inverse of the ``required`` argument passed i...
def shall_save(self, form, name, composite_form): if composite_form.empty_permitted and not composite_form.has_changed(): return False return True
Return ``True`` if the given ``composite_form`` (the nested form of this field) shall be saved. Return ``False`` if the form shall not be saved together with the super-form. By default it will return ``False`` if the form was not changed and the ``empty_permitted`` argument for the form...
def save(self, form, name, composite_form, commit): if self.shall_save(form, name, composite_form): return composite_form.save(commit=commit) return None
This method is called by :meth:`django_superform.forms.SuperModelForm.save` in order to save the modelform that this field takes care of and calls on the nested form's ``save()`` method. But only if :meth:`~django_superform.fields.ModelFormField.shall_save` returns ``True``.
def allow_blank(self, form, name): if self.blank is not None: return self.blank model = form._meta.model field = model._meta.get_field(self.get_field_name(form, name)) return field.blank
Allow blank determines if the form might be completely empty. If it's empty it will result in a None as the saved value for the ForeignKey.
def get_formset(self, form, name): kwargs = self.get_kwargs(form, name) formset_class = self.get_formset_class(form, name) formset = formset_class( form.data if form.is_bound else None, form.files if form.is_bound else None, **kwargs) return f...
Get an instance of the formset.
def get_formset_class(self, form, name): if self.formset_class is not None: return self.formset_class formset_class = inlineformset_factory( self.get_parent_model(form, name), self.get_model(form, name), **self.formset_factory_kwargs) retu...
Either return the formset class that was provided as argument to the __init__ method, or build one based on the ``parent_model`` and ``model`` attributes.
def init_app(self, app, config_prefix='MONGOALCHEMY'): self.config_prefix = config_prefix def key(suffix): return '%s_%s' % (config_prefix, suffix) if key('DATABASE') not in app.config: raise ImproperlyConfiguredError("You should provide a database name " ...
This callback can be used to initialize an application for the use with this MongoDB setup. Never use a database in the context of an application not initialized that way or connections will leak.
def prev(self, error_out=False): return self.query.paginate(self.page - 1, self.per_page, error_out)
Return a :class:`Pagination` object for the previous page.
def get(self, mongo_id): try: return self.filter(self.type.mongo_id == mongo_id).first() except exceptions.BadValueException: return None
Returns a :class:`Document` instance from its ``mongo_id`` or ``None`` if not found
def get_or_404(self, mongo_id): document = self.get(mongo_id) if document is None: abort(404) return document
Like :meth:`get` method but aborts with 404 if not found instead of returning `None`
def paginate(self, page, per_page=20, error_out=True): if page < 1 and error_out: abort(404) items = self.skip((page - 1) * per_page).limit(per_page).all() if len(items) < 1 and page != 1 and error_out: abort(404) return Pagination(self, page, per_page, s...
Returns ``per_page`` items from page ``page`` By default, it will abort with 404 if no items were found and the page was larger than 1. This behaviour can be disabled by setting ``error_out`` to ``False``. Returns a :class:`Pagination` object.
def save(self, safe=None): self._session.insert(self, safe=safe) self._session.flush()
Saves the document itself in the database. The optional ``safe`` argument is a boolean that specifies if the remove method should wait for the operation to complete.
def remove(self, safe=None): self._session.remove(self, safe=None) self._session.flush()
Removes the document itself from database. The optional ``safe`` argument is a boolean that specifies if the remove method should wait for the operation to complete.
def list_authors(): authors = Author.query.all() content = '<p>Authors:</p>' for author in authors: content += '<p>%s</p>' % author.name return content
List all authors. e.g.: GET /authors
def disable_option(self): disable = _CXString() conf.lib.clang_getDiagnosticOption(self, byref(disable)) return _CXString.from_result(disable)
The command-line option that disables this diagnostic.
def format(self, options=None): if options is None: options = conf.lib.clang_defaultDiagnosticDisplayOptions() if options & ~Diagnostic._FormatOptionsMask: raise ValueError('Invalid format options') return conf.lib.clang_formatDiagnostic(self, options)
Format this diagnostic for display. The options argument takes Diagnostic.Display* flags, which can be combined using bitwise OR. If the options argument is not provided, the default display options will be used.
def name(self): if self._name_map is None: self._name_map = {} for key, value in self.__class__.__dict__.items(): if isinstance(value, self.__class__): self._name_map[value] = key return self._name_map[self]
Get the enumeration name of this cursor kind.
def spelling(self): if not hasattr(self, '_spelling'): self._spelling = conf.lib.clang_getCursorSpelling(self) return self._spelling
Return the spelling of the entity pointed at by the cursor.
def displayname(self): if not hasattr(self, '_displayname'): self._displayname = conf.lib.clang_getCursorDisplayName(self) return self._displayname
Return the display name for the entity referenced by this cursor. The display name contains extra information that helps identify the cursor, such as the parameters of a function or template or the arguments of a class template specialization.
def mangled_name(self): if not hasattr(self, '_mangled_name'): self._mangled_name = conf.lib.clang_Cursor_getMangling(self) return self._mangled_name
Return the mangled name for the entity referenced by this cursor.
def linkage(self): if not hasattr(self, '_linkage'): self._linkage = conf.lib.clang_getCursorLinkage(self) return LinkageKind.from_id(self._linkage)
Return the linkage of this cursor.
def availability(self): if not hasattr(self, '_availability'): self._availability = conf.lib.clang_getCursorAvailability(self) return AvailabilityKind.from_id(self._availability)
Retrieves the availability of the entity pointed at by the cursor.
def objc_type_encoding(self): if not hasattr(self, '_objc_type_encoding'): self._objc_type_encoding = \ conf.lib.clang_getDeclObjCTypeEncoding(self) return self._objc_type_encoding
Return the Objective-C type encoding as a str.
def from_source(cls, filename, args=None, unsaved_files=None, options=0, index=None): if args is None: args = [] if unsaved_files is None: unsaved_files = [] if index is None: index = Index.create() args_array = None ...
Create a TranslationUnit by parsing source. This is capable of processing source code both from files on the filesystem as well as in-memory contents. Command-line arguments that would be passed to clang are specified as a list via args. These can be used to specify include paths, warn...
def cursor(self): cursor = Cursor() cursor._tu = self._tu conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) return cursor
The Cursor this Token corresponds to.
def process(self): self.index = cindex.Index.create() self.headers = {} for f in self.files: if f in self.processed: continue print('Processing {0}'.format(os.path.basename(f))) tu = self.index.parse(f, self.flags) if len(t...
process processes all the files with clang and extracts all relevant nodes from the generated AST
def visit(self, citer, parent=None): if not citer: return while True: try: item = next(citer) except StopIteration: return # Check the source of item if not item.location.file: self.visit...
visit iterates over the provided cursor iterator and creates nodes from the AST cursors.
def extract(self, filename, tu): it = tu.get_tokens(extent=tu.get_extent(filename, (0, int(os.stat(filename).st_size)))) while True: try: self.extract_loop(it) except StopIteration: break
extract extracts comments from a translation unit for a given file by iterating over all the tokens in the TU, locating the COMMENT tokens and finding out to which cursors the comments semantically belong.
def defaultsnamedtuple(name, fields, defaults=None): nt = collections.namedtuple(name, fields) nt.__new__.__defaults__ = (None,) * len(nt._fields) if isinstance(defaults, collections.Mapping): nt.__new__.__defaults__ = tuple(nt(**defaults)) elif defaults: nt.__new__.__defaults__ = t...
Generate namedtuple with default values. :param name: name :param fields: iterable with field names :param defaults: iterable or mapping with field defaults :returns: defaultdict with given fields and given defaults :rtype: collections.defaultdict
def init_app(self, app): self.app = app if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['plugin_manager'] = self self.reload()
Initialize this Flask extension for given app.
def reload(self): self.clear() for plugin in self.app.config.get('plugin_modules', ()): self.load_plugin(plugin)
Clear plugin manager state and reload plugins. This method will make use of :meth:`clear` and :meth:`load_plugin`, so all internal state will be cleared, and all plugins defined in :data:`self.app.config['plugin_modules']` will be loaded.
def import_plugin(self, plugin): names = [ '%s%s%s' % (namespace, '' if namespace[-1] == '_' else '.', plugin) if namespace else plugin for namespace in self.namespaces ] for name in names: if name in sys.modules: ...
Import plugin by given name, looking at :attr:`namespaces`. :param plugin: plugin module name :type plugin: str :raises PluginNotFoundError: if not found on any namespace
def load_plugin(self, plugin): module = super(RegistrablePluginManager, self).load_plugin(plugin) if hasattr(module, 'register_plugin'): module.register_plugin(self) return module
Import plugin (see :meth:`import_plugin`) and load related data. If available, plugin's module-level :func:`register_plugin` function will be called with current plugin manager instance as first argument. :param plugin: plugin module name :type plugin: str :raises PluginNotFoun...
def register_blueprint(self, blueprint): if blueprint not in self._blueprint_known: self.app.register_blueprint(blueprint) self._blueprint_known.add(blueprint)
Register given blueprint on curren app. This method is provided for using inside plugin's module-level :func:`register_plugin` functions. :param blueprint: blueprint object with plugin endpoints :type blueprint: flask.Blueprint
def _resolve_widget(cls, file, widget): return widget.__class__(*[ value(file) if callable(value) else value for value in widget ])
Resolve widget callable properties into static ones. :param file: file will be used to resolve callable properties. :type file: browsepy.file.Node :param widget: widget instance optionally with callable properties :type widget: object :returns: a new widget instance of the same ...
def iter_widgets(self, file=None, place=None): for filter, dynamic, cwidget in self._widgets: try: if file and filter and not filter(file): continue except BaseException as e: # Exception is handled as this method execution is...
Iterate registered widgets, optionally matching given criteria. :param file: optional file object will be passed to widgets' filter functions. :type file: browsepy.file.Node or None :param place: optional template place hint. :type place: str :yields: widget...
def create_widget(self, place, type, file=None, **kwargs): widget_class = self.widget_types.get(type, self.widget_types['base']) kwargs.update(place=place, type=type) try: element = widget_class(**kwargs) except TypeError as e: message = e.args[0] if e.ar...
Create a widget object based on given arguments. If file object is provided, callable arguments will be resolved: its return value will be used after calling them with file as first parameter. All extra `kwargs` parameters will be passed to widget constructor. :param place: pl...
def register_widget(self, place=None, type=None, widget=None, filter=None, **kwargs): if bool(widget) == bool(place or type): raise InvalidArgumentError( 'register_widget takes either place and type or widget' ) widget = widget...
Create (see :meth:`create_widget`) or use provided widget and register it. This method provides this dual behavior in order to simplify widget creation-registration on an functional single step without sacrifycing the reusability of a object-oriented approach. :param place: whe...
def clear(self): self._mimetype_functions = list(self._default_mimetype_functions) super(MimetypePluginManager, self).clear()
Clear plugin manager state. Registered mimetype functions will be disposed after calling this method.
def get_mimetype(self, path): for fnc in self._mimetype_functions: mime = fnc(path) if mime: return mime return mimetype.by_default(path)
Get mimetype of given path calling all registered mime functions (and default ones). :param path: filesystem path of file :type path: str :returns: mimetype :rtype: str
def extract_plugin_arguments(self, plugin): module = self.import_plugin(plugin) if hasattr(module, 'register_arguments'): manager = ArgumentPluginManager() module.register_arguments(manager) return manager._argparse_argkwargs return ()
Given a plugin name, extracts its registered_arguments as an iterable of (args, kwargs) tuples. :param plugin: plugin name :type plugin: str :returns: iterable if (args, kwargs) tuples. :rtype: iterable
def load_arguments(self, argv, base=None): plugin_parser = argparse.ArgumentParser(add_help=False) plugin_parser.add_argument('--plugin', action='append', default=[]) parent = base or plugin_parser parser = argparse.ArgumentParser( parents=(parent,), add_...
Process given argument list based on registered arguments and given optional base :class:`argparse.ArgumentParser` instance. This method saves processed arguments on itself, and this state won't be lost after :meth:`clean` calls. Processed argument state will be available via :meth:`ge...
def iter_cookie_browse_sorting(cookies): try: data = cookies.get('browse-sorting', 'e30=').encode('ascii') for path, prop in json.loads(base64.b64decode(data).decode('utf-8')): yield path, prop except (ValueError, TypeError, KeyError) as e: logger.exception(e)
Get sorting-cookie from cookies dictionary. :yields: tuple of path and sorting property :ytype: 2-tuple of strings
def get_cookie_browse_sorting(path, default): if request: for cpath, cprop in iter_cookie_browse_sorting(request.cookies): if path == cpath: return cprop return default
Get sorting-cookie data for path of current request. :returns: sorting property :rtype: string
def browse_sortkey_reverse(prop): if prop.startswith('-'): prop = prop[1:] reverse = True else: reverse = False if prop == 'text': return ( lambda x: ( x.is_directory == reverse, x.link.text.lower() if x.link and x.link.text el...
Get sorting function for directory listing based on given attribute name, with some caveats: * Directories will be first. * If *name* is given, link widget lowercase text will be used istead. * If *size* is given, bytesize will be used. :param prop: file attribute name :returns: tuple with sort...
def stream_template(template_name, **context): app.update_template_context(context) template = app.jinja_env.get_template(template_name) stream = template.generate(context) return Response(stream_with_context(stream))
Some templates can be huge, this function returns an streaming response, sending the content in chunks and preventing from timeout. :param template_name: template :param **context: parameters for templates. :yields: HTML strings
def gendict(cls, *args, **kwargs): gk = cls.genkey return dict((gk(k), v) for k, v in dict(*args, **kwargs).items())
Pre-translated key dictionary constructor. See :type:`dict` for more info. :returns: dictionary with uppercase keys :rtype: dict
def nearest(self): try: options = self.jumps[self.current] except KeyError: raise KeyError( 'Current state %r not defined in %s.jumps.' % (self.current, self.__class__) ) offset = len(self.start) index = len...
Get the next state jump. The next jump is calculated looking at :attr:`current` state and its possible :attr:`jumps` to find the nearest and bigger option in :attr:`pending` data. If none is found, the returned next state label will be None. :returns: tuple with index, substri...
def transform(self, data, mark, next): method = getattr(self, 'transform_%s' % self.current, None) return method(data, mark, next) if method else data
Apply the appropriate transformation function on current state data, which is supposed to end at this point. It is expected transformation logic makes use of :attr:`start`, :attr:`current` and :attr:`streaming` instance attributes to bettee know the state is being left. :param ...
def feed(self, data=''): self.streaming = True self.pending += data for i in self: yield i
Optionally add pending data, switch into streaming mode, and yield result chunks. :yields: result chunks :ytype: str
def finish(self, data=''): self.pending += data self.streaming = False for i in self: yield i
Optionally add pending data, turn off streaming mode, and yield result chunks, which implies all pending data will be consumed. :yields: result chunks :ytype: str
def fill(self): if self.exclude: exclude = self.exclude ap = functools.partial(os.path.join, self.path) self._tarfile.add( self.path, "", filter=lambda info: None if exclude(ap(info.name)) else info ) else: ...
Writes data on internal tarfile instance, which writes to current object, using :meth:`write`. As this method is blocking, it is used inside a thread. This method is called automatically, on a thread, on initialization, so there is little need to call it manually.
def write(self, data): self._add.wait() self._data += data if len(self._data) > self._want: self._add.clear() self._result.set() return len(data)
Write method used by internal tarfile instance to output data. This method blocks tarfile execution once internal buffer is full. As this method is blocking, it is used inside the same thread of :meth:`fill`. :param data: bytes to write to internal buffer :type data: bytes ...
def read(self, want=0): if self._finished: if self._finished == 1: self._finished += 1 return "" return EOFError("EOF reached") # Thread communication self._want = want self._add.set() self._result.wait() se...
Read method, gets data from internal buffer while releasing :meth:`write` locks when needed. The lock usage means it must ran on a different thread than :meth:`fill`, ie. the main thread, otherwise will deadlock. The combination of both write and this method running on different ...
def isexec(path): return os.path.isfile(path) and os.access(path, os.X_OK)
Check if given path points to an executable file. :param path: file path :type path: str :return: True if executable, False otherwise :rtype: bool
def fsdecode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None): if not isinstance(path, bytes): return path if not errors: use_strict = PY_LEGACY or os_name == 'nt' errors = 'strict' if use_strict else 'surrogateescape' return path.decode(fs_encoding, errors=errors)
Decode given path. :param path: path will be decoded if using bytes :type path: bytes or str :param os_name: operative system name, defaults to os.name :type os_name: str :param fs_encoding: current filesystem encoding, defaults to autodetected :type fs_encoding: str :return: decoded path ...
def fsencode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None): if isinstance(path, bytes): return path if not errors: use_strict = PY_LEGACY or os_name == 'nt' errors = 'strict' if use_strict else 'surrogateescape' return path.encode(fs_encoding, errors=errors)
Encode given path. :param path: path will be encoded if not using bytes :type path: bytes or str :param os_name: operative system name, defaults to os.name :type os_name: str :param fs_encoding: current filesystem encoding, defaults to autodetected :type fs_encoding: str :return: encoded pa...
def getcwd(fs_encoding=FS_ENCODING, cwd_fnc=os.getcwd): path = fsdecode(cwd_fnc(), fs_encoding=fs_encoding) return os.path.abspath(path)
Get current work directory's absolute path. Like os.getcwd but garanteed to return an unicode-str object. :param fs_encoding: filesystem encoding, defaults to autodetected :type fs_encoding: str :param cwd_fnc: callable used to get the path, defaults to os.getcwd :type cwd_fnc: Callable :return...
def getdebug(environ=os.environ, true_values=TRUE_VALUES): return environ.get('DEBUG', '').lower() in true_values
Get if app is expected to be ran in debug mode looking at environment variables. :param environ: environment dict-like object :type environ: collections.abc.Mapping :returns: True if debug contains a true-like string, False otherwise :rtype: bool
def deprecated(func_or_text, environ=os.environ): def inner(func): message = ( 'Deprecated function {}.'.format(func.__name__) if callable(func_or_text) else func_or_text ) @functools.wraps(func) def new_func(*args, **kwargs): ...
Decorator used to mark functions as deprecated. It will result in a warning being emmitted hen the function is called. Usage: >>> @deprecated ... def fnc(): ... pass Usage (custom message): >>> @deprecated('This is deprecated') ... def fnc(): ... pass :param func_or_...
def usedoc(other): def inner(fnc): fnc.__doc__ = fnc.__doc__ or getattr(other, '__doc__') return fnc return inner
Decorator which copies __doc__ of given object into decorated one. Usage: >>> def fnc1(): ... """docstring""" ... pass >>> @usedoc(fnc1) ... def fnc2(): ... pass >>> fnc2.__doc__ 'docstring'collections.abc.D :param other: anything with a __doc__ attribute :type...
def pathsplit(value, sep=os.pathsep): for part in value.split(sep): if part[:1] == part[-1:] == '"' or part[:1] == part[-1:] == '\'': part = part[1:-1] yield part
Get enviroment PATH elements as list. This function only cares about spliting across OSes. :param value: path string, as given by os.environ['PATH'] :type value: str :param sep: PATH separator, defaults to os.pathsep :type sep: str :yields: every path :ytype: str
def pathparse(value, sep=os.pathsep, os_sep=os.sep): escapes = [] normpath = ntpath.normpath if os_sep == '\\' else posixpath.normpath if '\\' not in (os_sep, sep): escapes.extend(( ('\\\\', '<ESCAPE-ESCAPE>', '\\'), ('\\"', '<ESCAPE-DQUOTE>', '"'), ('\\\'', ...
Get enviroment PATH directories as list. This function cares about spliting, escapes and normalization of paths across OSes. :param value: path string, as given by os.environ['PATH'] :type value: str :param sep: PATH separator, defaults to os.pathsep :type sep: str :param os_sep: OS filesy...
def pathconf(path, os_name=os.name, isdir_fnc=os.path.isdir, pathconf_fnc=getattr(os, 'pathconf', None), pathconf_names=getattr(os, 'pathconf_names', ())): if pathconf_fnc and pathconf_names: return {key: pathconf_fnc(path, key) for key in pathconf_na...
Get all pathconf variables for given path. :param path: absolute fs path :type path: str :returns: dictionary containing pathconf keys and their values (both str) :rtype: dict
def which(name, env_path=ENV_PATH, env_path_ext=ENV_PATHEXT, is_executable_fnc=isexec, path_join_fnc=os.path.join, os_name=os.name): for path in env_path: for suffix in env_path_ext: exe_file = path_join_fnc(path, name) + suffix ...
Get command absolute path. :param name: name of executable command :type name: str :param env_path: OS environment executable paths, defaults to autodetected :type env_path: list of str :param is_executable_fnc: callable will be used to detect if path is executable, de...