Beispiel #1
0
def _same_function(func1, func2):
    '''
    Helper function, used during namespace resolution for comparing whether to
    functions are the same. This takes care of treating a function and a
    `Function` variables whose `Function.pyfunc` attribute matches as the
    same. This prevents the user from getting spurious warnings when having
    for example a numpy function such as :np:func:`~random.randn` in the local
    namespace, while the ``randn`` symbol in the numpy namespace used for the
    code objects refers to a `RandnFunction` specifier.
    '''
    # use the function itself if it doesn't have a pyfunc attribute and try
    # to create a weak proxy to make a comparison to other weak proxys return
    # true
    func1 = getattr(func1, 'pyfunc', func1)
    try:
        func1 = weakref.proxy(func1)
    except TypeError:
        pass  # already a weakref proxy
    func2 = getattr(func2, 'pyfunc', func2)
    try:
        func2 = weakref.proxy(func2)
    except TypeError:
        pass

    return func1 is func2
 def __init__(self, frame):
     super(LogitechMonitorBattleMonoScreen, self).__init__(frame)
     self.__timerPresenter = _TimerPresenter(weakref.proxy(self))
     self.__fragsPresenter = _FragsPresenter(weakref.proxy(self))
     self.__timerDisplayData = None
     self.__fragsDisplayData = None
     return
Beispiel #3
0
    def __init__(self, wrapped, callback=None):
        # We need to determine if the wrapped function is actually a
        # bound method. In the case of a bound method, we need to keep a
        # reference to the original unbound function and the instance.
        # This is necessary because if we hold a reference to the bound
        # function, it will be the only reference and given it is a
        # temporary object, it will almost immediately expire and
        # the weakref callback triggered. So what is done is that we
        # hold a reference to the instance and unbound function and
        # when called bind the function to the instance once again and
        # then call it. Note that we avoid using a nested function for
        # the callback here so as not to cause any odd reference cycles.

        _callback = callback and functools.partial(
                _weak_function_proxy_callback, proxy=self,
                callback=callback)

        self._self_expired = False

        try:
            self._self_instance = weakref.ref(wrapped.__self__, _callback)

            super(WeakFunctionProxy, self).__init__(
                    weakref.proxy(wrapped.__func__, _callback))

        except AttributeError:
            self._self_instance = None

            super(WeakFunctionProxy, self).__init__(
                    weakref.proxy(wrapped, _callback))
 def start(self):
     import BattleReplay
     replayCtrl = BattleReplay.g_replayCtrl
     if isEventBattle():
         replayCtrl.enableAutoRecordingBattles(0)
     isReplayRecording = replayCtrl.isRecording
     isReplayPlaying = replayCtrl.isPlaying
     self.__arenaDP = ArenaDataProvider()
     self.__ctx.start(self.__arenaDP)
     self.__ammoCtrl = consumables.createAmmoCtrl(isReplayPlaying, isReplayRecording)
     self.__equipmentsCtrl = consumables.createEquipmentCtrl(isReplayPlaying)
     self.__optDevicesCtrl = consumables.createOptDevicesCtrl()
     self.__vehicleStateCtrl = vehicle_state_ctrl.createCtrl(isReplayRecording)
     self.__chatCommands = ChatCommandsController()
     self.__arenaLoadCtrl = ArenaLoadController()
     self.__drrScaleCtrl = DRRScaleController()
     self.__respawnsCtrl = RespawnsController()
     self.__notificationsCtrl = NotificationsController()
     self.__repairCtrl = RepairController()
     self.__arenaListeners = ListenersCollection()
     self.__arenaListeners.addController(weakref.proxy(self.__ctx), self.__arenaLoadCtrl)
     self.__arenaListeners.addController(weakref.proxy(self.__ctx), self.__respawnsCtrl)
     self.__arenaListeners.start(arenaDP=self.__arenaDP)
     self.__feedback = createFeedbackAdaptor(isReplayPlaying)
     self.__feedback.start(self.__arenaDP)
     self.__requestsCtrl = AvatarRequestsController()
Beispiel #5
0
 def __init__(self, plugin, callback, userdata, is_unload):
     self.is_unload = is_unload
     self.plugin = weakref.proxy(plugin)
     self.callback = callback
     self.userdata = userdata
     self.hexchat_hook = None
     self.handle = ffi.new_handle(weakref.proxy(self))
Beispiel #6
0
    def memhostalloc(self, bytesize, mapped=False, portable=False, wc=False):
        self.trashing.service()

        pointer = c_void_p()
        flags = 0
        if mapped:
            flags |= enums.CU_MEMHOSTALLOC_DEVICEMAP
        if portable:
            flags |= enums.CU_MEMHOSTALLOC_PORTABLE
        if wc:
            flags |= enums.CU_MEMHOSTALLOC_WRITECOMBINED

        driver.cuMemHostAlloc(byref(pointer), bytesize, flags)
        owner = None

        if mapped:
            _hostalloc_finalizer = _make_mem_finalizer(driver.cuMemFreeHost)
            finalizer = _hostalloc_finalizer(self, pointer)
            mem = MappedMemory(weakref.proxy(self), owner, pointer,
                               bytesize, finalizer=finalizer)

            self.allocations[mem.handle.value] = mem
            return mem.own()
        else:
            finalizer = _pinnedalloc_finalizer(self.trashing, pointer)
            mem = PinnedMemory(weakref.proxy(self), owner, pointer, bytesize,
                               finalizer=finalizer)
            return mem
Beispiel #7
0
    def mempin(self, owner, pointer, size, mapped=False):
        self.trashing.service()

        if isinstance(pointer, (int, long)):
            pointer = c_void_p(pointer)

        if mapped and not self.device.CAN_MAP_HOST_MEMORY:
            raise CudaDriverError("%s cannot map host memory" % self.device)

        # possible flags are "portable" (between context)
        # and "device-map" (map host memory to device thus no need
        # for memory transfer).
        flags = 0

        if mapped:
            flags |= enums.CU_MEMHOSTREGISTER_DEVICEMAP

        driver.cuMemHostRegister(pointer, size, flags)

        if mapped:
            _mapped_finalizer = _make_mem_finalizer(driver.cuMemHostUnregister)
            finalizer = _mapped_finalizer(self, pointer)
            mem = MappedMemory(weakref.proxy(self), owner, pointer, size,
                               finalizer=finalizer)
            self.allocations[mem.handle.value] = mem
            return mem.own()
        else:
            mem = PinnedMemory(weakref.proxy(self), owner, pointer, size,
                               finalizer=_pinned_finalizer(self.trashing,
                                                           pointer))
            return mem
Beispiel #8
0
 def __init__(self, inkmode, tdw):
     super(Overlay, self).__init__()
     self._inkmode = weakref.proxy(inkmode)
     self._tdw = weakref.proxy(tdw)
     self._button_pixbuf_cache = {}
     self.accept_button_pos = None
     self.reject_button_pos = None
Beispiel #9
0
    def __init__(self, machine, communicator=None, **kwargs):
        from candelabra.topology.machine import MachineNode

        assert isinstance(machine, MachineNode)
        assert isinstance(communicator, Communicator)
        self.machine = proxy(machine)
        self.communicator = proxy(communicator) if communicator else proxy(machine.communicator)
Beispiel #10
0
    def __set__(self, instance, value):
        """Descriptor for assigning a value to a field in a document.
        """

        # If setting to None and there is a default
        # Then set the value to the default value
        if value is None:
            if self.null:
                value = None
            elif self.default is not None:
                value = self.default
                if callable(value):
                    value = value()

        if instance._initialised:
            try:
                if (self.name not in instance._data or
                        instance._data[self.name] != value):
                    instance._mark_as_changed(self.name)
            except:
                # Values cant be compared eg: naive and tz datetimes
                # So mark it as changed
                instance._mark_as_changed(self.name)

        EmbeddedDocument = _import_class('EmbeddedDocument')
        if isinstance(value, EmbeddedDocument):
            value._instance = weakref.proxy(instance)
        elif isinstance(value, (list, tuple)):
            for v in value:
                if isinstance(v, EmbeddedDocument):
                    v._instance = weakref.proxy(instance)
        instance._data[self.name] = value
Beispiel #11
0
    def __init__(self, sess, gpcs, objectID, pa, refID):
        try:
            self.__dict__['session'] = weakref.proxy(sess)
        except TypeError:
            self.__dict__['session'] = sess
            sys.exc_clear()

        self.__dict__['objectID'] = objectID
        self.__dict__['sessionCheck'] = None
        self.__dict__['persistantObjectID'] = objectID
        self.__dict__['gpcs'] = weakref.proxy(gpcs)
        self.__dict__['__publicattributes__'] = pa
        self.__dict__['objectChangeHandlers'] = weakref.WeakKeyDictionary({})
        mask = sess.Masquerade()
        try:
            self.__dict__['clisid'] = gpcs.machoNet.GetClientSessionID()
        finally:
            mask.UnMask()

        if objectID[0] == 'C':
            self.__dict__['blocking'] = 0
            cid, oid = objectID.split(':')
            cid = cid.split('=')[1]
            self.__dict__['destination'] = macho.MachoAddress(clientID=long(cid))
        else:
            self.__dict__['blocking'] = 1
            nid, oid = objectID.split(':')
            nid = nid.split('=')[1]
            self.__dict__['destination'] = macho.MachoAddress(nodeID=long(nid))
        self.__dict__['deleted'] = 0
        sess.RegisterMachoObjectConnection(objectID, self, refID)
Beispiel #12
0
 def test_proxy_reuse(self):
     o = C()
     proxy1 = weakref.proxy(o)
     ref = weakref.ref(o)
     proxy2 = weakref.proxy(o)
     self.assert_(proxy1 is proxy2,
                  "proxy object w/out callback should have been re-used")
Beispiel #13
0
    def test_basic_proxy(self):
        o = C()
        self.check_proxy(o, weakref.proxy(o))

        L = UserList.UserList()
        p = weakref.proxy(L)
        self.failIf(p, "proxy for empty UserList should be false")
        p.append(12)
        self.assertEqual(len(L), 1)
        self.failUnless(p, "proxy for non-empty UserList should be true")
        p[:] = [2, 3]
        self.assertEqual(len(L), 2)
        self.assertEqual(len(p), 2)
        self.failUnless(3 in p,
                        "proxy didn't support __contains__() properly")
        p[1] = 5
        self.assertEqual(L[1], 5)
        self.assertEqual(p[1], 5)
        L2 = UserList.UserList(L)
        p2 = weakref.proxy(L2)
        self.assertEqual(p, p2)
        ## self.assertEqual(repr(L2), repr(p2))
        L3 = UserList.UserList(range(10))
        p3 = weakref.proxy(L3)
        self.assertEqual(L3[:], p3[:])
        self.assertEqual(L3[5:], p3[5:])
        self.assertEqual(L3[:5], p3[:5])
        self.assertEqual(L3[2:5], p3[2:5])
Beispiel #14
0
 def __init__(self, manager, module, message):
     self.manager = weakref.proxy(manager)
     self.module = None
     if module is not None:
         self.module = weakref.proxy(module)
     self.kmail = message
     self._info = message.toPyKol()
Beispiel #15
0
    def process_ConnectionBind(self, head, payload):
        log.info("%r process bind" % self)
        try:
            payload = json.loads(payload.decode())
            connection_id = payload.get('connection_id')
            self.connection_id = connection_id

            relay_session = self.server.allocation.relay_sessions.get(connection_id)
            data_session = self.server.allocation.data_sessions.get(connection_id)
            if connection_id and relay_session and data_session is None:
                relay_session.set_data_session(weakref.proxy(self))
                self.set_relay_session(weakref.proxy(relay_session))
                self.server.allocation.data_sessions[connection_id] = self
                rsp = {
                    'code': 200
                }
                log.info("bind ok")
            else:
                rsp = {
                    'code': 400
                }

            self.send_response(head, json.dumps(rsp).encode())
        except Exception as e:
            log.error(e)
Beispiel #16
0
    def __init__(self,world):
        """Args:
            world (WorldModel): the world that should be simulated.
        """
        Simulator.__init__(self,world)
        #these are functions automatically called at each time step
        self.robotControllers = [None]*world.numRobots()
        self.sensorEmulators = [[DefaultSensorEmulator(weakref.proxy(self),self.controller(i))] for i in range(world.numRobots())]
        self.actuatorEmulators = [[DefaultActuatorEmulator(weakref.proxy(self),self.controller(i))] for i in range(world.numRobots())]
        self.hooks = []
        self.hook_args = []
        #the rate of applying simulation substeps.  Hooks and actuator emulators are
        #called at this rate.  Note: this should be set at least as large as the simulation time step
        self.substep_dt = 0.001
        self.worst_status = Simulator.STATUS_NORMAL

        #turn this on to save log to disk
        self.logging = False
        self.logger = None
        self.log_state_fn="simulation_state.csv"
        self.log_contact_fn="simulation_contact.csv"

        #save state so controllers don't rely on world state
        self.robotStates = []
        self.objectStates = []
    def solve(self):
        dm = self.snes.getDM()

        nlevel = len(self.ctx._problems)
        dm.setAppCtx(weakref.proxy(self.ctx))
        dm.setCreateMatrix(self.ctx.create_matrix)
        # FIXME: Need to set this up on the subDMs
        for i in range(nlevel - 1, 0, -1):
            dm = dm.coarsen()
            dm.setAppCtx(weakref.proxy(self.ctx))

        for i in range(nlevel - 1):
            dm.setCreateInterpolation(create_interpolation)
            dm.setCreateInjection(create_injection)
            dm.setCreateMatrix(self.ctx.create_matrix)
            dm = dm.refine()

        self.snes.setFromOptions()

        for bc in self.problems[-1].bcs:
            bc.apply(self.problems[-1].u)

        with self.problems[-1].u.dat.vec as v:
            self.snes.solve(None, v)

        firedrake.solving_utils.check_snes_convergence(self.snes)
Beispiel #18
0
    def __init__(self,
                 application,
                 parent,
                 relx=0,
                 rely=0,
                 width=None,
                 height=None,
                 max_width=None,
                 max_height=None,
                 editable=True,
                 hidden=False,
                 keep_starting_dimensions=True,
                 **kwargs):

        try:
            self.workspace = weakref.proxy(workspace)
        except TypeError:
            self.workspace = workspace

        try:
            self.parent = weakref.proxy(parent)
        except TypeError:
            self.parent = parent

        self.keep_starting_dimensions = keep_starting_dimensions

        self.max_width, self.max_height = max_width, max_height

        self.requested_width, self.requested_height = width, height
        self.width, self.height = width, height

        self.relx, self.rely = relx, rely

        self.editable = editable
        self.hidden = hidden
Beispiel #19
0
 def initialize_endpoints(self):
     from predicthq import endpoints
     self.oauth2 = endpoints.OAuth2Endpoint(proxy(self))
     self.events = endpoints.EventsEndpoint(proxy(self))
     self.accounts = endpoints.AccountsEndpoint(proxy(self))
     self.signals = endpoints.SignalsEndpoint(proxy(self))
     self.places = endpoints.PlacesEndpoint(proxy(self))
Beispiel #20
0
    def __init__(self, registry, parent, command, target=None, is_background=False):
        super(ShBaseThread, self).__init__(group=None,
                                           target=target,
                                           name='_shthread',
                                           args=(),
                                           kwargs=None)

        # Registry management
        self.registry = weakref.proxy(registry)
        self.job_id = None  # to be set by the registry
        registry.add_worker(self)

        # The command that the thread runs
        if command.__class__.__name__ == 'ShIO':
            self.command = ''.join(command._buffer)[::-1].strip()
        else:
            self.command = command

        self.parent = weakref.proxy(parent)

        # Set up the state based on parent's state
        self.state = ShState.new_from_parent(parent.state)

        self.killed = False
        self.child_thread = None

        self.set_background(is_background)
Beispiel #21
0
    def get_master(self, flags=[], timeout=None):
        """
        Start (if necessary) an SSH master connection to speed up subsequent
        SSH sessions. Returns the SSHMaster instance on success.
        """
        flags = flags + self._get_flags()
        if self._ssh_master is not None:
            return weakref.proxy(self._ssh_master)

        tries = 5
        if timeout is not None:
            flags = flags + ["-o", "ConnectTimeout={0}".format(timeout)]
            tries = 1

        if self._host_fun() == "localhost":
            tries = 1

        sleep_time = 1
        while True:
            try:
                started_at = time.time()
                self._ssh_master = SSHMaster(self._get_target(), self._logger,
                                             flags, self._get_passwd())
                break
            except Exception:
                tries = tries - 1
                if tries == 0:
                    raise
                self._logger.log("could not connect to ‘{0}’, retrying in {1} seconds...".format(self._get_target(), sleep_time))
                time.sleep(sleep_time)
                sleep_time = sleep_time * 2
                pass

        return weakref.proxy(self._ssh_master)
Beispiel #22
0
    def __init__(self, name=None, parent=None, clear_lookup=True,
                 project=None):
        self._name = name
        if name is None:
            self._name = u"Default Segment Category"

        self._id = self.nextid
        if clear_lookup:
            self.id2obj.clear()
        self.id2obj[self._id] = self
        # weakref.proxy to this segment's parent segment.
        # If segment is child of project node in gui tree, then parent
        # should be None.
        # Get using parent property.
        self._parent = None
        if parent:
            if isinstance(parent, ProxyType):
                self._parent = parent
            else:
                self._parent = proxy(parent)
        # List of 0 - N child (sub) segments associated with this segment.
        # If segment has no children, then _childsegments should be [].
        # Get childsegments property.
        self._childsegments = []
        self._childsegment_ids = []

        # If a segment is locked, it can not be deleted or modified.
        self._locked = False

        if project:
            if isinstance(project, ProxyType):
                PenDataSegmentCategory._project = project
            else:
                PenDataSegmentCategory._project = proxy(project)
    def onSessionStart(self, hdrs):

        self.__init__()
        self.loadVoiceLib()

        self.mailbox = IMAP4_Mailbox(getSessionParam(hdrs, "Mailbox-URL"))
        debug("***** Mailbox Url: ******\n" + str(self.mailbox.url))

        self.new_msgs = self.loadMsgList("UNSEEN")
        self.saved_msgs = self.loadMsgList("SEEN")

        if (len(self.new_msgs) == 0) and (len(self.saved_msgs) == 0):

            self.enqueue(self.voice_lib["no_msg"], None)
            self.enqueue(self.voice_lib["bye"], None)
            self.exit = True
            return

        self.enqueue(self.voice_lib["you_have"], None)

        if len(self.new_msgs) > 0:

            self.enqueue(self.voice_lib["new_msg"], None)
            self.msg_list = weakref.proxy(self.new_msgs)
            self.cur_list = weakref.ref(self.new_msgs)

            if len(self.saved_msgs) > 0:
                self.enqueue(self.voice_lib["and"], None)
                self.enqueue(self.voice_lib["saved_msg"], None)
        else:
            self.enqueue(self.voice_lib["saved_msg"], None)
            self.msg_list = weakref.proxy(self.saved_msgs)
            self.cur_list = weakref.ref(self.saved_msgs)

        self.enqueueCurMsg()
    def join(self, drone):
        'Add this drone to our ring'
        # Make sure he's not already in our ring according to our 'database'
        if self.members.has_key(drone.designation):
            print self.members
            raise ValueError("Drone %s is already a member of this ring [%s]"
            %               (drone.designation, self.name))

        # Insert this drone into our 'database', and us into the drone's
        self.members[drone.designation] = weakref.proxy(drone)
        drone.ringmemberships[self.name] = weakref.proxy(self)
        partners = self._findringpartners(drone)	# Also adds drone to memberlist

        #print >>sys.stderr,'Adding drone %s to talk to partners'%drone.designation, partners
        if partners == None: return
        if len(self.memberlist) == 2:
            drone.start_heartbeat(self, partners[0])
            partners[0].start_heartbeat(self, drone)
            return
        elif len(self.memberlist) > 3:
            partners[0].stop_heartbeat(self, partners[1])
            partners[1].stop_heartbeat(self, partners[0])
        drone.start_heartbeat(self, partners[0], partners[1])
        partners[0].start_heartbeat(self, drone)
        partners[1].start_heartbeat(self, drone)
Beispiel #25
0
def setSetting(solver, value):
    app = solver.get_app()
    try:
       root = solver.get_root_parent()
       exec root._name + ' = root'
       if len(value[1].split()) != 0:
         a = eval(value[1])
         if isinstance(a, PyModel):
            solver._model = weakref.proxy(a)
         else:
            dialog.message(app, 'Model should be PyModel', 'Error')
            solver._model = None
       if len(value[2].split()) != 0:
         b = eval(value[2])
         if isinstance(b, PySol):
            solver._sol = weakref.proxy(b)
         else:
            dialog.message(app, 'Sol should be PySol', 'Error')
            solver._sol = None
       if len(value[3].split()) != 0:
         b = eval(value[3])
         if isinstance(b, PyParam):
            solver._param = weakref.proxy(b)
         else:
            dialog.message(app, 'Parameter should be PyParam', 'Error')
            solver._param = None
    except Exception:
       logging.exception("Solver Setting Failed")
Beispiel #26
0
    def testIsSame(self):
        s1 = _Stub()
        s2 = _Stub()

        r1 = weakref.ref(s1)
        r2 = weakref.ref(s2)

        p1 = weakref.proxy(s1)
        p2 = weakref.proxy(s2)

        assert IsSame(s1, s1)
        assert not IsSame(s1, s2)

        assert IsSame(s1, r1)
        assert IsSame(s1, p1)

        assert not IsSame(s1, r2)
        assert not IsSame(s1, p2)

        assert IsSame(p2, r2)
        assert IsSame(r1, p1)
        assert not IsSame(r1, p2)

        with pytest.raises(ReferenceError):
            IsSame(p1, p2)
Beispiel #27
0
    def post_init(self):
        """ Finalizes client initialization by querying API root info
        """

        log.debug("Getting root resources")

        response = self.nc.request(self.api_root)

        # obtain api info info
        self.root = Root.from_response(response, self.root_url)

        # instantiating handlers
        self._projects = ProjectHandle(
            weakref.proxy(self), self.nc, root_url=self.root_url,
            projects_href=self.root.get_href_by_name(u"projects"),)
        self._project_chroots = ProjectChrootHandle(
            weakref.proxy(self), self.nc, root_url=self.root_url)

        self._builds = BuildHandle(
            weakref.proxy(self), self.nc, root_url=self.root_url,
            builds_href=self.root.get_href_by_name(u"builds"),)

        self._build_tasks = BuildTaskHandle(
            weakref.proxy(self), self.nc, root_url=self.root_url,
            build_tasks_href=self.root.get_href_by_name("build_tasks")
        )

        self._mock_chroots = MockChrootHandle(
            weakref.proxy(self), self.nc, root_url=self.root_url,
            href=self.root.get_href_by_name(u"mock_chroots")
        )

        self._post_init_done = True
Beispiel #28
0
    def __init__(self, form, parent):
        try:
            self.form = weakref.proxy(form)
        except TypeError:
            self.form = form

        try:
            self.parent = weakref.proxy(parent)
        except TypeError:
            self.parent = parent

        self._commands = {'abort': basic.abort,
                          'action': basic.action,
                          'brakes': basic.brakes,
                          'connect': basic.connect,
                          'disconnect': basic.disconnect,
                          'fbw': basic.fbw,
                          'gear': basic.gear,
                          'haiku': basic.haiku,
                          'help': self.helps,
                          'lights': basic.lights,
                          'log': logs.logs,
                          'rate': basic.rate,
                          'rcs': basic.rcs,
                          'sas': basic.sas,
                          'sa': mechjeb.smartass,
                          'send': basic.send,
                          'stage': basic.stage,
                          'text': basic.text,
                          'telemetry': basic.telemetry,
                          'throttle': basic.throttle,
                          'quit': basic.quits,
                          'exit': basic.quits,  # overlaps with quit
                          }
Beispiel #29
0
    def __init__(self, handler):
        self.handler = weakref.proxy(handler)
        self.log = weakref.proxy(self.handler.log)

        if tornado.options.options.executor_type == 'threaded':
            self.executor = frontik.jobs.get_threadpool_executor()
        elif tornado.options.options.executor_type == 'ioloop':
            self.executor = frontik.jobs.IOLoopExecutor
        else:
            raise ValueError('Cannot initialize XslProducer with executor_type {0!r}'.format(
                tornado.options.options.executor_type))

        self.xml_cache = self.handler.ph_globals.xml.xml_cache
        self.xsl_cache = self.handler.ph_globals.xml.xsl_cache

        self.doc = frontik.doc.Doc(root_node=etree.Element('doc', frontik='true'))
        self.transform = None
        self.transform_filename = None

        if not self.handler.config.apply_xsl:
            self.log.debug('ignoring set_xsl() because config.apply_xsl=%s', self.handler.config.apply_xsl)
            self.apply_xsl = False
        elif frontik.util.get_cookie_or_url_param_value(self.handler, 'noxsl') is not None:
            self.handler.require_debug_access()
            self.log.debug('ignoring set_xsl() because noxsl parameter is set')
            self.apply_xsl = False
        else:
            self.apply_xsl = True
Beispiel #30
0
 def __init__(self, plugins):
     super(MigrationPlugin, self).__init__()
     self.__bwProto = weakref.proxy(plugins[PROTO_TYPE.BW])
     self.__bw2Proto = weakref.proxy(plugins[PROTO_TYPE.BW_CHAT2])
     self.__xmppProto = weakref.proxy(plugins[PROTO_TYPE.XMPP])
     self.__contacts = None
     return
Beispiel #31
0
 def __init__(self, trainer: 'pl.Trainer') -> None:
     self.trainer = proxy(trainer)
     self._internals = {}
     self.reset()
Beispiel #32
0
 def __init__(self, section, preBattleCond):
     self.__preBattleCond = weakref.proxy(preBattleCond)
     super(PostBattleConditions, self).__init__(section,
                                                rootName='postBattle')
Beispiel #33
0
    def test_objecttypes(self):
        # check all types defined in Objects/
        size = test.support.calcobjsize
        vsize = test.support.calcvobjsize
        check = self.check_sizeof
        # bool
        check(True, vsize('') + self.longdigit)
        # buffer
        # XXX
        # builtin_function_or_method
        check(len, size('3P'))  # XXX check layout
        # bytearray
        samples = [b'', b'u' * 100000]
        for sample in samples:
            x = bytearray(sample)
            check(x, vsize('n2Pi') + x.__alloc__())
        # bytearray_iterator
        check(iter(bytearray()), size('nP'))
        # bytes
        check(b'', vsize('n') + 1)
        check(b'x' * 10, vsize('n') + 11)

        # cell
        def get_cell():
            x = 42

            def inner():
                return x

            return inner

        check(get_cell().__closure__[0], size('P'))
        # code
        check(get_cell().__code__, size('5i9Pi3P'))
        check(get_cell.__code__, size('5i9Pi3P'))

        def get_cell2(x):
            def inner():
                return x

            return inner

        check(get_cell2.__code__, size('5i9Pi3P') + 1)
        # complex
        check(complex(0, 1), size('2d'))
        # method_descriptor (descriptor object)
        check(str.lower, size('3PP'))
        # classmethod_descriptor (descriptor object)
        # XXX
        # member_descriptor (descriptor object)
        import datetime
        check(datetime.timedelta.days, size('3PP'))
        # getset_descriptor (descriptor object)
        import collections
        check(collections.defaultdict.default_factory, size('3PP'))
        # wrapper_descriptor (descriptor object)
        check(int.__add__, size('3P2P'))
        # method-wrapper (descriptor object)
        check({}.__iter__, size('2P'))
        # dict
        check({}, size('n2P' + '2nPn' + 8 * 'n2P'))
        longdict = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}
        check(longdict, size('n2P' + '2nPn') + 16 * struct.calcsize('n2P'))
        # dictionary-keyiterator
        check({}.keys(), size('P'))
        # dictionary-valueiterator
        check({}.values(), size('P'))
        # dictionary-itemiterator
        check({}.items(), size('P'))
        # dictionary iterator
        check(iter({}), size('P2nPn'))

        # dictproxy
        class C(object):
            pass

        check(C.__dict__, size('P'))
        # BaseException
        check(BaseException(), size('5Pb'))
        # UnicodeEncodeError
        check(UnicodeEncodeError("", "", 0, 0, ""), size('5Pb 2P2nP'))
        # UnicodeDecodeError
        check(UnicodeDecodeError("", b"", 0, 0, ""), size('5Pb 2P2nP'))
        # UnicodeTranslateError
        check(UnicodeTranslateError("", 0, 1, ""), size('5Pb 2P2nP'))
        # ellipses
        check(Ellipsis, size(''))
        # EncodingMap
        import codecs, encodings.iso8859_3
        x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
        check(x, size('32B2iB'))
        # enumerate
        check(enumerate([]), size('n3P'))
        # reverse
        check(reversed(''), size('nP'))
        # float
        check(float(0), size('d'))
        # sys.floatinfo
        check(sys.float_info, vsize('') + self.P * len(sys.float_info))
        # frame
        import inspect
        CO_MAXBLOCKS = 20
        x = inspect.currentframe()
        ncells = len(x.f_code.co_cellvars)
        nfrees = len(x.f_code.co_freevars)
        extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\
                  ncells + nfrees - 1
        check(x, vsize('12P3ic' + CO_MAXBLOCKS * '3i' + 'P' + extras * 'P'))

        # function
        def func():
            pass

        check(func, size('12P'))

        class c():
            @staticmethod
            def foo():
                pass

            @classmethod
            def bar(cls):
                pass

            # staticmethod
            check(foo, size('PP'))
            # classmethod
            check(bar, size('PP'))

        # generator
        def get_gen():
            yield 1

        check(get_gen(), size('Pb2P'))
        # iterator
        check(iter('abc'), size('lP'))
        # callable-iterator
        import re
        check(re.finditer('', ''), size('2P'))
        # list
        samples = [[], [1, 2, 3], ['1', '2', '3']]
        for sample in samples:
            check(sample, vsize('Pn') + len(sample) * self.P)
        # sortwrapper (list)
        # XXX
        # cmpwrapper (list)
        # XXX
        # listiterator (list)
        check(iter([]), size('lP'))
        # listreverseiterator (list)
        check(reversed([]), size('nP'))
        # int
        check(0, vsize(''))
        check(1, vsize('') + self.longdigit)
        check(-1, vsize('') + self.longdigit)
        PyLong_BASE = 2**sys.int_info.bits_per_digit
        check(int(PyLong_BASE), vsize('') + 2 * self.longdigit)
        check(int(PyLong_BASE**2 - 1), vsize('') + 2 * self.longdigit)
        check(int(PyLong_BASE**2), vsize('') + 3 * self.longdigit)
        # module
        check(unittest, size('PnPPP'))
        # None
        check(None, size(''))
        # NotImplementedType
        check(NotImplemented, size(''))
        # object
        check(object(), size(''))

        # property (descriptor object)
        class C(object):
            def getx(self):
                return self.__x

            def setx(self, value):
                self.__x = value

            def delx(self):
                del self.__x

            x = property(getx, setx, delx, "")
            check(x, size('4Pi'))

        # PyCapsule
        # XXX
        # rangeiterator
        check(iter(range(1)), size('4l'))
        # reverse
        check(reversed(''), size('nP'))
        # range
        check(range(1), size('4P'))
        check(range(66000), size('4P'))
        # set
        # frozenset
        PySet_MINSIZE = 8
        samples = [[], range(10), range(50)]
        s = size('3n2P' + PySet_MINSIZE * 'nP' + 'nP')
        for sample in samples:
            minused = len(sample)
            if minused == 0: tmp = 1
            # the computation of minused is actually a bit more complicated
            # but this suffices for the sizeof test
            minused = minused * 2
            newsize = PySet_MINSIZE
            while newsize <= minused:
                newsize = newsize << 1
            if newsize <= 8:
                check(set(sample), s)
                check(frozenset(sample), s)
            else:
                check(set(sample), s + newsize * struct.calcsize('nP'))
                check(frozenset(sample), s + newsize * struct.calcsize('nP'))
        # setiterator
        check(iter(set()), size('P3n'))
        # slice
        check(slice(0), size('3P'))
        # super
        check(super(int), size('3P'))
        # tuple
        check((), vsize(''))
        check((1, 2, 3), vsize('') + 3 * self.P)
        # type
        # static type: PyTypeObject
        s = vsize('P2n15Pl4Pn9Pn11PIP')
        check(int, s)
        # (PyTypeObject + PyNumberMethods + PyMappingMethods +
        #  PySequenceMethods + PyBufferProcs + 4P)
        s = vsize('P2n15Pl4Pn9Pn11PIP') + struct.calcsize('34P 3P 10P 2P 4P')
        # Separate block for PyDictKeysObject with 4 entries
        s += struct.calcsize("2nPn") + 4 * struct.calcsize("n2P")

        # class
        class newstyleclass(object):
            pass

        check(newstyleclass, s)
        # dict with shared keys
        check(newstyleclass().__dict__, size('n2P' + '2nPn'))
        # unicode
        # each tuple contains a string and its expected character size
        # don't put any static strings here, as they may contain
        # wchar_t or UTF-8 representations
        samples = [
            '1' * 100, '\xff' * 50, '\u0100' * 40, '\uffff' * 100,
            '\U00010000' * 30, '\U0010ffff' * 100
        ]
        asciifields = "nnbP"
        compactfields = asciifields + "nPn"
        unicodefields = compactfields + "P"
        for s in samples:
            maxchar = ord(max(s))
            if maxchar < 128:
                L = size(asciifields) + len(s) + 1
            elif maxchar < 256:
                L = size(compactfields) + len(s) + 1
            elif maxchar < 65536:
                L = size(compactfields) + 2 * (len(s) + 1)
            else:
                L = size(compactfields) + 4 * (len(s) + 1)
            check(s, L)
        # verify that the UTF-8 size is accounted for
        s = chr(0x4000)  # 4 bytes canonical representation
        check(s, size(compactfields) + 4)
        # compile() will trigger the generation of the UTF-8
        # representation as a side effect
        compile(s, "<stdin>", "eval")
        check(s, size(compactfields) + 4 + 4)
        # TODO: add check that forces the presence of wchar_t representation
        # TODO: add check that forces layout of unicodefields
        # weakref
        import weakref
        check(weakref.ref(int), size('2Pn2P'))
        # weakproxy
        # XXX
        # weakcallableproxy
        check(weakref.proxy(int), size('2Pn2P'))
Beispiel #34
0
Datei: read.py Projekt: zoidy/puq
 def __init__(self, parent):
     self.tframe = Frame(parent)
     TimeFrame.me = weakref.proxy(self)
 def bindDataProvider(self, dataProvider):
     self.__dataProvider = weakref.proxy(dataProvider)
Beispiel #36
0
    def __init__(self,
                 screen,
                 relx=0,
                 rely=0,
                 name=None,
                 value=None,
                 width=False,
                 height=False,
                 max_height=False,
                 max_width=False,
                 editable=True,
                 hidden=False,
                 color='DEFAULT',
                 use_max_space=False,
                 check_value_change=True,
                 check_cursor_move=True,
                 value_changed_callback=None,
                 **keywords):
        """The following named arguments may be supplied:
        name= set the name of the widget.
        width= set the width of the widget.
        height= set the height.
        max_height= let the widget choose a height up to this maximum.
        max_width=  let the widget choose a width up to this maximum.
        editable=True/False the user may change the value of the widget.
        hidden=True/False The widget is hidden.
        check_value_change=True - perform a check on every keypress and run when_value_edit if the value is different.
        check_cursor_move=True - perform a check every keypress and run when_cursor_moved if the cursor has moved.
        value_changed_callback - should be None or a Function.  If it is a function, it will have be called when the value changes
                               and passed the keyword argument widget=self.
        """
        self.check_value_change = check_value_change
        self.check_cursor_move = check_cursor_move
        self.hidden = hidden
        self.interested_in_mouse_even_when_not_editable = False  # used only for rare widgets to allow user to click
        # even if can't actually select the widget.  See mutt-style forms

        try:
            self.parent = weakref.proxy(screen)
        except TypeError:
            self.parent = screen
        self.use_max_space = use_max_space
        self.set_relyx(rely, relx)
        #self.relx = relx
        #self.rely = rely
        self.color = color
        self.encoding = 'utf-8'  #locale.getpreferredencoding()
        if GlobalOptions.ASCII_ONLY or locale.getpreferredencoding(
        ) == 'US-ASCII':
            self._force_ascii = True
        else:
            self._force_ascii = False

        self.set_up_handlers()

        # To allow derived classes to set this and then call this method safely...
        try:
            self.value
        except AttributeError:
            self.value = value

        # same again
        try:
            self.name
        except Exception:
            self.name = name

        self.request_width = width  # widgets should honour if possible
        self.request_height = height  # widgets should honour if possible

        self.max_height = max_height
        self.max_width = max_width

        self.set_size()

        self.editing = False  # Change to true during an edit

        self.editable = editable
        if self.parent.curses_pad.getmaxyx()[0] - 1 == self.rely:
            self.on_last_line = True
        else:
            self.on_last_line = False

        if value_changed_callback:
            self.value_changed_callback = value_changed_callback
        else:
            self.value_changed_callback = None

        self.initialize_event_handling()
Beispiel #37
0
 def __init__(self, trigger):
     super(SimpleDialogResultAspect, self).__init__()
     self._trigger = weakref.proxy(trigger)
 def get_audio_player(self):
     if not self._audio_player:
         self._audio_player = XbmcPlayer('audio', weakref.proxy(self))
     return self._audio_player
 def get_audio_playlist(self):
     if not self._audio_playlist:
         self._audio_playlist = XbmcPlaylist('audio', weakref.proxy(self))
     return self._audio_playlist
 def get_ui(self):
     if not self._ui:
         self._ui = XbmcContextUI(self._addon, weakref.proxy(self))
     return self._ui
Beispiel #41
0
 def source(self, value):
     self._source = weakref.proxy(value)
 def get_video_player(self):
     if not self._video_player:
         self._video_player = XbmcPlayer('video', weakref.proxy(self))
     return self._video_player
Beispiel #43
0
 def __init__(self, driver):
     import weakref
     self._driver = weakref.proxy(driver)
 def get_video_playlist(self):
     if not self._video_playlist:
         self._video_playlist = XbmcPlaylist('video', weakref.proxy(self))
     return self._video_playlist
 def test_weakref(self):
     f = self.thetype(int, base=16)
     p = proxy(f)
     self.assertEqual(f.func, p.func)
     f = None
     self.assertRaises(ReferenceError, getattr, p, 'func')
Beispiel #46
0
 def test_weakref(self):
     s = array.array(self.typecode, self.example)
     p = weakref.proxy(s)
     self.assertEqual(p.tobytes(), s.tobytes())
     s = None
     self.assertRaises(ReferenceError, len, p)
Beispiel #47
0
    def setCallback(self, callback=None):
        """ setCallback(callback: class) -> None
            Sets a callback when receiving commands

        """
        self.callback = weakref.proxy(callback)
Beispiel #48
0
 def __init__(self, parent):
     super(Control, self).__init__()
     self.parent = weakref.proxy(parent)
Beispiel #49
0
 def weakref(self) -> anki.storage._Collection:
     "Shortcut to create a weak reference that doesn't break code completion."
     return weakref.proxy(self)
Beispiel #50
0
    def __init__(self, parent, proteins):
        super(TableTabs, self).__init__(parent)

        self.proteins = weakref.proxy(proteins)
        self.tables = []
        self.load()
Beispiel #51
0
 def __init__(self, native_dsound):
     # We only keep a weakref to native_dsound which is owned by
     # interface.DirectSoundDriver
     self._native_dsound = weakref.proxy(native_dsound)
Beispiel #52
0
 def __init__(self, obj):
     """
     Initialized on the object
     """
     self._store = {}
     self.obj = weakref.proxy(obj)
Beispiel #53
0
                                ['x', 'y', 'A'])
mahalanobis_distance.autoSetJacobians()
unit.setDeriv(0,
              lambda x, dx: if_(x == 0, zero(shape(x)), dx / norm(x) - x *
                                (dot(x, dx) / norm(x))**3),
              stackable=True)
inv = Function('inv', np.linalg.inv, ['A'], returnType='M')
inv.argTypes = [Matrix]


def _inv_deriv(A, dA):
    Ainv = inv(A)
    return -dot(Ainv, dot(dA, Ainv))


inv.properties['inverse'] = weakref.proxy(inv)
#patch the dot function
dot.addSimplifier(['inv', 'inv'],
                  lambda Ainv, Binv: inv(dot(Binv.args[0], Ainv.args[0])))
dot.addSimplifier(['linalg.inv', 'linalg.inv'],
                  lambda Ainv, Binv: inv(dot(Binv.args[0], Ainv.args[0])))
inv.addSimplifier(['neg'], lambda x: -inv(x.args[0]))
inv.setDeriv(0, _inv_deriv, asExpr=True)
inv.printers['str'] = lambda expr, astr: astr[0] + '^-1'
pinv = Function('pinv', np.linalg.pinv, ['A'], returnType='M')
pinv.argTypes = [Matrix]
pinv.addSimplifier(['neg'], lambda x: -pinv(x.args[0]))
pinv.printers['str'] = lambda expr, astr: astr[0] + '^+'


def _pinv_deriv(A, dA):
Beispiel #54
0
 def __init__(self, obj):
     self.proxy = weakref.proxy(obj)
Beispiel #55
0
 def __init__(self, program, name, index, size, uniforms):
     self.program = proxy(program)
     self.name = name
     self.index = index
     self.size = size
     self.uniforms = uniforms
Beispiel #56
0
 def __init__(self, ds_buffer, native_listener):
     # We only keep a weakref to ds_buffer as it is owned by
     # interface.DirectSound or a DirectSoundAudioPlayer
     self.ds_buffer = weakref.proxy(ds_buffer)
     self._native_listener = native_listener
Beispiel #57
0
 def __init__(self, obj, method):
     self.obj = weakref.proxy(obj)
     self.method = method
Beispiel #58
0
    def __init__(self, selfNodeAddr, otherNodesAddrs, conf=None):

        if conf is None:
            self.__conf = SyncObjConf()
        else:
            self.__conf = conf

        self.__conf.validate()

        if self.__conf.password is not None:
            if not HAS_CRYPTO:
                raise ImportError("Please install 'cryptography' module")
            self.__encryptor = getEncryptor(self.__conf.password)
        else:
            self.__encryptor = None

        self.__selfNodeAddr = selfNodeAddr
        self.__otherNodesAddrs = otherNodesAddrs
        self.__unknownConnections = {}  # descr => _Connection
        self.__raftState = _RAFT_STATE.FOLLOWER
        self.__raftCurrentTerm = 0
        self.__votedFor = None
        self.__votesCount = 0
        self.__raftLeader = None
        self.__raftElectionDeadline = time.time() + self.__generateRaftTimeout(
        )
        self.__raftLog = createJournal(self.__conf.journalFile)
        if len(self.__raftLog) == 0:
            self.__raftLog.add(_bchr(_COMMAND_TYPE.NO_OP), 1,
                               self.__raftCurrentTerm)
        self.__raftCommitIndex = 1
        self.__raftLastApplied = 1
        self.__raftNextIndex = {}
        self.__raftMatchIndex = {}
        self.__lastSerializedTime = time.time()
        self.__lastSerializedEntry = None
        self.__forceLogCompaction = False
        self.__leaderCommitIndex = None
        self.__onReadyCalled = False
        self.__changeClusterIDx = None
        self.__noopIDx = None
        self.__destroying = False

        self.__startTime = time.time()
        globalDnsResolver().setTimeouts(self.__conf.dnsCacheTime,
                                        self.__conf.dnsFailCacheTime)
        self.__serializer = Serializer(self.__conf.fullDumpFile,
                                       self.__conf.logCompactionBatchSize,
                                       self.__conf.useFork,
                                       self.__conf.serializer,
                                       self.__conf.deserializer,
                                       self.__conf.serializeChecker)
        self.__isInitialized = False
        self.__lastInitTryTime = 0
        self._poller = createPoller(self.__conf.pollerType)

        host, port = selfNodeAddr.split(':')
        self.__server = TcpServer(
            self._poller,
            host,
            port,
            onNewConnection=self.__onNewConnection,
            sendBufferSize=self.__conf.sendBufferSize,
            recvBufferSize=self.__conf.recvBufferSize,
            connectionTimeout=self.__conf.connectionTimeout)

        self._methodToID = {}
        self._idToMethod = {}
        methods = sorted([
            m for m in dir(self)
            if isinstance(getattr(self, m), collections.Callable)
        ])
        for i, method in enumerate(methods):
            self._methodToID[method] = i
            self._idToMethod[i] = getattr(self, method)

        self.__thread = None
        self.__mainThread = None
        self.__initialised = None
        self.__commandsQueue = queue.Queue(self.__conf.commandsQueueSize)
        self.__nodes = []
        self.__newAppendEntriesTime = 0

        self.__commandsWaitingCommit = collections.defaultdict(
            list)  # logID => [(termID, callback), ...]
        self.__commandsLocalCounter = 0
        self.__commandsWaitingReply = {}  # commandLocalCounter => callback

        self.__properies = set()
        for key in self.__dict__:
            self.__properies.add(key)

        if self.__conf.autoTick:
            self.__mainThread = threading.current_thread()
            self.__initialised = threading.Event()
            self.__thread = threading.Thread(target=SyncObj._autoTickThread,
                                             args=(weakref.proxy(self), ))
            self.__thread.start()
            while not self.__initialised.is_set():
                pass
        else:
            self.__initInTickThread()
Beispiel #59
0
    def low(self, fun, low):
        '''
        Execute a function from low data
        Low data includes:
            required:
                - fun: the name of the function to run
            optional:
                - args: a list of args to pass to fun
                - kwargs: kwargs for fun
                - __user__: user who is running the command
                - __jid__: jid to run under
                - __tag__: tag to run under
        '''
        # fire the mminion loading (if not already done) here
        # this is not to clutter the output with the module loading
        # if we have a high debug level.
        self.mminion  # pylint: disable=W0104
        jid = low.get('__jid__', salt.utils.jid.gen_jid())
        tag = low.get('__tag__', tagify(jid, prefix=self.tag_prefix))

        data = {
            'fun': '{0}.{1}'.format(self.client, fun),
            'jid': jid,
            'user': low.get('__user__', 'UNKNOWN'),
        }

        event = salt.utils.event.get_event('master',
                                           self.opts['sock_dir'],
                                           self.opts['transport'],
                                           opts=self.opts,
                                           listen=False)

        namespaced_event = salt.utils.event.NamespacedEvent(
            event,
            tag,
            print_func=self.print_async_event if hasattr(
                self, 'print_async_event') else None)
        # TODO: document these, and test that they exist
        # TODO: Other things to inject??
        func_globals = {
            '__jid__': jid,
            '__user__': data['user'],
            '__tag__': tag,
            # weak ref to avoid the Exception in interpreter
            # teardown of event
            '__jid_event__': weakref.proxy(namespaced_event),
        }

        func_globals['__jid_event__'].fire_event(data, 'new')

        try:
            verify_fun(self.functions, fun)

            # Inject some useful globals to *all* the function's global
            # namespace only once per module-- not per func
            completed_funcs = []

            for mod_name in six.iterkeys(self.functions):
                if '.' not in mod_name:
                    continue
                mod, _ = mod_name.split('.', 1)
                if mod in completed_funcs:
                    continue
                completed_funcs.append(mod)
                for global_key, value in six.iteritems(func_globals):
                    self.functions[mod_name].__globals__[global_key] = value

            # There are some descrepencies of what a "low" structure is in the
            # publisher world it is a dict including stuff such as jid, fun,
            # arg (a list of args, with kwargs packed in). Historically this
            # particular one has had no "arg" and just has had all the kwargs
            # packed into the top level object. The plan is to move away from
            # that since the caller knows what is an arg vs a kwarg, but while
            # we make the transition we will load "kwargs" using format_call if
            # there are no kwargs in the low object passed in
            f_call = None
            if 'args' not in low:
                f_call = salt.utils.format_call(
                    self.functions[fun],
                    low,
                    expected_extra_kws=CLIENT_INTERNAL_KEYWORDS)
                args = f_call.get('args', ())
            else:
                args = low['args']
            if 'kwargs' not in low:
                if f_call is None:
                    f_call = salt.utils.format_call(
                        self.functions[fun],
                        low,
                        expected_extra_kws=CLIENT_INTERNAL_KEYWORDS)
                kwargs = f_call.get('kwargs', {})

                # throw a warning for the badly formed low data if we found
                # kwargs using the old mechanism
                if kwargs:
                    salt.utils.warn_until(
                        'Boron',
                        'kwargs must be passed inside the low under "kwargs"')
            else:
                kwargs = low['kwargs']

            # Initialize a context for executing the method.
            with tornado.stack_context.StackContext(
                    self.functions.context_dict.clone):
                data['return'] = self.functions[fun](*args, **kwargs)
                data['success'] = True
        except (Exception, SystemExit) as ex:
            if isinstance(ex, salt.exceptions.NotImplemented):
                data['return'] = str(ex)
            else:
                data['return'] = 'Exception occurred in {0} {1}: {2}'.format(
                    self.client,
                    fun,
                    traceback.format_exc(),
                )
            data['success'] = False

        namespaced_event.fire_event(data, 'ret')
        try:
            salt.utils.job.store_job(
                self.opts,
                {
                    'id': self.opts['id'],
                    'tgt': self.opts['id'],
                    'jid': data['jid'],
                    'return': data,
                },
                event=None,
                mminion=self.mminion,
            )
        except salt.exceptions.SaltCacheError:
            log.error(
                'Could not store job cache info. Job details for this run may be unavailable.'
            )
        # if we fired an event, make sure to delete the event object.
        # This will ensure that we call destroy, which will do the 0MQ linger
        log.info('Runner completed: {0}'.format(data['jid']))
        del event
        del namespaced_event
        return data['return']
 def start(self, setup):
     self._visitor = weakref.proxy(setup.arenaVisitor)
     self._arenaDP = weakref.proxy(setup.arenaDP)