text
stringlengths
81
112k
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 (int): process return code stdout (str): collected process stdout...
Retrieve an item and expiry time from the cache by key. :param key: The cache key :type key: str :rtype: dict 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: dic...
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 minutes: int def put(self, key, value, minutes): ...
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 def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key...
Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool 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...
Remove all items from the cache. def flush(self): """ Remove all items from the cache. """ 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,...
Get the full path for the given cache key. :param key: The cache key :type key: str :rtype: str 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, pa...
Args: path: str, resource file url or resource file absolute/relative path. Returns: string, file content def resource_string(self, path): """ Args: path: str, resource file url or resource file absolute/relative path. Returns: string, f...
Args: path: str, resource file url or resource file absolute/relative path. Returns: file object def get_opener(self, path): """ Args: path: str, resource file url or resource file absolute/relative path. Returns: file object """...
Begin executing a new tags operation. :param names: The tags :type names: tuple :rtype: cachy.tagged_cache.TaggedCache def tags(self, *names): """ Begin executing a new tags operation. :param names: The tags :type names: tuple :rtype: cachy.tagged_cac...
Implement custom getter. def get_user_info(self, request): """Implement custom getter.""" if not current_user.is_authenticated: return {} user_info = { 'id': current_user.get_id(), } if 'SENTRY_USER_ATTRS' in current_app.config: for attr in ...
Create public Luna job Returns: job_id (basestring): Luna job id 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')...
Create and register metric, find subscribers for this metric (using meta as filter) and subscribe Return: metric (available_metrics[0]): one of Metric def new_metric(self, meta): """ Create and register metric, find subscribers for this metric (using meta as filter)...
Create and register metric, find subscribers for this metric (using meta as filter) and subscribe Return: metric (available_metrics[0]): one of Metric def new_tank_metric(self, _type, name, hostname=None, group=None, source=None, *kw): """ Create and register metric, ...
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: {'type': 'metrics', 'source': 'gun'} def subscribe(self, c...
filtering DataFrame using filter_ key-value conditions applying logic_operation only find rows strictly fitting the filter_ criterion def __filter(filterable, filter_, logic_operation='and'): """ filtering DataFrame using filter_ key-value conditions applying logic_operation only find rows stri...
reverse filtering DataFrame using filter_ key-value conditions applying logic_operation find rows where existing filterable columns (and its values) fitting the filter_ criterion def __reversed_filter(filterable, filter_, logic_operation='and'): """ reverse filtering DataFrame using filter_ key-value c...
Install log handler. def install_handler(self, app): """Install log handler.""" from raven.contrib.celery import register_logger_signal, \ register_signal from raven.contrib.flask import Sentry, make_client from raven.handlers.logging import SentryHandler # Installs...
Process event data. def process(self, data, **kwargs): """Process event data.""" data = super(RequestIdProcessor, self).process(data, **kwargs) if g and hasattr(g, 'request_id'): tags = data.get('tags', {}) tags['request_id'] = g.request_id data['tags'] = tag...
Retrieve an item from the cache by key. :param key: The cache key :type key: str :return: The cache value def get(self, key): """ Retrieve an item from the cache by key. :param key: The cache key :type key: str :return: The cache value """ ...
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 minutes: int def put(self, key, value, minutes): ...
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 def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key...
Decrement the value of an item in the cache. :param key: The cache key :type key: str :param value: The decrement value :type value: int :rtype: int or bool def decrement(self, key, value=1): """ Decrement the value of an item in the cache. :param key...
Store an item in the cache indefinitely. :param key: The cache key :type key: str :param value: The value to store :type value: mixed def forever(self, key, value): """ Store an item in the cache indefinitely. :param key: The cache key :type key: str ...
Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool def forget(self, key): """ Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool """ return bool(self._redis.delete(sel...
Retrieve an item from the cache by key. :param key: The cache key :type key: str :param default: The default value to return :type default: mixed :rtype: mixed def get(self, key, default=None): """ Retrieve an item from the cache by key. :param key: T...
Store an item in the cache. :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|datetime def put(self, key, val, minutes): """ Store an ite...
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|datetime :rtype: bool def add(self, key, val,...
Calculate a cache key given a function, args and kwargs. :param fn: The function :type fn: callable or str :param args: The function args :type args: tuple :param kwargs: The function kwargs :type kwargs: dict :rtype: str def _get_key(self, fn, args, kwargs):...
HTTP PATCH - payload: string passed to the body of the request - 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 def patch(self, path=None, payload=None, he...
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 def delete(self, path=None, headers=None): """ HTTP DELETE - path: string additionnal ...
Flushes the implicit main function if there is no main function defined. 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()') sel...
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 minutes: int def put(self, key, value, 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 :rtype: bool def add(self, key, val, minutes)...
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 def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key...
Decrement the value of an item in the cache. :param key: The cache key :type key: str :param value: The decrement value :type value: int :rtype: int or bool def decrement(self, key, value=1): """ Decrement the value of an item in the cache. :param key...
Collect all immediately available items from a queue 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
Store an item in the cache indefinitely. :param key: The cache key :type key: str :param value: The value :type value: mixed def forever(self, key, value): """ Store an item in the cache indefinitely. :param key: The cache key :type key: str :...
Store a copy of the full key for each namespace segment. :type namespace: str :type key: str 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 = '%...
Delete all of the items that were stored forever. def _delete_forever_keys(self): """ Delete all of the items that were stored forever. """ for segment in self._tags.get_namespace().split('|'): segment = self._forever_key(segment) self._delete_forever_values(segm...
Delete all of the keys that have been stored forever. :type forever_key: str def _delete_forever_values(self, forever_key): """ Delete all of the keys that have been stored forever. :type forever_key: str """ forever = self._store.connection().lrange(forever_key, 0, -1...
Log python system warnings. 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 l...
Retrieve an item and expiry time from the cache by key. :param key: The cache key :type key: str :rtype: dict 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: dic...
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 minutes: int def put(self, key, value, minutes): ...
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 def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key...
Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool def forget(self, key): """ Remove an item from the cache. :param key: The cache key :type key: str :rtype: bool """ if key in self._storage: ...
Get detail for a resource from the data endpoint. 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)...
Get alarms for a Netdata instance. 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) _LOGGE...
If request_id is set in flask.g, add it to log record. 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
Set up logging with default parameters: * default console logging level is INFO * ERROR, WARNING and CRITICAL are redirected to stderr Args: log_filename (str): if set, will write DEBUG log there verbose (bool): DEBUG level in console, overrides 'quiet' quiet (bool): WARNING level i...
Get a cache store instance by name. :param name: The cache store name :type name: str :rtype: Repository def store(self, name=None): """ Get a cache store instance by name. :param name: The cache store name :type name: str :rtype: Repository "...
Attempt to get the store from the local cache. :param name: The store name :type name: str :rtype: Repository def _get(self, name): """ Attempt to get the store from the local cache. :param name: The store name :type name: str :rtype: Repository ...
Resolve the given store :param name: The store to resolve :type name: str :rtype: Repository def _resolve(self, name): """ Resolve the given store :param name: The store to resolve :type name: str :rtype: Repository """ config = self._...
Call a custom driver creator. :param config: The driver configuration :type config: dict :rtype: Repository def _call_custom_creator(self, config): """ Call a custom driver creator. :param config: The driver configuration :type config: dict :rtype: Re...
Create an instance of the file cache driver. :param config: The driver configuration :type config: dict :rtype: Repository def _create_file_driver(self, config): """ Create an instance of the file cache driver. :param config: The driver configuration :type con...
Get the default cache driver name. :rtype: str :raises: RuntimeError def get_default_driver(self): """ Get the default cache driver name. :rtype: str :raises: RuntimeError """ if 'default' in self._config: return self._config['default'] ...
Resolve the given serializer. :param serializer: The serializer to resolve :type serializer: str or Serializer :rtype: Serializer def _resolve_serializer(self, serializer): """ Resolve the given serializer. :param serializer: The serializer to resolve :type se...
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 select. answers (int | iterable int): Either an inte...
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 that string will be marked correct. If a list of string, a...
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. Args: spec (str): BinderHub spec for Jupyter image. Must be i...
Attempts to save notebook. If unsuccessful, shows a warning. def _save_nb(nb_name): """ Attempts to save notebook. If unsuccessful, shows a warning. """ display(Javascript('IPython.notebook.save_checkpoint();')) display(Javascript('IPython.notebook.save_notebook();')) print('Saving notebook...'...
Waits for nb_name to update, waiting up to TIMEOUT seconds. Returns True if a save was detected, and False otherwise. def _wait_for_save(nb_name, timeout=5): """Waits for nb_name to update, waiting up to TIMEOUT seconds. Returns True if a save was detected, and False otherwise. """ modification_tim...
If maybe_fn is a function, get its arguments from kwargs and call it, also searching for prefixed kwargs if prefix is specified. Otherwise, return maybe_fn. Used to allow both functions and iterables to be passed into plotting functions. >>> def square(x): return x * x >>> maybe_call(square, {...
If maybe_fn is a function, curries it and passes in first_arg. Otherwise returns maybe_fn. 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...
Given function and a dict of kwargs return a dict containing only the args used by the function. If prefix is specified, also search for args that begin with '{prefix}__'. Removes prefix in returned dict. Raises ValueError if a required arg is missing from the kwargs. Raises ValueError if both pr...
Returns a list of all arguments for the function fn. >>> def foo(x, y, z=100): return x + y + z >>> get_all_args(foo) ['x', 'y', 'z'] def get_all_args(fn) -> list: """ Returns a list of all arguments for the function fn. >>> def foo(x, y, z=100): return x + y + z >>> get_all_args(foo) ...
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'] def get_required_args(fn) -> list: """ Returns a list of require...
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. Raises ValueError if both prefixed and unprefixed arg are given in kwargs. >>> f...
Updates docstring of func, filling in appearance of {options} with a description of the options. >>> def f(): '''{options}''' >>> f = _update_option_docstring(f, ['title', 'xlim']) >>> print(f.__doc__) options (dict): Options for the plot. Available options: <BLANKLINE> title: T...
Decorator that logs warnings when unpermitted options are passed into its wrapped function. Requires that wrapped function has an keyword-only argument named `options`. If wrapped function has {options} in its docstring, fills in with the docs for allowed options. Args: allowed (list str):...
Generates an interactive histogram that allows users to change the parameters of the input hist_function. Args: hist_function (Array | (*args -> Array int | Array float)): Function that takes in parameters to interact with and returns an array of numbers. These numbers will be p...
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 bar chart. If function, must take parameters to interact...
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 will automatically update. Args: x_points (Array Number): x-values of points to plot y_points (Array Number): y-values of points to plot Kwargs: ...
Generates an interactive scatter 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. If function, must take parameters to interact with ...
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. If function, must take parameters to interact with and...
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. def _merge_with_defaults(params): """ Performs a 2-level deep merge of pa...
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 options should be passed into options. Any additional parameters to initialize plot components are passed into params as a dict of { plot_component: { trait: val...
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 { 'mark': [{ trait: value, ... }, ...] } For example, when initializing t...
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 function to generate points. def _array_or_placeholder( maybe_iterable, placeholder=PLACEHOLDER_ZEROS ) -> np.array: """ Return maybe_iterable's contents or a plac...
Converts GitHub origin into a Binder spec. For example: git@github.com:SamLau95/nbinteract.git -> SamLau95/nbinteract/master https://github.com/Calebs97/riemann_book -> Calebs97/riemann_book/master def binder_spec_from_github_url(github_url): """ Converts GitHub origin into a Binder spec. For...
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 required of the user). The "answer" return val...
Parses command line options and runs nbinteract. 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)
Converts notebooks to HTML files. Returns list of output file paths 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: ...
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. def init(): ''' ...
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. def expand_folder(notebook_or_folder, recursive=False): """ If notebook_or_folder is a folder, returns a...
Returns an initialized exporter. def init_exporter(extract_images, execute, **exporter_config): """ Returns an initialized exporter. """ config = Config(InteractExporter=exporter_config) preprocessors = [] if extract_images: # Use ExtractOutputPreprocessor to extract the images to sepa...
Creates resources dict for the exporter 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']['...
Converts notebook into an HTML file, outputting notebooks into output_folder if set and images into images_folder if set. Returns the path to the resulting HTML file. def convert(notebook_path, exporter, output_folder=None, images_folder=None): """ Converts notebook into an HTML file, outputting noteb...
Converts notebooks in notebook_paths to HTML partials 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 ...
This cell is inserted at the start of each notebook to set the working directory to the correct folder. 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 p...
Generates mapping from each URL to its previous and next URLs in the textbook. The dictionary looks like: { 'ch/10/some_page.html' : { 'prev': 'ch/09/foo.html', 'next': 'ch/10/bar.html', }, ... } def generate_url_map(yaml_path=TOC_PATH) -> dict: """ ...
Finds an element class for the given element name contained within the registry. Returns Element when there is no matching element subclass. >>> registry.find_element_class('string') String >>> registry.find_element_class('unknown') Element def find_element_class(self...
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 context of the transformations (mutable). Returns: The transformed data. def _transform(transformer_chain: Sequenc...
Puts an objects into the data sink. The objects may be transformed into a new type for insertion if necessary. Args: item: The objects to be inserted into the data sink. context: The context of the insertion (mutable). def put(self, item: 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 data sink. context: The context of the insertions (mutable). def put_many(self, ...
Gets a query from the data source. 1) Extracts the query from the data source. 2) Inserts the result into any data sinks. 3) Transforms the result into the requested type if it wasn't already. 4) Inserts the transformed result into any data sinks. Args: query: The q...
Gets a query from the data source, where the query contains multiple elements to be extracted. 1) Extracts the query from the data source. 2) Inserts the result into any data sinks. 3) Transforms the results into the requested type if it wasn't already. 4) Inserts the transformed result...
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. 4) Inserts the transformed result into any data sinks. Arg...
Gets a query from the data pipeline, which contains a request for multiple objects. 1) Extracts the query the sequence of data sources. 2) Inserts the results into the data sinks (if appropriate). 3) Transforms the results into the requested type if it wasn't already. 4) Inserts the tra...
Puts an objects into the data pipeline. The object may be transformed into a new type for insertion if necessary. Args: item: The object to be inserted into the data pipeline. def put(self, type: Type[T], item: T) -> None: """Puts an objects into the data pipeline. The object may be transf...