output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Stores an item in the cache if it does not exist. Returns True if the item was added False otherwise.
Make a summary of the following Python 3 code def add(self, key, val, minutes): if not self.has(key): self.put(key, val, minutes) return True return False
As a Python code translator, you convert algorithms and pseudocode into Python.
def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key: The cache key :type key: str :param value: The increment value :type value: int :rtype: int or bool """ self._store.increment(self.tagged_item_key(ke...
Write a Python 3 script for incrementing the value of an item in the cache.
As a Python code composer, you craft elegant and concise scripts.
def forever(self, key, value): """ Store an item in the cache indefinitely. :param key: The cache key :type key: str :param value: The value :type value: mixed """ self._store.forever(self.tagged_item_key(key), value)
Implement a Python 3 function for storing an item in the cache indefinitely.
You are a Python code architect, reviewing and designing scalable and efficient code
def remember(self, key, minutes, callback): """ Get an item from the cache, or store the default value. :param key: The cache key :type key: str :param minutes: The lifetime in minutes of the cached value :type minutes: int or datetime :param callback: The defa...
Can you write a function in Python 3 where it gets an item from the cache or store the default value.
As a Python code composer, you craft elegant and concise scripts.
def remember_forever(self, key, callback): """ Get an item from the cache, or store the default value forever. :param key: The cache key :type key: str :param callback: The default function :type callback: mixed :rtype: mixed """ # If the item e...
Implement a function in Python 3 to get an item from the cache or store the default value forever.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a fully qualified key for a tagged item.
Can you generate the documentation for the following Python 3 function def tagged_item_key(self, key): return '%s:%s' % (hashlib.sha1(encode(self._tags.get_namespace())).hexdigest(), key)
As a Python code composer, you craft elegant and concise scripts.
def _get_minutes(self, duration): """ Calculate the number of minutes with the given duration. :param duration: The duration :type duration: int or datetime :rtype: int or None """ if isinstance(duration, datetime.datetime): from_now = (duration - da...
Write a Python 3 function that can calculate the number of minutes with the given duration.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the data from a Netdata instance.
Can you generate the documentation for the following Python 3 function async def main(): with aiohttp.ClientSession() as session: data = Netdata('localhost', loop, session, data='data') await data.get_data('system.cpu') print(json.dumps(data.values, indent=4, sort_keys=True)) # Pri...
As a Python code analyst, you investigate and solve complex coding mysteries
def execute(cmd, shell=False, poll_period=1.0, catch_out=False): """Execute UNIX command and wait for its completion Args: cmd (str or list): command to execute shell (bool): invoke inside shell environment catch_out (bool): collect process' output Returns: returncode (...
Create a Python 3 function for executing a command and wait for its completion
You are a Python code generator, capable of creating scripts from specifications.
def _get_payload(self, key): """ Retrieve an item and expiry time from the cache by key. :param key: The cache key :type key: str :rtype: dict """ path = self._path(key) # If the file doesn't exists, we obviously can't return the cache so we will ...
Write a Python 3 script to return the payload of a cache entry.
You are a Python code architect, reviewing and designing scalable and efficient code
def put(self, key, value, minutes): """ Store an item in the cache for a given number of minutes. :param key: The cache key :type key: str :param value: The cache value :type value: mixed :param minutes: The lifetime in minutes of the cached value :type...
Can you write a function in Python 3 where it stores an item in the cache for a given number of minutes.
As a Python code translator, you convert algorithms and pseudocode into Python.
def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key: The cache key :type key: str :param value: The increment value :type value: int :rtype: int or bool """ raw = self._get_payload(key) integer...
Create a Python 3 function for incrementing the value of an item in the cache.
As a Python code analyst, you investigate and solve complex coding mysteries
def forget(self, key): """ Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool """ path = self._path(key) if os.path.exists(path): os.remove(path) return True return False
Create a Python 3 function for removing an item from the cache.
As a python code expert, you are capable of creating scripts from specifications.
Remove all items from the cache.
How would you explain what the following Python 3 function does def flush(self): if os.path.isdir(self._directory): for root, dirs, files in os.walk(self._directory, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name i...
You are a Python code analyst, evaluating scripts for potential improvements.
def _path(self, key): """ Get the full path for the given cache key. :param key: The cache key :type key: str :rtype: str """ hash_type, parts_count = self._HASHES[self._hash_type] h = hash_type(encode(key)).hexdigest() parts = [h[i:i+2] for i i...
Can you implement a function in Python 3 that gets the full path for the given cache key.
You are a Python code analyst, evaluating scripts for potential improvements.
def resource_string(self, path): """ Args: path: str, resource file url or resource file absolute/relative path. Returns: string, file content """ opener = self.get_opener(path) filename = opener.get_filename try: size = os.pat...
Write a Python 3 function that can return the content of a resource file.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_opener(self, path): """ Args: path: str, resource file url or resource file absolute/relative path. Returns: file object """ self.path = path opener = None # FIXME this parser/matcher should use `urlparse` stdlib for opener...
Implement a function in Python 3 to return the opener object for the given path.
You are a Python code generator, capable of creating scripts from specifications.
Begin executing a new tags operation.
Can you tell what is the following Python 3 function doing def tags(self, *names): if len(names) == 1 and isinstance(names[0], list): names = names[0] return TaggedCache(self, TagSet(self, names))
You are a Python code generator, capable of creating scripts from specifications.
def create_job(self): """ Create public Luna job Returns: job_id (basestring): Luna job id """ my_user_agent = None try: my_user_agent = pkg_resources.require('netort')[0].version except pkg_resources.DistributionNotFound: my_user_agen...
Can you implement a function in Python 3 that creates public Luna job.
You are a Python code analyst, evaluating scripts for potential improvements.
Create and register a new metric object and return it
Explain what the following Python 3 code does def new_metric(self, meta): type_ = meta.get('type') if not type_: raise ValueError('Metric type should be defined.') if type_ in available_metrics: metric_obj = available_metrics[type_](meta, self.routing_queue) # create me...
As a python code expert, you are capable of creating scripts from specifications.
def new_tank_metric(self, _type, name, hostname=None, group=None, source=None, *kw): """ Create and register metric, find subscribers for this metric (using meta as filter) and subscribe Return: metric (available_metrics[0]): one of Metric """ if not _type: ...
Create a Python 3 function for creating and register a new tank metric.
As a Python code analyst, you investigate and solve complex coding mysteries
def subscribe(self, callback, filter_): """ Create and register metric subscriber, find metrics for this subscriber (using filter_) and subscribe Args: callback (object method): subscriber's callback filter_ (dict): filter dict filter sample: ...
How would you implement a function in Python 3 that subscribes to the manager and register the callback for each metric that has been discovered.
As a Python code analyst, you investigate and solve complex coding mysteries
def __filter(filterable, filter_, logic_operation='and'): """ filtering DataFrame using filter_ key-value conditions applying logic_operation only find rows strictly fitting the filter_ criterion""" condition = [] if not filter_: return filterable elif filter_.get('ty...
Implement a function in Python 3 to filter DataFrame using filter_ key - value conditions applying logic_operation only find rows strictly fitting the filter_ criterion
You are a Python code analyst, evaluating scripts for potential improvements.
def __reversed_filter(filterable, filter_, logic_operation='and'): """ reverse filtering DataFrame using filter_ key-value conditions applying logic_operation find rows where existing filterable columns (and its values) fitting the filter_ criterion""" condition = [] try: sub...
Write a Python 3 script to reverse filtering DataFrame using filter_ key - value conditions applying logic_operation
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieves an item from the cache by key.
Can you generate the documentation for the following Python 3 function def get(self, key): value = self._redis.get(self._prefix + key) if value is not None: return self.unserialize(value)
You are a Python code architect, reviewing and designing scalable and efficient code
Stores an item in the cache for a given number of minutes.
Given the following Python 3 function, write the documentation def put(self, key, value, minutes): value = self.serialize(value) minutes = max(1, minutes) self._redis.setex(self._prefix + key, minutes * 60, value)
You are a Python code analyst, evaluating scripts for potential improvements.
def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key: The cache key :type key: str :param value: The increment value :type value: int :rtype: int or bool """ return self._redis.incrby(self._prefix + key,...
Write a Python 3 function for incrementing the value of an item in the cache.
You are a Python code architect, reviewing and designing scalable and efficient code
def forever(self, key, value): """ Store an item in the cache indefinitely. :param key: The cache key :type key: str :param value: The value to store :type value: mixed """ value = self.serialize(value) self._redis.set(self._prefix + key, value)
Create a Python 3 function for storing an item in the cache indefinitely.
You are a Python code generator, capable of creating scripts from specifications.
Removes an item from the cache.
How would you explain what the following Python 3 function does def forget(self, key): return bool(self._redis.delete(self._prefix + key))
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieves an item from the cache by key.
Explain what the following Python 3 code does def get(self, key, default=None): val = self._store.get(key) if val is None: return value(default) return val
As a Python code composer, you craft elegant and concise scripts.
Stores an item in the cache.
Explain what the following Python 3 code does def put(self, key, val, minutes): minutes = self._get_minutes(minutes) if minutes is not None: self._store.put(key, val, minutes)
As a Python code analyst, you investigate and solve complex coding mysteries
def add(self, key, val, minutes): """ Store an item in the cache if it does not exist. :param key: The cache key :type key: str :param val: The cache value :type val: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int|d...
Write a Python 3 function for storing an item in the cache if it does not exist. Returns True if the item was added False otherwise.
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculate a cache key given a function args and kwargs.
Explain what the following Python 3 code does def _get_key(self, fn, args, kwargs): if args: serialized_arguments = ( self._store.serialize(args[1:]) + self._store.serialize([(k, kwargs[k]) for k in sorted(kwargs.keys())]) ) else: seria...
You are a Python code architect, reviewing and designing scalable and efficient code
HTTP DELETE - path: string additionnal path to the uri - headers: dict, optionnal headers that will be added to HTTP request. - params: Optionnal parameterss added to the request
How would you explain what the following Python 3 function does def delete(self, path=None, headers=None): return self.request("DELETE", path=path, headers=headers)
You are a Python code architect, reviewing and designing scalable and efficient code
def flush_main(self): """Flushes the implicit main function if there is no main function defined.""" if self.has_main: return self.in_main = True self.write('task main()') self.INDENT() if self.debug: print 'Flushing main:', self.fv.mai...
Write a Python 3 function that can flush the implicit main function if there is no main function defined.
As a Python code translator, you convert algorithms and pseudocode into Python.
Stores an item in the cache for a given number of minutes.
How would you explain what the following Python 3 function does def put(self, key, value, minutes): self._memcache.set(self._prefix + key, value, minutes * 60)
As a python code expert, you are capable of creating scripts from specifications.
Stores an item in the cache if it does not exist. Returns True if the item was added False otherwise.
Given the following Python 3 function, write the documentation def add(self, key, val, minutes): return self._memcache.add(self._prefix + key, val, minutes * 60)
As a Python code translator, you convert algorithms and pseudocode into Python.
def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key: The cache key :type key: str :param value: The increment value :type value: int :rtype: int or bool """ return self._memcache.incr(self._prefix + key...
Create a Python 3 function for incrementing the value of an item in the cache.
As a python code expert, you are capable of creating scripts from specifications.
def get_nowait_from_queue(queue): """ Collect all immediately available items from a queue """ data = [] for _ in range(queue.qsize()): try: data.append(queue.get_nowait()) except q.Empty: break return data
How would you code a function in Python 3 to collect all immediately available items from a queue
As a Python code composer, you craft elegant and concise scripts.
Store an item in the cache indefinitely.
Here you have a function in Python 3, explain what it does def forever(self, key, value): namespace = self._tags.get_namespace() self._push_forever_keys(namespace, key) self._store.forever( '%s:%s' % (hashlib.sha1(encode(self._tags.get_namespace())).hexdigest(), key), v...
As a python code expert, you are capable of creating scripts from specifications.
def _push_forever_keys(self, namespace, key): """ Store a copy of the full key for each namespace segment. :type namespace: str :type key: str """ full_key = '%s%s:%s' % (self.get_prefix(), hashlib.sha1(encode(self._tags.get_namespace()))....
How would you implement a function in Python 3 that pushes the full key for each namespace segment.
As a Python code analyst, you investigate and solve complex coding mysteries
Delete all of the items that were stored forever.
Can you generate the documentation for the following Python 3 function def _delete_forever_keys(self): for segment in self._tags.get_namespace().split('|'): segment = self._forever_key(segment) self._delete_forever_values(segment) self._store.connection().delete(segment)
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete all of the keys that have been stored forever.
Make a summary of the following Python 3 code def _delete_forever_values(self, forever_key): forever = self._store.connection().lrange(forever_key, 0, -1) if len(forever) > 0: self._store.connection().delete(*forever)
As a python code expert, you are capable of creating scripts from specifications.
def capture_pywarnings(handler): """Log python system warnings.""" logger = logging.getLogger('py.warnings') # Check for previously installed handlers. for h in logger.handlers: if isinstance(h, handler.__class__): return logger.addHandler(handler) ...
Write a Python 3 script for capturing Python system warnings.
You are a Python code generator, capable of creating scripts from specifications.
def _get_payload(self, key): """ Retrieve an item and expiry time from the cache by key. :param key: The cache key :type key: str :rtype: dict """ payload = self._storage.get(key) # If the key does not exist, we return nothing if not payload: ...
Can you write a function in Python 3 where it retrieves an item and expiry time from the cache by key.
You are a Python code generator, capable of creating scripts from specifications.
Stores an item in the cache for a given number of minutes.
How would you explain what the following Python 3 function does def put(self, key, value, minutes): self._storage[key] = (self._expiration(minutes), value)
You are a Python code generator, capable of creating scripts from specifications.
def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key: The cache key :type key: str :param value: The increment value :type value: int :rtype: int or bool """ data, time_ = self._get_payload(key) ...
How would you implement a function in Python 3 that increments the value of an item in the cache.
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes an item from the cache.
Make a summary of the following Python 3 code def forget(self, key): if key in self._storage: del self._storage[key] return True return False
As a Python code translator, you convert algorithms and pseudocode into Python.
async def get_data(self, resource): """Get detail for a resource from the data endpoint.""" url = '{}{}'.format( self.base_url, self.endpoint.format(resource=resource)) try: with async_timeout.timeout(5, loop=self._loop): response = await self._session.ge...
Write a Python 3 function that can get detail for a resource from the data endpoint.
As a python code expert, you are capable of creating scripts from specifications.
async def get_alarms(self): """Get alarms for a Netdata instance.""" url = '{}{}'.format(self.base_url, self.endpoint) try: with async_timeout.timeout(5, loop=self._loop): response = await self._session.get(url) _LOGGER.debug( "Response f...
Can you implement a function in Python 3 that gets alarms for a Netdata instance.
As a Python code translator, you convert algorithms and pseudocode into Python.
def filter(self, record): """If request_id is set in flask.g, add it to log record.""" if g and hasattr(g, 'request_id'): record.request_id = g.request_id return True
Write a Python 3 script to add request_id to log record.
You are a Python code architect, reviewing and designing scalable and efficient code
Initialize the logging module with default parameters.
Make a summary of the following Python 3 code def init_logging(log_filename, verbose, quiet): # TODO: consider making one verbosity parameter instead of two mutually exclusive # TODO: default values for parameters logger = logging.getLogger('') logger.setLevel(logging.DEBUG) # add file handler if n...
As a Python code translator, you convert algorithms and pseudocode into Python.
def store(self, name=None): """ Get a cache store instance by name. :param name: The cache store name :type name: str :rtype: Repository """ if name is None: name = self.get_default_driver() self._stores[name] = self._get(name) retu...
How would you implement a function in Python 3 that gets a cache store instance by name.
You are a Python code architect, reviewing and designing scalable and efficient code
Get the store from the local cache.
Given the following Python 3 function, write the documentation def _get(self, name): return self._stores.get(name, self._resolve(name))
As a Python code translator, you convert algorithms and pseudocode into Python.
Resolve the given store and return a new instance of the appropriate class.
Here you have a function in Python 3, explain what it does def _resolve(self, name): config = self._get_config(name) if not config: raise RuntimeError('Cache store [%s] is not defined.' % name) if config['driver'] in self._custom_creators: repository = self._call_custom...
As a python code expert, you are capable of creating scripts from specifications.
def _call_custom_creator(self, config): """ Call a custom driver creator. :param config: The driver configuration :type config: dict :rtype: Repository """ creator = self._custom_creators[config['driver']](config) if isinstance(creator, Store): ...
How would you code a function in Python 3 to call a custom driver creator.
As a Python code composer, you craft elegant and concise scripts.
def _create_file_driver(self, config): """ Create an instance of the file cache driver. :param config: The driver configuration :type config: dict :rtype: Repository """ kwargs = { 'directory': config['path'] } if 'hash_type' in conf...
Can you write a function in Python 3 where it creates an instance of the file cache driver.
As a python code expert, you are capable of creating scripts from specifications.
Get the default cache driver name.
Can you tell what is the following Python 3 function doing def get_default_driver(self): if 'default' in self._config: return self._config['default'] if len(self._config['stores']) == 1: return list(self._config['stores'].keys())[0] raise RuntimeError('Missing "default"...
As a python code expert, you are capable of creating scripts from specifications.
Resolve the given serializer.
Explain what the following Python 3 code does def _resolve_serializer(self, serializer): if isinstance(serializer, Serializer): return serializer if serializer in self._serializers: return self._serializers[serializer] raise RuntimeError('Unsupported serializer')
As a Python code translator, you convert algorithms and pseudocode into Python.
def multiple_choice(question, choices, answers): """ Generates a multiple choice question that allows the user to select an answer choice and shows whether choice was correct. Args: question (str): Question text displayed above choices. choices (list str): Answer choices that user can ...
Write a Python 3 function for generating a single multicommand question that allows the user to select one or more answers.
As a Python code translator, you convert algorithms and pseudocode into Python.
def short_answer(question, answers, explanation=None): """ Generates a short answer question that allows user to input an answer in a textbox and a submit button to check the answer. Args: question (str): The question being asked. answers (str | list str | func): If a string, only tha...
Write a Python 3 function that can generate a short answer question that allows user to input an answer in the order that they ve entered.
As a Python code analyst, you investigate and solve complex coding mysteries
def publish(spec, nb_name, template='full', save_first=True): """ Converts nb_name to an HTML file. Preserves widget functionality. Outputs a link to download HTML file after conversion if called in a notebook environment. Equivalent to running `nbinteract ${spec} ${nb_name}` on the command line. ...
Can you create a Python 3 function that converts a notebook file to an HTML file.
As a Python code analyst, you investigate and solve complex coding mysteries
Attempts to save notebook. If unsuccessful, shows a warning.
How would you explain what the following Python 3 function does def _save_nb(nb_name): display(Javascript('IPython.notebook.save_checkpoint();')) display(Javascript('IPython.notebook.save_notebook();')) print('Saving notebook...', end=' ') if _wait_for_save(nb_name): print("Saved '{}'.".format(...
You are a Python code architect, reviewing and designing scalable and efficient code
Waits for nb_name to update and returns True if a save was detected and False otherwise.
Given the following Python 3 function, write the documentation def _wait_for_save(nb_name, timeout=5): modification_time = os.path.getmtime(nb_name) start_time = time.time() while time.time() < start_time + timeout: if ( os.path.getmtime(nb_name) > modification_time and os.pa...
As a Python code translator, you convert algorithms and pseudocode into Python.
Call maybe_fn with kwargs and return maybe_fn.
Explain what the following Python 3 code does def maybe_call(maybe_fn, kwargs: dict, prefix: str = None) -> 'Any': if not callable(maybe_fn): return maybe_fn args = get_fn_args(maybe_fn, kwargs, prefix=prefix) return maybe_fn(**args)
As a Python code analyst, you investigate and solve complex coding mysteries
def maybe_curry(maybe_fn, first_arg) -> 'Function | Any': """ If maybe_fn is a function, curries it and passes in first_arg. Otherwise returns maybe_fn. """ if not callable(maybe_fn): return maybe_fn return tz.curry(maybe_fn)(first_arg)
Write a Python 3 function for currying maybe_fn and passes in first_arg. If maybe_fn is not a function returns maybe_fn. Otherwise returns maybe_fn.
As a Python code translator, you convert algorithms and pseudocode into Python.
Given function and a dict of kwargs return a dict containing only the args used by the function.
Can you generate a brief explanation for the following Python 3 code def get_fn_args(fn, kwargs: dict, prefix: str = None): all_args = get_all_args(fn) required_args = get_required_args(fn) fn_kwargs = pick_kwargs(kwargs, all_args, prefix) missing_args = [arg for arg in required_args if arg not in fn_k...
You are a Python code generator, capable of creating scripts from specifications.
Returns a list of all arguments for the function fn.
Here you have a function in Python 3, explain what it does def get_all_args(fn) -> list: sig = inspect.signature(fn) return list(sig.parameters)
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_required_args(fn) -> list: """ Returns a list of required arguments for the function fn. >>> def foo(x, y, z=100): return x + y + z >>> get_required_args(foo) ['x', 'y'] >>> def bar(x, y=100, *args, **kwargs): return x >>> get_required_args(bar) ['x'] """ sig = inspect....
How would you code a function in Python 3 to return a list of required arguments for the function fn.
As a python code expert, you are capable of creating scripts from specifications.
def pick_kwargs(kwargs: dict, required_args: list, prefix: str = None): """ Given a dict of kwargs and a list of required_args, return a dict containing only the args in required_args. If prefix is specified, also search for args that begin with '{prefix}__'. Removes prefix in returned dict. R...
Implement a Python 3 function for giving a dict of kwargs and a list of required_args return a dict containing only the args in required_args.
You are a Python code architect, reviewing and designing scalable and efficient code
Updates the docstring of a function to include the options for the plot.
Explain what the following Python 3 code does def _update_option_docstring(func, allowed, indent=' ' * 3): if not (func.__doc__ and '{options}' in func.__doc__): return func descriptions = [option + ': ' + option_doc[option] for option in allowed] full_desc = ('\n' + indent).join(descriptions) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator that validates options in the passed in alphabetical order.
Here you have a function in Python 3, explain what it does def use_options(allowed): def update_docstring(f): _update_option_docstring(f, allowed) @functools.wraps(f) def check_options(*args, **kwargs): options = kwargs.get('options', {}) not_allowed = [ ...
As a Python code analyst, you investigate and solve complex coding mysteries
Generates an interactive histogram that allows users to change the parameters of the input hist_function.
Here you have a function in Python 3, explain what it does def hist(hist_function, *, options={}, **interact_params): params = { 'marks': [{ 'sample': _array_or_placeholder(hist_function), 'bins': _get_option('bins'), 'normalized': _get_option('normalized'), '...
As a python code expert, you are capable of creating scripts from specifications.
def bar(x_fn, y_fn, *, options={}, **interact_params): """ Generates an interactive bar chart that allows users to change the parameters of the inputs x_fn and y_fn. Args: x_fn (Array | (*args -> Array str | Array int | Array float)): If array, uses array values for categories of ba...
Write a Python 3 script for generating an interactive bar chart that allows users to change the parameters of the inputs x_fn and y_fn.
As a Python code analyst, you investigate and solve complex coding mysteries
Generates an interactive scatter plot showing the best fit line of the given points.
Explain what the following Python 3 code does def scatter_drag( x_points: 'Array', y_points: 'Array', *, fig=None, show_eqn=True, options={} ): """ Generates an interactive scatter plot with the best fit line plotted over the points. The points can be dragged by the user and the line...
You are a Python code generator, capable of creating scripts from specifications.
Generates an interactive scatter chart that allows users to change the parameters of the inputs x_fn and y_fn.
Can you generate the documentation for the following Python 3 function def scatter(x_fn, y_fn, *, options={}, **interact_params): params = { 'marks': [{ 'x': _array_or_placeholder(x_fn), 'y': _array_or_placeholder(y_fn), 'marker': _get_option('marker'), }] } ...
You are a Python code architect, reviewing and designing scalable and efficient code
def line(x_fn, y_fn, *, options={}, **interact_params): """ Generates an interactive line chart that allows users to change the parameters of the inputs x_fn and y_fn. Args: x_fn (Array | (*args -> Array str | Array int | Array float)): If array, uses array values for x-coordinates....
How would you implement a function in Python 3 that generates an interactive line chart that allows users to change the parameters of x_fn and y_fn.
You are a Python code architect, reviewing and designing scalable and efficient code
def _merge_with_defaults(params): """ Performs a 2-level deep merge of params with _default_params with corrent merging of params for each mark. This is a bit complicated since params['marks'] is a list and we need to make sure each mark gets the default params. """ marks_params = [ ...
Create a Python 3 function for performing a 2 - level deep merge of params with _default_params with corrent merging of params for each mark.
As a Python code composer, you craft elegant and concise scripts.
def _create_fig( *, x_sc=bq.LinearScale, y_sc=bq.LinearScale, x_ax=bq.Axis, y_ax=bq.Axis, fig=bq.Figure, options={}, params={} ): """ Initializes scales and axes for a bqplot figure and returns the resulting blank figure. Each plot component is passed in as a class. The plot ...
How would you code a function in Python 3 to create a blank figure for a clustered plot.
As a python code expert, you are capable of creating scripts from specifications.
def _create_marks(fig, marks=[bq.Mark], options={}, params={}): """ Initializes and returns marks for a figure as a list. Each mark is passed in as a class. The plot options should be passed into options. Any additional parameters to initialize plot components are passed into params as a dict of { ...
Write a Python 3 function for creating a list of mark classes for a figure.
You are a Python code architect, reviewing and designing scalable and efficient code
Return maybe_iterable s contents or a placeholder array.
Can you generate a brief explanation for the following Python 3 code def _array_or_placeholder( maybe_iterable, placeholder=PLACEHOLDER_ZEROS ) -> np.array: """ Return maybe_iterable's contents or a placeholder array. Used to give bqplot its required initial points to plot even if we're using a fun...
As a Python code analyst, you investigate and solve complex coding mysteries
Converts a GitHub origin into a Binder spec.
How would you explain what the following Python 3 function does def binder_spec_from_github_url(github_url): tokens = re.split(r'/|:', github_url.replace('.git', '')) # The username and reponame are the last two tokens return '{}/{}/master'.format(tokens[-2], tokens[-1])
As a Python code translator, you convert algorithms and pseudocode into Python.
def yes_or_no(question, default="yes"): """Ask a yes/no question via input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is requ...
Can you create a Python 3 function that asks a yes or no question via input and return their answer.
You are a Python code generator, capable of creating scripts from specifications.
def main(): """ Parses command line options and runs nbinteract. """ arguments = docopt(__doc__) if arguments['init']: return_code = init() sys.exit(return_code) run_converter(arguments)
Write a Python 3 script for parsing command line options and runs nbinteract.
You are a Python code analyst, evaluating scripts for potential improvements.
def run_converter(arguments): """ Converts notebooks to HTML files. Returns list of output file paths """ # Get spec from config file if os.path.isfile(CONFIG_FILE): with open(CONFIG_FILE, encoding='utf-8') as f: config = json.load(f) arguments['--spec'] = arguments['...
Implement a function in Python 3 to convert notebooks to HTML files.
As a Python code composer, you craft elegant and concise scripts.
def init(): ''' Initializes git repo for nbinteract. 1. Checks for requirements.txt or Dockerfile, offering to create a requirements.txt if needed. 2. Sets the Binder spec using the `origin` git remote in .nbinteract.json. 3. Prints a Binder URL so the user can debug their image if needed. ...
Write a Python 3 script to initialize the nbinteract project.
You are a Python code architect, reviewing and designing scalable and efficient code
def expand_folder(notebook_or_folder, recursive=False): """ If notebook_or_folder is a folder, returns a list containing all notebooks in the folder. Otherwise, returns a list containing the notebook name. If recursive is True, recurses into subdirectories. """ is_file = os.path.isfile(notebook...
Create a Python 3 function for expanding a folder to a list of notebooks.
As a Python code composer, you craft elegant and concise scripts.
Returns an initialized exporter.
Given the following Python 3 function, write the documentation def init_exporter(extract_images, execute, **exporter_config): config = Config(InteractExporter=exporter_config) preprocessors = [] if extract_images: # Use ExtractOutputPreprocessor to extract the images to separate files prepr...
You are a Python code generator, capable of creating scripts from specifications.
def make_exporter_resources(nb_name, out_folder, images_folder=None): """ Creates resources dict for the exporter """ resources = defaultdict(str) resources['metadata'] = defaultdict(str) resources['metadata']['name'] = nb_name resources['metadata']['path'] = out_folder # This results i...
Create a Python 3 function to create a dictionary that contains the resources for the exporter.
You are a Python code analyst, evaluating scripts for potential improvements.
Converts a notebook into an HTML file outputting notebooks into output_folder if set and images into images_folder if set.
Here you have a function in Python 3, explain what it does def convert(notebook_path, exporter, output_folder=None, images_folder=None): if output_folder: os.makedirs(output_folder, exist_ok=True) if images_folder: os.makedirs(images_folder, exist_ok=True) # Computes notebooks/ch1 and <name...
As a Python code analyst, you investigate and solve complex coding mysteries
def convert_notebooks_to_html_partial(notebook_paths, url_map): """ Converts notebooks in notebook_paths to HTML partials """ for notebook_path in notebook_paths: # Computes <name>.ipynb from notebooks/01/<name>.ipynb path, filename = os.path.split(notebook_path) # Computes examp...
Can you create a Python 3 function that converts notebooks in notebook_paths to HTML partials.
You are a Python code architect, reviewing and designing scalable and efficient code
def _preamble_cell(path): """ This cell is inserted at the start of each notebook to set the working directory to the correct folder. """ code = dedent( ''' # HIDDEN # Clear previously defined variables %reset -f '''.format(path) ) return nbformat.v4.new_code_cell(sou...
Can you create a Python 3 function that creates a single notebook cell that will be used in the notebook file.
You are a Python code generator, capable of creating scripts from specifications.
Generates a dictionary mapping each URL to its previous and next URLs in the textbook.
Explain what the following Python 3 code does def generate_url_map(yaml_path=TOC_PATH) -> dict: with open(yaml_path) as f: data = yaml.load(f) pipeline = [ t.remove(_not_internal_link), flatmap(_flatten_sections), t.map(t.get('url')), list, _sliding_three, t.map(_adj_pag...
You are a Python code generator, capable of creating scripts from specifications.
Finds an element class for the given element name contained within the registry. Returns an Element when there is no matching element subclass.
Can you generate a brief explanation for the following Python 3 code def find_element_class(self, element_name): for element in self.elements: if element.element == element_name: return element return Element
You are a Python code analyst, evaluating scripts for potential improvements.
def _transform(transformer_chain: Sequence[Tuple[DataTransformer, Type]], data: S, context: PipelineContext = None) -> T: """Transform data to a new type. Args: transformer_chain: A sequence of (transformer, type) pairs to convert the data. data: The data to be transformed. context: The...
Write a Python 3 function for transforming data to a new type.
You are a Python code generator, capable of creating scripts from specifications.
Puts an object into the data sink.
Can you generate the documentation for the following Python 3 function def put(self, item: T, context: PipelineContext = None) -> None: LOGGER.info("Converting item \"{item}\" for sink \"{sink}\"".format(item=item, sink=self._sink)) item = self._transform(data=item, context=context) LOGGER.info(...
As a python code expert, you are capable of creating scripts from specifications.
def put_many(self, items: Iterable[T], context: PipelineContext = None) -> None: """Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary. Args: items: An iterable (e.g. list) of objects to be inserted into the d...
Write a Python 3 function for putting multiple objects of the same type into the data sink.
As a Python code composer, you craft elegant and concise scripts.
Gets a query from the data source and transforms it into the requested type.
Make a summary of the following Python 3 code def get(self, query: Mapping[str, Any], context: PipelineContext = None) -> T: result = self._source.get(self._source_type, deepcopy(query), context) LOGGER.info("Got result \"{result}\" from query \"{query}\" of source \"{source}\"".format(result=result, qu...
As a Python code composer, you craft elegant and concise scripts.
Gets a query from the data source where the query contains multiple elements to be extracted and transforms the result into the requested type.
Here you have a function in Python 3, explain what it does def get_many(self, query: Mapping[str, Any], context: PipelineContext = None, streaming: bool = False) -> Iterable[T]: result = self._source.get_many(self._source_type, deepcopy(query), context) LOGGER.info("Got results \"{result}\" from query \...
You are a Python code generator, capable of creating scripts from specifications.
def get(self, type: Type[T], query: Mapping[str, Any]) -> T: """Gets a query from the data pipeline. 1) Extracts the query the sequence of data sources. 2) Inserts the result into the data sinks (if appropriate). 3) Transforms the result into the requested type if it wasn't already. ...
Can you write a function in Python 3 where it gets a query from the data pipeline.
As a python code expert, you are capable of creating scripts from specifications.