output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def is_generator(self, node):
"""Checks whether a function is a generator by looking for a yield
statement or expression."""
if not isinstance(node.body, list):
# lambdas can not be generators
return False
for item in node.body:
if isinstance(item, (as... | Write a Python 3 function that can
check whether a function is a generator by looking for a yield statement or expression. | As a Python code analyst, you investigate and solve complex coding mysteries |
Keep track of globals declarations. | Can you generate the documentation for the following Python 3 function
def GLOBAL(self, node):
if isinstance(self.scope, FunctionScope):
self.scope.globals.update(node.names) | You are a Python code generator, capable of creating scripts from specifications. |
Process bindings for loop variables. | Here you have a function in Python 3, explain what it does
def FOR(self, node):
vars = []
def collectLoopVars(n):
if isinstance(n, ast.Name):
vars.append(n.id)
elif isinstance(n, ast.expr_context):
return
else:
for c in... | As a Python code composer, you craft elegant and concise scripts. |
def NAME(self, node):
"""Handle occurrence of Name (which can be a load/store/delete
access.)"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handle_node_load(node)
if (node.id == 'locals' and isin... | Create a Python 3 function to
handle occurrence of Name in function or globals. | You are a Python code architect, reviewing and designing scalable and efficient code |
Check names used in a class definition. | Explain what the following Python 3 code does
def CLASSDEF(self, node):
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.... | As a Python code analyst, you investigate and solve complex coding mysteries |
Check the Python source given by codeString for unfrosted flakes. | Explain what the following Python 3 code does
def check(codeString, filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
if not settings_path and filename:
settings_path = os.path.dirname(os.path.abspath(filename))
settings_path = settings_path or os.getcwd()
active_se... | You are a Python code architect, reviewing and designing scalable and efficient code |
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, ... | How would you code a function in Python 3 to
check the given path and print out any warnings detected. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Recursively check all source files defined in paths. | Can you generate a brief explanation for the following Python 3 code
def check_recursive(paths, reporter=modReporter.Default, settings_path=None, **setting_overrides):
warnings = 0
for source_path in iter_source_code(paths):
warnings += check_path(source_path, reporter, settings_path=None, **setting_ove... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return S3 files where the name does not include the path. | How would you explain what the following Python 3 function does
def get_files_from_storage(paths):
for path in paths:
f = default_storage.open(path)
f.name = os.path.basename(path)
try:
yield f
except ClientError:
logger.exception("... | You are a Python code analyst, evaluating scripts for potential improvements. |
def echo(bot, update):
"""Echo the user message."""
message = update.get_effective_message()
bot.reply(update, message) | How would you implement a function in Python 3 that
echoes the user message. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Log Errors caused by Updates. | Can you generate the documentation for the following Python 3 function
def error(bot, update, error):
logger.error('Update {} caused error {}'.format(update, error), extra={"tag": "err"}) | You are a Python code generator, capable of creating scripts from specifications. |
Returns a configured StompServer from a config file. | Given the following Python 3 function, write the documentation
def server_from_config(config=None, server_class=None, additional_kwargs=None):
global global_config
if not config:
config = global_config
queue_store_factory = resolve_name(config.get('coilmq', 'qstore.factory'))
subscriber_schedul... | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Write a Python 3 script for
starting a server within a context. | As a python code expert, you are capable of creating scripts from specifications. |
This is the main function for the socket server. | Make a summary of the following Python 3 code
def main(config, host, port, logfile, debug, daemon, uid, gid, pidfile, umask, rundir):
_main(**locals()) | You are a Python code generator, capable of creating scripts from specifications. |
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 | Write a Python 3 script to
return a SQLAlchemy queue store | You are a Python code generator, capable of creating scripts from specifications. |
Initializes the shared SQLAlchemy model. | Make a summary of the following Python 3 code
def init_model(engine, create=True, drop=False):
meta.engine = engine
meta.metadata = MetaData(bind=meta.engine)
meta.Session = scoped_session(sessionmaker(bind=meta.engine))
model.setup_tables(create=create, drop=drop) | As a Python code composer, you craft elegant and concise scripts. |
Enqueue a message to the queue for this destination. | How would you explain what the following Python 3 function does
def enqueue(self, destination, 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_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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.
... | How would you implement a function in Python 3 that
removes and returns an item from the queue. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 = ... | Create a Python 3 function for
returning C { bool } if the specified queue has any frames in the specified queue. | As a python code expert, you are capable of creating scripts from specifications. |
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.Sessio... | Create a Python 3 function for
returning the number of frames in the specified queue. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 = sessio... | Implement a function in Python 3 to
provide a list of destinations available. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create and drop the tables in the database. | Can you generate a brief explanation for the following Python 3 code
def setup_tables(create=True, drop=False):
global frames_table
frames_table = Table('frames', meta.metadata,
Column('message_id', String(255), primary_key=True),
Column('sequence', BigInteger,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Subscribes a connection to the specified topic destination. | Can you tell what is the following Python 3 function doing
def subscribe(self, connection, destination):
self.log.debug("Subscribing %s to %s" % (connection, destination))
self._topics[destination].add(connection) | You are a Python code architect, reviewing and designing scalable and efficient code |
Unsubscribes a connection from the specified topic destination. | Explain what the following Python 3 code does
def unsubscribe(self, connection, destination):
self.log.debug("Unsubscribing %s from %s" % (connection, destination))
if connection in self._topics[destination]:
self._topics[destination].remove(connection)
if not self._topics[destinati... | You are a Python code architect, reviewing and designing scalable and efficient code |
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.ke... | Can you create a Python 3 function that
disconnects a subscriber connection from all topics. | As a Python code composer, you craft elegant and concise scripts. |
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}
"""
des... | Write a Python 3 script for
sending a message to all subscribers of destination. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Unbinds this connection from queue and topic managers. | Explain what the following Python 3 code does
def unbind(self):
self.connected = False
self.queue_manager.disconnect(self.connection)
self.topic_manager.disconnect(self.connection) | You are a Python code architect, reviewing and designing scalable and efficient code |
Closes all resources and backends associated with this queue manager. | How would you explain what the following Python 3 function does
def close(self):
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()
i... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a count of the number of subscribers. | Here you have a function in Python 3, explain what it does
def subscriber_count(self, destination=None):
if destination:
return len(self._queues[destination])
else:
# total them up
total = 0
for k in self._queues.keys():
total += len(self._... | You are a Python code analyst, evaluating scripts for potential improvements. |
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. '/q... | Write a Python 3 function for
subscribing a connection to the specified destination. | As a Python code composer, you craft elegant and concise scripts. |
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" % con... | Implement a Python 3 function for
disconnecting a subscriber connection from the server. | You are a Python code architect, reviewing and designing scalable and efficient code |
Sends a MESSAGE frame to an eligible subscriber connection. | How would you explain what the following Python 3 function does
def send(self, message):
dest = message.headers.get('destination')
if not dest:
raise ValueError(
"Cannot send frame with no destination: %s" % message)
message.cmd = 'message'
message.headers.s... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 th... | Can you implement a function in Python 3 that
acknowledges receipt of a message. | As a Python code analyst, you investigate and solve complex coding mysteries |
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: ... | Implement a function in Python 3 to
resend the messages that were ACK'd in specified transaction. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sends any queued - up messages to the specified destination. | How would you explain what the following Python 3 function does
def _send_backlog(self, connection, destination=None):
if destination is None:
# Find all destinations that have frames and that contain this
# connection (subscriber).
eligible_queues = dict([(dest, q) for (dest... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sends a frame to a specific subscriber connection. | Make a summary of the following Python 3 code
def _send_frame(self, connection, 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:
... | As a python code expert, you are capable of creating scripts from specifications. |
Creates a DBM queue store for the current node. | Can you generate the documentation for the following Python 3 function
def make_dbm():
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')
ex... | You are a Python code generator, capable of creating scripts from specifications. |
Enqueue a message to the specified destination. | How would you explain what the following Python 3 function does
def enqueue(self, destination, 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:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Removes and returns an item from the queue. | Can you generate the documentation for the following Python 3 function
def dequeue(self, destination):
if not self.has_frames(destination):
return None
message_id = self.queue_metadata[destination]['frames'].pop()
self.queue_metadata[destination]['dequeued'] += 1
frame = se... | As a python code expert, you are capable of creating scripts from specifications. |
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 (de... | Write a Python 3 script to
determine if the specified queue has any frames in the specified queue. | You are a Python code generator, capable of creating scripts from specifications. |
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... | How would you implement a function in Python 3 that
returns the size of the queue for the specified destination. | You are a Python code generator, capable of creating scripts from specifications. |
Synchronize the cache with the underlyind database. | Given the following Python 3 function, write the documentation
def _sync(self):
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()
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Reads an ordered list of configuration values and deep merge the values in reverse order. | How would you explain what the following Python 3 function does
def read(config_values):
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 = Co... | You are a Python code analyst, evaluating scripts for potential improvements. |
Parses buffer and returns command and headers as strings
| Here you have a function in Python 3, explain what it does
def parse_headers(buff):
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(':')... | As a python code expert, you are capable of creating scripts from specifications. |
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
... | Implement a function in Python 3 to
create a string representation of this object state. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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
fu... | Can you create a Python 3 function that
extracts one complete frame off the buffer and returns it. | As a Python code composer, you craft elegant and concise scripts. |
Choose a random connection favoring those that are reliable from
subscriber pool to deliver specified message. | How would you explain what the following Python 3 function does
def choice(self, subscribers, message):
if not subscribers:
return None
reliable_subscribers = [
s for s in subscribers if s.reliable_subscriber]
if reliable_subscribers:
return random.choice(reli... | You are a Python code generator, capable of creating scripts from specifications. |
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} ... | How would you code a function in Python 3 to
return a random queue destination for messages to specified connection. | As a Python code analyst, you investigate and solve complex coding mysteries |
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`/`li... | Can you implement a function in Python 3 that
gets a value corresponding to the key and converts it to int. | As a python code expert, you are capable of creating scripts from specifications. |
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... | Write a Python 3 function that can
get a value corresponding to the key and converts it to float. | As a Python code composer, you craft elegant and concise scripts. |
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 ... | Write a Python 3 script for
getting a boolean value corresponding to the key and converts it to bool or list ( str. | You are a Python code analyst, evaluating scripts for potential improvements. |
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 ... | Create a Python 3 function for
getting a value corresponding to the key and converts it to str. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a value corresponding to the key and converts it to dict. | Can you generate the documentation for the following Python 3 function
def get_dict(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
""... | You are a Python code generator, capable of creating scripts from specifications. |
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 ... | Write a Python 3 function for
getting a dict corresponding to the key and converts it to dict. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a value corresponding to the key and converts it to UriSpec. | Here you have a function in Python 3, explain what it does
def get_uri(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get a value corresponding to the key and converts it to AuthSpec. | Make a summary of the following Python 3 code
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... | You are a Python code generator, capable of creating scripts from specifications. |
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.
... | Implement a Python 3 function for
getting a the value corresponding to the key and converts comma separated values to a list. | You are a Python code generator, capable of creating scripts from specifications. |
Internal method that returns the typed value of the key. | Explain what the following Python 3 code does
def _get_typed_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
... | As a python code expert, you are capable of creating scripts from specifications. |
def _get_typed_list_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
... | Write a Python 3 function that can
return the value corresponding to the given key converted first to list then each element to the given type. | You are a Python code analyst, evaluating scripts for potential improvements. |
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.... | Can you write a function in Python 3 where it
creates a L{SimpleAuthenticator instance using values read from coilmq configuration. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 au... | How would you code a function in Python 3 to
initialize the authentication store from a config file. | You are a Python code architect, reviewing and designing scalable and efficient code |
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 | Write a Python 3 function for
authenticating the login and passcode. | As a Python code analyst, you investigate and solve complex coding mysteries |
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:
... | Write a Python 3 function that can
dispatch a received frame to the appropriate internal method. | As a python code expert, you are capable of creating scripts from specifications. |
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.heade... | Can you write a function in Python 3 where it
establishes a new connection and checks auth. | You are a Python code generator, capable of creating scripts from specifications. |
Handle the SEND command. | Can you generate a brief explanation for the following Python 3 code
def send(self, frame):
dest = frame.headers.get('destination')
if not dest:
raise ProtocolError('Missing destination for SEND command.')
if dest.startswith('/queue/'):
self.engine.queue_manager.send(fra... | You are a Python code architect, reviewing and designing scalable and efficient code |
Handle the SUBSCRIBE command. Adds this connection to destination. | Here you have a function in Python 3, explain what it does
def subscribe(self, frame):
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:
... | You are a Python code generator, capable of creating scripts from specifications. |
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... | Can you write a function in Python 3 where it
handles the UNSUBSCRIBE command. Removes this connection from destination. | You are a Python code generator, capable of creating scripts from specifications. |
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] = [] | Can you create a Python 3 function that
handles the BEGIN command. | As a Python code analyst, you investigate and solve complex coding mysteries |
Handles COMMIT command: Commits specified transaction. | Make a summary of the following Python 3 code
def commit(self, frame):
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... | You are a Python code analyst, evaluating scripts for potential improvements. |
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("Inv... | Implement a Python 3 function for
handling an ABORT command. | As a Python code analyst, you investigate and solve complex coding mysteries |
Handles the ACK command. | Explain what the following Python 3 code does
def ack(self, frame):
if not frame.message_id:
raise ProtocolError("No message-id specified for ACK command.")
self.engine.queue_manager.ack(self.engine.connection, frame) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Handles the DISCONNECT command. Unbinds the connection. | Make a summary of the following Python 3 code
def disconnect(self, frame):
self.engine.log.debug("Disconnect")
self.engine.unbind() | As a Python code analyst, you investigate and solve complex coding mysteries |
Handles the NACK command. | Explain what the following Python 3 code does
def nack(self, frame):
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.... | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize the configuration from a config file. | Here you have a function in Python 3, explain what it does
def init_config(config_file=None):
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" %... | As a python code expert, you are capable of creating scripts from specifications. |
Initializes the logging for the daemons. | Given the following Python 3 function, write the documentation
def init_logging(logfile=None, loglevel=logging.INFO, configfile=None):
# 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 = Co... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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'... | Implement a function in Python 3 to
resolve a dotted name to some object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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)
... | Write a Python 3 function for
handling a new connection. | You are a Python code analyst, evaluating scripts for potential improvements. |
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.r... | Create a Python 3 function to
send a frame to connected socket client. | As a Python code analyst, you investigate and solve complex coding mysteries |
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,... | Create a Python 3 function for
closing the socket server and any associated resources. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Handle one request at a time until shutdown. | Given the following Python 3 function, write the documentation
def serve_forever(self, poll_interval=0.5):
self._serving_event.set()
self._shutdown_request_event.clear()
TCPServer.serve_forever(self, poll_interval=poll_interval) | As a python code expert, you are capable of creating scripts from specifications. |
Create a grayscale 3d texture map with the specified pixel width on each side and load it into the current texture. | How would you explain what the following Python 3 function does
def create_3d_texture(width, scale):
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... | As a python code expert, you are capable of creating scripts from specifications. |
Randomize the permutation table used by the noise functions. This is a utility method that randomly generates noise patterns for the same inputs. | Make a summary of the following Python 3 code
def randomize(self, period=None):
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 =... | As a Python code composer, you craft elegant and concise scripts. |
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. | Explain what the following Python 3 code does
def noise3(self, x, y, z, repeat, base=0.0):
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 += ... | You are a Python code generator, capable of creating scripts from specifications. |
Load the noise texture into the current texture unit | Can you generate a brief explanation for the following Python 3 code
def load(self):
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)) | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the vision of the specified target. | Given the following Python 3 function, write the documentation
def compute(self, now, x, y, angle):
# 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)
... | As a python code expert, you are capable of creating scripts from specifications. |
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='... | Create a Python 3 function for
running Friedman s test of fixed - span smoothers from Figure 2b. | You are a Python code generator, capable of creating scripts from specifications. |
Used for development and testing. | Can you tell what is the following Python 3 function doing
def main():
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('u... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the entire sub expressions as a string with spaces. | Make a summary of the following Python 3 code
def fmtd_sub_expr_str(self):
result = u"{}({}".format(self.normalized_func,
self._metric_name)
if self._dimensions is not None:
result += "{" + self.dimensions_str + "}"
if self._period != _DEFAULT_PERIO... | As a python code expert, you are capable of creating scripts from specifications. |
Return the operator as one of LT GT LTE or GTE. | Make a summary of the following Python 3 code
def normalized_operator(self):
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._o... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a new instance of the base class for the theory of the given base class. | Here you have a function in Python 3, explain what it does
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,
... | You are a Python code generator, capable of creating scripts from specifications. |
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:`... | Create a Python 3 function for
giving 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. :par... | You are a Python code analyst, evaluating scripts for potential improvements. |
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)
... | How would you code a function in Python 3 to
run Friedman s test from Figure 2b. | You are a Python code analyst, evaluating scripts for potential improvements. |
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_smoot... | Write a Python 3 function that can
compare residuals with basic smoother. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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_bas... | Write a Python 3 script for
validating the supersmoother with extra bass. | As a Python code composer, you craft elegant and concise scripts. |
Figure 2d? from Friedman82. | How would you explain what the following Python 3 function does
def validate_average_best_span():
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(
... | As a Python code composer, you craft elegant and concise scripts. |
Validate on a sin function. | Explain what the following Python 3 code does
def validate_known_curve():
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.SuperSmoo... | As a Python code composer, you craft elegant and concise scripts. |
Run the FORTRAN supersmoother. | Can you generate the documentation for the following Python 3 function
def run_freidman_supsmu(x, y, bass_enhancement=0.0):
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 | You are a Python code analyst, evaluating scripts for potential improvements. |
def run_friedman_smooth(x, y, span):
"""Run the FORTRAN smoother."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
residuals = numpy.zeros(N)
mace.smooth(x, y, weight, span, 1, 1e-7, results, residuals)
return results, residuals | How would you code a function in Python 3 to
run the FORTRAN smoother. | You are a Python code analyst, evaluating scripts for potential improvements. |
Run the FORTRAN SMOTHR. | Can you generate a brief explanation for the following Python 3 code
def run_mace_smothr(x, y, bass_enhancement=0.0): # pylint: disable=unused-argument
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
flags = numpy.zeros((N, 7))
mace.smothr(1, x, y, weight, results, flags)
return resu... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_conn(self, host, port):
"""Get or create a connection to a broker using host and port"""
host_key = (host, port)
if host_key not in self.conns:
self.conns[host_key] = KafkaConnection(
host,
port,
timeout=self.timeout
... | Create a Python 3 function for
getting or create a connection to a broker using host and port | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.