Example #1
0
 def HasNestedEventHandler():
     value, set_value = idom.hooks.use_state(False)
     set_value(not value)  # trigger renders forever
     event_handler.current = weakref(set_value)
     button = idom.html.button({"onClick": set_value}, "state is: ", value)
     event_handler.current = weakref(
         button["eventHandlers"]["onClick"].function)
     return idom.html.div(idom.html.div(button))
Example #2
0
 def __init__(s, initializer, debug_rule, debug_id=0, kbdbg_frame=None):
     OrderedDict.__init__(s)
     s.debug_id = debug_id
     s.debug_last_instance_id = 0
     s.debug_rule = weakref(debug_rule)
     s.kbdbg_frame = kbdbg_frame
     for k, v in initializer.items():
         if type(v) is Var:
             s[k] = Var(nolog or (v.debug_name + "_clone"), nolog
                        or weakref(s))
         else:
             s[k] = Atom(v.value, nolog or weakref(s))
Example #3
0
 def __init__(self, channel, level, msg, args=None, kwargs=None,
              exc_info=None, extra=None, frame=None, dispatcher=None):
     #: the name of the logger that created it or any other textual
     #: channel description.  This is a descriptive name and can be
     #: used for filtering.
     self.channel = channel
     #: The message of the log record as new-style format string.
     self.msg = msg
     #: the positional arguments for the format string.
     self.args = args or ()
     #: the keyword arguments for the format string.
     self.kwargs = kwargs or {}
     #: the level of the log record as integer.
     self.level = level
     #: optional exception information.  If set, this is a tuple in the
     #: form ``(exc_type, exc_value, tb)`` as returned by
     #: :func:`sys.exc_info`.
     #: This parameter can also be ``True``, which would cause the exception info tuple
     #: to be fetched for you.
     self.exc_info = exc_info
     #: optional extra information as dictionary.  This is the place
     #: where custom log processors can attach custom context sensitive
     #: data.
     self.extra = ExtraDict(extra or ())
     #: If available, optionally the interpreter frame that pulled the
     #: heavy init.  This usually points to somewhere in the dispatcher.
     #: Might not be available for all calls and is removed when the log
     #: record is closed.
     self.frame = frame
     #: the PID of the current process
     self.process = None
     if dispatcher is not None:
         dispatcher = weakref(dispatcher)
     self._dispatcher = dispatcher
Example #4
0
 def __init__(self, source, extra_params, record):
     self.source = source
     self.extra_params = extra_params
     self.__record = weakref(record) if record is not None else lambda: None
     self.__cached_for_ctx = None
     self.__html = None
     self.__meta = None
Example #5
0
    def __init__(self, treeConfig, nameTuple, description,
        msgArgsInfo, parent=None):
        """Create a topic. Should only be called by TopicManager via its
        getOrCreateTopic() method (which gets called in several places
        in pubsub, such as sendMessage, subscribe, and newTopic).

        :param treeConfig: topic tree configuration settings
        :param nameTuple: topic name, in tuple format (no dots)
        :param description: "docstring" for topic
        :param ArgsInfo msgArgsInfo: object that defines MDS for topic
        :param parent: parent of topic

        :raises ValueError: invalid topic name
        """
        if parent is None:
            if nameTuple != (ALL_TOPICS,):
                msg = 'Only one topic, named %s, can be root of topic tree'
                raise ValueError(msg % 'pub.ALL_TOPICS')
        else:
            validateName(nameTuple)
        self.__tupleName = nameTuple

        self.__handlingUncaughtListenerExc = False
        self._treeConfig = treeConfig
        PublisherMixin.__init__(self)

        self.__validator = None
        # Registered listeners were originally kept in a Python list; however
        # a few methods require lookup of the Listener for the given callable,
        # which is an O(n) operation. A set() could have been more suitable but
        # there is no way of retrieving an element from a set without iterating
        # over the set, again an O(n) operation. A dict() is ok too. Because
        # Listener.__eq__(callable) returns true if the Listener instance wraps
        # the given callable, and because Listener.__hash__ produces the hash
        # value of the wrapped callable, calling dict[callable] on a
        # dict(Listener -> Listener) mapping will be O(1) in most cases:
        # the dict will take the callables hash, find the list of Listeners that
        # have that hash, and then iterate over that inner list to find the
        # Listener instance which satisfies Listener == callable, and will return
        # the Listener.
        self.__listeners = dict()

        # specification:
        self.__description  = None
        self.setDescription(description)
        self.__msgArgs = msgArgsInfo
        if msgArgsInfo.isComplete():
            self.__finalize()
        else:
            assert not self._treeConfig.raiseOnTopicUnspecified

        # now that we know the args are fine, we can link to parent
        self.__parentTopic = None
        self.__subTopics = {}
        if parent is None:
            assert self.hasMDS()
        else:
            self.__parentTopic = weakref(parent)
            assert self.__msgArgs.parentAI() is parent._getListenerSpec()
            parent.__adoptSubtopic( self )
Example #6
0
    def __init__(self, *args, **kwargs):
        super(Kannel, self).__init__(*args, **kwargs)

        reference = weakref(self)

        # set up event handler for incoming messages
        def on_incoming(sender=None, request=None, response=None, **kwargs):
            transport = reference()
            if transport is not None:
                body, status_code = transport.handle(request)
                response.write(body)
                response.status_code = status_code

        kannel_event.connect(on_incoming, sender=self.name, weak=False)
        del on_incoming

        # set up event handler for outgoing messages
        def on_outgoing(sender=None, instance=None, created=False, **kwargs):
            transport = reference()
            if transport is not None:
                if created is True and instance.transport == transport.name:
                    transport.send(instance)

        signals.post_save.connect(on_outgoing, sender=Outgoing, weak=False)
        del on_outgoing
Example #7
0
 def __init__(self, source, extra_params, record):
     self.source = source
     self.extra_params = extra_params
     self.__record = weakref(record) if record is not None else lambda: None
     self.__cached_for_ctx = None
     self.__html = None
     self.__meta = None
Example #8
0
    def listen(self, filename, kind, root, callback):
        """Listens for updates on the specified file.

		filename -- the name of the file to get updates on
		kind -- the kind of file to get updates on
		root -- the listening will go on as long as this object remains alive
		callback -- takes three parameters:
			clientResourceManager -- this manager
			filename -- the original filename requested
			translation -- the new value the filename translates to

		"""
        # NOTE: Weak references always get me in trouble...
        response = self._makeResponse(kind, callback)
        if not hasattr(root, KEEP_ALIVE_FIELD):
            setattr(root, KEEP_ALIVE_FIELD, [])
        getattr(root, KEEP_ALIVE_FIELD).append(response)
        self._listeners[filename] = [
            listener for listener in self._listeners[filename] if listener()
        ]
        self._listeners[filename].append(weakref(response))
        current = self._status[filename]
        if current == STATE_UNKNOWN:
            self._update(filename, STATE_READY)
            if not self._request(filename):
                self._onFileFailed(None, filename)
        else:
            self._update(filename, current)
Example #9
0
 def __init__(self, channel, level, msg, args=None, kwargs=None,
              exc_info=None, extra=None, frame=None, dispatcher=None):
     #: the name of the logger that created it or any other textual
     #: channel description.  This is a descriptive name and can be
     #: used for filtering.
     self.channel = channel
     #: The message of the log record as new-style format string.
     self.msg = msg
     #: the positional arguments for the format string.
     self.args = args or ()
     #: the keyword arguments for the format string.
     self.kwargs = kwargs or {}
     #: the level of the log record as integer.
     self.level = level
     #: optional exception information.  If set, this is a tuple in the
     #: form ``(exc_type, exc_value, tb)`` as returned by
     #: :func:`sys.exc_info`.
     #: This parameter can also be ``True``, which would cause the exception info tuple
     #: to be fetched for you.
     self.exc_info = exc_info
     #: optional extra information as dictionary.  This is the place
     #: where custom log processors can attach custom context sensitive
     #: data.
     self.extra = ExtraDict(extra or ())
     #: If available, optionally the interpreter frame that pulled the
     #: heavy init.  This usually points to somewhere in the dispatcher.
     #: Might not be available for all calls and is removed when the log
     #: record is closed.
     self.frame = frame
     #: the PID of the current process
     self.process = None
     if dispatcher is not None:
         dispatcher = weakref(dispatcher)
     self._dispatcher = dispatcher
Example #10
0
File: repos.py Project: pnasrat/yum
    def __init__(self, ayum):
        self.repos = {} # list of repos by repoid pointing a repo object 
                        # of repo options/misc data
        self.callback = None # progress callback used for populateSack() for importing the xml files
        self.cache = 0
        self.pkgSack = MetaSack()
        self.logger = logging.getLogger("yum.RepoStorage")

        self._setup = False

        self.ayum = weakref(ayum)
        # callbacks for handling gpg key imports for repomd.xml sig checks
        # need to be set from outside of the repos object to do anything
        # even quasi-useful
        # defaults to what is probably sane-ish
        self.gpg_import_func = _wrap_ayum_getKeyForRepo(ayum)
        self.gpgca_import_func = _wrap_ayum_getKeyForRepo(ayum, ca=True)
        self.confirm_func = None

        # This allow listEnabled() to be O(1) most of the time.
        self._cache_enabled_repos = []
        self.quick_enable_disable = {}

        #  This allows plugins to setup a repo. just before the first
        # listEnabled() call.
        self._list_enabled_hasrun = False
Example #11
0
	def __init__(s, debug_name, debug_locals):
		super().__init__()
		s.debug_name = debug_name
		s.debug_locals = weakref(debug_locals) if debug_locals != None else None
		if debug_locals != None:
			s.kbdbg_name = debug_locals.kbdbg_frame
		s.kbdbg_name += "_" + urllib.parse.quote_plus(debug_name)
Example #12
0
    def __init__(self, *args, **kwargs):
        super(HTTP, self).__init__(*args, **kwargs)

        reference = weakref(self)

        # set up event handler for incoming messages
        def on_incoming(sender=None, name=None, request=None, response=None, **kwargs):
            transport = reference()
            if transport is not None and name == transport.name:
                body, status_code = transport.handle(request)
                response.write(body)
                response.status_code = status_code

        http_event.connect(on_incoming, weak=False)
        del on_incoming

        # set up event handler for outgoing messages
        def on_outgoing(sender=None, instance=None, created=False, **kwargs):
            transport = reference()
            if transport is not None:
                if created is True and instance.connection.transport == transport.name:
                    try:
                        suppress = instance.in_response_to.message.suppress_responses
                    except:
                        pass
                    else:
                        if suppress:
                            return
                    
                    transport.send(instance)

        signals.post_save.connect(on_outgoing, sender=Outgoing, weak=False)
        del on_outgoing
Example #13
0
    def __init__(self, history, row):
        self._history = weakref(history)

        self.tid = row[0]
        self.beg_timestamp = row[1]
        self.beg_rpmdbversion = row[2]
        self.end_timestamp = row[3]
        self.end_rpmdbversion = row[4]
        self.loginuid = row[5]
        self.return_code = row[6]

        self._loaded_TW = None
        self._loaded_TD = None
        self._loaded_TS = None

        self._loaded_PROB = None

        self._have_loaded_CMD = False  # cmdline can validly be None
        self._loaded_CMD = None

        self._loaded_ER = None
        self._loaded_OT = None

        self.altered_lt_rpmdb = None
        self.altered_gt_rpmdb = None
Example #14
0
 def __init__(self, channel, level, msg, args=None, kwargs=None,
              exc_info=None, extra=None, frame=None, dispatcher=None):
     #: the name of the logger that created it or any other textual
     #: channel description.  This is a descriptive name and should not
     #: be used for filtering.  A log record might have a
     #: :attr:`dispatcher` defined which provides more information for
     #: filtering if this is absolutely necessary.
     self.channel = channel
     #: The message of the log record as new-style format string.
     self.msg = msg
     #: the positional arguments for the format string.
     self.args = args or ()
     #: the keyword arguments for the format string.
     self.kwargs = kwargs or {}
     #: the level of the log record as integer.
     self.level = level
     #: optional exception information.  If set, this is a tuple in the
     #: form ``(exc_type, exc_value, tb)`` as returned by
     #: :func:`sys.exc_info`.
     self.exc_info = exc_info
     #: optional extra information as dictionary.  This is the place
     #: where custom log processors can attach custom context sensitive
     #: data.
     self.extra = ExtraDict(extra or ())
     #: If available, optionally the interpreter frame that created the
     #: log record.  Might not be available for all calls and is removed
     #: when the log record is closed.
     self.frame = frame
     #: the PID of the current process
     self.process = os.getpid()
     if dispatcher is not None:
         dispatcher = weakref(dispatcher)
     self._dispatcher = dispatcher
Example #15
0
    def __init__(self, treeConfig: TreeConfig, nameTuple: Tuple[str, ...], description: str,
                 msgArgsInfo: ArgsInfo, parent: Topic = None):
        """
        Create a topic. Should only be called by TopicManager via its
        getOrCreateTopic() method (which gets called in several places
        in pubsub, such as sendMessage, subscribe, and newTopic).

        :param treeConfig: topic tree configuration settings
        :param nameTuple: topic name, in tuple format (no dots)
        :param description: "docstring" for topic
        :param ArgsInfo msgArgsInfo: object that defines MDS for topic
        :param parent: parent of topic

        :raises ValueError: invalid topic name
        """
        if parent is None:
            if nameTuple != (ALL_TOPICS,):
                msg = 'Only one topic, named %s, can be root of topic tree'
                raise ValueError(msg % 'pub.ALL_TOPICS')
        else:
            validateName(nameTuple)
        self.__tupleName = nameTuple

        self.__handlingUncaughtListenerExc = False
        self._treeConfig = treeConfig

        self.__validator = None
        # Registered listeners were originally kept in a Python list; however
        # a few methods require lookup of the Listener for the given callable,
        # which is an O(n) operation. A set() could have been more suitable but
        # there is no way of retrieving an element from a set without iterating
        # over the set, again an O(n) operation. A dict() is ok too. Because
        # Listener.__eq__(callable) returns true if the Listener instance wraps
        # the given callable, and because Listener.__hash__ produces the hash
        # value of the wrapped callable, calling dict[callable] on a
        # dict(Listener -> Listener) mapping will be O(1) in most cases:
        # the dict will take the callables hash, find the list of Listeners that
        # have that hash, and then iterate over that inner list to find the
        # Listener instance which satisfies Listener == callable, and will return
        # the Listener.
        self.__listeners = dict()

        # specification:
        self.__description = None
        self.setDescription(description)
        self.__msgArgs = msgArgsInfo
        if msgArgsInfo.isComplete():
            self.__finalize()
        else:
            assert not self._treeConfig.raiseOnTopicUnspecified

        # now that we know the args are fine, we can link to parent
        self.__parentTopic = None
        self.__subTopics = {}
        if parent is None:
            assert self.hasMDS()
        else:
            self.__parentTopic = weakref(parent)
            assert self.__msgArgs.parentAI() is parent.__msgArgs
            parent.__adoptSubtopic(self)
Example #16
0
    def __init__(self, ayum):
        self.repos = {}  # list of repos by repoid pointing a repo object
        # of repo options/misc data
        self.callback = None  # progress callback used for populateSack() for importing the xml files
        self.cache = 0
        self.pkgSack = MetaSack()
        self.logger = logging.getLogger("yum.RepoStorage")

        self._setup = False

        self.ayum = weakref(ayum)
        # callbacks for handling gpg key imports for repomd.xml sig checks
        # need to be set from outside of the repos object to do anything
        # even quasi-useful
        # defaults to what is probably sane-ish
        self.gpg_import_func = _wrap_ayum_getKeyForRepo(ayum)
        self.gpgca_import_func = _wrap_ayum_getKeyForRepo(ayum, ca=True)
        self.confirm_func = None

        # This allow listEnabled() to be O(1) most of the time.
        self._cache_enabled_repos = []
        self.quick_enable_disable = {}

        #  This allows plugins to setup a repo. just before the first
        # listEnabled() call.
        self._list_enabled_hasrun = False
    def __init__(self, history, row):
        self._history = weakref(history)

        self.tid              = row[0]
        self.beg_timestamp    = row[1]
        self.beg_rpmdbversion = row[2]
        self.end_timestamp    = row[3]
        self.end_rpmdbversion = row[4]
        self.loginuid         = row[5]
        self.return_code      = row[6]

        self._loaded_TW = None
        self._loaded_TD = None
        self._loaded_TS = None

        self._loaded_PROB = None

        self._have_loaded_CMD = False # cmdline can validly be None
        self._loaded_CMD = None

        self._loaded_ER = None
        self._loaded_OT = None

        self.altered_lt_rpmdb = None
        self.altered_gt_rpmdb = None
Example #18
0
	def prepare_grammar(s, scope):
		#s.marpa.t.input.clear()
		log("prepare grammar..")
		for i in s.editor.root.flatten():
			i.forget_symbols() # todo:start using visitors
		s.marpa.collect_grammar(scope)
		assert s.current_parser_node
		s.marpa.enqueue_precomputation(weakref(s.current_parser_node))
Example #19
0
File: io.py Project: joke325/Pyrop
 def __init__(self, own, iid):
     self.__own = weakref(own)
     self.__lib = own.lib
     if iid is None or iid.value is None:
         raise RopError(self.__own().ROP_ERROR_NULL_HANDLE)
     self.__iid = iid
     self._reader = None
     self._rcloser = None
Example #20
0
    def __init__(self, history, rpid, problem, text):
        self._history = weakref(history)

        self.rpid = rpid
        self.problem = problem
        self.text = text

        self._loaded_P = None
Example #21
0
 def __init__(self, own, sid):
     self.__own = weakref(own)
     self.__lib = own.lib
     if sid is None or sid.value is None:
         raise RopError(self.__own().ROP_ERROR_NULL_HANDLE)
     self.__sid = sid
     self.__pass_provider = None
     self.__key_provider = None
    def __init__(self, history, rpid, problem, text):
        self._history = weakref(history)

        self.rpid = rpid
        self.problem = problem
        self.text = text

        self._loaded_P = None
Example #23
0
File: io.py Project: joke325/Pyrop
 def __init__(self, own, oid):
     self.__own = weakref(own)
     self.__lib = own.lib
     if oid is None or oid.value is None:
         raise RopError(self.__own().ROP_ERROR_NULL_HANDLE)
     self.__oid = oid
     self._writer = None
     self._wcloser = None
Example #24
0
	def __init__(s, initializer, debug_rule, debug_id = 0, kbdbg_frame=None):
		super().__init__()
		s.debug_id = debug_id
		s.debug_last_instance_id = 0
		s.debug_rule = weakref(debug_rule)
		s.kbdbg_frame = kbdbg_frame
		for k,v in initializer.items():
			s[k] = v.__class__(v.debug_name, s)
Example #25
0
    def __init__(
        self,
        channel,
        level,
        msg,
        args=None,
        kwargs=None,
        exc_info=None,
        extra=None,
        frame=None,
        dispatcher=None,
        frame_correction=0,
    ):
        #: the name of the logger that created it or any other textual
        #: channel description.  This is a descriptive name and can be
        #: used for filtering.
        self.channel = channel
        #: The message of the log record as new-style format string.
        self.msg = msg
        #: the positional arguments for the format string.
        self.args = args or ()
        #: the keyword arguments for the format string.
        self.kwargs = kwargs or {}
        #: the level of the log record as integer.
        self.level = level
        #: optional exception information.  If set, this is a tuple in the
        #: form ``(exc_type, exc_value, tb)`` as returned by
        #: :func:`sys.exc_info`.
        #: This parameter can also be ``True``, which would cause the exception
        #: info tuple to be fetched for you.
        if not exc_info:
            # this is a special case where exc_info=False can be passed in
            # theory, and it should be the same as exc_info=None
            exc_info = None
        self.exc_info = exc_info
        #: optional extra information as dictionary.  This is the place
        #: where custom log processors can attach custom context sensitive
        #: data.

        # TODO: Replace the lambda with str when we remove support for python 2
        self.extra = defaultdict(lambda: u"", extra or ())
        #: If available, optionally the interpreter frame that pulled the
        #: heavy init.  This usually points to somewhere in the dispatcher.
        #: Might not be available for all calls and is removed when the log
        #: record is closed.
        self.frame = frame
        #: A positive integer telling the number of frames to go back from
        #: the frame which triggered the log entry. This is mainly useful
        #: for decorators that want to show that the log was emitted from
        #: form the function they decorate
        self.frame_correction = frame_correction
        #: the PID of the current process
        self.process = None
        if dispatcher is not None:
            dispatcher = weakref(dispatcher)
        self._dispatcher = dispatcher
Example #26
0
 def __init__(self, client=None):
     breadcrumbs = raven.breadcrumbs.make_buffer(
         client is None or client.enable_breadcrumbs)
     if client is not None:
         client = weakref(client)
     self._client = client
     self.activate()
     self.data = {}
     self.exceptions_to_skip = set()
     self.breadcrumbs = breadcrumbs
Example #27
0
    def contribute_to_class(self, ModelClass, name):
        # Use weakref because of possible memory leak / circular reference.
        self._model = weakref(ModelClass)
        original_save = ModelClass.save

        def save_and_clear_cache(instance, *args, **kwargs):
            original_save(instance, *args, **kwargs)
            self.clear(instance=instance)

        setattr(ModelClass, name, self)
Example #28
0
    def get_connection(self, command_name, shard_hint=None):
        host_id = shard_hint
        if host_id is None:
            raise RuntimeError('The routing pool requires the host id '
                               'as shard hint')

        real_pool = self.cluster.get_pool_for_host(host_id)
        con = real_pool.get_connection(command_name)
        con.__creating_pool = weakref(real_pool)
        return con
Example #29
0
    def get_connection(self, command_name, shard_hint=None):
        host_id = shard_hint
        if host_id is None:
            raise RuntimeError('The routing pool requires the host id '
                               'as shard hint')

        real_pool = self.cluster.get_pool_for_host(host_id)
        con = real_pool.get_connection(command_name)
        con.__creating_pool = weakref(real_pool)
        return con
    def contribute_to_class(self, ModelClass, name):
        # Use weakref because of possible memory leak / circular reference.
        self._model = weakref(ModelClass)
        original_save = ModelClass.save

        def save_and_clear_cache(instance, *args, **kwargs):
            original_save(instance, *args, **kwargs)
            self.clear(instance=instance)

        setattr(ModelClass, name, self)
Example #31
0
    def __init__(self,
                 base,
                 searchpath,
                 optparser=None,
                 types=None,
                 pluginconfpath=None,
                 disabled=None,
                 enabled=None):
        '''Initialise the instance.

        @param base: The
        @param searchpath: A list of paths to look for plugin modules.
        @param optparser: The OptionParser instance for this run (optional).
            Use to allow plugins to extend command line options.
        @param types: A sequence specifying the types of plugins to load.
            This should be sequnce containing one or more of the TYPE_...
            constants. If None (the default), all plugins will be loaded.
        @param pluginconfpath: A list of paths to look for plugin configuration
            files. Defaults to "/etc/yum/pluginconf.d".
        '''
        if not pluginconfpath:
            pluginconfpath = ['/etc/yum/pluginconf.d']

        self.searchpath = searchpath
        self.pluginconfpath = pluginconfpath
        self.base = weakref(base)
        self.optparser = optparser
        self.cmdline = (None, None)
        self.verbose_logger = logging.getLogger("yum.verbose.YumPlugins")
        self.disabledPlugins = disabled
        self.enabledPlugins = enabled
        if types is None:
            types = ALL_TYPES
        if not isinstance(types, (list, tuple)):
            types = (types, )

        if id(TYPE_INTERFACE) in [id(t) for t in types]:
            self.verbose_logger.log(
                logginglevels.INFO_2,
                'Deprecated constant TYPE_INTERFACE during plugin '
                'initialization.\nPlease use TYPE_INTERACTIVE instead.')

        self._importplugins(types)

        self.cmdlines = {}

        # Call close handlers when yum exit's
        if self._pluginfuncs['close']:
            self.verbose_logger.error(
                _('One or more plugins uses "close" handling but should use atexit directly.'
                  ))
            atexit.register(self.run, 'close')

        # Let plugins register custom config file options
        self.run('config')
Example #32
0
    def __init__(self,
                 channel,
                 level,
                 msg,
                 args=None,
                 kwargs=None,
                 exc_info=None,
                 extra=None,
                 frame=None,
                 dispatcher=None,
                 frame_correction=0):
        #: the name of the logger that created it or any other textual
        #: channel description.  This is a descriptive name and can be
        #: used for filtering.
        self.channel = channel
        #: The message of the log record as new-style format string.
        self.msg = msg
        #: the positional arguments for the format string.
        self.args = args or ()
        #: the keyword arguments for the format string.
        self.kwargs = kwargs or {}
        #: the level of the log record as integer.
        self.level = level
        #: optional exception information.  If set, this is a tuple in the
        #: form ``(exc_type, exc_value, tb)`` as returned by
        #: :func:`sys.exc_info`.
        #: This parameter can also be ``True``, which would cause the exception
        #: info tuple to be fetched for you.
        if not exc_info:
            # this is a special case where exc_info=False can be passed in
            # theory, and it should be the same as exc_info=None
            exc_info = None
        self.exc_info = exc_info
        #: optional extra information as dictionary.  This is the place
        #: where custom log processors can attach custom context sensitive
        #: data.

        # TODO: Replace the lambda with str when we remove support for python 2
        self.extra = defaultdict(lambda: u'', extra or ())
        #: If available, optionally the interpreter frame that pulled the
        #: heavy init.  This usually points to somewhere in the dispatcher.
        #: Might not be available for all calls and is removed when the log
        #: record is closed.
        self.frame = frame
        #: A positive integer telling the number of frames to go back from
        #: the frame which triggered the log entry. This is mainly useful
        #: for decorators that want to show that the log was emitted from
        #: form the function they decorate
        self.frame_correction = frame_correction
        #: the PID of the current process
        self.process = None
        if dispatcher is not None:
            dispatcher = weakref(dispatcher)
        self._dispatcher = dispatcher
Example #33
0
 def recursive_clone(s):
     r = Var(nolog or s.debug_name, nolog or s.debug_locals)
     if not nolog:
         r.kbdbg_name = s.kbdbg_name
     if s.bound_to:
         r.bound_to = s.bound_to.recursive_clone()
     r.bnode = weakref(s.bnode()) if s.bnode() else lambda: None
     if s.bnode():
         r.is_a_bnode_from_original_rule = s.is_a_bnode_from_original_rule
         r.is_from_name = s.is_from_name
     return r
Example #34
0
    def __init__(self, topicMgr, nameTuple, description, parent=None,
                 argsSpec=None, reqdArgs=(), msgArgs=None, deadListenerCB=None):
        '''Specify the name, description, and parent of this Topic. Any remaining 
        keyword arguments (which will be put in msgArgs) describe the arguments that 
        a listener of this topic must support (i.e., the key is the argument name and
        the value is a documentation string explaining what the argument is for). 
        The reqdArgs is an optional list of names identifying which variables in 
        msgArgs keys are required arguments. E.g. 
        
            Topic(('a','b'), 'what is topic for', parentTopic, _reqdArgs=('c','d'), 
                c='what is c for', d='what is d for', e='what is e for')
            
        would create a Topic whose listeners would have to be of the form
        
            callable(c, d, e=...)
            
        ie 
            callable(c, d, e=...)
            callable(self, c, d, e=..., **kwargs) (method)
            
        would all be valid listeners but 
        
            callable(c, e=...) # error: required d is missing
            callable(c, d, e)  # error: e is optional
        
        would not be valid listeners of this topic. 
        
        The _useKwa is only used by the package to indicate whether the arguments are
        specified as part of __init__ (there is no other way since msgArgs cannot be None). 
        '''
        self.__validateName(nameTuple, parent is None)
        self.__tupleName = nameTuple

        self.__validator    = None
        self.__listeners    = []
        self.__deadListenerCB = deadListenerCB
        
        # specification: 
        self.__description  = None
        self.setDescription(description)
        getArgsSpec = topicMgr._getDefnProvider_().getSubSpec
        self.__msgArgs      = ArgsInfo(getArgsSpec, nameTuple, 
                                       parent, msgArgs, reqdArgs, argsSpec) 
        if self.__msgArgs.isComplete():
            self.__finalize()
        self.argsSpec = self.__msgArgs
        
        # now that we know the args are fine, we can link to parent
        self.__parentTopic = None
        if parent is None:
            assert self.isSendable()
        else:
            self.__parentTopic = weakref(parent)
            parent.__setSubtopic( self.getTailName(), self )
Example #35
0
def test_weakref():
    from weakref import ref as weakref
    from inspect import isfunction, ismethod

    class Foo:
        def instanceMethod(self):
            pass

        @classmethod
        def classMethod(cls):
            pass

        def __call__(self):
            pass

    assert isfunction(Foo.instanceMethod)
    wr = weakref(Foo.instanceMethod)
    assert wr() is not None, 'Foo.instanceMethod'

    assert ismethod(Foo.classMethod)
    wr = weakref(Foo.classMethod)
    gc.collect()  # for pypy: the gc doesn't work the same as cpython's
    assert wr() is None, 'Foo.classMethod'

    foo = Foo()
    fooWR = weakref(foo)
    assert fooWR() is not None, 'foo'

    assert ismethod(foo.instanceMethod)
    wr = weakref(foo.instanceMethod)
    gc.collect()  # for pypy: the gc doesn't work the same as cpython's
    assert wr() is None, 'foo.instanceMethod'

    assert ismethod(foo.classMethod)
    wr = weakref(foo.classMethod)
    gc.collect()  # for pypy: the gc doesn't work the same as cpython's
    assert wr() is None, 'foo.classMethod'

    del foo
    gc.collect()
    assert fooWR() is None, 'foo'
Example #36
0
	def __init__(s, initializer, debug_rule, debug_id = 0, kbdbg_frame=None):
		if dbg:
			super().__init__()
			s.debug_id = debug_id
			s.debug_last_instance_id = 0
			s.debug_rule = weakref(debug_rule)
			s.kbdbg_frame = kbdbg_frame
		for k,v in initializer.items():
			if type(v) == Var:
				s[k] = Var(v.debug_name + "_clone")
			else:
				s[k] = Atom(v.value)
Example #37
0
 def __init__(self, client=None):
     breadcrumbs = raven.breadcrumbs.make_buffer(
         client is None or client.enable_breadcrumbs)
     if client is not None:
         client = weakref(client)
     self._client = client
     # Because the thread auto activates the thread local this also
     # means that we auto activate this thing.  Only if someone decides
     # to deactivate manually later another call to activate is
     # technically necessary.
     self.activate()
     self.data = {}
     self.exceptions_to_skip = set()
     self.breadcrumbs = breadcrumbs
Example #38
0
 def __init__(self, mgr, name, files):
     self._mgr = weakref(mgr)
     self.name = name
     self._css = []
     self._js = []
     for filename in files:
         assert "." in filename, "unknown file without extension"
         ext = filename.rsplit(".", 1)[-1]
         if ext == "js":
             self._js.append(filename)
         elif ext == "css":
             self._css.append(filename)
         else:
             assert False, 'unknown extension ".%s"' % ext
Example #39
0
 def __init__(self, client=None):
     breadcrumbs = raven.breadcrumbs.make_buffer(
         client is None or client.enable_breadcrumbs)
     if client is not None:
         client = weakref(client)
     self._client = client
     # Because the thread auto activates the thread local this also
     # means that we auto activate this thing.  Only if someone decides
     # to deactivate manually later another call to activate is
     # technically necessary.
     self.activate()
     self.data = {}
     self.exceptions_to_skip = set()
     self.breadcrumbs = breadcrumbs
Example #40
0
 def __init__(s, debug_name, debug_locals):
     s.debug_name = debug_name
     if not nolog:
         Kbdbgable.__init__(s)
         if isinstance(debug_locals, weakref):
             s.debug_locals = debug_locals
         elif debug_locals == None:
             s.debug_locals = None
         else:
             s.debug_locals = weakref(debug_locals)
         if s.debug_locals != None:
             s.kbdbg_name = s.debug_locals().kbdbg_frame
         assert (debug_name != None)
         s.kbdbg_name += "_" + quote_plus(debug_name)
Example #41
0
	def __init__(s, debug_name, debug_locals):
		if dbg:
			super().__init__()
			s.debug_name = debug_name
			if type(debug_locals) == weakref:
				s.debug_locals = debug_locals
			elif debug_locals == None:
				s.debug_locals = None
			else:
				s.debug_locals = weakref(debug_locals)
			if debug_locals != None:
				s.kbdbg_name = debug_locals.kbdbg_frame
			assert(debug_name)
			s.kbdbg_name += "_" + urllib.parse.quote_plus(debug_name)
Example #42
0
 def __init__(self, mgr, name, files):
     self._mgr = weakref(mgr)
     self.name = name
     self._css = []
     self._js = []
     for filename in files:
         assert '.' in filename, 'unknown file without extension'
         ext = filename.rsplit('.', 1)[-1]
         if ext == 'js':
             self._js.append(filename)
         elif ext == 'css':
             self._css.append(filename)
         else:
             assert False, 'unknown extension ".%s"' % ext
Example #43
0
def test_weakref():
    from weakref import ref as weakref
    from inspect import isfunction, ismethod

    class Foo:
        def instanceMethod(self): pass
        @classmethod
        def classMethod(cls): pass
        def __call__(self): pass

    assert isfunction(Foo.instanceMethod)
    wr = weakref(Foo.instanceMethod)
    assert wr() is not None, 'Foo.instanceMethod'

    assert ismethod(Foo.classMethod)
    wr = weakref(Foo.classMethod)
    gc.collect() # for pypy: the gc doesn't work the same as cpython's
    assert wr() is None, 'Foo.classMethod'

    foo = Foo()
    fooWR = weakref(foo)
    assert fooWR() is not None, 'foo'

    assert ismethod(foo.instanceMethod)
    wr = weakref(foo.instanceMethod)
    gc.collect() # for pypy: the gc doesn't work the same as cpython's
    assert wr() is None, 'foo.instanceMethod'

    assert ismethod(foo.classMethod)
    wr = weakref(foo.classMethod)
    gc.collect() # for pypy: the gc doesn't work the same as cpython's
    assert wr() is None, 'foo.classMethod'

    del foo
    gc.collect()
    assert fooWR() is None, 'foo'
Example #44
0
File: plugins.py Project: dmnks/yum
    def __init__(self, base, searchpath, optparser=None, types=None, 
            pluginconfpath=None,disabled=None,enabled=None):
        '''Initialise the instance.

        @param base: The
        @param searchpath: A list of paths to look for plugin modules.
        @param optparser: The OptionParser instance for this run (optional).
            Use to allow plugins to extend command line options.
        @param types: A sequence specifying the types of plugins to load.
            This should be sequnce containing one or more of the TYPE_...
            constants. If None (the default), all plugins will be loaded.
        @param pluginconfpath: A list of paths to look for plugin configuration
            files. Defaults to "/etc/yum/pluginconf.d".
        '''
        if not pluginconfpath:
            pluginconfpath = ['/etc/yum/pluginconf.d']

        self.searchpath = searchpath
        self.pluginconfpath = pluginconfpath
        self.base = weakref(base)
        self.optparser = optparser
        self.cmdline = (None, None)
        self.verbose_logger = logging.getLogger("yum.verbose.YumPlugins")
        self.disabledPlugins = disabled
        self.enabledPlugins  = enabled
        if types is None:
            types = ALL_TYPES
        if not isinstance(types, (list, tuple)):
            types = (types,)

        if id(TYPE_INTERFACE) in [id(t) for t in types]:
            self.verbose_logger.log(logginglevels.INFO_2,
                    'Deprecated constant TYPE_INTERFACE during plugin '
                    'initialization.\nPlease use TYPE_INTERACTIVE instead.')

        self._importplugins(types)

        self.cmdlines = {}

        # Call close handlers when yum exit's
        if self._pluginfuncs['close']:
            self.verbose_logger.error(
                _('One or more plugins uses "close" handling but should use atexit directly.'))
            atexit.register(self.run, 'close')

        # Let plugins register custom config file options
        self.run('config')
Example #45
0
    def __init__(self, ayum):
        self.repos = {} # list of repos by repoid pointing a repo object 
                        # of repo options/misc data
        self.callback = None # progress callback used for populateSack() for importing the xml files
        self.cache = 0
        self.pkgSack = MetaSack()
        self.logger = logging.getLogger("yum.RepoStorage")

        self._setup = False

        self.ayum = weakref(ayum)
        # callbacks for handling gpg key imports for repomd.xml sig checks
        # need to be set from outside of the repos object to do anything
        # even quasi-useful
        # defaults to what is probably sane-ish
        self.gpg_import_func = _wrap_ayum_getKeyForRepo(ayum)
        self.confirm_func = None
Example #46
0
 def newfunc(*args, **kwargs):
     if policy == POLICY_MANY:
         # just start the timer
         t = (timer or Timer)(func, *args, **kwargs)
         t.start(interval)
         return True
     store = DecoratorDataStore(func, newfunc, args)
     # check current timer
     if 'timer' in store and store.timer and store.timer.active:
         if policy == POLICY_ONCE:
             # timer already running and not override
             return False
         # stop old timer
         store.timer.stop()
     # create new timer, store it in the object and start it
     t = (timer or Timer)(func, *args, **kwargs)
     store.timer = weakref(t)
     t.start(interval)
     return True
Example #47
0
    def get_connection(self, command_name, shard_hint=None):
        host_id = shard_hint
        if host_id is None:
            raise RuntimeError('The routing pool requires the host id '
                               'as shard hint')

        real_pool = self.cluster.get_pool_for_host(host_id)

        # When we check something out from the real underlying pool it's
        # very much possible that the connection is stale.  This is why we
        # check out up to 10 connections which are either not connected
        # yet or verified alive.
        for _ in xrange(10):
            con = real_pool.get_connection(command_name)
            if con._sock is None or not is_closed(con._sock):
                con.__creating_pool = weakref(real_pool)
                return con

        raise ConnectionError('Failed to check out a valid connection '
                              '(host %s)' % host_id)
Example #48
0
    def get_connection(self, command_name, shard_hint=None):
        host_id = shard_hint
        if host_id is None:
            raise RuntimeError('The routing pool requires the host id '
                               'as shard hint')

        real_pool = self.cluster.get_pool_for_host(host_id)

        # When we check something out from the real underlying pool it's
        # very much possible that the connection is stale.  This is why we
        # check out up to 10 connections which are either not connected
        # yet or verified alive.
        for _ in xrange(10):
            con = real_pool.get_connection(command_name)
            if con._sock is None or not is_closed(con._sock):
                con.__creating_pool = weakref(real_pool)
                return con

        raise ConnectionError('Failed to check out a valid connection '
                              '(host %s)' % host_id)
Example #49
0
 def _find_control(self, x, y):
     ctrl = self.get_control()
     if ctrl is not None and ctrl.active:
         return ctrl
     width, height = self.scale()
     if x < 0 or x > width or y < 0 or y > height:
         # the mouse is not even in the widget
         pass
     else:
         for level in range(0, 2):
             for curve in self._curves:
                 ctrl = curve.get_control(x, y, level)
                 if ctrl is not None:
                     self._ctrl = weakref(ctrl)
                     break
             if ctrl is not None:
                 break
     if ctrl is None:
         self._ctrl = None
     return ctrl
Example #50
0
 def __init__(self,
              ref,
              parent,
              scope,
              key=None,
              descriptor_type=None,
              synchronized=False):
     self._ref = weakref(ref)
     if parent is not None:
         parent = parent.__dependency_info__
     self.parent = parent
     self.scope = scope
     self.instances = {}
     self.key = key
     self.descriptor_type = descriptor_type
     self.active = 0
     self.closed = False
     self.synchronized = synchronized
     if synchronized:
         self._lock = RLock()
Example #51
0
        def __import_target(self):
            context = Context.current
            ProxyBase.__setattr__(self, '__context', context)
            name = context[id(self)]
            if ':' in name:
                name, objname = name.split(':', 1)
            else:
                objname = None

            module = import_module(name)
            target = getattr(module, objname) if objname else module

            try:
                target = weakref(target)
            except TypeError:
                ProxyBase.__setattr__(self, '__is_weakref', False)
            else:
                ProxyBase.__setattr__(self, '__is_weakref', True)

            ProxyBase.__setattr__(self, '__target', target)
Example #52
0
    def delTopic(self, name):
        '''Undefines the named topic. Returns True if the subtopic was 
        removed, false otherwise (ie the topic doesn't exist). Also 
        unsubscribes any listeners of topic. Note that it must undefine 
        all subtopics to all depths, and unsubscribe their listeners. '''
        # find from which parent the topic object should be removed
        dottedName = stringize(name)
        try:
            obj = weakref( self._topicsMap[dottedName] )
        except KeyError:
            return False
            
        assert obj().getName() == dottedName
        # notification must be before deletion in case 
        if self.__notifyOnDelTopic:
            Policies._notificationHandler.notifyDelTopic(dottedName)
        
        obj()._undefineSelf_(self._topicsMap)
        assert obj() is None

        return True
Example #53
0
    def __init__(
        self,
        parent: Optional[_ModelState],
        index: int,
        key: Any,
        model: Ref[VdomJson],
        patch_path: str,
        children_by_key: Dict[str, _ModelState],
        targets_by_event: Dict[str, str],
        life_cycle_state: Optional[_LifeCycleState] = None,
    ):
        self.index = index
        """The index of the element amongst its siblings"""

        self.key = key
        """A key that uniquely identifies the element amongst its siblings"""

        self.model = model
        """The actual model of the element"""

        self.patch_path = patch_path
        """A "/" delimitted path to the element within the greater layout"""

        self.children_by_key = children_by_key
        """Child model states indexed by their unique keys"""

        self.targets_by_event = targets_by_event
        """The element's event handler target strings indexed by their event name"""

        # === Conditionally Available Attributes ===
        # It's easier to conditionally assign than to force a null check on every usage

        if parent is not None:
            self._parent_ref = weakref(parent)
            """The parent model state"""

        if life_cycle_state is not None:
            self.life_cycle_state = life_cycle_state
            """The state for the element's component (if it has one)"""
Example #54
0
 def __init__(self, logger_name, level, msg, args=None, kwargs=None,
              exc_info=None, extra=None, frame=None, channel=None):
     #: the time of the log record creation as :class:`datetime.datetime`
     #: object.
     self.time = datetime.utcnow()
     #: the name of the logger that created it.  This is a descriptive
     #: name and should not be used for logging.  A log record might have
     #: a :attr:`channel` defined which provides more information for
     #: filtering if this is absolutely necessary.
     self.logger_name = logger_name
     #: The message of the log record as new-style format string.
     self.msg = msg
     #: the positional arguments for the format string.
     self.args = args or ()
     #: the keyword arguments for the format string.
     self.kwargs = kwargs or {}
     #: the level of the log record as integer.
     self.level = level
     #: optional exception information.  If set, this is a tuple in the
     #: form ``(exc_type, exc_value, tb)`` as returned by
     #: :func:`sys.exc_info`.
     self.exc_info = exc_info
     #: optional extra information as dictionary.  This is the place
     #: where custom log processors can attach custom context sensitive
     #: data.
     self.extra = ExtraDict(extra or ())
     #: If available, optionally the interpreter frame that created the
     #: log record.  Might not be available for all calls and is removed
     #: when the log record is closed.
     self.frame = frame
     #: the PID of the current process
     self.process = os.getpid()
     if channel is not None:
         channel = weakref(channel)
     self._channel = channel
     self._information_pulled = False
Example #55
0
 def __init__(self, ayum, ca=False):
     self.ayum = weakref(ayum)
     self.ca = ca
Example #56
0
 def canonicalize(self, value):
     value = toterm(value)
     if isinstance(value, _Constant):
         return value
     result = None
     try:
         result = self.__canonicalization_table[value]()
     except KeyError:
         pass
     if result is None:
         if isinstance(value, Variable):
             result = value
         elif isinstance(value, Not):
             child = self.canonicalise(value.expression)
             if isinstance(child, Not):
                 result = child.expression
             elif child is TRUE:
                 result = False
             elif child is FALSE:
                 result = True
             elif child is value.expression:
                 result = value
             else:
                 result = Not(child)
         else:
             assert isinstance(value, And)
             left = self.canonicalize(value.left)
             right = self.canonicalize(value.right)
             if left is value.left and right is value.right:
                 result = value
             elif left is FALSE or right is FALSE:
                 result = FALSE
             elif left is TRUE:
                 result = right
             elif right is TRUE:
                 result = left
             else:
                 result = And(left, right)
     else:
         if result.root is None and not result.canonical:
             # Now the hard part happens
             node = self.__decision_tree
             while len(node) == 3:
                 assignment, iffalse, iftrue = node
                 if value.evaluate(assignment):
                     node = iftrue
                 else:
                     node = iffalse
             assert len(node) == 1
             candidate = node[0]
             if candidate.canon_counter < self.__canon_counter:
                 candidate.canon_counter = self.__canon_counter
                 candidate = candidate.patch()
                 node[0] = candidate
             assert value != candidate
             experiment = distinguish(candidate, value)
             if experiment is not None:
                 value.canonical = True
                 table = {}
                 valresult = value.evaluate(experiment, table)
                 canresult = candidate.evaluate(experiment, table)
                 assert valresult != canresult
                 node[0] = experiment
                 if valresult:
                     node.append([candidate])
                     node.append([value])
                 else:
                     node.append([value])
                     node.append([candidate])
             else:
                 # Are equivalent
                 if value < candidate:
                     candidate.root = value
                     self.__canon_counter += 1
                     candidate.canonical = False
                     value.canonical = True
                     value.canon_counter = self.__canon_counter
                     node[0] = value
                     self.__canonicalization_table[
                         value] = weakref(value)
                     result = value
                 else:
                     value.root = candidate
                     result = candidate
     result = result.reroot()
     assert result.root is None
     self.__canonicalization_table[value] = weakref(result)
     return result
Example #57
0
 def __init__(self, pad):
     self._pad = weakref(pad)
Example #58
0
 def __init__(self, statistic_type, character):
     self.statistic_type = statistic_type
     self.character = weakref(character)
Example #59
0
	def __init__(self, *paths, dir_fd = None, env = None, preseed = None):
		# thread-local storage
		tls = local()
		self.tls = tls

		if preseed is None:
			globals = subdict()
		else:
			globals = subdict(preseed)
		self.globals = globals

		extra_builtins = dict(builtins)
		extra_builtins['delayed'] = delayed
		globals['__builtins__'] = extra_builtins
		weak_globals = weakref(globals)

		def include(path):
			with open(str(path) + '.py', opener = opener(dir_fd = dir_fd)) as f:
				content = f.read()
			exec(content, weak_globals())
		extra_builtins['include'] = include

		cfg_env = {}
		if env is not None:
			for k, v in env.items():
				k = fsencode(k)
				if k in cfg_env:
					continue
				try:
					v = fsencode(v)
				except:
					pass
				else:
					cfg_env[k] = v

		def run(*args, env = None, **kwargs):
			tls_env = getattr(tls, 'env', {})
			if cfg_env or tls_env:
				new_env = {}
				if env is None:
					env = environ
				for k, v in env.items():
					new_env[fsencode(k)] = fsencode(v)

				new_env.update(cfg_env)

				for k, v in tls_env.items():
					k = fsencode(k)
					if k in new_env:
						continue
					try:
						v = fsencode(v)
					except:
						pass
					else:
						new_env[k] = v

				kwargs = dict(kwargs, env = new_env)
			return subprocess_run(*args, **kwargs)
		extra_builtins['run'] = run

		def backticks(command, **kwargs):
			if kwargs.get('shell') is None:
				try:
					command = (b'sh', b'-ec', ensure_bytes(command))
				except TypeError:
					pass
				else:
					kwargs['shell'] = False
			completed = run(command, stdout = PIPE, **kwargs)
			completed.check_returncode()
			return completed.stdout
		extra_builtins['backticks'] = backticks

		for p in paths:
			include(p)
Example #60
0
 def __init__(self, metaview):
     self._metaview = weakref(metaview)