output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def set_vnic_connectivity_status(nic_spec, to_connect):
"""
sets the device spec as connected or disconnected
:param nic_spec: the specification
:param to_connect: bool
"""
nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
nic... | Can you implement a function in Python 3 that
sets the vnic connectivity status of the nic spec. | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a new instance of the class based on the given parameters. | Can you generate a brief explanation for the following Python 3 code
def create_from_params(cls, template_model, datastore_name, vm_cluster_model, ip_regex, refresh_ip_timeout,
auto_power_on, auto_power_off, wait_for_ip, auto_delete):
"""
:param VCenterTemplateModel template_m... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the name of the current snapshot | Given the following Python 3 function, write the documentation
def get_current_snapshot_name(vm):
all_snapshots = SnapshotRetriever.get_vm_snapshots(vm)
# noinspection PyProtectedMember
if not vm.snapshot:
return None
current_snapshot_id = vm.snapshot.currentSnapshot._moId
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Recursively traverses child snapshots and returns dictinary of snapshot path and snapshot instances | Can you generate a brief explanation for the following Python 3 code
def _get_snapshots_recursively(snapshots, snapshot_location):
snapshot_paths = collections.OrderedDict()
if not snapshots:
return snapshot_paths
for snapshot in snapshots:
if snapshot_location:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def wait_for_task(self, task, logger, action_name='job', hide_result=False, cancellation_context=None):
"""
Waits and provides updates on a vSphere task
:param cancellation_context: package.cloudshell.cp.vcenter.models.QualiDriverModels.CancellationContext
:param task:
:param act... | How would you code a function in Python 3 to
wait for a task to complete and provides updates on a vSphere task. | You are a Python code architect, reviewing and designing scalable and efficient code |
deploy_from_linked_clone - Deploys a VM From VM Command will deploy vm from a snapshot | How would you explain what the following Python 3 function does
def deploy_from_linked_clone(self, si, logger, data_holder, vcenter_data_model, reservation_id,
cancellation_context):
"""
deploy Cloned VM From VM Command, will deploy vm from a snapshot
:param can... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def deploy_clone_from_vm(self, si, logger, data_holder, vcenter_data_model, reservation_id, cancellation_context):
"""
deploy Cloned VM From VM Command, will deploy vm from another vm
:param cancellation_context:
:param reservation_id:
:param si:
:param logger:
:... | Can you create a Python 3 function that
deploys Cloned VM From VM Command, will deploy vm from another vm :param cancellation_context: :param reservation_id: :param si: :param logger: :type data_holder: :type vcenter_data_model: :rtype DeployAppResult: :return: | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the deploy image parameters for the specified image resource model. | Given the following Python 3 function, write the documentation
def _get_deploy_image_params(data_holder, host_info, vm_name):
image_params = OvfImageParams()
if hasattr(data_holder, 'vcenter_image_arguments') and data_holder.vcenter_image_arguments:
image_params.user_arguments = data_holder.... | As a Python code composer, you craft elegant and concise scripts. |
def get_details(self):
"""
:rtype list[VmDataField]
"""
data = []
if isinstance(self.model, vCenterCloneVMFromVMResourceModel):
data.append(VmDetailsProperty(key='Cloned VM Name', value=self.model.vcenter_vm))
if isinstance(self.model, VCenterDeployVMFromLink... | Write a Python 3 function for
returning details of the current VM | You are a Python code architect, reviewing and designing scalable and efficient code |
def convert_to_resource_model(self, attributes, resource_model_type):
"""
Converts an instance of resource with dictionary of attributes
to a class instance according to family and assigns its properties
:type attributes: dict
:param resource_model_type: Resource Model type to cr... | Write a Python 3 script for
converting an instance of resource with dictionary of attributes to a class instance according to family and assigns its properties | You are a Python code analyst, evaluating scripts for potential improvements. |
Create an instance of class named *ResourceModel
from models folder according to ResourceModelName of a resource | Can you tell what is the following Python 3 function doing
def create_resource_model_instance(resource_instance):
resource_model = ResourceModelParser.get_resource_model(resource_instance)
resource_class_name = ResourceModelParser.get_resource_model_class_name(
resource_model)
# prin... | As a python code expert, you are capable of creating scripts from specifications. |
Returns an instance of a class by its class_path. | Make a summary of the following Python 3 code
def get_class(class_path):
module_path, class_name = class_path.rsplit(".", 1)
try:
module = __import__(class_path, fromlist=[class_name])
except ImportError:
raise ValueError('Class {0} could not be imported'.format(class_pa... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns property name from attribute name | Can you generate a brief explanation for the following Python 3 code
def get_property_name_from_attribute_name(attribute):
if isinstance(attribute, str) or isinstance(attribute, unicode):
attribute_name = attribute
elif hasattr(attribute, 'Name'):
attribute_name = attribute.Name
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Computes the CRC - 32 of the contents of filename optionally skipping a certain number of bytes at the beginning of the file. | Can you generate the documentation for the following Python 3 function
def crc32File(filename, skip=0):
with open(filename, 'rb') as stream:
discard = stream.read(skip)
return zlib.crc32(stream.read()) & 0xffffffff | As a Python code analyst, you investigate and solve complex coding mysteries |
def endianSwapU16(bytes):
"""Swaps pairs of bytes (16-bit words) in the given bytearray."""
for b in range(0, len(bytes), 2):
bytes[b], bytes[b + 1] = bytes[b + 1], bytes[b]
return bytes | How would you code a function in Python 3 to
swap pairs of bytes in the given bytearray. | As a python code expert, you are capable of creating scripts from specifications. |
Sets all defaults for the given dictionary to those contained in a
athermotto. | Make a summary of the following Python 3 code
def setDictDefaults (d, defaults):
for key, val in defaults.items():
d.setdefault(key, val)
return d | As a Python code analyst, you investigate and solve complex coding mysteries |
def getDefaultDict(modname, config_key, loader, reload=False, filename=None):
"""Returns default AIT dictonary for modname
This helper function encapulates the core logic necessary to
(re)load, cache (via util.ObjectCache), and return the default
dictionary. For example, in ait.core.cmd:
def getD... | Can you create a Python 3 function that
returns the default AIT dictonary for modname | As a Python code analyst, you investigate and solve complex coding mysteries |
def toBCD (n):
"""Converts the number n into Binary Coded Decimal."""
bcd = 0
bits = 0
while True:
n, r = divmod(n, 10)
bcd |= (r << bits)
if n is 0:
break
bits += 4
return bcd | Create a Python 3 function to
convert the number n into a Binary Coded Decimal. | You are a Python code generator, capable of creating scripts from specifications. |
Converts the given string to a floating - point value. | Given the following Python 3 function, write the documentation
def toFloat (str, default=None):
value = default
try:
value = float(str)
except ValueError:
pass
return value | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert a string to a numeric value. | Given the following Python 3 function, write the documentation
def toNumber (str, default=None):
value = default
try:
if str.startswith("0x"):
value = int(str, 16)
else:
try:
value = int(str)
except ValueError:
value = float(st... | You are a Python code generator, capable of creating scripts from specifications. |
Convert the Python object to a string representation of the kind
often returned by a class __repr__ method. | Given the following Python 3 function, write the documentation
def toRepr (obj):
args = [ ]
names = [ ]
if hasattr(obj, "__dict__"):
names += getattr(obj, "__dict__").keys()
if hasattr(obj, "__slots__"):
names += getattr(obj, "__slots__")
for name in names:
value = getattr... | You are a Python code architect, reviewing and designing scalable and efficient code |
def toStringDuration (duration):
"""Returns a description of the given duration in the most appropriate
units (e.g. seconds, ms, us, or ns).
"""
table = (
('%dms' , 1e-3, 1e3),
(u'%d\u03BCs', 1e-6, 1e6),
('%dns' , 1e-9, 1e9)
)
if duration > 1:
return '... | Can you implement a function in Python 3 that
returns a description of the given duration in the most appropriate units. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return pathname as an absolute path either expanded by the users
home directory or with prefix prepended. | Given the following Python 3 function, write the documentation
def expandPath (pathname, prefix=None):
if prefix is None:
prefix = ''
expanded = pathname
if pathname[0] == '~':
expanded = os.path.expanduser(pathname)
elif pathname[0] != '/':
expanded = os.path.join(prefix, path... | You are a Python code architect, reviewing and designing scalable and efficient code |
def listAllFiles (directory, suffix=None, abspath=False):
"""Returns the list of all files within the input directory and
all subdirectories.
"""
files = []
directory = expandPath(directory)
for dirpath, dirnames, filenames in os.walk(directory, followlinks=True):
if suffix:
... | How would you implement a function in Python 3 that
returns the list of all files within the input directory and all subdirectories. | You are a Python code generator, capable of creating scripts from specifications. |
def dirty(self):
"""True if the cache needs to be updated, False otherwise"""
return not os.path.exists(self.cachename) or \
(os.path.getmtime(self.filename) >
os.path.getmtime(self.cachename)) | Write a Python 3 function that can
true if the cache needs to be updated False otherwise. | You are a Python code architect, reviewing and designing scalable and efficient code |
def cache(self):
"""Caches the result of loader(filename) to cachename."""
msg = 'Saving updates from more recent "%s" to "%s"'
log.info(msg, self.filename, self.cachename)
with open(self.cachename, 'wb') as output:
cPickle.dump(self._dict, output, -1) | Create a Python 3 function for
caching the result of loader ( filename to cachename. | You are a Python code analyst, evaluating scripts for potential improvements. |
def load(self):
"""Loads the Python object
Loads the Python object, either via loader(filename) or the
pickled cache file, whichever was modified most recently.
"""
if self._dict is None:
if self.dirty:
self._dict = self._loader(self.filename)
... | Implement a Python 3 function for
loading the Python object from the cache file. | As a Python code composer, you craft elegant and concise scripts. |
Process a message received from PacketHandler into a tuple and inserts it into the database backend. | Can you generate the documentation for the following Python 3 function
def process(self, input_data, topic=None, **kwargs):
try:
split = input_data[1:-1].split(',', 1)
uid, pkt = int(split[0]), split[1]
defn = self.packet_dict[uid]
decoded = tlm.Packet(defn, data=... | As a Python code analyst, you investigate and solve complex coding mysteries |
def getTimestampUTC():
"""getTimestampUTC() -> (ts_sec, ts_usec)
Returns the current UTC time in seconds and microseconds.
"""
utc = datetime.datetime.utcnow()
ts_sec = calendar.timegm( utc.timetuple() )
ts_usec = utc.microsecond
return ts_sec, ts_usec | Can you implement a function in Python 3 that
returns the current UTC time in seconds and microseconds. | You are a Python code generator, capable of creating scripts from specifications. |
getUTCDatetimeDOY - Returns the UTC current datetime with the input timedelta arguments days hours minutes seconds | How would you explain what the following Python 3 function does
def getUTCDatetimeDOY(days=0, hours=0, minutes=0, seconds=0):
return (datetime.datetime.utcnow() +
datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).strftime(DOY_Format) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the total elapsed seconds since the most recent tic call or None if tic was not called. | Here you have a function in Python 3, explain what it does
def toc():
end = datetime.datetime.now()
return totalSeconds( end - TICs.pop() ) if len(TICs) else None | You are a Python code generator, capable of creating scripts from specifications. |
def toGPSWeekAndSecs(timestamp=None):
"""Converts the given UTC timestamp (defaults to the current time) to
a two-tuple, (GPS week number, GPS seconds within the week).
"""
if timestamp is None:
timestamp = datetime.datetime.utcnow()
leap = LeapSeconds.get_GPS_offset_for_date(timestamp)
... | Write a Python 3 function that can
convert the given UTC timestamp to a two - tuple that is a two - tuple with the GPS week number and GPS seconds within the week. | As a python code expert, you are capable of creating scripts from specifications. |
def toGMST(dt=None):
"""Converts the given Python datetime or Julian date (float) to
Greenwich Mean Sidereal Time (GMST) (in radians) using the formula
from D.A. Vallado (2004).
See:
D.A. Vallado, Fundamentals of Astrodynamics and Applications, p. 192
http://books.google.com/books?id=P... | How would you code a function in Python 3 to
convert the given Python datetime or Julian date to Greenwich Mean Sidereal Time in radians | As a python code expert, you are capable of creating scripts from specifications. |
Converts a Python datetime to a Julian date using the formula from
Meesus ( 2004. | Can you generate the documentation for the following Python 3 function
def toJulian(dt=None):
if dt is None:
dt = datetime.datetime.utcnow()
if dt.month < 3:
year = dt.year - 1
month = dt.month + 12
else:
year = dt.year
month = dt.month
A = int(year / 100.... | You are a Python code analyst, evaluating scripts for potential improvements. |
def toLocalTime(seconds, microseconds=0):
"""toLocalTime(seconds, microseconds=0) -> datetime
Converts the given number of seconds since the GPS Epoch (midnight
on January 6th, 1980) to this computer's local time. Returns a
Python datetime object.
Examples:
>>> toLocalTime(0)
datetime.da... | Write a Python 3 function that can
convert the given number of seconds since the GPS Epoch to this computer s local time. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the total number of seconds contained in the given Python
datetime. timedelta object. | Can you tell what is the following Python 3 function doing
def totalSeconds(td):
if hasattr(td, "total_seconds"):
ts = td.total_seconds()
else:
ts = (td.microseconds + (td.seconds + td.days * 24 * 3600.0) * 1e6) / 1e6
return ts | As a python code expert, you are capable of creating scripts from specifications. |
Updates the system leap second information from the system leap second list file and updates the leap second config file. | Explain what the following Python 3 code does
def _update_leap_second_data(self):
log.info('Attempting to acquire latest leapsecond data')
ls_file = ait.config.get(
'leapseconds.filename',
os.path.join(ait.config._directory, _DEFAULT_FILE_NAME)
)
url = 'https:/... | As a python code expert, you are capable of creating scripts from specifications. |
Starts all greenlets and joins all servers. | Can you generate the documentation for the following Python 3 function
def wait(self):
for greenlet in (self.greenlets + self.servers):
log.info("Starting {} greenlet...".format(greenlet))
greenlet.start()
gevent.joinall(self.greenlets) | You are a Python code architect, reviewing and designing scalable and efficient code |
Reads and creates streams specified in config. yaml. | Given the following Python 3 function, write the documentation
def _load_streams(self):
common_err_msg = 'No valid {} stream configurations found. '
specific_err_msg = {'inbound': 'No data will be received (or displayed).',
'outbound': 'No data will be published.'}
er... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _create_inbound_stream(self, config=None):
"""
Creates an inbound stream from its config.
Params:
config: stream configuration as read by ait.config
Returns:
stream: a Stream
Raises:
ValueError: if any of the required config ... | Write a Python 3 script to
create an inbound stream from its config. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _create_outbound_stream(self, config=None):
"""
Creates an outbound stream from its config.
Params:
config: stream configuration as read by ait.config
Returns:
stream: a Stream
Raises:
ValueError: if any of the required confi... | Write a Python 3 function for
creating an outbound stream from its config. | As a Python code composer, you craft elegant and concise scripts. |
def _create_handler(self, config):
"""
Creates a handler from its config.
Params:
config: handler config
Returns:
handler instance
"""
if config is None:
raise ValueError('No handler config to create handler from.')
if 'n... | Implement a function in Python 3 to
create a handler from its config. | As a Python code composer, you craft elegant and concise scripts. |
Reads parses and creates plugins specified in config. yaml. | Here you have a function in Python 3, explain what it does
def _load_plugins(self):
plugins = ait.config.get('server.plugins')
if plugins is None:
log.warn('No plugins specified in config.')
else:
for index, p in enumerate(plugins):
try:
... | As a python code expert, you are capable of creating scripts from specifications. |
Create a new plugin from its config. | Given the following Python 3 function, write the documentation
def _create_plugin(self, config):
if config is None:
raise ValueError('No plugin config to create plugin from.')
name = config.pop('name', None)
if name is None:
raise(cfg.AitConfigMissing('plugin name'))
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts the given Python object to one suitable for Javascript
Object Notation ( JSON serialization via json. dumps. | Explain what the following Python 3 code does
def slotsToJSON(obj, slots=None):
if slots is None:
slots = list(obj.__slots__) if hasattr(obj, '__slots__') else [ ]
for base in obj.__class__.__bases__:
if hasattr(base, '__slots__'):
slots.extend(base.__slots__)
testOm... | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts a Python object to one suitable for Javascript
Object Notation ( JSON serialization via JSON. | Explain what the following Python 3 code does
def toJSON (obj):
if hasattr(obj, 'toJSON') and callable(obj.toJSON):
result = obj.toJSON()
elif isinstance(obj, (int, long, float, str, unicode)) or obj is None:
result = obj
elif isinstance(obj, collections.Mapping):
result = { toJSON(k... | As a Python code composer, you craft elegant and concise scripts. |
def createDirStruct(paths, verbose=True):
'''Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[optional] list of di... | Create a Python 3 function to
loop ait. config. _datapaths from AIT_CONFIG and creates a directory structure. | As a Python code composer, you craft elegant and concise scripts. |
def capture_packet(self):
''' Write packet data to the logger's log file. '''
data = self.socket.recv(self._buffer_size)
for h in self.capture_handlers:
h['reads'] += 1
h['data_read'] += len(data)
d = data
if 'pre_write_transforms' in h:
... | Can you write a function in Python 3 where it
writes packet data to the logger s log file. | As a python code expert, you are capable of creating scripts from specifications. |
Clean up the socket and log file handles. | Given the following Python 3 function, write the documentation
def clean_up(self):
''' Clean up the socket and log file handles. '''
self.socket.close()
for h in self.capture_handlers:
h['logger'].close() | You are a Python code generator, capable of creating scripts from specifications. |
def socket_monitor_loop(self):
''' Monitor the socket and log captured data. '''
try:
while True:
gevent.socket.wait_read(self.socket.fileno())
self._handle_log_rotations()
self.capture_packet()
finally:
self.clean_up() | Write a Python 3 function that can
monitor the socket and log captured data. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_handler(self, handler):
''' Add an additional handler
Args:
handler:
A dictionary of handler configuration for the handler
that should be added. See :func:`__init__` for details
on valid parameters.
'''
handler['logger'... | Write a Python 3 function for
adding an additional handler for the | You are a Python code generator, capable of creating scripts from specifications. |
def remove_handler(self, name):
''' Remove a handler given a name
Note, if multiple handlers have the same name the last matching
instance in the handler list will be removed.
Args:
name:
The name of the handler to remove
'''
index = None
... | Create a Python 3 function for
removing a handler given a name. | You are a Python code generator, capable of creating scripts from specifications. |
def dump_handler_config_data(self):
''' Return capture handler configuration data.
Return a dictionary of capture handler configuration data of the form:
.. code-block:: none
[{
'handler': <handler configuration dictionary>,
'log_file_path': <Path ... | Create a Python 3 function for
returning a dictionary of capture handler configuration data. | As a Python code composer, you craft elegant and concise scripts. |
Dump the capture statistics for all handler in the system. | Make a summary of the following Python 3 code
def dump_all_handler_stats(self):
''' Return handler capture statistics
Return a dictionary of capture handler statistics of the form:
.. code-block:: none
[{
'name': The handler's name,
'reads': The nu... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _handle_log_rotations(self):
''' Rotate each handler's log file if necessary '''
for h in self.capture_handlers:
if self._should_rotate_log(h):
self._rotate_log(h) | How would you implement a function in Python 3 that
rotates each handler s log file if necessary | As a Python code composer, you craft elegant and concise scripts. |
Determine if a log file rotation is necessary | Explain what the following Python 3 code does
def _should_rotate_log(self, handler):
''' Determine if a log file rotation is necessary '''
if handler['rotate_log']:
rotate_time_index = handler.get('rotate_log_index', 'day')
try:
rotate_time_index = self._decode_ti... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _decode_time_rotation_index(self, time_rot_index):
''' Return the time struct index to use for log rotation checks '''
time_index_decode_table = {
'year': 0, 'years': 0, 'tm_year': 0,
'month': 1, 'months': 1, 'tm_mon': 1,
'day': 2, 'days': 2, 'tm... | Create a Python 3 function to
return the time struct index to use for log rotation checks | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_log_file(self, handler):
''' Generate log file path for a given handler
Args:
handler:
The handler configuration dictionary for which a log file
path should be generated.
'''
if 'file_name_pattern' not in handler:
filename... | How would you implement a function in Python 3 that
generates a log file path for a given handler. | You are a Python code generator, capable of creating scripts from specifications. |
def _get_logger(self, handler):
''' Initialize a PCAP stream for logging data '''
log_file = self._get_log_file(handler)
if not os.path.isdir(os.path.dirname(log_file)):
os.makedirs(os.path.dirname(log_file))
handler['log_rot_time'] = time.gmtime()
return pcap.open(... | Can you implement a function in Python 3 that
initializes a PCAP stream for logging data | You are a Python code generator, capable of creating scripts from specifications. |
def add_logger(self, name, address, conn_type, log_dir_path=None, **kwargs):
''' Add a new stream capturer to the manager.
Add a new stream capturer to the manager with the provided configuration
details. If an existing capturer is monitoring the same address the
new handler will be add... | Can you create a Python 3 function that
adds a new capturer to the manager. | You are a Python code architect, reviewing and designing scalable and efficient code |
def stop_capture_handler(self, name):
''' Remove all handlers with a given name
Args:
name:
The name of the handler(s) to remove.
'''
empty_capturers_indeces = []
for k, sc in self._stream_capturers.iteritems():
stream_capturer = sc[0]
... | Can you create a Python 3 function that
stops capture handler with a given name. | You are a Python code architect, reviewing and designing scalable and efficient code |
def stop_stream_capturer(self, address):
''' Stop a capturer that the manager controls.
Args:
address:
An address array of the form ['host', 'port'] or similar
depending on the connection type of the stream capturer being
terminated. The captu... | How would you code a function in Python 3 to
stop a capturer that the manager controls. | As a python code expert, you are capable of creating scripts from specifications. |
def rotate_capture_handler_log(self, name):
''' Force a rotation of a handler's log file
Args:
name:
The name of the handler who's log file should be rotated.
'''
for sc_key, sc in self._stream_capturers.iteritems():
for h in sc[0].capture_handler... | Write a Python 3 function that can
force a rotation of a handler s log file | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return data on managed loggers.
Returns a dictionary of managed loggers. | Explain what the following Python 3 code does
def get_logger_data(self):
''' Return data on managed loggers.
Returns a dictionary of managed logger configuration data. The format
is primarily controlled by the
:func:`SocketStreamCapturer.dump_handler_config_data` function::
... | As a python code expert, you are capable of creating scripts from specifications. |
def get_handler_stats(self):
''' Return handler read statistics
Returns a dictionary of managed handler data read statistics. The
format is primarily controlled by the
:func:`SocketStreamCapturer.dump_all_handler_stats` function::
{
<capture address>: <list ... | Write a Python 3 script for
returning handler read statistics Returns a dictionary of managed handler read statistics. The format is primarily controlled by the SocketStreamCapturer. dump_all_handler_stats | As a python code expert, you are capable of creating scripts from specifications. |
Return data for a given name. | Explain what the following Python 3 code does
def get_capture_handler_config_by_name(self, name):
''' Return data for handlers of a given name.
Args:
name:
Name of the capture handler(s) to return config data for.
Returns:
Dictionary dump from the named ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Start monitoring managed loggers. | How would you explain what the following Python 3 function does
def run_socket_event_loop(self):
''' Start monitoring managed loggers. '''
try:
while True:
self._pool.join()
# If we have no loggers we'll sleep briefly to ensure that we
# allow... | You are a Python code architect, reviewing and designing scalable and efficient code |
Handles server route instantiation. | Can you tell what is the following Python 3 function doing
def _route(self):
''' Handles server route instantiation. '''
self._app.route('/',
method='GET',
callback=self._get_logger_list)
self._app.route('/stats',
method='GE... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _add_logger_by_name(self, name):
''' Handles POST requests for adding a new logger.
Expects logger configuration to be passed in the request's query string.
The logger name is included in the URL and the address components and
connection type should be included as well. The loc attr... | How would you code a function in Python 3 to
handle POST requests for adding a new logger. | As a python code expert, you are capable of creating scripts from specifications. |
Recursive handling of includes for any input list of defns. | How would you explain what the following Python 3 function does
def handle_includes(defns):
'''Recursive handling of includes for any input list of defns.
The assumption here is that when an include is handled by the
pyyaml reader, it adds them as a list, which is stands apart from the rest
of the expec... | You are a Python code architect, reviewing and designing scalable and efficient code |
def eval(self, packet):
"""Returns the result of evaluating this DNToEUConversion in the
context of the given Packet.
"""
result = None
terms = None
if self._when is None or self._when.eval(packet):
result = self._equation.eval(packet)
return result | Write a Python 3 function that can
return the result of evaluating this DNToEUConversion in the context of the given Packet. | You are a Python code analyst, evaluating scripts for potential improvements. |
def validate(self, value, messages=None):
"""Returns True if the given field value is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
primitive = value
def log(msg):
if messages is not... | Write a Python 3 script to
return True if the given field value is valid False otherwise. | As a python code expert, you are capable of creating scripts from specifications. |
def decode(self, bytes, raw=False, index=None):
"""Decodes the given bytes according to this Field Definition.
If raw is True, no enumeration substitutions will be applied
to the data returned.
If index is an integer or slice (and the type of this
FieldDefinition is an ArrayTyp... | Write a Python 3 function that can
decode the given bytes according to this Field Definition. | You are a Python code architect, reviewing and designing scalable and efficient code |
Encodes the given value according to this FieldDefinition. | Given the following Python 3 function, write the documentation
def encode(self, value):
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
if type(value) == int:
if self.shift > 0:
value <<= self.shift
if self.mask is... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a Python slice object that is used to retrieve the start and stop byte positions of this Telemetry field. | Explain what the following Python 3 code does
def slice(self, offset=0):
if self.bytes is None:
start = 0
stop = start + self.nbytes
elif type(self.bytes) is int:
start = self.bytes
stop = start + self.nbytes
else:
start = self.bytes[... | As a python code expert, you are capable of creating scripts from specifications. |
Raise AttributeError when Packet has no field with the given fieldname. | Can you tell what is the following Python 3 function doing
def _assertField(self, fieldname):
if not self._hasattr(fieldname):
values = self._defn.name, fieldname
raise AttributeError("Packet '%s' has no field '%s'" % values) | You are a Python code analyst, evaluating scripts for potential improvements. |
def _getattr (self, fieldname, raw=False, index=None):
"""Returns the value of the given packet field name.
If raw is True, the field value is only decoded. That is no
enumeration substituions or DN to EU conversions are applied.
"""
self._assertField(fieldname)
value =... | Write a Python 3 script for
returning the value of the given field name. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _hasattr(self, fieldname):
"""Returns True if this packet contains fieldname, False otherwise."""
special = 'history', 'raw'
return (fieldname in special or
fieldname in self._defn.fieldmap or
fieldname in self._defn.derivationmap) | Can you write a function in Python 3 where it
returns True if this packet contains fieldname False otherwise. | As a Python code translator, you convert algorithms and pseudocode into Python. |
The number of bytes for this telemetry packet | Make a summary of the following Python 3 code
def nbytes(self):
max_byte = -1
for defn in self.fields:
byte = defn.bytes if type(defn.bytes) is int else max(defn.bytes)
max_byte = max(max_byte, byte)
return max_byte + 1 | As a Python code analyst, you investigate and solve complex coding mysteries |
def validate(self, pkt, messages=None):
"""Returns True if the given Packet is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
for f in self.fields:
try:
value = getattr(pkt, f.nam... | Write a Python 3 script for
returning True if the given Packet is valid False otherwise. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the result of evaluating this PacketExpression in the
context of the given Packet. | Can you tell what is the following Python 3 function doing
def eval(self, packet):
try:
context = createPacketContext(packet)
result = eval(self._code, packet._defn.globals, context)
except ZeroDivisionError:
result = None
return result | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _assertField(self, name):
"""Raise AttributeError when PacketHistory has no field with the given
name.
"""
if name not in self._names:
msg = 'PacketHistory "%s" has no field "%s"'
values = self._defn.name, name
raise AttributeError(msg % values) | Can you implement a function in Python 3 that
raises AttributeError when PacketHistory has no field with the given name. | As a Python code analyst, you investigate and solve complex coding mysteries |
def add(self, packet):
"""Add the given Packet to this PacketHistory."""
for name in self._names:
value = getattr(packet, name)
if value is not None:
self._dict[name] = value | How would you implement a function in Python 3 that
adds the given Packet to this PacketHistory. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Adds the given Packet Definition to this Telemetry Dictionary. | How would you explain what the following Python 3 function does
def add(self, defn):
if defn.name not in self:
self[defn.name] = defn
else:
msg = "Duplicate packet name '%s'" % defn.name
log.error(msg)
raise util.YAMLError(msg) | As a python code expert, you are capable of creating scripts from specifications. |
Creates a new packet with the given definition and raw data. | Can you tell what is the following Python 3 function doing
def create(self, name, data=None):
return createPacket(self[name], data) if name in self else None | You are a Python code generator, capable of creating scripts from specifications. |
def load(self, content):
"""Loads Packet Definitions from the given YAML content into this
Telemetry Dictionary. Content may be either a filename
containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename or ... | Create a Python 3 function to
load Packet Definitions from the given YAML content into this Telemetry Dictionary. | You are a Python code analyst, evaluating scripts for potential improvements. |
writeToCSV - write the telemetry dictionary to CSV | How would you explain what the following Python 3 function does
def writeToCSV(self, output_path=None):
'''writeToCSV - write the telemetry dictionary to csv
'''
header = ['Name', 'First Byte', 'Last Byte', 'Bit Mask', 'Endian',
'Type', 'Description', 'Values']
if outp... | You are a Python code analyst, evaluating scripts for potential improvements. |
Decodes the given bytes according to this AIT Argument
Definition. | Can you generate a brief explanation for the following Python 3 code
def decode(self, bytes):
value = self.type.decode(bytes)
if self._enum is not None:
for name, val in self._enum.items():
if value == val:
value = name
break
re... | You are a Python code analyst, evaluating scripts for potential improvements. |
Encodes the given value according to this AIT Argument
Definition. | How would you explain what the following Python 3 function does
def encode(self, value):
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
return self.type.encode(value) if self.type else bytearray() | As a Python code composer, you craft elegant and concise scripts. |
def validate(self, value, messages=None):
"""Returns True if the given Argument value is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
primitive = value
def log(msg):
if messages is ... | Write a Python 3 function that can
return True if the given Argument value is valid False otherwise. | You are a Python code analyst, evaluating scripts for potential improvements. |
def encode(self, pad=106):
"""Encodes this AIT command to binary.
If pad is specified, it indicates the maximum size of the encoded
command in bytes. If the encoded command is less than pad, the
remaining bytes are set to zero.
Commands sent to ISS payloads over 1553 are limit... | How would you code a function in Python 3 to
encode this AIT command to binary. | You are a Python code architect, reviewing and designing scalable and efficient code |
The number of bytes required to encode this command. | Can you generate a brief explanation for the following Python 3 code
def nbytes(self):
return len(self.opcode) + 1 + sum(arg.nbytes for arg in self.argdefns) | As a Python code analyst, you investigate and solve complex coding mysteries |
The total size in bytes of all the command arguments. | Can you generate the documentation for the following Python 3 function
def argsize(self):
argsize = sum(arg.nbytes for arg in self.argdefns)
return argsize if len(self.argdefns) > 0 else 0 | As a Python code composer, you craft elegant and concise scripts. |
Returns True if the given Command is valid False otherwise. Messages are appended to an optional messages array. Messages are appended to an optional messages array. Messages are appended to an optional messages array. | Explain what the following Python 3 code does
def validate(self, cmd, messages=None):
valid = True
args = [ arg for arg in cmd.args if arg is not None ]
if self.nargs != len(args):
valid = False
if messages is not None:
msg = 'Expected %d arguments, but... | As a python code expert, you are capable of creating scripts from specifications. |
def add(self, defn):
"""Adds the given Command Definition to this Command Dictionary."""
self[defn.name] = defn
self.opcodes[defn._opcode] = defn | How would you code a function in Python 3 to
add the given Command Definition to this Command Dictionary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates a new AIT command with the given arguments. | Here you have a function in Python 3, explain what it does
def create(self, name, *args, **kwargs):
tokens = name.split()
if len(tokens) > 1 and (len(args) > 0 or len(kwargs) > 0):
msg = 'A Cmd may be created with either positional arguments '
msg += '(passed as a string or a P... | As a Python code analyst, you investigate and solve complex coding mysteries |
Decodes the given bytes according to this AIT Command
Definition. | Can you tell what is the following Python 3 function doing
def decode(self, bytes):
opcode = struct.unpack(">H", bytes[0:2])[0]
nbytes = struct.unpack("B", bytes[2:3])[0]
name = None
args = []
if opcode in self.opcodes:
defn = self.opcodes[opcode]
... | You are a Python code generator, capable of creating scripts from specifications. |
def load(self, content):
"""Loads Command Definitions from the given YAML content into
into this Command Dictionary. Content may be either a
filename containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename... | How would you code a function in Python 3 to
load Command Definitions from the given YAML content into this Command Dictionary. | You are a Python code architect, reviewing and designing scalable and efficient code |
def cbrt (x):
"""Returns the cube root of x."""
if x >= 0:
return math.pow(x , 1.0 / 3.0)
else:
return - math.pow(abs(x), 1.0 / 3.0) | Write a Python 3 script for
returning the cube root of x. | As a Python code composer, you craft elegant and concise scripts. |
def eci2ecef (x, y, z, gmst=None):
"""Converts the given ECI coordinates to ECEF at the given Greenwich
Mean Sidereal Time (GMST) (defaults to now).
This code was adapted from
`shashwatak/satellite-js <https://github.com/shashwatak/satellite-js/blob/master/src/coordinate-transforms.js>`_
and http://ccar.co... | Implement a function in Python 3 to
convert the given ECI coordinates to ECEF at the given Greenwich Mean Sidereal Time. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.