sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
def check(codeString, filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Check the Python source given by codeString for unfrosted flakes."""
if not settings_path and filename:
settings_path = os.path.dirname(os.path.abspath(filename))
settings_path = settings_path or os.getcwd()
active_settings = settings.from_path(settings_path).copy()
for key, value in itemsview(setting_overrides):
access_key = key.replace('not_', '').lower()
if type(active_settings.get(access_key)) in (list, tuple):
if key.startswith('not_'):
active_settings[access_key] = list(set(active_settings[access_key]).difference(value))
else:
active_settings[access_key] = list(set(active_settings[access_key]).union(value))
else:
active_settings[key] = value
active_settings.update(setting_overrides)
if _should_skip(filename, active_settings.get('skip', [])):
if active_settings.get('directly_being_checked', None) == 1:
reporter.flake(FileSkipped(filename))
return 1
elif active_settings.get('verbose', False):
ignore = active_settings.get('ignore_frosted_errors', [])
if(not "W200" in ignore and not "W201" in ignore):
reporter.flake(FileSkipped(filename, None, verbose=active_settings.get('verbose')))
return 0
# First, compile into an AST and handle syntax errors.
try:
tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
# If there's an encoding problem with the file, the text is None.
if text is None:
# Avoid using msg, since for the only known case, it contains a
# bogus message that claims the encoding the file declared was
# unknown.
reporter.unexpected_error(filename, 'problem decoding source')
else:
reporter.flake(PythonSyntaxError(filename, msg, lineno, offset, text,
verbose=active_settings.get('verbose')))
return 1
except Exception:
reporter.unexpected_error(filename, 'problem decoding source')
return 1
# Okay, it's syntactically valid. Now check it.
w = checker.Checker(tree, filename, None, ignore_lines=_noqa_lines(codeString), **active_settings)
w.messages.sort(key=lambda m: m.lineno)
for warning in w.messages:
reporter.flake(warning)
return len(w.messages) | Check the Python source given by codeString for unfrosted flakes. | entailment |
def check_path(filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Check the given path, printing out any warnings detected."""
try:
with open(filename, 'U') as f:
codestr = f.read() + '\n'
except UnicodeError:
reporter.unexpected_error(filename, 'problem decoding source')
return 1
except IOError:
msg = sys.exc_info()[1]
reporter.unexpected_error(filename, msg.args[1])
return 1
return check(codestr, filename, reporter, settings_path, **setting_overrides) | Check the given path, printing out any warnings detected. | entailment |
def check_recursive(paths, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Recursively check all source files defined in paths."""
warnings = 0
for source_path in iter_source_code(paths):
warnings += check_path(source_path, reporter, settings_path=None, **setting_overrides)
return warnings | Recursively check all source files defined in paths. | entailment |
def get_files_from_storage(paths):
"""Return S3 file where the name does not include the path."""
for path in paths:
f = default_storage.open(path)
f.name = os.path.basename(path)
try:
yield f
except ClientError:
logger.exception("File not found: %s", path) | Return S3 file where the name does not include the path. | entailment |
def echo(bot, update):
"""Echo the user message."""
message = update.get_effective_message()
bot.reply(update, message) | Echo the user message. | entailment |
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.error('Update {} caused error {}'.format(update, error), extra={"tag": "err"}) | Log Errors caused by Updates. | entailment |
def main():
"""Start the bot."""
# Bale Bot Authorization Token
updater = Updater("TOKEN")
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Bale
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Bale
dp.add_handler(MessageHandler(DefaultFilter(), echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.run() | Start the bot. | entailment |
def server_from_config(config=None, server_class=None, additional_kwargs=None):
"""
Gets a configured L{coilmq.server.StompServer} from specified config.
If `config` is None, global L{coilmq.config.config} var will be used instead.
The `server_class` and `additional_kwargs` are primarily hooks for using this method
from a testing environment.
@param config: A C{ConfigParser.ConfigParser} instance with loaded config values.
@type config: C{ConfigParser.ConfigParser}
@param server_class: Which class to use for the server. (This doesn't come from config currently.)
@type server_class: C{class}
@param additional_kwargs: Any additional args that should be passed to class.
@type additional_kwargs: C{list}
@return: The configured StompServer.
@rtype: L{coilmq.server.StompServer}
"""
global global_config
if not config:
config = global_config
queue_store_factory = resolve_name(config.get('coilmq', 'qstore.factory'))
subscriber_scheduler_factory = resolve_name(config.get(
'coilmq', 'scheduler.subscriber_priority_factory'))
queue_scheduler_factory = resolve_name(config.get(
'coilmq', 'scheduler.queue_priority_factory'))
if config.has_option('coilmq', 'auth.factory'):
authenticator_factory = resolve_name(
config.get('coilmq', 'auth.factory'))
authenticator = authenticator_factory()
else:
authenticator = None
server = ThreadedStompServer((config.get('coilmq', 'listen_addr'), config.getint('coilmq', 'listen_port')),
queue_manager=QueueManager(store=queue_store_factory(),
subscriber_scheduler=subscriber_scheduler_factory(),
queue_scheduler=queue_scheduler_factory()),
topic_manager=TopicManager(),
authenticator=authenticator,
protocol=STOMP11)
logger.info("Created server:%r" % server)
return server | Gets a configured L{coilmq.server.StompServer} from specified config.
If `config` is None, global L{coilmq.config.config} var will be used instead.
The `server_class` and `additional_kwargs` are primarily hooks for using this method
from a testing environment.
@param config: A C{ConfigParser.ConfigParser} instance with loaded config values.
@type config: C{ConfigParser.ConfigParser}
@param server_class: Which class to use for the server. (This doesn't come from config currently.)
@type server_class: C{class}
@param additional_kwargs: Any additional args that should be passed to class.
@type additional_kwargs: C{list}
@return: The configured StompServer.
@rtype: L{coilmq.server.StompServer} | entailment |
def context_serve(context, configfile, listen_addr, listen_port, logfile,
debug, daemon, uid, gid, pidfile, umask, rundir):
"""
Takes a context object, which implements the __enter__/__exit__ "with" interface
and starts a server within that context.
This method is a refactored single-place for handling the server-run code whether
running in daemon or non-daemon mode. It is invoked with a dummy (passthrough)
context object for the non-daemon use case.
@param options: The compiled collection of options that need to be parsed.
@type options: C{ConfigParser}
@param context: The context object that implements __enter__/__exit__ "with" methods.
@type context: C{object}
@raise Exception: Any underlying exception will be logged but then re-raised.
@see: server_from_config()
"""
global global_config
server = None
try:
with context:
# There's a possibility here that init_logging() will throw an exception. If it does,
# AND we're in a daemon context, then we're not going to be able to do anything with it.
# We've got no stderr/stdout here; and so (to my knowledge) no reliable (& cross-platform),
# way to display errors.
level = logging.DEBUG if debug else logging.INFO
init_logging(logfile=logfile, loglevel=level,
configfile=configfile)
server = server_from_config()
logger.info("Stomp server listening on %s:%s" % server.server_address)
if debug:
poll_interval = float(global_config.get(
'coilmq', 'debug.stats_poll_interval'))
if poll_interval: # Setting poll_interval to 0 effectively disables it.
def diagnostic_loop(server):
log = logger
while True:
log.debug(
"Stats heartbeat -------------------------------")
store = server.queue_manager.store
for dest in store.destinations():
log.debug("Queue %s: size=%s, subscribers=%s" % (
dest, store.size(dest), server.queue_manager.subscriber_count(dest)))
# TODO: Add number of subscribers?
time.sleep(poll_interval)
diagnostic_thread = threading.Thread(
target=diagnostic_loop, name='DiagnosticThread', args=(server,))
diagnostic_thread.daemon = True
diagnostic_thread.start()
server.serve_forever()
except (KeyboardInterrupt, SystemExit):
logger.info("Stomp server stopped by user interrupt.")
raise SystemExit()
except Exception as e:
logger.error("Stomp server stopped due to error: %s" % e)
logger.exception(e)
raise SystemExit()
finally:
if server:
server.server_close() | Takes a context object, which implements the __enter__/__exit__ "with" interface
and starts a server within that context.
This method is a refactored single-place for handling the server-run code whether
running in daemon or non-daemon mode. It is invoked with a dummy (passthrough)
context object for the non-daemon use case.
@param options: The compiled collection of options that need to be parsed.
@type options: C{ConfigParser}
@param context: The context object that implements __enter__/__exit__ "with" methods.
@type context: C{object}
@raise Exception: Any underlying exception will be logged but then re-raised.
@see: server_from_config() | entailment |
def main(config, host, port, logfile, debug, daemon, uid, gid, pidfile, umask, rundir):
"""
Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whether deamon mode was specified or not,
the process may be forked (or not) and the server will be started.
"""
_main(**locals()) | Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whether deamon mode was specified or not,
the process may be forked (or not) and the server will be started. | entailment |
def make_sa():
"""
Factory to creates a SQLAlchemy queue store, pulling config values from the CoilMQ configuration.
"""
configuration = dict(config.items('coilmq'))
engine = engine_from_config(configuration, 'qstore.sqlalchemy.')
init_model(engine)
store = SAQueue()
return store | Factory to creates a SQLAlchemy queue store, pulling config values from the CoilMQ configuration. | entailment |
def init_model(engine, create=True, drop=False):
"""
Initializes the shared SQLAlchemy state in the L{coilmq.store.sa.model} module.
@param engine: The SQLAlchemy engine instance.
@type engine: C{sqlalchemy.Engine}
@param create: Whether to create the tables (if they do not exist).
@type create: C{bool}
@param drop: Whether to drop the tables (if they exist).
@type drop: C{bool}
"""
meta.engine = engine
meta.metadata = MetaData(bind=meta.engine)
meta.Session = scoped_session(sessionmaker(bind=meta.engine))
model.setup_tables(create=create, drop=drop) | Initializes the shared SQLAlchemy state in the L{coilmq.store.sa.model} module.
@param engine: The SQLAlchemy engine instance.
@type engine: C{sqlalchemy.Engine}
@param create: Whether to create the tables (if they do not exist).
@type create: C{bool}
@param drop: Whether to drop the tables (if they exist).
@type drop: C{bool} | entailment |
def enqueue(self, destination, frame):
"""
Store message (frame) for specified destinationination.
@param destination: The destinationination queue name for this message (frame).
@type destination: C{str}
@param frame: The message (frame) to send to specified destinationination.
@type frame: C{stompclient.frame.Frame}
"""
session = meta.Session()
message_id = frame.headers.get('message-id')
if not message_id:
raise ValueError("Cannot queue a frame without message-id set.")
ins = model.frames_table.insert().values(
message_id=message_id, destination=destination, frame=frame)
session.execute(ins)
session.commit() | Store message (frame) for specified destinationination.
@param destination: The destinationination queue name for this message (frame).
@type destination: C{str}
@param frame: The message (frame) to send to specified destinationination.
@type frame: C{stompclient.frame.Frame} | entailment |
def dequeue(self, destination):
"""
Removes and returns an item from the queue (or C{None} if no items in queue).
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: The first frame in the specified queue, or C{None} if there are none.
@rtype: C{stompclient.frame.Frame}
"""
session = meta.Session()
try:
selstmt = select(
[model.frames_table.c.message_id, model.frames_table.c.frame])
selstmt = selstmt.where(
model.frames_table.c.destination == destination)
selstmt = selstmt.order_by(
model.frames_table.c.queued, model.frames_table.c.sequence)
result = session.execute(selstmt)
first = result.fetchone()
if not first:
return None
delstmt = model.frames_table.delete().where(model.frames_table.c.message_id ==
first[model.frames_table.c.message_id])
session.execute(delstmt)
frame = first[model.frames_table.c.frame]
except:
session.rollback()
raise
else:
session.commit()
return frame | Removes and returns an item from the queue (or C{None} if no items in queue).
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: The first frame in the specified queue, or C{None} if there are none.
@rtype: C{stompclient.frame.Frame} | entailment |
def has_frames(self, destination):
"""
Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool}
"""
session = meta.Session()
sel = select([model.frames_table.c.message_id]).where(
model.frames_table.c.destination == destination)
result = session.execute(sel)
first = result.fetchone()
return first is not None | Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool} | entailment |
def size(self, destination):
"""
Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int}
"""
session = meta.Session()
sel = select([func.count(model.frames_table.c.message_id)]).where(
model.frames_table.c.destination == destination)
result = session.execute(sel)
first = result.fetchone()
if not first:
return 0
else:
return int(first[0]) | Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int} | entailment |
def destinations(self):
"""
Provides a list of destinations (queue "addresses") available.
@return: A list of the detinations available.
@rtype: C{set}
"""
session = meta.Session()
sel = select([distinct(model.frames_table.c.destination)])
result = session.execute(sel)
return set([r[0] for r in result.fetchall()]) | Provides a list of destinations (queue "addresses") available.
@return: A list of the detinations available.
@rtype: C{set} | entailment |
def setup_tables(create=True, drop=False):
"""
Binds the model classes to registered metadata and engine and (potentially)
creates the db tables.
This function expects that you have bound the L{meta.metadata} and L{meta.engine}.
@param create: Whether to create the tables (if they do not exist).
@type create: C{bool}
@param drop: Whether to drop the tables (if they exist).
@type drop: C{bool}
"""
global frames_table
frames_table = Table('frames', meta.metadata,
Column('message_id', String(255), primary_key=True),
Column('sequence', BigInteger,
primary_key=False, autoincrement=True),
Column('destination', String(255), index=True),
Column('frame', PickleType),
Column('queued', DateTime, default=func.now()))
if drop:
meta.metadata.drop_all()
if drop or create:
meta.metadata.create_all() | Binds the model classes to registered metadata and engine and (potentially)
creates the db tables.
This function expects that you have bound the L{meta.metadata} and L{meta.engine}.
@param create: Whether to create the tables (if they do not exist).
@type create: C{bool}
@param drop: Whether to drop the tables (if they exist).
@type drop: C{bool} | entailment |
def subscribe(self, connection, destination):
"""
Subscribes a connection to the specified topic destination.
@param connection: The client connection to subscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str}
"""
self.log.debug("Subscribing %s to %s" % (connection, destination))
self._topics[destination].add(connection) | Subscribes a connection to the specified topic destination.
@param connection: The client connection to subscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str} | entailment |
def unsubscribe(self, connection, destination):
"""
Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str}
"""
self.log.debug("Unsubscribing %s from %s" % (connection, destination))
if connection in self._topics[destination]:
self._topics[destination].remove(connection)
if not self._topics[destination]:
del self._topics[destination] | Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str} | entailment |
def disconnect(self, connection):
"""
Removes a subscriber connection.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
"""
self.log.debug("Disconnecting %s" % connection)
for dest in list(self._topics.keys()):
if connection in self._topics[dest]:
self._topics[dest].remove(connection)
if not self._topics[dest]:
# This won't trigger RuntimeError, since we're using keys()
del self._topics[dest] | Removes a subscriber connection.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection} | entailment |
def send(self, message):
"""
Sends a message to all subscribers of destination.
@param message: The message frame. (The frame will be modified to set command
to MESSAGE and set a message id.)
@type message: L{stompclient.frame.Frame}
"""
dest = message.headers.get('destination')
if not dest:
raise ValueError(
"Cannot send frame with no destination: %s" % message)
message.cmd = 'message'
message.headers.setdefault('message-id', str(uuid.uuid4()))
bad_subscribers = set()
for subscriber in self._topics[dest]:
try:
subscriber.send_frame(message)
except:
self.log.exception(
"Error delivering message to subscriber %s; client will be disconnected." % subscriber)
# We queue for deletion so we are not modifying the topics dict
# while iterating over it.
bad_subscribers.add(subscriber)
for subscriber in bad_subscribers:
self.disconnect(subscriber) | Sends a message to all subscribers of destination.
@param message: The message frame. (The frame will be modified to set command
to MESSAGE and set a message id.)
@type message: L{stompclient.frame.Frame} | entailment |
def unbind(self):
"""
Unbinds this connection from queue and topic managers (freeing up resources)
and resets state.
"""
self.connected = False
self.queue_manager.disconnect(self.connection)
self.topic_manager.disconnect(self.connection) | Unbinds this connection from queue and topic managers (freeing up resources)
and resets state. | entailment |
def close(self):
"""
Closes all resources/backends associated with this queue manager.
"""
self.log.info("Shutting down queue manager.")
if hasattr(self.store, 'close'):
self.store.close()
if hasattr(self.subscriber_scheduler, 'close'):
self.subscriber_scheduler.close()
if hasattr(self.queue_scheduler, 'close'):
self.queue_scheduler.close() | Closes all resources/backends associated with this queue manager. | entailment |
def subscriber_count(self, destination=None):
"""
Returns a count of the number of subscribers.
If destination is specified then it only returns count of subscribers
for that specific destination.
@param destination: The optional topic/queue destination (e.g. '/queue/foo')
@type destination: C{str}
"""
if destination:
return len(self._queues[destination])
else:
# total them up
total = 0
for k in self._queues.keys():
total += len(self._queues[k])
return total | Returns a count of the number of subscribers.
If destination is specified then it only returns count of subscribers
for that specific destination.
@param destination: The optional topic/queue destination (e.g. '/queue/foo')
@type destination: C{str} | entailment |
def subscribe(self, connection, destination):
"""
Subscribes a connection to the specified destination (topic or queue).
@param connection: The connection to subscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic/queue destination (e.g. '/queue/foo')
@type destination: C{str}
"""
self.log.debug("Subscribing %s to %s" % (connection, destination))
self._queues[destination].add(connection)
self._send_backlog(connection, destination) | Subscribes a connection to the specified destination (topic or queue).
@param connection: The connection to subscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic/queue destination (e.g. '/queue/foo')
@type destination: C{str} | entailment |
def unsubscribe(self, connection, destination):
"""
Unsubscribes a connection from a destination (topic or queue).
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic/queue destination (e.g. '/queue/foo')
@type destination: C{str}
"""
self.log.debug("Unsubscribing %s from %s" % (connection, destination))
if connection in self._queues[destination]:
self._queues[destination].remove(connection)
if not self._queues[destination]:
del self._queues[destination] | Unsubscribes a connection from a destination (topic or queue).
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic/queue destination (e.g. '/queue/foo')
@type destination: C{str} | entailment |
def disconnect(self, connection):
"""
Removes a subscriber connection, ensuring that any pending commands get requeued.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
"""
self.log.debug("Disconnecting %s" % connection)
if connection in self._pending:
pending_frame = self._pending[connection]
self.store.requeue(pending_frame.headers.get(
'destination'), pending_frame)
del self._pending[connection]
for dest in list(self._queues.keys()):
if connection in self._queues[dest]:
self._queues[dest].remove(connection)
if not self._queues[dest]:
# This won't trigger RuntimeError, since we're using keys()
del self._queues[dest] | Removes a subscriber connection, ensuring that any pending commands get requeued.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection} | entailment |
def send(self, message):
"""
Sends a MESSAGE frame to an eligible subscriber connection.
Note that this method will modify the incoming message object to
add a message-id header (if not present) and to change the command
to 'MESSAGE' (if it is not).
@param message: The message frame.
@type message: C{stompclient.frame.Frame}
"""
dest = message.headers.get('destination')
if not dest:
raise ValueError(
"Cannot send frame with no destination: %s" % message)
message.cmd = 'message'
message.headers.setdefault('message-id', str(uuid.uuid4()))
# Grab all subscribers for this destination that do not have pending
# frames
subscribers = [s for s in self._queues[dest]
if s not in self._pending]
if not subscribers:
self.log.debug(
"No eligible subscribers; adding message %s to queue %s" % (message, dest))
self.store.enqueue(dest, message)
else:
selected = self.subscriber_scheduler.choice(subscribers, message)
self.log.debug("Delivering message %s to subscriber %s" %
(message, selected))
self._send_frame(selected, message) | Sends a MESSAGE frame to an eligible subscriber connection.
Note that this method will modify the incoming message object to
add a message-id header (if not present) and to change the command
to 'MESSAGE' (if it is not).
@param message: The message frame.
@type message: C{stompclient.frame.Frame} | entailment |
def ack(self, connection, frame, transaction=None):
"""
Acknowledge receipt of a message.
If the `transaction` parameter is non-null, the frame being ack'd
will be queued so that it can be requeued if the transaction
is rolled back.
@param connection: The connection that is acknowledging the frame.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame being acknowledged.
"""
self.log.debug("ACK %s for %s" % (frame, connection))
if connection in self._pending:
pending_frame = self._pending[connection]
# Make sure that the frame being acknowledged matches
# the expected frame
if pending_frame.headers.get('message-id') != frame.headers.get('message-id'):
self.log.warning(
"Got a ACK for unexpected message-id: %s" % frame.message_id)
self.store.requeue(pending_frame.destination, pending_frame)
# (The pending frame will be removed further down)
if transaction is not None:
self._transaction_frames[connection][
transaction].append(pending_frame)
del self._pending[connection]
self._send_backlog(connection)
else:
self.log.debug("No pending messages for %s" % connection) | Acknowledge receipt of a message.
If the `transaction` parameter is non-null, the frame being ack'd
will be queued so that it can be requeued if the transaction
is rolled back.
@param connection: The connection that is acknowledging the frame.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame being acknowledged. | entailment |
def resend_transaction_frames(self, connection, transaction):
"""
Resend the messages that were ACK'd in specified transaction.
This is called by the engine when there is an abort command.
@param connection: The client connection that aborted the transaction.
@type connection: L{coilmq.server.StompConnection}
@param transaction: The transaction id (which was aborted).
@type transaction: C{str}
"""
for frame in self._transaction_frames[connection][transaction]:
self.send(frame) | Resend the messages that were ACK'd in specified transaction.
This is called by the engine when there is an abort command.
@param connection: The client connection that aborted the transaction.
@type connection: L{coilmq.server.StompConnection}
@param transaction: The transaction id (which was aborted).
@type transaction: C{str} | entailment |
def _send_backlog(self, connection, destination=None):
"""
Sends any queued-up messages for the (optionally) specified destination to connection.
If the destination is not provided, a destination is chosen using the
L{QueueManager.queue_scheduler} scheduler algorithm.
(This method assumes it is being called from within a lock-guarded public
method.)
@param connection: The client connection.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic/queue destination (e.g. '/queue/foo')
@type destination: C{str}
@raise Exception: if the underlying connection object raises an error, the message
will be re-queued and the error will be re-raised.
"""
if destination is None:
# Find all destinations that have frames and that contain this
# connection (subscriber).
eligible_queues = dict([(dest, q) for (dest, q) in self._queues.items()
if connection in q and self.store.has_frames(dest)])
destination = self.queue_scheduler.choice(
eligible_queues, connection)
if destination is None:
self.log.debug(
"No eligible queues (with frames) for subscriber %s" % connection)
return
self.log.debug("Sending backlog to %s for destination %s" %
(connection, destination))
if connection.reliable_subscriber:
# only send one message (waiting for ack)
frame = self.store.dequeue(destination)
if frame:
try:
self._send_frame(connection, frame)
except Exception as x:
self.log.error(
"Error sending message %s (requeueing): %s" % (frame, x))
self.store.requeue(destination, frame)
raise
else:
for frame in self.store.frames(destination):
try:
self._send_frame(connection, frame)
except Exception as x:
self.log.error(
"Error sending message %s (requeueing): %s" % (frame, x))
self.store.requeue(destination, frame)
raise | Sends any queued-up messages for the (optionally) specified destination to connection.
If the destination is not provided, a destination is chosen using the
L{QueueManager.queue_scheduler} scheduler algorithm.
(This method assumes it is being called from within a lock-guarded public
method.)
@param connection: The client connection.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic/queue destination (e.g. '/queue/foo')
@type destination: C{str}
@raise Exception: if the underlying connection object raises an error, the message
will be re-queued and the error will be re-raised. | entailment |
def _send_frame(self, connection, frame):
"""
Sends a frame to a specific subscriber connection.
(This method assumes it is being called from within a lock-guarded public
method.)
@param connection: The subscriber connection object to send to.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame to send.
@type frame: L{stompclient.frame.Frame}
"""
assert connection is not None
assert frame is not None
self.log.debug("Delivering frame %s to connection %s" %
(frame, connection))
if connection.reliable_subscriber:
if connection in self._pending:
raise RuntimeError("Connection already has a pending frame.")
self.log.debug(
"Tracking frame %s as pending for connection %s" % (frame, connection))
self._pending[connection] = frame
connection.send_frame(frame) | Sends a frame to a specific subscriber connection.
(This method assumes it is being called from within a lock-guarded public
method.)
@param connection: The subscriber connection object to send to.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame to send.
@type frame: L{stompclient.frame.Frame} | entailment |
def make_dbm():
"""
Creates a DBM queue store, pulling config values from the CoilMQ configuration.
"""
try:
data_dir = config.get('coilmq', 'qstore.dbm.data_dir')
cp_ops = config.getint('coilmq', 'qstore.dbm.checkpoint_operations')
cp_timeout = config.getint('coilmq', 'qstore.dbm.checkpoint_timeout')
except ConfigParser.NoOptionError as e:
raise ConfigError('Missing configuration parameter: %s' % e)
if not os.path.exists(data_dir):
raise ConfigError('DBM directory does not exist: %s' % data_dir)
# FIXME: how do these get applied? Is OR appropriate?
if not os.access(data_dir, os.W_OK | os.R_OK):
raise ConfigError('Cannot read and write DBM directory: %s' % data_dir)
store = DbmQueue(data_dir, checkpoint_operations=cp_ops,
checkpoint_timeout=cp_timeout)
return store | Creates a DBM queue store, pulling config values from the CoilMQ configuration. | entailment |
def enqueue(self, destination, frame):
"""
Store message (frame) for specified destinationination.
@param destination: The destinationination queue name for this message (frame).
@type destination: C{str}
@param frame: The message (frame) to send to specified destinationination.
@type frame: C{stompclient.frame.Frame}
"""
message_id = frame.headers.get('message-id')
if not message_id:
raise ValueError("Cannot queue a frame without message-id set.")
if not destination in self.queue_metadata:
self.log.info(
"Destination %s not in metadata; creating new entry and queue database." % destination)
self.queue_metadata[destination] = {
'frames': deque(), 'enqueued': 0, 'dequeued': 0, 'size': 0}
self.queue_metadata[destination]['frames'].appendleft(message_id)
self.queue_metadata[destination]['enqueued'] += 1
self.frame_store[message_id] = frame
self._opcount += 1
self._sync() | Store message (frame) for specified destinationination.
@param destination: The destinationination queue name for this message (frame).
@type destination: C{str}
@param frame: The message (frame) to send to specified destinationination.
@type frame: C{stompclient.frame.Frame} | entailment |
def dequeue(self, destination):
"""
Removes and returns an item from the queue (or C{None} if no items in queue).
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: The first frame in the specified queue, or C{None} if there are none.
@rtype: C{stompclient.frame.Frame}
"""
if not self.has_frames(destination):
return None
message_id = self.queue_metadata[destination]['frames'].pop()
self.queue_metadata[destination]['dequeued'] += 1
frame = self.frame_store[message_id]
del self.frame_store[message_id]
self._opcount += 1
self._sync()
return frame | Removes and returns an item from the queue (or C{None} if no items in queue).
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: The first frame in the specified queue, or C{None} if there are none.
@rtype: C{stompclient.frame.Frame} | entailment |
def has_frames(self, destination):
"""
Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool}
"""
return (destination in self.queue_metadata) and bool(self.queue_metadata[destination]['frames']) | Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool} | entailment |
def size(self, destination):
"""
Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int}
"""
if not destination in self.queue_metadata:
return 0
else:
return len(self.queue_metadata[destination]['frames']) | Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int} | entailment |
def _sync(self):
"""
Synchronize the cached data with the underlyind database.
Uses an internal transaction counter and compares to the checkpoint_operations
and checkpoint_timeout paramters to determine whether to persist the memory store.
In this implementation, this method wraps calls to C{shelve.Shelf#sync}.
"""
if (self._opcount > self.checkpoint_operations or
datetime.now() > self._last_sync + self.checkpoint_timeout):
self.log.debug("Synchronizing queue metadata.")
self.queue_metadata.sync()
self._last_sync = datetime.now()
self._opcount = 0
else:
self.log.debug("NOT synchronizing queue metadata.") | Synchronize the cached data with the underlyind database.
Uses an internal transaction counter and compares to the checkpoint_operations
and checkpoint_timeout paramters to determine whether to persist the memory store.
In this implementation, this method wraps calls to C{shelve.Shelf#sync}. | entailment |
def read(config_values):
"""Reads an ordered list of configuration values and deep merge the values in reverse order."""
if not config_values:
raise RheaError('Cannot read config_value: `{}`'.format(config_values))
config_values = to_list(config_values)
config = {}
for config_value in config_values:
config_value = ConfigSpec.get_from(value=config_value)
config_value.check_type()
config_results = config_value.read()
if config_results and isinstance(config_results, Mapping):
config = deep_update(config, config_results)
elif config_value.check_if_exists:
raise RheaError('Cannot read config_value: `{}`'.format(config_value))
return config | Reads an ordered list of configuration values and deep merge the values in reverse order. | entailment |
def parse_headers(buff):
"""
Parses buffer and returns command and headers as strings
"""
preamble_lines = list(map(
lambda x: six.u(x).decode(),
iter(lambda: buff.readline().strip(), b''))
)
if not preamble_lines:
raise EmptyBuffer()
return preamble_lines[0], OrderedDict([l.split(':') for l in preamble_lines[1:]]) | Parses buffer and returns command and headers as strings | entailment |
def pack(self):
"""
Create a string representation from object state.
@return: The string (bytes) for this stomp frame.
@rtype: C{str}
"""
self.headers.setdefault('content-length', len(self.body))
# Convert and append any existing headers to a string as the
# protocol describes.
headerparts = ("{0}:{1}\n".format(key, value)
for key, value in self.headers.items())
# Frame is Command + Header + EOF marker.
return six.b("{0}\n{1}\n".format(self.cmd, "".join(headerparts))) + (self.body if isinstance(self.body, six.binary_type) else six.b(self.body)) + six.b('\x00') | Create a string representation from object state.
@return: The string (bytes) for this stomp frame.
@rtype: C{str} | entailment |
def extract_frame(self):
"""
Pulls one complete frame off the buffer and returns it.
If there is no complete message in the buffer, returns None.
Note that the buffer can contain more than once message. You
should therefore call this method in a loop (or use iterator
functionality exposed by class) until None returned.
@return: The next complete frame in the buffer.
@rtype: L{stomp.frame.Frame}
"""
# (mbytes, hbytes) = self._find_message_bytes(self.buffer)
# if not mbytes:
# return None
#
# msgdata = self.buffer[:mbytes]
# self.buffer = self.buffer[mbytes:]
# hdata = msgdata[:hbytes]
# # Strip off any leading whitespace from headers; this is necessary, because
# # we do not (any longer) expect a trailing \n after the \x00 byte (which means
# # it will become a leading \n to the next frame).
# hdata = hdata.lstrip()
# elems = hdata.split('\n')
# cmd = elems.pop(0)
# headers = {}
#
# for e in elems:
# try:
# (k,v) = e.split(':', 1) # header values may contain ':' so specify maxsplit
# except ValueError:
# continue
# headers[k.strip()] = v.strip()
#
# # hbytes points to the start of the '\n\n' at the end of the header,
# # so 2 bytes beyond this is the start of the body. The body EXCLUDES
# # the final byte, which is '\x00'.
# body = msgdata[hbytes + 2:-1]
self._buffer.seek(self._pointer, 0)
try:
f = Frame.from_buffer(self._buffer)
self._pointer = self._buffer.tell()
except (IncompleteFrame, EmptyBuffer):
self._buffer.seek(self._pointer, 0)
return None
return f | Pulls one complete frame off the buffer and returns it.
If there is no complete message in the buffer, returns None.
Note that the buffer can contain more than once message. You
should therefore call this method in a loop (or use iterator
functionality exposed by class) until None returned.
@return: The next complete frame in the buffer.
@rtype: L{stomp.frame.Frame} | entailment |
def choice(self, subscribers, message):
"""
Choose a random connection, favoring those that are reliable from
subscriber pool to deliver specified message.
@param subscribers: Collection of subscribed connections to destination.
@type subscribers: C{list} of L{coilmq.server.StompConnection}
@param message: The message to be delivered.
@type message: L{stompclient.frame.Frame}
@return: A random subscriber from the list or None if list is empty.
@rtype: L{coilmq.server.StompConnection}
"""
if not subscribers:
return None
reliable_subscribers = [
s for s in subscribers if s.reliable_subscriber]
if reliable_subscribers:
return random.choice(reliable_subscribers)
else:
return random.choice(subscribers) | Choose a random connection, favoring those that are reliable from
subscriber pool to deliver specified message.
@param subscribers: Collection of subscribed connections to destination.
@type subscribers: C{list} of L{coilmq.server.StompConnection}
@param message: The message to be delivered.
@type message: L{stompclient.frame.Frame}
@return: A random subscriber from the list or None if list is empty.
@rtype: L{coilmq.server.StompConnection} | entailment |
def choice(self, queues, connection):
"""
Chooses a random queue for messages to specified connection.
@param queues: A C{dict} mapping queue name to queues (sets of frames) to which
specified connection is subscribed.
@type queues: C{dict} of C{str} to C{set} of L{stompclient.frame.Frame}
@param connection: The connection that is going to be delivered the frame(s).
@type connection: L{coilmq.server.StompConnection}
@return: A random queue destination or None if list is empty.
@rtype: C{str}
"""
if not queues:
return None
return random.choice(list(queues.keys())) | Chooses a random queue for messages to specified connection.
@param queues: A C{dict} mapping queue name to queues (sets of frames) to which
specified connection is subscribed.
@type queues: C{dict} of C{str} to C{set} of L{stompclient.frame.Frame}
@param connection: The connection that is going to be delivered the frame(s).
@type connection: L{coilmq.server.StompConnection}
@return: A random queue destination or None if list is empty.
@rtype: C{str} | entailment |
def get_int(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `int`/`list(int)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`int`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=int,
type_convert=int,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=int,
type_convert=int,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | Get a the value corresponding to the key and converts it to `int`/`list(int)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`int`: value corresponding to the key. | entailment |
def get_float(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `float`/`list(float)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`float`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=float,
type_convert=float,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=float,
type_convert=float,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | Get a the value corresponding to the key and converts it to `float`/`list(float)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`float`: value corresponding to the key. | entailment |
def get_boolean(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `bool`/`list(str)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`bool`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=bool,
type_convert=lambda x: bool(strtobool(x)),
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=bool,
type_convert=lambda x: bool(strtobool(x)),
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | Get a the value corresponding to the key and converts it to `bool`/`list(str)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`bool`: value corresponding to the key. | entailment |
def get_string(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `str`/`list(str)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=str,
type_convert=str,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=str,
type_convert=str,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | Get a the value corresponding to the key and converts it to `str`/`list(str)`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | entailment |
def get_dict(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `dict`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
def convert_to_dict(x):
x = json.loads(x)
if not isinstance(x, Mapping):
raise RheaError("Cannot convert value `{}` (key: `{}`) to `dict`".format(x, key))
return x
if is_list:
return self._get_typed_list_value(key=key,
target_type=Mapping,
type_convert=convert_to_dict,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
value = self._get_typed_value(key=key,
target_type=Mapping,
type_convert=convert_to_dict,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
if not value:
return default
if not isinstance(value, Mapping):
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `dict`".format(value, key))
return value | Get a the value corresponding to the key and converts it to `dict`.
Args:
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | entailment |
def get_dict_of_dicts(self,
key,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `dict`.
Add an extra validation that all keys have a dict as values.
Args:
key: the dict key.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
value = self.get_dict(
key=key,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options,
)
if not value:
return default
for k in value:
if not isinstance(value[k], Mapping):
raise RheaError(
"`{}` must be an object. "
"Received a non valid configuration for key `{}`.".format(value[k], key))
return value | Get a the value corresponding to the key and converts it to `dict`.
Add an extra validation that all keys have a dict as values.
Args:
key: the dict key.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | entailment |
def get_uri(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | entailment |
def get_auth(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `AuthSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=AuthSpec,
type_convert=self.parse_auth_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=AuthSpec,
type_convert=self.parse_auth_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | Get a the value corresponding to the key and converts it to `AuthSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | entailment |
def get_list(self,
key,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts comma separated values to a list.
Args:
key: the dict key.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
def parse_list(v):
parts = v.split(',')
results = []
for part in parts:
part = part.strip()
if part:
results.append(part)
return results
return self._get_typed_value(key=key,
target_type=list,
type_convert=parse_list,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | Get a the value corresponding to the key and converts comma separated values to a list.
Args:
key: the dict key.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | entailment |
def _get_typed_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Return the value corresponding to the key converted to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
The corresponding value of the key converted.
"""
try:
value = self._get(key)
except KeyError:
if not is_optional:
raise RheaError(
'No value was provided for the non optional key `{}`.'.format(key))
return default
if isinstance(value, six.string_types):
try:
self._add_key(key, is_secret=is_secret, is_local=is_local)
self._check_options(key=key, value=value, options=options)
return type_convert(value)
except ValueError:
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `{}`".format(value, key, target_type))
if isinstance(value, target_type):
self._add_key(key, is_secret=is_secret, is_local=is_local)
self._check_options(key=key, value=value, options=options)
return value
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `{}`".format(value, key, target_type)) | Return the value corresponding to the key converted to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
The corresponding value of the key converted. | entailment |
def _get_typed_list_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Return the value corresponding to the key converted first to list
than each element to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
"""
value = self._get_typed_value(key=key,
target_type=list,
type_convert=json.loads,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
if not value:
return default
raise_type = 'dict' if target_type == Mapping else target_type
if not isinstance(value, list):
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `{}`".format(value, key, raise_type))
# If we are here the value must be a list
result = []
for v in value:
if isinstance(v, six.string_types):
try:
result.append(type_convert(v))
except ValueError:
raise RheaError("Cannot convert value `{}` (found in list key: `{}`) "
"to `{}`".format(v, key, raise_type))
elif isinstance(v, target_type):
result.append(v)
else:
raise RheaError("Cannot convert value `{}` (found in list key: `{}`) "
"to `{}`".format(v, key, raise_type))
return result | Return the value corresponding to the key converted first to list
than each element to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values. | entailment |
def make_simple():
"""
Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error.
"""
authfile = config.get('coilmq', 'auth.simple.file')
if not authfile:
raise ConfigError('Missing configuration parameter: auth.simple.file')
sa = SimpleAuthenticator()
sa.from_configfile(authfile)
return sa | Create a L{SimpleAuthenticator} instance using values read from coilmq configuration.
@return: The configured L{SimpleAuthenticator}
@rtype: L{SimpleAuthenticator}
@raise ConfigError: If there is a configuration error. | entailment |
def from_configfile(self, configfile):
"""
Initialize the authentication store from a "config"-style file.
Auth "config" file is parsed with C{ConfigParser.RawConfigParser} and must contain
an [auth] section which contains the usernames (keys) and passwords (values).
Example auth file::
[auth]
someuser = somepass
anotheruser = anotherpass
@param configfile: Path to config file or file-like object.
@type configfile: C{any}
@raise ValueError: If file could not be read or does not contain [auth] section.
"""
cfg = ConfigParser()
if hasattr(configfile, 'read'):
cfg.read_file(configfile)
else:
filesread = cfg.read(configfile)
if not filesread:
raise ValueError('Could not parse auth file: %s' % configfile)
if not cfg.has_section('auth'):
raise ValueError('Config file contains no [auth] section.')
self.store = dict(cfg.items('auth')) | Initialize the authentication store from a "config"-style file.
Auth "config" file is parsed with C{ConfigParser.RawConfigParser} and must contain
an [auth] section which contains the usernames (keys) and passwords (values).
Example auth file::
[auth]
someuser = somepass
anotheruser = anotherpass
@param configfile: Path to config file or file-like object.
@type configfile: C{any}
@raise ValueError: If file could not be read or does not contain [auth] section. | entailment |
def authenticate(self, login, passcode):
"""
Authenticate the login and passcode.
@return: Whether provided login and password match values in store.
@rtype: C{bool}
"""
return login in self.store and self.store[login] == passcode | Authenticate the login and passcode.
@return: Whether provided login and password match values in store.
@rtype: C{bool} | entailment |
def process_frame(self, frame):
"""
Dispatches a received frame to the appropriate internal method.
@param frame: The frame that was received.
@type frame: C{stompclient.frame.Frame}
"""
cmd_method = frame.cmd.lower()
if not cmd_method in VALID_COMMANDS:
raise ProtocolError("Invalid STOMP command: {}".format(frame.cmd))
method = getattr(self, cmd_method, None)
if not self.engine.connected and method not in (self.connect, self.stomp):
raise ProtocolError("Not connected.")
try:
transaction = frame.headers.get('transaction')
if not transaction or method in (self.begin, self.commit, self.abort):
method(frame)
else:
if not transaction in self.engine.transactions:
raise ProtocolError(
"Invalid transaction specified: %s" % transaction)
self.engine.transactions[transaction].append(frame)
except Exception as e:
self.engine.log.error("Error processing STOMP frame: %s" % e)
self.engine.log.exception(e)
try:
self.engine.connection.send_frame(ErrorFrame(str(e), str(e)))
except Exception as e: # pragma: no cover
self.engine.log.error("Could not send error frame: %s" % e)
self.engine.log.exception(e)
else:
# The protocol is not especially clear here (not sure why I'm surprised)
# about the expected behavior WRT receipts and errors. We will assume that
# the RECEIPT frame should not be sent if there is an error frame.
# Also we'll assume that a transaction should not preclude sending the receipt
# frame.
# import pdb; pdb.set_trace()
if frame.headers.get('receipt') and method != self.connect:
self.engine.connection.send_frame(ReceiptFrame(
receipt=frame.headers.get('receipt'))) | Dispatches a received frame to the appropriate internal method.
@param frame: The frame that was received.
@type frame: C{stompclient.frame.Frame} | entailment |
def connect(self, frame, response=None):
"""
Handle CONNECT command: Establishes a new connection and checks auth (if applicable).
"""
self.engine.log.debug("CONNECT")
if self.engine.authenticator:
login = frame.headers.get('login')
passcode = frame.headers.get('passcode')
if not self.engine.authenticator.authenticate(login, passcode):
raise AuthError("Authentication failed for %s" % login)
self.engine.connected = True
response = response or Frame(frames.CONNECTED)
response.headers['session'] = uuid.uuid4()
# TODO: Do we want to do anything special to track sessions?
# (Actually, I don't think the spec actually does anything with this at all.)
self.engine.connection.send_frame(response) | Handle CONNECT command: Establishes a new connection and checks auth (if applicable). | entailment |
def send(self, frame):
"""
Handle the SEND command: Delivers a message to a queue or topic (default).
"""
dest = frame.headers.get('destination')
if not dest:
raise ProtocolError('Missing destination for SEND command.')
if dest.startswith('/queue/'):
self.engine.queue_manager.send(frame)
else:
self.engine.topic_manager.send(frame) | Handle the SEND command: Delivers a message to a queue or topic (default). | entailment |
def subscribe(self, frame):
"""
Handle the SUBSCRIBE command: Adds this connection to destination.
"""
ack = frame.headers.get('ack')
reliable = ack and ack.lower() == 'client'
self.engine.connection.reliable_subscriber = reliable
dest = frame.headers.get('destination')
if not dest:
raise ProtocolError('Missing destination for SUBSCRIBE command.')
if dest.startswith('/queue/'):
self.engine.queue_manager.subscribe(self.engine.connection, dest)
else:
self.engine.topic_manager.subscribe(self.engine.connection, dest) | Handle the SUBSCRIBE command: Adds this connection to destination. | entailment |
def unsubscribe(self, frame):
"""
Handle the UNSUBSCRIBE command: Removes this connection from destination.
"""
dest = frame.headers.get('destination')
if not dest:
raise ProtocolError('Missing destination for UNSUBSCRIBE command.')
if dest.startswith('/queue/'):
self.engine.queue_manager.unsubscribe(self.engine.connection, dest)
else:
self.engine.topic_manager.unsubscribe(self.engine.connection, dest) | Handle the UNSUBSCRIBE command: Removes this connection from destination. | entailment |
def begin(self, frame):
"""
Handles BEGING command: Starts a new transaction.
"""
if not frame.transaction:
raise ProtocolError("Missing transaction for BEGIN command.")
self.engine.transactions[frame.transaction] = [] | Handles BEGING command: Starts a new transaction. | entailment |
def commit(self, frame):
"""
Handles COMMIT command: Commits specified transaction.
"""
if not frame.transaction:
raise ProtocolError("Missing transaction for COMMIT command.")
if not frame.transaction in self.engine.transactions:
raise ProtocolError("Invalid transaction: %s" % frame.transaction)
for tframe in self.engine.transactions[frame.transaction]:
del tframe.headers['transaction']
self.process_frame(tframe)
self.engine.queue_manager.clear_transaction_frames(
self.engine.connection, frame.transaction)
del self.engine.transactions[frame.transaction] | Handles COMMIT command: Commits specified transaction. | entailment |
def abort(self, frame):
"""
Handles ABORT command: Rolls back specified transaction.
"""
if not frame.transaction:
raise ProtocolError("Missing transaction for ABORT command.")
if not frame.transaction in self.engine.transactions:
raise ProtocolError("Invalid transaction: %s" % frame.transaction)
self.engine.queue_manager.resend_transaction_frames(
self.engine.connection, frame.transaction)
del self.engine.transactions[frame.transaction] | Handles ABORT command: Rolls back specified transaction. | entailment |
def ack(self, frame):
"""
Handles the ACK command: Acknowledges receipt of a message.
"""
if not frame.message_id:
raise ProtocolError("No message-id specified for ACK command.")
self.engine.queue_manager.ack(self.engine.connection, frame) | Handles the ACK command: Acknowledges receipt of a message. | entailment |
def disconnect(self, frame):
"""
Handles the DISCONNECT command: Unbinds the connection.
Clients are supposed to send this command, but in practice it should not be
relied upon.
"""
self.engine.log.debug("Disconnect")
self.engine.unbind() | Handles the DISCONNECT command: Unbinds the connection.
Clients are supposed to send this command, but in practice it should not be
relied upon. | entailment |
def nack(self, frame):
"""
Handles the NACK command: Unacknowledges receipt of a message.
For now, this is just a placeholder to implement this version of the protocol
"""
if not frame.headers.get('message-id'):
raise ProtocolError("No message-id specified for NACK command.")
if not frame.headers.get('subscription'):
raise ProtocolError("No subscription specified for NACK command.") | Handles the NACK command: Unacknowledges receipt of a message.
For now, this is just a placeholder to implement this version of the protocol | entailment |
def init_config(config_file=None):
"""
Initialize the configuration from a config file.
The values in config_file will override those already loaded from the default
configuration file (defaults.cfg, in current package).
This method does not setup logging.
@param config_file: The path to a configuration file.
@type config_file: C{str}
@raise ValueError: if the specified config_file could not be read.
@see: L{init_logging}
"""
global config
if config_file and os.path.exists(config_file):
read = config.read([config_file])
if not read:
raise ValueError(
"Could not read configuration from file: %s" % config_file) | Initialize the configuration from a config file.
The values in config_file will override those already loaded from the default
configuration file (defaults.cfg, in current package).
This method does not setup logging.
@param config_file: The path to a configuration file.
@type config_file: C{str}
@raise ValueError: if the specified config_file could not be read.
@see: L{init_logging} | entailment |
def init_logging(logfile=None, loglevel=logging.INFO, configfile=None):
"""
Configures the logging using either basic filename + loglevel or passed config file path.
This is performed separately from L{init_config()} in order to support the case where
logging should happen independent of (usu. *after*) other aspects of the configuration
initialization. For example, if logging may need to be initialized within a daemon
context.
@param logfile: An explicitly specified logfile destination. If this is specified in addition
to default logging, a warning will be issued.
@type logfile: C{str}
@param loglevel: Which level to use when logging to explicitly specified file or stdout.
@type loglevel: C{int}
@param configfile: The path to a configuration file. This takes precedence over any explicitly
specified logfile/loglevel (but a warning will be logged if both are specified).
If the file is not specified or does not exist annd no logfile was specified,
then the default.cfg configuration file will be used to initialize logging.
@type configfile: C{str}
"""
# If a config file was specified, we will use that in place of the
# explicitly
use_configfile = False
if configfile and os.path.exists(configfile):
testcfg = ConfigParser()
read = testcfg.read(configfile)
use_configfile = (read and testcfg.has_section('loggers'))
if use_configfile:
logging.config.fileConfig(configfile)
if logfile:
msg = "Config file conflicts with explicitly specified logfile; config file takes precedence."
logging.warn(msg)
else:
format = '%(asctime)s [%(threadName)s] %(name)s - %(levelname)s - %(message)s'
if logfile:
logging.basicConfig(
filename=logfile, level=loglevel, format=format)
else:
logging.basicConfig(level=loglevel, format=format) | Configures the logging using either basic filename + loglevel or passed config file path.
This is performed separately from L{init_config()} in order to support the case where
logging should happen independent of (usu. *after*) other aspects of the configuration
initialization. For example, if logging may need to be initialized within a daemon
context.
@param logfile: An explicitly specified logfile destination. If this is specified in addition
to default logging, a warning will be issued.
@type logfile: C{str}
@param loglevel: Which level to use when logging to explicitly specified file or stdout.
@type loglevel: C{int}
@param configfile: The path to a configuration file. This takes precedence over any explicitly
specified logfile/loglevel (but a warning will be logged if both are specified).
If the file is not specified or does not exist annd no logfile was specified,
then the default.cfg configuration file will be used to initialize logging.
@type configfile: C{str} | entailment |
def resolve_name(name):
"""
Resolve a dotted name to some object (usually class, module, or function).
Supported naming formats include:
1. path.to.module:method
2. path.to.module.ClassName
>>> resolve_name('coilmq.store.memory.MemoryQueue')
<class 'coilmq.store.memory.MemoryQueue'>
>>> t = resolve_name('coilmq.store.dbm.make_dbm')
>>> import inspect
>>> inspect.isfunction(t)
True
>>> t.__name__
'make_dbm'
@param name: The dotted name (e.g. path.to.MyClass)
@type name: C{str}
@return: The resolved object (class, callable, etc.) or None if not found.
"""
if ':' in name:
# Normalize foo.bar.baz:main to foo.bar.baz.main
# (since our logic below will handle that)
name = '%s.%s' % tuple(name.split(':'))
name = name.split('.')
used = name.pop(0)
found = __import__(used)
for n in name:
used = used + '.' + n
try:
found = getattr(found, n)
except AttributeError:
__import__(used)
found = getattr(found, n)
return found | Resolve a dotted name to some object (usually class, module, or function).
Supported naming formats include:
1. path.to.module:method
2. path.to.module.ClassName
>>> resolve_name('coilmq.store.memory.MemoryQueue')
<class 'coilmq.store.memory.MemoryQueue'>
>>> t = resolve_name('coilmq.store.dbm.make_dbm')
>>> import inspect
>>> inspect.isfunction(t)
True
>>> t.__name__
'make_dbm'
@param name: The dotted name (e.g. path.to.MyClass)
@type name: C{str}
@return: The resolved object (class, callable, etc.) or None if not found. | entailment |
def handle(self):
"""
Handle a new socket connection.
"""
# self.request is the TCP socket connected to the client
try:
while not self.server._shutdown_request_event.is_set():
try:
data = self.request.recv(8192)
if not data:
break
if self.debug:
self.log.debug("RECV: %r" % data)
self.buffer.append(data)
for frame in self.buffer:
self.log.debug("Processing frame: %s" % frame)
self.engine.process_frame(frame)
if not self.engine.connected:
raise ClientDisconnected()
except socket.timeout: # pragma: no cover
pass
except ClientDisconnected:
self.log.debug("Client disconnected, discontinuing read loop.")
except Exception as e: # pragma: no cover
self.log.error("Error receiving data (unbinding): %s" % e)
self.engine.unbind()
raise | Handle a new socket connection. | entailment |
def send_frame(self, frame):
""" Sends a frame to connected socket client.
@param frame: The frame to send.
@type frame: C{stompclient.frame.Frame}
"""
packed = frame.pack()
if self.debug: # pragma: no cover
self.log.debug("SEND: %r" % packed)
self.request.sendall(packed) | Sends a frame to connected socket client.
@param frame: The frame to send.
@type frame: C{stompclient.frame.Frame} | entailment |
def server_close(self):
"""
Closes the socket server and any associated resources.
"""
self.log.debug("Closing the socket server connection.")
TCPServer.server_close(self)
self.queue_manager.close()
self.topic_manager.close()
if hasattr(self.authenticator, 'close'):
self.authenticator.close()
self.shutdown() | Closes the socket server and any associated resources. | entailment |
def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self._serving_event.set()
self._shutdown_request_event.clear()
TCPServer.serve_forever(self, poll_interval=poll_interval) | Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread. | entailment |
def create_3d_texture(width, scale):
"""Create a grayscale 3d texture map with the specified
pixel width on each side and load it into the current texture
unit. The luminace of each texel is derived using the input
function as:
v = func(x * scale, y * scale, z * scale)
where x, y, z = 0 in the center texel of the texture.
func(x, y, z) is assumed to always return a value in the
range [-1, 1].
"""
coords = range(width)
texel = (ctypes.c_byte * width**3)()
half = 0 #width * scale / 2.0
for z in coords:
for y in coords:
for x in coords:
v = snoise3(x * scale - half, y * scale - half, z * scale - half, octaves=4, persistence=0.25)
texel[x + (y * width) + (z * width**2)] = int(v * 127.0)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE, width, width, width, 0,
GL_LUMINANCE, GL_BYTE, ctypes.byref(texel))
return texel | Create a grayscale 3d texture map with the specified
pixel width on each side and load it into the current texture
unit. The luminace of each texel is derived using the input
function as:
v = func(x * scale, y * scale, z * scale)
where x, y, z = 0 in the center texel of the texture.
func(x, y, z) is assumed to always return a value in the
range [-1, 1]. | entailment |
def randomize(self, period=None):
"""Randomize the permutation table used by the noise functions. This
makes them generate a different noise pattern for the same inputs.
"""
if period is not None:
self.period = period
perm = list(range(self.period))
perm_right = self.period - 1
for i in list(perm):
j = self.randint_function(0, perm_right)
perm[i], perm[j] = perm[j], perm[i]
self.permutation = tuple(perm) * 2 | Randomize the permutation table used by the noise functions. This
makes them generate a different noise pattern for the same inputs. | entailment |
def noise2(self, x, y):
"""2D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y coordinate.
The same value is always returned for a given x, y pair unless the
permutation table changes (see randomize above).
"""
# Skew input space to determine which simplex (triangle) we are in
s = (x + y) * _F2
i = floor(x + s)
j = floor(y + s)
t = (i + j) * _G2
x0 = x - (i - t) # "Unskewed" distances from cell origin
y0 = y - (j - t)
if x0 > y0:
i1 = 1; j1 = 0 # Lower triangle, XY order: (0,0)->(1,0)->(1,1)
else:
i1 = 0; j1 = 1 # Upper triangle, YX order: (0,0)->(0,1)->(1,1)
x1 = x0 - i1 + _G2 # Offsets for middle corner in (x,y) unskewed coords
y1 = y0 - j1 + _G2
x2 = x0 + _G2 * 2.0 - 1.0 # Offsets for last corner in (x,y) unskewed coords
y2 = y0 + _G2 * 2.0 - 1.0
# Determine hashed gradient indices of the three simplex corners
perm = self.permutation
ii = int(i) % self.period
jj = int(j) % self.period
gi0 = perm[ii + perm[jj]] % 12
gi1 = perm[ii + i1 + perm[jj + j1]] % 12
gi2 = perm[ii + 1 + perm[jj + 1]] % 12
# Calculate the contribution from the three corners
tt = 0.5 - x0**2 - y0**2
if tt > 0:
g = _GRAD3[gi0]
noise = tt**4 * (g[0] * x0 + g[1] * y0)
else:
noise = 0.0
tt = 0.5 - x1**2 - y1**2
if tt > 0:
g = _GRAD3[gi1]
noise += tt**4 * (g[0] * x1 + g[1] * y1)
tt = 0.5 - x2**2 - y2**2
if tt > 0:
g = _GRAD3[gi2]
noise += tt**4 * (g[0] * x2 + g[1] * y2)
return noise * 70.0 | 2D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y coordinate.
The same value is always returned for a given x, y pair unless the
permutation table changes (see randomize above). | entailment |
def noise3(self, x, y, z):
"""3D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y, z coordinate.
The same value is always returned for a given x, y, z pair unless the
permutation table changes (see randomize above).
"""
# Skew the input space to determine which simplex cell we're in
s = (x + y + z) * _F3
i = floor(x + s)
j = floor(y + s)
k = floor(z + s)
t = (i + j + k) * _G3
x0 = x - (i - t) # "Unskewed" distances from cell origin
y0 = y - (j - t)
z0 = z - (k - t)
# For the 3D case, the simplex shape is a slightly irregular tetrahedron.
# Determine which simplex we are in.
if x0 >= y0:
if y0 >= z0:
i1 = 1; j1 = 0; k1 = 0
i2 = 1; j2 = 1; k2 = 0
elif x0 >= z0:
i1 = 1; j1 = 0; k1 = 0
i2 = 1; j2 = 0; k2 = 1
else:
i1 = 0; j1 = 0; k1 = 1
i2 = 1; j2 = 0; k2 = 1
else: # x0 < y0
if y0 < z0:
i1 = 0; j1 = 0; k1 = 1
i2 = 0; j2 = 1; k2 = 1
elif x0 < z0:
i1 = 0; j1 = 1; k1 = 0
i2 = 0; j2 = 1; k2 = 1
else:
i1 = 0; j1 = 1; k1 = 0
i2 = 1; j2 = 1; k2 = 0
# Offsets for remaining corners
x1 = x0 - i1 + _G3
y1 = y0 - j1 + _G3
z1 = z0 - k1 + _G3
x2 = x0 - i2 + 2.0 * _G3
y2 = y0 - j2 + 2.0 * _G3
z2 = z0 - k2 + 2.0 * _G3
x3 = x0 - 1.0 + 3.0 * _G3
y3 = y0 - 1.0 + 3.0 * _G3
z3 = z0 - 1.0 + 3.0 * _G3
# Calculate the hashed gradient indices of the four simplex corners
perm = self.permutation
ii = int(i) % self.period
jj = int(j) % self.period
kk = int(k) % self.period
gi0 = perm[ii + perm[jj + perm[kk]]] % 12
gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1]]] % 12
gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2]]] % 12
gi3 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1]]] % 12
# Calculate the contribution from the four corners
noise = 0.0
tt = 0.6 - x0**2 - y0**2 - z0**2
if tt > 0:
g = _GRAD3[gi0]
noise = tt**4 * (g[0] * x0 + g[1] * y0 + g[2] * z0)
else:
noise = 0.0
tt = 0.6 - x1**2 - y1**2 - z1**2
if tt > 0:
g = _GRAD3[gi1]
noise += tt**4 * (g[0] * x1 + g[1] * y1 + g[2] * z1)
tt = 0.6 - x2**2 - y2**2 - z2**2
if tt > 0:
g = _GRAD3[gi2]
noise += tt**4 * (g[0] * x2 + g[1] * y2 + g[2] * z2)
tt = 0.6 - x3**2 - y3**2 - z3**2
if tt > 0:
g = _GRAD3[gi3]
noise += tt**4 * (g[0] * x3 + g[1] * y3 + g[2] * z3)
return noise * 32.0 | 3D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y, z coordinate.
The same value is always returned for a given x, y, z pair unless the
permutation table changes (see randomize above). | entailment |
def noise3(self, x, y, z, repeat, base=0.0):
"""Tileable 3D noise.
repeat specifies the integer interval in each dimension
when the noise pattern repeats.
base allows a different texture to be generated for
the same repeat interval.
"""
i = int(fmod(floor(x), repeat))
j = int(fmod(floor(y), repeat))
k = int(fmod(floor(z), repeat))
ii = (i + 1) % repeat
jj = (j + 1) % repeat
kk = (k + 1) % repeat
if base:
i += base; j += base; k += base
ii += base; jj += base; kk += base
x -= floor(x); y -= floor(y); z -= floor(z)
fx = x**3 * (x * (x * 6 - 15) + 10)
fy = y**3 * (y * (y * 6 - 15) + 10)
fz = z**3 * (z * (z * 6 - 15) + 10)
perm = self.permutation
A = perm[i]
AA = perm[A + j]
AB = perm[A + jj]
B = perm[ii]
BA = perm[B + j]
BB = perm[B + jj]
return lerp(fz, lerp(fy, lerp(fx, grad3(perm[AA + k], x, y, z),
grad3(perm[BA + k], x - 1, y, z)),
lerp(fx, grad3(perm[AB + k], x, y - 1, z),
grad3(perm[BB + k], x - 1, y - 1, z))),
lerp(fy, lerp(fx, grad3(perm[AA + kk], x, y, z - 1),
grad3(perm[BA + kk], x - 1, y, z - 1)),
lerp(fx, grad3(perm[AB + kk], x, y - 1, z - 1),
grad3(perm[BB + kk], x - 1, y - 1, z - 1)))) | Tileable 3D noise.
repeat specifies the integer interval in each dimension
when the noise pattern repeats.
base allows a different texture to be generated for
the same repeat interval. | entailment |
def load(self):
"""Load the noise texture data into the current texture unit"""
glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE16_ALPHA16,
self.width, self.width, self.width, 0, GL_LUMINANCE_ALPHA,
GL_UNSIGNED_SHORT, ctypes.byref(self.data)) | Load the noise texture data into the current texture unit | entailment |
def enable(self):
"""Convenience method to enable 3D texturing state so the texture may be used by the
ffpnoise shader function
"""
glEnable(GL_TEXTURE_3D)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) | Convenience method to enable 3D texturing state so the texture may be used by the
ffpnoise shader function | entailment |
def compute(self, now, x, y, angle):
"""
Call this when vision processing should be enabled
:param now: The value passed to ``update_sim``
:param x: Returned from physics_controller.get_position
:param y: Returned from physics_controller.get_position
:param angle: Returned from physics_controller.get_position
:returns: None or list of tuples of (found=0 or 1, capture_time, offset_degrees, distance).
The tuples are ordered by absolute offset from the
target. If a list is returned, it is guaranteed to have at
least one element in it.
Note: If your vision targeting doesn't have the ability
to focus on multiple targets, then you should ignore
the other elements.
"""
# Normalize angle to [-180,180]
output = []
angle = ((angle + math.pi) % (math.pi * 2)) - math.pi
for target in self.targets:
proposed = target.compute(now, x, y, angle)
if proposed:
output.append(proposed)
if not output:
output.append((0, now, inf, 0))
self.distance = None
else:
# order by absolute offset
output.sort(key=lambda i: abs(i[2]))
self.distance = output[-1][3]
# Only store stuff every once in awhile
if now - self.last_compute_time > self.update_period:
self.last_compute_time = now
self.send_queue.appendleft(output)
# simulate latency by delaying camera output
if self.send_queue:
output = self.send_queue[-1]
if now - output[0][1] > self.data_lag:
return self.send_queue.pop() | Call this when vision processing should be enabled
:param now: The value passed to ``update_sim``
:param x: Returned from physics_controller.get_position
:param y: Returned from physics_controller.get_position
:param angle: Returned from physics_controller.get_position
:returns: None or list of tuples of (found=0 or 1, capture_time, offset_degrees, distance).
The tuples are ordered by absolute offset from the
target. If a list is returned, it is guaranteed to have at
least one element in it.
Note: If your vision targeting doesn't have the ability
to focus on multiple targets, then you should ignore
the other elements. | entailment |
def run_friedman82_super():
"""Run Friedman's test of fixed-span smoothers from Figure 2b."""
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
plt.figure()
smooth = SuperSmoother()
smooth.specify_data_set(x, y, sort_data=True)
smooth.compute()
plt.plot(x, y, '.', label='Data')
plt.plot(smooth.x, smooth.smooth_result, 'o', label='Smooth')
plt.grid(color='0.7')
plt.legend(loc='upper left')
plt.title('Demo of SuperSmoother based on Friedman 82')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('sample_supersmoother_friedman82.png')
return smooth | Run Friedman's test of fixed-span smoothers from Figure 2b. | entailment |
def main():
"""Used for development and testing."""
expr_list = [
"max(-_.千幸福的笑脸{घोड़ा=馬, "
"dn2=dv2,千幸福的笑脸घ=千幸福的笑脸घ}) gte 100 "
"times 3 && "
"(min(ເຮືອນ{dn3=dv3,家=дом}) < 10 or sum(biz{dn5=dv5}) >99 and "
"count(fizzle) lt 0or count(baz) > 1)".decode('utf8'),
"max(foo{hostname=mini-mon,千=千}, 120) > 100 and (max(bar)>100 "
" or max(biz)>100)".decode('utf8'),
"max(foo)>=100",
"test_metric{this=that, that = this} < 1",
"max ( 3test_metric5 { this = that }) lt 5 times 3",
"3test_metric5 lt 3",
"ntp.offset > 1 or ntp.offset < -5",
"max(3test_metric5{it's this=that's it}) lt 5 times 3",
"count(log.error{test=1}, deterministic) > 1.0",
"count(log.error{test=1}, deterministic, 120) > 1.0",
"last(test_metric{hold=here}) < 13",
"count(log.error{test=1}, deterministic, 130) > 1.0",
"count(log.error{test=1}, deterministic) > 1.0 times 0",
]
for expr in expr_list:
print('orig expr: {}'.format(expr.encode('utf8')))
sub_exprs = []
try:
alarm_expr_parser = AlarmExprParser(expr)
sub_exprs = alarm_expr_parser.sub_expr_list
except Exception as ex:
print("Parse failed: {}".format(ex))
for sub_expr in sub_exprs:
print('sub expr: {}'.format(
sub_expr.fmtd_sub_expr_str.encode('utf8')))
print('sub_expr dimensions: {}'.format(
sub_expr.dimensions_str.encode('utf8')))
print('sub_expr deterministic: {}'.format(
sub_expr.deterministic))
print('sub_expr period: {}'.format(
sub_expr.period))
print("")
print("") | Used for development and testing. | entailment |
def fmtd_sub_expr_str(self):
"""Get the entire sub expressions as a string with spaces."""
result = u"{}({}".format(self.normalized_func,
self._metric_name)
if self._dimensions is not None:
result += "{" + self.dimensions_str + "}"
if self._period != _DEFAULT_PERIOD:
result += ", {}".format(self._period)
result += ")"
result += " {} {}".format(self._operator,
self._threshold)
if self._periods != _DEFAULT_PERIODS:
result += " times {}".format(self._periods)
return result | Get the entire sub expressions as a string with spaces. | entailment |
def normalized_operator(self):
"""Get the operator as one of LT, GT, LTE, or GTE."""
if self._operator.lower() == "lt" or self._operator == "<":
return u"LT"
elif self._operator.lower() == "gt" or self._operator == ">":
return u"GT"
elif self._operator.lower() == "lte" or self._operator == "<=":
return u"LTE"
elif self._operator.lower() == "gte" or self._operator == ">=":
return u"GTE" | Get the operator as one of LT, GT, LTE, or GTE. | entailment |
def compute(self, motor_pct: float, tm_diff: float) -> float:
"""
:param motor_pct: Percentage of power for motor in range [1..-1]
:param tm_diff: Time elapsed since this function was last called
:returns: velocity
"""
appliedVoltage = self._nominalVoltage * motor_pct
appliedVoltage = math.copysign(
max(abs(appliedVoltage) - self._vintercept, 0), appliedVoltage
)
# Heun's method (taken from Ether's drivetrain calculator)
# -> yn+1 = yn + (h/2) (f(xn, yn) + f(xn + h, yn + h f(xn, yn)))
a0 = self.acceleration
v0 = self.velocity
# initial estimate for next velocity/acceleration
v1 = v0 + a0 * tm_diff
a1 = (appliedVoltage - self._kv * v1) / self._ka
# corrected trapezoidal estimate
v1 = v0 + (a0 + a1) * 0.5 * tm_diff
a1 = (appliedVoltage - self._kv * v1) / self._ka
self.position += (v0 + v1) * 0.5 * tm_diff
self.velocity = v1
self.acceleration = a1
return self.velocity | :param motor_pct: Percentage of power for motor in range [1..-1]
:param tm_diff: Time elapsed since this function was last called
:returns: velocity | entailment |
def theory(
cls,
motor_config: MotorModelConfig,
robot_mass: units.Quantity,
gearing: float,
nmotors: int = 1,
x_wheelbase: units.Quantity = _kitbot_wheelbase,
robot_width: units.Quantity = _kitbot_width,
robot_length: units.Quantity = _kitbot_length,
wheel_diameter: units.Quantity = 6 * units.inch,
vintercept: units.volts = 1.3 * units.volts,
timestep: int = 5 * units.ms,
):
r"""
Use this to create the drivetrain model when you haven't measured
``kv`` and ``ka`` for your robot.
:param motor_config: Specifications for your motor
:param robot_mass: Mass of the robot
:param gearing: Gear ratio .. so for a 10.74:1 ratio, you would pass 10.74
:param nmotors: Number of motors per side
:param x_wheelbase: Wheelbase of the robot
:param robot_width: Width of the robot
:param robot_length: Length of the robot
:param wheel_diameter: Diameter of the wheel
:param vintercept: The minimum voltage required to generate enough
torque to overcome steady-state friction (see the
paper for more details)
:param timestep_ms: Model computation timestep
Computation of ``kv`` and ``ka`` are done as follows:
* :math:`\omega_{free}` is the free speed of the motor
* :math:`\tau_{stall}` is the stall torque of the motor
* :math:`n` is the number of drive motors
* :math:`m_{robot}` is the mass of the robot
* :math:`d_{wheels}` is the diameter of the robot's wheels
* :math:`r_{gearing}` is the total gear reduction between the motors and the wheels
* :math:`V_{max}` is the nominal max voltage of the motor
.. math::
velocity_{max} = \frac{\omega_{free} \cdot \pi \cdot d_{wheels} }{r_{gearing}}
acceleration_{max} = \frac{2 \cdot n \cdot \tau_{stall} \cdot r_{gearing} }{d_{wheels} \cdot m_{robot}}
k_{v} = \frac{V_{max}}{velocity_{max}}
k_{a} = \frac{V_{max}}{acceleration_{max}}
"""
# Check input units
# -> pint doesn't seem to support default args in check()
Helpers.ensure_mass(robot_mass)
Helpers.ensure_length(x_wheelbase)
Helpers.ensure_length(robot_width)
Helpers.ensure_length(robot_length)
Helpers.ensure_length(wheel_diameter)
max_velocity = (motor_config.freeSpeed * math.pi * wheel_diameter) / gearing
max_acceleration = (2.0 * nmotors * motor_config.stallTorque * gearing) / (
wheel_diameter * robot_mass
)
Helpers.ensure_velocity(max_velocity)
Helpers.ensure_acceleration(max_acceleration)
kv = motor_config.nominalVoltage / max_velocity
ka = motor_config.nominalVoltage / max_acceleration
kv = units.tm_kv.from_(kv, name="kv")
ka = units.tm_ka.from_(ka, name="ka")
logger.info(
"Motor config: %d %s motors @ %.2f gearing with %.1f diameter wheels",
nmotors,
motor_config.name,
gearing,
wheel_diameter.m,
)
logger.info(
"- Theoretical: vmax=%.3f ft/s, amax=%.3f ft/s^2, kv=%.3f, ka=%.3f",
max_velocity.m_as(units.foot / units.second),
max_acceleration.m_as(units.foot / units.second ** 2),
kv.m,
ka.m,
)
return cls(
motor_config,
robot_mass,
x_wheelbase,
robot_width,
robot_length,
kv,
ka,
vintercept,
kv,
ka,
vintercept,
timestep,
) | r"""
Use this to create the drivetrain model when you haven't measured
``kv`` and ``ka`` for your robot.
:param motor_config: Specifications for your motor
:param robot_mass: Mass of the robot
:param gearing: Gear ratio .. so for a 10.74:1 ratio, you would pass 10.74
:param nmotors: Number of motors per side
:param x_wheelbase: Wheelbase of the robot
:param robot_width: Width of the robot
:param robot_length: Length of the robot
:param wheel_diameter: Diameter of the wheel
:param vintercept: The minimum voltage required to generate enough
torque to overcome steady-state friction (see the
paper for more details)
:param timestep_ms: Model computation timestep
Computation of ``kv`` and ``ka`` are done as follows:
* :math:`\omega_{free}` is the free speed of the motor
* :math:`\tau_{stall}` is the stall torque of the motor
* :math:`n` is the number of drive motors
* :math:`m_{robot}` is the mass of the robot
* :math:`d_{wheels}` is the diameter of the robot's wheels
* :math:`r_{gearing}` is the total gear reduction between the motors and the wheels
* :math:`V_{max}` is the nominal max voltage of the motor
.. math::
velocity_{max} = \frac{\omega_{free} \cdot \pi \cdot d_{wheels} }{r_{gearing}}
acceleration_{max} = \frac{2 \cdot n \cdot \tau_{stall} \cdot r_{gearing} }{d_{wheels} \cdot m_{robot}}
k_{v} = \frac{V_{max}}{velocity_{max}}
k_{a} = \frac{V_{max}}{acceleration_{max}} | entailment |
def get_distance(
self, l_motor: float, r_motor: float, tm_diff: float
) -> typing.Tuple[float, float]:
"""
Given motor values and the amount of time elapsed since this was last
called, retrieves the x,y,angle that the robot has moved. Pass these
values to :meth:`PhysicsInterface.distance_drive`.
To update your encoders, use the ``l_position`` and ``r_position``
attributes of this object.
:param l_motor: Left motor value (-1 to 1); -1 is forward
:param r_motor: Right motor value (-1 to 1); 1 is forward
:param tm_diff: Elapsed time since last call to this function
:returns: x travel, y travel, angle turned (radians)
.. note:: If you are using more than 2 motors, it is assumed that
all motors on each side are set to the same speed. Only
pass in one of the values from each side
"""
# This isn't quite right, the right way is to use matrix math. However,
# this is Good Enough for now...
x = 0
y = 0
angle = 0
# split the time difference into timestep_ms steps
total_time = int(tm_diff * 100000)
steps = total_time // self._timestep
remainder = total_time % self._timestep
step = self._timestep / 100000.0
if remainder:
last_step = remainder / 100000.0
steps += 1
else:
last_step = step
while steps != 0:
if steps == 1:
tm_diff = last_step
else:
tm_diff = step
steps -= 1
l = self._lmotor.compute(-l_motor, tm_diff)
r = self._rmotor.compute(r_motor, tm_diff)
# Tank drive motion equations
velocity = (l + r) * 0.5
# Thanks to Tyler Veness for fixing the rotation equation, via conservation
# of angular momentum equations
# -> omega = b * m * (l - r) / J
rotation = self._bm * (l - r) / self._inertia
distance = velocity * tm_diff
turn = rotation * tm_diff
x += distance * math.cos(angle)
y += distance * math.sin(angle)
angle += turn
return x, y, angle | Given motor values and the amount of time elapsed since this was last
called, retrieves the x,y,angle that the robot has moved. Pass these
values to :meth:`PhysicsInterface.distance_drive`.
To update your encoders, use the ``l_position`` and ``r_position``
attributes of this object.
:param l_motor: Left motor value (-1 to 1); -1 is forward
:param r_motor: Right motor value (-1 to 1); 1 is forward
:param tm_diff: Elapsed time since last call to this function
:returns: x travel, y travel, angle turned (radians)
.. note:: If you are using more than 2 motors, it is assumed that
all motors on each side are set to the same speed. Only
pass in one of the values from each side | entailment |
def validate_basic_smoother():
"""Run Friedman's test from Figure 2b."""
x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82())
plt.figure()
# plt.plot(x, y, '.', label='Data')
for span in smoother.DEFAULT_SPANS:
my_smoother = smoother.perform_smooth(x, y, span)
friedman_smooth, _resids = run_friedman_smooth(x, y, span)
plt.plot(x, my_smoother.smooth_result, '.-', label='pyace span = {0}'.format(span))
plt.plot(x, friedman_smooth, '.-', label='Friedman span = {0}'.format(span))
finish_plot() | Run Friedman's test from Figure 2b. | entailment |
def validate_basic_smoother_resid():
"""Compare residuals."""
x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82())
plt.figure()
for span in smoother.DEFAULT_SPANS:
my_smoother = smoother.perform_smooth(x, y, span)
_friedman_smooth, resids = run_friedman_smooth(x, y, span) # pylint: disable=unused-variable
plt.plot(x, my_smoother.cross_validated_residual, '.-',
label='pyace span = {0}'.format(span))
plt.plot(x, resids, '.-', label='Friedman span = {0}'.format(span))
finish_plot() | Compare residuals. | entailment |
def validate_supersmoother():
"""Validate the supersmoother."""
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
x, y = sort_data(x, y)
my_smoother = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmootherWithPlots)
# smoother.DEFAULT_BASIC_SMOOTHER = BasicFixedSpanSmootherBreiman
supsmu_result = run_freidman_supsmu(x, y, bass_enhancement=0.0)
mace_result = run_mace_smothr(x, y, bass_enhancement=0.0)
plt.plot(x, y, '.', label='Data')
plt.plot(x, my_smoother.smooth_result, '-', label='pyace')
plt.plot(x, supsmu_result, '--', label='SUPSMU')
plt.plot(x, mace_result, ':', label='SMOOTH')
plt.legend()
plt.savefig('supersmoother_validation.png') | Validate the supersmoother. | entailment |
def validate_supersmoother_bass():
"""Validate the supersmoother with extra bass."""
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
plt.figure()
plt.plot(x, y, '.', label='Data')
for bass in range(0, 10, 3):
smooth = supersmoother.SuperSmoother()
smooth.set_bass_enhancement(bass)
smooth.specify_data_set(x, y)
smooth.compute()
plt.plot(x, smooth.smooth_result, '.', label='Bass = {0}'.format(bass))
# pylab.plot(self.x, smoother.smooth_result, label='Bass = {0}'.format(bass))
finish_plot() | Validate the supersmoother with extra bass. | entailment |
def validate_average_best_span():
"""Figure 2d? from Friedman."""
N = 200
num_trials = 400
avg = numpy.zeros(N)
for i in range(num_trials):
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82(N=N)
my_smoother = smoother.perform_smooth(
x, y, smoother_cls=supersmoother.SuperSmoother
)
avg += my_smoother._smoothed_best_spans.smooth_result
if not (i + 1) % 20:
print(i + 1)
avg /= num_trials
plt.plot(my_smoother.x, avg, '.', label='Average JCV')
finish_plot() | Figure 2d? from Friedman. | entailment |
def validate_known_curve():
"""Validate on a sin function."""
plt.figure()
N = 100
x = numpy.linspace(-1, 1, N)
y = numpy.sin(4 * x)
smoother.DEFAULT_BASIC_SMOOTHER = smoother.BasicFixedSpanSmootherSlowUpdate
smooth = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmoother)
plt.plot(x, smooth.smooth_result, label='Slow')
smoother.DEFAULT_BASIC_SMOOTHER = smoother.BasicFixedSpanSmoother
smooth = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmoother)
plt.plot(x, smooth.smooth_result, label='Fast')
plt.plot(x, y, '.', label='data')
plt.legend()
plt.show() | Validate on a sin function. | entailment |
def finish_plot():
"""Helper for plotting."""
plt.legend()
plt.grid(color='0.7')
plt.xlabel('x')
plt.ylabel('y')
plt.show() | Helper for plotting. | entailment |
def run_freidman_supsmu(x, y, bass_enhancement=0.0):
"""Run the FORTRAN supersmoother."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
flags = numpy.zeros((N, 7))
mace.supsmu(x, y, weight, 1, 0.0, bass_enhancement, results, flags)
return results | Run the FORTRAN supersmoother. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.