Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> shutil.rmtree(self.docs_dir) mkdir_p(self.docs_dir) mkdir_p(self.site_dir) assets = glob.glob(os.path.join(self.mkdocs_dir, '*')) for asset in assets: filename = os.path.basename(asset) if filename not in set(['docs', 'site', 'mkdocs.yml']): os.symlink(asset, os.path.join(self.docs_dir, filename)) self.root.name = self.momo_configs['momo_root_name'] def _get_pages(self, root, level=0): if level == self.momo_configs['momo_page_level']: filename = self._make_page(root) return filename else: pages = [ {'Index': self._make_index_page(root, level + 1)} ] pages += [ {elem.name: self._get_pages(elem, level + 1)} for elem in root.node_svals ] return pages def _get_docs(self): if self.momo_configs['momo_docs_dir'] is None: return [] src_momo_docs_dir = eval_path(self.momo_configs['momo_docs_dir']) if os.path.isdir(src_momo_docs_dir): <|code_end|> , predict the next line using imports from the current file: import os import shutil import yaml import glob from momo.utils import run_cmd, mkdir_p, utf8_encode, txt_type, eval_path from momo.plugins.base import Plugin and context including class names, function names, and sometimes code from other files: # Path: momo/utils.py # MIN_PAGE_LINES = 50 # PY3 = sys.version_info[0] == 3 # def eval_path(path): # def smart_print(*args, **kwargs): # def utf8_decode(s): # def utf8_encode(s): # def run_cmd(cmd_str=None, cmd=None, cmd_args=None, stdout=sys.stdout, # stderr=sys.stderr, stdin=None): # def open_default(path): # def mkdir_p(path): # def page_lines(lines): # # Path: momo/plugins/base.py # class Plugin(object): # def __init__(self): # self.settings = settings # # def setup(self): # """Initializae the plugin""" # raise NotImplementedError # # def run(self, extra_args=None): # """Run the plugin # # :param extra_args: a list of command-line arguments to pass to the # underlying plugin. # """ # raise NotImplementedError . Output only the next line.
markdown_paths = glob.glob(
Given the following code snippet before the placeholder: <|code_start|> FLASK_DEFAULT_HOST = '127.0.0.1' FLASK_DEFAULT_PORT = 7000 FLASK_DEFAULT_DEBUG = True FLASK_APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__))) FLASK_TEMPLATE_FOLDER = os.path.join(FLASK_APP_ROOT, 'templates') FLASK_STATIC_FOLDER = os.path.join(FLASK_APP_ROOT, 'static') app = Flask( import_name=__name__, template_folder=FLASK_TEMPLATE_FOLDER, static_folder=FLASK_STATIC_FOLDER, ) # instrument app Bootstrap(app) # extensions <|code_end|> , predict the next line using imports from the current file: import os from flask import ( Flask, g, redirect, render_template, request, send_from_directory, ) from flask_bootstrap import Bootstrap from momo.plugins.flask import filters, functions from momo.plugins.flask.utils import get_public_functions from momo.plugins.flask.sorting import sort_nodes_by_request from momo.plugins.flask.nodes import merge_nodes from momo.utils import open_default and context including class names, function names, and sometimes code from other files: # Path: momo/plugins/flask/filters.py # def txt_type(s): # def get_attr(node, attrname, default=None): # def get_parents(node): # def slugify(s): # def attr_image(node): # def attr_path(node): # def node_to_path(node): # def split_path(path): # def sort_attrs(attrs): # def pin_attrs(attrs): # def safe_quote(s): # # Path: momo/plugins/flask/functions.py # def paginate(page, total, per_page, config): # def _paginate(page, total, per_page, record_name, display_msg): # def get_page(request): # def toggle_arg(endpoint, request, arg, value, **kwargs): # # Path: momo/plugins/flask/utils.py # def get_public_functions(module): # """Get public functions in a module. Return a dictionary of function names # to objects.""" # return { # o[0]: o[1] for o in getmembers(module, isfunction) # if not o[0].startswith('_') # } # # Path: momo/plugins/flask/sorting.py # def sort_nodes_by_request(nodes, request, g, default_terms=None): # """High-level function to sort nodes with a request object.""" # sorting_terms = request.args.getlist('sort') or default_terms # desc = request.args.get('desc', default=False, type=str_to_bool) # if not sorting_terms: # if desc: # nodes.reverse() # else: # nodes = sort_nodes_by_terms( # terms=sorting_terms, # nodes=nodes, # desc=desc, # functions=g.sorting_functions, # ) # return nodes # # Path: momo/plugins/flask/nodes.py # def merge_nodes(nodes): # """ # Merge nodes to deduplicate same-name nodes and add a "parents" # attribute to each node, which is a list of Node objects. # """ # # def add_parent(unique_node, parent): # if getattr(unique_node, 'parents', None): # if parent.name not in unique_node.parents: # unique_node.parents[parent.name] = parent # else: # unique_node.parents = {parent.name: parent} # # names = OrderedDict() # for node in nodes: # if node.name not in names: # names[node.name] = node # add_parent(names[node.name], node.parent) # else: # add_parent(names[node.name], node.parent) # return names.values() # # Path: momo/utils.py # def open_default(path): # if platform.system() == 'Darwin': # sh.open(path) # elif os.name == 'nt': # os.startfile(path) # elif os.name == 'posix': # run = sh.Command('xdg-open') # run(path) . Output only the next line.
app.jinja_env.add_extension('jinja2.ext.do')
Based on the snippet: <|code_start|> FLASK_DEFAULT_HOST = '127.0.0.1' FLASK_DEFAULT_PORT = 7000 FLASK_DEFAULT_DEBUG = True FLASK_APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__))) FLASK_TEMPLATE_FOLDER = os.path.join(FLASK_APP_ROOT, 'templates') FLASK_STATIC_FOLDER = os.path.join(FLASK_APP_ROOT, 'static') app = Flask( import_name=__name__, template_folder=FLASK_TEMPLATE_FOLDER, static_folder=FLASK_STATIC_FOLDER, <|code_end|> , predict the immediate next line with the help of imports: import os from flask import ( Flask, g, redirect, render_template, request, send_from_directory, ) from flask_bootstrap import Bootstrap from momo.plugins.flask import filters, functions from momo.plugins.flask.utils import get_public_functions from momo.plugins.flask.sorting import sort_nodes_by_request from momo.plugins.flask.nodes import merge_nodes from momo.utils import open_default and context (classes, functions, sometimes code) from other files: # Path: momo/plugins/flask/filters.py # def txt_type(s): # def get_attr(node, attrname, default=None): # def get_parents(node): # def slugify(s): # def attr_image(node): # def attr_path(node): # def node_to_path(node): # def split_path(path): # def sort_attrs(attrs): # def pin_attrs(attrs): # def safe_quote(s): # # Path: momo/plugins/flask/functions.py # def paginate(page, total, per_page, config): # def _paginate(page, total, per_page, record_name, display_msg): # def get_page(request): # def toggle_arg(endpoint, request, arg, value, **kwargs): # # Path: momo/plugins/flask/utils.py # def get_public_functions(module): # """Get public functions in a module. Return a dictionary of function names # to objects.""" # return { # o[0]: o[1] for o in getmembers(module, isfunction) # if not o[0].startswith('_') # } # # Path: momo/plugins/flask/sorting.py # def sort_nodes_by_request(nodes, request, g, default_terms=None): # """High-level function to sort nodes with a request object.""" # sorting_terms = request.args.getlist('sort') or default_terms # desc = request.args.get('desc', default=False, type=str_to_bool) # if not sorting_terms: # if desc: # nodes.reverse() # else: # nodes = sort_nodes_by_terms( # terms=sorting_terms, # nodes=nodes, # desc=desc, # functions=g.sorting_functions, # ) # return nodes # # Path: momo/plugins/flask/nodes.py # def merge_nodes(nodes): # """ # Merge nodes to deduplicate same-name nodes and add a "parents" # attribute to each node, which is a list of Node objects. # """ # # def add_parent(unique_node, parent): # if getattr(unique_node, 'parents', None): # if parent.name not in unique_node.parents: # unique_node.parents[parent.name] = parent # else: # unique_node.parents = {parent.name: parent} # # names = OrderedDict() # for node in nodes: # if node.name not in names: # names[node.name] = node # add_parent(names[node.name], node.parent) # else: # add_parent(names[node.name], node.parent) # return names.values() # # Path: momo/utils.py # def open_default(path): # if platform.system() == 'Darwin': # sh.open(path) # elif os.name == 'nt': # os.startfile(path) # elif os.name == 'posix': # run = sh.Command('xdg-open') # run(path) . Output only the next line.
)
Predict the next line after this snippet: <|code_start|> FLASK_DEFAULT_HOST = '127.0.0.1' FLASK_DEFAULT_PORT = 7000 FLASK_DEFAULT_DEBUG = True FLASK_APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__))) FLASK_TEMPLATE_FOLDER = os.path.join(FLASK_APP_ROOT, 'templates') FLASK_STATIC_FOLDER = os.path.join(FLASK_APP_ROOT, 'static') app = Flask( <|code_end|> using the current file's imports: import os from flask import ( Flask, g, redirect, render_template, request, send_from_directory, ) from flask_bootstrap import Bootstrap from momo.plugins.flask import filters, functions from momo.plugins.flask.utils import get_public_functions from momo.plugins.flask.sorting import sort_nodes_by_request from momo.plugins.flask.nodes import merge_nodes from momo.utils import open_default and any relevant context from other files: # Path: momo/plugins/flask/filters.py # def txt_type(s): # def get_attr(node, attrname, default=None): # def get_parents(node): # def slugify(s): # def attr_image(node): # def attr_path(node): # def node_to_path(node): # def split_path(path): # def sort_attrs(attrs): # def pin_attrs(attrs): # def safe_quote(s): # # Path: momo/plugins/flask/functions.py # def paginate(page, total, per_page, config): # def _paginate(page, total, per_page, record_name, display_msg): # def get_page(request): # def toggle_arg(endpoint, request, arg, value, **kwargs): # # Path: momo/plugins/flask/utils.py # def get_public_functions(module): # """Get public functions in a module. Return a dictionary of function names # to objects.""" # return { # o[0]: o[1] for o in getmembers(module, isfunction) # if not o[0].startswith('_') # } # # Path: momo/plugins/flask/sorting.py # def sort_nodes_by_request(nodes, request, g, default_terms=None): # """High-level function to sort nodes with a request object.""" # sorting_terms = request.args.getlist('sort') or default_terms # desc = request.args.get('desc', default=False, type=str_to_bool) # if not sorting_terms: # if desc: # nodes.reverse() # else: # nodes = sort_nodes_by_terms( # terms=sorting_terms, # nodes=nodes, # desc=desc, # functions=g.sorting_functions, # ) # return nodes # # Path: momo/plugins/flask/nodes.py # def merge_nodes(nodes): # """ # Merge nodes to deduplicate same-name nodes and add a "parents" # attribute to each node, which is a list of Node objects. # """ # # def add_parent(unique_node, parent): # if getattr(unique_node, 'parents', None): # if parent.name not in unique_node.parents: # unique_node.parents[parent.name] = parent # else: # unique_node.parents = {parent.name: parent} # # names = OrderedDict() # for node in nodes: # if node.name not in names: # names[node.name] = node # add_parent(names[node.name], node.parent) # else: # add_parent(names[node.name], node.parent) # return names.values() # # Path: momo/utils.py # def open_default(path): # if platform.system() == 'Darwin': # sh.open(path) # elif os.name == 'nt': # os.startfile(path) # elif os.name == 'posix': # run = sh.Command('xdg-open') # run(path) . Output only the next line.
import_name=__name__,
Continue the code snippet: <|code_start|> FLASK_DEFAULT_HOST = '127.0.0.1' FLASK_DEFAULT_PORT = 7000 FLASK_DEFAULT_DEBUG = True FLASK_APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__))) FLASK_TEMPLATE_FOLDER = os.path.join(FLASK_APP_ROOT, 'templates') FLASK_STATIC_FOLDER = os.path.join(FLASK_APP_ROOT, 'static') app = Flask( import_name=__name__, <|code_end|> . Use current file imports: import os from flask import ( Flask, g, redirect, render_template, request, send_from_directory, ) from flask_bootstrap import Bootstrap from momo.plugins.flask import filters, functions from momo.plugins.flask.utils import get_public_functions from momo.plugins.flask.sorting import sort_nodes_by_request from momo.plugins.flask.nodes import merge_nodes from momo.utils import open_default and context (classes, functions, or code) from other files: # Path: momo/plugins/flask/filters.py # def txt_type(s): # def get_attr(node, attrname, default=None): # def get_parents(node): # def slugify(s): # def attr_image(node): # def attr_path(node): # def node_to_path(node): # def split_path(path): # def sort_attrs(attrs): # def pin_attrs(attrs): # def safe_quote(s): # # Path: momo/plugins/flask/functions.py # def paginate(page, total, per_page, config): # def _paginate(page, total, per_page, record_name, display_msg): # def get_page(request): # def toggle_arg(endpoint, request, arg, value, **kwargs): # # Path: momo/plugins/flask/utils.py # def get_public_functions(module): # """Get public functions in a module. Return a dictionary of function names # to objects.""" # return { # o[0]: o[1] for o in getmembers(module, isfunction) # if not o[0].startswith('_') # } # # Path: momo/plugins/flask/sorting.py # def sort_nodes_by_request(nodes, request, g, default_terms=None): # """High-level function to sort nodes with a request object.""" # sorting_terms = request.args.getlist('sort') or default_terms # desc = request.args.get('desc', default=False, type=str_to_bool) # if not sorting_terms: # if desc: # nodes.reverse() # else: # nodes = sort_nodes_by_terms( # terms=sorting_terms, # nodes=nodes, # desc=desc, # functions=g.sorting_functions, # ) # return nodes # # Path: momo/plugins/flask/nodes.py # def merge_nodes(nodes): # """ # Merge nodes to deduplicate same-name nodes and add a "parents" # attribute to each node, which is a list of Node objects. # """ # # def add_parent(unique_node, parent): # if getattr(unique_node, 'parents', None): # if parent.name not in unique_node.parents: # unique_node.parents[parent.name] = parent # else: # unique_node.parents = {parent.name: parent} # # names = OrderedDict() # for node in nodes: # if node.name not in names: # names[node.name] = node # add_parent(names[node.name], node.parent) # else: # add_parent(names[node.name], node.parent) # return names.values() # # Path: momo/utils.py # def open_default(path): # if platform.system() == 'Darwin': # sh.open(path) # elif os.name == 'nt': # os.startfile(path) # elif os.name == 'posix': # run = sh.Command('xdg-open') # run(path) . Output only the next line.
template_folder=FLASK_TEMPLATE_FOLDER,
Next line prediction: <|code_start|> FLASK_DEFAULT_HOST = '127.0.0.1' FLASK_DEFAULT_PORT = 7000 FLASK_DEFAULT_DEBUG = True FLASK_APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__))) FLASK_TEMPLATE_FOLDER = os.path.join(FLASK_APP_ROOT, 'templates') FLASK_STATIC_FOLDER = os.path.join(FLASK_APP_ROOT, 'static') app = Flask( import_name=__name__, template_folder=FLASK_TEMPLATE_FOLDER, static_folder=FLASK_STATIC_FOLDER, <|code_end|> . Use current file imports: (import os from flask import ( Flask, g, redirect, render_template, request, send_from_directory, ) from flask_bootstrap import Bootstrap from momo.plugins.flask import filters, functions from momo.plugins.flask.utils import get_public_functions from momo.plugins.flask.sorting import sort_nodes_by_request from momo.plugins.flask.nodes import merge_nodes from momo.utils import open_default) and context including class names, function names, or small code snippets from other files: # Path: momo/plugins/flask/filters.py # def txt_type(s): # def get_attr(node, attrname, default=None): # def get_parents(node): # def slugify(s): # def attr_image(node): # def attr_path(node): # def node_to_path(node): # def split_path(path): # def sort_attrs(attrs): # def pin_attrs(attrs): # def safe_quote(s): # # Path: momo/plugins/flask/functions.py # def paginate(page, total, per_page, config): # def _paginate(page, total, per_page, record_name, display_msg): # def get_page(request): # def toggle_arg(endpoint, request, arg, value, **kwargs): # # Path: momo/plugins/flask/utils.py # def get_public_functions(module): # """Get public functions in a module. Return a dictionary of function names # to objects.""" # return { # o[0]: o[1] for o in getmembers(module, isfunction) # if not o[0].startswith('_') # } # # Path: momo/plugins/flask/sorting.py # def sort_nodes_by_request(nodes, request, g, default_terms=None): # """High-level function to sort nodes with a request object.""" # sorting_terms = request.args.getlist('sort') or default_terms # desc = request.args.get('desc', default=False, type=str_to_bool) # if not sorting_terms: # if desc: # nodes.reverse() # else: # nodes = sort_nodes_by_terms( # terms=sorting_terms, # nodes=nodes, # desc=desc, # functions=g.sorting_functions, # ) # return nodes # # Path: momo/plugins/flask/nodes.py # def merge_nodes(nodes): # """ # Merge nodes to deduplicate same-name nodes and add a "parents" # attribute to each node, which is a list of Node objects. # """ # # def add_parent(unique_node, parent): # if getattr(unique_node, 'parents', None): # if parent.name not in unique_node.parents: # unique_node.parents[parent.name] = parent # else: # unique_node.parents = {parent.name: parent} # # names = OrderedDict() # for node in nodes: # if node.name not in names: # names[node.name] = node # add_parent(names[node.name], node.parent) # else: # add_parent(names[node.name], node.parent) # return names.values() # # Path: momo/utils.py # def open_default(path): # if platform.system() == 'Darwin': # sh.open(path) # elif os.name == 'nt': # os.startfile(path) # elif os.name == 'posix': # run = sh.Command('xdg-open') # run(path) . Output only the next line.
)
Given the following code snippet before the placeholder: <|code_start|> FLASK_DEFAULT_HOST = '127.0.0.1' FLASK_DEFAULT_PORT = 7000 FLASK_DEFAULT_DEBUG = True FLASK_APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__))) FLASK_TEMPLATE_FOLDER = os.path.join(FLASK_APP_ROOT, 'templates') <|code_end|> , predict the next line using imports from the current file: import os from flask import ( Flask, g, redirect, render_template, request, send_from_directory, ) from flask_bootstrap import Bootstrap from momo.plugins.flask import filters, functions from momo.plugins.flask.utils import get_public_functions from momo.plugins.flask.sorting import sort_nodes_by_request from momo.plugins.flask.nodes import merge_nodes from momo.utils import open_default and context including class names, function names, and sometimes code from other files: # Path: momo/plugins/flask/filters.py # def txt_type(s): # def get_attr(node, attrname, default=None): # def get_parents(node): # def slugify(s): # def attr_image(node): # def attr_path(node): # def node_to_path(node): # def split_path(path): # def sort_attrs(attrs): # def pin_attrs(attrs): # def safe_quote(s): # # Path: momo/plugins/flask/functions.py # def paginate(page, total, per_page, config): # def _paginate(page, total, per_page, record_name, display_msg): # def get_page(request): # def toggle_arg(endpoint, request, arg, value, **kwargs): # # Path: momo/plugins/flask/utils.py # def get_public_functions(module): # """Get public functions in a module. Return a dictionary of function names # to objects.""" # return { # o[0]: o[1] for o in getmembers(module, isfunction) # if not o[0].startswith('_') # } # # Path: momo/plugins/flask/sorting.py # def sort_nodes_by_request(nodes, request, g, default_terms=None): # """High-level function to sort nodes with a request object.""" # sorting_terms = request.args.getlist('sort') or default_terms # desc = request.args.get('desc', default=False, type=str_to_bool) # if not sorting_terms: # if desc: # nodes.reverse() # else: # nodes = sort_nodes_by_terms( # terms=sorting_terms, # nodes=nodes, # desc=desc, # functions=g.sorting_functions, # ) # return nodes # # Path: momo/plugins/flask/nodes.py # def merge_nodes(nodes): # """ # Merge nodes to deduplicate same-name nodes and add a "parents" # attribute to each node, which is a list of Node objects. # """ # # def add_parent(unique_node, parent): # if getattr(unique_node, 'parents', None): # if parent.name not in unique_node.parents: # unique_node.parents[parent.name] = parent # else: # unique_node.parents = {parent.name: parent} # # names = OrderedDict() # for node in nodes: # if node.name not in names: # names[node.name] = node # add_parent(names[node.name], node.parent) # else: # add_parent(names[node.name], node.parent) # return names.values() # # Path: momo/utils.py # def open_default(path): # if platform.system() == 'Darwin': # sh.open(path) # elif os.name == 'nt': # os.startfile(path) # elif os.name == 'posix': # run = sh.Command('xdg-open') # run(path) . Output only the next line.
FLASK_STATIC_FOLDER = os.path.join(FLASK_APP_ROOT, 'static')
Predict the next line after this snippet: <|code_start|> TEST_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, '__tests__')) @pytest.fixture def testdir(request): mkdir_p(TEST_DIR) @request.addfinalizer def cleanup(): <|code_end|> using the current file's imports: import os import pytest import shutil from momo.utils import mkdir_p and any relevant context from other files: # Path: momo/utils.py # def mkdir_p(path): # """mkdir -p path""" # if PY3: # return os.makedirs(path, exist_ok=True) # try: # os.makedirs(path) # except OSError as exc: # if exc.errno == errno.EEXIST and os.path.isdir(path): # pass # else: # raise . Output only the next line.
shutil.rmtree(TEST_DIR)
Here is a snippet: <|code_start|> "in | outt -> TRUE", "A + B = C - D", "b + next(1) -", "a := b" ] for expr in exprs: with self.assertRaises(NuSMVParsingError): node = parse_next_expression(expr) def test_good_identifiers(self): exprs = ["a", "a[4]", "t[v.r]", "inn", "AA", "a.b" ] for expr in exprs: node = parse_identifier(expr) self.assertIsNotNone(node) self.assertIsNotNone(nsnode.sprint_node(node)) def test_bad_identifiers(self): exprs = ["a =", "e <=> 56", <|code_end|> . Write the next line using the current file imports: import unittest import sys from pynusmv_lower_interface.nusmv.node import node as nsnode from pynusmv_lower_interface.nusmv.parser import parser as nsparser from pynusmv.parser import * from pynusmv.exception import NuSMVParsingError from pynusmv.init import init_nusmv, deinit_nusmv and context from other files: # Path: pynusmv/exception.py # class NuSMVParsingError(PyNuSMVError): # # """ # A :class:`NuSMVParsingError` is a NuSMV parsing exception. Contains several # errors accessible through the :attr:`errors` attribute. # # """ # # def __init__(self, errors): # """ # Initialize this exception with errors. # # :param errors: a tuple of errors # :type errors: tuple(:class:`Error`) # """ # super(NuSMVParsingError, self).__init__(self) # self._errors = errors # # @staticmethod # def from_nusmv_errors_list(errors): # """ # Create a new NuSMVParsingError from the given list of NuSMV errors. # # :param errors: the list of errors from NuSMV # """ # errlist = [] # while errors is not None: # error = nsnode.car(errors) # err = nsparser.Parser_get_syntax_error(error) # errlist.append(_Error(*err[1:])) # errors = nsnode.cdr(errors) # return NuSMVParsingError(tuple(errlist)) # # def __str__(self): # return "\n".join([str(err) for err in self._errors]) # # def __repr__(self): # return repr(self._errors) # # @property # def errors(self): # """ # The tuple of errors of this exception. These errors are tuples # `(line, token, message)` representing the line, the token and the # message of the error. # # """ # return self._errors # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() , which may include functions, classes, or code. Output only the next line.
"--",
Based on the snippet: <|code_start|> for expr in exprs: with self.assertRaises(NuSMVParsingError): node = parse_next_expression(expr) def test_good_identifiers(self): exprs = ["a", "a[4]", "t[v.r]", "inn", "AA", "a.b" ] for expr in exprs: node = parse_identifier(expr) self.assertIsNotNone(node) self.assertIsNotNone(nsnode.sprint_node(node)) def test_bad_identifiers(self): exprs = ["a =", "e <=> 56", "--", "a[4] % t[v]", # The lexer prints an error message at stderr # cannot be avoided "in | outt -> TRUE", "A + B = C - D", <|code_end|> , predict the immediate next line with the help of imports: import unittest import sys from pynusmv_lower_interface.nusmv.node import node as nsnode from pynusmv_lower_interface.nusmv.parser import parser as nsparser from pynusmv.parser import * from pynusmv.exception import NuSMVParsingError from pynusmv.init import init_nusmv, deinit_nusmv and context (classes, functions, sometimes code) from other files: # Path: pynusmv/exception.py # class NuSMVParsingError(PyNuSMVError): # # """ # A :class:`NuSMVParsingError` is a NuSMV parsing exception. Contains several # errors accessible through the :attr:`errors` attribute. # # """ # # def __init__(self, errors): # """ # Initialize this exception with errors. # # :param errors: a tuple of errors # :type errors: tuple(:class:`Error`) # """ # super(NuSMVParsingError, self).__init__(self) # self._errors = errors # # @staticmethod # def from_nusmv_errors_list(errors): # """ # Create a new NuSMVParsingError from the given list of NuSMV errors. # # :param errors: the list of errors from NuSMV # """ # errlist = [] # while errors is not None: # error = nsnode.car(errors) # err = nsparser.Parser_get_syntax_error(error) # errlist.append(_Error(*err[1:])) # errors = nsnode.cdr(errors) # return NuSMVParsingError(tuple(errlist)) # # def __str__(self): # return "\n".join([str(err) for err in self._errors]) # # def __repr__(self): # return repr(self._errors) # # @property # def errors(self): # """ # The tuple of errors of this exception. These errors are tuples # `(line, token, message)` representing the line, the token and the # message of the error. # # """ # return self._errors # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() . Output only the next line.
"b + 1 -",
Predict the next line for this snippet: <|code_start|> def setUp(self): init_nusmv() def tearDown(self): deinit_nusmv() def test_good_simple_expressions(self): exprs = ["a.car = 3", "e <= 56", "a[4] & t[v]", "inn | outt -> TRUE", "AA + B = C - D", "a -- b = c" # OK because b = c is commented so the expr is 'a' ] for expr in exprs: node = parse_simple_expression(expr) self.assertIsNotNone(node) self.assertIsNotNone(nsnode.sprint_node(node)) def test_bad_simple_expressions(self): exprs = ["a =", "e <=> 56", "--", "a[4] % t[v]", # The lexer prints an error message at stderr # cannot be avoided "in | outt -> TRUE", "A + B = C - D", <|code_end|> with the help of current file imports: import unittest import sys from pynusmv_lower_interface.nusmv.node import node as nsnode from pynusmv_lower_interface.nusmv.parser import parser as nsparser from pynusmv.parser import * from pynusmv.exception import NuSMVParsingError from pynusmv.init import init_nusmv, deinit_nusmv and context from other files: # Path: pynusmv/exception.py # class NuSMVParsingError(PyNuSMVError): # # """ # A :class:`NuSMVParsingError` is a NuSMV parsing exception. Contains several # errors accessible through the :attr:`errors` attribute. # # """ # # def __init__(self, errors): # """ # Initialize this exception with errors. # # :param errors: a tuple of errors # :type errors: tuple(:class:`Error`) # """ # super(NuSMVParsingError, self).__init__(self) # self._errors = errors # # @staticmethod # def from_nusmv_errors_list(errors): # """ # Create a new NuSMVParsingError from the given list of NuSMV errors. # # :param errors: the list of errors from NuSMV # """ # errlist = [] # while errors is not None: # error = nsnode.car(errors) # err = nsparser.Parser_get_syntax_error(error) # errlist.append(_Error(*err[1:])) # errors = nsnode.cdr(errors) # return NuSMVParsingError(tuple(errlist)) # # def __str__(self): # return "\n".join([str(err) for err in self._errors]) # # def __repr__(self): # return repr(self._errors) # # @property # def errors(self): # """ # The tuple of errors of this exception. These errors are tuples # `(line, token, message)` representing the line, the token and the # message of the error. # # """ # return self._errors # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() , which may contain function names, class names, or code. Output only the next line.
"b + 1 -",
Next line prediction: <|code_start|> class TestPropDb(unittest.TestCase): def setUp(self): init_nusmv() ret = cmd.Cmd_SecureCommandExecute("read_model -i" " tests/pynusmv/models/admin.smv") self.assertEqual(ret, 0) ret = cmd.Cmd_SecureCommandExecute("go") self.assertEqual(ret, 0) def tearDown(self): deinit_nusmv() def test_propDb(self): propDb = glob.prop_database() self.assertTrue(propDb.get_size() >= 1, "propDb misses some props") prop = propDb.get_prop_at_index(0) self.assertIsNotNone(prop, "prop should not be None") <|code_end|> . Use current file imports: (import unittest import sys from pynusmv_lower_interface.nusmv.cmd import cmd from pynusmv.prop import PropDb, propTypes from pynusmv import glob from pynusmv.init import init_nusmv, deinit_nusmv) and context including class names, function names, or small code snippets from other files: # Path: pynusmv/prop.py # class Prop(PointerWrapper): # class PropDb(PointerWrapper): # class Spec(PointerWrapper): # def type(self): # def status(self): # def name(self): # def expr(self): # def exprcore(self): # def bddFsm(self): # def beFsm(self): # def scalarFsm(self): # def booleanFsm(self): # def need_rewriting(self): # def master(self): # def get_prop_at_index(self, index): # def get_size(self): # def get_props_of_type(self, prop_type): # def __len__(self): # def __getitem__(self, index): # def __iter__(self): # def __init__(self, ptr, freeit=False): # def _free(self): # def type(self): # def car(self): # def cdr(self): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def __or__(self, other): # def __and__(self, other): # def __invert__(self): # def true(): # def false(): # def not_(spec): # def and_(left, right): # def or_(left, right): # def imply(left, right): # def iff(left, right): # def ex(spec): # def eg(spec): # def ef(spec): # def eu(left, right): # def ew(left, right): # def ax(spec): # def ag(spec): # def af(spec): # def au(left, right): # def aw(left, right): # def x(spec): # def g(spec): # def f(spec): # def u(left, right): # def atom(strrep, type_checking=True): # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() . Output only the next line.
self.assertEqual(len(propDb), propDb.get_size())
Based on the snippet: <|code_start|> class TestPropDb(unittest.TestCase): def setUp(self): init_nusmv() ret = cmd.Cmd_SecureCommandExecute("read_model -i" " tests/pynusmv/models/admin.smv") self.assertEqual(ret, 0) ret = cmd.Cmd_SecureCommandExecute("go") <|code_end|> , predict the immediate next line with the help of imports: import unittest import sys from pynusmv_lower_interface.nusmv.cmd import cmd from pynusmv.prop import PropDb, propTypes from pynusmv import glob from pynusmv.init import init_nusmv, deinit_nusmv and context (classes, functions, sometimes code) from other files: # Path: pynusmv/prop.py # class Prop(PointerWrapper): # class PropDb(PointerWrapper): # class Spec(PointerWrapper): # def type(self): # def status(self): # def name(self): # def expr(self): # def exprcore(self): # def bddFsm(self): # def beFsm(self): # def scalarFsm(self): # def booleanFsm(self): # def need_rewriting(self): # def master(self): # def get_prop_at_index(self, index): # def get_size(self): # def get_props_of_type(self, prop_type): # def __len__(self): # def __getitem__(self, index): # def __iter__(self): # def __init__(self, ptr, freeit=False): # def _free(self): # def type(self): # def car(self): # def cdr(self): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def __or__(self, other): # def __and__(self, other): # def __invert__(self): # def true(): # def false(): # def not_(spec): # def and_(left, right): # def or_(left, right): # def imply(left, right): # def iff(left, right): # def ex(spec): # def eg(spec): # def ef(spec): # def eu(left, right): # def ew(left, right): # def ax(spec): # def ag(spec): # def af(spec): # def au(left, right): # def aw(left, right): # def x(spec): # def g(spec): # def f(spec): # def u(left, right): # def atom(strrep, type_checking=True): # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() . Output only the next line.
self.assertEqual(ret, 0)
Predict the next line for this snippet: <|code_start|> class TestPropDb(unittest.TestCase): def setUp(self): init_nusmv() ret = cmd.Cmd_SecureCommandExecute("read_model -i" " tests/pynusmv/models/admin.smv") self.assertEqual(ret, 0) ret = cmd.Cmd_SecureCommandExecute("go") self.assertEqual(ret, 0) def tearDown(self): deinit_nusmv() <|code_end|> with the help of current file imports: import unittest import sys from pynusmv_lower_interface.nusmv.cmd import cmd from pynusmv.prop import PropDb, propTypes from pynusmv import glob from pynusmv.init import init_nusmv, deinit_nusmv and context from other files: # Path: pynusmv/prop.py # class Prop(PointerWrapper): # class PropDb(PointerWrapper): # class Spec(PointerWrapper): # def type(self): # def status(self): # def name(self): # def expr(self): # def exprcore(self): # def bddFsm(self): # def beFsm(self): # def scalarFsm(self): # def booleanFsm(self): # def need_rewriting(self): # def master(self): # def get_prop_at_index(self, index): # def get_size(self): # def get_props_of_type(self, prop_type): # def __len__(self): # def __getitem__(self, index): # def __iter__(self): # def __init__(self, ptr, freeit=False): # def _free(self): # def type(self): # def car(self): # def cdr(self): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def __or__(self, other): # def __and__(self, other): # def __invert__(self): # def true(): # def false(): # def not_(spec): # def and_(left, right): # def or_(left, right): # def imply(left, right): # def iff(left, right): # def ex(spec): # def eg(spec): # def ef(spec): # def eu(left, right): # def ew(left, right): # def ax(spec): # def ag(spec): # def af(spec): # def au(left, right): # def aw(left, right): # def x(spec): # def g(spec): # def f(spec): # def u(left, right): # def atom(strrep, type_checking=True): # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() , which may contain function names, class names, or code. Output only the next line.
def test_propDb(self):
Here is a snippet: <|code_start|> class TestPropDb(unittest.TestCase): def setUp(self): init_nusmv() def tearDown(self): deinit_nusmv() def load_admin_model(self): glob.load("tests/pynusmv/models/admin.smv") glob.compute_model() def test_prop(self): self.load_admin_model() propDb = glob.prop_database() fsm = propDb.master.bddFsm <|code_end|> . Write the next line using the current file imports: import unittest import sys from pynusmv import glob from pynusmv.prop import propStatuses from pynusmv.init import init_nusmv, deinit_nusmv and context from other files: # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/prop.py # class Prop(PointerWrapper): # class PropDb(PointerWrapper): # class Spec(PointerWrapper): # def type(self): # def status(self): # def name(self): # def expr(self): # def exprcore(self): # def bddFsm(self): # def beFsm(self): # def scalarFsm(self): # def booleanFsm(self): # def need_rewriting(self): # def master(self): # def get_prop_at_index(self, index): # def get_size(self): # def get_props_of_type(self, prop_type): # def __len__(self): # def __getitem__(self, index): # def __iter__(self): # def __init__(self, ptr, freeit=False): # def _free(self): # def type(self): # def car(self): # def cdr(self): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def __or__(self, other): # def __and__(self, other): # def __invert__(self): # def true(): # def false(): # def not_(spec): # def and_(left, right): # def or_(left, right): # def imply(left, right): # def iff(left, right): # def ex(spec): # def eg(spec): # def ef(spec): # def eu(left, right): # def ew(left, right): # def ax(spec): # def ag(spec): # def af(spec): # def au(left, right): # def aw(left, right): # def x(spec): # def g(spec): # def f(spec): # def u(left, right): # def atom(strrep, type_checking=True): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() , which may include functions, classes, or code. Output only the next line.
prop1 = propDb[0]
Predict the next line after this snippet: <|code_start|> class TestPropDb(unittest.TestCase): def setUp(self): init_nusmv() def tearDown(self): deinit_nusmv() def load_admin_model(self): glob.load("tests/pynusmv/models/admin.smv") glob.compute_model() <|code_end|> using the current file's imports: import unittest import sys from pynusmv import glob from pynusmv.prop import propStatuses from pynusmv.init import init_nusmv, deinit_nusmv and any relevant context from other files: # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/prop.py # class Prop(PointerWrapper): # class PropDb(PointerWrapper): # class Spec(PointerWrapper): # def type(self): # def status(self): # def name(self): # def expr(self): # def exprcore(self): # def bddFsm(self): # def beFsm(self): # def scalarFsm(self): # def booleanFsm(self): # def need_rewriting(self): # def master(self): # def get_prop_at_index(self, index): # def get_size(self): # def get_props_of_type(self, prop_type): # def __len__(self): # def __getitem__(self, index): # def __iter__(self): # def __init__(self, ptr, freeit=False): # def _free(self): # def type(self): # def car(self): # def cdr(self): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def __or__(self, other): # def __and__(self, other): # def __invert__(self): # def true(): # def false(): # def not_(spec): # def and_(left, right): # def or_(left, right): # def imply(left, right): # def iff(left, right): # def ex(spec): # def eg(spec): # def ef(spec): # def eu(left, right): # def ew(left, right): # def ax(spec): # def ag(spec): # def af(spec): # def au(left, right): # def aw(left, right): # def x(spec): # def g(spec): # def f(spec): # def u(left, right): # def atom(strrep, type_checking=True): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() . Output only the next line.
def test_prop(self):
Next line prediction: <|code_start|> class TestPropDb(unittest.TestCase): def setUp(self): init_nusmv() def tearDown(self): deinit_nusmv() def load_admin_model(self): glob.load("tests/pynusmv/models/admin.smv") glob.compute_model() <|code_end|> . Use current file imports: (import unittest import sys from pynusmv import glob from pynusmv.prop import propStatuses from pynusmv.init import init_nusmv, deinit_nusmv) and context including class names, function names, or small code snippets from other files: # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/prop.py # class Prop(PointerWrapper): # class PropDb(PointerWrapper): # class Spec(PointerWrapper): # def type(self): # def status(self): # def name(self): # def expr(self): # def exprcore(self): # def bddFsm(self): # def beFsm(self): # def scalarFsm(self): # def booleanFsm(self): # def need_rewriting(self): # def master(self): # def get_prop_at_index(self, index): # def get_size(self): # def get_props_of_type(self, prop_type): # def __len__(self): # def __getitem__(self, index): # def __iter__(self): # def __init__(self, ptr, freeit=False): # def _free(self): # def type(self): # def car(self): # def cdr(self): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def __or__(self, other): # def __and__(self, other): # def __invert__(self): # def true(): # def false(): # def not_(spec): # def and_(left, right): # def or_(left, right): # def imply(left, right): # def iff(left, right): # def ex(spec): # def eg(spec): # def ef(spec): # def eu(left, right): # def ew(left, right): # def ax(spec): # def ag(spec): # def af(spec): # def au(left, right): # def aw(left, right): # def x(spec): # def g(spec): # def f(spec): # def u(left, right): # def atom(strrep, type_checking=True): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() . Output only the next line.
def test_prop(self):
Based on the snippet: <|code_start|> class TestPropDb(unittest.TestCase): def setUp(self): init_nusmv() def tearDown(self): deinit_nusmv() def load_admin_model(self): glob.load("tests/pynusmv/models/admin.smv") glob.compute_model() def test_prop(self): self.load_admin_model() propDb = glob.prop_database() <|code_end|> , predict the immediate next line with the help of imports: import unittest import sys from pynusmv import glob from pynusmv.prop import propStatuses from pynusmv.init import init_nusmv, deinit_nusmv and context (classes, functions, sometimes code) from other files: # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/prop.py # class Prop(PointerWrapper): # class PropDb(PointerWrapper): # class Spec(PointerWrapper): # def type(self): # def status(self): # def name(self): # def expr(self): # def exprcore(self): # def bddFsm(self): # def beFsm(self): # def scalarFsm(self): # def booleanFsm(self): # def need_rewriting(self): # def master(self): # def get_prop_at_index(self, index): # def get_size(self): # def get_props_of_type(self, prop_type): # def __len__(self): # def __getitem__(self, index): # def __iter__(self): # def __init__(self, ptr, freeit=False): # def _free(self): # def type(self): # def car(self): # def cdr(self): # def __str__(self): # def __eq__(self, other): # def __hash__(self): # def __or__(self, other): # def __and__(self, other): # def __invert__(self): # def true(): # def false(): # def not_(spec): # def and_(left, right): # def or_(left, right): # def imply(left, right): # def iff(left, right): # def ex(spec): # def eg(spec): # def ef(spec): # def eu(left, right): # def ew(left, right): # def ax(spec): # def ag(spec): # def af(spec): # def au(left, right): # def aw(left, right): # def x(spec): # def g(spec): # def f(spec): # def u(left, right): # def atom(strrep, type_checking=True): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() . Output only the next line.
fsm = propDb.master.bddFsm
Next line prediction: <|code_start|> # -- is the comment, this input is well formed "cat -- dog is < than cat ++ dog"] for test in tests_ok: node, err = nsparser.ReadSimpExprFromString(test) self.assertEqual(err, 0) self.assertIsNone(nsparser.Parser_get_syntax_errors_list()) self.assertEqual(node.type, nsparser.SIMPWFF) tests_ko = [ "3 + ", "a / b)", "a ** b ++ c", "strings are good", "test on", "(a + b) - c * 4[-]", "test - c\n= 5[]", "next(i) = 3"#, "a % b" ] # FIXME Segmentation fault when trying to read an expression containing # a % character for test in tests_ko: node, err = nsparser.ReadSimpExprFromString(test) if node is not None: self.assertEqual(node.type, nsparser.SIMPWFF) self.assertTrue(err > 0) # err = 1 means there is a parse error # err = 2 means there is an exception if err == 1: self.assertIsNotNone(nsparser.Parser_get_syntax_errors_list()) errors = nsparser.Parser_get_syntax_errors_list() while errors is not None: error = car(errors) <|code_end|> . Use current file imports: (import unittest from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv_lower_interface.nusmv.parser import parser as nsparser from pynusmv_lower_interface.nusmv.utils import utils as nsutils from pynusmv_lower_interface.nusmv.node import node as nsnode from pynusmv_lower_interface.nusmv.opt import opt as nsopt from pynusmv_lower_interface.nusmv.cmd import cmd as nscmd) and context including class names, function names, or small code snippets from other files: # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() . Output only the next line.
err = nsparser.Parser_get_syntax_error(error)
Given the code snippet: <|code_start|> def test_identifier(self): car = nsnode.car cdr = nsnode.cdr tests_ok = ["a", "a[3]", "a[b]", "a3", "ab_cd", "o0"] for test in tests_ok: node, err = nsparser.ReadIdentifierExprFromString(test) self.assertEqual(err, 0) self.assertIsNone(nsparser.Parser_get_syntax_errors_list()) self.assertEqual(node.type, nsparser.COMPID) tests_ko = [ "c = 3", "a[]", "a[3", "next(i)", "0x52" ] for test in tests_ko: node, err = nsparser.ReadIdentifierExprFromString(test) if node is not None: self.assertEqual(node.type, nsparser.COMPID) self.assertTrue(err > 0) # err = 1 means there is a parse error # err = 2 means there is an exception if err == 1: self.assertIsNotNone(nsparser.Parser_get_syntax_errors_list()) errors = nsparser.Parser_get_syntax_errors_list() while errors is not None: error = car(errors) <|code_end|> , generate the next line using the imports in this file: import unittest from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv_lower_interface.nusmv.parser import parser as nsparser from pynusmv_lower_interface.nusmv.utils import utils as nsutils from pynusmv_lower_interface.nusmv.node import node as nsnode from pynusmv_lower_interface.nusmv.opt import opt as nsopt from pynusmv_lower_interface.nusmv.cmd import cmd as nscmd and context (functions, classes, or occasionally code) from other files: # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() . Output only the next line.
err = nsparser.Parser_get_syntax_error(error)
Using the snippet: <|code_start|> class TestEval(unittest.TestCase): def setUp(self): init_nusmv() def tearDown(self): deinit_nusmv() def model(self): glob.load_from_file("tests/pynusmv/models/cardgame-post-fair.smv") glob.compute_model() fsm = glob.prop_database().master.bddFsm self.assertIsNotNone(fsm) return fsm def show_si(self, fsm, bdd): for si in fsm.pick_all_states_inputs(bdd): print(si.get_str_values()) def show_s(self, fsm, bdd): for s in fsm.pick_all_states(bdd): print(s.get_str_values()) def show_i(self, fsm, bdd): for i in fsm.pick_all_inputs(bdd): print(i.get_str_values()) <|code_end|> , determine the next line of code. You have imports: import unittest from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv import glob from pynusmv.mc import eval_simple_expression and context (class names, function names, or code) available: # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/mc.py # def eval_simple_expression(fsm, sexp): # """ # Return the set of states of `fsm` satisfying `sexp`, as a BDD. # `sexp` is first parsed, then evaluated on `fsm`. # # :param fsm: the concerned FSM # :type fsm: :class:`BddFsm <pynusmv.fsm.BddFsm>` # :param sexp: a simple expression, as a string # :rtype: :class:`BDD <pynusmv.dd.BDD>` # # """ # return eval_ctl_spec(fsm, atom(sexp)) . Output only the next line.
def test_eval_and_mask(self):
Predict the next line for this snippet: <|code_start|> dda = eval_simple_expression(fsm, "ddcard = Ac") ddk = eval_simple_expression(fsm, "ddcard = K") ddq = eval_simple_expression(fsm, "ddcard = Q") pan = eval_simple_expression(fsm, "player.action = none") pak = eval_simple_expression(fsm, "player.action = keep") pas = eval_simple_expression(fsm, "player.action = swap") dan = eval_simple_expression(fsm, "dealer.action = none") win = eval_simple_expression(fsm, "win") lose = eval_simple_expression(fsm, "lose") true = eval_simple_expression(fsm, "TRUE") false = eval_simple_expression(fsm, "FALSE") self.assertNotEqual(pan, pan & fsm.bddEnc.statesInputsMask) self.assertNotEqual(s1, s1 & fsm.bddEnc.statesInputsMask) self.assertNotEqual(true, true & fsm.bddEnc.statesInputsMask) self.assertEqual((pan | s1) & fsm.bddEnc.statesInputsMask, (pan & fsm.bddEnc.statesInputsMask) | (s1 & fsm.bddEnc.statesInputsMask)) pan_si = pan & fsm.bddEnc.statesInputsMask s1_si = s1 & fsm.bddEnc.statesInputsMask self.assertEqual(pan_si & s1_si, pan_si & s1_si & fsm.bddEnc.statesInputsMask) self.assertEqual(pan_si | s1_si, (pan_si | s1_si) & fsm.bddEnc.statesInputsMask) <|code_end|> with the help of current file imports: import unittest from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv import glob from pynusmv.mc import eval_simple_expression and context from other files: # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/mc.py # def eval_simple_expression(fsm, sexp): # """ # Return the set of states of `fsm` satisfying `sexp`, as a BDD. # `sexp` is first parsed, then evaluated on `fsm`. # # :param fsm: the concerned FSM # :type fsm: :class:`BddFsm <pynusmv.fsm.BddFsm>` # :param sexp: a simple expression, as a string # :rtype: :class:`BDD <pynusmv.dd.BDD>` # # """ # return eval_ctl_spec(fsm, atom(sexp)) , which may contain function names, class names, or code. Output only the next line.
self.assertNotEqual(~pan_si, ~pan_si & fsm.bddEnc.statesInputsMask)
Continue the code snippet: <|code_start|> dda = eval_simple_expression(fsm, "ddcard = Ac") ddk = eval_simple_expression(fsm, "ddcard = K") ddq = eval_simple_expression(fsm, "ddcard = Q") pan = eval_simple_expression(fsm, "player.action = none") pak = eval_simple_expression(fsm, "player.action = keep") pas = eval_simple_expression(fsm, "player.action = swap") dan = eval_simple_expression(fsm, "dealer.action = none") win = eval_simple_expression(fsm, "win") lose = eval_simple_expression(fsm, "lose") true = eval_simple_expression(fsm, "TRUE") false = eval_simple_expression(fsm, "FALSE") self.assertNotEqual(pan, pan & fsm.bddEnc.statesInputsMask) self.assertNotEqual(s1, s1 & fsm.bddEnc.statesInputsMask) self.assertNotEqual(true, true & fsm.bddEnc.statesInputsMask) self.assertEqual((pan | s1) & fsm.bddEnc.statesInputsMask, (pan & fsm.bddEnc.statesInputsMask) | (s1 & fsm.bddEnc.statesInputsMask)) pan_si = pan & fsm.bddEnc.statesInputsMask s1_si = s1 & fsm.bddEnc.statesInputsMask self.assertEqual(pan_si & s1_si, pan_si & s1_si & fsm.bddEnc.statesInputsMask) self.assertEqual(pan_si | s1_si, (pan_si | s1_si) & fsm.bddEnc.statesInputsMask) <|code_end|> . Use current file imports: import unittest from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv import glob from pynusmv.mc import eval_simple_expression and context (classes, functions, or code) from other files: # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/mc.py # def eval_simple_expression(fsm, sexp): # """ # Return the set of states of `fsm` satisfying `sexp`, as a BDD. # `sexp` is first parsed, then evaluated on `fsm`. # # :param fsm: the concerned FSM # :type fsm: :class:`BddFsm <pynusmv.fsm.BddFsm>` # :param sexp: a simple expression, as a string # :rtype: :class:`BDD <pynusmv.dd.BDD>` # # """ # return eval_ctl_spec(fsm, atom(sexp)) . Output only the next line.
self.assertNotEqual(~pan_si, ~pan_si & fsm.bddEnc.statesInputsMask)
Continue the code snippet: <|code_start|> dk = eval_simple_expression(fsm, "dcard = K") dq = eval_simple_expression(fsm, "dcard = Q") dda = eval_simple_expression(fsm, "ddcard = Ac") ddk = eval_simple_expression(fsm, "ddcard = K") ddq = eval_simple_expression(fsm, "ddcard = Q") pan = eval_simple_expression(fsm, "player.action = none") pak = eval_simple_expression(fsm, "player.action = keep") pas = eval_simple_expression(fsm, "player.action = swap") dan = eval_simple_expression(fsm, "dealer.action = none") win = eval_simple_expression(fsm, "win") lose = eval_simple_expression(fsm, "lose") true = eval_simple_expression(fsm, "TRUE") false = eval_simple_expression(fsm, "FALSE") self.assertNotEqual(pan, pan & fsm.bddEnc.statesInputsMask) self.assertNotEqual(s1, s1 & fsm.bddEnc.statesInputsMask) self.assertNotEqual(true, true & fsm.bddEnc.statesInputsMask) self.assertEqual((pan | s1) & fsm.bddEnc.statesInputsMask, (pan & fsm.bddEnc.statesInputsMask) | (s1 & fsm.bddEnc.statesInputsMask)) pan_si = pan & fsm.bddEnc.statesInputsMask s1_si = s1 & fsm.bddEnc.statesInputsMask <|code_end|> . Use current file imports: import unittest from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv import glob from pynusmv.mc import eval_simple_expression and context (classes, functions, or code) from other files: # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/mc.py # def eval_simple_expression(fsm, sexp): # """ # Return the set of states of `fsm` satisfying `sexp`, as a BDD. # `sexp` is first parsed, then evaluated on `fsm`. # # :param fsm: the concerned FSM # :type fsm: :class:`BddFsm <pynusmv.fsm.BddFsm>` # :param sexp: a simple expression, as a string # :rtype: :class:`BDD <pynusmv.dd.BDD>` # # """ # return eval_ctl_spec(fsm, atom(sexp)) . Output only the next line.
self.assertEqual(pan_si & s1_si, pan_si & s1_si & fsm.bddEnc.statesInputsMask)
Here is a snippet: <|code_start|> class TestTypeChecking(unittest.TestCase): def setUp(self): init_nusmv() def tearDown(self): deinit_nusmv() def test_get_mod_instance_type(self): glob.load_from_file("tests/pynusmv/models/counters.smv") glob.compute_model() sexp = parse_simple_expression("c1") self.assertIsNotNone(sexp) st = glob.symb_table() tp = nssymb_table.SymbTable_get_type_checker(st._ptr) <|code_end|> . Write the next line using the current file imports: import unittest from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv import glob from pynusmv.parser import parse_simple_expression from pynusmv_lower_interface.nusmv.compile.symb_table import symb_table as nssymb_table from pynusmv_lower_interface.nusmv.compile.type_checking import type_checking as nstype_checking and context from other files: # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/parser.py # def parse_simple_expression(expression): # """ # Parse a simple expression. # # :param string expression: the expression to parse # :raise: a :exc:`NuSMVParsingError # <pynusmv.exception.NuSMVParsingError>` # if a parsing error occurs # # .. warning:: Returned value is a SWIG wrapper for the NuSMV node_ptr. # It is the responsibility of the caller to manage it. # # """ # node, err = nsparser.ReadSimpExprFromString(expression) # if err: # errors = nsparser.Parser_get_syntax_errors_list() # raise NuSMVParsingError.from_nusmv_errors_list(errors) # else: # node = nsnode.car(node) # Get rid of the top SIMPWFF node # if node.type is nsparser.CONTEXT and nsnode.car(node) is None: # # Get rid of the top empty context if any # return nsnode.cdr(node) # else: # return node , which may include functions, classes, or code. Output only the next line.
expr_type = nstype_checking.TypeChecker_get_expression_type(
Given the following code snippet before the placeholder: <|code_start|> class TestTypeChecking(unittest.TestCase): def setUp(self): init_nusmv() def tearDown(self): deinit_nusmv() def test_get_mod_instance_type(self): glob.load_from_file("tests/pynusmv/models/counters.smv") glob.compute_model() sexp = parse_simple_expression("c1") <|code_end|> , predict the next line using imports from the current file: import unittest from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv import glob from pynusmv.parser import parse_simple_expression from pynusmv_lower_interface.nusmv.compile.symb_table import symb_table as nssymb_table from pynusmv_lower_interface.nusmv.compile.type_checking import type_checking as nstype_checking and context including class names, function names, and sometimes code from other files: # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/parser.py # def parse_simple_expression(expression): # """ # Parse a simple expression. # # :param string expression: the expression to parse # :raise: a :exc:`NuSMVParsingError # <pynusmv.exception.NuSMVParsingError>` # if a parsing error occurs # # .. warning:: Returned value is a SWIG wrapper for the NuSMV node_ptr. # It is the responsibility of the caller to manage it. # # """ # node, err = nsparser.ReadSimpExprFromString(expression) # if err: # errors = nsparser.Parser_get_syntax_errors_list() # raise NuSMVParsingError.from_nusmv_errors_list(errors) # else: # node = nsnode.car(node) # Get rid of the top SIMPWFF node # if node.type is nsparser.CONTEXT and nsnode.car(node) is None: # # Get rid of the top empty context if any # return nsnode.cdr(node) # else: # return node . Output only the next line.
self.assertIsNotNone(sexp)
Given the code snippet: <|code_start|> class TestTypeChecking(unittest.TestCase): def setUp(self): init_nusmv() <|code_end|> , generate the next line using the imports in this file: import unittest from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv import glob from pynusmv.parser import parse_simple_expression from pynusmv_lower_interface.nusmv.compile.symb_table import symb_table as nssymb_table from pynusmv_lower_interface.nusmv.compile.type_checking import type_checking as nstype_checking and context (functions, classes, or occasionally code) from other files: # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/parser.py # def parse_simple_expression(expression): # """ # Parse a simple expression. # # :param string expression: the expression to parse # :raise: a :exc:`NuSMVParsingError # <pynusmv.exception.NuSMVParsingError>` # if a parsing error occurs # # .. warning:: Returned value is a SWIG wrapper for the NuSMV node_ptr. # It is the responsibility of the caller to manage it. # # """ # node, err = nsparser.ReadSimpExprFromString(expression) # if err: # errors = nsparser.Parser_get_syntax_errors_list() # raise NuSMVParsingError.from_nusmv_errors_list(errors) # else: # node = nsnode.car(node) # Get rid of the top SIMPWFF node # if node.type is nsparser.CONTEXT and nsnode.car(node) is None: # # Get rid of the top empty context if any # return nsnode.cdr(node) # else: # return node . Output only the next line.
def tearDown(self):
Given the code snippet: <|code_start|> def setUp(self): init_nusmv() glob.load_from_file(self.model()) def tearDown(self): deinit_nusmv() def test_hierarchy_must_be_flattened(self): with self.assertRaises(NuSMVNeedVariablesEncodedError): glob.build_boolean_model() def test_vars_must_be_encoded(self): glob.flatten_hierarchy() with self.assertRaises(NuSMVNeedVariablesEncodedError): glob.build_boolean_model() def test_must_not_be_already_built(self): glob.flatten_hierarchy() glob.encode_variables() glob.build_boolean_model() with self.assertRaises(NuSMVModelAlreadyBuiltError): glob.build_boolean_model() def test_must_not_be_already_built_unless_force_flag(self): glob.flatten_hierarchy() glob.encode_variables() glob.build_boolean_model() glob.build_boolean_model(force=True) <|code_end|> , generate the next line using the imports in this file: import unittest from tests import utils as tests from pynusmv import glob from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv.exception import (NuSMVNeedVariablesEncodedError, NuSMVModelAlreadyBuiltError, NuSMVNeedBooleanModelError) and context (functions, classes, or occasionally code) from other files: # Path: tests/utils.py # def todo(fn): # def skip(reason): # def _log(fn, message): # def canonical_cnf(be): # def current_directory(what): # def __init__(self, testcase, location, model): # def __enter__(self): # def __exit__(self, type_, value, traceback): # class Configure: # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/exception.py # class NuSMVNeedVariablesEncodedError(PyNuSMVError): # # """ # Exception raised when the variables of the model must be encoded. # # """ # pass # # class NuSMVModelAlreadyBuiltError(PyNuSMVError): # # """ # Exception raised when the BDD model is already built. # # """ # pass # # class NuSMVNeedBooleanModelError(PyNuSMVError): # # """ # Exception raised when the boolean model must be created. # # """ # pass . Output only the next line.
def test_sets_the_global_values(self):
Next line prediction: <|code_start|> def setUp(self): init_nusmv() glob.load_from_file(self.model()) def tearDown(self): deinit_nusmv() def test_hierarchy_must_be_flattened(self): with self.assertRaises(NuSMVNeedVariablesEncodedError): glob.build_boolean_model() def test_vars_must_be_encoded(self): glob.flatten_hierarchy() with self.assertRaises(NuSMVNeedVariablesEncodedError): glob.build_boolean_model() def test_must_not_be_already_built(self): glob.flatten_hierarchy() glob.encode_variables() glob.build_boolean_model() with self.assertRaises(NuSMVModelAlreadyBuiltError): glob.build_boolean_model() def test_must_not_be_already_built_unless_force_flag(self): glob.flatten_hierarchy() glob.encode_variables() glob.build_boolean_model() glob.build_boolean_model(force=True) <|code_end|> . Use current file imports: (import unittest from tests import utils as tests from pynusmv import glob from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv.exception import (NuSMVNeedVariablesEncodedError, NuSMVModelAlreadyBuiltError, NuSMVNeedBooleanModelError)) and context including class names, function names, or small code snippets from other files: # Path: tests/utils.py # def todo(fn): # def skip(reason): # def _log(fn, message): # def canonical_cnf(be): # def current_directory(what): # def __init__(self, testcase, location, model): # def __enter__(self): # def __exit__(self, type_, value, traceback): # class Configure: # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/exception.py # class NuSMVNeedVariablesEncodedError(PyNuSMVError): # # """ # Exception raised when the variables of the model must be encoded. # # """ # pass # # class NuSMVModelAlreadyBuiltError(PyNuSMVError): # # """ # Exception raised when the BDD model is already built. # # """ # pass # # class NuSMVNeedBooleanModelError(PyNuSMVError): # # """ # Exception raised when the boolean model must be created. # # """ # pass . Output only the next line.
def test_sets_the_global_values(self):
Given the following code snippet before the placeholder: <|code_start|> class TestBuildBooleanModel(unittest.TestCase): def model(self): return tests.current_directory(__file__)+"/models/flipflops_trans_invar_fairness.smv" def setUp(self): init_nusmv() glob.load_from_file(self.model()) def tearDown(self): deinit_nusmv() def test_hierarchy_must_be_flattened(self): with self.assertRaises(NuSMVNeedVariablesEncodedError): glob.build_boolean_model() def test_vars_must_be_encoded(self): glob.flatten_hierarchy() with self.assertRaises(NuSMVNeedVariablesEncodedError): glob.build_boolean_model() def test_must_not_be_already_built(self): glob.flatten_hierarchy() glob.encode_variables() glob.build_boolean_model() with self.assertRaises(NuSMVModelAlreadyBuiltError): glob.build_boolean_model() <|code_end|> , predict the next line using imports from the current file: import unittest from tests import utils as tests from pynusmv import glob from pynusmv.init import init_nusmv, deinit_nusmv from pynusmv.exception import (NuSMVNeedVariablesEncodedError, NuSMVModelAlreadyBuiltError, NuSMVNeedBooleanModelError) and context including class names, function names, and sometimes code from other files: # Path: tests/utils.py # def todo(fn): # def skip(reason): # def _log(fn, message): # def canonical_cnf(be): # def current_directory(what): # def __init__(self, testcase, location, model): # def __enter__(self): # def __exit__(self, type_, value, traceback): # class Configure: # # Path: pynusmv/glob.py # def global_compile_cmps(): # def global_compile_flathierarchy(): # def _reset_globals(): # def load(*model): # def load_from_string(model): # def load_from_modules(*modules): # def load_from_file(filepath): # def flatten_hierarchy(keep_single_enum=False): # def symb_table(): # def encode_variables(layers=None, variables_ordering=None): # def encode_variables_for_layers(layers=None, init=False): # def bdd_encoding(): # def build_flat_model(): # def build_model(): # def build_boolean_model(force=False): # def master_bool_sexp_fsm(): # def flat_hierarchy(): # def prop_database(): # def compute_model(variables_ordering=None, keep_single_enum=False): # def is_cone_of_influence_enabled(): # # Path: pynusmv/init.py # def init_nusmv(collecting=True): # """ # Initialize NuSMV. Must be called only once before calling # :func:`deinit_nusmv`. # # :param collecting: Whether or not collecting pointer wrappers to free them # before deiniting nusmv. # # .. warning: Deactivating the collection of pointer wrappers may provoke # segmentation faults when deiniting nusmv without correctly # freeing all pointer wrappers in advance. # On the other hand, collection may blow memory. # # """ # global __collector, __collecting # if __collector is not None: # raise NuSMVInitError("Cannot initialize NuSMV twice.") # else: # __collecting = collecting # __collector = set() # nscinit.NuSMVCore_init_data() # nscinit.NuSMVCore_init(None, 0) # No addons specified # nscinit.NuSMVCore_init_cmd_options() # # # Set NuSMV in interactive mode to avoid fast termination when errors # # nsopt.unset_batch(nsopt.OptsHandler_get_instance()) # # # Initialize option commands (set, unset) # # to be able to set parser_is_lax # nsopt.init_options_cmd() # nscmd.Cmd_SecureCommandExecute("set parser_is_lax") # # return _PyNuSMVContext() # # def deinit_nusmv(ddinfo=False): # """ # Quit NuSMV. Must be called only once, after calling :func:`init_nusmv`. # # :param ddinfo: Whether or not display Decision Diagrams statistics. # # """ # global __collector # if __collector is None: # raise NuSMVInitError( # "Cannot deinitialize NuSMV before initialization.") # else: # # Apply Python garbage collection first, # # then collect every pointer wrapper # # that is not yet collected by Python GC # from . import glob # # # Print statistics on stdout about DDs handled by the main DD manager. # if ddinfo: # try: # manager = glob.prop_database().master.bddFsm.bddEnc.DDmanager # nsdd.dd_print_stats(manager._ptr, nscinit.cvar.nusmv_stdout) # except PyNuSMVError: # pass # # glob._reset_globals() # # # First garbage collect with Python # gc.collect() # # Then garbage collect with PyNuSMV # for elem in __collector: # elem._free() # __collector = None # nscinit.NuSMVCore_quit() # # Path: pynusmv/exception.py # class NuSMVNeedVariablesEncodedError(PyNuSMVError): # # """ # Exception raised when the variables of the model must be encoded. # # """ # pass # # class NuSMVModelAlreadyBuiltError(PyNuSMVError): # # """ # Exception raised when the BDD model is already built. # # """ # pass # # class NuSMVNeedBooleanModelError(PyNuSMVError): # # """ # Exception raised when the boolean model must be created. # # """ # pass . Output only the next line.
def test_must_not_be_already_built_unless_force_flag(self):
Given the code snippet: <|code_start|> logger = getLogger(__name__) FOLLOWING_CHARS = {"\r", "\n", "\t", " ", ")", "]", ";", "}", "\x00"} PLUGIN_ONLY_COMPLETION = ( sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS ) def debounce(wait): """ Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked. """ def decorator(fn): def debounced(*args, **kwargs): def call_it(): fn(*args, **kwargs) try: debounced.t.cancel() except(AttributeError): pass debounced.t = Timer(wait, call_it) debounced.t.start() return debounced return decorator @debounce(0.2) <|code_end|> , generate the next line using the imports in this file: import re import sublime import sublime_plugin from threading import Timer from .console_logging import getLogger from .daemon import ask_daemon from .utils import get_settings, is_python_scope, is_repl and context (functions, classes, or occasionally code) from other files: # Path: sublime_jedi/console_logging.py # def get_plugin_debug_level(default='error'): # def __init__(self, name): # def level(self): # def _print(self, msg): # def log(self, level, msg, **kwargs): # def _log(self, level, msg, **kwargs): # def debug(self, msg): # def info(self, msg): # def error(self, msg, exc_info=False): # def exception(self, msg): # def warning(self, msg): # class Logger: # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) # # Path: sublime_jedi/utils.py # def get_settings(view): # """Get plugin settings. # # :type view: sublime.View # :rtype: dict # """ # python_virtualenv = get_settings_param(view, 'python_virtualenv', None) # if python_virtualenv: # python_virtualenv = expand_path(view, python_virtualenv) # # python_interpreter = get_settings_param(view, 'python_interpreter', None) # if python_interpreter: # python_interpreter = expand_path(view, python_interpreter) # # extra_packages = get_settings_param(view, 'python_package_paths', []) # extra_packages = [expand_path(view, p) for p in extra_packages] # # complete_funcargs = get_settings_param( # view, 'auto_complete_function_params', 'all') # # enable_in_sublime_repl = get_settings_param( # view, 'enable_in_sublime_repl', False) # # sublime_completions_visibility = get_settings_param( # view, 'sublime_completions_visibility', 'default') # # only_complete_after_regex = get_settings_param( # view, 'only_complete_after_regex', '') # # first_folder = '' # if view.window().folders(): # first_folder = os.path.split(view.window().folders()[0])[-1] # project_name = get_settings_param(view, 'project_name', first_folder) # # return { # 'python_interpreter': python_interpreter, # 'python_virtualenv': python_virtualenv, # 'extra_packages': extra_packages, # 'project_name': project_name, # 'complete_funcargs': complete_funcargs, # 'enable_in_sublime_repl': enable_in_sublime_repl, # 'sublime_completions_visibility': sublime_completions_visibility, # 'follow_imports': get_settings_param(view, 'follow_imports', True), # 'completion_timeout': get_settings_param(view, 'comletion_timeout', 3), # 'only_complete_after_regex': only_complete_after_regex, # } # # def is_python_scope(view, location): # """ (View, Point) -> bool # # Get if this is a python source scope (not a string and not a comment) # """ # return view.match_selector(location, "source.python - string - comment") # # def is_repl(view): # """Check if a view is a REPL.""" # return view.settings().get("repl", False) . Output only the next line.
def debounced_ask_daemon(*args, **kwargs):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- logger = getLogger(__name__) FOLLOWING_CHARS = {"\r", "\n", "\t", " ", ")", "]", ";", "}", "\x00"} PLUGIN_ONLY_COMPLETION = ( sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS ) def debounce(wait): """ Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked. """ def decorator(fn): def debounced(*args, **kwargs): def call_it(): fn(*args, **kwargs) <|code_end|> using the current file's imports: import re import sublime import sublime_plugin from threading import Timer from .console_logging import getLogger from .daemon import ask_daemon from .utils import get_settings, is_python_scope, is_repl and any relevant context from other files: # Path: sublime_jedi/console_logging.py # def get_plugin_debug_level(default='error'): # def __init__(self, name): # def level(self): # def _print(self, msg): # def log(self, level, msg, **kwargs): # def _log(self, level, msg, **kwargs): # def debug(self, msg): # def info(self, msg): # def error(self, msg, exc_info=False): # def exception(self, msg): # def warning(self, msg): # class Logger: # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) # # Path: sublime_jedi/utils.py # def get_settings(view): # """Get plugin settings. # # :type view: sublime.View # :rtype: dict # """ # python_virtualenv = get_settings_param(view, 'python_virtualenv', None) # if python_virtualenv: # python_virtualenv = expand_path(view, python_virtualenv) # # python_interpreter = get_settings_param(view, 'python_interpreter', None) # if python_interpreter: # python_interpreter = expand_path(view, python_interpreter) # # extra_packages = get_settings_param(view, 'python_package_paths', []) # extra_packages = [expand_path(view, p) for p in extra_packages] # # complete_funcargs = get_settings_param( # view, 'auto_complete_function_params', 'all') # # enable_in_sublime_repl = get_settings_param( # view, 'enable_in_sublime_repl', False) # # sublime_completions_visibility = get_settings_param( # view, 'sublime_completions_visibility', 'default') # # only_complete_after_regex = get_settings_param( # view, 'only_complete_after_regex', '') # # first_folder = '' # if view.window().folders(): # first_folder = os.path.split(view.window().folders()[0])[-1] # project_name = get_settings_param(view, 'project_name', first_folder) # # return { # 'python_interpreter': python_interpreter, # 'python_virtualenv': python_virtualenv, # 'extra_packages': extra_packages, # 'project_name': project_name, # 'complete_funcargs': complete_funcargs, # 'enable_in_sublime_repl': enable_in_sublime_repl, # 'sublime_completions_visibility': sublime_completions_visibility, # 'follow_imports': get_settings_param(view, 'follow_imports', True), # 'completion_timeout': get_settings_param(view, 'comletion_timeout', 3), # 'only_complete_after_regex': only_complete_after_regex, # } # # def is_python_scope(view, location): # """ (View, Point) -> bool # # Get if this is a python source scope (not a string and not a comment) # """ # return view.match_selector(location, "source.python - string - comment") # # def is_repl(view): # """Check if a view is a REPL.""" # return view.settings().get("repl", False) . Output only the next line.
try:
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- logger = getLogger(__name__) FOLLOWING_CHARS = {"\r", "\n", "\t", " ", ")", "]", ";", "}", "\x00"} PLUGIN_ONLY_COMPLETION = ( sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS ) def debounce(wait): """ Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked. """ def decorator(fn): def debounced(*args, **kwargs): def call_it(): fn(*args, **kwargs) try: <|code_end|> using the current file's imports: import re import sublime import sublime_plugin from threading import Timer from .console_logging import getLogger from .daemon import ask_daemon from .utils import get_settings, is_python_scope, is_repl and any relevant context from other files: # Path: sublime_jedi/console_logging.py # def get_plugin_debug_level(default='error'): # def __init__(self, name): # def level(self): # def _print(self, msg): # def log(self, level, msg, **kwargs): # def _log(self, level, msg, **kwargs): # def debug(self, msg): # def info(self, msg): # def error(self, msg, exc_info=False): # def exception(self, msg): # def warning(self, msg): # class Logger: # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) # # Path: sublime_jedi/utils.py # def get_settings(view): # """Get plugin settings. # # :type view: sublime.View # :rtype: dict # """ # python_virtualenv = get_settings_param(view, 'python_virtualenv', None) # if python_virtualenv: # python_virtualenv = expand_path(view, python_virtualenv) # # python_interpreter = get_settings_param(view, 'python_interpreter', None) # if python_interpreter: # python_interpreter = expand_path(view, python_interpreter) # # extra_packages = get_settings_param(view, 'python_package_paths', []) # extra_packages = [expand_path(view, p) for p in extra_packages] # # complete_funcargs = get_settings_param( # view, 'auto_complete_function_params', 'all') # # enable_in_sublime_repl = get_settings_param( # view, 'enable_in_sublime_repl', False) # # sublime_completions_visibility = get_settings_param( # view, 'sublime_completions_visibility', 'default') # # only_complete_after_regex = get_settings_param( # view, 'only_complete_after_regex', '') # # first_folder = '' # if view.window().folders(): # first_folder = os.path.split(view.window().folders()[0])[-1] # project_name = get_settings_param(view, 'project_name', first_folder) # # return { # 'python_interpreter': python_interpreter, # 'python_virtualenv': python_virtualenv, # 'extra_packages': extra_packages, # 'project_name': project_name, # 'complete_funcargs': complete_funcargs, # 'enable_in_sublime_repl': enable_in_sublime_repl, # 'sublime_completions_visibility': sublime_completions_visibility, # 'follow_imports': get_settings_param(view, 'follow_imports', True), # 'completion_timeout': get_settings_param(view, 'comletion_timeout', 3), # 'only_complete_after_regex': only_complete_after_regex, # } # # def is_python_scope(view, location): # """ (View, Point) -> bool # # Get if this is a python source scope (not a string and not a comment) # """ # return view.match_selector(location, "source.python - string - comment") # # def is_repl(view): # """Check if a view is a REPL.""" # return view.settings().get("repl", False) . Output only the next line.
debounced.t.cancel()
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- logger = getLogger(__name__) FOLLOWING_CHARS = {"\r", "\n", "\t", " ", ")", "]", ";", "}", "\x00"} PLUGIN_ONLY_COMPLETION = ( sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS ) def debounce(wait): """ Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked. """ def decorator(fn): def debounced(*args, **kwargs): def call_it(): <|code_end|> with the help of current file imports: import re import sublime import sublime_plugin from threading import Timer from .console_logging import getLogger from .daemon import ask_daemon from .utils import get_settings, is_python_scope, is_repl and context from other files: # Path: sublime_jedi/console_logging.py # def get_plugin_debug_level(default='error'): # def __init__(self, name): # def level(self): # def _print(self, msg): # def log(self, level, msg, **kwargs): # def _log(self, level, msg, **kwargs): # def debug(self, msg): # def info(self, msg): # def error(self, msg, exc_info=False): # def exception(self, msg): # def warning(self, msg): # class Logger: # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) # # Path: sublime_jedi/utils.py # def get_settings(view): # """Get plugin settings. # # :type view: sublime.View # :rtype: dict # """ # python_virtualenv = get_settings_param(view, 'python_virtualenv', None) # if python_virtualenv: # python_virtualenv = expand_path(view, python_virtualenv) # # python_interpreter = get_settings_param(view, 'python_interpreter', None) # if python_interpreter: # python_interpreter = expand_path(view, python_interpreter) # # extra_packages = get_settings_param(view, 'python_package_paths', []) # extra_packages = [expand_path(view, p) for p in extra_packages] # # complete_funcargs = get_settings_param( # view, 'auto_complete_function_params', 'all') # # enable_in_sublime_repl = get_settings_param( # view, 'enable_in_sublime_repl', False) # # sublime_completions_visibility = get_settings_param( # view, 'sublime_completions_visibility', 'default') # # only_complete_after_regex = get_settings_param( # view, 'only_complete_after_regex', '') # # first_folder = '' # if view.window().folders(): # first_folder = os.path.split(view.window().folders()[0])[-1] # project_name = get_settings_param(view, 'project_name', first_folder) # # return { # 'python_interpreter': python_interpreter, # 'python_virtualenv': python_virtualenv, # 'extra_packages': extra_packages, # 'project_name': project_name, # 'complete_funcargs': complete_funcargs, # 'enable_in_sublime_repl': enable_in_sublime_repl, # 'sublime_completions_visibility': sublime_completions_visibility, # 'follow_imports': get_settings_param(view, 'follow_imports', True), # 'completion_timeout': get_settings_param(view, 'comletion_timeout', 3), # 'only_complete_after_regex': only_complete_after_regex, # } # # def is_python_scope(view, location): # """ (View, Point) -> bool # # Get if this is a python source scope (not a string and not a comment) # """ # return view.match_selector(location, "source.python - string - comment") # # def is_repl(view): # """Check if a view is a REPL.""" # return view.settings().get("repl", False) , which may contain function names, class names, or code. Output only the next line.
fn(*args, **kwargs)
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- logger = getLogger(__name__) FOLLOWING_CHARS = {"\r", "\n", "\t", " ", ")", "]", ";", "}", "\x00"} PLUGIN_ONLY_COMPLETION = ( sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS ) def debounce(wait): """ Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked. """ <|code_end|> with the help of current file imports: import re import sublime import sublime_plugin from threading import Timer from .console_logging import getLogger from .daemon import ask_daemon from .utils import get_settings, is_python_scope, is_repl and context from other files: # Path: sublime_jedi/console_logging.py # def get_plugin_debug_level(default='error'): # def __init__(self, name): # def level(self): # def _print(self, msg): # def log(self, level, msg, **kwargs): # def _log(self, level, msg, **kwargs): # def debug(self, msg): # def info(self, msg): # def error(self, msg, exc_info=False): # def exception(self, msg): # def warning(self, msg): # class Logger: # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) # # Path: sublime_jedi/utils.py # def get_settings(view): # """Get plugin settings. # # :type view: sublime.View # :rtype: dict # """ # python_virtualenv = get_settings_param(view, 'python_virtualenv', None) # if python_virtualenv: # python_virtualenv = expand_path(view, python_virtualenv) # # python_interpreter = get_settings_param(view, 'python_interpreter', None) # if python_interpreter: # python_interpreter = expand_path(view, python_interpreter) # # extra_packages = get_settings_param(view, 'python_package_paths', []) # extra_packages = [expand_path(view, p) for p in extra_packages] # # complete_funcargs = get_settings_param( # view, 'auto_complete_function_params', 'all') # # enable_in_sublime_repl = get_settings_param( # view, 'enable_in_sublime_repl', False) # # sublime_completions_visibility = get_settings_param( # view, 'sublime_completions_visibility', 'default') # # only_complete_after_regex = get_settings_param( # view, 'only_complete_after_regex', '') # # first_folder = '' # if view.window().folders(): # first_folder = os.path.split(view.window().folders()[0])[-1] # project_name = get_settings_param(view, 'project_name', first_folder) # # return { # 'python_interpreter': python_interpreter, # 'python_virtualenv': python_virtualenv, # 'extra_packages': extra_packages, # 'project_name': project_name, # 'complete_funcargs': complete_funcargs, # 'enable_in_sublime_repl': enable_in_sublime_repl, # 'sublime_completions_visibility': sublime_completions_visibility, # 'follow_imports': get_settings_param(view, 'follow_imports', True), # 'completion_timeout': get_settings_param(view, 'comletion_timeout', 3), # 'only_complete_after_regex': only_complete_after_regex, # } # # def is_python_scope(view, location): # """ (View, Point) -> bool # # Get if this is a python source scope (not a string and not a comment) # """ # return view.match_selector(location, "source.python - string - comment") # # def is_repl(view): # """Check if a view is a REPL.""" # return view.settings().get("repl", False) , which may contain function names, class names, or code. Output only the next line.
def decorator(fn):
Next line prediction: <|code_start|># -*- coding: utf-8 -*- try: except ImportError as e: logger = getLogger(__name__) logger.debug('Unable to import tooltips: %s %s' % (type(e), e.message)) logger.warning('Tooltips disabled for ST2.') logger = getLogger(__name__) <|code_end|> . Use current file imports: (from functools import partial from .console_logging import getLogger from .daemon import ask_daemon from .settings import get_plugin_settings from .utils import is_sublime_v2, PythonCommandMixin from .tooltips import show_docstring_tooltip import sublime import sublime_plugin) and context including class names, function names, or small code snippets from other files: # Path: sublime_jedi/console_logging.py # def get_plugin_debug_level(default='error'): # def __init__(self, name): # def level(self): # def _print(self, msg): # def log(self, level, msg, **kwargs): # def _log(self, level, msg, **kwargs): # def debug(self, msg): # def info(self, msg): # def error(self, msg, exc_info=False): # def exception(self, msg): # def warning(self, msg): # class Logger: # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) # # Path: sublime_jedi/utils.py # def is_sublime_v2(): # return sublime.version().startswith('2') # # class PythonCommandMixin(object): # """A mixin that hides and disables command for non-python code """ # # def is_visible(self): # """ The command is visible only for python code """ # return is_python_scope(self.view, self.view.sel()[0].begin()) # # def is_enabled(self): # """ The command is enabled only when it is visible """ # return self.is_visible() . Output only the next line.
class HelpMessageCommand(sublime_plugin.TextCommand):
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- try: except ImportError as e: logger = getLogger(__name__) logger.debug('Unable to import tooltips: %s %s' % (type(e), e.message)) logger.warning('Tooltips disabled for ST2.') logger = getLogger(__name__) <|code_end|> , predict the immediate next line with the help of imports: from functools import partial from .console_logging import getLogger from .daemon import ask_daemon from .settings import get_plugin_settings from .utils import is_sublime_v2, PythonCommandMixin from .tooltips import show_docstring_tooltip import sublime import sublime_plugin and context (classes, functions, sometimes code) from other files: # Path: sublime_jedi/console_logging.py # def get_plugin_debug_level(default='error'): # def __init__(self, name): # def level(self): # def _print(self, msg): # def log(self, level, msg, **kwargs): # def _log(self, level, msg, **kwargs): # def debug(self, msg): # def info(self, msg): # def error(self, msg, exc_info=False): # def exception(self, msg): # def warning(self, msg): # class Logger: # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) # # Path: sublime_jedi/utils.py # def is_sublime_v2(): # return sublime.version().startswith('2') # # class PythonCommandMixin(object): # """A mixin that hides and disables command for non-python code """ # # def is_visible(self): # """ The command is visible only for python code """ # return is_python_scope(self.view, self.view.sel()[0].begin()) # # def is_enabled(self): # """ The command is enabled only when it is visible """ # return self.is_visible() . Output only the next line.
class HelpMessageCommand(sublime_plugin.TextCommand):
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- try: except ImportError as e: logger = getLogger(__name__) logger.debug('Unable to import tooltips: %s %s' % (type(e), e.message)) logger.warning('Tooltips disabled for ST2.') logger = getLogger(__name__) <|code_end|> , predict the next line using imports from the current file: from functools import partial from .console_logging import getLogger from .daemon import ask_daemon from .settings import get_plugin_settings from .utils import is_sublime_v2, PythonCommandMixin from .tooltips import show_docstring_tooltip import sublime import sublime_plugin and context including class names, function names, and sometimes code from other files: # Path: sublime_jedi/console_logging.py # def get_plugin_debug_level(default='error'): # def __init__(self, name): # def level(self): # def _print(self, msg): # def log(self, level, msg, **kwargs): # def _log(self, level, msg, **kwargs): # def debug(self, msg): # def info(self, msg): # def error(self, msg, exc_info=False): # def exception(self, msg): # def warning(self, msg): # class Logger: # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) # # Path: sublime_jedi/utils.py # def is_sublime_v2(): # return sublime.version().startswith('2') # # class PythonCommandMixin(object): # """A mixin that hides and disables command for non-python code """ # # def is_visible(self): # """ The command is visible only for python code """ # return is_python_scope(self.view, self.view.sel()[0].begin()) # # def is_enabled(self): # """ The command is enabled only when it is visible """ # return self.is_visible() . Output only the next line.
class HelpMessageCommand(sublime_plugin.TextCommand):
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- try: except Exception: pass class BaseLookUpJediCommand(PythonCommandMixin): <|code_end|> with the help of current file imports: from typing import Set, List, Tuple, Any from functools import partial from .utils import to_relative_path, PythonCommandMixin, get_settings, is_python_scope, debounce from .daemon import ask_daemon from .settings import get_settings_param import sublime import sublime_plugin import re and context from other files: # Path: sublime_jedi/utils.py # def to_relative_path(path): # """ # Trim project root pathes from **path** passed as argument # # If no any folders opened, path will be retuned unchanged # """ # folders = sublime.active_window().folders() # for folder in folders: # # close path with separator # if folder[-1] != os.path.sep: # folder += os.path.sep # # if path.startswith(folder): # return path.replace(folder, '') # # return path # # class PythonCommandMixin(object): # """A mixin that hides and disables command for non-python code """ # # def is_visible(self): # """ The command is visible only for python code """ # return is_python_scope(self.view, self.view.sel()[0].begin()) # # def is_enabled(self): # """ The command is enabled only when it is visible """ # return self.is_visible() # # def get_settings(view): # """Get plugin settings. # # :type view: sublime.View # :rtype: dict # """ # python_virtualenv = get_settings_param(view, 'python_virtualenv', None) # if python_virtualenv: # python_virtualenv = expand_path(view, python_virtualenv) # # python_interpreter = get_settings_param(view, 'python_interpreter', None) # if python_interpreter: # python_interpreter = expand_path(view, python_interpreter) # # extra_packages = get_settings_param(view, 'python_package_paths', []) # extra_packages = [expand_path(view, p) for p in extra_packages] # # complete_funcargs = get_settings_param( # view, 'auto_complete_function_params', 'all') # # enable_in_sublime_repl = get_settings_param( # view, 'enable_in_sublime_repl', False) # # sublime_completions_visibility = get_settings_param( # view, 'sublime_completions_visibility', 'default') # # only_complete_after_regex = get_settings_param( # view, 'only_complete_after_regex', '') # # first_folder = '' # if view.window().folders(): # first_folder = os.path.split(view.window().folders()[0])[-1] # project_name = get_settings_param(view, 'project_name', first_folder) # # return { # 'python_interpreter': python_interpreter, # 'python_virtualenv': python_virtualenv, # 'extra_packages': extra_packages, # 'project_name': project_name, # 'complete_funcargs': complete_funcargs, # 'enable_in_sublime_repl': enable_in_sublime_repl, # 'sublime_completions_visibility': sublime_completions_visibility, # 'follow_imports': get_settings_param(view, 'follow_imports', True), # 'completion_timeout': get_settings_param(view, 'comletion_timeout', 3), # 'only_complete_after_regex': only_complete_after_regex, # } # # def is_python_scope(view, location): # """ (View, Point) -> bool # # Get if this is a python source scope (not a string and not a comment) # """ # return view.match_selector(location, "source.python - string - comment") # # def debounce(wait): # def decorator(fn): # def debounced(*args, **kwargs): # def call(): # fn(*args, **kwargs) # try: # debounced.t.cancel() # except AttributeError: # pass # debounced.t = Timer(wait, call) # debounced.t.start() # return debounced # return decorator # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) , which may contain function names, class names, or code. Output only the next line.
def _jump_to_in_window(self, filename, line_number=None, column_number=None, transient=False):
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- try: except Exception: pass class BaseLookUpJediCommand(PythonCommandMixin): <|code_end|> . Use current file imports: from typing import Set, List, Tuple, Any from functools import partial from .utils import to_relative_path, PythonCommandMixin, get_settings, is_python_scope, debounce from .daemon import ask_daemon from .settings import get_settings_param import sublime import sublime_plugin import re and context (classes, functions, or code) from other files: # Path: sublime_jedi/utils.py # def to_relative_path(path): # """ # Trim project root pathes from **path** passed as argument # # If no any folders opened, path will be retuned unchanged # """ # folders = sublime.active_window().folders() # for folder in folders: # # close path with separator # if folder[-1] != os.path.sep: # folder += os.path.sep # # if path.startswith(folder): # return path.replace(folder, '') # # return path # # class PythonCommandMixin(object): # """A mixin that hides and disables command for non-python code """ # # def is_visible(self): # """ The command is visible only for python code """ # return is_python_scope(self.view, self.view.sel()[0].begin()) # # def is_enabled(self): # """ The command is enabled only when it is visible """ # return self.is_visible() # # def get_settings(view): # """Get plugin settings. # # :type view: sublime.View # :rtype: dict # """ # python_virtualenv = get_settings_param(view, 'python_virtualenv', None) # if python_virtualenv: # python_virtualenv = expand_path(view, python_virtualenv) # # python_interpreter = get_settings_param(view, 'python_interpreter', None) # if python_interpreter: # python_interpreter = expand_path(view, python_interpreter) # # extra_packages = get_settings_param(view, 'python_package_paths', []) # extra_packages = [expand_path(view, p) for p in extra_packages] # # complete_funcargs = get_settings_param( # view, 'auto_complete_function_params', 'all') # # enable_in_sublime_repl = get_settings_param( # view, 'enable_in_sublime_repl', False) # # sublime_completions_visibility = get_settings_param( # view, 'sublime_completions_visibility', 'default') # # only_complete_after_regex = get_settings_param( # view, 'only_complete_after_regex', '') # # first_folder = '' # if view.window().folders(): # first_folder = os.path.split(view.window().folders()[0])[-1] # project_name = get_settings_param(view, 'project_name', first_folder) # # return { # 'python_interpreter': python_interpreter, # 'python_virtualenv': python_virtualenv, # 'extra_packages': extra_packages, # 'project_name': project_name, # 'complete_funcargs': complete_funcargs, # 'enable_in_sublime_repl': enable_in_sublime_repl, # 'sublime_completions_visibility': sublime_completions_visibility, # 'follow_imports': get_settings_param(view, 'follow_imports', True), # 'completion_timeout': get_settings_param(view, 'comletion_timeout', 3), # 'only_complete_after_regex': only_complete_after_regex, # } # # def is_python_scope(view, location): # """ (View, Point) -> bool # # Get if this is a python source scope (not a string and not a comment) # """ # return view.match_selector(location, "source.python - string - comment") # # def debounce(wait): # def decorator(fn): # def debounced(*args, **kwargs): # def call(): # fn(*args, **kwargs) # try: # debounced.t.cancel() # except AttributeError: # pass # debounced.t = Timer(wait, call) # debounced.t.start() # return debounced # return decorator # # Path: sublime_jedi/daemon.py # def ask_daemon(view, callback, ask_type, ask_kwargs=None, location=None): # """Jedi async request shortcut. # # :type view: sublime.View # :type callback: callable # :type ask_type: str # :type ask_kwargs: dict or None # :type location: type of (int, int) or None # """ # window_id = view.window().id() # # def _async_summon(): # answer = ask_daemon_sync(view, ask_type, ask_kwargs, location) # _run_in_active_view(window_id)(callback)(answer) # # if callback: # sublime.set_timeout_async(_async_summon, 0) . Output only the next line.
def _jump_to_in_window(self, filename, line_number=None, column_number=None, transient=False):
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class SimpleTooltip(Tooltip): @classmethod def guess(cls, docstring): return True def _build_html(self, docstring): docstring = html.escape(docstring, quote=False).split('\n') docstring[0] = '<b>' + docstring[0] + '</b>' content = '<body><p style="font-family: sans-serif;">{0}</p></body>'.format( '<br />'.join(docstring) ) return content def show_popup(self, view, docstring, location=None): if location is None: location = view.sel()[0].begin() content = self._build_html(docstring) <|code_end|> , determine the next line of code. You have imports: import html from .base import Tooltip and context (class names, function names, or code) available: # Path: sublime_jedi/tooltips/base.py # class Tooltip: # # __metaclass__ = abc.ABCMeta # works for 2.7 and 3+ # # @classmethod # @abc.abstractmethod # def guess(cls, docstring): # """Check if tooltip can render the docstring. # # :rtype: bool # """ # # @abc.abstractmethod # def show_popup(self, view, docstring, location=None): # """Show tooltip with docstring. # # :rtype: NoneType # """ . Output only the next line.
view.show_popup(content, location=location, max_width=512)
Predict the next line after this snippet: <|code_start|># # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # $Id$ # # try : except ImportError as msg : sys.stderr.write("%s\n" % msg) sys.stderr.write("You need the DistUtils Python module.\nunder Debian, you may have to install the python-dev package.\nOf course, YMMV.\n") sys.exit(-1) try : except ImportError : sys.stderr.write("You need the Python Imaging Library (aka PIL).\nYou can grab it from http://www.pythonware.com\n") sys.exit(-1) sys.path.insert(0, "pkpgpdls") data_files = [] mofiles = glob.glob(os.sep.join(["po", "*", "*.mo"])) for mofile in mofiles : lang = mofile.split(os.sep)[1] <|code_end|> using the current file's imports: import sys import glob import os import shutil from distutils.core import setup from PIL import Image from pkpgpdls.version import __version__, __doc__ and any relevant context from other files: # Path: pkpgpdls/version.py . Output only the next line.
directory = os.sep.join(["share", "locale", lang, "LC_MESSAGES"])
Using the snippet: <|code_start|>except ImportError : sys.stderr.write("You need the Python Imaging Library (aka PIL).\nYou can grab it from http://www.pythonware.com\n") sys.exit(-1) sys.path.insert(0, "pkpgpdls") data_files = [] mofiles = glob.glob(os.sep.join(["po", "*", "*.mo"])) for mofile in mofiles : lang = mofile.split(os.sep)[1] directory = os.sep.join(["share", "locale", lang, "LC_MESSAGES"]) data_files.append((directory, [ mofile ])) docdir = "share/doc/pkpgcounter" docfiles = ["README", "COPYING", "BUGS", "CREDITS", "AUTHORS", "TODO"] data_files.append((docdir, docfiles)) if os.path.exists("ChangeLog") : data_files.append((docdir, ["ChangeLog"])) directory = os.sep.join(["share", "man", "man1"]) manpages = glob.glob(os.sep.join(["man", "*.1"])) data_files.append((directory, manpages)) setup(name = "pkpgcounter", version = __version__, license = "GNU GPL", description = __doc__, author = "Jerome Alet", author_email = "alet@librelogiciel.com", url = "http://www.pykota.com/software/pkpgcounter/", <|code_end|> , determine the next line of code. You have imports: import sys import glob import os import shutil from distutils.core import setup from PIL import Image from pkpgpdls.version import __version__, __doc__ and context (class names, function names, or code) available: # Path: pkpgpdls/version.py . Output only the next line.
packages = [ "pkpgpdls" ],
Given the code snippet: <|code_start|> sha1=None))), ('Sphinx-0.6b1-py2.5.egg', IndexRow( download_url=( 'https://pypi.python.org/simple/Sphinx/' '../../packages/2.5/S/Sphinx/' 'Sphinx-0.6b1-py2.5.egg' '#md5=b877f156e5c4b22257c47873021da3d2'), checksums=Checksums( md5='b877f156e5c4b22257c47873021da3d2', sha1=None))), ('Sphinx-0.1.61945-py2.5.egg', IndexRow( download_url=( 'https://pypi.python.org/simple/Sphinx/' '../../packages/2.5/S/Sphinx/' 'Sphinx-0.1.61945-py2.5.egg' '#md5=8139b5a66e41202b362bac270eef26ad'), checksums=Checksums( md5='8139b5a66e41202b362bac270eef26ad', sha1=None))), ('Sphinx-0.6-py2.5.egg', IndexRow( download_url=( 'https://pypi.python.org/simple/Sphinx/' '../../packages/2.5/S/Sphinx/' 'Sphinx-0.6-py2.5.egg' '#sha1=0000e1d327ab9524a006179aef4155a0d7a0'), checksums=Checksums( md5=None, <|code_end|> , generate the next line using the imports in this file: from collections import OrderedDict from nose.tools import eq_ from _utils import read_index from ...server_app import index_builder from ...server_app.index_parser import IndexRow, Checksums and context (functions, classes, or occasionally code) from other files: # Path: pypi_redirect/pypi_redirect/server_app/index_builder.py # def build(index_rows): # def _rows_for_file(package_filename, index_row): # def _format_row(filename): # def _escape_for_html(s, quote=False): # # Path: pypi_redirect/pypi_redirect/server_app/index_parser.py # def _all_internal_links_and_directories(html_root): # def parse( # base_url, # package_path, # html_str, # strict_html=True, # find_links_fn=_all_internal_links_and_directories): # def _parse_internal_links(base_url, html_root, package_path, find_links_fn): # def _is_ascii(s): # def _parse_html(html_str, strict_html): # def _is_absolute_url(url): # def _make_url_absolute(base_url, package_path, url): # def _determine_checksums(href): . Output only the next line.
sha1='0000e1d327ab9524a006179aef4155a0d7a0'))),
Given the following code snippet before the placeholder: <|code_start|> def typical_index_test(): index_rows = OrderedDict([ ('Sphinx-0.6.4-py2.5.egg', IndexRow( download_url=( 'https://pypi.python.org/simple/Sphinx/' '../../packages/2.5/S/Sphinx/Sphinx-0.6.4-py2.5.egg' '#md5=b9e637ba15a27b31b7f94b8809cdebe3'), checksums=Checksums( md5='b9e637ba15a27b31b7f94b8809cdebe3', <|code_end|> , predict the next line using imports from the current file: from collections import OrderedDict from nose.tools import eq_ from _utils import read_index from ...server_app import index_builder from ...server_app.index_parser import IndexRow, Checksums and context including class names, function names, and sometimes code from other files: # Path: pypi_redirect/pypi_redirect/server_app/index_builder.py # def build(index_rows): # def _rows_for_file(package_filename, index_row): # def _format_row(filename): # def _escape_for_html(s, quote=False): # # Path: pypi_redirect/pypi_redirect/server_app/index_parser.py # def _all_internal_links_and_directories(html_root): # def parse( # base_url, # package_path, # html_str, # strict_html=True, # find_links_fn=_all_internal_links_and_directories): # def _parse_internal_links(base_url, html_root, package_path, find_links_fn): # def _is_ascii(s): # def _parse_html(html_str, strict_html): # def _is_absolute_url(url): # def _make_url_absolute(base_url, package_path, url): # def _determine_checksums(href): . Output only the next line.
sha1=None))),
Next line prediction: <|code_start|> md5=None, sha1=None))), ('Sphinx-0.6b1-py2.5.egg', IndexRow( download_url=( 'https://pypi.python.org/simple/Sphinx/' '../../packages/2.5/S/Sphinx/' 'Sphinx-0.6b1-py2.5.egg' '#md5=b877f156e5c4b22257c47873021da3d2'), checksums=Checksums( md5='b877f156e5c4b22257c47873021da3d2', sha1=None))), ('Sphinx-0.1.61945-py2.5.egg', IndexRow( download_url=( 'https://pypi.python.org/simple/Sphinx/' '../../packages/2.5/S/Sphinx/' 'Sphinx-0.1.61945-py2.5.egg' '#md5=8139b5a66e41202b362bac270eef26ad'), checksums=Checksums( md5='8139b5a66e41202b362bac270eef26ad', sha1=None))), ('Sphinx-0.6-py2.5.egg', IndexRow( download_url=( 'https://pypi.python.org/simple/Sphinx/' '../../packages/2.5/S/Sphinx/' 'Sphinx-0.6-py2.5.egg' '#sha1=0000e1d327ab9524a006179aef4155a0d7a0'), checksums=Checksums( <|code_end|> . Use current file imports: (from collections import OrderedDict from nose.tools import eq_ from _utils import read_index from ...server_app import index_builder from ...server_app.index_parser import IndexRow, Checksums) and context including class names, function names, or small code snippets from other files: # Path: pypi_redirect/pypi_redirect/server_app/index_builder.py # def build(index_rows): # def _rows_for_file(package_filename, index_row): # def _format_row(filename): # def _escape_for_html(s, quote=False): # # Path: pypi_redirect/pypi_redirect/server_app/index_parser.py # def _all_internal_links_and_directories(html_root): # def parse( # base_url, # package_path, # html_str, # strict_html=True, # find_links_fn=_all_internal_links_and_directories): # def _parse_internal_links(base_url, html_root, package_path, find_links_fn): # def _is_ascii(s): # def _parse_html(html_str, strict_html): # def _is_absolute_url(url): # def _make_url_absolute(base_url, package_path, url): # def _determine_checksums(href): . Output only the next line.
md5=None,
Next line prediction: <|code_start|> def empty_path_is_index_test(): _check_root_path([], is_index=True) def empty_path_not_index_test(): <|code_end|> . Use current file imports: (from collections import OrderedDict from functools import partial from nose.tools import eq_ from _utils import RequestStub, FunctionStub, ResponseStub from _utils import assert_http_redirect from ...server_app.handler.root_index_handler import RootIndexHandler) and context including class names, function names, or small code snippets from other files: # Path: pypi_redirect/pypi_redirect/server_app/handler/root_index_handler.py # class RootIndexHandler(object): # def __init__(self, build_index_fn): # self.build_index_fn = build_index_fn # # @ensure_index # def handle(self, path, request, response): # html_str = self.build_index_fn( # index_rows=OrderedDict([('python/', None)])) # # return html_str . Output only the next line.
handler_runner = partial(
Using the snippet: <|code_start|> '#md5=8139b5a66e41202b362bac270eef26ad', checksums=index_parser.Checksums( md5='8139b5a66e41202b362bac270eef26ad', sha1=None))), ('Sphinx-0.6-py2.5.egg', index_parser.IndexRow( download_url='https://pypi.python.org/simple/Sphinx/../../packages' '/2.5/S/Sphinx/Sphinx-0.6-py2.5.egg' '#sha1=0000e1d327ab9524a006179aef4155a0d7a0', checksums=index_parser.Checksums( md5=None, sha1='0000e1d327ab9524a006179aef4155a0d7a0'))), ('Sphinx-1.0b2.tar.gz', index_parser.IndexRow( download_url='https://pypi.python.org/simple/Sphinx/../../packages' '/source/S/Sphinx/Sphinx-1.0b2.tar.gz' '#sha1=00006bf13da4fd0542cc85705d1c4abd3c0a', checksums=index_parser.Checksums( md5=None, sha1='00006bf13da4fd0542cc85705d1c4abd3c0a'))), ('Sphinx-0.6.1-py2.4.egg', index_parser.IndexRow( download_url='http://pypi.acme.com/packages' '/2.4/S/Sphinx/Sphinx-0.6.1-py2.4.egg' '#md5=8b5d93be6d4f76e1c3d8c3197f84526f', checksums=index_parser.Checksums( md5='8b5d93be6d4f76e1c3d8c3197f84526f', sha1=None))), ('Sphinx-0.5.tar.gz', index_parser.IndexRow( download_url='https://pypi.python.org/simple/Sphinx/../../packages' '/source/S/Sphinx/Sphinx-0.5.tar.gz' '#md5=55a33cc13b5096c8763cd4a933b30ddc', checksums=index_parser.Checksums( <|code_end|> , determine the next line of code. You have imports: from collections import OrderedDict from nose.tools import eq_, raises from lxml.etree import XMLSyntaxError from _utils import read_index from ...server_app import index_parser and context (class names, function names, or code) available: # Path: pypi_redirect/pypi_redirect/server_app/index_parser.py # def _all_internal_links_and_directories(html_root): # def parse( # base_url, # package_path, # html_str, # strict_html=True, # find_links_fn=_all_internal_links_and_directories): # def _parse_internal_links(base_url, html_root, package_path, find_links_fn): # def _is_ascii(s): # def _parse_html(html_str, strict_html): # def _is_absolute_url(url): # def _make_url_absolute(base_url, package_path, url): # def _determine_checksums(href): . Output only the next line.
md5='55a33cc13b5096c8763cd4a933b30ddc',
Here is a snippet: <|code_start|> def typical_usage_test(): def handler_runner(): InvalidPathHandler().handle( path=['path', 'little', 'too', 'long'], request=None, response=None) assert_http_not_found( <|code_end|> . Write the next line using the current file imports: from _utils import assert_http_not_found from ...server_app.handler.invalid_path_handler import InvalidPathHandler and context from other files: # Path: pypi_redirect/pypi_redirect/server_app/handler/invalid_path_handler.py # class InvalidPathHandler(object): # def handle(self, path, request, response): # raise http_404('Invalid path of "{}"'.format('/'.join(path))) , which may include functions, classes, or code. Output only the next line.
run_handler_fn=handler_runner,
Continue the code snippet: <|code_start|> path=['not_python', 'nose'], is_index=True) assert_http_not_found( run_handler_fn=handler_runner, failure_description='Failed to return 404 on non-"/python/" path') def _check_main_index_path( path, is_index, http_get_exception=None, parse_index_exception=None): pypi_base_url = 'http://dumb_url.com' builder_response = 'be dumb builder' parser_response = 'be dumb parser' html_get_response = 'be dumb html' py, package_path = path html_get_stub = FunctionStub( name='HTML Get', dummy_result=html_get_response, dummy_exception=http_get_exception) parser_stub = FunctionStub( name='Parser', dummy_result=parser_response, dummy_exception=parse_index_exception) <|code_end|> . Use current file imports: from functools import partial from lxml.etree import ParseError from nose.tools import eq_ from requests import RequestException from _utils import RequestStub, ResponseStub, FunctionStub from _utils import assert_http_redirect, assert_http_not_found from ...server_app.handler.pypi_index_handler import PyPIIndexHandler and context (classes, functions, or code) from other files: # Path: pypi_redirect/pypi_redirect/server_app/handler/pypi_index_handler.py # class PyPIIndexHandler(object): # def __init__( # self, # pypi_base_url, # http_get_fn, # parse_index_fn, # build_index_fn): # self.pypi_base_url = pypi_base_url # self.http_get_fn = http_get_fn # self.parse_index_fn = parse_index_fn # self.build_index_fn = build_index_fn # # def _simple_pypi_or_package(self, path): # """ # Determines whether the given path points to a specific package # or to the root of the "simple" PyPI structure. # """ # if len(path) == 2: # py, package_name = path # index_url = '{}/{}/'.format(self.pypi_base_url, package_name) # else: # package_name = 'python' # index_url = '{}/'.format(self.pypi_base_url) # return index_url, package_name # # @ensure_python_dir # @ensure_index # def handle(self, path, request, response): # index_url, package_name = self._simple_pypi_or_package(path) # # index_rows = fetch_and_parse_index( # http_get_fn=self.http_get_fn, # parse_index_fn=self.parse_index_fn, # pypi_base_url=self.pypi_base_url, # index_url=index_url, # package_path=package_name) # # rebuilt_html_str = self.build_index_fn( # index_rows=index_rows) # # return rebuilt_html_str . Output only the next line.
builder_stub = FunctionStub(
Predict the next line for this snippet: <|code_start|> else: raise AssertionError(failure_description) def assert_http_redirect( run_handler_fn, expected_url, expected_status, failure_description): try: run_handler_fn() except HandlerException as e: kwargs = e.wrapped_exception.keywords assert 'urls' in kwargs, \ 'No URL specified for redirection ' \ '(expected `urls` keyword argument)' assert 'status' in kwargs, \ 'No redirect status specified ' \ '(expected `status` keyword argument)' eq_(kwargs['urls'], expected_url, msg='Incorrect redirection URL') eq_(kwargs['status'], expected_status, msg='Incorrect redirection status') except: <|code_end|> with the help of current file imports: import os from nose.tools import eq_ from ...server_app.handler._exception import HandlerException and context from other files: # Path: pypi_redirect/pypi_redirect/server_app/handler/_exception.py # class HandlerException(Exception): # def __init__(self, wrapped_exception): # self.wrapped_exception = wrapped_exception # # def raise_wrapped(self): # """ # Raises the 'wrapped' exception, preserving the original # traceback. This must be called from within an `except` block. # """ # # The first item is a class instance, so the second item must # # be None. The third item is the traceback object, which is why # # this method must be called from within an `except` block. # raise ( # self.wrapped_exception(), # None, # sys.exc_info()[2]) , which may contain function names, class names, or code. Output only the next line.
raise AssertionError('Failed to raise a HandlerException')
Predict the next line for this snippet: <|code_start|> FileEntry = namedtuple('FileEntry', ('pkg_name', 'filename', 'index_row')) def _generate_file_entry(has_md5=True, has_sha1=True): checksums = Checksums( md5='MD5-nose-1.2.1.tar.gz' if has_md5 else None, sha1='SHA1-nose-1.2.1.tar.gz' if has_sha1 else None) file_entry = FileEntry( pkg_name='nose', filename='nose-1.2.1.tar.gz', index_row=IndexRow( download_url='http://some_url.com/nose/nose-1.2.1.tar.gz', checksums=checksums)) return file_entry <|code_end|> with the help of current file imports: from collections import OrderedDict, namedtuple from functools import partial from lxml.etree import ParseError from nose.tools import eq_ from requests import RequestException from ...server_app.handler.file_handler import FileHandler from ...server_app.index_parser import IndexRow, Checksums from _utils import FunctionStub, RequestStub, ResponseStub from _utils import assert_http_redirect, assert_http_not_found and context from other files: # Path: pypi_redirect/pypi_redirect/server_app/handler/file_handler.py # class FileHandler(object): # def __init__(self, pypi_base_url, http_get_fn, parse_index_fn): # self.pypi_base_url = pypi_base_url # self.http_get_fn = http_get_fn # self.parse_index_fn = parse_index_fn # # def _is_checksum_file(self, filename): # return filename.lower().endswith(('.md5', '.sha1')) # # def _handle_checksum(self, checksum_filename, index_rows, response): # filename_base, ext = os.path.splitext(checksum_filename) # ext_no_dot = ext[1:].lower() # _ensure_file_in_index(filename=filename_base, index_rows=index_rows) # checksums = index_rows[filename_base].checksums # # return _get_checksum( # checksums=checksums, # checksum_ext=ext_no_dot, # response_headers=response.headers) # # def _redirect_to_download_url(self, filename, index_rows): # _ensure_file_in_index(filename=filename, index_rows=index_rows) # download_url = index_rows[filename].download_url # raise http_302(download_url) # # @ensure_python_dir # def handle(self, path, request, response): # py, package_name, filename = path # # index_url = '{}/{}/'.format(self.pypi_base_url, package_name) # # index_rows = fetch_and_parse_index( # http_get_fn=self.http_get_fn, # parse_index_fn=self.parse_index_fn, # pypi_base_url=self.pypi_base_url, # index_url=index_url, # package_path=package_name) # # if self._is_checksum_file(filename=filename): # return self._handle_checksum( # checksum_filename=filename, # index_rows=index_rows, # response=response) # # self._redirect_to_download_url( # filename=filename, # index_rows=index_rows) # # Path: pypi_redirect/pypi_redirect/server_app/index_parser.py # def _all_internal_links_and_directories(html_root): # def parse( # base_url, # package_path, # html_str, # strict_html=True, # find_links_fn=_all_internal_links_and_directories): # def _parse_internal_links(base_url, html_root, package_path, find_links_fn): # def _is_ascii(s): # def _parse_html(html_str, strict_html): # def _is_absolute_url(url): # def _make_url_absolute(base_url, package_path, url): # def _determine_checksums(href): , which may contain function names, class names, or code. Output only the next line.
def handle_file_request_test():
Predict the next line for this snippet: <|code_start|> failure_description='Failed to return 404 on non-"/python/" path') def _check_file_handler( file_entry, file_requested, root_dir='python', expected_checksum=None, http_get_exception=None, parse_index_exception=None): pypi_base_url = 'http://dumb_url.com' parser_response = OrderedDict([ ('nose-1.2.0.tar.gz', IndexRow( download_url='http://some_url.com/nose/nose-1.2.0.tar.gz', checksums=Checksums( md5='MD5-nose-1.2.0.tar.gz', sha1=None))), (file_entry.filename, file_entry.index_row), ('nose-1.2.1.egg', IndexRow( download_url='http://some_url.com/nose/nose-1.2.1.egg', checksums=Checksums( md5='MD5-nose-1.2.1.egg', sha1=None))), ]) html_get_response = 'be dumb html' html_get_stub = FunctionStub( <|code_end|> with the help of current file imports: from collections import OrderedDict, namedtuple from functools import partial from lxml.etree import ParseError from nose.tools import eq_ from requests import RequestException from ...server_app.handler.file_handler import FileHandler from ...server_app.index_parser import IndexRow, Checksums from _utils import FunctionStub, RequestStub, ResponseStub from _utils import assert_http_redirect, assert_http_not_found and context from other files: # Path: pypi_redirect/pypi_redirect/server_app/handler/file_handler.py # class FileHandler(object): # def __init__(self, pypi_base_url, http_get_fn, parse_index_fn): # self.pypi_base_url = pypi_base_url # self.http_get_fn = http_get_fn # self.parse_index_fn = parse_index_fn # # def _is_checksum_file(self, filename): # return filename.lower().endswith(('.md5', '.sha1')) # # def _handle_checksum(self, checksum_filename, index_rows, response): # filename_base, ext = os.path.splitext(checksum_filename) # ext_no_dot = ext[1:].lower() # _ensure_file_in_index(filename=filename_base, index_rows=index_rows) # checksums = index_rows[filename_base].checksums # # return _get_checksum( # checksums=checksums, # checksum_ext=ext_no_dot, # response_headers=response.headers) # # def _redirect_to_download_url(self, filename, index_rows): # _ensure_file_in_index(filename=filename, index_rows=index_rows) # download_url = index_rows[filename].download_url # raise http_302(download_url) # # @ensure_python_dir # def handle(self, path, request, response): # py, package_name, filename = path # # index_url = '{}/{}/'.format(self.pypi_base_url, package_name) # # index_rows = fetch_and_parse_index( # http_get_fn=self.http_get_fn, # parse_index_fn=self.parse_index_fn, # pypi_base_url=self.pypi_base_url, # index_url=index_url, # package_path=package_name) # # if self._is_checksum_file(filename=filename): # return self._handle_checksum( # checksum_filename=filename, # index_rows=index_rows, # response=response) # # self._redirect_to_download_url( # filename=filename, # index_rows=index_rows) # # Path: pypi_redirect/pypi_redirect/server_app/index_parser.py # def _all_internal_links_and_directories(html_root): # def parse( # base_url, # package_path, # html_str, # strict_html=True, # find_links_fn=_all_internal_links_and_directories): # def _parse_internal_links(base_url, html_root, package_path, find_links_fn): # def _is_ascii(s): # def _parse_html(html_str, strict_html): # def _is_absolute_url(url): # def _make_url_absolute(base_url, package_path, url): # def _determine_checksums(href): , which may contain function names, class names, or code. Output only the next line.
name='HTML Get',
Predict the next line for this snippet: <|code_start|> run_handler_fn=handler_runner, failure_description='Failed to return 404 on failure to parse index') def non_python_root_path_test(): file_entry = _generate_file_entry() handler_runner = partial( _check_file_handler, file_entry=file_entry, file_requested=file_entry.filename, root_dir='not_python') assert_http_not_found( run_handler_fn=handler_runner, failure_description='Failed to return 404 on non-"/python/" path') def _check_file_handler( file_entry, file_requested, root_dir='python', expected_checksum=None, http_get_exception=None, parse_index_exception=None): pypi_base_url = 'http://dumb_url.com' parser_response = OrderedDict([ ('nose-1.2.0.tar.gz', IndexRow( <|code_end|> with the help of current file imports: from collections import OrderedDict, namedtuple from functools import partial from lxml.etree import ParseError from nose.tools import eq_ from requests import RequestException from ...server_app.handler.file_handler import FileHandler from ...server_app.index_parser import IndexRow, Checksums from _utils import FunctionStub, RequestStub, ResponseStub from _utils import assert_http_redirect, assert_http_not_found and context from other files: # Path: pypi_redirect/pypi_redirect/server_app/handler/file_handler.py # class FileHandler(object): # def __init__(self, pypi_base_url, http_get_fn, parse_index_fn): # self.pypi_base_url = pypi_base_url # self.http_get_fn = http_get_fn # self.parse_index_fn = parse_index_fn # # def _is_checksum_file(self, filename): # return filename.lower().endswith(('.md5', '.sha1')) # # def _handle_checksum(self, checksum_filename, index_rows, response): # filename_base, ext = os.path.splitext(checksum_filename) # ext_no_dot = ext[1:].lower() # _ensure_file_in_index(filename=filename_base, index_rows=index_rows) # checksums = index_rows[filename_base].checksums # # return _get_checksum( # checksums=checksums, # checksum_ext=ext_no_dot, # response_headers=response.headers) # # def _redirect_to_download_url(self, filename, index_rows): # _ensure_file_in_index(filename=filename, index_rows=index_rows) # download_url = index_rows[filename].download_url # raise http_302(download_url) # # @ensure_python_dir # def handle(self, path, request, response): # py, package_name, filename = path # # index_url = '{}/{}/'.format(self.pypi_base_url, package_name) # # index_rows = fetch_and_parse_index( # http_get_fn=self.http_get_fn, # parse_index_fn=self.parse_index_fn, # pypi_base_url=self.pypi_base_url, # index_url=index_url, # package_path=package_name) # # if self._is_checksum_file(filename=filename): # return self._handle_checksum( # checksum_filename=filename, # index_rows=index_rows, # response=response) # # self._redirect_to_download_url( # filename=filename, # index_rows=index_rows) # # Path: pypi_redirect/pypi_redirect/server_app/index_parser.py # def _all_internal_links_and_directories(html_root): # def parse( # base_url, # package_path, # html_str, # strict_html=True, # find_links_fn=_all_internal_links_and_directories): # def _parse_internal_links(base_url, html_root, package_path, find_links_fn): # def _is_ascii(s): # def _parse_html(html_str, strict_html): # def _is_absolute_url(url): # def _make_url_absolute(base_url, package_path, url): # def _determine_checksums(href): , which may contain function names, class names, or code. Output only the next line.
download_url='http://some_url.com/nose/nose-1.2.0.tar.gz',
Predict the next line after this snippet: <|code_start|>def _create_normal_sad_handlers(number_of_handlers): handlers = [] for n in xrange(number_of_handlers): handlers.append(FunctionStub( name='Path length {} handler'.format(n), dummy_exception=HandlerException( wrapped_exception=_UniqueException))) return handlers def _create_normal_happy_handlers(number_of_handlers): handlers = [] for n in xrange(number_of_handlers): handlers.append(FunctionStub( name='Path length {} handler'.format(n), dummy_result='Path length {} handler result'.format(n))) return handlers def _create_sad_exception_handler(): handler = FunctionStub( name='Invalid path handler', dummy_exception=_UniqueException) return handler def _create_happy_exception_handler(): handler = FunctionStub( name='Invalid path handler', dummy_result='Invalid path handler result') <|code_end|> using the current file's imports: from nose.tools import eq_ from ...server_app.handler._exception import HandlerException from ...server_app.http.path_length_dispatcher import PathLengthDispatcher from _utils import FunctionStub and any relevant context from other files: # Path: pypi_redirect/pypi_redirect/server_app/handler/_exception.py # class HandlerException(Exception): # def __init__(self, wrapped_exception): # self.wrapped_exception = wrapped_exception # # def raise_wrapped(self): # """ # Raises the 'wrapped' exception, preserving the original # traceback. This must be called from within an `except` block. # """ # # The first item is a class instance, so the second item must # # be None. The third item is the traceback object, which is why # # this method must be called from within an `except` block. # raise ( # self.wrapped_exception(), # None, # sys.exc_info()[2]) # # Path: pypi_redirect/pypi_redirect/server_app/http/path_length_dispatcher.py # class PathLengthDispatcher(object): # def __init__( # self, # handlers_indexed_by_path_length, # invalid_path_handler): # self.handlers_indexed_by_path_length = handlers_indexed_by_path_length # self.invalid_path_handler = invalid_path_handler # # @cherrypy.expose # def default(self, *path): # try: # return self.handlers_indexed_by_path_length[len(path)]( # path=path, # request=cherrypy.request, # response=cherrypy.response) # # except IndexError: # return self.invalid_path_handler( # path=path, # request=cherrypy.request, # response=cherrypy.response) # # except HandlerException as e: # e.raise_wrapped() . Output only the next line.
return handler
Predict the next line after this snippet: <|code_start|> def test_all_permutations(): permutations = ( TestHelper(0, False, False), TestHelper(0, True, False), TestHelper(0, False, True), TestHelper(1, False, False), TestHelper(1, True, False), TestHelper(1, False, True), TestHelper(2, False, False), TestHelper(2, True, False), TestHelper(2, False, True), ) for permutation in permutations: yield permutation.perform_assertions <|code_end|> using the current file's imports: from nose.tools import eq_ from ...server_app.handler._exception import HandlerException from ...server_app.http.path_length_dispatcher import PathLengthDispatcher from _utils import FunctionStub and any relevant context from other files: # Path: pypi_redirect/pypi_redirect/server_app/handler/_exception.py # class HandlerException(Exception): # def __init__(self, wrapped_exception): # self.wrapped_exception = wrapped_exception # # def raise_wrapped(self): # """ # Raises the 'wrapped' exception, preserving the original # traceback. This must be called from within an `except` block. # """ # # The first item is a class instance, so the second item must # # be None. The third item is the traceback object, which is why # # this method must be called from within an `except` block. # raise ( # self.wrapped_exception(), # None, # sys.exc_info()[2]) # # Path: pypi_redirect/pypi_redirect/server_app/http/path_length_dispatcher.py # class PathLengthDispatcher(object): # def __init__( # self, # handlers_indexed_by_path_length, # invalid_path_handler): # self.handlers_indexed_by_path_length = handlers_indexed_by_path_length # self.invalid_path_handler = invalid_path_handler # # @cherrypy.expose # def default(self, *path): # try: # return self.handlers_indexed_by_path_length[len(path)]( # path=path, # request=cherrypy.request, # response=cherrypy.response) # # except IndexError: # return self.invalid_path_handler( # path=path, # request=cherrypy.request, # response=cherrypy.response) # # except HandlerException as e: # e.raise_wrapped() . Output only the next line.
class _UniqueException(Exception):
Here is a snippet: <|code_start|> floatX = theano.config.floatX theano_rand = MRG_RandomStreams() class Linear(Template): <|code_end|> . Write the next line using the current file imports: import numpy as np import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams from mozi.utils.theano_utils import shared_zeros from mozi.weight_init import GaussianWeight from mozi.layers.template import Template and context from other files: # Path: mozi/utils/theano_utils.py # def shared_zeros(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.zeros(shape), dtype=dtype, name=name, **kwargs) # # Path: mozi/weight_init.py # class GaussianWeight(WeightInitialization): # def __init__(self, mean=0, std=0.1): # self.mean = mean # self.std = std # # def __call__(self, dim, name='W', **kwargs): # W_values = np.random.normal(loc=self.mean, scale=self.std, size=dim) # return sharedX(name=name, value=W_values, borrow=True, **kwargs) # # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] , which may include functions, classes, or code. Output only the next line.
def __init__(self, prev_dim=None, this_dim=None, W=None, b=None,
Based on the snippet: <|code_start|> floatX = theano.config.floatX theano_rand = MRG_RandomStreams() class Sigmoid(Template): def _train_fprop(self, state_below): return T.nnet.sigmoid(state_below) class RELU(Template): def _train_fprop(self, state_below): return state_below * (state_below > 0.) class PRELU(Template): <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams from mozi.layers.template import Template from mozi.utils.theano_utils import sharedX and context (classes, functions, sometimes code) from other files: # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] # # Path: mozi/utils/theano_utils.py # def sharedX(value, dtype=floatX, name=None, borrow=False, **kwargs): # return theano.shared(np.asarray(value, dtype=dtype), name=name, borrow=borrow, **kwargs) . Output only the next line.
def __init__(self, dim, alpha=0.2):
Given the code snippet: <|code_start|> floatX = theano.config.floatX theano_rand = MRG_RandomStreams() class Dropout(Template): <|code_end|> , generate the next line using the imports in this file: import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams from mozi.layers.template import Template and context (functions, classes, or occasionally code) from other files: # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] . Output only the next line.
def __init__(self, dropout_below=0.5):
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import from __future__ import print_function floatX = theano.config.floatX def duplicate_param(name, tensor_list): for param in tensor_list: <|code_end|> , predict the next line using imports from the current file: import matplotlib import theano import theano.tensor as T import numpy as np import matplotlib.pyplot as plt import tarfile, inspect, os from theano.compile.ops import as_op from mozi.utils.progbar import Progbar from mozi.utils.train_object_utils import is_shared_var from six.moves.urllib.request import urlretrieve and context including class names, function names, and sometimes code from other files: # Path: mozi/utils/progbar.py # class Progbar(object): # def __init__(self, target, width=30, verbose=1): # ''' # @param target: total number of steps expected # ''' # self.width = width # self.target = target # self.sum_values = {} # self.unique_values = [] # self.start = time.time() # self.total_width = 0 # self.seen_so_far = 0 # self.verbose = verbose # # def update(self, current, values=[]): # ''' # @param current: index of current step # @param values: list of tuples (name, value_for_last_step). # The progress bar will display averages for these values. # ''' # for k, v in values: # if k not in self.sum_values: # self.sum_values[k] = [v * (current-self.seen_so_far), current-self.seen_so_far] # self.unique_values.append(k) # else: # self.sum_values[k][0] += v * (current-self.seen_so_far) # self.sum_values[k][1] += (current-self.seen_so_far) # self.seen_so_far = current # # now = time.time() # if self.verbose == 1: # prev_total_width = self.total_width # sys.stdout.write("\b" * prev_total_width) # sys.stdout.write("\r") # # numdigits = int(np.floor(np.log10(self.target))) + 1 # barstr = '%%%dd/%%%dd [' % (numdigits, numdigits) # bar = barstr % (current, self.target) # prog = float(current)/self.target # if current > self.target: # prog = 1 # prog_width = int(self.width*prog) # if prog_width > 0: # bar += ('='*(prog_width-1)) # if current < self.target: # bar += '>' # bar += ('.'*(self.width-prog_width)) # bar += ']' # sys.stdout.write(bar) # self.total_width = len(bar) # # if current: # time_per_unit = (now - self.start) / current # else: # time_per_unit = 0 # eta = time_per_unit*(self.target - current) # info = '' # if current < self.target: # info += ' - ETA: %ds' % eta # else: # info += ' - %ds' % (now - self.start) # for k in self.unique_values: # info += ' - %s: %.4f' % (k, self.sum_values[k][0]/ max(1, self.sum_values[k][1])) # # self.total_width += len(info) # if prev_total_width > self.total_width: # info += ((prev_total_width-self.total_width) * " ") # # sys.stdout.write(info) # sys.stdout.flush() # # if self.verbose == 2: # if current >= self.target: # info = '%ds' % (now - self.start) # for k in self.unique_values: # info += ' - %s: %.4f' % (k, self.sum_values[k][0]/ max(1, self.sum_values[k][1])) # sys.stdout.write(info + "\n") # # # def add(self, n, values=[]): # self.update(self.seen_so_far+n, values) # # Path: mozi/utils/train_object_utils.py # def is_shared_var(var): # return var.__class__.__name__ == 'TensorSharedVariable' or \ # var.__class__.__name__ == 'CudaNdarraySharedVariable' . Output only the next line.
if param.name is name:
Given the code snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function floatX = theano.config.floatX def duplicate_param(name, tensor_list): for param in tensor_list: if param.name is name: return True return False <|code_end|> , generate the next line using the imports in this file: import matplotlib import theano import theano.tensor as T import numpy as np import matplotlib.pyplot as plt import tarfile, inspect, os from theano.compile.ops import as_op from mozi.utils.progbar import Progbar from mozi.utils.train_object_utils import is_shared_var from six.moves.urllib.request import urlretrieve and context (functions, classes, or occasionally code) from other files: # Path: mozi/utils/progbar.py # class Progbar(object): # def __init__(self, target, width=30, verbose=1): # ''' # @param target: total number of steps expected # ''' # self.width = width # self.target = target # self.sum_values = {} # self.unique_values = [] # self.start = time.time() # self.total_width = 0 # self.seen_so_far = 0 # self.verbose = verbose # # def update(self, current, values=[]): # ''' # @param current: index of current step # @param values: list of tuples (name, value_for_last_step). # The progress bar will display averages for these values. # ''' # for k, v in values: # if k not in self.sum_values: # self.sum_values[k] = [v * (current-self.seen_so_far), current-self.seen_so_far] # self.unique_values.append(k) # else: # self.sum_values[k][0] += v * (current-self.seen_so_far) # self.sum_values[k][1] += (current-self.seen_so_far) # self.seen_so_far = current # # now = time.time() # if self.verbose == 1: # prev_total_width = self.total_width # sys.stdout.write("\b" * prev_total_width) # sys.stdout.write("\r") # # numdigits = int(np.floor(np.log10(self.target))) + 1 # barstr = '%%%dd/%%%dd [' % (numdigits, numdigits) # bar = barstr % (current, self.target) # prog = float(current)/self.target # if current > self.target: # prog = 1 # prog_width = int(self.width*prog) # if prog_width > 0: # bar += ('='*(prog_width-1)) # if current < self.target: # bar += '>' # bar += ('.'*(self.width-prog_width)) # bar += ']' # sys.stdout.write(bar) # self.total_width = len(bar) # # if current: # time_per_unit = (now - self.start) / current # else: # time_per_unit = 0 # eta = time_per_unit*(self.target - current) # info = '' # if current < self.target: # info += ' - ETA: %ds' % eta # else: # info += ' - %ds' % (now - self.start) # for k in self.unique_values: # info += ' - %s: %.4f' % (k, self.sum_values[k][0]/ max(1, self.sum_values[k][1])) # # self.total_width += len(info) # if prev_total_width > self.total_width: # info += ((prev_total_width-self.total_width) * " ") # # sys.stdout.write(info) # sys.stdout.flush() # # if self.verbose == 2: # if current >= self.target: # info = '%ds' % (now - self.start) # for k in self.unique_values: # info += ' - %s: %.4f' % (k, self.sum_values[k][0]/ max(1, self.sum_values[k][1])) # sys.stdout.write(info + "\n") # # # def add(self, n, values=[]): # self.update(self.seen_so_far+n, values) # # Path: mozi/utils/train_object_utils.py # def is_shared_var(var): # return var.__class__.__name__ == 'TensorSharedVariable' or \ # var.__class__.__name__ == 'CudaNdarraySharedVariable' . Output only the next line.
def tile_raster_graphs(dct_reconstruct, orig, ae_reconstruct, tile_shape, tile_spacing=(0.1,0.1),
Next line prediction: <|code_start|>floatX = theano.config.floatX theano_rand = MRG_RandomStreams() class VariationalAutoencoder(Template): def __init__(self, input_dim, bottlenet_dim, z_dim, weight_init=GaussianWeight(mean=0, std=0.01)): self.input_dim = input_dim self.bottlenet_dim = bottlenet_dim # encoder self.W_e = weight_init((input_dim, bottlenet_dim), name='W_e') self.b_e = shared_zeros(shape=bottlenet_dim, name='b_e') self.W_miu = weight_init((bottlenet_dim, z_dim), name='W_miu') self.b_miu = shared_zeros(shape=z_dim, name='b_miu') self.W_sig = weight_init((bottlenet_dim, z_dim), name='W_sig') self.b_sig = shared_zeros(shape=z_dim, name='b_sig') # decoder self.W1_d = weight_init((z_dim, bottlenet_dim), name='W1_d') self.b1_d = shared_zeros(shape=bottlenet_dim, name='b1_d') self.W2_d = weight_init((bottlenet_dim, input_dim), name='W2_d') self.b2_d = shared_zeros(shape=input_dim, name='b2_d') self.params = [self.W_e, self.b_e, self.W_miu, self.b_miu, self.W_sig, self.b_sig, self.W1_d, self.b1_d, self.W2_d, self.b2_d] def _train_fprop(self, state_below): h_e = T.tanh(T.dot(state_below, self.W_e) + self.b_e) miu_e = T.dot(h_e, self.W_miu) + self.b_miu <|code_end|> . Use current file imports: (import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams from mozi.layers.template import Template from mozi.weight_init import GaussianWeight from mozi.utils.theano_utils import shared_zeros) and context including class names, function names, or small code snippets from other files: # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] # # Path: mozi/weight_init.py # class GaussianWeight(WeightInitialization): # def __init__(self, mean=0, std=0.1): # self.mean = mean # self.std = std # # def __call__(self, dim, name='W', **kwargs): # W_values = np.random.normal(loc=self.mean, scale=self.std, size=dim) # return sharedX(name=name, value=W_values, borrow=True, **kwargs) # # Path: mozi/utils/theano_utils.py # def shared_zeros(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.zeros(shape), dtype=dtype, name=name, **kwargs) . Output only the next line.
logsig_e = 0.5 * (T.dot(h_e, self.W_sig) + self.b_sig)
Predict the next line after this snippet: <|code_start|> self.b_miu = shared_zeros(shape=z_dim, name='b_miu') self.W_sig = weight_init((bottlenet_dim, z_dim), name='W_sig') self.b_sig = shared_zeros(shape=z_dim, name='b_sig') # decoder self.W1_d = weight_init((z_dim, bottlenet_dim), name='W1_d') self.b1_d = shared_zeros(shape=bottlenet_dim, name='b1_d') self.W2_d = weight_init((bottlenet_dim, input_dim), name='W2_d') self.b2_d = shared_zeros(shape=input_dim, name='b2_d') self.params = [self.W_e, self.b_e, self.W_miu, self.b_miu, self.W_sig, self.b_sig, self.W1_d, self.b1_d, self.W2_d, self.b2_d] def _train_fprop(self, state_below): h_e = T.tanh(T.dot(state_below, self.W_e) + self.b_e) miu_e = T.dot(h_e, self.W_miu) + self.b_miu logsig_e = 0.5 * (T.dot(h_e, self.W_sig) + self.b_sig) eps = theano_rand.normal(avg=0, std=1, size=logsig_e.shape, dtype=floatX) z = miu_e + T.exp(logsig_e) * eps h_d = T.tanh(T.dot(z, self.W1_d) + self.b1_d) y = T.nnet.sigmoid(T.dot(h_d, self.W2_d) + self.b2_d) return y, miu_e, logsig_e def _layer_stats(self, state_below, layer_output): y, miu, logsig = layer_output return [('W_miu', self.W_miu.mean()), ('W_e', self.W_e.mean()), ('logsig', logsig.mean()), ('ymean,', y.mean()), <|code_end|> using the current file's imports: import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams from mozi.layers.template import Template from mozi.weight_init import GaussianWeight from mozi.utils.theano_utils import shared_zeros and any relevant context from other files: # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] # # Path: mozi/weight_init.py # class GaussianWeight(WeightInitialization): # def __init__(self, mean=0, std=0.1): # self.mean = mean # self.std = std # # def __call__(self, dim, name='W', **kwargs): # W_values = np.random.normal(loc=self.mean, scale=self.std, size=dim) # return sharedX(name=name, value=W_values, borrow=True, **kwargs) # # Path: mozi/utils/theano_utils.py # def shared_zeros(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.zeros(shape), dtype=dtype, name=name, **kwargs) . Output only the next line.
('miu', miu.mean())]
Based on the snippet: <|code_start|> def __init__(self, input_dim, bottlenet_dim, z_dim, weight_init=GaussianWeight(mean=0, std=0.01)): self.input_dim = input_dim self.bottlenet_dim = bottlenet_dim # encoder self.W_e = weight_init((input_dim, bottlenet_dim), name='W_e') self.b_e = shared_zeros(shape=bottlenet_dim, name='b_e') self.W_miu = weight_init((bottlenet_dim, z_dim), name='W_miu') self.b_miu = shared_zeros(shape=z_dim, name='b_miu') self.W_sig = weight_init((bottlenet_dim, z_dim), name='W_sig') self.b_sig = shared_zeros(shape=z_dim, name='b_sig') # decoder self.W1_d = weight_init((z_dim, bottlenet_dim), name='W1_d') self.b1_d = shared_zeros(shape=bottlenet_dim, name='b1_d') self.W2_d = weight_init((bottlenet_dim, input_dim), name='W2_d') self.b2_d = shared_zeros(shape=input_dim, name='b2_d') self.params = [self.W_e, self.b_e, self.W_miu, self.b_miu, self.W_sig, self.b_sig, self.W1_d, self.b1_d, self.W2_d, self.b2_d] def _train_fprop(self, state_below): h_e = T.tanh(T.dot(state_below, self.W_e) + self.b_e) miu_e = T.dot(h_e, self.W_miu) + self.b_miu logsig_e = 0.5 * (T.dot(h_e, self.W_sig) + self.b_sig) eps = theano_rand.normal(avg=0, std=1, size=logsig_e.shape, dtype=floatX) z = miu_e + T.exp(logsig_e) * eps h_d = T.tanh(T.dot(z, self.W1_d) + self.b1_d) y = T.nnet.sigmoid(T.dot(h_d, self.W2_d) + self.b2_d) <|code_end|> , predict the immediate next line with the help of imports: import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams from mozi.layers.template import Template from mozi.weight_init import GaussianWeight from mozi.utils.theano_utils import shared_zeros and context (classes, functions, sometimes code) from other files: # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] # # Path: mozi/weight_init.py # class GaussianWeight(WeightInitialization): # def __init__(self, mean=0, std=0.1): # self.mean = mean # self.std = std # # def __call__(self, dim, name='W', **kwargs): # W_values = np.random.normal(loc=self.mean, scale=self.std, size=dim) # return sharedX(name=name, value=W_values, borrow=True, **kwargs) # # Path: mozi/utils/theano_utils.py # def shared_zeros(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.zeros(shape), dtype=dtype, name=name, **kwargs) . Output only the next line.
return y, miu_e, logsig_e
Given the code snippet: <|code_start|>logger = logging.getLogger(__name__) floatX = theano.config.floatX class Cifar10(SingleBlock): def __init__(self, flatten=False, **kwargs): im_dir = os.environ['MOZI_DATA_PATH'] + '/cifar10/' path = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' im_dir = get_file(fpath="{}/cifar-10-python.tar.gz".format(im_dir), origin=path, untar=True) self.label_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog','horse','ship','truck'] self.img_shape = (3,32,32) self.img_size = np.prod(self.img_shape) <|code_end|> , generate the next line using the imports in this file: import logging import os import cPickle import numpy as np import theano from mozi.utils.utils import get_file, make_one_hot from mozi.datasets.dataset import SingleBlock and context (functions, classes, or occasionally code) from other files: # Path: mozi/utils/utils.py # def get_file(fpath, origin, untar=False): # datadir = os.path.dirname(fpath) # if not os.path.exists(datadir): # os.makedirs(datadir) # # if not os.path.exists(fpath): # print('Downloading data from', origin) # # global progbar # progbar = None # def dl_progress(count, block_size, total_size): # global progbar # if progbar is None: # progbar = Progbar(total_size) # else: # progbar.update(count*block_size) # # urlretrieve(origin, fpath, dl_progress) # progbar = None # # dirname = "" # if untar: # tfile = tarfile.open(fpath, 'r:*') # names = tfile.getnames() # dirname = names[0] # not_exists = [int(not os.path.exists("{}/{}".format(datadir, fname))) for fname in names] # if sum(not_exists) > 0: # print('Untaring file...') # tfile.extractall(path=datadir) # else: # print('Files already downloaded and untarred') # tfile.close() # # return "{}/{}".format(datadir, dirname) # # def make_one_hot(X, onehot_size): # """ # DESCRIPTION: # Make a one-hot version of X # PARAM: # X: 1d numpy with each value in X representing the class of X # onehot_size: length of the one hot vector # RETURN: # 2d numpy tensor, with each row been the onehot vector # """ # # rX = np.zeros((len(X), onehot_size), dtype=theano.config.floatX) # for i in xrange(len(X)): # rX[i, X[i]] = 1 # # return rX # # Path: mozi/datasets/dataset.py # class SingleBlock(Dataset): # # def __init__(self, X=None, y=None, train_valid_test_ratio=[8,1,1], log=None, **kwargs): # ''' # All the data is loaded into memory for one go training # ''' # super(SingleBlock, self).__init__(log=log) # self.ratio = train_valid_test_ratio # self.train = IterMatrix(X=None, y=None, **kwargs) # self.valid = IterMatrix(X=None, y=None, **kwargs) # self.test = IterMatrix(X=None, y=None, **kwargs) # # assert len(self.ratio) == 3, 'the size of list is not 3' # # if X is not None and y is not None: # self.set_Xy(X, y) # # def __iter__(self): # self.iter = True # return self # # def next(self): # if self.iter: # # only one iteration since there is only one data block # self.iter = False # return self # else: # raise StopIteration # # @property # def nblocks(self): # return 1 # # def set_Xy(self, X, y): # num_examples = len(X) # total_ratio = sum(self.ratio) # num_train = int(self.ratio[0] * 1.0 * num_examples / total_ratio) # num_valid = int(self.ratio[1] * 1.0 * num_examples / total_ratio) # # train_X = X[:num_train] # train_y = y[:num_train] # # valid_X = X[num_train:num_train+num_valid] # valid_y = y[num_train:num_train+num_valid] # # test_X = X[num_train+num_valid:] # test_y = y[num_train+num_valid:] # # self.train.X = train_X # self.train.y = train_y # # if self.ratio[1] == 0: # self.log.info('Valid set is empty! It is needed for early stopping and saving best model') # # self.valid.X = valid_X # self.valid.y = valid_y # # if self.ratio[2] == 0: # self.log.info('Test set is empty! It is needed for testing the best model') # # self.test.X = test_X # self.test.y = test_y # # # def get_train(self): # return self.train # # def get_valid(self): # return self.valid # # def get_test(self): # return self.test # # def set_train(self, X, y): # self.train.X = X # self.train.y = y # # def set_valid(self, X, y): # self.valid.X = X # self.valid.y = y # # def set_test(self, X, y): # self.test.X = X # self.test.y = y . Output only the next line.
self.n_classes = 10
Predict the next line after this snippet: <|code_start|>logger = logging.getLogger(__name__) floatX = theano.config.floatX class Cifar10(SingleBlock): <|code_end|> using the current file's imports: import logging import os import cPickle import numpy as np import theano from mozi.utils.utils import get_file, make_one_hot from mozi.datasets.dataset import SingleBlock and any relevant context from other files: # Path: mozi/utils/utils.py # def get_file(fpath, origin, untar=False): # datadir = os.path.dirname(fpath) # if not os.path.exists(datadir): # os.makedirs(datadir) # # if not os.path.exists(fpath): # print('Downloading data from', origin) # # global progbar # progbar = None # def dl_progress(count, block_size, total_size): # global progbar # if progbar is None: # progbar = Progbar(total_size) # else: # progbar.update(count*block_size) # # urlretrieve(origin, fpath, dl_progress) # progbar = None # # dirname = "" # if untar: # tfile = tarfile.open(fpath, 'r:*') # names = tfile.getnames() # dirname = names[0] # not_exists = [int(not os.path.exists("{}/{}".format(datadir, fname))) for fname in names] # if sum(not_exists) > 0: # print('Untaring file...') # tfile.extractall(path=datadir) # else: # print('Files already downloaded and untarred') # tfile.close() # # return "{}/{}".format(datadir, dirname) # # def make_one_hot(X, onehot_size): # """ # DESCRIPTION: # Make a one-hot version of X # PARAM: # X: 1d numpy with each value in X representing the class of X # onehot_size: length of the one hot vector # RETURN: # 2d numpy tensor, with each row been the onehot vector # """ # # rX = np.zeros((len(X), onehot_size), dtype=theano.config.floatX) # for i in xrange(len(X)): # rX[i, X[i]] = 1 # # return rX # # Path: mozi/datasets/dataset.py # class SingleBlock(Dataset): # # def __init__(self, X=None, y=None, train_valid_test_ratio=[8,1,1], log=None, **kwargs): # ''' # All the data is loaded into memory for one go training # ''' # super(SingleBlock, self).__init__(log=log) # self.ratio = train_valid_test_ratio # self.train = IterMatrix(X=None, y=None, **kwargs) # self.valid = IterMatrix(X=None, y=None, **kwargs) # self.test = IterMatrix(X=None, y=None, **kwargs) # # assert len(self.ratio) == 3, 'the size of list is not 3' # # if X is not None and y is not None: # self.set_Xy(X, y) # # def __iter__(self): # self.iter = True # return self # # def next(self): # if self.iter: # # only one iteration since there is only one data block # self.iter = False # return self # else: # raise StopIteration # # @property # def nblocks(self): # return 1 # # def set_Xy(self, X, y): # num_examples = len(X) # total_ratio = sum(self.ratio) # num_train = int(self.ratio[0] * 1.0 * num_examples / total_ratio) # num_valid = int(self.ratio[1] * 1.0 * num_examples / total_ratio) # # train_X = X[:num_train] # train_y = y[:num_train] # # valid_X = X[num_train:num_train+num_valid] # valid_y = y[num_train:num_train+num_valid] # # test_X = X[num_train+num_valid:] # test_y = y[num_train+num_valid:] # # self.train.X = train_X # self.train.y = train_y # # if self.ratio[1] == 0: # self.log.info('Valid set is empty! It is needed for early stopping and saving best model') # # self.valid.X = valid_X # self.valid.y = valid_y # # if self.ratio[2] == 0: # self.log.info('Test set is empty! It is needed for testing the best model') # # self.test.X = test_X # self.test.y = test_y # # # def get_train(self): # return self.train # # def get_valid(self): # return self.valid # # def get_test(self): # return self.test # # def set_train(self, X, y): # self.train.X = X # self.train.y = y # # def set_valid(self, X, y): # self.valid.X = X # self.valid.y = y # # def set_test(self, X, y): # self.test.X = X # self.test.y = y . Output only the next line.
def __init__(self, flatten=False, **kwargs):
Here is a snippet: <|code_start|> class Flatten(Template): def _train_fprop(self, state_below): size = T.prod(state_below.shape) / state_below.shape[0] nshape = (state_below.shape[0], size) return T.reshape(state_below, nshape) class Reshape(Template): <|code_end|> . Write the next line using the current file imports: import theano import theano.tensor as T import numpy as np from mozi.layers.template import Template and context from other files: # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] , which may include functions, classes, or code. Output only the next line.
def __init__(self, dims):
Here is a snippet: <|code_start|> def _step(self, xi_t, xf_t, xo_t, xc_t, h_tm1, c_tm1, u_i, u_f, u_o, u_c): i_t = T.nnet.sigmoid(xi_t + T.dot(h_tm1, u_i)) f_t = T.nnet.sigmoid(xf_t + T.dot(h_tm1, u_f)) o_t = T.nnet.sigmoid(xo_t + T.dot(h_tm1, u_o)) g_t = T.tanh(xc_t + T.dot(h_tm1, u_c)) c_t = f_t * c_tm1 + i_t * g_t h_t = o_t * T.tanh(c_t) return h_t, c_t def _train_fprop(self, state_below): X = state_below.dimshuffle((1, 0, 2)) xi = T.dot(X, self.W_i) + self.b_i xf = T.dot(X, self.W_f) + self.b_f xc = T.dot(X, self.W_c) + self.b_c xo = T.dot(X, self.W_o) + self.b_o [outputs, memories], updates = theano.scan( self._step, sequences=[xi, xf, xo, xc], outputs_info=[ T.unbroadcast(alloc_zeros_matrix(X.shape[1], self.output_dim), 1), T.unbroadcast(alloc_zeros_matrix(X.shape[1], self.output_dim), 1) ], non_sequences=[self.U_i, self.U_f, self.U_o, self.U_c], <|code_end|> . Write the next line using the current file imports: from mozi.utils.theano_utils import shared_zeros, alloc_zeros_matrix, shared_ones from mozi.layers.template import Template from mozi.weight_init import OrthogonalWeight, GaussianWeight, Identity import theano.tensor as T import theano and context from other files: # Path: mozi/utils/theano_utils.py # def shared_zeros(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.zeros(shape), dtype=dtype, name=name, **kwargs) # # def alloc_zeros_matrix(*dims): # return T.alloc(np.cast[floatX](0.), *dims) # # def shared_ones(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.ones(shape), dtype=dtype, name=name, **kwargs) # # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] # # Path: mozi/weight_init.py # class OrthogonalWeight(WeightInitialization): # def __init__(self, scale=1.1): # self.scale = scale # # def __call__(self, dim, name='W', **kwargs): # ''' From Lasagne # ''' # flat_shape = (dim[0], np.prod(dim[1:])) # a = np.random.normal(0.0, 1.0, flat_shape) # u, _, v = np.linalg.svd(a, full_matrices=False) # # pick the one with the correct shape # q = u if u.shape == flat_shape else v # q = q.reshape(dim) # return sharedX(name=name, value=self.scale * q[:dim[0],:dim[1]], borrow=True, **kwargs) # # class GaussianWeight(WeightInitialization): # def __init__(self, mean=0, std=0.1): # self.mean = mean # self.std = std # # def __call__(self, dim, name='W', **kwargs): # W_values = np.random.normal(loc=self.mean, scale=self.std, size=dim) # return sharedX(name=name, value=W_values, borrow=True, **kwargs) # # class Identity(WeightInitialization): # def __init__(self, scale=1): # self.scale = scale # # def __call__(self, dim, name='W', **kwargs): # if len(dim) != 2 or dim[0] != dim[1]: # raise Exception("Identity matrix initialization can only be used for 2D square matrices") # else: # return sharedX(self.scale * np.identity(dim[0]), **kwargs) , which may include functions, classes, or code. Output only the next line.
truncate_gradient=self.truncate_gradient)
Given snippet: <|code_start|> self.input_dim = input_dim self.output_dim = output_dim self.truncate_gradient = truncate_gradient self.return_sequences = return_sequences self.W_i = weight_init((self.input_dim, self.output_dim)) self.U_i = inner_init((self.output_dim, self.output_dim)) self.b_i = shared_zeros((self.output_dim), name='b_i') self.W_f = weight_init((self.input_dim, self.output_dim)) self.U_f = inner_init((self.output_dim, self.output_dim)) self.b_f = shared_ones((self.output_dim), name='b_f') self.W_c = weight_init((self.input_dim, self.output_dim)) self.U_c = inner_init((self.output_dim, self.output_dim)) self.b_c = shared_zeros((self.output_dim), name='b_c') self.W_o = weight_init((self.input_dim, self.output_dim)) self.U_o = inner_init((self.output_dim, self.output_dim)) self.b_o = shared_zeros((self.output_dim), name='b_o') self.params = [ self.W_i, self.U_i, self.b_i, self.W_c, self.U_c, self.b_c, self.W_f, self.U_f, self.b_f, self.W_o, self.U_o, self.b_o, ] def _step(self, xi_t, xf_t, xo_t, xc_t, <|code_end|> , continue by predicting the next line. Consider current file imports: from mozi.utils.theano_utils import shared_zeros, alloc_zeros_matrix, shared_ones from mozi.layers.template import Template from mozi.weight_init import OrthogonalWeight, GaussianWeight, Identity import theano.tensor as T import theano and context: # Path: mozi/utils/theano_utils.py # def shared_zeros(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.zeros(shape), dtype=dtype, name=name, **kwargs) # # def alloc_zeros_matrix(*dims): # return T.alloc(np.cast[floatX](0.), *dims) # # def shared_ones(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.ones(shape), dtype=dtype, name=name, **kwargs) # # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] # # Path: mozi/weight_init.py # class OrthogonalWeight(WeightInitialization): # def __init__(self, scale=1.1): # self.scale = scale # # def __call__(self, dim, name='W', **kwargs): # ''' From Lasagne # ''' # flat_shape = (dim[0], np.prod(dim[1:])) # a = np.random.normal(0.0, 1.0, flat_shape) # u, _, v = np.linalg.svd(a, full_matrices=False) # # pick the one with the correct shape # q = u if u.shape == flat_shape else v # q = q.reshape(dim) # return sharedX(name=name, value=self.scale * q[:dim[0],:dim[1]], borrow=True, **kwargs) # # class GaussianWeight(WeightInitialization): # def __init__(self, mean=0, std=0.1): # self.mean = mean # self.std = std # # def __call__(self, dim, name='W', **kwargs): # W_values = np.random.normal(loc=self.mean, scale=self.std, size=dim) # return sharedX(name=name, value=W_values, borrow=True, **kwargs) # # class Identity(WeightInitialization): # def __init__(self, scale=1): # self.scale = scale # # def __call__(self, dim, name='W', **kwargs): # if len(dim) != 2 or dim[0] != dim[1]: # raise Exception("Identity matrix initialization can only be used for 2D square matrices") # else: # return sharedX(self.scale * np.identity(dim[0]), **kwargs) which might include code, classes, or functions. Output only the next line.
h_tm1, c_tm1, u_i, u_f, u_o, u_c):
Given snippet: <|code_start|> class LSTM(Template): def __init__(self, input_dim, output_dim, truncate_gradient=-1, return_sequences=True, weight_init=OrthogonalWeight(), inner_init=GaussianWeight(mean=0, std=0.1)): self.input_dim = input_dim self.output_dim = output_dim self.truncate_gradient = truncate_gradient self.return_sequences = return_sequences self.W_i = weight_init((self.input_dim, self.output_dim)) self.U_i = inner_init((self.output_dim, self.output_dim)) self.b_i = shared_zeros((self.output_dim), name='b_i') self.W_f = weight_init((self.input_dim, self.output_dim)) self.U_f = inner_init((self.output_dim, self.output_dim)) self.b_f = shared_ones((self.output_dim), name='b_f') <|code_end|> , continue by predicting the next line. Consider current file imports: from mozi.utils.theano_utils import shared_zeros, alloc_zeros_matrix, shared_ones from mozi.layers.template import Template from mozi.weight_init import OrthogonalWeight, GaussianWeight, Identity import theano.tensor as T import theano and context: # Path: mozi/utils/theano_utils.py # def shared_zeros(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.zeros(shape), dtype=dtype, name=name, **kwargs) # # def alloc_zeros_matrix(*dims): # return T.alloc(np.cast[floatX](0.), *dims) # # def shared_ones(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.ones(shape), dtype=dtype, name=name, **kwargs) # # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] # # Path: mozi/weight_init.py # class OrthogonalWeight(WeightInitialization): # def __init__(self, scale=1.1): # self.scale = scale # # def __call__(self, dim, name='W', **kwargs): # ''' From Lasagne # ''' # flat_shape = (dim[0], np.prod(dim[1:])) # a = np.random.normal(0.0, 1.0, flat_shape) # u, _, v = np.linalg.svd(a, full_matrices=False) # # pick the one with the correct shape # q = u if u.shape == flat_shape else v # q = q.reshape(dim) # return sharedX(name=name, value=self.scale * q[:dim[0],:dim[1]], borrow=True, **kwargs) # # class GaussianWeight(WeightInitialization): # def __init__(self, mean=0, std=0.1): # self.mean = mean # self.std = std # # def __call__(self, dim, name='W', **kwargs): # W_values = np.random.normal(loc=self.mean, scale=self.std, size=dim) # return sharedX(name=name, value=W_values, borrow=True, **kwargs) # # class Identity(WeightInitialization): # def __init__(self, scale=1): # self.scale = scale # # def __call__(self, dim, name='W', **kwargs): # if len(dim) != 2 or dim[0] != dim[1]: # raise Exception("Identity matrix initialization can only be used for 2D square matrices") # else: # return sharedX(self.scale * np.identity(dim[0]), **kwargs) which might include code, classes, or functions. Output only the next line.
self.W_c = weight_init((self.input_dim, self.output_dim))
Predict the next line after this snippet: <|code_start|> def _step(self, xi_t, xf_t, xo_t, xc_t, h_tm1, c_tm1, u_i, u_f, u_o, u_c): i_t = T.nnet.sigmoid(xi_t + T.dot(h_tm1, u_i)) f_t = T.nnet.sigmoid(xf_t + T.dot(h_tm1, u_f)) o_t = T.nnet.sigmoid(xo_t + T.dot(h_tm1, u_o)) g_t = T.tanh(xc_t + T.dot(h_tm1, u_c)) c_t = f_t * c_tm1 + i_t * g_t h_t = o_t * T.tanh(c_t) return h_t, c_t def _train_fprop(self, state_below): X = state_below.dimshuffle((1, 0, 2)) xi = T.dot(X, self.W_i) + self.b_i xf = T.dot(X, self.W_f) + self.b_f xc = T.dot(X, self.W_c) + self.b_c xo = T.dot(X, self.W_o) + self.b_o [outputs, memories], updates = theano.scan( self._step, sequences=[xi, xf, xo, xc], outputs_info=[ T.unbroadcast(alloc_zeros_matrix(X.shape[1], self.output_dim), 1), T.unbroadcast(alloc_zeros_matrix(X.shape[1], self.output_dim), 1) ], non_sequences=[self.U_i, self.U_f, self.U_o, self.U_c], <|code_end|> using the current file's imports: from mozi.utils.theano_utils import shared_zeros, alloc_zeros_matrix, shared_ones from mozi.layers.template import Template from mozi.weight_init import OrthogonalWeight, GaussianWeight, Identity import theano.tensor as T import theano and any relevant context from other files: # Path: mozi/utils/theano_utils.py # def shared_zeros(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.zeros(shape), dtype=dtype, name=name, **kwargs) # # def alloc_zeros_matrix(*dims): # return T.alloc(np.cast[floatX](0.), *dims) # # def shared_ones(shape, dtype=floatX, name=None, **kwargs): # return sharedX(np.ones(shape), dtype=dtype, name=name, **kwargs) # # Path: mozi/layers/template.py # class Template(object): # """ # DESCRIPTION: # The interface to be implemented by any layer. # """ # def __init__(self): # ''' # FIELDS: # self.params: any params from the layer that needs to be updated # by backpropagation can be put inside self.params # self.updates: use for updating any shared variables # ''' # self.params = [] # self.updates = [] # # def _test_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during validating/testing of the model. # PARAM: # state_below: the input to layer # ''' # return self._train_fprop(state_below) # # def _train_fprop(self, state_below): # ''' # DESCRIPTION: # This is called during every training batch whereby the output from the # model will be used to update the parameters during error backpropagation. # PARAM: # state_below: the input to layer # ''' # raise NotImplementedError() # # # def _layer_stats(self, state_below, layer_output): # """ # DESCRIPTION: # Layer stats is used for debugging the layer by allowing user to peek # at the weight values or the layer output or any parameters of interest # during training. By computing the values of parameter of interest, # for example T.max(self.W) and put in the return list, the training will # print the maximum of the weight in the layer after every epoch. # PARAM: # state_below: the input to layer # layer_output: the output from the layer # RETURN: # A list of tuples of [('name_a', var_a), ('name_b', var_b)] whereby var is scalar # """ # return [] # # Path: mozi/weight_init.py # class OrthogonalWeight(WeightInitialization): # def __init__(self, scale=1.1): # self.scale = scale # # def __call__(self, dim, name='W', **kwargs): # ''' From Lasagne # ''' # flat_shape = (dim[0], np.prod(dim[1:])) # a = np.random.normal(0.0, 1.0, flat_shape) # u, _, v = np.linalg.svd(a, full_matrices=False) # # pick the one with the correct shape # q = u if u.shape == flat_shape else v # q = q.reshape(dim) # return sharedX(name=name, value=self.scale * q[:dim[0],:dim[1]], borrow=True, **kwargs) # # class GaussianWeight(WeightInitialization): # def __init__(self, mean=0, std=0.1): # self.mean = mean # self.std = std # # def __call__(self, dim, name='W', **kwargs): # W_values = np.random.normal(loc=self.mean, scale=self.std, size=dim) # return sharedX(name=name, value=W_values, borrow=True, **kwargs) # # class Identity(WeightInitialization): # def __init__(self, scale=1): # self.scale = scale # # def __call__(self, dim, name='W', **kwargs): # if len(dim) != 2 or dim[0] != dim[1]: # raise Exception("Identity matrix initialization can only be used for 2D square matrices") # else: # return sharedX(self.scale * np.identity(dim[0]), **kwargs) . Output only the next line.
truncate_gradient=self.truncate_gradient)
Predict the next line for this snippet: <|code_start|>except Exception as e: print (e) try: deepnlp.download("pos", "zh_finance") except Exception as e: print (e) deepnlp.register_model("pos", "zh_finance") deepnlp.download("pos", "zh_finance") try: pos_tagger.load_model("zh_finance") except Exception as e: print (e) try: deepnlp.download("ner", "zh_finance") except Exception as e: print (e) deepnlp.register_model("ner", "zh_finance") deepnlp.download("ner", "zh_finance") try: ner_tagger.load_model("zh_finance") except Exception as e: print (e) try: deepnlp.download("parse", "zh_finance") except Exception as e: <|code_end|> with the help of current file imports: import deepnlp from deepnlp import segmenter from deepnlp import pos_tagger from deepnlp import ner_tagger from deepnlp import nn_parser and context from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): # # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): # # Path: deepnlp/nn_parser.py # UNKNOWN = "*" # X = np.array([features]) # convert 1-D list to ndarray size [1, dim] # Y = np.array([[0] * target_num]) # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tags = None): # def _init_model(self, session): # def _predict(self, session, model, words, tags): # def _predict_tree(self, session, model, sent, debug = False): # def load_model(name = 'zh'): , which may contain function names, class names, or code. Output only the next line.
print (e)
Here is a snippet: <|code_start|> seg_tagger = segmenter.load_model("zh_finance") except Exception as e: print (e) try: deepnlp.download("pos", "zh_finance") except Exception as e: print (e) deepnlp.register_model("pos", "zh_finance") deepnlp.download("pos", "zh_finance") try: pos_tagger.load_model("zh_finance") except Exception as e: print (e) try: deepnlp.download("ner", "zh_finance") except Exception as e: print (e) deepnlp.register_model("ner", "zh_finance") deepnlp.download("ner", "zh_finance") try: ner_tagger.load_model("zh_finance") except Exception as e: print (e) try: deepnlp.download("parse", "zh_finance") <|code_end|> . Write the next line using the current file imports: import deepnlp from deepnlp import segmenter from deepnlp import pos_tagger from deepnlp import ner_tagger from deepnlp import nn_parser and context from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): # # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): # # Path: deepnlp/nn_parser.py # UNKNOWN = "*" # X = np.array([features]) # convert 1-D list to ndarray size [1, dim] # Y = np.array([[0] * target_num]) # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tags = None): # def _init_model(self, session): # def _predict(self, session, model, words, tags): # def _predict_tree(self, session, model, sent, debug = False): # def load_model(name = 'zh'): , which may include functions, classes, or code. Output only the next line.
except Exception as e:
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python # -*- coding:utf-8 -*- try: deepnlp.download("segment", "zh_finance") except Exception as e: print (e) deepnlp.register_model("segment", "zh_finance") deepnlp.download("segment", "zh_finance") try: seg_tagger = segmenter.load_model("zh_finance") except Exception as e: print (e) <|code_end|> with the help of current file imports: import deepnlp from deepnlp import segmenter from deepnlp import pos_tagger from deepnlp import ner_tagger from deepnlp import nn_parser and context from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): # # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): # # Path: deepnlp/nn_parser.py # UNKNOWN = "*" # X = np.array([features]) # convert 1-D list to ndarray size [1, dim] # Y = np.array([[0] * target_num]) # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tags = None): # def _init_model(self, session): # def _predict(self, session, model, words, tags): # def _predict_tree(self, session, model, sent, debug = False): # def load_model(name = 'zh'): , which may contain function names, class names, or code. Output only the next line.
try:
Next line prediction: <|code_start|>#!/usr/bin/python # -*- coding:utf-8 -*- from __future__ import unicode_literals # compatible with python3 unicode deepnlp.download('ner') # download the NER pretrained models from github if installed from pip tagger = ner_tagger.load_model(name = 'zh') # Base LSTM Based Model tagger.load_dict("zh_o2o") # Change to other dict <|code_end|> . Use current file imports: (import deepnlp from deepnlp import ner_tagger from deepnlp.ner_tagger import udf_disambiguation_cooccur from deepnlp.ner_tagger import udf_default ) and context including class names, function names, or small code snippets from other files: # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): # # Path: deepnlp/ner_tagger.py # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # """ Disambiguation based on cooccurence of context and tag_feat_dict # Args: word: input word # tags: multiple tags on word # context: list of words surrounding current word of a window # """ # if (len(tag_feat_dict) == 0) or (len(tags) == 0): # return None, 0.0 # # num = len(tags) # coocur_dict = {} # coocur_count = [] # for tag in tags: # feat_words = tag_feat_dict[tag] if tag in tag_feat_dict else [] # common = [] # for feat in feat_words: # if feat in context: # common.append(feat) # coocur_dict[tag] = len(common) # How many occurence under current tags # coocur_count.append(len(common)) # vec = np.array(coocur_count) # total = np.sum(vec) # prob_vec = [] # if total > 0.0: # prob_vec = vec/total # else: # prob_vec = 0.0 * vec # max_index = np.argmax(prob_vec) # return tags[max_index], prob_vec[max_index] # # Path: deepnlp/ner_tagger.py # def udf_default(word, tags, *args): # """ Default get the first tag # Return: tag, confidence # """ # if (len(tags) > 0): # return tags[0], 1.0 # else: # return TAG_NONE_ENTITY # return tags[0], 1.0 . Output only the next line.
text = "北京 望京 最好吃 的 黑椒 牛排 在哪里"
Continue the code snippet: <|code_start|>#coding:utf-8 from __future__ import unicode_literals # compatible with python3 unicode # Load Model tokenizer = segmenter.load_model(name = 'zh') tagger = pos_tagger.load_model(name = 'zh') #Segmentation text = "我爱吃北京烤鸭" # unicode coding, py2 and py3 compatible words = tokenizer.seg(text) print(" ".join(words)) #POS Tagging tagging = tagger.predict(words) for (w,t) in tagging: pair = w + "/" + t <|code_end|> . Use current file imports: from deepnlp import segmenter from deepnlp import pos_tagger and context (classes, functions, or code) from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): . Output only the next line.
print(pair)
Next line prediction: <|code_start|>#coding:utf-8 from __future__ import unicode_literals # compatible with python3 unicode # Load Model tokenizer = segmenter.load_model(name = 'zh') tagger = pos_tagger.load_model(name = 'zh') #Segmentation text = "我爱吃北京烤鸭" # unicode coding, py2 and py3 compatible words = tokenizer.seg(text) print(" ".join(words)) #POS Tagging tagging = tagger.predict(words) <|code_end|> . Use current file imports: (from deepnlp import segmenter from deepnlp import pos_tagger ) and context including class names, function names, or small code snippets from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): . Output only the next line.
for (w,t) in tagging:
Next line prediction: <|code_start|>#coding:utf-8 from __future__ import unicode_literals # compatible with python3 unicode deepnlp.download('segment') # download all the required pretrained models from github if installed from pip deepnlp.download('pos') deepnlp.download('ner') p = pipeline.load_model('zh') # concatenate tuples into one string "w1/t1 w2/t2 ..." def _concat_tuples(tagging): TOKEN_BLANK = " " wl = [] # wordlist <|code_end|> . Use current file imports: (import sys,os import codecs import deepnlp from deepnlp import pipeline ) and context including class names, function names, or small code snippets from other files: # Path: deepnlp/pipeline.py # class Pipeline(object): # def __init__(self, name): # def analyze(self, string): # def segment(self, string): # def tag_pos(self, words): # def tag_ner(self, words): # def parse(self, words): # def _concat_tuples(tagging): # def load_model(lang = 'zh'): # TOKEN_BLANK = " " . Output only the next line.
for (x, y) in tagging:
Given the code snippet: <|code_start|>#coding:utf-8 from __future__ import unicode_literals # compatible with python3 unicode deepnlp.download('ner') # download the NER pretrained models from github if installed from pip tokenizer = segmenter.load_model(name = 'zh') tagger = ner_tagger.load_model(name = 'zh') #Segmentation text = "我爱吃北京烤鸭" words = tokenizer.seg(text) print (" ".join(words)) #NER tagging tagging = tagger.predict(words) for (w,t) in tagging: <|code_end|> , generate the next line using the imports in this file: import deepnlp from deepnlp import segmenter from deepnlp import ner_tagger and context (functions, classes, or occasionally code) from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): . Output only the next line.
pair = w + "/" + t
Given the code snippet: <|code_start|>BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # concatenate tuples into one string "w1/t1 w2/t2 ..." def _concat_tuples(tagging): TOKEN_BLANK = " " wl = [] # wordlist for (x, y) in tagging: wl.append(x + "/" + y) concat_str = TOKEN_BLANK.join(wl) return concat_str # read input file docs = [] file = codecs.open(os.path.join(BASE_DIR, 'docs_test.txt'), 'r', encoding='utf-8') for line in file: line = line.replace("\n", "").replace("\r", "") docs.append(line) # Test each individual module # output file fileOut = codecs.open(os.path.join(BASE_DIR, 'modules_test_results.txt'), 'w', encoding='utf-8') words = tokenizer.seg(docs[0]) pos_tagging = _concat_tuples(tagger_pos.predict(words)) ner_tagging = _concat_tuples(tagger_ner.predict(words)) fileOut.writelines(" ".join(words) + "\n") fileOut.writelines(pos_tagging + "\n") fileOut.writelines(ner_tagging + "\n") fileOut.close <|code_end|> , generate the next line using the imports in this file: import sys,os import codecs from deepnlp import segmenter from deepnlp import pos_tagger # module: pos_tagger from deepnlp import ner_tagger # module: ner_tagger and context (functions, classes, or occasionally code) from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): # # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): . Output only the next line.
print (" ".join(words))
Next line prediction: <|code_start|>#coding:utf-8 from __future__ import unicode_literals # Create new tagger instance tokenizer = segmenter.load_model(name = 'zh') tagger_pos = pos_tagger.load_model(name = 'zh') tagger_ner = ner_tagger.load_model(name = 'zh') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # concatenate tuples into one string "w1/t1 w2/t2 ..." def _concat_tuples(tagging): TOKEN_BLANK = " " wl = [] # wordlist for (x, y) in tagging: wl.append(x + "/" + y) concat_str = TOKEN_BLANK.join(wl) return concat_str # read input file <|code_end|> . Use current file imports: (import sys,os import codecs from deepnlp import segmenter from deepnlp import pos_tagger # module: pos_tagger from deepnlp import ner_tagger # module: ner_tagger ) and context including class names, function names, or small code snippets from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): # # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): . Output only the next line.
docs = []
Next line prediction: <|code_start|> # Example 1. Change to other dict tagger = ner_tagger.load_model(name = 'zh_o2o') # Base LSTM Based Model + zh_o2o dictionary text = "北京 望京 最好吃 的 小龙虾 在 哪里" words = text.split(" ") tagging = tagger.predict(words, tagset = ['city', 'area', 'dish']) for (w,t) in tagging: pair = w + "/" + t print (pair) #Result #北京/city #望京/area #最好吃/nt #的/nt #小龙虾/dish #在/nt #哪里/nt # Example 2: Switch to base NER LSTM-Based Model and domain-specific dictionary tagger = ner_tagger.load_model(name = 'zh_entertainment') # Base LSTM Based Model #Load Entertainment Dict tagger.load_dict("zh_entertainment") text = "你 最近 在 看 胡歌 演的 猎场 吗 ?" words = text.split(" ") tagset_entertainment = ['actor', 'role_name', 'teleplay', 'teleplay_tag'] tagging = tagger.predict(words, tagset = tagset_entertainment) for (w,t) in tagging: pair = w + "/" + t <|code_end|> . Use current file imports: (import deepnlp from deepnlp import ner_tagger ) and context including class names, function names, or small code snippets from other files: # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): . Output only the next line.
print (pair)
Based on the snippet: <|code_start|>#coding=utf-8 from __future__ import unicode_literals # Download module and domain-specific model deepnlp.download(module = 'segment', name = 'zh_entertainment') deepnlp.download(module = 'pos', name = 'en') deepnlp.download(module = 'ner', name = 'zh_o2o') # Download module deepnlp.download('segment') deepnlp.download('pos') deepnlp.download('ner') deepnlp.download('parse') # deepnlp.download() ## 测试 load model try: tokenizer = segmenter.load_model(name = 'zh') tokenizer = segmenter.load_model(name = 'zh_o2o') tokenizer = segmenter.load_model(name = 'zh_entertainment') except Exception as e: print ("DEBUG: ERROR Found...") print (e) ## pos <|code_end|> , predict the immediate next line with the help of imports: import tensorflow as tf import deepnlp from deepnlp import segmenter from deepnlp import pos_tagger from deepnlp import ner_tagger from deepnlp import nn_parser and context (classes, functions, sometimes code) from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): # # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): # # Path: deepnlp/nn_parser.py # UNKNOWN = "*" # X = np.array([features]) # convert 1-D list to ndarray size [1, dim] # Y = np.array([[0] * target_num]) # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tags = None): # def _init_model(self, session): # def _predict(self, session, model, words, tags): # def _predict_tree(self, session, model, sent, debug = False): # def load_model(name = 'zh'): . Output only the next line.
try:
Using the snippet: <|code_start|>#coding=utf-8 from __future__ import unicode_literals # Download module and domain-specific model deepnlp.download(module = 'segment', name = 'zh_entertainment') deepnlp.download(module = 'pos', name = 'en') deepnlp.download(module = 'ner', name = 'zh_o2o') # Download module deepnlp.download('segment') deepnlp.download('pos') deepnlp.download('ner') deepnlp.download('parse') # deepnlp.download() ## 测试 load model try: tokenizer = segmenter.load_model(name = 'zh') tokenizer = segmenter.load_model(name = 'zh_o2o') tokenizer = segmenter.load_model(name = 'zh_entertainment') except Exception as e: print ("DEBUG: ERROR Found...") print (e) ## pos try: tagger = pos_tagger.load_model(name = 'en') # Loading English model, lang code 'en' tagger = pos_tagger.load_model(name = 'zh') # Loading English model, lang code 'en' <|code_end|> , determine the next line of code. You have imports: import tensorflow as tf import deepnlp from deepnlp import segmenter from deepnlp import pos_tagger from deepnlp import ner_tagger from deepnlp import nn_parser and context (class names, function names, or code) available: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): # # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): # # Path: deepnlp/nn_parser.py # UNKNOWN = "*" # X = np.array([features]) # convert 1-D list to ndarray size [1, dim] # Y = np.array([[0] * target_num]) # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tags = None): # def _init_model(self, session): # def _predict(self, session, model, words, tags): # def _predict_tree(self, session, model, sent, debug = False): # def load_model(name = 'zh'): . Output only the next line.
except Exception as e:
Given the code snippet: <|code_start|>deepnlp.download(module = 'pos', name = 'en') deepnlp.download(module = 'ner', name = 'zh_o2o') # Download module deepnlp.download('segment') deepnlp.download('pos') deepnlp.download('ner') deepnlp.download('parse') # deepnlp.download() ## 测试 load model try: tokenizer = segmenter.load_model(name = 'zh') tokenizer = segmenter.load_model(name = 'zh_o2o') tokenizer = segmenter.load_model(name = 'zh_entertainment') except Exception as e: print ("DEBUG: ERROR Found...") print (e) ## pos try: tagger = pos_tagger.load_model(name = 'en') # Loading English model, lang code 'en' tagger = pos_tagger.load_model(name = 'zh') # Loading English model, lang code 'en' except Exception as e: print ("DEBUG: ERROR Found...") print (e) ## ner <|code_end|> , generate the next line using the imports in this file: import tensorflow as tf import deepnlp from deepnlp import segmenter from deepnlp import pos_tagger from deepnlp import ner_tagger from deepnlp import nn_parser and context (functions, classes, or occasionally code) from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): # # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): # # Path: deepnlp/ner_tagger.py # TAG_NONE_ENTITY = "nt" # ENTITY_TAG_DICT = "entity_tags.dic" # ENTITY_TAG_DICT_PICKLE = "entity_tags.dic.pkl" # DEFAULT_DICT_ZH_NAME = "zh" # def udf_default(word, tags, *args): # def udf_disambiguation_cooccur(word, tags, context, tag_feat_dict, *args): # def ensemble_udf(udfs, word, tags, *args): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tagset = []): # def _init_ner_model(self, session): # def _predict_ner_tags_model(self, session, model, words, data_path): # def set_tag_feat_dict(self, tag_feat_dict): # def _predict_ner_tags_dict(self, words, merge = False, tagset = [],udfs = [udf_default]): # def _get_context_words(self, words, i, window = 4): # def _preprocess_segment(self, words): # def _merge_tagging(self, model_tagging, dict_tagging): # def _load_default_dict(self, name = 'zh'): # def _load_dict(self, dict_name): # def load_dict(self, dict_name): # def load_user_dict(self, path): # def load_model(name = 'zh'): # class ModelLoader(object): # # Path: deepnlp/nn_parser.py # UNKNOWN = "*" # X = np.array([features]) # convert 1-D list to ndarray size [1, dim] # Y = np.array([[0] * target_num]) # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words, tags = None): # def _init_model(self, session): # def _predict(self, session, model, words, tags): # def _predict_tree(self, session, model, sent, debug = False): # def load_model(name = 'zh'): . Output only the next line.
try:
Continue the code snippet: <|code_start|>#coding=utf-8 from __future__ import unicode_literals ## Example 1: Base Model tokenizer = segmenter.load_model(name = 'zh') text = "我爱吃北京烤鸭" segList = tokenizer.seg(text) # python 2/3: function input: unicode, return unicode text_seg = " ".join(segList) print (text_seg) # 我 爱 吃 北京 烤鸭 ## Example 2: Entertainment domain, Movie, Teleplay, Actor name, ... tokenizer = segmenter.load_model(name = 'zh_entertainment') text = "我刚刚在浙江卫视看了电视剧老九门,觉得陈伟霆很帅" segList = tokenizer.seg(text) <|code_end|> . Use current file imports: from deepnlp import segmenter and context (classes, functions, or code) from other files: # Path: deepnlp/segmenter.py # DEFAULT_MODEL = str(os.path.join(pkg_path, "segment/models/zh/crf_model")) # class Tokenizer(object): # def __init__(self, model_path = DEFAULT_MODEL): # def seg(self, text): # def load_model(name = 'zh'): # def load_user_model(model_path): . Output only the next line.
text_seg = " ".join(segList)
Given the following code snippet before the placeholder: <|code_start|>#coding:utf-8 from __future__ import unicode_literals deepnlp.download(module='pos',name='en') # download the POS pretrained models from github if installed from pip tagger = pos_tagger.load_model(name = 'en') # Loading English model, lang code 'en' #Segmentation text = "I want to see a funny movie" words = text.split(" ") print (" ".join(words)) #POS Tagging tagging = tagger.predict(words) for (w,t) in tagging: pair = w + "/" + t <|code_end|> , predict the next line using imports from the current file: import deepnlp from deepnlp import pos_tagger and context including class names, function names, and sometimes code from other files: # Path: deepnlp/pos_tagger.py # class ModelLoader(object): # def __init__(self, name, data_path, ckpt_path, conf_path): # def predict(self, words): # def _init_pos_model(self, session): # def _predict_pos_tags(self, session, model, words, data_path): # def load_model(name = 'zh'): . Output only the next line.
print (pair)
Based on the snippet: <|code_start|> class CharField(BaseField): def __init__(self, length=None, *args, **kwargs): self.length = length <|code_end|> , predict the immediate next line with the help of imports: from .base import BaseField and context (classes, functions, sometimes code) from other files: # Path: blitzdb/fields/base.py # class BaseField(object): # # def __init__( # self, # key=None, # nullable=True, # unique=False, # default=None, # primary_key=False, # server_default=None, # indexed=False, # ): # self.key = key # self.nullable = nullable # self.indexed = indexed # self.primary_key = primary_key # self.default = default # self.server_default = server_default # self.unique = unique . Output only the next line.
super(CharField, self).__init__(*args, **kwargs)
Predict the next line after this snippet: <|code_start|> francis_coppola = Director({'name' : 'Francis Coppola'}) stanley_kubrick = Director({'name' : 'Stanley Kubrick'}) robert_de_niro = Actor({'name' : 'Robert de Niro','movies' : []}) harrison_ford = Actor({'name' : 'Harrison Ford'}) andreas_dewes = Actor({'name' : 'Andreas Dewes'}) brian_de_palma = Director({'name' : 'Brian de Palma'}) al_pacino = Actor({'name' : 'Al Pacino','movies' : [],'salary' : {'amount' : 100000000,'currency' : u'€'}}) scarface = Movie({'title' : 'Scarface','director' : brian_de_palma}) the_godfather = Movie({'title' : 'The Godfather', 'director' : francis_coppola}) space_odyssey = Movie({'title' : '2001 - A space odyssey', 'director' : stanley_kubrick}) clockwork_orange = Movie({'title' : 'A Clockwork Orange', 'director' : stanley_kubrick}) robert_de_niro.movies.append(the_godfather) al_pacino.movies.append(the_godfather) al_pacino.movies.append(scarface) apocalypse_now = Movie({'title' : 'Apocalypse Now'}) star_wars_v = Movie({'title' : 'Star Wars V: The Empire Strikes Back'}) harrison_ford.movies = [star_wars_v] backend.save(robert_de_niro) <|code_end|> using the current file's imports: from ..helpers.movie_data import Actor, Director, Movie and any relevant context from other files: # Path: tests/helpers/movie_data.py # class Actor(Document): # # name = CharField(indexed = True) # gross_income_m = FloatField(indexed = True) # salary_amount = FloatField(indexed = True,key = 'salary.amount') # salary_currency = CharField(indexed = True,key = 'salary.currency') # appearances = IntegerField(indexed = True) # birth_year = IntegerField(indexed = True) # favorite_food = ManyToManyField('Food') # is_funny = BooleanField(indexed = True) # movies = ManyToManyField('Movie',backref = 'actors') # # class Director(Document): # # """ # Warning: There is a circular foreign key relationship between # Director and Movie, hence trying to save a pair of those objects # that point to each other will yield an exception for e.g. # the Postgres backend. # """ # # name = CharField(indexed = True) # favorite_actor = ForeignKeyField('Actor') # best_movie = ForeignKeyField('Movie',unique=True,backref = 'best_of_director') # # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] . Output only the next line.
backend.save(al_pacino)
Based on the snippet: <|code_start|> stanley_kubrick = Director({'name' : 'Stanley Kubrick'}) robert_de_niro = Actor({'name' : 'Robert de Niro','movies' : []}) harrison_ford = Actor({'name' : 'Harrison Ford'}) andreas_dewes = Actor({'name' : 'Andreas Dewes'}) brian_de_palma = Director({'name' : 'Brian de Palma'}) al_pacino = Actor({'name' : 'Al Pacino','movies' : [],'salary' : {'amount' : 100000000,'currency' : u'€'}}) scarface = Movie({'title' : 'Scarface','director' : brian_de_palma}) the_godfather = Movie({'title' : 'The Godfather', 'director' : francis_coppola}) space_odyssey = Movie({'title' : '2001 - A space odyssey', 'director' : stanley_kubrick}) clockwork_orange = Movie({'title' : 'A Clockwork Orange', 'director' : stanley_kubrick}) robert_de_niro.movies.append(the_godfather) al_pacino.movies.append(the_godfather) al_pacino.movies.append(scarface) apocalypse_now = Movie({'title' : 'Apocalypse Now'}) star_wars_v = Movie({'title' : 'Star Wars V: The Empire Strikes Back'}) harrison_ford.movies = [star_wars_v] backend.save(robert_de_niro) backend.save(al_pacino) backend.save(francis_coppola) <|code_end|> , predict the immediate next line with the help of imports: from ..helpers.movie_data import Actor, Director, Movie and context (classes, functions, sometimes code) from other files: # Path: tests/helpers/movie_data.py # class Actor(Document): # # name = CharField(indexed = True) # gross_income_m = FloatField(indexed = True) # salary_amount = FloatField(indexed = True,key = 'salary.amount') # salary_currency = CharField(indexed = True,key = 'salary.currency') # appearances = IntegerField(indexed = True) # birth_year = IntegerField(indexed = True) # favorite_food = ManyToManyField('Food') # is_funny = BooleanField(indexed = True) # movies = ManyToManyField('Movie',backref = 'actors') # # class Director(Document): # # """ # Warning: There is a circular foreign key relationship between # Director and Movie, hence trying to save a pair of those objects # that point to each other will yield an exception for e.g. # the Postgres backend. # """ # # name = CharField(indexed = True) # favorite_actor = ForeignKeyField('Actor') # best_movie = ForeignKeyField('Movie',unique=True,backref = 'best_of_director') # # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] . Output only the next line.
backend.save(andreas_dewes)
Next line prediction: <|code_start|> backend.init_schema() backend.create_schema() francis_coppola = Director({'name' : 'Francis Coppola'}) stanley_kubrick = Director({'name' : 'Stanley Kubrick'}) robert_de_niro = Actor({'name' : 'Robert de Niro','movies' : []}) harrison_ford = Actor({'name' : 'Harrison Ford'}) andreas_dewes = Actor({'name' : 'Andreas Dewes'}) brian_de_palma = Director({'name' : 'Brian de Palma'}) al_pacino = Actor({'name' : 'Al Pacino','movies' : [],'salary' : {'amount' : 100000000,'currency' : u'€'}}) scarface = Movie({'title' : 'Scarface','director' : brian_de_palma}) the_godfather = Movie({'title' : 'The Godfather', 'director' : francis_coppola}) space_odyssey = Movie({'title' : '2001 - A space odyssey', 'director' : stanley_kubrick}) clockwork_orange = Movie({'title' : 'A Clockwork Orange', 'director' : stanley_kubrick}) robert_de_niro.movies.append(the_godfather) al_pacino.movies.append(the_godfather) al_pacino.movies.append(scarface) apocalypse_now = Movie({'title' : 'Apocalypse Now'}) star_wars_v = Movie({'title' : 'Star Wars V: The Empire Strikes Back'}) <|code_end|> . Use current file imports: (from ..helpers.movie_data import Actor, Director, Movie) and context including class names, function names, or small code snippets from other files: # Path: tests/helpers/movie_data.py # class Actor(Document): # # name = CharField(indexed = True) # gross_income_m = FloatField(indexed = True) # salary_amount = FloatField(indexed = True,key = 'salary.amount') # salary_currency = CharField(indexed = True,key = 'salary.currency') # appearances = IntegerField(indexed = True) # birth_year = IntegerField(indexed = True) # favorite_food = ManyToManyField('Food') # is_funny = BooleanField(indexed = True) # movies = ManyToManyField('Movie',backref = 'actors') # # class Director(Document): # # """ # Warning: There is a circular foreign key relationship between # Director and Movie, hence trying to save a pair of those objects # that point to each other will yield an exception for e.g. # the Postgres backend. # """ # # name = CharField(indexed = True) # favorite_actor = ForeignKeyField('Actor') # best_movie = ForeignKeyField('Movie',unique=True,backref = 'best_of_director') # # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] . Output only the next line.
harrison_ford.movies = [star_wars_v]
Given snippet: <|code_start|>from __future__ import absolute_import def test_delete_transaction(transactional_backend, small_transactional_test_data): (movies, actors, directors) = small_transactional_test_data all_movies = transactional_backend.filter(Movie, {}) assert len(all_movies) == 20 <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from .helpers.movie_data import Movie and context: # Path: tests/helpers/movie_data.py # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] which might include code, classes, or functions. Output only the next line.
trans = transactional_backend.begin()
Given the code snippet: <|code_start|> @pytest.fixture def transactional_store(): tmpdir = tempfile.mkdtemp() yield TransactionalStore({'path': tmpdir}) subprocess.call(["rm", "-rf", tmpdir]) def test_transactional_store_save(transactional_store): store = transactional_store <|code_end|> , generate the next line using the imports in this file: import subprocess import tempfile import pytest from blitzdb.backends.file import TransactionalStore and context (functions, classes, or occasionally code) from other files: # Path: blitzdb/backends/file/store.py # class TransactionalStore(Store): # # """ # This class adds transaction support to the Store class. # """ # # def __init__(self, properties): # super(TransactionalStore, self).__init__(properties) # self._enabled = True # self.begin() # # def begin(self): # self._delete_cache = set() # self._update_cache = {} # # def commit(self): # try: # self._enabled = False # for store_key in self._delete_cache: # if super(TransactionalStore, self).has_blob(store_key): # super(TransactionalStore, self).delete_blob(store_key) # for store_key, blob in self._update_cache.items(): # super(TransactionalStore, self).store_blob(blob, store_key) # finally: # self._enabled = True # # def has_blob(self, key): # if not self._enabled: # return super(TransactionalStore, self).has_blob(key) # if key in self._delete_cache: # return False # if key in self._update_cache: # return True # return super(TransactionalStore, self).has_blob(key) # # def get_blob(self, key): # if not self._enabled: # return super(TransactionalStore, self).get_blob(key) # if key in self._update_cache: # return self._update_cache[key] # return super(TransactionalStore, self).get_blob(key) # # def store_blob(self, blob, key, *args, **kwargs): # if not self._enabled: # return super(TransactionalStore, self).store_blob(blob, key, *args, **kwargs) # if key in self._delete_cache: # self._delete_cache.remove(key) # self._update_cache[key] = copy.copy(blob) # return key # # def delete_blob(self, key, *args, **kwargs): # if not self._enabled: # return super(TransactionalStore, self).delete_blob(key, *args, **kwargs) # if not self.has_blob(key): # raise KeyError("Key %s not found!" % key) # self._delete_cache.add(key) # if key in self._update_cache: # del self._update_cache[key] # # def rollback(self): # self._delete_cache = set() # self._update_cache = {} . Output only the next line.
store.autocommit = True
Here is a snippet: <|code_start|> logger = logging.getLogger(__name__) if six.PY3: unicode = str class DoesNotExist(BaseException): def __str__(self): message = BaseException.__str__(self) return u"DoesNotExist({}): {}".format(self.__class__.__name__, message) class MultipleDocumentsReturned(BaseException): def __str__(self): message = BaseException.__str__(self) return u"MultipleDocumentsReturned({}): {}".format(self.__class__.__name__, message) <|code_end|> . Write the next line using the current file imports: import copy import logging import uuid import six from blitzdb.fields import CharField from blitzdb.fields.base import BaseField and context from other files: # Path: blitzdb/fields/char.py # class CharField(BaseField): # # def __init__(self, length=None, *args, **kwargs): # self.length = length # super(CharField, self).__init__(*args, **kwargs) # # Path: blitzdb/fields/base.py # class BaseField(object): # # def __init__( # self, # key=None, # nullable=True, # unique=False, # default=None, # primary_key=False, # server_default=None, # indexed=False, # ): # self.key = key # self.nullable = nullable # self.indexed = indexed # self.primary_key = primary_key # self.default = default # self.server_default = server_default # self.unique = unique , which may include functions, classes, or code. Output only the next line.
class MetaDocument(type):
Next line prediction: <|code_start|> assert marlon_brando in result result = backend.filter(Actor,{'movies' : {'$in' : [the_godfather,apocalypse_now]}}) assert marlon_brando in result assert al_pacino in result assert len(result) == 2 result = backend.filter(Actor,{'movies.title' : 'The Godfather'}) assert len(result) == 2 assert marlon_brando in result result = backend.filter(Actor,{'movies' : {'$elemMatch' : {'title' : 'The Godfather'}}}) assert len(result) == 2 assert marlon_brando in result assert al_pacino in result result = backend.filter(Actor,{'movies' : {'$all' : [{'$elemMatch' : {'title' : 'The Godfather'}},{'$elemMatch' : {'title' : 'Apocalypse Now'}}]}}) assert len(result) == 1 assert marlon_brando in result result = backend.filter(Actor,{'movies' : {'$all' : [the_godfather,apocalypse_now]}}) assert len(result) == 1 assert marlon_brando in result assert al_pacino not in result <|code_end|> . Use current file imports: (import pytest from ..helpers.movie_data import Actor, Director, Movie) and context including class names, function names, or small code snippets from other files: # Path: tests/helpers/movie_data.py # class Actor(Document): # # name = CharField(indexed = True) # gross_income_m = FloatField(indexed = True) # salary_amount = FloatField(indexed = True,key = 'salary.amount') # salary_currency = CharField(indexed = True,key = 'salary.currency') # appearances = IntegerField(indexed = True) # birth_year = IntegerField(indexed = True) # favorite_food = ManyToManyField('Food') # is_funny = BooleanField(indexed = True) # movies = ManyToManyField('Movie',backref = 'actors') # # class Director(Document): # # """ # Warning: There is a circular foreign key relationship between # Director and Movie, hence trying to save a pair of those objects # that point to each other will yield an exception for e.g. # the Postgres backend. # """ # # name = CharField(indexed = True) # favorite_actor = ForeignKeyField('Actor') # best_movie = ForeignKeyField('Movie',unique=True,backref = 'best_of_director') # # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] . Output only the next line.
with pytest.raises(AttributeError):
Given snippet: <|code_start|> result = backend.filter(Actor,{'movies' : [the_godfather,apocalypse_now]}) result = backend.filter(Actor,{'movies.title' : 'The Godfather'}) assert len(result) == 2 assert marlon_brando in result assert al_pacino in result result = backend.filter(Actor,{'movies' : {'$in' : [the_godfather,apocalypse_now]}}) assert len(result) == 2 assert marlon_brando in result assert al_pacino in result result = backend.filter(Actor,{'movies.title' : 'The Godfather'}) assert len(result) == 2 assert marlon_brando in result assert al_pacino in result result = backend.filter(Actor,{'movies.director.name' : {'$in' : ['Francis Coppola']}}) assert len(result) == 2 assert marlon_brando in result assert al_pacino in result result = backend.filter(Actor,{'movies.director.favorite_actor.name' : {'$in' : ['Al Pacino']}}) assert len(result) == 2 <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from ..helpers.movie_data import Actor, Director, Movie and context: # Path: tests/helpers/movie_data.py # class Actor(Document): # # name = CharField(indexed = True) # gross_income_m = FloatField(indexed = True) # salary_amount = FloatField(indexed = True,key = 'salary.amount') # salary_currency = CharField(indexed = True,key = 'salary.currency') # appearances = IntegerField(indexed = True) # birth_year = IntegerField(indexed = True) # favorite_food = ManyToManyField('Food') # is_funny = BooleanField(indexed = True) # movies = ManyToManyField('Movie',backref = 'actors') # # class Director(Document): # # """ # Warning: There is a circular foreign key relationship between # Director and Movie, hence trying to save a pair of those objects # that point to each other will yield an exception for e.g. # the Postgres backend. # """ # # name = CharField(indexed = True) # favorite_actor = ForeignKeyField('Actor') # best_movie = ForeignKeyField('Movie',unique=True,backref = 'best_of_director') # # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] which might include code, classes, or functions. Output only the next line.
assert marlon_brando in result
Here is a snippet: <|code_start|> assert len(result) == 1 assert marlon_brando in result result = backend.filter(Actor,{'movies' : {'$in' : [the_godfather,apocalypse_now]}}) assert marlon_brando in result assert al_pacino in result assert len(result) == 2 result = backend.filter(Actor,{'movies.title' : 'The Godfather'}) assert len(result) == 2 assert marlon_brando in result result = backend.filter(Actor,{'movies' : {'$elemMatch' : {'title' : 'The Godfather'}}}) assert len(result) == 2 assert marlon_brando in result assert al_pacino in result result = backend.filter(Actor,{'movies' : {'$all' : [{'$elemMatch' : {'title' : 'The Godfather'}},{'$elemMatch' : {'title' : 'Apocalypse Now'}}]}}) assert len(result) == 1 assert marlon_brando in result result = backend.filter(Actor,{'movies' : {'$all' : [the_godfather,apocalypse_now]}}) assert len(result) == 1 assert marlon_brando in result <|code_end|> . Write the next line using the current file imports: import pytest from ..helpers.movie_data import Actor, Director, Movie and context from other files: # Path: tests/helpers/movie_data.py # class Actor(Document): # # name = CharField(indexed = True) # gross_income_m = FloatField(indexed = True) # salary_amount = FloatField(indexed = True,key = 'salary.amount') # salary_currency = CharField(indexed = True,key = 'salary.currency') # appearances = IntegerField(indexed = True) # birth_year = IntegerField(indexed = True) # favorite_food = ManyToManyField('Food') # is_funny = BooleanField(indexed = True) # movies = ManyToManyField('Movie',backref = 'actors') # # class Director(Document): # # """ # Warning: There is a circular foreign key relationship between # Director and Movie, hence trying to save a pair of those objects # that point to each other will yield an exception for e.g. # the Postgres backend. # """ # # name = CharField(indexed = True) # favorite_actor = ForeignKeyField('Actor') # best_movie = ForeignKeyField('Movie',unique=True,backref = 'best_of_director') # # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] , which may include functions, classes, or code. Output only the next line.
assert al_pacino not in result
Predict the next line after this snippet: <|code_start|> @pytest.fixture def backend(request): engine = get_sql_engine() backend = _sql_backend(request, engine) backend.register(Actor) backend.register(Director) backend.register(Movie) backend.register(Food) backend.init_schema() backend.create_schema() return backend @pytest.fixture def empty_backend(request): engine = get_sql_engine() backend = _sql_backend(request, engine) <|code_end|> using the current file's imports: import pytest from ..conftest import _sql_backend, get_sql_engine from ..helpers.movie_data import Actor, Director, Food, Movie and any relevant context from other files: # Path: tests/conftest.py # def _sql_backend(request, engine, **kwargs): # # meta = MetaData(engine) # meta.reflect() # meta.drop_all() # # we enable foreign key checks for SQLITE # if str(engine.url).startswith('sqlite://'): # engine.connect().execute('pragma foreign_keys=ON') # # if not 'ondelete' in kwargs: # kwargs['ondelete'] = 'CASCADE' # backend = SqlBackend(engine=engine, **kwargs) # backend.init_schema() # backend.create_schema() # # def finalizer(): # backend.rollback() # del backend.connection # print("Dropping schema...") # # we disable foreign key checks for SQLITE (as dropping tables with circular foreign keys won't work otherwise...) # if str(engine.url).startswith('sqlite://'): # engine.connect().execute('pragma foreign_keys=OFF') # meta = MetaData(engine) # meta.reflect() # meta.drop_all() # print("Done...") # # request.addfinalizer(finalizer) # # return backend # # def get_sql_engine(): # url = os.environ.get('BLITZDB_SQLALCHEMY_URL', memory_url) # engine = create_engine(url, echo=False) # # we make sure foreign keys are enforced... # return engine # # Path: tests/helpers/movie_data.py # class Actor(Document): # # name = CharField(indexed = True) # gross_income_m = FloatField(indexed = True) # salary_amount = FloatField(indexed = True,key = 'salary.amount') # salary_currency = CharField(indexed = True,key = 'salary.currency') # appearances = IntegerField(indexed = True) # birth_year = IntegerField(indexed = True) # favorite_food = ManyToManyField('Food') # is_funny = BooleanField(indexed = True) # movies = ManyToManyField('Movie',backref = 'actors') # # class Director(Document): # # """ # Warning: There is a circular foreign key relationship between # Director and Movie, hence trying to save a pair of those objects # that point to each other will yield an exception for e.g. # the Postgres backend. # """ # # name = CharField(indexed = True) # favorite_actor = ForeignKeyField('Actor') # best_movie = ForeignKeyField('Movie',unique=True,backref = 'best_of_director') # # class Food(Document): # # name = CharField(indexed = True) # # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] . Output only the next line.
return backend
Here is a snippet: <|code_start|> @pytest.fixture def backend(request): engine = get_sql_engine() backend = _sql_backend(request, engine) backend.register(Actor) backend.register(Director) backend.register(Movie) backend.register(Food) backend.init_schema() backend.create_schema() return backend <|code_end|> . Write the next line using the current file imports: import pytest from ..conftest import _sql_backend, get_sql_engine from ..helpers.movie_data import Actor, Director, Food, Movie and context from other files: # Path: tests/conftest.py # def _sql_backend(request, engine, **kwargs): # # meta = MetaData(engine) # meta.reflect() # meta.drop_all() # # we enable foreign key checks for SQLITE # if str(engine.url).startswith('sqlite://'): # engine.connect().execute('pragma foreign_keys=ON') # # if not 'ondelete' in kwargs: # kwargs['ondelete'] = 'CASCADE' # backend = SqlBackend(engine=engine, **kwargs) # backend.init_schema() # backend.create_schema() # # def finalizer(): # backend.rollback() # del backend.connection # print("Dropping schema...") # # we disable foreign key checks for SQLITE (as dropping tables with circular foreign keys won't work otherwise...) # if str(engine.url).startswith('sqlite://'): # engine.connect().execute('pragma foreign_keys=OFF') # meta = MetaData(engine) # meta.reflect() # meta.drop_all() # print("Done...") # # request.addfinalizer(finalizer) # # return backend # # def get_sql_engine(): # url = os.environ.get('BLITZDB_SQLALCHEMY_URL', memory_url) # engine = create_engine(url, echo=False) # # we make sure foreign keys are enforced... # return engine # # Path: tests/helpers/movie_data.py # class Actor(Document): # # name = CharField(indexed = True) # gross_income_m = FloatField(indexed = True) # salary_amount = FloatField(indexed = True,key = 'salary.amount') # salary_currency = CharField(indexed = True,key = 'salary.currency') # appearances = IntegerField(indexed = True) # birth_year = IntegerField(indexed = True) # favorite_food = ManyToManyField('Food') # is_funny = BooleanField(indexed = True) # movies = ManyToManyField('Movie',backref = 'actors') # # class Director(Document): # # """ # Warning: There is a circular foreign key relationship between # Director and Movie, hence trying to save a pair of those objects # that point to each other will yield an exception for e.g. # the Postgres backend. # """ # # name = CharField(indexed = True) # favorite_actor = ForeignKeyField('Actor') # best_movie = ForeignKeyField('Movie',unique=True,backref = 'best_of_director') # # class Food(Document): # # name = CharField(indexed = True) # # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] , which may include functions, classes, or code. Output only the next line.
@pytest.fixture
Given snippet: <|code_start|> @pytest.fixture def backend(request): engine = get_sql_engine() backend = _sql_backend(request, engine) backend.register(Actor) backend.register(Director) backend.register(Movie) backend.register(Food) backend.init_schema() backend.create_schema() return backend <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from ..conftest import _sql_backend, get_sql_engine from ..helpers.movie_data import Actor, Director, Food, Movie and context: # Path: tests/conftest.py # def _sql_backend(request, engine, **kwargs): # # meta = MetaData(engine) # meta.reflect() # meta.drop_all() # # we enable foreign key checks for SQLITE # if str(engine.url).startswith('sqlite://'): # engine.connect().execute('pragma foreign_keys=ON') # # if not 'ondelete' in kwargs: # kwargs['ondelete'] = 'CASCADE' # backend = SqlBackend(engine=engine, **kwargs) # backend.init_schema() # backend.create_schema() # # def finalizer(): # backend.rollback() # del backend.connection # print("Dropping schema...") # # we disable foreign key checks for SQLITE (as dropping tables with circular foreign keys won't work otherwise...) # if str(engine.url).startswith('sqlite://'): # engine.connect().execute('pragma foreign_keys=OFF') # meta = MetaData(engine) # meta.reflect() # meta.drop_all() # print("Done...") # # request.addfinalizer(finalizer) # # return backend # # def get_sql_engine(): # url = os.environ.get('BLITZDB_SQLALCHEMY_URL', memory_url) # engine = create_engine(url, echo=False) # # we make sure foreign keys are enforced... # return engine # # Path: tests/helpers/movie_data.py # class Actor(Document): # # name = CharField(indexed = True) # gross_income_m = FloatField(indexed = True) # salary_amount = FloatField(indexed = True,key = 'salary.amount') # salary_currency = CharField(indexed = True,key = 'salary.currency') # appearances = IntegerField(indexed = True) # birth_year = IntegerField(indexed = True) # favorite_food = ManyToManyField('Food') # is_funny = BooleanField(indexed = True) # movies = ManyToManyField('Movie',backref = 'actors') # # class Director(Document): # # """ # Warning: There is a circular foreign key relationship between # Director and Movie, hence trying to save a pair of those objects # that point to each other will yield an exception for e.g. # the Postgres backend. # """ # # name = CharField(indexed = True) # favorite_actor = ForeignKeyField('Actor') # best_movie = ForeignKeyField('Movie',unique=True,backref = 'best_of_director') # # class Food(Document): # # name = CharField(indexed = True) # # class Movie(Document): # # title = CharField(nullable = True,indexed = True) # director = ForeignKeyField(related = 'Director',nullable = True,backref = 'movies') # cast = ManyToManyField(related = 'Actor') # year = IntegerField(indexed = True) # best_actor = ForeignKeyField('Actor',backref = 'best_movies') # # class Meta(Document.Meta): # # dbref_includes = ['title','year'] which might include code, classes, or functions. Output only the next line.
@pytest.fixture