text
stringlengths
81
112k
Updating the payoff convex hull by iterating all action pairs. Using the R operator proposed by Abreu and Sannikov 2014. Parameters ---------- delta : scalar(float) The common discount rate at which all players discount the future. nums_actions : tuple(int) Tuple of...
Find all the intersection points between the current convex hull and the two IC constraints. It is done by iterating simplex counterclockwise. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated potential extreme points of one action profile. ...
Find the intersection points of a half-closed simplex (pt0, pt1] and IC constraints. Parameters ---------- C : ndarray(float, ndim=2) The 4 by 2 array for storing the generated points of one action profile. One action profile can only generate at most 4 points. n : scalar(i...
Update the threat points if it not feasible in the new W, by the minimum of new feasible payoffs. Parameters ---------- u : ndarray(float, ndim=1) The threat points. W : ndarray(float, ndim=1) The points that construct the feasible payoff convex hull. Returns ------- u...
Compute the set of payoff pairs of all pure-strategy subgame-perfect equilibria with public randomization for any repeated two-player games with perfect monitoring and discounting. Parameters ---------- method : str, optional The method for solving the equilibrium pa...
Return a random NormalFormGame instance where the payoffs are drawn independently from the uniform distribution on [0, 1). Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one for each player. random_state : int or np.random.RandomState, optional Ran...
Return a random NormalFormGame instance where the payoff profiles are drawn independently from the standard multi-normal with the covariance of any pair of payoffs equal to `rho`, as studied in [1]_. Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one fo...
Return a tuple of random pure actions (integers). Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one for each player. random_state : int or np.random.RandomState, optional Random seed (integer) or np.random.RandomState instance to set the initi...
Return a tuple of random mixed actions (vectors of floats). Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one for each player. random_state : int or np.random.RandomState, optional Random seed (integer) or np.random.RandomState instance to set ...
Retrieve raw files from QuantEcon.notebooks or other Github repo Parameters ---------- file_list list or dict A list of files to specify a collection of filenames A dict of dir : list(files) to specify a directory repo str, optional(default=REPO) raw ...
r""" Compute the limit of a Nash linear quadratic dynamic game. In this problem, player i minimizes .. math:: \sum_{t=0}^{\infty} \left\{ x_t' r_i x_t + 2 x_t' w_i u_{it} +u_{it}' q_i u_{it} + u_{jt}' s_i u_{jt} + 2 u_{jt}' m_i u_{it} \right\} ...
r"""Select from a tuple of(root, funccalls, iterations, flag) def _results(r): r"""Select from a tuple of(root, funccalls, iterations, flag)""" x, funcalls, iterations, flag = r return results(x, funcalls, iterations, flag == 0)
Find a zero from the Newton-Raphson method using the jitted version of Scipy's newton for scalars. Note that this does not provide an alternative method such as secant. Thus, it is important that `fprime` can be provided. Note that `func` and `fprime` must be jitted via Numba. They are recommended to b...
Find a zero from the secant method using the jitted version of Scipy's secant method. Note that `func` must be jitted via Numba. Parameters ---------- func : callable and jitted The function whose zero is wanted. It must be a function of a single variable of the form f(x,a,b,c...),...
Conditional checks for intervals in methods involving bisection def _bisect_interval(a, b, fa, fb): """Conditional checks for intervals in methods involving bisection""" if fa*fb > 0: raise ValueError("f(a) and f(b) must have different signs") root = 0.0 status = _ECONVERR # Root found at ...
Find root of a function within an interval adapted from Scipy's bisect. Basic bisection routine to find a zero of the function `f` between the arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same signs. `f` must be jitted via numba. Parameters ---------- f : jitted and callable ...
Find a root of a function in a bracketing interval using Brent's method adapted from Scipy's brentq. Uses the classic Brent's method to find a zero of the function `f` on the sign changing interval [a , b]. `f` must be jitted via numba. Parameters ---------- f : jitted and callable ...
r""" Computes and returns an approximate fixed point of the function `T`. The default method `'iteration'` simply iterates the function given an initial condition `v` and returns :math:`T^k v` when the condition :math:`\lVert T^k v - T^{k-1} v\rVert \leq \mathrm{error\_tol}` is satisfied or the num...
Implement the imitation game algorithm by McLennan and Tourky (2006) for computing an approximate fixed point of `T`. Parameters ---------- is_approx_fp : callable A callable with signature `is_approx_fp(v)` which determines whether `v` is an approximate fixed point with a bool return ...
Given sequences `X` and `Y` of ndarrays, initialize the tableau and basis arrays in place for the "geometric" imitation game as defined in McLennan and Tourky (2006), to be passed to `_lemke_howson_tbl`. Parameters ---------- X, Y : ndarray(float) Arrays of the same shape (m, n). table...
Return an iterable with the active participants in a room. def get_participants(self, namespace, room): """Return an iterable with the active participants in a room.""" for sid, active in six.iteritems(self.rooms[namespace][room].copy()): yield sid
Register a client connection to a namespace. def connect(self, sid, namespace): """Register a client connection to a namespace.""" self.enter_room(sid, namespace, None) self.enter_room(sid, namespace, sid)
Put the client in the to-be-disconnected list. This allows the client data structures to be present while the disconnect handler is invoked, but still recognize the fact that the client is soon going away. def pre_disconnect(self, sid, namespace): """Put the client in the to-be-disconn...
Register a client disconnect from a namespace. def disconnect(self, sid, namespace): """Register a client disconnect from a namespace.""" if namespace not in self.rooms: return rooms = [] for room_name, room in six.iteritems(self.rooms[namespace].copy()): if sid ...
Add a client to a room. def enter_room(self, sid, namespace, room): """Add a client to a room.""" if namespace not in self.rooms: self.rooms[namespace] = {} if room not in self.rooms[namespace]: self.rooms[namespace][room] = {} self.rooms[namespace][room][sid] = ...
Remove a client from a room. def leave_room(self, sid, namespace, room): """Remove a client from a room.""" try: del self.rooms[namespace][room][sid] if len(self.rooms[namespace][room]) == 0: del self.rooms[namespace][room] if len(self.rooms[names...
Remove all participants from a room. def close_room(self, room, namespace): """Remove all participants from a room.""" try: for sid in self.get_participants(namespace, room): self.leave_room(sid, namespace, room) except KeyError: pass
Return the rooms a client is in. def get_rooms(self, sid, namespace): """Return the rooms a client is in.""" r = [] try: for room_name, room in six.iteritems(self.rooms[namespace]): if room_name is not None and sid in room and room[sid]: r.append(...
Invoke an application callback. def trigger_callback(self, sid, namespace, id, data): """Invoke an application callback.""" callback = None try: callback = self.callbacks[sid][namespace][id] except KeyError: # if we get an unknown callback we just ignore it ...
Generate a unique identifier for an ACK packet. def _generate_ack_id(self, sid, namespace, callback): """Generate a unique identifier for an ACK packet.""" namespace = namespace or '/' if sid not in self.callbacks: self.callbacks[sid] = {} if namespace not in self.callbacks[...
Get the appropriate logger Prevents uninitialized servers in write-only mode from failing. def _get_logger(self): """Get the appropriate logger Prevents uninitialized servers in write-only mode from failing. """ if self.logger: return self.logger elif self...
Register an event handler. :param event: The event name. It can be any string. The event names ``'connect'``, ``'message'`` and ``'disconnect'`` are reserved and should not be used. :param handler: The function that should be invoked to handle the ...
Register a namespace handler object. :param namespace_handler: An instance of a :class:`Namespace` subclass that handles all the event traffic for a namespace. def register_namespace(self, namespace_handler): """Register a namespace h...
Enter a room. This function adds the client to a room. The :func:`emit` and :func:`send` functions can optionally broadcast events to all the clients in a room. :param sid: Session ID of the client. :param room: Room name. If the room does not exist it is created. :para...
Leave a room. This function removes the client from a room. :param sid: Session ID of the client. :param room: Room name. :param namespace: The Socket.IO namespace for the event. If this argument is omitted the default namespace is used. def leave_room(self, ...
Return the rooms a client is in. :param sid: Session ID of the client. :param namespace: The Socket.IO namespace for the event. If this argument is omitted the default namespace is used. def rooms(self, sid, namespace=None): """Return the rooms a client is in. ...
Return the user session for a client. :param sid: The session id of the client. :param namespace: The Socket.IO namespace. If this argument is omitted the default namespace is used. The return value is a dictionary. Modifications made to this dictionary are no...
Store the user session for a client. :param sid: The session id of the client. :param session: The session dictionary. :param namespace: The Socket.IO namespace. If this argument is omitted the default namespace is used. def save_session(self, sid, session, namespace=...
Return the user session for a client with context manager syntax. :param sid: The session id of the client. This is a context manager that returns the user session dictionary for the client. Any changes that are made to this dictionary inside the context manager block are saved back to...
Start a background task using the appropriate async model. This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode. :param target: the target function to execute. :param args: arguments to ...
Send a message to a client. def _emit_internal(self, sid, event, data, namespace=None, id=None): """Send a message to a client.""" if six.PY2 and not self.binary: binary = False # pragma: nocover else: binary = None # tuples are expanded to multiple arguments, e...
Send a Socket.IO packet to a client. def _send_packet(self, sid, pkt): """Send a Socket.IO packet to a client.""" encoded_packet = pkt.encode() if isinstance(encoded_packet, list): binary = False for ep in encoded_packet: self.eio.send(sid, ep, binary=bin...
Handle a client connection request. def _handle_connect(self, sid, namespace): """Handle a client connection request.""" namespace = namespace or '/' self.manager.connect(sid, namespace) if self.always_connect: self._send_packet(sid, packet.Packet(packet.CONNECT, ...
Handle a client disconnect. def _handle_disconnect(self, sid, namespace): """Handle a client disconnect.""" namespace = namespace or '/' if namespace == '/': namespace_list = list(self.manager.get_namespaces()) else: namespace_list = [namespace] for n in ...
Handle an incoming client event. def _handle_event(self, sid, namespace, id, data): """Handle an incoming client event.""" namespace = namespace or '/' self.logger.info('received event "%s" from %s [%s]', data[0], sid, namespace) if self.async_handlers: ...
Invoke an application event handler. def _trigger_event(self, event, namespace, *args): """Invoke an application event handler.""" # first see if we have an explicit handler for the event if namespace in self.handlers and event in self.handlers[namespace]: return self.handlers[names...
Handle the Engine.IO connection event. def _handle_eio_connect(self, sid, environ): """Handle the Engine.IO connection event.""" if not self.manager_initialized: self.manager_initialized = True self.manager.initialize() self.environ[sid] = environ return self._ha...
Dispatch Engine.IO messages. def _handle_eio_message(self, sid, data): """Dispatch Engine.IO messages.""" if sid in self._binary_packet: pkt = self._binary_packet[sid] if pkt.add_attachment(data): del self._binary_packet[sid] if pkt.packet_type ==...
Handle Engine.IO disconnect event. def _handle_eio_disconnect(self, sid): """Handle Engine.IO disconnect event.""" self._handle_disconnect(sid, '/') if sid in self.environ: del self.environ[sid]
Emit a message to a single client, a room, or all the clients connected to the namespace. This method takes care or propagating the message to all the servers that are connected through the message queue. The parameters are the same as in :meth:`.Server.emit`. Note: this metho...
Connect to a Socket.IO server. :param url: The URL of the Socket.IO server. It can include custom query string parameters if required by the server. :param headers: A dictionary with custom headers to send with the connection request. :param transport...
Wait until the connection with the server ends. Client applications can use this function to block the main thread during the life of the connection. Note: this method is a coroutine. async def wait(self): """Wait until the connection with the server ends. Client applications...
Register a namespace handler object. :param namespace_handler: An instance of a :class:`Namespace` subclass that handles all the event traffic for a namespace. def register_namespace(self, namespace_handler): """Register a namespace h...
Emit a custom event to one or more connected clients. :param event: The event name. It can be any string. The event names ``'connect'``, ``'message'`` and ``'disconnect'`` are reserved and should not be used. :param data: The data to send to the client or cli...
Send a message to one or more connected clients. This function emits an event with the name ``'message'``. Use :func:`emit` to issue custom event names. :param data: The data to send to the client or clients. Data can be of type ``str``, ``bytes``, ``list`` or ``dict``. If...
Emit a custom event to a client and wait for the response. :param event: The event name. It can be any string. The event names ``'connect'``, ``'message'`` and ``'disconnect'`` are reserved and should not be used. :param data: The data to send to the client o...
Disconnect from the server. def disconnect(self): """Disconnect from the server.""" # here we just request the disconnection # later in _handle_eio_disconnect we invoke the disconnect handler for n in self.namespaces: self._send_packet(packet.Packet(packet.DISCONNECT, namesp...
Handle the Engine.IO disconnection event. def _handle_eio_disconnect(self): """Handle the Engine.IO disconnection event.""" self.logger.info('Engine.IO connection dropped') for n in self.namespaces: self._trigger_event('disconnect', namespace=n) self._trigger_event('disconne...
Encode the packet for transmission. If the packet contains binary elements, this function returns a list of packets where the first is the original packet with placeholders for the binary components and the remaining ones the binary attachments. def encode(self): """Encode the packet f...
Decode a transmitted package. The return value indicates how many binary attachment packets are necessary to fully decode the packet. def decode(self, encoded_packet): """Decode a transmitted package. The return value indicates how many binary attachment packets are necessary ...
Reconstruct a decoded packet using the given list of binary attachments. def reconstruct_binary(self, attachments): """Reconstruct a decoded packet using the given list of binary attachments. """ self.data = self._reconstruct_binary_internal(self.data, ...
Extract binary components in the packet. def _deconstruct_binary(self, data): """Extract binary components in the packet.""" attachments = [] data = self._deconstruct_binary_internal(data, attachments) return data, attachments
Check if the data contains binary components. def _data_is_binary(self, data): """Check if the data contains binary components.""" if isinstance(data, six.binary_type): return True elif isinstance(data, list): return functools.reduce( lambda a, b: a or b,...
Dispatch an event to the proper handler method. In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overriden if special dispatching rules are needed, or if having a single method that catche...
Close a room. The only difference with the :func:`socketio.Server.close_room` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. Note: this method is a coroutine. async def close_room(self, room, namespace=None): """Clo...
Disconnect a client. The only difference with the :func:`socketio.Server.disconnect` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. Note: this method is a coroutine. async def disconnect(self, sid, namespace=None): ...
Emit a custom event to the server. The only difference with the :func:`socketio.Client.emit` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. Note: this method is a coroutine. async def emit(self, event, data=None, namespace=...
Send a message to the server. The only difference with the :func:`socketio.Client.send` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. Note: this method is a coroutine. async def send(self, data, namespace=None, callback=No...
Dispatch an event to the proper handler method. In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overriden if special dispatching rules are needed, or if having a single method that catche...
Emit a custom event to one or more connected clients. The only difference with the :func:`socketio.Server.emit` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. def emit(self, event, data=None, room=None, skip_sid=None, namespace=None...
Send a message to one or more connected clients. The only difference with the :func:`socketio.Server.send` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. def send(self, data, room=None, skip_sid=None, namespace=None, ca...
Enter a room. The only difference with the :func:`socketio.Server.enter_room` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. def enter_room(self, sid, room, namespace=None): """Enter a room. The only difference with...
Leave a room. The only difference with the :func:`socketio.Server.leave_room` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. def leave_room(self, sid, room, namespace=None): """Leave a room. The only difference with...
Return the rooms a client is in. The only difference with the :func:`socketio.Server.rooms` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. def rooms(self, sid, namespace=None): """Return the rooms a client is in. Th...
Return the user session for a client. The only difference with the :func:`socketio.Server.get_session` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. def get_session(self, sid, namespace=None): """Return the user session for...
Store the user session for a client. The only difference with the :func:`socketio.Server.save_session` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. def save_session(self, sid, session, namespace=None): """Store the user se...
Send a message to the server. The only difference with the :func:`socketio.Client.send` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. def send(self, data, room=None, skip_sid=None, namespace=None, callback=None): ...
Emit a message to a single client, a room, or all the clients connected to the namespace. Note: this method is a coroutine. async def emit(self, event, data, namespace, room=None, skip_sid=None, callback=None, **kwargs): """Emit a message to a single client, a room, or all t...
Invoke an application callback. Note: this method is a coroutine. async def trigger_callback(self, sid, namespace, id, data): """Invoke an application callback. Note: this method is a coroutine. """ callback = None try: callback = self.callbacks[sid][namesp...
Emit a custom event to one or more connected clients. :param event: The event name. It can be any string. The event names ``'connect'``, ``'message'`` and ``'disconnect'`` are reserved and should not be used. :param data: The data to send to the client or cli...
Send a message to one or more connected clients. This function emits an event with the name ``'message'``. Use :func:`emit` to issue custom event names. :param data: The data to send to the client or clients. Data can be of type ``str``, ``bytes``, ``list`` or ``dict``. If...
Close a room. This function removes all the clients from the given room. :param room: Room name. :param namespace: The Socket.IO namespace for the event. If this argument is omitted the default namespace is used. Note: this method is a coroutine. async def c...
Disconnect a client. :param sid: Session ID of the client. :param namespace: The Socket.IO namespace to disconnect. If this argument is omitted the default namespace is used. Note: this method is a coroutine. async def disconnect(self, sid, namespace=None): "...
Handle ACK packets from the client. async def _handle_ack(self, sid, namespace, id, data): """Handle ACK packets from the client.""" namespace = namespace or '/' self.logger.info('received ack from %s [%s]', sid, namespace) await self.manager.trigger_callback(sid, namespace, id, data)
Invoke an application event handler. async def _trigger_event(self, event, namespace, *args): """Invoke an application event handler.""" # first see if we have an explicit handler for the event if namespace in self.handlers and event in self.handlers[namespace]: if asyncio.iscorouti...
Determine whether ``__tablename__`` should be automatically generated for a model. * If no class in the MRO sets a name, one should be generated. * If a declared attr is found, it should be used instead. * If a name is found, it should be used if the class is a mixin, otherwise one should be gene...
View decorator that redirects anonymous users to the login page. def login_required(view): """View decorator that redirects anonymous users to the login page.""" @functools.wraps(view) def wrapped_view(**kwargs): if g.user is None: return redirect(url_for("auth.login")) return...
If a user id is stored in the session, load the user object from the database into ``g.user``. def load_logged_in_user(): """If a user id is stored in the session, load the user object from the database into ``g.user``.""" user_id = session.get("user_id") g.user = User.query.get(user_id) if user_id...
Register a new user. Validates that the username is not already taken. Hashes the password for security. def register(): """Register a new user. Validates that the username is not already taken. Hashes the password for security. """ if request.method == "POST": username = request....
Log in a registered user by adding the user id to the session. def login(): """Log in a registered user by adding the user id to the session.""" if request.method == "POST": username = request.form["username"] password = request.form["password"] error = None user = User.query.fi...
Show all the posts, most recent first. def index(): """Show all the posts, most recent first.""" posts = Post.query.order_by(Post.created.desc()).all() return render_template("blog/index.html", posts=posts)
Get a post and its author by id. Checks that the id exists and optionally that the current user is the author. :param id: id of post to get :param check_author: require the current user to be the author :return: the post with author information :raise 404: if a post with the given id doesn't e...
Create a new post for the current user. def create(): """Create a new post for the current user.""" if request.method == "POST": title = request.form["title"] body = request.form["body"] error = None if not title: error = "Title is required." if error is no...
Update a post if the current user is the author. def update(id): """Update a post if the current user is the author.""" post = get_post(id) if request.method == "POST": title = request.form["title"] body = request.form["body"] error = None if not title: error =...
Delete a post. Ensures that the post exists and that the logged in user is the author of the post. def delete(id): """Delete a post. Ensures that the post exists and that the logged in user is the author of the post. """ post = get_post(id) db.session.delete(post) db.session.commi...
Take a string version and conver it to a tuple (for easier comparison), e.g.: "1.2.3" --> (1, 2, 3) "1.2" --> (1, 2, 0) "1" --> (1, 0, 0) def parse_version(v): """ Take a string version and conver it to a tuple (for easier comparison), e.g.: "1.2.3" --> (1,...
Return the engine or connection for a given model or table, using the ``__bind_key__`` if it is set. def get_bind(self, mapper=None, clause=None): """Return the engine or connection for a given model or table, using the ``__bind_key__`` if it is set. """ # mapper is None if some...
The total number of pages def pages(self): """The total number of pages""" if self.per_page == 0 or self.total is None: pages = 0 else: pages = int(ceil(self.total / float(self.per_page))) return pages
Returns a :class:`Pagination` object for the next page. def next(self, error_out=False): """Returns a :class:`Pagination` object for the next page.""" assert self.query is not None, 'a query object is required ' \ 'for this method to work' return self.quer...
Like :meth:`get` but aborts with 404 if not found instead of returning ``None``. def get_or_404(self, ident, description=None): """Like :meth:`get` but aborts with 404 if not found instead of returning ``None``.""" rv = self.get(ident) if rv is None: abort(404, description=descript...