output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Removes aliases from your config file that point to inactive projects.
Make a summary of the following Python 3 code def clean_aliases(ctx, force_yes): inactive_aliases = [] for (alias, mapping) in six.iteritems(aliases_database): # Ignore local aliases if mapping.mapping is None: continue project = ctx.obj['projects_db'].get(mapping.mapping[0...
As a Python code composer, you craft elegant and concise scripts.
def get_plugin_info(plugin): """ Fetch information about the given package on PyPI and return it as a dict. If the package cannot be found on PyPI, :exc:`NameError` will be raised. """ url = 'https://pypi.python.org/pypi/{}/json'.format(plugin) try: resp = request.urlopen(url) excep...
Write a Python 3 function for fetching information about the given plugin on PyPI and return it as a dict.
As a python code expert, you are capable of creating scripts from specifications.
Return a dict of installed plugins.
Can you tell what is the following Python 3 function doing def get_installed_plugins(): return { # Strip the first five characters from the plugin name since all # plugins are expected to start with `taxi-` backend.dist.project_name[5:]: backend.dist.version for backend in backends_r...
As a python code expert, you are capable of creating scripts from specifications.
Install the given plugin.
Can you tell what is the following Python 3 function doing def install(ctx, plugin): ensure_inside_venv(ctx) plugin_name = get_plugin_name(plugin) try: info = get_plugin_info(plugin_name) except NameError: echo_error("Plugin {} could not be found.".format(plugin)) sys.exit(1) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Uninstalls the given plugin.
Explain what the following Python 3 code does def uninstall(ctx, plugin): ensure_inside_venv(ctx) if plugin not in get_installed_plugins(): echo_error("Plugin {} does not seem to be installed.".format(plugin)) sys.exit(1) plugin_name = get_plugin_name(plugin) try: run_command([...
As a Python code composer, you craft elegant and concise scripts.
Return the number of hours this entry has lasted.
Can you generate a brief explanation for the following Python 3 code def hours(self): if not isinstance(self.duration, tuple): return self.duration if self.duration[1] is None: return 0 time_start = self.get_start_time() # This can happen if the previous entry ...
As a Python code composer, you craft elegant and concise scripts.
def get_start_time(self): """ Return the start time of the entry as a :class:`datetime.time` object. If the start time is `None`, the end time of the previous entry will be returned instead. If the current entry doesn't have a duration in the form of a tuple, if there's no previo...
Implement a Python 3 function for returning the start time of the current entry as a : class : datetime. time object.
As a Python code composer, you craft elegant and concise scripts.
def hash(self): """ Return a value that's used to uniquely identify an entry in a date so we can regroup all entries that share the same hash. """ return u''.join([ self.alias, self.description, str(self.ignored), str(self.flags), ...
Implement a Python 3 function for returning a unique hash of the entry.
You are a Python code analyst, evaluating scripts for potential improvements.
def add_flag(self, flag): """ Add flag to the flags and memorize this attribute has changed so we can regenerate it when outputting text. """ super(Entry, self).add_flag(flag) self._changed_attrs.add('flags')
Create a Python 3 function for adding flag to the flags attribute.
As a Python code translator, you convert algorithms and pseudocode into Python.
def remove_flag(self, flag): """ Remove flag to the flags and memorize this attribute has changed so we can regenerate it when outputting text. """ super(Entry, self).remove_flag(flag) self._changed_attrs.add('flags')
Write a Python 3 script to remove flag from the flags attribute.
You are a Python code analyst, evaluating scripts for potential improvements.
Add the given entry to the textual representation.
Can you generate the documentation for the following Python 3 function def add_entry(self, date, entry): in_date = False insert_at = 0 for (lineno, line) in enumerate(self.lines): # Search for the date of the entry if isinstance(line, DateLine) and line.date == date: ...
As a python code expert, you are capable of creating scripts from specifications.
def delete_entries(self, entries): """ Remove the given entries from the textual representation. """ self.lines = trim([ line for line in self.lines if not isinstance(line, Entry) or line not in entries ])
Create a Python 3 function to remove the given entries from the textual representation.
As a Python code composer, you craft elegant and concise scripts.
Removes the date line from the textual representation. This doesn t remove any entry line. This doesn t remove any entry line. This doesn t remove any entry line.
Explain what the following Python 3 code does def delete_date(self, date): self.lines = [ line for line in self.lines if not isinstance(line, DateLine) or line.date != date ] self.lines = trim(self.lines)
As a Python code analyst, you investigate and solve complex coding mysteries
Add the given date to the textual representation.
Here you have a function in Python 3, explain what it does def add_date(self, date): self.lines = self.parser.add_date(date, self.lines)
You are a Python code analyst, evaluating scripts for potential improvements.
def init_from_str(self, entries): """ Initialize the structured and textual data based on a string representing the entries. For detailed information about the format of this string, refer to the :func:`~taxi.timesheet.parser.parse_text` function. """ self.lines =...
How would you implement a function in Python 3 that initializes the structured and textual data based on a string containing the entries.
As a python code expert, you are capable of creating scripts from specifications.
def filter(self, date=None, regroup=False, ignored=None, pushed=None, unmapped=None, current_workday=None): """ Return the entries as a dict of {:class:`datetime.date`: :class:`~taxi.timesheet.lines.Entry`} items. `date` can either be a single :class:`datetime.date` object to filter onl...
Can you write a function in Python 3 where it returns the entries in the list that match the given date.
You are a Python code generator, capable of creating scripts from specifications.
def append(self, x): """ Append the given element to the list and synchronize the textual representation. """ super(EntriesList, self).append(x) if self.entries_collection is not None: self.entries_collection.add_entry(self.date, x)
Can you create a Python 3 function that appends the given element to the list and synchronize the textual representation.
As a python code expert, you are capable of creating scripts from specifications.
Show the results of the projects database update.
How would you explain what the following Python 3 function does def projects_database_update_success(self, aliases_after_update, projects_db): """ Display the results of the projects/aliases database update. We need the projects db to extract the name of ...
You are a Python code generator, capable of creating scripts from specifications.
Return True if dates in the given lines go in an ascending order or False otherwise.
Here you have a function in Python 3, explain what it does def is_top_down(lines): date_lines = [ line for line in lines if hasattr(line, 'is_date_line') and line.is_date_line ] if len(date_lines) < 2 or date_lines[0].date == date_lines[1].date: return None else: return date_lin...
As a Python code translator, you convert algorithms and pseudocode into Python.
def trim(lines): """ Remove lines at the start and at the end of the given `lines` that are :class:`~taxi.timesheet.lines.TextLine` instances and don't have any text. """ trim_top = None trim_bottom = None _lines = lines[:] for (lineno, line) in enumerate(_lines): if hasattr(lin...
Implement a Python 3 function for removing lines that are not text lines and don t have any text.
As a Python code composer, you craft elegant and concise scripts.
def commit(ctx, f, force_yes, date): """ Commits your work to the server. The [date] option can be used either as a single date (eg. 20.01.2014), as a range (eg. 20.01.2014-22.01.2014), or as a range with one of the dates omitted (eg. -22.01.2014). """ timesheet_collection = get_timesheet_collec...
How would you code a function in Python 3 to commit your work to the server.
You are a Python code analyst, evaluating scripts for potential improvements.
Make the actual request and return the parsed response.
Given the following Python 3 function, write the documentation async def _request(self, path): url = '{}{}'.format(self.base_url, path) data = None try: async with self.websession.get(url, auth=self._auth, timeout=self._timeout) as response: if response.status == 200...
You are a Python code generator, capable of creating scripts from specifications.
async def update(self): """Fetch the latest data from IP Webcam.""" status_data = await self._request('/status.json?show_avail=1') if status_data: self.status_data = status_data sensor_data = await self._request('/sensors.json') if sensor_data: ...
Implement a function in Python 3 to fetch the latest data from IP Webcam.
As a Python code composer, you craft elegant and concise scripts.
Return dict with all config include.
Make a summary of the following Python 3 code def current_settings(self): settings = {} if not self.status_data: return settings for (key, val) in self.status_data.get('curvals', {}).items(): try: val = float(val) except ValueError: ...
As a Python code composer, you craft elegant and concise scripts.
def available_settings(self): """Return dict of lists with all available config settings.""" available = {} if not self.status_data: return available for (key, val) in self.status_data.get('avail', {}).items(): available[key] = [] for subval in val: ...
Write a Python 3 function for returning dict of lists with all available config settings.
You are a Python code generator, capable of creating scripts from specifications.
Return ( value unit ) from a sensor node.
Can you generate a brief explanation for the following Python 3 code def export_sensor(self, sensor): value = None unit = None try: container = self.sensor_data.get(sensor) unit = container.get('unit') data_point = container.get('data', [[0, [0.0]]]) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def change_setting(self, key, val): """Change a setting. Return a coroutine. """ if isinstance(val, bool): payload = 'on' if val else 'off' else: payload = val return self._request('/settings/{}?set={}'.format(key, payload))
Implement a function in Python 3 to change a setting. Return a coroutine.
As a python code expert, you are capable of creating scripts from specifications.
Enable or disable recording.
Can you generate the documentation for the following Python 3 function def record(self, record=True, tag=None): path = '/startvideo?force=1' if record else '/stopvideo?force=1' if record and tag is not None: path = '/startvideo?force=1&tag={}'.format(URL(tag).raw_path) return self._...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_orientation(self, orientation='landscape'): """Set the video orientation. Return a coroutine. """ if orientation not in ALLOWED_ORIENTATIONS: _LOGGER.debug('%s is not a valid orientation', orientation) return False return self.change_setting('orie...
Write a Python 3 function that can set the video orientation.
You are a Python code generator, capable of creating scripts from specifications.
Set the video scene mode.
Make a summary of the following Python 3 code def set_scenemode(self, scenemode='auto'): if scenemode not in self.available_settings['scenemode']: _LOGGER.debug('%s is not a valid scenemode', scenemode) return False return self.change_setting('scenemode', scenemode)
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a TimesheetCollection object with the current timesheets.
Can you tell what is the following Python 3 function doing def get_timesheet_collection_for_context(ctx, entries_file=None): if not entries_file: entries_file = ctx.obj['settings'].get_entries_file_path(False) parser = TimesheetParser( date_format=ctx.obj['settings']['date_format'], add...
As a python code expert, you are capable of creating scripts from specifications.
def create_config_file(filename): """ Create main configuration file if it doesn't exist. """ import textwrap from six.moves.urllib import parse if not os.path.exists(filename): old_default_config_file = os.path.join(os.path.dirname(filename), ...
Can you create a Python 3 function that creates main configuration file if it doesn t exist.
As a Python code analyst, you investigate and solve complex coding mysteries
Decorator to add support for date options to the given command.
Here you have a function in Python 3, explain what it does def date_options(func): @click.option( '--until', type=Date(), help="Only show entries until the given date." ) @click.option( '--since', type=Date(), help="Only show entries starting at the given date.", ) @click.option( ...
As a Python code analyst, you investigate and solve complex coding mysteries
def months_ago(date, nb_months=1): """ Return the given `date` with `nb_months` substracted from it. """ nb_years = nb_months // 12 nb_months = nb_months % 12 month_diff = date.month - nb_months if month_diff > 0: new_month = month_diff else: new_month = 12 + month_diff...
Can you create a Python 3 function that returns the given date with nb_months substracted from it.
You are a Python code generator, capable of creating scripts from specifications.
def time_ago_to_date(value): """ Parse a date and return it as ``datetime.date`` objects. Examples of valid dates: * Relative: 2 days ago, today, yesterday, 1 week ago * Absolute: 25.10.2017 """ today = datetime.date.today() if value == 'today': return today elif value ...
How would you implement a function in Python 3 that parses a date and return it as a datetime. date object.
As a python code expert, you are capable of creating scripts from specifications.
List configured aliases. Aliases in red belong to inactive projects and trying to push entries to these aliases will probably result in an error.
Explain what the following Python 3 code does def list_(ctx, search_string, reverse, backend, used, inactive): if not reverse: list_aliases(ctx, search_string, backend, used, inactive=inactive) else: show_mapping(ctx, search_string, backend)
You are a Python code generator, capable of creating scripts from specifications.
Add a new alias to your configuration file.
Here you have a function in Python 3, explain what it does def add(ctx, alias, mapping, backend): if not backend: backends_list = ctx.obj['settings'].get_backends() if len(backends_list) > 1: raise click.UsageError( "You're using more than 1 backend. Please set the backen...
As a Python code composer, you craft elegant and concise scripts.
def convert_to_4(self): """ Convert a pre-4.0 configuration file to a 4.0 configuration file. """ from six.moves.urllib import parse if not self.config.has_section('backends'): self.config.add_section('backends') site = parse.urlparse(self.get('site', defaul...
Create a Python 3 function to convert a pre - 4. 0 configuration file to a 4. 0 configuration file.
As a Python code analyst, you investigate and solve complex coding mysteries
Fills your timesheet up to today for the specified auto_fill_days.
Can you tell what is the following Python 3 function doing def autofill(ctx, f): auto_fill_days = ctx.obj['settings']['auto_fill_days'] if not auto_fill_days: ctx.obj['view'].view.err("The parameter `auto_fill_days` must be set " "to use this command.") return ...
You are a Python code generator, capable of creating scripts from specifications.
List all projects in the database.
Given the following Python 3 function, write the documentation def list_(ctx, search, backend): projects = ctx.obj['projects_db'].search(search, backend=backend) projects = sorted(projects, key=lambda project: project.name.lower()) ctx.obj['view'].search_results(projects)
You are a Python code generator, capable of creating scripts from specifications.
Adds an alias for the given project.
Here you have a function in Python 3, explain what it does def alias(ctx, search, backend): projects = ctx.obj['projects_db'].search(search, active_only=True) projects = sorted(projects, key=lambda project: project.name) if len(projects) == 0: ctx.obj['view'].msg( "No active project mat...
You are a Python code architect, reviewing and designing scalable and efficient code
Show the details of the given project id.
Explain what the following Python 3 code does def show(ctx, project_id, backend): try: project = ctx.obj['projects_db'].get(project_id, backend) except IOError: raise Exception("Error: the projects database file doesn't exist. " "Please run `taxi update` to create it") ...
As a Python code analyst, you investigate and solve complex coding mysteries
Stop the current task.
Can you generate a brief explanation for the following Python 3 code def stop(ctx, description, f): description = ' '.join(description) try: timesheet_collection = get_timesheet_collection_for_context(ctx, f) current_timesheet = timesheet_collection.latest() current_timesheet.continue_en...
As a Python code translator, you convert algorithms and pseudocode into Python.
Start a new entry in the entries file.
Given the following Python 3 function, write the documentation def start(ctx, alias, description, f): today = datetime.date.today() try: timesheet_collection = get_timesheet_collection_for_context(ctx, f) except ParseError as e: ctx.obj['view'].err(e) return t = timesheet_colle...
As a Python code composer, you craft elegant and concise scripts.
Parse a time in the form hhmm or hmm or even hmm or hmm and return a datetime. time object.
Can you generate the documentation for the following Python 3 function def create_time_from_text(text): text = text.replace(':', '') if not re.match('^\d{3,}$', text): raise ValueError("Time must be numeric") minutes = int(text[-2:]) hours = int(text[0:2] if len(text) > 3 else text[0]) re...
As a Python code analyst, you investigate and solve complex coding mysteries
Return the textual representation of the given duration.
How would you explain what the following Python 3 function does def duration_to_text(self, duration): if isinstance(duration, tuple): start = (duration[0].strftime(self.ENTRY_DURATION_FORMAT) if duration[0] is not None else '') end = (duration[1...
As a python code expert, you are capable of creating scripts from specifications.
def to_text(self, line): """ Return the textual representation of the given `line`. """ return getattr(self, self.ENTRY_TRANSFORMERS[line.__class__])(line)
Write a Python 3 script for returning the textual representation of the given line.
You are a Python code generator, capable of creating scripts from specifications.
def date_line_to_text(self, date_line): """ Return the textual representation of the given :class:`~taxi.timesheet.lines.DateLine` instance. The date format is set by the `date_format` parameter given when instanciating the parser instance. """ # Changing the date in a dateline i...
How would you code a function in Python 3 to return the textual representation of the given date line.
You are a Python code architect, reviewing and designing scalable and efficient code
Converts an entry line into a textual representation of an entry.
Can you tell what is the following Python 3 function doing def entry_line_to_text(self, entry): line = [] # The entry is new, it didn't come from an existing line, so let's just return a simple text representation of # it if not entry._text: flags_text = self.flags_to_text(e...
As a python code expert, you are capable of creating scripts from specifications.
Parses the given text line and returns an Entry object.
Given the following Python 3 function, write the documentation def create_entry_line_from_text(self, text): split_line = re.match(self.entry_line_regexp, text) if not split_line: raise ParseError("Line must have an alias, a duration and a description") alias = split_line.group('ali...
You are a Python code analyst, evaluating scripts for potential improvements.
def create_date_from_text(self, text): """ Parse a text in the form dd/mm/yyyy, dd/mm/yy or yyyy/mm/dd and return a corresponding :class:`datetime.date` object. If no date can be extracted from the given text, a :exc:`ValueError` will be raised. """ # Try to match dd/mm/yyyy form...
Can you implement a function in Python 3 that parses a text in the form dd mm dd or yyyy or dd or yyyy or dd or yyyy or dd or yyyy.
As a Python code translator, you convert algorithms and pseudocode into Python.
def extract_flags_from_text(self, text): """ Extract the flags from the given text and return a :class:`set` of flag values. See :class:`~taxi.timesheet.lines.Entry` for a list of existing flags. """ flags = set() reversed_flags_repr = {v: k for k, v in self.flags_repr.it...
Can you write a function in Python 3 where it extracts the flags from the given text and return a set of flag values.
As a Python code composer, you craft elegant and concise scripts.
Parse the given text and return a list of : class:`~taxi. timesheet. lines. DateLine and ~taxi. timesheet. lines. Entry and ~taxi. timesheet. lines. TextLine objects.
How would you explain what the following Python 3 function does def parse_text(self, text): text = text.strip() lines = text.splitlines() parsed_lines = [] encountered_date = False for (lineno, line) in enumerate(lines, 1): try: parsed_line = self.par...
As a Python code composer, you craft elegant and concise scripts.
Parses the given text and returns either a DateLine or an EntryLine.
Make a summary of the following Python 3 code def parse_line(self, text): text = text.strip().replace('\t', ' ' * 4) # The logic is: if the line starts with a #, consider it's a comment (TextLine), otherwise try to parse it as a # date and if this fails, try to parse it as an entry. If this fai...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the given lines with the date added in the right place.
Can you tell what is the following Python 3 function doing def add_date(self, date, lines): _lines = lines[:] _lines = trim(_lines) if self.add_date_to_bottom is None: add_date_to_bottom = is_top_down(lines) else: add_date_to_bottom = self.add_date_to_bottom ...
As a Python code composer, you craft elegant and concise scripts.
Synchronizes your project database with the server and updates the shared aliases.
Can you tell what is the following Python 3 function doing def update(ctx): ctx.obj['view'].updating_projects_database() projects = [] for backend_name, backend_uri in ctx.obj['settings'].get_backends(): backend = plugins_registry.get_backend(backend_name) backend_projects = backend.get_pr...
As a Python code analyst, you investigate and solve complex coding mysteries
A dictionary mapping names of attributes to BiomartAttribute instances.
Can you generate the documentation for the following Python 3 function def attributes(self): if not self._attribute_pages: self.fetch_attributes() result = {} for page in self._attribute_pages.values(): result.update(page.attributes) return result
As a Python code analyst, you investigate and solve complex coding mysteries
def get_backends_by_class(self, backend_class): """ Return a list of backends that are instances of the given `backend_class`. """ return [backend for backend in self._backends_registry.values() if isinstance(backend, backend_class)]
Create a Python 3 function to return a list of backends that are instances of the given backend_class.
As a Python code analyst, you investigate and solve complex coding mysteries
Populate the internal dictionary with the given backends.
Here you have a function in Python 3, explain what it does def populate_backends(self, backends, context): for name, uri in backends.items(): self._backends_registry[name] = self._load_backend(uri, context)
You are a Python code generator, capable of creating scripts from specifications.
Loads the backend identified by the given backend_uri.
Can you generate a brief explanation for the following Python 3 code def _load_backend(self, backend_uri, context): parsed = parse.urlparse(backend_uri) options = dict(parse.parse_qsl(parsed.query)) try: backend = self._entry_points[self.BACKENDS_ENTRY_POINT][parsed.scheme].load() ...
As a Python code composer, you craft elegant and concise scripts.
Load entry points for custom commands.
Here you have a function in Python 3, explain what it does def register_commands(self): for command in self._entry_points[self.COMMANDS_ENTRY_POINT].values(): command.load()
You are a Python code architect, reviewing and designing scalable and efficient code
Add or remove the given flag if add is True.
Explain what the following Python 3 code does def _add_or_remove_flag(self, flag, add): meth = self.add_flag if add else self.remove_flag meth(flag)
As a Python code translator, you convert algorithms and pseudocode into Python.
Get an application configuration.
How would you explain what the following Python 3 function does def get_application_configuration(name): _check() rc = _ec.get_application_configuration(name) if rc is False: raise ValueError("Application configuration {0} not found.".format(name)) return rc
As a Python code analyst, you investigate and solve complex coding mysteries
Internal method to submit a tuple
Can you generate the documentation for the following Python 3 function def _submit(primitive, port_index, tuple_): args = (_get_opc(primitive), port_index, tuple_) _ec._submit(args)
As a Python code translator, you convert algorithms and pseudocode into Python.
def value(self, value): """ Set the current value of the metric. """ args = (self.__ptr, int(value)) _ec.metric_set(args)
Can you implement a function in Python 3 that sets the current value of the metric.
You are a Python code analyst, evaluating scripts for potential improvements.
def resource_tags(self): """Resource tags for this processing logic. Tags are a mechanism for differentiating and identifying resources that have different physical characteristics or logical uses. For example a resource (host) that has external connectivity for public data sources may be tagged `inges...
Create a Python 3 function for returning a set of tags associated with the resource.
As a Python code composer, you craft elegant and concise scripts.
def submit(ctxtype, graph, config=None, username=None, password=None): """ Submits a `Topology` (application) using the specified context type. Used to submit an application for compilation into a Streams application and execution within an Streaming Analytics service or IBM Streams instance. `ctx...
Can you implement a function in Python 3 that submits a topology to an application using the specified context type.
You are a Python code analyst, evaluating scripts for potential improvements.
Turn a service definition into a vcap services containing a single service.
Given the following Python 3 function, write the documentation def _vcap_from_service_definition(service_def): if 'credentials' in service_def: credentials = service_def['credentials'] else: credentials = service_def service = {} service['credentials'] = credentials service['name'] ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_java_env(self): "Pass the VCAP through the environment to the java submission" env = super(_StreamingAnalyticsSubmitter, self)._get_java_env() vcap = streamsx.rest._get_vcap_services(self._vcap_services) env['VCAP_SERVICES'] = json.dumps(vcap) return env
Write a Python 3 function for passing the VCAP through the environment to the java submission
You are a Python code generator, capable of creating scripts from specifications.
def _get_java_env(self): "Set env vars from connection if set" env = super(_DistributedSubmitter, self)._get_java_env() if self._streams_connection is not None: # Need to sure the environment matches the connection. sc = self._streams_connection if isinstance(...
Write a Python 3 function that can set env vars from connection if set
As a python code expert, you are capable of creating scripts from specifications.
Create a JobConfig instance from a full job configuration overlays object.
Can you generate the documentation for the following Python 3 function def from_overlays(overlays): jc = JobConfig() jc.comment = overlays.get('comment') if 'jobConfigOverlays' in overlays: if len(overlays['jobConfigOverlays']) >= 1: jco = copy.deepcopy(overlays['jo...
As a Python code analyst, you investigate and solve complex coding mysteries
def _add_overlays(self, config): """ Add this as a jobConfigOverlays JSON to config. """ if self._comment: config['comment'] = self._comment jco = {} config["jobConfigOverlays"] = [jco] if self._raw_overlay: jco.update(self._raw_overlay) ...
Can you write a function in Python 3 where it adds this as a jobConfigOverlays JSON to config.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the REST binding for the running job associated with the submitted build.
Explain what the following Python 3 code does def job(self): if self._submitter and hasattr(self._submitter, '_job_access'): return self._submitter._job_access() return None
As a Python code composer, you craft elegant and concise scripts.
def cancel_job_button(self, description=None): """Display a button that will cancel the submitted job. Used in a Jupyter IPython notebook to provide an interactive mechanism to cancel a job submitted from the notebook. Once clicked the button is disabled unless the cancel fails. ...
Implement a function in Python 3 to display a button that will cancel the submission of the current job.
As a python code expert, you are capable of creating scripts from specifications.
def add_default(self, key: str, value: Optional[str], default_type: type = str) -> None: """ Adds a default value and a default type for a key. :param key: Key :param value: *Serialized* default value, i.e. a string or ``None``. :param default_type: The type to unserialize value...
Can you write a function in Python 3 where it adds a default value and a default type for a key.
You are a Python code generator, capable of creating scripts from specifications.
Adds serialization support for a new type.
Make a summary of the following Python 3 code def add_type(self, type: type, serialize: Callable[[Any], str], unserialize: Callable[[str], Any]) -> None: self.types.append(HierarkeyType(type=type, serialize=serialize, unserialize=unserialize))
As a Python code translator, you convert algorithms and pseudocode into Python.
A class decorator that creates a key - value store for the given hierarchy.
Given the following Python 3 function, write the documentation def add(self, cache_namespace: str = None, parent_field: str = None) -> type: if isinstance(cache_namespace, type): raise ImproperlyConfigured('Incorrect decorator usage, you need to use .add() instead of .add') def wrapper(mode...
As a Python code composer, you craft elegant and concise scripts.
def _as_spl_expr(value): """ Return value converted to an SPL expression if needed other otherwise value. """ import streamsx._streams._numpy if hasattr(value, 'spl_json'): return value if isinstance(value, Enum): value = streamsx.spl.op.Expression.expression(value.name) ...
How would you code a function in Python 3 to return value converted to a SPL expression if necessary other otherwise value.
As a Python code composer, you craft elegant and concise scripts.
def _unique_id(self, prefix): """ Generate a unique (within the graph) identifer internal to graph generation. """ _id = self._id_gen self._id_gen += 1 return prefix + str(_id)
Can you create a Python 3 function that generates a unique identifier for the current node.
As a python code expert, you are capable of creating scripts from specifications.
def _requested_name(self, name, action=None, func=None): """Create a unique name for an operator or a stream. """ if name is not None: if name in self._used_names: # start at 2 for the "second" one of this name n = 2 while True: ...
Write a Python 3 script for creating a unique name for an operator or a stream.
As a Python code composer, you craft elegant and concise scripts.
Wrap a main composite invocation as a Topology.
Can you tell what is the following Python 3 function doing def main_composite(kind, toolkits=None, name=None): if '::' in kind: ns, name = kind.rsplit('::', 1) ns += '._spl' else: raise ValueError('Main composite requires a namespace qualified name: ' + str(kind)) topo = streamsx.top...
As a Python code composer, you craft elegant and concise scripts.
Returns an expression representing the input attribute.
Can you tell what is the following Python 3 function doing def attribute(self, stream, name): if stream not in self._inputs: raise ValueError("Stream is not an input of this operator.") if len(self._inputs) == 1: return Expression('attribute', name) else: ipor...
As a Python code analyst, you investigate and solve complex coding mysteries
def output(self, stream, value): """SPL output port assignment expression. Arguments: stream(Stream): Output stream the assignment is for. value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`. Returns: ...
Write a Python 3 function for creating an output port assignment expression.
As a Python code composer, you craft elegant and concise scripts.
SPL output port assignment expression.
Can you generate the documentation for the following Python 3 function def output(self, value): return super(Source, self).output(self.stream, value)
As a Python code composer, you craft elegant and concise scripts.
SPL output port assignment expression.
Can you generate the documentation for the following Python 3 function def output(self, value): return super(Map, self).output(self.stream, value)
As a Python code analyst, you investigate and solve complex coding mysteries
Create an SPL expression from a value.
Can you generate a brief explanation for the following Python 3 code def expression(value): if isinstance(value, Expression): # Clone the expression to allow it to # be used in multiple contexts return Expression(value._type, value._value) if hasattr(value, 'spl_json'...
As a python code expert, you are capable of creating scripts from specifications.
def _extract_from_toolkit(args): """ Look at all the modules in opt/python/streams (opt/python/streams/*.py) and extract any spl decorated function as an operator. """ extractor = _Extractor(args) if extractor._cmd_args.verbose: print("spl-python-extract:", __version__) print("T...
Create a Python 3 function to extract a single object from the toolkit.
As a Python code translator, you convert algorithms and pseudocode into Python.
Copy the language resource files for python api functions This function copies the TopologySplpy Resource files from Topology toolkit directory into the impl / nl folder of the project.
Can you generate a brief explanation for the following Python 3 code def _copy_globalization_resources(self): '''Copy the language resource files for python api functions This function copies the TopologySplpy Resource files from Topology toolkit directory into the impl/nl folder of the pro...
You are a Python code architect, reviewing and designing scalable and efficient code
def main(args=None): """ Output information about `streamsx` and the environment. Useful for support to get key information for use of `streamsx` and Python in IBM Streams. """ _parse_args(args) streamsx._streams._version._mismatch_check('streamsx.topology.context') srp = pkg_res...
Write a Python 3 script for outputting information about `streamsx` and the environment. Useful for support to get key information for use of `streamsx` and Python in IBM Streams.
You are a Python code analyst, evaluating scripts for potential improvements.
Define an operator - driven consistent region configuration.
Can you generate the documentation for the following Python 3 function def operator_driven(drain_timeout=_DEFAULT_DRAIN, reset_timeout=_DEFAULT_RESET, max_consecutive_attempts=_DEFAULT_ATTEMPTS): return ConsistentRegionConfig(trigger=ConsistentRegionConfig.Trigger.OPERATOR_DRIVEN, drain_timeout=drain_timeout, ...
You are a Python code analyst, evaluating scripts for potential improvements.
def periodic(period, drain_timeout=_DEFAULT_DRAIN, reset_timeout=_DEFAULT_RESET, max_consecutive_attempts=_DEFAULT_ATTEMPTS): """Create a periodic consistent region configuration. The IBM Streams runtime will trigger a drain and checkpoint the region periodically at the time interval specified b...
Can you create a Python 3 function that creates a periodic consistent region configuration.
You are a Python code generator, capable of creating scripts from specifications.
Internal method to get a timestamp tuple from a value.
Explain what the following Python 3 code does def _get_timestamp_tuple(ts): if isinstance(ts, datetime.datetime): return Timestamp.from_datetime(ts).tuple() elif isinstance(ts, Timestamp): return ts raise TypeError('Timestamp or datetime.datetime required')
You are a Python code architect, reviewing and designing scalable and efficient code
def from_datetime(dt, machine_id=0): """ Convert a datetime to an SPL `Timestamp`. Args: dt(datetime.datetime): Datetime to be converted. machine_id(int): Machine identifier. Returns: Timestamp: Datetime converted to Timestamp. """ ...
Can you create a Python 3 function that converts a datetime to an SPL Timestamp.
As a python code expert, you are capable of creating scripts from specifications.
Add a SPL toolkit to a topology.
Explain what the following Python 3 code does def add_toolkit(topology, location): import streamsx.topology.topology assert isinstance(topology, streamsx.topology.topology.Topology) tkinfo = dict() tkinfo['root'] = os.path.abspath(location) topology.graph._spl_toolkits.append(tkinfo)
You are a Python code generator, capable of creating scripts from specifications.
def add_toolkit_dependency(topology, name, version): """Add a version dependency on an SPL toolkit to a topology. To specify a range of versions for the dependent toolkits, use brackets (``[]``) or parentheses. Use brackets to represent an inclusive range and parentheses to represent an exclusive range...
Implement a function in Python 3 to add a version dependency on a SPL toolkit to a topology.
As a python code expert, you are capable of creating scripts from specifications.
Submits the current streamsx. Topology to the streamsx server.
Here you have a function in Python 3, explain what it does def submit(args=None): streamsx._streams._version._mismatch_check('streamsx.topology.context') cmd_args = _parse_args(args) if cmd_args.topology is not None: app = _get_topology_app(cmd_args) elif cmd_args.main_composite is not None: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Define job configuration arguments.
Can you generate a brief explanation for the following Python 3 code def _define_jco_args(cmd_parser): jo_group = cmd_parser.add_argument_group('Job options', 'Job configuration options') jo_group.add_argument('--job-name', help='Job name') jo_group.add_argument('--preload', action='store_true', help='Prel...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _submit_topology(cmd_args, app): """Submit a Python topology to the service. This includes an SPL main composite wrapped in a Python topology. """ cfg = app.cfg if cmd_args.create_bundle: ctxtype = ctx.ContextTypes.BUNDLE elif cmd_args.service_name: cfg[ctx.ConfigParams.FORCE...
Write a Python 3 script for submitting a Python topology to the service.
As a Python code composer, you craft elegant and concise scripts.
Submit an existing bundle to the service
Explain what the following Python 3 code does def _submit_bundle(cmd_args, app): sac = streamsx.rest.StreamingAnalyticsConnection(service_name=cmd_args.service_name) sas = sac.get_streaming_analytics() sr = sas.submit_job(bundle=app.app, job_config=app.cfg[ctx.ConfigParams.JOB_CONFIG]) if 'exception' in...
You are a Python code generator, capable of creating scripts from specifications.
For the callable see how many positional parameters are required
Make a summary of the following Python 3 code def _define_fixed(wrapped, callable_): is_class = inspect.isclass(wrapped) style = callable_._splpy_style if hasattr(callable_, '_splpy_style') else wrapped._splpy_style if style == 'dictionary': return -1 fixed_count = 0 if style == 'tuple': ...
As a Python code translator, you convert algorithms and pseudocode into Python.