当前位置: 首页>>代码示例>>Python>>正文


Python WeakKeyDictionary.values方法代码示例

本文整理汇总了Python中weakref.WeakKeyDictionary.values方法的典型用法代码示例。如果您正苦于以下问题:Python WeakKeyDictionary.values方法的具体用法?Python WeakKeyDictionary.values怎么用?Python WeakKeyDictionary.values使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在weakref.WeakKeyDictionary的用法示例。


在下文中一共展示了WeakKeyDictionary.values方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Condition

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import values [as 别名]
class Condition(object):
    """ A gevent-aware version of threading.Condition.

    This allows greenlets to wait on notifications generated by bona fide
    threads.

    (Calling threading.Condition.wait from a greenlet will block all greenlets
    in the thread.)

    This is currently only a partial re-implementation which supports only
    ``notifyAll``.  It does not currently support ``notify``.

    """
    def __init__(self, lock=None):
        if lock is None:
            lock = RLock()              # a real threading.Lock
        self.lock = lock
        self.waiters_by_thread = WeakKeyDictionary()

        self.acquire = lock.acquire
        self.release = lock.release


    def __enter__(self):
        return self.lock.__enter__()

    def __exit__(self, exc_type, exc_value, tb):
        return self.lock.__exit__(exc_type, exc_value, tb)

    def wait(self, timeout=None):
        # FIXME: check that we own and have locked the lock?
        try:
            async, waiters = self.waiters_by_thread[current_thread()]
        except KeyError:
            # How we communicate from other threads to the gevent thread
            async = gevent.get_hub().loop.async()
            async.start(self._notify_all)
            waiters = []
            self.waiters_by_thread[current_thread()] = async, waiters

        waiter = gevent.lock.Semaphore(0)
        waiters.append(waiter)
        self.release()
        try:
            if not waiter.wait(timeout):
                waiters.remove(waiter)
        finally:
            self.acquire()

    def notifyAll(self):
        # FIXME: check that we own and have locked the lock?
        for async, waiters in self.waiters_by_thread.values():
            async.send()
开发者ID:dairiki,项目名称:puppyserv,代码行数:55,代码来源:greenlet.py

示例2: SendObject

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import values [as 别名]
class SendObject(object):
    send_key = id
    def __init__(self, cls=None):
        def _change(obj, name, val, selfref=ref(self)):
            self = selfref()
            if self is not None:
                self.send(obj)
        self.change = _change

        self.send_keys = WeakKeyDictionary()
        if cls:
            auto_sub(cls, self)

    @public.send_meth('set')
    def send_create(self, obj):
        data = [getattr(obj, name, '') for name in obj.send_attrs]
        send_once = getattr(obj, 'send_once', ())
        data.extend(getattr(obj, name, '') for name in send_once)
        return self.send_keys[obj], data

    @public.send_meth('set', functions=send_functions)
    def send(self, obj):
        data = [getattr(obj, name, '') for name in obj.send_attrs]
        return self.send_keys[obj], data

    @public.send_meth('removeElement')
    def send_delete(self, key):
        return key,

    def subscribe_property(self, obj):
        send_key = getattr(obj, 'send_key', self.send_key)
        if callable(send_key):
            send_key = send_key(obj)
        self._test_same_key(send_key, obj)
        self.send_keys[obj] = send_key

        for name in getattr(obj, 'send_attrs', ()):
            property_ = getattr(type(obj), name)
            property_.subscribe(obj, self.change)

    def _test_same_key(self, send_key, obj):
        assert send_key not in self.send_keys.values(), \
            'тот же ключ %s' % send_key

    def unsubscribe_property(self, obj):
        for name in getattr(obj, 'send_attrs', ()):
            property_ = getattr(type(obj), name)
            property_.unsubscribe(obj)
        del self.send_keys[obj]

    def subscribe(self, sub):
        for obj in self:
            self.send_create(obj, to=sub)
开发者ID:yrttyr,项目名称:Multiplayer-snake-game,代码行数:55,代码来源:objects.py

示例3: Control

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import values [as 别名]
class Control(view.View):

    STATE_NORMAL = 0
    STATE_HIGHLIGHTED = 1
    STATE_ACTIVATED = 2
    STATE_DISABLED = 3

    STATE_ALL = 0xFF

    removeAllTargetsWhenUnload = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__targets = WeakKeyDictionary()

    def addTarget(self, key, callback):
        if callable(callback):
            self.__targets[key] = callback
        else:
            raise TypeError("func is not callable")
        pass

    def removeTarget(self, key):
        try:
            del self.__targets[key]
        except KeyError:
            pass

    def removeAllTargets(self):
        self.__targets = WeakKeyDictionary()

    def invokeAllTargets(self, *args):
        for cb in self.__targets.values():
            cb(*args)

    def invokeOneTarget(self, key, *args):
        cb = self.__targets[key]
        cb(*args)

    def onUnload(self):
        if self.removeAllTargetsWhenUnload:
            self.removeAllTargets()
        return super().onUnload()
开发者ID:hhg128,项目名称:DKGL,代码行数:45,代码来源:control.py

示例4: FerryServerFactory

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import values [as 别名]
class FerryServerFactory(WebSocketServerFactory):
    def __init__(self, uri, debug=False, assets='./'):
        WebSocketServerFactory.__init__(self, uri, debug=debug)
        self._peers = WeakKeyDictionary()
        self.assets = assets

    def __getitem__(self, key):
        if key in self._peers:
            return self._peers[key]
        return None

    def __setitem__(self, key, value):
        self._peers[key] = value

    def __contains__(self, key):
        if self._peers.get(key) is not None:
            return True
        return False

    def __repr__(self):
        return 'Ferry(%s)' % ', '.join('User(%s)' % (
                                       urlparse(user.tab.url).netloc
                                       for user in self._peers.values()
                                       if user.tab))
开发者ID:JDFISH,项目名称:portia,代码行数:26,代码来源:ferry.py

示例5: BaseNode

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import values [as 别名]
class BaseNode(models.Model):

    dispatcher = None

    name = models.StringField()
    parent = models.ModelField(allow_null=True)
    user = models.StringField()
    priority = models.IntegerField()
    dispatchKey = models.FloatField()
    maxRN = models.IntegerField()
    updateTime = models.FloatField()
    poolShares = PoolShareDictField()
    additionnalPoolShares = AdditionnalPoolShareDictField()
    completion = models.FloatField()
    status = models.IntegerField()
    creationTime = models.FloatField()
    startTime = models.FloatField(allow_null=True)
    updateTime = models.FloatField(allow_null=True)
    endTime = models.FloatField(allow_null=True)
    dependencies = DependencyListField()
    averageTimeByFrame = models.FloatField(allow_null=True)
    minTimeByFrame = models.FloatField(allow_null=True)
    maxTimeByFrame = models.FloatField(allow_null=True)
    timer = models.FloatField(allow_null=True)

    @property
    def tags(self):
        return {}

    def __init__(self, id, name, parent, user, priority, dispatchKey, maxRN,
                 creationTime=None, startTime=None,
                 updateTime=None, endTime=None,
                 status=NODE_READY):
        '''
        Base class for each node in dispatcher tree structure. Holds main model
        fields.

        :param id int: unique id for this node
        :param name str:  a short string describing this node
        :param parent: a FolderNode or None if this node is a root node
        :param priority int: priority value
        :param dispatchKey int: dispatchKey value
        :param maxRN int: maximum number of render nodes that can be allocated to this tree node
        :param creationTime: timestamp indicating when the node was created
        :param startTime: timestamp indicating when the node was started
        :param updateTime: timestamp indicating when the node was updated
        :param endTime: timestamp indicating when the node was ended
        :param status int: current node's status
        '''
        if not self.dispatcher:
            from octopus.dispatcher.dispatcher import Dispatcher
            self.dispatcher = Dispatcher(None)
        self.__dict__['parent'] = None
        models.Model.__init__(self)
        self.id = int(id) if id is not None else None
        self.name = str(name)
        self.parent = parent
        self.user = str(user)
        self.priority = int(priority)
        self.dispatchKey = int(dispatchKey)
        self.maxRN = int(maxRN)
        self.optimalMaxRN = 0
        self.allocatedRN = 0
        self.poolShares = WeakKeyDictionary()
        self.additionnalPoolShares = WeakKeyDictionary()
        self.completion = 1.0
        self.status = status
        self.creationTime = time() if not creationTime else creationTime
        self.startTime = startTime
        self.updateTime = updateTime
        self.endTime = endTime

        self.dependencies = []
        self.reverseDependencies = []
        self.lastDependenciesSatisfaction = False
        self.lastDependenciesSatisfactionDispatchCycle = -1
        self.readyCommandCount = 0
        self.doneCommandCount = 0
        self.commandCount = 0
        self.averageTimeByFrameList = []
        self.averageTimeByFrame = 0.0
        self.minTimeByFrame = 0.0
        self.maxTimeByFrame = 0.0
        self.timer = None

    def mainPoolShare(self):
        return self.poolShares.values()[0]

    def mainPool(self):
        return self.poolShares.keys()[0]

    def to_json(self):
        base = super(BaseNode, self).to_json()
        base["allocatedRN"] = self.allocatedRN
        base["optimalMaxRN"] = self.optimalMaxRN
        base["tags"] = self.tags.copy()
        base["readyCommandCount"] = self.readyCommandCount
        base["doneCommandCount"] = self.doneCommandCount
        base["commandCount"] = self.commandCount
        return base
#.........这里部分代码省略.........
开发者ID:madmouser1,项目名称:OpenRenderManagement,代码行数:103,代码来源:node.py

示例6: GameServer

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import values [as 别名]
class GameServer(Server):
    channelClass = PlayerServer

    def __init__(self, *args, **kwargs):
        self.players = WeakKeyDictionary()
        self.games = WeakKeyDictionary()
        self.other = None
        Server.__init__(self, *args, **kwargs)
        print "Server launched"

    def Connected(self, channel, addr):
        self.AddPlayer(channel)

    def AddPlayer(self, player):
        print "Adding player "
        game = self.getAvailableGames()
        uuid = player.uuid
        self.players[uuid] = player
        player.Send({"action": "getUUID", "message": str(uuid)})
        if not game is None:
            player.inGame = True
            self.games[game].addPlayer(player)
            player.game = game
            opponents = game.getOpponents(player)
            if game.minPlayersConnected() == True:
                player.inGame = True
                # player.Send({"action": "inGameStart", "message": str(opponents[0].uuid)})
                # self.other.Send({"action":"inGameStart", "message": str(uuid)})
                for p in opponents:
                    p.Send({"action": "inGameStart", "message": str(uuid)})
                    self.players[p.uuid].inGame = True
        else:
            game = Game()
            game.addPlayer(player)
            self.games[game] = game
            player.game = game
            player.Send({"action": "isHost", "message": True})
            self.other = player

    def getAvailableGames(self):
        game = None
        listGames = self.games.values()
        for g in listGames:
            if g.numberOfPlayers() == 1:
                game = g
                break
        return game

    def getPlayer(self, playerUUID):
        uuid = self.convertUUID(playerUUID)
        return self.players[uuid]

    def DelPlayer(self, player):
        print "Deleting Player " + str(player.nickName)
        game = player.game
        game.removePlayer(player)
        players = game.getPlayers()
        if game.minPlayersConnected() == False:
            if len(players) >= 1:
                [p.Send({"action": "message", "message": "Not enough players"}) for p in players]
                [p.Send({"action": "inGameStart", "message": None}) for p in players]
            else:
                del self.games[game]
        else:
            [p.Send({"action": "message", "message": str(p.nickName) + " left the game"}) for p in players]

    def sendPlayer(self, playerUUID, data):
        uuid = self.convertUUID(playerUUID)
        self.players[uuid].Send(data)

    def SendPlayers(self, nickName):
        self.SendToAll({"action": "message", "message": str(nickName) + " has joined"})

    def convertUUID(self, data):
        strUUID = uuid.UUID(data["message"]).hex
        return uuid.UUID(strUUID)

    def SendToAll(self, data):
        print self.players
        [p.Send(data) for p in self.players]

    def Launch(self):
        while True:
            self.Pump()
            sleep(0.0001)
开发者ID:borgaster,项目名称:GameServerClient,代码行数:87,代码来源:GameServer.py

示例7: GameServer

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import values [as 别名]
class GameServer(object):
    """
    """
    
    def __init__(self):
        """
        
        """
        #: List of available Game sessions object
        self.sessions = {}
        
        self.clients = WeakKeyDictionary()
        
        
    def create_client(self, socket, id):
        """
        Create a new game client.
        """
        client = GameClient(self, socket, id)
        
        self.clients[socket] = client
        
        client.send_message("welcome", None)
        
        logger.info("Client succesfully connected")
        
        return client
    
    def create_session(self, host, name):
        """
        Create a new game session.
        
        :param host: GameClient instance hosting the session
        """
        
        session = GameSession(self, host)
        session.init(name)        
        
        self.sessions[session.id] = session
        
        return session
        
    def join_session(self, session_id, client):
        """
        Join to an existing gaming session.
        
        :return: Session object where we joined or None if failed
        """
        
        session = self.sessions.get(session_id, None)
        if not session:
            return None
        
        session.add_client(client)
      
        self.broadcast_all("clientJoined", client)
        
        self.broadcast_all("sessionStateChanged", session)
        
        return session

    def on_client_message(self, socket, message, payload):
        """
        Handle l
        """
        
        client = self.clients[socket]
        
        client.on_message(message, payload)
        
    def close_client(self, client):
        """
        Clean-up client and make other players aware we lost this one.
        """
        del self.clients[client.socket]
        
    def broadcast_all(self, type, payload):
        """
        Send a message to all client.
        """
        for client in self.clients.values():
            client.send_message(type, payload)
开发者ID:miohtama,项目名称:mopedwarriors,代码行数:84,代码来源:main.py


注:本文中的weakref.WeakKeyDictionary.values方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。