output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def sink(wrapped):
"""Creates an SPL operator with a single input port.
A SPL operator with a single input port and no output ports.
For each tuple on the input port the decorated function
is called passing the contents of the tuple.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.f... | Can you write a function in Python 3 where it
creates an SPL operator with a single input port and no output ports. | As a Python code analyst, you investigate and solve complex coding mysteries |
Submit a tuple to the output port. | Given the following Python 3 function, write the documentation
def submit(self, port_id, tuple_):
port_index = self._splpy_output_ports[port_id]
ec._submit(self, port_index, tuple_) | You are a Python code generator, capable of creating scripts from specifications. |
def _splpy_convert_tuple(attributes):
"""Create a function that converts tuples to
be submitted as dict objects into Python tuples
with the value by position.
Return function handles tuple,dict,list[tuple|dict|None],None
"""
def _to_tuples(tuple_):
if isinstance(tuple_, tuple):
... | How would you implement a function in Python 3 that
creates a function that converts tuples to be submitted as dict objects into Python tuples with the value by position. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _splpy_primitive_input_fns(obj):
"""Convert the list of class input functions to be
instance functions against obj.
Used by @spl.primitive_operator SPL cpp template.
"""
ofns = list()
for fn in obj._splpy_input_ports:
ofns.append(getattr(obj, fn.__name__))
return ofns | Write a Python 3 function that can
convert the list of class input functions to be instance functions against obj. | As a python code expert, you are capable of creating scripts from specifications. |
def _splpy_all_ports_ready(callable_):
"""Call all_ports_ready for a primitive operator."""
if hasattr(type(callable_), 'all_ports_ready'):
try:
return callable_.all_ports_ready()
except:
ei = sys.exc_info()
if streamsx._streams._runtime._call_exit(callable_, ... | Implement a Python 3 function for
calling all_ports_ready for a primitive operator. | You are a Python code architect, reviewing and designing scalable and efficient code |
Sets trace for the current IKP3db object. | Can you generate a brief explanation for the following Python 3 code
def set_trace(a_frame=None):
if not ikpdb:
return "Error: IKP3db must be launched before calling ikpd.set_trace()."
if a_frame is None:
a_frame = sys._getframe().f_back
ikpdb._line_tracer(a_frame)
return None | You are a Python code architect, reviewing and designing scalable and efficient code |
def post_mortem(trace_back=None, exc_info=None):
""" Breaks on a traceback and send all execution information to the debugger
client. If the interpreter is handling an exception at this traceback,
exception information is sent to _line_tracer() which will transmit it to
the debugging client.
Call... | How would you implement a function in Python 3 that
breaks on a traceback and send all execution information to the debugger client. If the interpreter is handling an exception at this traceback, exception information is sent to _line_tracer() which will transmit it to the debugging client. Caller can also pass an *exc... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function sets up the IKPdbLogger class. | How would you explain what the following Python 3 function does
def setup(cls, ikpdb_log_arg):
if not ikpdb_log_arg:
return
IKPdbLogger.enabled = True
logging_configuration_string = ikpdb_log_arg.lower()
for letter in logging_configuration_string:
if lett... | You are a Python code architect, reviewing and designing scalable and efficient code |
def send(self, command, _id=None, result={}, frames=[], threads=None,
error_messages=[], warning_messages=[], info_messages=[],
exception=None):
""" Build a message from parameters and send it to debugger.
:param command: The command sent to the debugger client.
... | Write a Python 3 script to
send a message to the debugger. | You are a Python code architect, reviewing and designing scalable and efficient code |
Builds a response from a previouslsy received command message and send it to the debugger client. | Here you have a function in Python 3, explain what it does
def reply(self, obj, result, command_exec_status='ok', info_messages=[],
warning_messages=[], error_messages=[]):
"""Build a response from a previouslsy received command message, send it
and return number of sent bytes.
... | As a python code expert, you are capable of creating scripts from specifications. |
Waits for a message from the debugger and returns it as a dict. | Explain what the following Python 3 code does
def receive(self, ikpdb):
# with self._connection_lock:
while self._network_loop:
_logger.n_debug("Enter socket.recv(%s) with self._received_data = %s",
self.SOCKET_BUFFER_SIZE,
self._rece... | You are a Python code architect, reviewing and designing scalable and efficient code |
Clear a breakpoint by removing it from all lists. | Given the following Python 3 function, write the documentation
def clear(self):
del IKBreakpoint.breakpoints_by_file_and_line[self.file_name, self.line_number]
IKBreakpoint.breakpoints_by_number[self.number] = None
IKBreakpoint.breakpoints_files[self.file_name].remove(self.line_number)
i... | As a python code expert, you are capable of creating scripts from specifications. |
Checks all breakpoints to find wether at least one is active and updates any_active_breakpoint attribute. | How would you explain what the following Python 3 function does
def update_active_breakpoint_flag(cls):
cls.any_active_breakpoint=any([bp.enabled for bp in cls.breakpoints_by_number if bp]) | As a Python code composer, you craft elegant and concise scripts. |
Checks if there is an enabled breakpoint at given file_name and line_number. Check if any. cke_condition is set to True. | Can you generate the documentation for the following Python 3 function
def lookup_effective_breakpoint(cls, file_name, line_number, frame):
bp = cls.breakpoints_by_file_and_line.get((file_name, line_number), None)
if not bp:
return None
if not bp.enabled:
ret... | You are a Python code architect, reviewing and designing scalable and efficient code |
returns a list of all breakpoints. | Can you tell what is the following Python 3 function doing
def get_breakpoints_list(cls):
breakpoints_list = []
for bp in cls.breakpoints_by_number:
if bp: # breakpoint #0 exists and is always None
bp_dict = {
'breakpoint_number': bp.number,
... | As a Python code composer, you craft elegant and concise scripts. |
def disable_all_breakpoints(cls):
""" Disable all breakpoints and udate `active_breakpoint_flag`.
"""
for bp in cls.breakpoints_by_number:
if bp: # breakpoint #0 exists and is always None
bp.enabled = False
cls.update_active_breakpoint_flag()
return | Create a Python 3 function to
disable all breakpoints and udate active_breakpoint_flag. | As a Python code composer, you craft elegant and concise scripts. |
Returns the state of all breakpoints in a list that can be used
later to restore all breakpoints state | Given the following Python 3 function, write the documentation
def backup_breakpoints_state(cls):
all_breakpoints_state = []
for bp in cls.breakpoints_by_number:
if bp:
all_breakpoints_state.append((bp.number,
bp.enabled,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Restore the state of breakpoints given a list provided by
backup_breakpoints_state(). If list of breakpoints has changed
since backup missing or added breakpoints are ignored. | Given the following Python 3 function, write the documentation
def restore_breakpoints_state(cls, breakpoints_state_list):
for breakpoint_state in breakpoints_state_list:
bp = cls.breakpoints_by_number[breakpoint_state[0]]
if bp:
bp.enabled = breakpoint_state[1]
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
returns a canonical version of a file name. | Given the following Python 3 function, write the documentation
def canonic(self, file_name):
if file_name == "<" + file_name[1:-1] + ">":
return file_name
c_file_name = self.file_name_cache.get(file_name)
if not c_file_name:
c_file_name = os.path.abspath(file_name)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def normalize_path_in(self, client_file_name):
"""Translate a (possibly incomplete) file or module name received from debugging client
into an absolute file name.
"""
_logger.p_debug("normalize_path_in(%s) with os.getcwd()=>%s", client_file_name, os.getcwd())
# remove cl... | Can you implement a function in Python 3 that
translates a file or module name received from debugging client into an absolute file name. | As a Python code analyst, you investigate and solve complex coding mysteries |
def normalize_path_out(self, path):
"""Normalizes path sent to client
:param path: path to normalize
:return: normalized path
"""
if path.startswith(self._CWD):
normalized_path = path[len(self._CWD):]
else:
normalized_path = path
# For remo... | Can you write a function in Python 3 where it
normalizes path sent to client | You are a Python code generator, capable of creating scripts from specifications. |
Returns the number of user browsable properties of an object. | Can you tell what is the following Python 3 function doing
def object_properties_count(self, o):
o_type = type(o)
if isinstance(o, (dict, list, tuple, set)):
return len(o)
elif isinstance(o, (type(None), bool, float,
str, int,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Extracts all properties from an object and returns them as a list of variables. | Can you tell what is the following Python 3 function doing
def extract_object_properties(self, o, limit_size=False):
try:
prop_str = repr(o)[:512]
except:
prop_str = "Error while extracting value"
_logger.e_debug("extract_object_properties(%s)", prop_str)
var_lis... | You are a Python code architect, reviewing and designing scalable and efficient code |
Extracts value of any object eventually reduces it s size and returns name truncated value and type | Explain what the following Python 3 code does
def extract_name_value_type(self, name, value, limit_size=False):
MAX_STRING_LEN_TO_RETURN = 487
try:
t_value = repr(value)
except:
t_value = "Error while extracting value"
# convert all var names to string
if... | You are a Python code generator, capable of creating scripts from specifications. |
def dump_frames(self, frame):
""" dumps frames chain in a representation suitable for serialization
and remote (debugger) client usage.
"""
current_thread = threading.currentThread()
frames = []
frame_browser = frame
# Browse the frame chain as far as... | Create a Python 3 function for
dumping the given frame in a representation suitable for serialization and remote client usage. | As a Python code analyst, you investigate and solve complex coding mysteries |
def evaluate(self, frame_id, expression, global_context=False, disable_break=False):
"""Evaluates 'expression' in the context of the frame identified by
'frame_id' or globally.
Breakpoints are disabled depending on 'disable_break' value.
Returns a tuple of value and type both as str.
... | Create a Python 3 function for
evaluating expression in the context of the frame identified by frame_id or globally. | You are a Python code architect, reviewing and designing scalable and efficient code |
Let a frame s var with a value by building then eval a let
expression with breakoints disabled. | Make a summary of the following Python 3 code
def let_variable(self, frame_id, var_name, expression_value):
breakpoints_backup = IKBreakpoint.backup_breakpoints_state()
IKBreakpoint.disable_all_breakpoints()
let_expression = "%s=%s" % (var_name, expression_value,)
eval_frame = ctypes.c... | As a python code expert, you are capable of creating scripts from specifications. |
Setup debugger for a stepInto | Make a summary of the following Python 3 code
def setup_step_into(self, frame, pure=False):
self.frame_calling = frame
if pure:
self.frame_stop = None
else:
self.frame_stop = frame
self.frame_return = None
self.frame_suspend = False
self.pending_st... | You are a Python code generator, capable of creating scripts from specifications. |
Setup debugger to suspend execution
| Here you have a function in Python 3, explain what it does
def setup_suspend(self):
self.frame_calling = None
self.frame_stop = None
self.frame_return = None
self.frame_suspend = True
self.pending_stop = True
self.enable_tracing()
return | As a Python code analyst, you investigate and solve complex coding mysteries |
Checks if debugger should stop at the current location. | Given the following Python 3 function, write the documentation
def should_stop_here(self, frame):
# TODO: Optimization => defines a set of modules / names where _tracer
# is never registered. This will replace skip
#if self.skip and self.is_skipped_module(frame.f_globals.get('__name__')):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def should_break_here(self, frame):
"""Check wether there is a breakpoint at this frame."""
# Next line commented out for performance
#_logger.b_debug("should_break_here(filename=%s, lineno=%s) with breaks=%s",
# frame.f_code.co_filename,
# frame.f_l... | Implement a function in Python 3 to
check if there is a breakpoint at this frame. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_threads(self):
"""Returns a dict of all threads and indicates thread being debugged.
key is thread ident and values thread info.
Information from this list can be used to swap thread being debugged.
"""
thread_list = {}
for thread in threading.enumerate():
... | Write a Python 3 script for
returning a dict of all threads and indicates thread being debugged. | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_debugged_thread(self, target_thread_ident=None):
""" Allows to reset or set the thread to debug. """
if target_thread_ident is None:
self.debugged_thread_ident = None
self.debugged_thread_name = ''
return {
"result": self.get_threads(),
... | Implement a function in Python 3 to
allow to reset or set the thread to debug. | You are a Python code architect, reviewing and designing scalable and efficient code |
Enable tracing if it is disabled and debugged program is running. | Make a summary of the following Python 3 code
def enable_tracing(self):
_logger.x_debug("entering enable_tracing()")
# uncomment next line to get debugger tracing info
#self.dump_tracing_state("before enable_tracing()")
if not self.tracing_enabled and self.execution_started:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def disable_tracing(self):
""" Disable tracing if it is disabled and debugged program is running,
else do nothing.
:return: False if tracing has been disabled, True else.
"""
_logger.x_debug("disable_tracing()")
#self.dump_tracing_state("before disable_tracing()")
... | Write a Python 3 function for
disabling tracing if tracing is enabled and debugged program is running. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a breakpoint and register it in the class s lists and returns the breakpoint number and error message. | How would you explain what the following Python 3 function does
def set_breakpoint(self, file_name, line_number, condition=None, enabled=True):
c_file_name = self.canonic(file_name)
import linecache
line = linecache.getline(c_file_name, line_number)
if not line:
return "Line ... | As a Python code composer, you craft elegant and concise scripts. |
def change_breakpoint_state(self, bp_number, enabled, condition=None):
""" Change breakpoint status or `condition` expression.
:param bp_number: number of breakpoint to change
:return: None or an error message (string)
"""
if not (0 <= bp_number < len(IKBreakpoint.break... | How would you implement a function in Python 3 that
changes the state of a breakpoint or condition expression. | As a Python code analyst, you investigate and solve complex coding mysteries |
def clear_breakpoint(self, breakpoint_number):
""" Delete a breakpoint identified by it's number.
:param breakpoint_number: index of breakpoint to delete
:type breakpoint_number: int
:return: an error message or None
"""
if not (0 <= breakpoint_number < len(IKB... | Write a Python 3 function that can
delete a breakpoint identified by it s number. | You are a Python code generator, capable of creating scripts from specifications. |
def _runscript(self, filename):
""" Launchs debugged program execution using the execfile() builtin.
We reset and setup the __main__ dict to allow the script to run
in __main__ namespace. This is required for imports from __main__ to
run correctly.
Note tha... | Can you implement a function in Python 3 that
launches debugged program execution using execfile. | As a Python code composer, you craft elegant and concise scripts. |
This is the debugger command loop that processes client - specific requests. | Explain what the following Python 3 code does
def command_loop(self, run_script_event):
while True:
obj = remote_client.receive(self)
command = obj["command"]
# TODO: ensure we always have a command if receive returns
args = obj.get('args', {})
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_elements(self, url, key, eclass, id=None, name=None):
"""Get elements matching `id` or `name`
Args:
url(str): url of children.
key(str): key in the returned JSON.
eclass(subclass type of :py:class:`_ResourceElement`): element class to create instances of.
... | Write a Python 3 script for
getting elements matching id or name | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get a single element matching an id | Make a summary of the following Python 3 code
def _get_element_by_id(self, url, key, eclass, id):
elements = self._get_elements(url, key, eclass, id=id)
if not elements:
raise ValueError("No resource matching: {0}".format(id))
if len(elements) == 1:
return elements[0]
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_domain(self):
"""Get the Streams domain for the instance that owns this view.
Returns:
Domain: Streams domain for the instance owning this view.
"""
if hasattr(self, 'domain'):
return Domain(self.rest_client.make_request(self.domain), self.rest_client) | Implement a function in Python 3 to
get the Streams domain for the instance that owns this view. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the instance that owns this view. | Make a summary of the following Python 3 code
def get_instance(self):
return Instance(self.rest_client.make_request(self.instance), self.rest_client) | You are a Python code generator, capable of creating scripts from specifications. |
def get_job(self):
"""Get the Streams job that owns this view.
Returns:
Job: Streams Job owning this view.
"""
return Job(self.rest_client.make_request(self.job), self.rest_client) | How would you code a function in Python 3 to
return the Streams Job that owns this view. | As a Python code analyst, you investigate and solve complex coding mysteries |
def stop_data_fetch(self):
"""Stops the thread that fetches data from the Streams view server.
"""
if self._data_fetcher:
self._data_fetcher.stop.set()
self._data_fetcher = None | Write a Python 3 script to
stop the thread that fetches data from the Streams view server. | You are a Python code analyst, evaluating scripts for potential improvements. |
Starts a thread that fetches data from the Streams view server. | Explain what the following Python 3 code does
def start_data_fetch(self):
self.stop_data_fetch()
self._data_fetcher = _ViewDataFetcher(self, self._tuple_fn)
t = threading.Thread(target=self._data_fetcher)
t.start()
return self._data_fetcher.items | As a python code expert, you are capable of creating scripts from specifications. |
Fetch a number of tuples from this view. | Can you generate the documentation for the following Python 3 function
def fetch_tuples(self, max_tuples=20, timeout=None):
tuples = list()
if timeout is None:
while len(tuples) < max_tuples:
fetcher = self._data_fetcher
if not fetcher:
bre... | As a Python code composer, you craft elegant and concise scripts. |
def display(self, duration=None, period=2):
"""Display a view within a Jupyter or IPython notebook.
Provides an easy mechanism to visualize data on a stream
using a view.
Tuples are fetched from the view and displayed in a table
within the notebook cell using a ``pandas.DataFra... | Write a Python 3 function for
displaying a view within a Jupyter or IPython notebook cell. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_view_items(self):
"""Get a list of :py:class:`ViewItem` elements associated with this view.
Returns:
list(ViewItem): List of ViewItem(s) associated with this view.
"""
view_items = [ViewItem(json_view_items, self.rest_client) for json_view_items
... | Can you write a function in Python 3 where it
gets a list of ViewItem elements associated with this view. | You are a Python code generator, capable of creating scripts from specifications. |
def retrieve_log_trace(self, filename=None, dir=None):
"""Retrieves the application log and trace files of the job
and saves them as a compressed tar file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the created tar file. Defaults ... | Implement a Python 3 function for
retrieving the application log and trace files of the job and saves them as a compressed tar file. | You are a Python code generator, capable of creating scripts from specifications. |
Get the list of views associated with this job. | Explain what the following Python 3 code does
def get_views(self, name=None):
return self._get_elements(self.views, 'views', View, name=name) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_operators(self, name=None):
"""Get the list of :py:class:`Operator` elements associated with this job.
Args:
name(str): Only return operators matching `name`, where `name` can be a regular expression. If
`name` is not supplied, then all operators for this job are re... | Implement a function in Python 3 to
get the list of Operator elements associated with this job. | As a Python code analyst, you investigate and solve complex coding mysteries |
def cancel(self, force=False):
"""Cancel this job.
Args:
force (bool, optional): Forcefully cancel this job.
Returns:
bool: True if the job was cancelled, otherwise False if an error occurred.
"""
return self.rest_client._sc._delegator._cancel_job(self, ... | Create a Python 3 function for
canceling this job. Args: force (bool, optional): Forcefully cancel this job. Returns: bool: True if the job was cancelled, otherwise False if an error occurred. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_metrics(self, name=None):
"""Get metrics for this operator.
Args:
name(str, optional): Only return metrics matching `name`, where `name` can be a regular expression. If
`name` is not supplied, then all metrics for this operator are returned.
Returns:
... | Write a Python 3 script for
getting metrics for this operator. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the resource this operator is currently executing in. | Here you have a function in Python 3, explain what it does
def get_host(self):
if hasattr(self, 'host') and self.host:
return Host(self.rest_client.make_request(self.host), self.rest_client) | As a Python code composer, you craft elegant and concise scripts. |
Get the processing element this operator is executing in. | Make a summary of the following Python 3 code
def get_pe(self):
return PE(self.rest_client.make_request(self.pe), self.rest_client) | You are a Python code architect, reviewing and designing scalable and efficient code |
def retrieve_trace(self, filename=None, dir=None):
"""Retrieves the application trace files for this PE
and saves them as a plain text file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the created file. Defaults to `pe_<id>_<timest... | Write a Python 3 function that can
retrieve the application trace files for this PE and saves them as plain text files. | You are a Python code architect, reviewing and designing scalable and efficient code |
Retrieves the application console log for this PE and saves them as plain text files. | Make a summary of the following Python 3 code
def retrieve_console_log(self, filename=None, dir=None):
if hasattr(self, "consoleLog") and self.consoleLog is not None:
logger.debug("Retrieving PE console log: " + self.consoleLog)
if not filename:
filename = _file_name('pe'... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the : py : class : ResourceAllocation element tance. | Can you tell what is the following Python 3 function doing
def get_resource_allocation(self):
if hasattr(self, 'resourceAllocation'):
return ResourceAllocation(self.rest_client.make_request(self.resourceAllocation), self.rest_client) | As a python code expert, you are capable of creating scripts from specifications. |
Get the resource of the resource allocation. | Can you generate a brief explanation for the following Python 3 code
def get_resource(self):
return Resource(self.rest_client.make_request(self.resource), self.rest_client) | As a Python code analyst, you investigate and solve complex coding mysteries |
Retrieves jobs running on this resource in its instance. | Can you generate a brief explanation for the following Python 3 code
def get_jobs(self, name=None):
if self.applicationResource:
return self._get_elements(self.jobs, 'jobs', Job, None, name)
else:
return [] | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the OperatorOutputPort object for this exported stream. | How would you explain what the following Python 3 function does
def get_operator_output_port(self):
return OperatorOutputPort(self.rest_client.make_request(self.operatorOutputPort), self.rest_client) | As a Python code composer, you craft elegant and concise scripts. |
def of_service(config):
"""Connect to an IBM Streams service instance running in IBM Cloud Private for Data.
The instance is specified in `config`. The configuration may be code injected from the list of services
in a Jupyter notebook running in ICPD or manually created. The code that selects a... | Can you create a Python 3 function that
connects to an IBM Streams service instance. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_job(self, id):
"""Retrieves a job matching the given `id`
Args:
id (str): Job `id` to match.
Returns:
Job: Job matching the given `id`
Raises:
ValueError: No resource matches given `id` or multiple resources matching given `id`
"""
... | Write a Python 3 function for
retrieving a job matching the given id | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_published_topics(self):
"""Get a list of published topics for this instance.
Streams applications publish streams to a a topic that can be subscribed to by other
applications. This allows a microservice approach where publishers
and subscribers are independent of each other.
... | Write a Python 3 script to
get a list of currently published topics for this instance. | As a Python code composer, you craft elegant and concise scripts. |
def get_application_configurations(self, name=None):
"""Retrieves application configurations for this instance.
Args:
name (str, optional): Only return application configurations containing property **name** that matches `name`. `name` can be a
regular expression. If `name` ... | How would you code a function in Python 3 to
retrieve application configurations for this instance. | As a Python code composer, you craft elegant and concise scripts. |
Create an application configuration. | Explain what the following Python 3 code does
def create_application_configuration(self, name, properties, description=None):
if not hasattr(self, 'applicationConfigurations'):
raise NotImplementedError()
cv = ApplicationConfiguration._props(name, properties, description)
res = sel... | You are a Python code architect, reviewing and designing scalable and efficient code |
def submit_job(self, bundle, job_config=None):
"""Submit a Streams Application Bundle (sab file) to
this Streaming Analytics service.
Args:
bundle(str): path to a Streams application bundle (sab file)
containing the application to be submitted
job... | Write a Python 3 function for
submitting a new application bundle to this Streaming Analytics service. | As a Python code composer, you craft elegant and concise scripts. |
def cancel_job(self, job_id=None, job_name=None):
"""Cancel a running job.
Args:
job_id (str, optional): Identifier of job to be canceled.
job_name (str, optional): Name of job to be canceled.
Returns:
dict: JSON response for the job cancel operation.
... | How would you code a function in Python 3 to
cancel a running job. | As a Python code composer, you craft elegant and concise scripts. |
Get & save jobs URL from the status call. | Can you tell what is the following Python 3 function doing
def _get_jobs_url(self):
if self._jobs_url is None:
self.get_instance_status()
if self._jobs_url is None:
raise ValueError("Cannot obtain jobs URL")
return self._jobs_url | You are a Python code architect, reviewing and designing scalable and efficient code |
def cancel_job(self, job_id=None, job_name=None):
"""Cancel a running job.
Args:
job_id (str, optional): Identifier of job to be canceled.
job_name (str, optional): Name of job to be canceled.
Returns:
dict: JSON response for the job cancel operation.
... | How would you implement a function in Python 3 that
cancels a running job. | You are a Python code generator, capable of creating scripts from specifications. |
Start the instance for this Streaming Analytics service. | Can you tell what is the following Python 3 function doing
def start_instance(self):
start_url = self._get_url('start_path')
res = self.rest_client.session.put(start_url, json={})
_handle_http_errors(res)
return res.json() | As a Python code translator, you convert algorithms and pseudocode into Python. |
def stop_instance(self):
"""Stop the instance for this Streaming Analytics service.
Returns:
dict: JSON response for the instance stop operation.
"""
stop_url = self._get_url('stop_path')
res = self.rest_client.session.put(stop_url, json={})
_handle_http_erro... | How would you implement a function in Python 3 that
stops the instance for this Streaming Analytics service. | You are a Python code generator, capable of creating scripts from specifications. |
Get the status of the instance for this Streaming Analytics service. | Make a summary of the following Python 3 code
def get_instance_status(self):
status_url = self._get_url('status_path')
res = self.rest_client.session.get(status_url)
_handle_http_errors(res)
return res.json() | You are a Python code architect, reviewing and designing scalable and efficient code |
def submit_job(self, job_config=None):
"""Submit this Streams Application Bundle (sab file) to
its associated instance.
Args:
job_config(JobConfig): a job configuration overlay
Returns:
Job: Resulting job instance.
"""
job_id = se... | How would you implement a function in Python 3 that
submits this Streams Application Bundle to its associated instance. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _cancel_job(self, job, force):
"""Cancel job using streamtool."""
import streamsx.st as st
if st._has_local_install:
return st._cancel_job(job.id, force,
domain_id=job.get_instance().get_domain().id, instance_id=job.get_instance().id)
return False | Implement a Python 3 function for
canceling the job using streamtool. | As a Python code composer, you craft elegant and concise scripts. |
def update(self, properties=None, description=None):
"""Update this application configuration.
To create or update a property provide its key-value
pair in `properties`.
To delete a property provide its key with the value ``None``
in properties.
Args:
prope... | Implement a Python 3 function for
updating this application configuration. | As a Python code composer, you craft elegant and concise scripts. |
Delete this application configuration. | Make a summary of the following Python 3 code
def delete(self):
res = self.rest_client.session.delete(self.rest_self)
_handle_http_errors(res) | As a python code expert, you are capable of creating scripts from specifications. |
Is schema an common schema? | Make a summary of the following Python 3 code
def is_common(schema):
if isinstance(schema, StreamSchema):
return schema.schema() in _SCHEMA_COMMON
if isinstance(schema, CommonSchema):
return True
if isinstance(schema, basestring):
return is_common(StreamSchema(schema))
return Fal... | As a python code expert, you are capable of creating scripts from specifications. |
def _set(self, schema):
"""Set a schema from another schema"""
if isinstance(schema, CommonSchema):
self._spl_type = False
self._schema = schema.schema()
self._style = self._default_style()
else:
self._spl_type = schema._spl_type
self._... | Write a Python 3 function that can
set a schema from another schema | As a python code expert, you are capable of creating scripts from specifications. |
Create a structured schema that will pass stream tuples into a tuple. | Can you tell what is the following Python 3 function doing
def as_tuple(self, named=None):
if not named:
return self._copy(tuple)
if named == True or isinstance(named, basestring):
return self._copy(self._make_named_tuple(name=named))
return self._copy(tuple) | As a Python code composer, you craft elegant and concise scripts. |
def extend(self, schema):
"""
Extend a structured schema by another.
For example extending ``tuple<rstring id, timestamp ts, float64 value>``
with ``tuple<float32 score>`` results in ``tuple<rstring id, timestamp ts, float64 value, float32 score>``.
Args:
schema(Str... | Write a Python 3 function that can
extend this schema by another schema. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _fnop_style(schema, op, name):
"""Set an operator's parameter representing the style of this schema."""
if is_common(schema):
if name in op.params:
del op.params[name]
return
if _is_pending(schema):
ntp = 'pending'
elif schema.style... | Write a Python 3 script to
set an operator s parameter representing the style of this schema. | You are a Python code analyst, evaluating scripts for potential improvements. |
def save(self) -> None:
"""
Saves all changed values to the database.
"""
for name, field in self.fields.items():
value = self.cleaned_data[name]
if isinstance(value, UploadedFile):
# Delete old file
fname = self._s.get(name, as_typ... | Implement a Python 3 function for
saving all changed values to the database. | You are a Python code generator, capable of creating scripts from specifications. |
def get_new_filename(self, name: str) -> str:
"""
Returns the file name to use based on the original filename of an uploaded file.
By default, the file name is constructed as::
<model_name>-<attribute_name>/<primary_key>/<original_basename>.<random_nonce>.<extension>
... | Can you create a Python 3 function that
returns the new filename based on the original filename of an uploaded file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Stop the service if no jobs are running unless force is set | Given the following Python 3 function, write the documentation
def _stop(sas, cmd_args):
if not cmd_args.force:
status = sas.get_instance_status()
jobs = int(status['job_count'])
if jobs:
return status
return sas.stop_instance() | As a Python code analyst, you investigate and solve complex coding mysteries |
Runs an action against a Streaming Analytics service. | Can you tell what is the following Python 3 function doing
def main(args=None):
streamsx._streams._version._mismatch_check('streamsx.topology.context')
try:
sr = run_cmd(args)
sr['return_code'] = 0
except:
sr = {'return_code':1, 'error': sys.exc_info()}
return sr | You are a Python code architect, reviewing and designing scalable and efficient code |
def _source_info():
"""
Get information from the user's code (two frames up)
to leave breadcrumbs for file, line, class and function.
"""
ofi = inspect.getouterframes(inspect.currentframe())[2]
try:
calling_class = ofi[0].f_locals['self'].__class__
except KeyError:
calling_cl... | Write a Python 3 function that can
get information from the user s code. | You are a Python code architect, reviewing and designing scalable and efficient code |
Declare a source stream that introduces tuples from an external source. | Can you tell what is the following Python 3 function doing
def source(self, func, name=None):
_name = name
if inspect.isroutine(func):
pass
elif callable(func):
pass
else:
if _name is None:
_name = type(func).__name__
func =... | As a Python code composer, you craft elegant and concise scripts. |
def subscribe(self, topic, schema=streamsx.topology.schema.CommonSchema.Python, name=None, connect=None, buffer_capacity=None, buffer_full_policy=None):
"""
Subscribe to a topic published by other Streams applications.
A Streams application may publish a stream to allow other
Streams app... | Implement a Python 3 function for
subscribing to a topic. | You are a Python code generator, capable of creating scripts from specifications. |
Adds a file or directory dependency into an Streams application bundle. | Can you generate a brief explanation for the following Python 3 code
def add_file_dependency(self, path, location):
if location not in {'etc', 'opt'}:
raise ValueError(location)
if not os.path.isfile(path) and not os.path.isdir(path):
raise ValueError(path)
path = os.pa... | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_pip_package(self, requirement):
"""
Add a Python package dependency for this topology.
If the package defined by the requirement specifier
is not pre-installed on the build system then the
package is installed using `pip` and becomes part
of the Streams applicati... | Create a Python 3 function for
adding a Python package dependency to the internal list of packages that are required by pip. | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a submission parameter. | Make a summary of the following Python 3 code
def create_submission_parameter(self, name, default=None, type_=None):
if name in self._submission_parameters:
raise ValueError("Submission parameter {} already defined.".format(name))
sp = streamsx.topology.runtime._SubmissionParam(name... | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate the info to create requirements. txt in the toookit. | Can you generate the documentation for the following Python 3 function
def _generate_requirements(self):
if not self._pip_packages:
return
reqs = ''
for req in self._pip_packages:
reqs += "{}\n".format(req)
reqs_include = {
'contents': reqs,
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a JobControlPlane operator to the topology if one has not already been added. | Can you generate the documentation for the following Python 3 function
def _add_job_control_plane(self):
if not self._has_jcp:
jcp = self.graph.addOperator(kind="spl.control::JobControlPlane", name="JobControlPlane")
jcp.viewable = False
self._has_jcp = True | As a Python code translator, you convert algorithms and pseudocode into Python. |
def aliased_as(self, name):
"""
Create an alias of this stream.
Returns an alias of this stream with name `name`.
When invocation of an SPL operator requires an
:py:class:`~streamsx.spl.op.Expression` against
an input port this can be used to ensure expression
ma... | How would you code a function in Python 3 to
create an alias of this stream with name equal to name. | As a Python code composer, you craft elegant and concise scripts. |
def view(self, buffer_time = 10.0, sample_size = 10000, name=None, description=None, start=False):
"""
Defines a view on a stream.
A view is a continually updated sampled buffer of a streams's tuples.
Views allow visibility into a stream from external clients such
as Jupyter Not... | How would you code a function in Python 3 to
create a view on a distributed topology. | You are a Python code architect, reviewing and designing scalable and efficient code |
def map(self, func=None, name=None, schema=None):
"""
Maps each tuple from this stream into 0 or 1 stream tuples.
For each tuple on this stream ``result = func(tuple)`` is called.
If `result` is not `None` then the result will be submitted
as a tuple on the returned stream. If `... | Write a Python 3 function for
mapping each tuple from this stream into 0 or 1 stream tuples. | You are a Python code architect, reviewing and designing scalable and efficient code |
def flat_map(self, func=None, name=None):
"""
Maps and flatterns each tuple from this stream into 0 or more tuples.
For each tuple on this stream ``func(tuple)`` is called.
If the result is not `None` then the the result is iterated over
with each value from the iterator that i... | Write a Python 3 function for
returning a Stream containing the flattened and mapped tuples. | 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.