Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|>#
# This tool helps you rebase your package to the latest version
# Copyright (C) 2013-2019 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
class TestResultsStore:
old_rpm_data: Dict[str, Union[str, List[str]]] = {
'rpm': ['rpm-0.1.0.x86_64.rpm', ' rpm-devel-0.1.0.x86_64.rpm'],
<|code_end|>
. Use current file imports:
(import pytest # type: ignore
from typing import Dict, List, Union
from rebasehelper.results_store import ResultsStore)
and context including class names, function names, or small code snippets from other files:
# Path: rebasehelper/results_store.py
# class ResultsStore:
# """Class for storing information about results from rebase-helper actions."""
#
# RESULTS_INFORMATION: str = 'information'
# RESULTS_CHECKERS: str = 'checkers'
# RESULTS_BUILD_LOG_HOOKS: str = 'build_log_hooks'
# RESULTS_BUILDS: str = 'builds'
# RESULTS_PATCHES: str = 'patches'
# RESULTS_CHANGES_PATCH: str = 'changes_patch'
# RESULTS_SUCCESS: str = 'result'
#
# def __init__(self):
# self._data_store: Dict[str, Any] = dict()
#
# def clear(self):
# self._data_store.clear()
#
# def set_results(self, results_type, data_dict):
# if results_type not in (
# self.RESULTS_INFORMATION,
# self.RESULTS_CHECKERS,
# self.RESULTS_BUILD_LOG_HOOKS,
# self.RESULTS_BUILDS,
# self.RESULTS_PATCHES,
# self.RESULTS_CHANGES_PATCH,
# self.RESULTS_SUCCESS
# ):
# raise ValueError('Trying to set unsupported type of results: {}!'.format(results_type))
#
# try:
# dict_to_update = self._data_store[results_type]
# except KeyError:
# dict_to_update = dict()
# self._data_store[results_type] = dict_to_update
# dict_to_update.update(data_dict)
#
# def set_info_text(self, text, data):
# self.set_results(self.RESULTS_INFORMATION, {text: data})
#
# def set_patches_results(self, results_dict):
# self.set_results(self.RESULTS_PATCHES, results_dict)
#
# def set_checker_output(self, text, data):
# self.set_results(self.RESULTS_CHECKERS, {text: data})
#
# def set_build_log_hooks_result(self, text, data):
# self.set_results(self.RESULTS_BUILD_LOG_HOOKS, {text: data})
#
# def set_build_data(self, version, data):
# self.set_results(self.RESULTS_BUILDS, {version: data})
#
# def set_changes_patch(self, text, data):
# self.set_results(self.RESULTS_CHANGES_PATCH, {text: data})
#
# def set_result_message(self, text, data):
# self.set_results(self.RESULTS_SUCCESS, {text: data})
#
# def get_all(self):
# return copy.deepcopy(self._data_store)
#
# def get_build(self, version):
# builds_results = self._data_store.get(self.RESULTS_BUILDS, None)
# if builds_results is not None:
# return builds_results.get(version, None)
# else:
# return None
#
# def get_old_build(self):
# return self.get_build('old')
#
# def get_new_build(self):
# return self.get_build('new')
#
# def get_patches(self):
# return self._data_store.get(self.RESULTS_PATCHES, None)
#
# def get_checkers(self):
# return self._data_store.get(self.RESULTS_CHECKERS, {})
#
# def get_build_log_hooks(self):
# return self._data_store.get(self.RESULTS_BUILD_LOG_HOOKS, {})
#
# def get_summary_info(self):
# return self._data_store.get(self.RESULTS_INFORMATION, None)
#
# def get_changes_patch(self):
# return self._data_store.get(self.RESULTS_CHANGES_PATCH, None)
#
# def get_result_message(self):
# return self._data_store.get(self.RESULTS_SUCCESS, None)
. Output only the next line. | 'srpm': 'rpm-0.1.0.src.rpm', |
Continue the code snippet: <|code_start|> ]]
@pytest.fixture
def extracted_archive(self, archive, workdir):
a = Archive(archive)
d = os.path.join(workdir, 'dir')
a.extract_archive(d)
if archive == self.GEM:
# append top level dir
d = os.path.join(d, 'archive')
return d
@pytest.mark.parametrize('archive', [
TAR_GZ,
TGZ,
TAR_XZ,
TAR_BZ2,
BZ2,
ZIP,
CRATE,
GEM,
], ids=[
'tar.gz',
'tgz',
'tar.xz',
'tar.bz2',
'bz2',
'zip',
'crate',
'gem',
<|code_end|>
. Use current file imports:
import os
import pytest # type: ignore
from typing import List
from rebasehelper.archive import Archive
from rebasehelper.constants import ENCODING
and context (classes, functions, or code) from other files:
# Path: rebasehelper/archive.py
# class Archive:
# """Class representing an archive with sources"""
#
# def __init__(self, filename):
# self._filename = filename
# self._archive_type = None
#
# for archive_type in archive_types.values():
# if archive_type.match(self._filename):
# self._archive_type = archive_type
#
# if self._archive_type is None:
# raise NotImplementedError('Unsupported archive type')
#
# def extract_archive(self, path):
# """
# Extracts the archive into the given path
#
# :param path: Path where to extract the archive to.
# """
# logger.verbose('Extracting %s to %s', self._filename, path)
#
# try:
# archive = self._archive_type.open(self._filename)
# except (EOFError, tarfile.ReadError, lzma.LZMAError) as e:
# raise IOError(str(e)) from e
#
# try:
# self._archive_type.extract(archive, self._filename, path)
# finally:
# archive.close()
#
# @classmethod
# def get_supported_archives(cls):
# return archive_types.keys()
#
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | ]) |
Based on the snippet: <|code_start|> TAR_BZ2,
BZ2,
ZIP,
CRATE,
GEM,
], ids=[
'tar.gz',
'tgz',
'tar.xz',
'tar.bz2',
'bz2',
'zip',
'crate',
'gem',
])
def test_archive(self, extracted_archive):
extracted_file = os.path.join(extracted_archive, self.ARCHIVED_FILE)
# check if the dir was created
assert os.path.isdir(extracted_archive)
# check if the file was extracted
assert os.path.isfile(extracted_file)
# check the content
with open(extracted_file, encoding=ENCODING) as f:
assert f.read().strip() == self.ARCHIVED_FILE_CONTENT
@pytest.mark.parametrize('archive', [
INVALID_TAR_BZ2,
INVALID_TAR_XZ,
], ids=[
'tar.bz2',
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import pytest # type: ignore
from typing import List
from rebasehelper.archive import Archive
from rebasehelper.constants import ENCODING
and context (classes, functions, sometimes code) from other files:
# Path: rebasehelper/archive.py
# class Archive:
# """Class representing an archive with sources"""
#
# def __init__(self, filename):
# self._filename = filename
# self._archive_type = None
#
# for archive_type in archive_types.values():
# if archive_type.match(self._filename):
# self._archive_type = archive_type
#
# if self._archive_type is None:
# raise NotImplementedError('Unsupported archive type')
#
# def extract_archive(self, path):
# """
# Extracts the archive into the given path
#
# :param path: Path where to extract the archive to.
# """
# logger.verbose('Extracting %s to %s', self._filename, path)
#
# try:
# archive = self._archive_type.open(self._filename)
# except (EOFError, tarfile.ReadError, lzma.LZMAError) as e:
# raise IOError(str(e)) from e
#
# try:
# self._archive_type.extract(archive, self._filename, path)
# finally:
# archive.close()
#
# @classmethod
# def get_supported_archives(cls):
# return archive_types.keys()
#
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | 'tar.xz', |
Predict the next line for this snippet: <|code_start|>#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
class TestGitHelper:
def write_config_file(self, config_file, name, email):
with open(config_file, 'w', encoding=ENCODING) as f:
f.write('[user]\n'
' name = {0}\n'
' email = {1}\n'.format(name, email))
@pytest.mark.parametrize('config', [
# Get from $XDG_CONFIG_HOME/git/config
'global',
# Get from included file in $XDG_CONFIG_HOME/git/config
'global_include',
# Get from $repo_path/.git/config
'local',
# Get from GIT_CONFIG
<|code_end|>
with the help of current file imports:
import os
import git # type: ignore
import pytest # type: ignore
from rebasehelper.constants import ENCODING
from rebasehelper.helpers.git_helper import GitHelper
and context from other files:
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
#
# Path: rebasehelper/helpers/git_helper.py
# class GitHelper:
#
# """Class which operates with git repositories"""
#
# # provide fallback values if system is not configured
# GIT_USER_NAME: str = 'rebase-helper'
# GIT_USER_EMAIL: str = 'rebase-helper@localhost.local'
#
# @classmethod
# def get_user(cls):
# try:
# return git.cmd.Git().config('user.name', get=True, stdout_as_string=True)
# except git.GitCommandError:
# logger.warning("Failed to get configured git user name, using '%s'", cls.GIT_USER_NAME)
# return cls.GIT_USER_NAME
#
# @classmethod
# def get_email(cls):
# try:
# return git.cmd.Git().config('user.email', get=True, stdout_as_string=True)
# except git.GitCommandError:
# logger.warning("Failed to get configured git user email, using '%s'", cls.GIT_USER_EMAIL)
# return cls.GIT_USER_EMAIL
#
# @classmethod
# def run_mergetool(cls, repo):
# # we can't use GitPython here, as it doesn't allow
# # for the command to attach to stdout directly
# cwd = os.getcwd()
# try:
# os.chdir(repo.working_tree_dir)
# ProcessHelper.run_subprocess(['git', 'mergetool'])
# finally:
# os.chdir(cwd)
, which may contain function names, class names, or code. Output only the next line. | 'env', |
Given snippet: <|code_start|># František Nečas <fifinecas@seznam.cz>
class TestGitHelper:
def write_config_file(self, config_file, name, email):
with open(config_file, 'w', encoding=ENCODING) as f:
f.write('[user]\n'
' name = {0}\n'
' email = {1}\n'.format(name, email))
@pytest.mark.parametrize('config', [
# Get from $XDG_CONFIG_HOME/git/config
'global',
# Get from included file in $XDG_CONFIG_HOME/git/config
'global_include',
# Get from $repo_path/.git/config
'local',
# Get from GIT_CONFIG
'env',
])
def test_get_user_and_email(self, config, workdir):
name = 'Foo Bar'
email = 'foo@bar.com'
env = os.environ.copy()
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import git # type: ignore
import pytest # type: ignore
from rebasehelper.constants import ENCODING
from rebasehelper.helpers.git_helper import GitHelper
and context:
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
#
# Path: rebasehelper/helpers/git_helper.py
# class GitHelper:
#
# """Class which operates with git repositories"""
#
# # provide fallback values if system is not configured
# GIT_USER_NAME: str = 'rebase-helper'
# GIT_USER_EMAIL: str = 'rebase-helper@localhost.local'
#
# @classmethod
# def get_user(cls):
# try:
# return git.cmd.Git().config('user.name', get=True, stdout_as_string=True)
# except git.GitCommandError:
# logger.warning("Failed to get configured git user name, using '%s'", cls.GIT_USER_NAME)
# return cls.GIT_USER_NAME
#
# @classmethod
# def get_email(cls):
# try:
# return git.cmd.Git().config('user.email', get=True, stdout_as_string=True)
# except git.GitCommandError:
# logger.warning("Failed to get configured git user email, using '%s'", cls.GIT_USER_EMAIL)
# return cls.GIT_USER_EMAIL
#
# @classmethod
# def run_mergetool(cls, repo):
# # we can't use GitPython here, as it doesn't allow
# # for the command to attach to stdout directly
# cwd = os.getcwd()
# try:
# os.chdir(repo.working_tree_dir)
# ProcessHelper.run_subprocess(['git', 'mergetool'])
# finally:
# os.chdir(cwd)
which might include code, classes, or functions. Output only the next line. | if config == 'global': |
Continue the code snippet: <|code_start|> CONFIG_FILE: str = 'test_config.cfg'
@pytest.fixture
def config_file(self, config_args):
config = configparser.ConfigParser()
config.add_section('Section1')
for key, value in config_args.items():
config.set('Section1', key, value)
with open(self.CONFIG_FILE, 'w', encoding=ENCODING) as configfile:
config.write(configfile)
return os.path.abspath(self.CONFIG_FILE)
@pytest.mark.parametrize('config_args', [
{
'changelog-entry': 'Updated to',
'versioneer': 'pypi',
},
{},
], ids=[
'configured',
'empty',
])
def test_get_config(self, config_args, config_file):
config = Config(config_file)
expected_result = {k.replace('-', '_'): v for k, v in config_args.items()}
assert expected_result == config.config
@pytest.mark.parametrize('cli_args, config_args, merged', [
(
<|code_end|>
. Use current file imports:
import configparser
import os
import pytest # type: ignore
from rebasehelper.cli import CLI
from rebasehelper.config import Config
from rebasehelper.constants import ENCODING
and context (classes, functions, or code) from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/config.py
# class Config:
#
# def __init__(self, config_file=None):
# self.path_to_config = self.get_config_path(config_file)
# self.config = self.get_config()
#
# def __getattr__(self, name):
# return self.config.get(name)
#
# @staticmethod
# def get_config_path(config_file):
# # ensure XDG_CONFIG_HOME is set
# if 'XDG_CONFIG_HOME' not in os.environ:
# os.environ['XDG_CONFIG_HOME'] = os.path.expandvars(os.path.join('$HOME', '.config'))
# path = os.path.expandvars(config_file or os.path.join(CONFIG_PATH, CONFIG_FILENAME))
# return os.path.abspath(path)
#
# def get_config(self):
# conf = {}
# if os.path.isfile(self.path_to_config):
# config = configparser.ConfigParser()
# config.read(self.path_to_config)
# for section in config.sections():
# conf.update({k.replace('-', '_'): v for k, v in config.items(section)})
#
# return conf
#
# def merge(self, cli):
# self.config.update(vars(cli.args))
#
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# if 'dest' in option:
# dest = option['dest']
# else:
# args = [n.lstrip('-').replace('-', '_') for n in option['name'] if n.startswith('--')]
# if args:
# dest = args[0]
#
# if dest and dest not in self.config:
# self.config[dest] = option.get('default')
#
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | [ |
Continue the code snippet: <|code_start|># František Nečas <fifinecas@seznam.cz>
class TestConfig:
CONFIG_FILE: str = 'test_config.cfg'
@pytest.fixture
def config_file(self, config_args):
config = configparser.ConfigParser()
config.add_section('Section1')
for key, value in config_args.items():
config.set('Section1', key, value)
with open(self.CONFIG_FILE, 'w', encoding=ENCODING) as configfile:
config.write(configfile)
return os.path.abspath(self.CONFIG_FILE)
@pytest.mark.parametrize('config_args', [
{
'changelog-entry': 'Updated to',
'versioneer': 'pypi',
},
{},
], ids=[
'configured',
'empty',
])
<|code_end|>
. Use current file imports:
import configparser
import os
import pytest # type: ignore
from rebasehelper.cli import CLI
from rebasehelper.config import Config
from rebasehelper.constants import ENCODING
and context (classes, functions, or code) from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/config.py
# class Config:
#
# def __init__(self, config_file=None):
# self.path_to_config = self.get_config_path(config_file)
# self.config = self.get_config()
#
# def __getattr__(self, name):
# return self.config.get(name)
#
# @staticmethod
# def get_config_path(config_file):
# # ensure XDG_CONFIG_HOME is set
# if 'XDG_CONFIG_HOME' not in os.environ:
# os.environ['XDG_CONFIG_HOME'] = os.path.expandvars(os.path.join('$HOME', '.config'))
# path = os.path.expandvars(config_file or os.path.join(CONFIG_PATH, CONFIG_FILENAME))
# return os.path.abspath(path)
#
# def get_config(self):
# conf = {}
# if os.path.isfile(self.path_to_config):
# config = configparser.ConfigParser()
# config.read(self.path_to_config)
# for section in config.sections():
# conf.update({k.replace('-', '_'): v for k, v in config.items(section)})
#
# return conf
#
# def merge(self, cli):
# self.config.update(vars(cli.args))
#
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# if 'dest' in option:
# dest = option['dest']
# else:
# args = [n.lstrip('-').replace('-', '_') for n in option['name'] if n.startswith('--')]
# if args:
# dest = args[0]
#
# if dest and dest not in self.config:
# self.config[dest] = option.get('default')
#
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | def test_get_config(self, config_args, config_file): |
Given the code snippet: <|code_start|># Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
class TestConfig:
CONFIG_FILE: str = 'test_config.cfg'
@pytest.fixture
def config_file(self, config_args):
config = configparser.ConfigParser()
config.add_section('Section1')
for key, value in config_args.items():
config.set('Section1', key, value)
with open(self.CONFIG_FILE, 'w', encoding=ENCODING) as configfile:
config.write(configfile)
return os.path.abspath(self.CONFIG_FILE)
@pytest.mark.parametrize('config_args', [
{
'changelog-entry': 'Updated to',
'versioneer': 'pypi',
},
{},
], ids=[
'configured',
<|code_end|>
, generate the next line using the imports in this file:
import configparser
import os
import pytest # type: ignore
from rebasehelper.cli import CLI
from rebasehelper.config import Config
from rebasehelper.constants import ENCODING
and context (functions, classes, or occasionally code) from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/config.py
# class Config:
#
# def __init__(self, config_file=None):
# self.path_to_config = self.get_config_path(config_file)
# self.config = self.get_config()
#
# def __getattr__(self, name):
# return self.config.get(name)
#
# @staticmethod
# def get_config_path(config_file):
# # ensure XDG_CONFIG_HOME is set
# if 'XDG_CONFIG_HOME' not in os.environ:
# os.environ['XDG_CONFIG_HOME'] = os.path.expandvars(os.path.join('$HOME', '.config'))
# path = os.path.expandvars(config_file or os.path.join(CONFIG_PATH, CONFIG_FILENAME))
# return os.path.abspath(path)
#
# def get_config(self):
# conf = {}
# if os.path.isfile(self.path_to_config):
# config = configparser.ConfigParser()
# config.read(self.path_to_config)
# for section in config.sections():
# conf.update({k.replace('-', '_'): v for k, v in config.items(section)})
#
# return conf
#
# def merge(self, cli):
# self.config.update(vars(cli.args))
#
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# if 'dest' in option:
# dest = option['dest']
# else:
# args = [n.lstrip('-').replace('-', '_') for n in option['name'] if n.startswith('--')]
# if args:
# dest = args[0]
#
# if dest and dest not in self.config:
# self.config[dest] = option.get('default')
#
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | 'empty', |
Using the snippet: <|code_start|># the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
if TYPE_CHECKING:
# avoid cyclic import at runtime
class PluginCollection:
def __init__(self, entrypoint: str, manager: 'PluginManager'):
self.plugins: Dict[str, Optional[Type[Plugin]]] = PluginLoader.load(entrypoint, manager)
def get_all_plugins(self) -> List[str]:
return list(self.plugins)
<|code_end|>
, determine the next line of code. You have imports:
from typing import Dict, List, Optional, Type, Union, TYPE_CHECKING
from rebasehelper.plugins.plugin_loader import PluginLoader
from rebasehelper.plugins.plugin import Plugin
from rebasehelper.types import Options
from rebasehelper.plugins.plugin_manager import PluginManager
and context (class names, function names, or code) available:
# Path: rebasehelper/plugins/plugin_loader.py
# class PluginLoader:
# @classmethod
# def load(cls, entrypoint, manager):
# result: Dict[str, Optional[Type[Plugin]]] = {}
# for ep in pkg_resources.iter_entry_points(entrypoint):
# result[ep.name] = None
# try:
# plugin = ep.load()
# except BaseException:
# # skip broken plugin
# continue
# try:
# if not issubclass(plugin, Plugin):
# raise TypeError
# except TypeError:
# # skip broken plugin
# continue
# else:
# plugin.name = ep.name
# # Some plugins require access to other plugins. Avoid cyclic
# # imports by setting manager as an attribute.
# plugin.manager = manager
# result[ep.name] = plugin
# return result
#
# Path: rebasehelper/plugins/plugin.py
# class Plugin:
# name: Optional[str] = None
# manager: Optional['PluginManager'] = None
#
# OPTIONS: Options = []
#
# Path: rebasehelper/types.py
. Output only the next line. | def get_supported_plugins(self) -> List[str]: |
Given the following code snippet before the placeholder: <|code_start|># This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
if TYPE_CHECKING:
# avoid cyclic import at runtime
class PluginCollection:
def __init__(self, entrypoint: str, manager: 'PluginManager'):
self.plugins: Dict[str, Optional[Type[Plugin]]] = PluginLoader.load(entrypoint, manager)
def get_all_plugins(self) -> List[str]:
<|code_end|>
, predict the next line using imports from the current file:
from typing import Dict, List, Optional, Type, Union, TYPE_CHECKING
from rebasehelper.plugins.plugin_loader import PluginLoader
from rebasehelper.plugins.plugin import Plugin
from rebasehelper.types import Options
from rebasehelper.plugins.plugin_manager import PluginManager
and context including class names, function names, and sometimes code from other files:
# Path: rebasehelper/plugins/plugin_loader.py
# class PluginLoader:
# @classmethod
# def load(cls, entrypoint, manager):
# result: Dict[str, Optional[Type[Plugin]]] = {}
# for ep in pkg_resources.iter_entry_points(entrypoint):
# result[ep.name] = None
# try:
# plugin = ep.load()
# except BaseException:
# # skip broken plugin
# continue
# try:
# if not issubclass(plugin, Plugin):
# raise TypeError
# except TypeError:
# # skip broken plugin
# continue
# else:
# plugin.name = ep.name
# # Some plugins require access to other plugins. Avoid cyclic
# # imports by setting manager as an attribute.
# plugin.manager = manager
# result[ep.name] = plugin
# return result
#
# Path: rebasehelper/plugins/plugin.py
# class Plugin:
# name: Optional[str] = None
# manager: Optional['PluginManager'] = None
#
# OPTIONS: Options = []
#
# Path: rebasehelper/types.py
. Output only the next line. | return list(self.plugins) |
Given snippet: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
class PluginLoader:
@classmethod
def load(cls, entrypoint, manager):
result: Dict[str, Optional[Type[Plugin]]] = {}
for ep in pkg_resources.iter_entry_points(entrypoint):
result[ep.name] = None
try:
plugin = ep.load()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from typing import Dict, Optional, Type
from rebasehelper.plugins.plugin import Plugin
import pkg_resources
and context:
# Path: rebasehelper/plugins/plugin.py
# class Plugin:
# name: Optional[str] = None
# manager: Optional['PluginManager'] = None
#
# OPTIONS: Options = []
which might include code, classes, or functions. Output only the next line. | except BaseException: |
Next line prediction: <|code_start|> return None
return usage[idx + len(option_string)]
parser = CLI.build_parser()
result = []
actions = parser._get_optional_actions() + parser._get_positional_actions() # pylint: disable=protected-access
for action in actions:
if not action.option_strings:
continue
delimiter = get_delimiter(parser, action) or ''
result.append(dict(
options=[o + delimiter.strip() for o in action.option_strings],
choices=action.choices or []))
return result
@classmethod
def dump(cls):
options = cls.options()
return {
# pattern list of extensions
'RH_EXTENSIONS': '@({})'.format('|'.join(cls.extensions())),
# array of options
'RH_OPTIONS': '({})'.format(' '.join('"{}"'.format(' '.join(o['options'])) for o in options)),
# array of choices of respective options
'RH_CHOICES': '({})'.format(' '.join('"{}"'.format(' '.join(o['choices'])) for o in options)),
}
def replace_placeholders(s, **kwargs):
placeholder_re = re.compile(r'@(\w+)@')
matches = list(placeholder_re.finditer(s))
<|code_end|>
. Use current file imports:
(import re
import sys
from rebasehelper.cli import CLI
from rebasehelper.constants import ENCODING
from rebasehelper.archive import Archive)
and context including class names, function names, or small code snippets from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
#
# Path: rebasehelper/archive.py
# class Archive:
# """Class representing an archive with sources"""
#
# def __init__(self, filename):
# self._filename = filename
# self._archive_type = None
#
# for archive_type in archive_types.values():
# if archive_type.match(self._filename):
# self._archive_type = archive_type
#
# if self._archive_type is None:
# raise NotImplementedError('Unsupported archive type')
#
# def extract_archive(self, path):
# """
# Extracts the archive into the given path
#
# :param path: Path where to extract the archive to.
# """
# logger.verbose('Extracting %s to %s', self._filename, path)
#
# try:
# archive = self._archive_type.open(self._filename)
# except (EOFError, tarfile.ReadError, lzma.LZMAError) as e:
# raise IOError(str(e)) from e
#
# try:
# self._archive_type.extract(archive, self._filename, path)
# finally:
# archive.close()
#
# @classmethod
# def get_supported_archives(cls):
# return archive_types.keys()
. Output only the next line. | result = s |
Predict the next line after this snippet: <|code_start|> return None
fmt = parser._get_formatter() # pylint: disable=protected-access
usage = fmt._format_actions_usage([action], []) # pylint: disable=protected-access
option_string = action.option_strings[0]
idx = usage.find(option_string)
if idx == -1:
return None
return usage[idx + len(option_string)]
parser = CLI.build_parser()
result = []
actions = parser._get_optional_actions() + parser._get_positional_actions() # pylint: disable=protected-access
for action in actions:
if not action.option_strings:
continue
delimiter = get_delimiter(parser, action) or ''
result.append(dict(
options=[o + delimiter.strip() for o in action.option_strings],
choices=action.choices or []))
return result
@classmethod
def dump(cls):
options = cls.options()
return {
# pattern list of extensions
'RH_EXTENSIONS': '@({})'.format('|'.join(cls.extensions())),
# array of options
'RH_OPTIONS': '({})'.format(' '.join('"{}"'.format(' '.join(o['options'])) for o in options)),
# array of choices of respective options
'RH_CHOICES': '({})'.format(' '.join('"{}"'.format(' '.join(o['choices'])) for o in options)),
<|code_end|>
using the current file's imports:
import re
import sys
from rebasehelper.cli import CLI
from rebasehelper.constants import ENCODING
from rebasehelper.archive import Archive
and any relevant context from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
#
# Path: rebasehelper/archive.py
# class Archive:
# """Class representing an archive with sources"""
#
# def __init__(self, filename):
# self._filename = filename
# self._archive_type = None
#
# for archive_type in archive_types.values():
# if archive_type.match(self._filename):
# self._archive_type = archive_type
#
# if self._archive_type is None:
# raise NotImplementedError('Unsupported archive type')
#
# def extract_archive(self, path):
# """
# Extracts the archive into the given path
#
# :param path: Path where to extract the archive to.
# """
# logger.verbose('Extracting %s to %s', self._filename, path)
#
# try:
# archive = self._archive_type.open(self._filename)
# except (EOFError, tarfile.ReadError, lzma.LZMAError) as e:
# raise IOError(str(e)) from e
#
# try:
# self._archive_type.extract(archive, self._filename, path)
# finally:
# archive.close()
#
# @classmethod
# def get_supported_archives(cls):
# return archive_types.keys()
. Output only the next line. | } |
Next line prediction: <|code_start|># Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
class Completion:
@staticmethod
def extensions():
archives = Archive.get_supported_archives()
return [a.lstrip('.') for a in archives]
@staticmethod
def options():
def get_delimiter(parser, action):
if action.nargs == 0:
return None
fmt = parser._get_formatter() # pylint: disable=protected-access
usage = fmt._format_actions_usage([action], []) # pylint: disable=protected-access
option_string = action.option_strings[0]
idx = usage.find(option_string)
if idx == -1:
return None
return usage[idx + len(option_string)]
parser = CLI.build_parser()
result = []
actions = parser._get_optional_actions() + parser._get_positional_actions() # pylint: disable=protected-access
for action in actions:
<|code_end|>
. Use current file imports:
(import re
import sys
from rebasehelper.cli import CLI
from rebasehelper.constants import ENCODING
from rebasehelper.archive import Archive)
and context including class names, function names, or small code snippets from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/constants.py
# ENCODING: str = locale.getpreferredencoding()
#
# Path: rebasehelper/archive.py
# class Archive:
# """Class representing an archive with sources"""
#
# def __init__(self, filename):
# self._filename = filename
# self._archive_type = None
#
# for archive_type in archive_types.values():
# if archive_type.match(self._filename):
# self._archive_type = archive_type
#
# if self._archive_type is None:
# raise NotImplementedError('Unsupported archive type')
#
# def extract_archive(self, path):
# """
# Extracts the archive into the given path
#
# :param path: Path where to extract the archive to.
# """
# logger.verbose('Extracting %s to %s', self._filename, path)
#
# try:
# archive = self._archive_type.open(self._filename)
# except (EOFError, tarfile.ReadError, lzma.LZMAError) as e:
# raise IOError(str(e)) from e
#
# try:
# self._archive_type.extract(archive, self._filename, path)
# finally:
# archive.close()
#
# @classmethod
# def get_supported_archives(cls):
# return archive_types.keys()
. Output only the next line. | if not action.option_strings: |
Here is a snippet: <|code_start|>
def make_artifacts_report():
artifacts = [
DEBUG_LOG,
CHANGES_PATCH,
REPORT + '.json',
'old-build/SRPM/build.log',
'old-build/RPM/build.log',
'old-build/RPM/root.log',
'old-build/RPM/mock_output.log',
'new-build/SRPM/build.log',
'new-build/RPM/build.log',
'new-build/RPM/root.log',
'new-build/RPM/mock_output.log',
]
report = []
for artifact in artifacts:
try:
with open(os.path.join(RESULTS_DIR, artifact), encoding=ENCODING) as f:
content = f.read()
report.append(' {} '.format(artifact).center(80, '_'))
report.append(content)
except IOError:
continue
return '\n'.join(report)
<|code_end|>
. Write the next line using the current file imports:
import os
import pytest # type: ignore
from rebasehelper.constants import RESULTS_DIR, DEBUG_LOG, CHANGES_PATCH, REPORT, ENCODING
and context from other files:
# Path: rebasehelper/constants.py
# RESULTS_DIR: str = 'rebase-helper-results'
#
# DEBUG_LOG: str = 'debug.log'
#
# CHANGES_PATCH: str = 'changes.patch'
#
# REPORT: str = 'report'
#
# ENCODING: str = locale.getpreferredencoding()
, which may include functions, classes, or code. Output only the next line. | @pytest.mark.hookwrapper |
Given snippet: <|code_start|>
def make_artifacts_report():
artifacts = [
DEBUG_LOG,
CHANGES_PATCH,
REPORT + '.json',
'old-build/SRPM/build.log',
'old-build/RPM/build.log',
'old-build/RPM/root.log',
'old-build/RPM/mock_output.log',
'new-build/SRPM/build.log',
'new-build/RPM/build.log',
'new-build/RPM/root.log',
'new-build/RPM/mock_output.log',
]
report = []
for artifact in artifacts:
try:
with open(os.path.join(RESULTS_DIR, artifact), encoding=ENCODING) as f:
content = f.read()
report.append(' {} '.format(artifact).center(80, '_'))
report.append(content)
except IOError:
continue
return '\n'.join(report)
@pytest.mark.hookwrapper
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import pytest # type: ignore
from rebasehelper.constants import RESULTS_DIR, DEBUG_LOG, CHANGES_PATCH, REPORT, ENCODING
and context:
# Path: rebasehelper/constants.py
# RESULTS_DIR: str = 'rebase-helper-results'
#
# DEBUG_LOG: str = 'debug.log'
#
# CHANGES_PATCH: str = 'changes.patch'
#
# REPORT: str = 'report'
#
# ENCODING: str = locale.getpreferredencoding()
which might include code, classes, or functions. Output only the next line. | def pytest_runtest_makereport(): |
Continue the code snippet: <|code_start|>#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
def make_artifacts_report():
artifacts = [
DEBUG_LOG,
CHANGES_PATCH,
REPORT + '.json',
'old-build/SRPM/build.log',
<|code_end|>
. Use current file imports:
import os
import pytest # type: ignore
from rebasehelper.constants import RESULTS_DIR, DEBUG_LOG, CHANGES_PATCH, REPORT, ENCODING
and context (classes, functions, or code) from other files:
# Path: rebasehelper/constants.py
# RESULTS_DIR: str = 'rebase-helper-results'
#
# DEBUG_LOG: str = 'debug.log'
#
# CHANGES_PATCH: str = 'changes.patch'
#
# REPORT: str = 'report'
#
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | 'old-build/RPM/build.log', |
Continue the code snippet: <|code_start|># Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
def make_artifacts_report():
artifacts = [
DEBUG_LOG,
CHANGES_PATCH,
REPORT + '.json',
'old-build/SRPM/build.log',
'old-build/RPM/build.log',
'old-build/RPM/root.log',
'old-build/RPM/mock_output.log',
'new-build/SRPM/build.log',
'new-build/RPM/build.log',
'new-build/RPM/root.log',
'new-build/RPM/mock_output.log',
]
report = []
for artifact in artifacts:
try:
with open(os.path.join(RESULTS_DIR, artifact), encoding=ENCODING) as f:
content = f.read()
report.append(' {} '.format(artifact).center(80, '_'))
report.append(content)
except IOError:
<|code_end|>
. Use current file imports:
import os
import pytest # type: ignore
from rebasehelper.constants import RESULTS_DIR, DEBUG_LOG, CHANGES_PATCH, REPORT, ENCODING
and context (classes, functions, or code) from other files:
# Path: rebasehelper/constants.py
# RESULTS_DIR: str = 'rebase-helper-results'
#
# DEBUG_LOG: str = 'debug.log'
#
# CHANGES_PATCH: str = 'changes.patch'
#
# REPORT: str = 'report'
#
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | continue |
Continue the code 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
def make_artifacts_report():
artifacts = [
DEBUG_LOG,
CHANGES_PATCH,
REPORT + '.json',
'old-build/SRPM/build.log',
'old-build/RPM/build.log',
'old-build/RPM/root.log',
'old-build/RPM/mock_output.log',
'new-build/SRPM/build.log',
'new-build/RPM/build.log',
<|code_end|>
. Use current file imports:
import os
import pytest # type: ignore
from rebasehelper.constants import RESULTS_DIR, DEBUG_LOG, CHANGES_PATCH, REPORT, ENCODING
and context (classes, functions, or code) from other files:
# Path: rebasehelper/constants.py
# RESULTS_DIR: str = 'rebase-helper-results'
#
# DEBUG_LOG: str = 'debug.log'
#
# CHANGES_PATCH: str = 'changes.patch'
#
# REPORT: str = 'report'
#
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | 'new-build/RPM/root.log', |
Given the code snippet: <|code_start|> FILE_XML,
]
def get_data(self):
data = {'moved': ['/usr/src/debug/iproute2-3.12.0/test/mytest.c',
'/usr/src/debug/iproute2-3.12.0/test/mytest2.c'],
'changed': ['/usr/include/test.h']}
return data
def test_fill_dictionary(self):
expected_dict = {'added': ['/usr/sbin/test',
'/usr/sbin/pkg-*/binary_test',
'/usr/lib64/libtest.so',
'/usr/lib64/libtest.so.1'],
'removed': ['/usr/sbin/my_test',
'/usr/sbin/pkg-*/binary_test',
'/usr/lib64/libtest2.so',
'/usr/lib64/libtest2.so.1'],
'changed': ['/usr/share/test.man'],
'moved': ['/usr/local/test.sh',
'/usr/sbin/pkg-*/binary_test;/usr/sbin/pkg-*/binary_test (1%)'],
'renamed': ['/usr/lib/libtest3.so.3',
'/usr/lib/libtest3.so']}
plugin_manager.checkers.plugins['pkgdiff'].results_dir = TEST_FILES_DIR
plugin_manager.checkers.plugins['pkgdiff'].fill_dictionary(TEST_FILES_DIR, old_version='1.0.1',
new_version='1.0.2')
assert plugin_manager.checkers.plugins['pkgdiff'].results_dict == expected_dict
def test_process_xml(self):
expected_dict = {'added': ['/usr/sbin/test',
<|code_end|>
, generate the next line using the imports in this file:
from typing import List
from rebasehelper.plugins.plugin_manager import plugin_manager
from rebasehelper.tests.conftest import TEST_FILES_DIR
and context (functions, classes, or occasionally code) from other files:
# Path: rebasehelper/plugins/plugin_manager.py
# class PluginManager:
# COLLECTIONS: List[Type[PluginCollection]] = [
# BuildLogHookCollection,
# BuildToolCollection,
# SRPMBuildToolCollection,
# CheckerCollection,
# OutputToolCollection,
# SpecHookCollection,
# VersioneerCollection,
# ]
# def __init__(self):
# def convert_class_name(class_name):
# def get_options(self) -> Options:
# def __getattr__(self, name):
#
# Path: rebasehelper/tests/conftest.py
# TEST_FILES_DIR: str = os.path.join(TESTS_DIR, 'testing_files')
. Output only the next line. | '/usr/lib64/libtest.so', |
Using the snippet: <|code_start|> FILE_XML,
]
def get_data(self):
data = {'moved': ['/usr/src/debug/iproute2-3.12.0/test/mytest.c',
'/usr/src/debug/iproute2-3.12.0/test/mytest2.c'],
'changed': ['/usr/include/test.h']}
return data
def test_fill_dictionary(self):
expected_dict = {'added': ['/usr/sbin/test',
'/usr/sbin/pkg-*/binary_test',
'/usr/lib64/libtest.so',
'/usr/lib64/libtest.so.1'],
'removed': ['/usr/sbin/my_test',
'/usr/sbin/pkg-*/binary_test',
'/usr/lib64/libtest2.so',
'/usr/lib64/libtest2.so.1'],
'changed': ['/usr/share/test.man'],
'moved': ['/usr/local/test.sh',
'/usr/sbin/pkg-*/binary_test;/usr/sbin/pkg-*/binary_test (1%)'],
'renamed': ['/usr/lib/libtest3.so.3',
'/usr/lib/libtest3.so']}
plugin_manager.checkers.plugins['pkgdiff'].results_dir = TEST_FILES_DIR
plugin_manager.checkers.plugins['pkgdiff'].fill_dictionary(TEST_FILES_DIR, old_version='1.0.1',
new_version='1.0.2')
assert plugin_manager.checkers.plugins['pkgdiff'].results_dict == expected_dict
def test_process_xml(self):
expected_dict = {'added': ['/usr/sbin/test',
<|code_end|>
, determine the next line of code. You have imports:
from typing import List
from rebasehelper.plugins.plugin_manager import plugin_manager
from rebasehelper.tests.conftest import TEST_FILES_DIR
and context (class names, function names, or code) available:
# Path: rebasehelper/plugins/plugin_manager.py
# class PluginManager:
# COLLECTIONS: List[Type[PluginCollection]] = [
# BuildLogHookCollection,
# BuildToolCollection,
# SRPMBuildToolCollection,
# CheckerCollection,
# OutputToolCollection,
# SpecHookCollection,
# VersioneerCollection,
# ]
# def __init__(self):
# def convert_class_name(class_name):
# def get_options(self) -> Options:
# def __getattr__(self, name):
#
# Path: rebasehelper/tests/conftest.py
# TEST_FILES_DIR: str = os.path.join(TESTS_DIR, 'testing_files')
. Output only the next line. | '/usr/lib64/libtest.so', |
Next line prediction: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
class SampleConfig:
DESCRIPTION: List[str] = [
'# sample configuration file for rebase-helper',
'# copy this file to {} and edit it as necessary'.format(os.path.join(CONFIG_PATH, CONFIG_FILENAME)),
'# all options specified here can be overridden on the command line',
]
BLACKLIST: List[str] = [
<|code_end|>
. Use current file imports:
(import os
import sys
from argparse import SUPPRESS
from typing import List
from rebasehelper.cli import CLI
from rebasehelper.constants import CONFIG_PATH, CONFIG_FILENAME, ENCODING)
and context including class names, function names, or small code snippets from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/constants.py
# CONFIG_PATH: str = '$XDG_CONFIG_HOME'
#
# CONFIG_FILENAME: str = 'rebase-helper.cfg'
#
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | 'help', |
Given the following code snippet before the placeholder: <|code_start|>
BLACKLIST: List[str] = [
'help',
'version',
'config-file',
]
@classmethod
def generate(cls):
result = cls.DESCRIPTION + ['']
parser = CLI.build_parser()
result.append('[general]')
for action in parser._get_optional_actions(): # pylint: disable=protected-access
if action.help is SUPPRESS:
continue
fmt = parser._get_formatter() # pylint: disable=protected-access
opts = action.option_strings
if len(opts) > 1:
opts.pop(0)
name = opts[0].lstrip('-')
if name in cls.BLACKLIST:
continue
value = getattr(action, 'actual_default', None)
if isinstance(value, list):
value = ','.join(value)
args = fmt._format_args(action, action.dest.upper()) # pylint: disable=protected-access
result.append('')
result.append('# {}'.format(fmt._expand_help(action))) # pylint: disable=protected-access
if args:
result.append('# synopsis: {} = {}'.format(name, args))
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
from argparse import SUPPRESS
from typing import List
from rebasehelper.cli import CLI
from rebasehelper.constants import CONFIG_PATH, CONFIG_FILENAME, ENCODING
and context including class names, function names, and sometimes code from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/constants.py
# CONFIG_PATH: str = '$XDG_CONFIG_HOME'
#
# CONFIG_FILENAME: str = 'rebase-helper.cfg'
#
# ENCODING: str = locale.getpreferredencoding()
. Output only the next line. | result.append('{} = {}'.format(name, value if value is not None else '')) |
Here is a snippet: <|code_start|># This tool helps you rebase your package to the latest version
# Copyright (C) 2013-2019 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
class SampleConfig:
DESCRIPTION: List[str] = [
'# sample configuration file for rebase-helper',
'# copy this file to {} and edit it as necessary'.format(os.path.join(CONFIG_PATH, CONFIG_FILENAME)),
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
from argparse import SUPPRESS
from typing import List
from rebasehelper.cli import CLI
from rebasehelper.constants import CONFIG_PATH, CONFIG_FILENAME, ENCODING
and context from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/constants.py
# CONFIG_PATH: str = '$XDG_CONFIG_HOME'
#
# CONFIG_FILENAME: str = 'rebase-helper.cfg'
#
# ENCODING: str = locale.getpreferredencoding()
, which may include functions, classes, or code. Output only the next line. | '# all options specified here can be overridden on the command line', |
Here is a 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
class SampleConfig:
DESCRIPTION: List[str] = [
'# sample configuration file for rebase-helper',
'# copy this file to {} and edit it as necessary'.format(os.path.join(CONFIG_PATH, CONFIG_FILENAME)),
'# all options specified here can be overridden on the command line',
]
BLACKLIST: List[str] = [
'help',
'version',
'config-file',
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
from argparse import SUPPRESS
from typing import List
from rebasehelper.cli import CLI
from rebasehelper.constants import CONFIG_PATH, CONFIG_FILENAME, ENCODING
and context from other files:
# Path: rebasehelper/cli.py
# class CLI:
# """ Class for processing data from commandline """
#
# @staticmethod
# def build_parser(available_choices_only=False):
# parser = CustomArgumentParser(description=PROGRAM_DESCRIPTION,
# formatter_class=CustomHelpFormatter)
#
# group = None
# current_group = 0
# for option in traverse_options(OPTIONS + plugin_manager.get_options()):
# available_choices = option.pop("available_choices", option.get("choices"))
# if available_choices_only:
# option["choices"] = available_choices
#
# option_kwargs = dict(option)
# for key in ("group", "default", "name"):
# if key in option_kwargs:
# del option_kwargs[key]
#
# if "group" in option:
# if not group or current_group != option["group"]:
# current_group = option["group"]
# group = parser.add_mutually_exclusive_group()
# actions_container = group
# else:
# actions_container = parser
#
# # default is set to SUPPRESS to prevent arguments which were not specified on command line from being
# # added to namespace. This allows rebase-helper to determine which arguments are used with their
# # default value. This is later used for merging CLI arguments with config.
# actions_container.add_argument(*option["name"], action=CustomAction, default=argparse.SUPPRESS,
# actual_default=option.get("default"), **option_kwargs)
#
# return parser
#
# def __init__(self, args=None):
# """parse arguments"""
# if args is None:
# args = sys.argv[1:]
# # sanitize builder options to prevent ArgumentParser from processing them
# for opt in ['--builder-options', '--srpm-builder-options']:
# try:
# i = args.index(opt)
# args[i:i+2] = ['='.join(args[i:i+2])]
# except ValueError:
# continue
# self.parser = CLI.build_parser(available_choices_only=True)
# self.args = self.parser.parse_args(args)
#
# def __getattr__(self, name):
# try:
# return getattr(self.args, name)
# except AttributeError:
# return object.__getattribute__(self, name)
#
# Path: rebasehelper/constants.py
# CONFIG_PATH: str = '$XDG_CONFIG_HOME'
#
# CONFIG_FILENAME: str = 'rebase-helper.cfg'
#
# ENCODING: str = locale.getpreferredencoding()
, which may include functions, classes, or code. Output only the next line. | ] |
Continue the code snippet: <|code_start|># This tool helps you rebase your package to the latest version
# Copyright (C) 2013-2019 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
if TYPE_CHECKING:
# avoid cyclic import at runtime
class Plugin:
name: Optional[str] = None
<|code_end|>
. Use current file imports:
from typing import Optional, TYPE_CHECKING
from rebasehelper.types import Options
from rebasehelper.plugins.plugin_manager import PluginManager
and context (classes, functions, or code) from other files:
# Path: rebasehelper/types.py
. Output only the next line. | manager: Optional['PluginManager'] = None |
Next line prediction: <|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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Authors: Petr Hráček <phracek@redhat.com>
# Tomáš Hozza <thozza@redhat.com>
# Nikola Forró <nforro@redhat.com>
# František Nečas <fifinecas@seznam.cz>
logger: CustomLogger = cast(CustomLogger, logging.getLogger(__name__))
# supported archive types
archive_types: Dict[str, Type['ArchiveTypeBase']] = {}
def register_archive_type(archive):
archive_types[archive.EXTENSION] = archive
return archive
<|code_end|>
. Use current file imports:
(import bz2
import logging
import lzma
import os
import shutil
import tarfile
import zipfile
from typing import Dict, Type, cast
from rebasehelper.logger import CustomLogger
from rebasehelper.helpers.path_helper import PathHelper)
and context including class names, function names, or small code snippets from other files:
# Path: rebasehelper/logger.py
# class CustomLogger(logging.Logger):
#
# TRACE: int = logging.DEBUG + 1
# VERBOSE: int = logging.DEBUG + 2
# SUCCESS: int = logging.INFO + 5
# HEADING: int = logging.INFO + 6
# IMPORTANT: int = logging.INFO + 7
#
# _nameToLevel: Dict[str, int] = {
# 'TRACE': TRACE,
# 'VERBOSE': VERBOSE,
# 'SUCCESS': SUCCESS,
# 'HEADING': HEADING,
# 'IMPORTANT': IMPORTANT,
# }
#
# def __init__(self, name, level=logging.NOTSET):
# super().__init__(name, level)
#
# for lev, severity in self._nameToLevel.items():
# logging.addLevelName(severity, lev)
#
# def __getattr__(self, level):
# severity = self._nameToLevel.get(level.upper())
#
# def log(message, *args, **kwargs):
# if self.isEnabledFor(severity):
# self._log(severity, message, args, **kwargs)
#
# if severity:
# return log
#
# raise AttributeError
#
# Path: rebasehelper/helpers/path_helper.py
# class PathHelper:
#
# """Class for performing path related tasks."""
#
# @staticmethod
# def find_first_dir_with_file(top_path, pattern):
# """Recursively searches for a directory containing a file that matches the given pattern.
#
# Args:
# top_path (str): Directory where to start the search.
# pattern (str): Filename pattern.
#
# Returns:
# str: Full path to the directory containing the first occurence of the searched file.
# None if there is no file matching the pattern.
#
# """
# for root, dirs, files in os.walk(top_path):
# dirs.sort()
# for f in files:
# if fnmatch.fnmatch(f, pattern):
# return os.path.abspath(root)
# return None
#
# @staticmethod
# def find_first_file(top_path, pattern, recursion_level=None):
# """Recursively searches for a file that matches the given pattern.
#
# Args:
# top_path (str): Directory where to start the search.
# pattern (str): Filename pattern.
# recursion_level (int): How deep in the directory tree the search can go.
#
# Returns:
# str: Path to the file matching the pattern or None if there is no file matching the pattern.
#
# """
# for loop, (root, dirs, files) in enumerate(os.walk(top_path)):
# dirs.sort()
# for f in files:
# if fnmatch.fnmatch(f, pattern):
# return os.path.join(os.path.abspath(root), f)
# if recursion_level is not None:
# if loop == recursion_level:
# break
# return None
#
# @staticmethod
# def find_all_files(top_path, pattern):
# """Recursively searches for all files matching the given pattern.
#
# Args:
# top_path (str): Directory where to start the search.
# pattern (str): Filename pattern.
#
# Returns:
# list: List containing absolute paths to all found files.
#
# """
# files_list = []
# for root, dirs, files in os.walk(top_path):
# dirs.sort()
# for f in files:
# if fnmatch.fnmatch(f, pattern):
# files_list.append(os.path.join(os.path.abspath(root), f))
# return files_list
#
# @staticmethod
# def find_all_files_current_dir(top_path, pattern):
# """Searches for all files that match the given pattern inside a directory.
#
# Args:
# top_path (str): Directory where to start the search.
# pattern (str): Filename pattern.
#
# Returns:
# list: List containing absolute paths to all found files.
#
# """
# files_list = []
# for files in os.listdir(top_path):
# if fnmatch.fnmatch(files, pattern):
# files_list.append(os.path.join(os.path.abspath(top_path), files))
# return files_list
#
# @staticmethod
# def get_temp_dir():
# """Creates a new temporary directory.
#
# Return:
# str: Path to the created directory.
#
# """
# return tempfile.mkdtemp(prefix='rebase-helper-')
#
# @staticmethod
# def file_available(filename):
# """Checks if the given file exists.
#
# Args:
# filename (str): Path to the file.
#
# Returns:
# bool: Whether the file exists.
#
# """
# if os.path.exists(filename) and os.path.getsize(filename) != 0:
# return True
# else:
# return False
. Output only the next line. | class ArchiveTypeBase: |
Predict the next line after this snippet: <|code_start|> metavar=metavar,
type=type,
help=help,
choices=choices)
self.switch = switch
self.counter = counter
self.append = append
self.nargs = 0 if self.switch or self.counter else 1 if self.append else nargs
self.actual_default = actual_default
def __call__(self, parser, namespace, values, option_string=None):
if self.counter:
value = getattr(namespace, self.dest, 0) + 1
elif self.append:
value = getattr(namespace, self.dest, [])
value.extend(values)
elif self.switch:
value = True
else:
value = values
setattr(namespace, self.dest, value)
class CustomArgumentParser(argparse.ArgumentParser):
def _check_value(self, action, value):
if isinstance(value, list):
# converted value must be subset of the choices (if specified)
empty = value == action.const
<|code_end|>
using the current file's imports:
import argparse
import sys
from rebasehelper.exceptions import RebaseHelperError, ParseError
and any relevant context from other files:
# Path: rebasehelper/exceptions.py
# class RebaseHelperError(Exception):
# """Class representing Error raised inside rebase-helper after intentionally
# catching some expected and well known exception/error.
#
# """
#
# def __init__(self, *args, **kwargs):
# """Constructor of RebaseHelperError"""
# super().__init__()
# if not args:
# self.msg = None
# elif len(args) > 1:
# self.msg = args[0] % args[1:]
# else:
# self.msg = args[0]
# self.logfiles = kwargs.get('logfiles')
#
# def __str__(self):
# return str(self.msg) if self.msg else ''
#
# class ParseError(Exception):
# pass
. Output only the next line. | if action.choices is not None and not empty and not set(value).issubset(action.choices): |
Based on the snippet: <|code_start|> self.actual_default = actual_default
def __call__(self, parser, namespace, values, option_string=None):
if self.counter:
value = getattr(namespace, self.dest, 0) + 1
elif self.append:
value = getattr(namespace, self.dest, [])
value.extend(values)
elif self.switch:
value = True
else:
value = values
setattr(namespace, self.dest, value)
class CustomArgumentParser(argparse.ArgumentParser):
def _check_value(self, action, value):
if isinstance(value, list):
# converted value must be subset of the choices (if specified)
empty = value == action.const
if action.choices is not None and not empty and not set(value).issubset(action.choices):
invalid = set(value).difference(action.choices)
if len(invalid) == 1:
tup = repr(invalid.pop()), ', '.join(map(repr, action.choices))
msg = 'invalid choice: %s (choose from %s)' % tup
else:
tup = ', '.join(map(repr, invalid)), ', '.join(map(repr, action.choices))
msg = 'invalid choices: %s (choose from %s)' % tup
raise argparse.ArgumentError(action, msg)
<|code_end|>
, predict the immediate next line with the help of imports:
import argparse
import sys
from rebasehelper.exceptions import RebaseHelperError, ParseError
and context (classes, functions, sometimes code) from other files:
# Path: rebasehelper/exceptions.py
# class RebaseHelperError(Exception):
# """Class representing Error raised inside rebase-helper after intentionally
# catching some expected and well known exception/error.
#
# """
#
# def __init__(self, *args, **kwargs):
# """Constructor of RebaseHelperError"""
# super().__init__()
# if not args:
# self.msg = None
# elif len(args) > 1:
# self.msg = args[0] % args[1:]
# else:
# self.msg = args[0]
# self.logfiles = kwargs.get('logfiles')
#
# def __str__(self):
# return str(self.msg) if self.msg else ''
#
# class ParseError(Exception):
# pass
. Output only the next line. | else: |
Predict the next line for this snippet: <|code_start|>class LoginForm(forms.Form):
name = forms.CharField(label='Your Name', max_length=100)
password = forms.CharField(label='Password', max_length=20, widget=forms.PasswordInput())
#def clean(self):
# first_pass = self.cleaned_data['password']
# rep_pass = self.cleaned_data['repeat_password']
# if first_pass and rep_pass:
# if first_pass != rep_pass:
# raise forms.ValidationError('Passwords must match')
class Password(forms.Form):
name = forms.CharField(label='Your name', max_length=100)
email = forms.EmailField(label='Your mail', max_length=100)
class RouteAddForm(forms.Form):
stop1 = forms.ModelChoiceField(queryset=Stop.objects.all(), to_field_name="id")
stop2 = forms.ModelChoiceField(queryset=Stop.objects.all(), to_field_name="id")
<|code_end|>
with the help of current file imports:
from django import forms
from django.contrib.admin import widgets
from django.forms import ModelForm
from runner.models import User
from bus.models import *
from taxi.models import *
and context from other files:
# Path: runner/models.py
# class User(UserAbstract):
# def __str__(self):
# return self.name ;
# class Meta:
# managed = True
# db_table = 'User'
, which may contain function names, class names, or code. Output only the next line. | stop3 = forms.ModelChoiceField(queryset=Stop.objects.all(), to_field_name="id") |
Next line prediction: <|code_start|> try:
taxi = Taxi.objects.get(id=tid)
serial_taxi = TaxiSerializer(taxi, many=True)
response.status_code = 200
response.data = serial_taxi.data
return response
except:
response.data = "TAXI NOT FOUND"
return response
else:
response.data = "Corrupted URL"
return response
@api_view(['GET'])
@protector
def taxi_choice(request):
choicedict = {}
for key in request.GET.keys():
choicedict[key] = request.GET[key]
taxis = Taxi.objects.filter(**choicedict)
serial_taxi = TaxiSerializer(taxis, many=True)
return Response(serial_taxi.data)
@api_view(['POST'])
@protector
def book_taxi(request):
#try:
uid = request.POST['user']
tid = request.POST['taxi']
<|code_end|>
. Use current file imports:
(from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.db.models import Q
from taxi.serializers import *
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.core.mail import send_mail
from taxi.models import *
from runner.models import User
from datetime import timedelta, datetime
from django.utils import timezone
from e_auth.middleware import protector
import urllib, urllib2
import json)
and context including class names, function names, or small code snippets from other files:
# Path: runner/models.py
# class User(UserAbstract):
# def __str__(self):
# return self.name ;
# class Meta:
# managed = True
# db_table = 'User'
#
# Path: e_auth/middleware.py
# def protector(func):
# def decorator(request, *args, **kwargs):
# app_name = request.resolver_match.app_name
# from django.conf import settings
# allowed_apps = settings.EAUTH_ALLOWEDAPPS
# if app_name in allowed_apps:
# return func(request, *args, **kwargs)
#
# token = request.GET.get('token') or request.POST.get('token')
# response = HttpResponse()
# if token:
# try:
# auth = Authorize.objects.get(auth_token=token)
#
# if(timezone.now() < auth.expire_time):
# return func(request, *args, **kwargs)
# else:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "Token Has Expired"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
# except:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "User Not Authorized"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# else:
# retdict = {}
# retdict['status'] = 404
# retdict['data'] = "Access Token Is Required"
# retdict['detail'] = "Unverified Request to restricted url"
# response.status_code = 404
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# return decorator
. Output only the next line. | j_time = request.POST['journey_time'] |
Based on the snippet: <|code_start|>
@api_view(['GET'])
@protector
def taxi_detail(request):
response = Response()
response.status_code = 405
tid = request.GET['id']
if(tid):
try:
taxi = Taxi.objects.get(id=tid)
serial_taxi = TaxiSerializer(taxi, many=True)
response.status_code = 200
response.data = serial_taxi.data
return response
except:
response.data = "TAXI NOT FOUND"
return response
else:
response.data = "Corrupted URL"
return response
@api_view(['GET'])
@protector
def taxi_choice(request):
choicedict = {}
for key in request.GET.keys():
choicedict[key] = request.GET[key]
taxis = Taxi.objects.filter(**choicedict)
serial_taxi = TaxiSerializer(taxis, many=True)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.db.models import Q
from taxi.serializers import *
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.core.mail import send_mail
from taxi.models import *
from runner.models import User
from datetime import timedelta, datetime
from django.utils import timezone
from e_auth.middleware import protector
import urllib, urllib2
import json
and context (classes, functions, sometimes code) from other files:
# Path: runner/models.py
# class User(UserAbstract):
# def __str__(self):
# return self.name ;
# class Meta:
# managed = True
# db_table = 'User'
#
# Path: e_auth/middleware.py
# def protector(func):
# def decorator(request, *args, **kwargs):
# app_name = request.resolver_match.app_name
# from django.conf import settings
# allowed_apps = settings.EAUTH_ALLOWEDAPPS
# if app_name in allowed_apps:
# return func(request, *args, **kwargs)
#
# token = request.GET.get('token') or request.POST.get('token')
# response = HttpResponse()
# if token:
# try:
# auth = Authorize.objects.get(auth_token=token)
#
# if(timezone.now() < auth.expire_time):
# return func(request, *args, **kwargs)
# else:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "Token Has Expired"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
# except:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "User Not Authorized"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# else:
# retdict = {}
# retdict['status'] = 404
# retdict['data'] = "Access Token Is Required"
# retdict['detail'] = "Unverified Request to restricted url"
# response.status_code = 404
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# return decorator
. Output only the next line. | return Response(serial_taxi.data) |
Continue the code snippet: <|code_start|> journey_time = models.DateTimeField(null=True, blank=True)
fair = models.IntegerField( null=True, default='0')
def __str__(self):
return str(self.source.name)+"("+str(self.source.city)+")"+"-"+str(self.dest.name)+"("+str(self.dest.city)+")"
def save(self, *args, **kwargs):
if(self.journey_time and self.fair):
super(Route, self).save(*args, **kwargs)
else:
datadict = gmaps(source=self.source.get_location(), dest=self.dest.get_location())
self.fair = self.bus.fair_ratio*datadict['distance']/1000
self.journey_time = self.start_time + timedelta(seconds=datadict['time'])
super(Route, self).save(*args, **kwargs)
class Meta:
managed = True
@python_2_unicode_compatible
class Ticket(models.Model):
id = models.AutoField( primary_key=True) # Field name made lowercase.
user = models.ForeignKey(User, models.DO_NOTHING, related_name='+') # Field name made lowercase.
route = models.ForeignKey(Route, models.DO_NOTHING, related_name='+') # Field name made lowercase.
seats = models.IntegerField( default='0') # Field name made lowercase.
price = models.IntegerField( default='0') # Field name made lowercase.
book_time = models.DateTimeField() # Field name made lowercase.
seats_config = models.CharField(max_length=56, default=def_ticket)
payment_status = models.CharField(max_length=20, choices=PAYMENT_STATUS)
def __str__(self):
<|code_end|>
. Use current file imports:
from django.utils.encoding import python_2_unicode_compatible
from django.db.models import Q
from django.db import models, transaction
from django.db.utils import OperationalError
from runner.models import User
from datetime import datetime, timedelta
from django.utils import timezone
import urllib, urllib2
import json
and context (classes, functions, or code) from other files:
# Path: runner/models.py
# class User(UserAbstract):
# def __str__(self):
# return self.name ;
# class Meta:
# managed = True
# db_table = 'User'
. Output only the next line. | return self.user.name |
Here is a snippet: <|code_start|>
# Create your views here.
@api_view(['GET', 'POST'],)
@protector
def get_stops(request):
sql = """select * from bus_stop where bus_stop.id != -1"""
queryset = Stop.objects.raw(sql)
result = StopSerializer(queryset, many=True)
return Response(result.data)
@api_view(['POST', 'GET'],)
@protector
def get_routes(request):
source = request.POST['source']
dest = request.POST['dest']
time = request.POST['time']
now = str(timezone.now())
sql = ROUTE_SEARCH_QUERY
queryset = Route.objects.raw(sql, (source, dest, now, time, time) )
result = RouteSerializer(queryset, many=True)
return Response(result.data)
@api_view(['GET', 'POST'])
@protector
def get_route_detail(request, id):
rid = id
sql = ROUTE_DETAIL_QUERY
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.db import connection
from bus.queries import *
from bus.serializers import *
from bus.models import *
from rest_framework.decorators import api_view
from rest_framework.response import Response
from bus import forms
from rest_framework import viewsets
from MySQLdb.cursors import SSDictCursor
from django.core.mail import send_mail
from django.utils import timezone
from e_auth.middleware import protector
import MySQLdb as mysql
import json
and context from other files:
# Path: bus/forms.py
#
# Path: e_auth/middleware.py
# def protector(func):
# def decorator(request, *args, **kwargs):
# app_name = request.resolver_match.app_name
# from django.conf import settings
# allowed_apps = settings.EAUTH_ALLOWEDAPPS
# if app_name in allowed_apps:
# return func(request, *args, **kwargs)
#
# token = request.GET.get('token') or request.POST.get('token')
# response = HttpResponse()
# if token:
# try:
# auth = Authorize.objects.get(auth_token=token)
#
# if(timezone.now() < auth.expire_time):
# return func(request, *args, **kwargs)
# else:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "Token Has Expired"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
# except:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "User Not Authorized"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# else:
# retdict = {}
# retdict['status'] = 404
# retdict['data'] = "Access Token Is Required"
# retdict['detail'] = "Unverified Request to restricted url"
# response.status_code = 404
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# return decorator
, which may include functions, classes, or code. Output only the next line. | queryset = Route.objects.raw(sql, (rid,)) |
Next line prediction: <|code_start|>#from runner.serializers import StopSerializer, RouteSerializer, RouteDetailSerializer
#from django.core.mail import send_mail
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
def index(request):
<|code_end|>
. Use current file imports:
(from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.db import connection
from runner.queries import *
from runner.serializers import *
from rest_framework.decorators import api_view
from rest_framework.response import Response
from runner import forms
from rest_framework import viewsets
from MySQLdb.cursors import SSDictCursor
from django.core.mail import send_mail
from runner.models import *
from e_auth.middleware import protector
import MySQLdb as mysql
import json)
and context including class names, function names, or small code snippets from other files:
# Path: runner/forms.py
# class LoginForm(forms.Form):
# class Password(forms.Form):
# class RouteAddForm(forms.Form):
# class StopsForm(forms.Form):
# class RouteForm(forms.Form):
# class BusBookForm(forms.Form):
# class UserSignupForm(ModelForm):
# class Meta:
# class AuthForm(forms.Form):
# class TokenForm(forms.Form):
# class PassForm(forms.Form):
# class BookingForm(ModelForm):
# class Meta:
#
# Path: e_auth/middleware.py
# def protector(func):
# def decorator(request, *args, **kwargs):
# app_name = request.resolver_match.app_name
# from django.conf import settings
# allowed_apps = settings.EAUTH_ALLOWEDAPPS
# if app_name in allowed_apps:
# return func(request, *args, **kwargs)
#
# token = request.GET.get('token') or request.POST.get('token')
# response = HttpResponse()
# if token:
# try:
# auth = Authorize.objects.get(auth_token=token)
#
# if(timezone.now() < auth.expire_time):
# return func(request, *args, **kwargs)
# else:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "Token Has Expired"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
# except:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "User Not Authorized"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# else:
# retdict = {}
# retdict['status'] = 404
# retdict['data'] = "Access Token Is Required"
# retdict['detail'] = "Unverified Request to restricted url"
# response.status_code = 404
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# return decorator
. Output only the next line. | return HttpResponse("Hello kapil") |
Given snippet: <|code_start|>
@api_view(['GET'])
@protector
def get_user_detail(request, id):
cursor = connection.cursor()
uid = id
sql = USER_DETAIL_QUERY
cursor.execute(sql, (uid,))
queryset = dictfetchall(cursor)
result = UserDetailSerializer(queryset, many=True)
return Response(result.data)
@api_view(['POST', 'GET'])
@protector
def get_user_by_name(request):
if request.method=="GET":
uname = request.GET['username']
elif request.method == "POST":
uname = request.POST['username']
try:
user = User.objects.get(name=uname)
serial_user = UserSerializer(user)
return Response(serial_user.data)
except:
return Response("NO_DATA", status=404)
@api_view(['GET'])
@protector
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.db import connection
from runner.queries import *
from runner.serializers import *
from rest_framework.decorators import api_view
from rest_framework.response import Response
from runner import forms
from rest_framework import viewsets
from MySQLdb.cursors import SSDictCursor
from django.core.mail import send_mail
from runner.models import *
from e_auth.middleware import protector
import MySQLdb as mysql
import json
and context:
# Path: runner/forms.py
# class LoginForm(forms.Form):
# class Password(forms.Form):
# class RouteAddForm(forms.Form):
# class StopsForm(forms.Form):
# class RouteForm(forms.Form):
# class BusBookForm(forms.Form):
# class UserSignupForm(ModelForm):
# class Meta:
# class AuthForm(forms.Form):
# class TokenForm(forms.Form):
# class PassForm(forms.Form):
# class BookingForm(ModelForm):
# class Meta:
#
# Path: e_auth/middleware.py
# def protector(func):
# def decorator(request, *args, **kwargs):
# app_name = request.resolver_match.app_name
# from django.conf import settings
# allowed_apps = settings.EAUTH_ALLOWEDAPPS
# if app_name in allowed_apps:
# return func(request, *args, **kwargs)
#
# token = request.GET.get('token') or request.POST.get('token')
# response = HttpResponse()
# if token:
# try:
# auth = Authorize.objects.get(auth_token=token)
#
# if(timezone.now() < auth.expire_time):
# return func(request, *args, **kwargs)
# else:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "Token Has Expired"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
# except:
# retdict = {}
# retdict['status'] = 400
# retdict['data'] = "User Not Authorized"
# retdict['detail'] = "Invalid Token"
# response.status_code = 400
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# else:
# retdict = {}
# retdict['status'] = 404
# retdict['data'] = "Access Token Is Required"
# retdict['detail'] = "Unverified Request to restricted url"
# response.status_code = 404
# serialdata = json.dumps(retdict)
# response.content = serialdata
# return response
#
# return decorator
which might include code, classes, or functions. Output only the next line. | def get_user(request, id): |
Continue the code snippet: <|code_start|>from __future__ import unicode_literals
TAXI_TYPES = (
('SUV', 'SUV'),
('TRUCK', 'Truck'),
('SEDAN', 'Sedan'),
('VAN', 'Van'),
('WAGON', 'Wagon'),
('CONVERTIBLE', 'Convertible'),
('SPORTS', 'Sports'),
('DIESEL', 'Diesel'),
('CROSSOVER', 'Crossover'),
('LUXURY', 'Luxury'),
('ELECTRIC', 'Electric'),
('HATCHBACK', 'Hatchback'),
<|code_end|>
. Use current file imports:
from django.utils.encoding import python_2_unicode_compatible
from django.db import models, transaction
from runner.models import User
and context (classes, functions, or code) from other files:
# Path: runner/models.py
# class User(UserAbstract):
# def __str__(self):
# return self.name ;
# class Meta:
# managed = True
# db_table = 'User'
. Output only the next line. | ('OTHER', 'Other'), |
Predict the next line after this snippet: <|code_start|> self.changed = True
def visit_preamble(self, preamble):
if preamble.transform(self.visit_pre_insn):
self.changed = True
def visit_pre_insn(self, insn):
if isinstance(insn, DefineGlobal):
var = insn._value
if not var.is_referenced:
#print("Unreferenced global define", var)
return None
return insn
def visit_global(self, name, var):
if not var.is_referenced:
#print("Unreferenced global", var)
return None, None
return name, var
def visit_function(self, name, func):
if not func.extern_visibility and not func.has_usage():
#print("Dead function", func)
self.changed = True
return None, None
return name, func
class DeadCodeFuncEliminator(FuncVisitor):
def visit(self, func):
<|code_end|>
using the current file's imports:
from .visitor import TopVisitor, FuncVisitor, BlockVisitor
from .core import *
from .instructions import *
from collections import defaultdict
and any relevant context from other files:
# Path: cmd_ir/visitor.py
# class TopVisitor:
#
# def visit(self, top):
# self.visit_preamble(top.preamble)
# return top.transform_scope(self.visit_var)
#
# def visit_preamble(self, preamble):
# pass
#
# def visit_var(self, name, var):
# if isinstance(var, IRFunction):
# return self.visit_function(name, var)
# if isinstance(var, GlobalVariable):
# return self.visit_global(name, var)
# return name, var
#
# def visit_function(self, name, func):
# return name, func
#
# def visit_global(self, name, var):
# return name, var
#
# class FuncVisitor:
#
# def visit(self, func):
# self.visit_preamble(func.preamble)
# for fn in func.get_compiletimes():
# self.visit_compiletime(fn)
# return func.transform_scope(self.visit_var)
#
# def visit_preamble(self, preamble):
# pass
#
# def visit_compiletime(self, compiletime):
# pass
#
# def visit_var(self, name, var):
# if isinstance(var, BasicBlock):
# return self.visit_block(name, var)
# if isinstance(var, LocalVariable):
# return self.visit_local_var(name, var)
# return name, var
#
# def visit_local_var(self, name, var):
# return name, var
#
# def visit_block(self, name, block):
# return name, block
#
# class BlockVisitor:
#
# def visit(self, block):
# self._block = block
# return block.transform(self.visit_insn)
#
# def visit_insn(self, insn):
# return insn
. Output only the next line. | self.changed = False |
Using the snippet: <|code_start|> def visit_insn(self, insn):
new_attach = self.reattach_block
if isinstance(insn, Invoke) and insn.func.is_inline:
deferred = isinstance(insn, DeferredInvoke)
#print("Inlining invoke to function:", insn.func)
entry, exit = self.inline_function(insn.func, insn.fnargs,
insn.retvars)
if deferred:
exit.add(Branch(insn.retblock))
exit = insn.retblock
new_attach = exit
insn = Branch(entry)
insn.declare()
if self.reattach_block is not None:
self.reattach_block.insns.append(insn)
insn = None
self.reattach_block = new_attach
return insn
def inline_function(self, func, args, retvars):
return func.inline_into(self._block._func, args, retvars)
class BranchEliminator(BlockVisitor):
def visit_insn(self, insn):
if isinstance(insn, Branch):
if insn.label.is_empty():
#print("Empty", insn.label)
return None
if isinstance(insn, (CmpBr, RangeBr)):
<|code_end|>
, determine the next line of code. You have imports:
from .visitor import TopVisitor, FuncVisitor, BlockVisitor
from .core import *
from .instructions import *
from collections import defaultdict
and context (class names, function names, or code) available:
# Path: cmd_ir/visitor.py
# class TopVisitor:
#
# def visit(self, top):
# self.visit_preamble(top.preamble)
# return top.transform_scope(self.visit_var)
#
# def visit_preamble(self, preamble):
# pass
#
# def visit_var(self, name, var):
# if isinstance(var, IRFunction):
# return self.visit_function(name, var)
# if isinstance(var, GlobalVariable):
# return self.visit_global(name, var)
# return name, var
#
# def visit_function(self, name, func):
# return name, func
#
# def visit_global(self, name, var):
# return name, var
#
# class FuncVisitor:
#
# def visit(self, func):
# self.visit_preamble(func.preamble)
# for fn in func.get_compiletimes():
# self.visit_compiletime(fn)
# return func.transform_scope(self.visit_var)
#
# def visit_preamble(self, preamble):
# pass
#
# def visit_compiletime(self, compiletime):
# pass
#
# def visit_var(self, name, var):
# if isinstance(var, BasicBlock):
# return self.visit_block(name, var)
# if isinstance(var, LocalVariable):
# return self.visit_local_var(name, var)
# return name, var
#
# def visit_local_var(self, name, var):
# return name, var
#
# def visit_block(self, name, block):
# return name, block
#
# class BlockVisitor:
#
# def visit(self, block):
# self._block = block
# return block.transform(self.visit_insn)
#
# def visit_insn(self, insn):
# return insn
. Output only the next line. | copy = insn.copy() |
Given the code snippet: <|code_start|> self.data.aliases[block] = insn.func
#print("Alias", block, "to", insn.func)
# Blocks that have one instruction that generates one command
# are recorded for exec_run substitution
if insn.single_command():
self.changed |= block not in self.data.cmd_aliases
self.data.cmd_aliases.add(block)
#print("Alias", block, "to insn", insn)
return name, block
class AliasRewriter(BlockVisitor):
def __init__(self, data):
self.data = data
def visit(self, block):
self.block = block
return super().visit(block)
def visit_insn(self, insn):
new = insn.copy()
changed = False
for arg in new.query(FunctionLike):
if arg.val in self.data.aliases:
changed = True
#print("Alias re", arg.val, "to", self.data.aliases[arg.val])
# If the inliner detected an invoke, we need to replace branch
# with invoke
if isinstance(insn, Branch) and \
<|code_end|>
, generate the next line using the imports in this file:
from .visitor import TopVisitor, FuncVisitor, BlockVisitor
from .core import *
from .instructions import *
from collections import defaultdict
and context (functions, classes, or occasionally code) from other files:
# Path: cmd_ir/visitor.py
# class TopVisitor:
#
# def visit(self, top):
# self.visit_preamble(top.preamble)
# return top.transform_scope(self.visit_var)
#
# def visit_preamble(self, preamble):
# pass
#
# def visit_var(self, name, var):
# if isinstance(var, IRFunction):
# return self.visit_function(name, var)
# if isinstance(var, GlobalVariable):
# return self.visit_global(name, var)
# return name, var
#
# def visit_function(self, name, func):
# return name, func
#
# def visit_global(self, name, var):
# return name, var
#
# class FuncVisitor:
#
# def visit(self, func):
# self.visit_preamble(func.preamble)
# for fn in func.get_compiletimes():
# self.visit_compiletime(fn)
# return func.transform_scope(self.visit_var)
#
# def visit_preamble(self, preamble):
# pass
#
# def visit_compiletime(self, compiletime):
# pass
#
# def visit_var(self, name, var):
# if isinstance(var, BasicBlock):
# return self.visit_block(name, var)
# if isinstance(var, LocalVariable):
# return self.visit_local_var(name, var)
# return name, var
#
# def visit_local_var(self, name, var):
# return name, var
#
# def visit_block(self, name, block):
# return name, block
#
# class BlockVisitor:
#
# def visit(self, block):
# self._block = block
# return block.transform(self.visit_insn)
#
# def visit_insn(self, insn):
# return insn
. Output only the next line. | isinstance(self.data.aliases[arg.val], VisibleFunction): |
Continue the code snippet: <|code_start|>
def asm(visitor, expr):
assert expr.args, "__asm__ takes at least 1 argument"
asm = visitor.visit_expression(expr.args[0])
assert isinstance(asm, IR.LiteralString),\
"__asm__ called with non-constant string"
asm = asm.val
idx = 1
elements = []
while True:
ind = asm.find('?')
if ind == -1:
break
arg = visitor.visit_expression(expr.args[idx])
idx += 1
start, end = ind, ind+1
is_dest, write_only = False, False
if ind > 0 and asm[ind - 1] == '>':
start -= 1
is_dest = True
if ind > 1 and asm[ind - 2] == '!':
start -= 1
write_only = True
<|code_end|>
. Use current file imports:
from ..ir import IR
and context (classes, functions, or code) from other files:
# Path: c_comp/ir.py
# class IR:
#
# _counter = 0
#
# FunctionBegin = namedtuple('FunctionBegin', 'name storage pragma')
# FunctionEnd = namedtuple('FunctionEnd', '')
#
# Label = namedtuple('Label', 'label')
# EntityLocalVar = namedtuple('EntityLocalVar', 'name offset specific')
#
# Jump = namedtuple('Jump', 'dest')
# JumpIf = namedtuple('JumpIf', 'dest cond')
# JumpIfNot = namedtuple('JumpIfNot', 'dest cond')
#
# Push = namedtuple('Push', 'src')
# Pop = namedtuple('Pop', 'dest')
# Call = namedtuple('Call', 'name')
# Return = namedtuple('Return', '')
# Print = namedtuple('Print', 'args')
#
# Move = namedtuple('Move', 'src dest')
#
# Sync = namedtuple('Sync', '')
# Test = namedtuple('Test', 'cmd dest')
# Asm = namedtuple('Asm', 'args')
# ExecSel = namedtuple('ExecSel', 'label exec_type sel_type args')
# ExecEnd = namedtuple('ExecSelEnd', 'label')
# ExecChain = namedtuple('ExecChain', 'label exec_type args')
#
# StackPointer = namedtuple('StackPointer', 'type')(IntType())
# BasePointer = namedtuple('BasePointer', 'type')(IntType())
# GlobalIndex = namedtuple('GlobalIndex', 'type')(IntType())
# EntityLocalBase = namedtuple('EntityLocalBase', 'type')(IntType())
# ReturnRegister = namedtuple('ReturnRegister', 'type')(IntType())
#
# SlotOffset = namedtuple('SlotOffset', 'base offset type')
# GlobalSlot = namedtuple('GlobalSlot', 'offset type')
# EntityLocalSlot = namedtuple('EntityLocalSlot', 'offset type')
# Dereference = namedtuple('Dereference', 'addr type')
# Free = namedtuple('Free', 'slot')
#
# class Slot(namedtuple('Slot', 'idx type')):
# def __new__(cls, type):
# IR._counter += 1
# return tuple.__new__(cls, (IR._counter, type))
#
# Operation = namedtuple('Operation', 'op left right dest')
# UnaryOperation = namedtuple('UnaryOperation', 'op val dest')
#
# LiteralString = namedtuple('LiteralString', 'val type')
# LiteralInt = namedtuple('LiteralInt', 'val type')
#
# class Op:
#
# Add = namedtuple('Add', '')()
# Sub = namedtuple('Sub', '')()
# Mul = namedtuple('Mul', '')()
# Div = namedtuple('Div', '')()
# Mod = namedtuple('Mod', '')()
# Shl = namedtuple('Shl', '')()
# Shr = namedtuple('Shr', '')()
# And = namedtuple('And', '')()
# Xor = namedtuple('Xor', '')()
# Or = namedtuple('Or', '')()
# Eq = namedtuple('Eq', '')()
# Neq = namedtuple('Neq', '')()
# Lt = namedtuple('Lt', '')()
# Gt = namedtuple('Gt', '')()
# LtEq = namedtuple('LtEq', '')()
# GtEq = namedtuple('GtEq', '')()
# LogOr = namedtuple('LogOr', '')()
# LogAnd = namedtuple('LogAnd', '')()
#
# @classmethod
# def lookup(cls, op):
# return {
# '+': cls.Add,
# '-': cls.Sub,
# '*': cls.Mul,
# '/': cls.Div,
# '%': cls.Mod,
# '<<': cls.Shl,
# '>>': cls.Shr,
# '&': cls.And,
# '^': cls.Xor,
# '|': cls.Or,
# '==': cls.Eq,
# '!=': cls.Neq,
# '<': cls.Lt,
# '>': cls.Gt,
# '<=': cls.LtEq,
# '>=': cls.GtEq,
# '||': cls.LogOr,
# '&&': cls.LogAnd
# }[op]
#
# class UnaryOp:
#
# AddrOf = namedtuple('AddrOf', '')()
# Deref = namedtuple('Deref', '')()
# IntPromote = namedtuple('IntPromote', '')()
# Negate = namedtuple('Negate', '')()
# Not = namedtuple('Not', '')()
# LogNot = namedtuple('LogNot', '')()
#
#
# @classmethod
# def lookup(cls, op):
# return {
# '&': cls.AddrOf,
# '*': cls.Deref,
# '+': cls.IntPromote,
# '-': cls.Negate,
# '~': cls.Not,
# '!': cls.LogNot
# }[op]
. Output only the next line. | before = asm[:start] |
Continue the code snippet: <|code_start|> for arg in args:
if type(arg) in [str, int, float]:
self._components.append(str(arg))
elif isinstance(arg, Resolvable):
self._components.append(arg)
else:
assert False, type(arg)
return self
def run(self, cmd):
self.add('run', cmd)
return Execute(self)
def finish(self):
assert self.can_terminate
return Execute(self)
def as_entity(self, select_arg):
self.can_terminate = False
return self.add('as', ensure_selector(select_arg))
def at(self, select_arg):
self.can_terminate = False
return self.add('at', ensure_selector(select_arg))
def at_pos(self, pos):
self.can_terminate = False
return self.add('positioned', pos)
def at_entity_pos(self, select_arg):
<|code_end|>
. Use current file imports:
from .core import Command, Resolvable, EntityRef, SimpleResolve, WorldPos
from .nbt import NBTStorable
from .scoreboard import ScoreRef
from .selector import ScoreRange
and context (classes, functions, or code) from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class SimpleResolve(Resolvable):
#
# def __init__(self, *args):
# self.args = args
#
# def resolve(self, scope):
# return ' '.join(map(lambda el: el.resolve(scope) \
# if isinstance(el, Resolvable) \
# else el, self.args))
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
#
# Path: commands/nbt.py
# class NBTStorable(Resolvable):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/selector.py
# class ScoreRange(Resolvable):
#
# def __init__(self, min=None, max=None):
# assert min is not None or max is not None
# self.min = min
# self.max = max
#
# def resolve(self, scope):
# range = ''
# if self.min is not None:
# range = '%d' % self.min
# if self.max is not None and self.max != self.min:
# range += '..%d' % self.max
# elif self.max is None:
# range += '..'
# return range
. Output only the next line. | self.can_terminate = False |
Here is a snippet: <|code_start|> def __init__(self, parent, cond_type):
self.parent = parent
self.cond_type = cond_type
def entity(self, entityref):
return self.add('entity', ensure_selector(entityref))
def score(self, targetref, operator, sourceref):
assert isinstance(targetref, ScoreRef)
assert isinstance(sourceref, ScoreRef)
assert operator in ['<', '<=', '=', '>=', '>']
return self.add('score', targetref, operator, sourceref)
def score_range(self, scoreref, range):
assert isinstance(scoreref, ScoreRef)
assert isinstance(range, ScoreRange)
return self.add('score', scoreref, 'matches', range)
def block(self, pos, block):
assert isinstance(pos, WorldPos) and pos.block_pos
return self.add('block', pos, block)
def blocks_match(self, begin, end, dest, type):
assert type in ['all', 'masked']
return self.add('blocks', begin, end, dest, type)
def data(self, dataref, path):
assert isinstance(dataref, NBTStorable)
return self.add('data', dataref, path)
<|code_end|>
. Write the next line using the current file imports:
from .core import Command, Resolvable, EntityRef, SimpleResolve, WorldPos
from .nbt import NBTStorable
from .scoreboard import ScoreRef
from .selector import ScoreRange
and context from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class SimpleResolve(Resolvable):
#
# def __init__(self, *args):
# self.args = args
#
# def resolve(self, scope):
# return ' '.join(map(lambda el: el.resolve(scope) \
# if isinstance(el, Resolvable) \
# else el, self.args))
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
#
# Path: commands/nbt.py
# class NBTStorable(Resolvable):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/selector.py
# class ScoreRange(Resolvable):
#
# def __init__(self, min=None, max=None):
# assert min is not None or max is not None
# self.min = min
# self.max = max
#
# def resolve(self, scope):
# range = ''
# if self.min is not None:
# range = '%d' % self.min
# if self.max is not None and self.max != self.min:
# range += '..%d' % self.max
# elif self.max is None:
# range += '..'
# return range
, which may include functions, classes, or code. Output only the next line. | def store(self, store_type): |
Continue the code snippet: <|code_start|> def block(self, pos, block):
assert isinstance(pos, WorldPos) and pos.block_pos
return self.add('block', pos, block)
def blocks_match(self, begin, end, dest, type):
assert type in ['all', 'masked']
return self.add('blocks', begin, end, dest, type)
def data(self, dataref, path):
assert isinstance(dataref, NBTStorable)
return self.add('data', dataref, path)
def store(self, store_type):
assert store_type in ['result', 'success']
self.can_terminate = False
return ExecuteChain.Store(self, store_type)
class Store:
def add(self, *args):
return self.parent.add(*(('store', self.store_type) + args))
def __init__(self, parent, store_type):
self.parent = parent
self.store_type = store_type
def score(self, scoreref):
assert isinstance(scoreref, ScoreRef)
return self.add('score', scoreref)
<|code_end|>
. Use current file imports:
from .core import Command, Resolvable, EntityRef, SimpleResolve, WorldPos
from .nbt import NBTStorable
from .scoreboard import ScoreRef
from .selector import ScoreRange
and context (classes, functions, or code) from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class SimpleResolve(Resolvable):
#
# def __init__(self, *args):
# self.args = args
#
# def resolve(self, scope):
# return ' '.join(map(lambda el: el.resolve(scope) \
# if isinstance(el, Resolvable) \
# else el, self.args))
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
#
# Path: commands/nbt.py
# class NBTStorable(Resolvable):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/selector.py
# class ScoreRange(Resolvable):
#
# def __init__(self, min=None, max=None):
# assert min is not None or max is not None
# self.min = min
# self.max = max
#
# def resolve(self, scope):
# range = ''
# if self.min is not None:
# range = '%d' % self.min
# if self.max is not None and self.max != self.min:
# range += '..%d' % self.max
# elif self.max is None:
# range += '..'
# return range
. Output only the next line. | def nbt(self, storeref, path, data_type, scale=1): |
Given the code snippet: <|code_start|> self.can_terminate = False
return self.add('as', ensure_selector(select_arg))
def at(self, select_arg):
self.can_terminate = False
return self.add('at', ensure_selector(select_arg))
def at_pos(self, pos):
self.can_terminate = False
return self.add('positioned', pos)
def at_entity_pos(self, select_arg):
self.can_terminate = False
return self.add('positioned', 'as', ensure_selector(select_arg))
def align(self, axes):
self.can_terminate = False
assert ''.join(axis for axis in axes if axis in 'xyz') == axes
return self.add('align', axes)
def facing(self, pos):
self.can_terminate = False
return self.add('facing', pos)
def facing_entity(self, select_arg, feature):
self.can_terminate = False
assert feature == 'eyes' or feature == 'feet'
return self.add('facing', 'entity', ensure_selector(select_arg), \
feature)
<|code_end|>
, generate the next line using the imports in this file:
from .core import Command, Resolvable, EntityRef, SimpleResolve, WorldPos
from .nbt import NBTStorable
from .scoreboard import ScoreRef
from .selector import ScoreRange
and context (functions, classes, or occasionally code) from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class SimpleResolve(Resolvable):
#
# def __init__(self, *args):
# self.args = args
#
# def resolve(self, scope):
# return ' '.join(map(lambda el: el.resolve(scope) \
# if isinstance(el, Resolvable) \
# else el, self.args))
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
#
# Path: commands/nbt.py
# class NBTStorable(Resolvable):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/selector.py
# class ScoreRange(Resolvable):
#
# def __init__(self, min=None, max=None):
# assert min is not None or max is not None
# self.min = min
# self.max = max
#
# def resolve(self, scope):
# range = ''
# if self.min is not None:
# range = '%d' % self.min
# if self.max is not None and self.max != self.min:
# range += '..%d' % self.max
# elif self.max is None:
# range += '..'
# return range
. Output only the next line. | def rotated(self, y, x): |
Given the code snippet: <|code_start|> def __init__(self, parent, cond_type):
self.parent = parent
self.cond_type = cond_type
def entity(self, entityref):
return self.add('entity', ensure_selector(entityref))
def score(self, targetref, operator, sourceref):
assert isinstance(targetref, ScoreRef)
assert isinstance(sourceref, ScoreRef)
assert operator in ['<', '<=', '=', '>=', '>']
return self.add('score', targetref, operator, sourceref)
def score_range(self, scoreref, range):
assert isinstance(scoreref, ScoreRef)
assert isinstance(range, ScoreRange)
return self.add('score', scoreref, 'matches', range)
def block(self, pos, block):
assert isinstance(pos, WorldPos) and pos.block_pos
return self.add('block', pos, block)
def blocks_match(self, begin, end, dest, type):
assert type in ['all', 'masked']
return self.add('blocks', begin, end, dest, type)
def data(self, dataref, path):
assert isinstance(dataref, NBTStorable)
return self.add('data', dataref, path)
<|code_end|>
, generate the next line using the imports in this file:
from .core import Command, Resolvable, EntityRef, SimpleResolve, WorldPos
from .nbt import NBTStorable
from .scoreboard import ScoreRef
from .selector import ScoreRange
and context (functions, classes, or occasionally code) from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class SimpleResolve(Resolvable):
#
# def __init__(self, *args):
# self.args = args
#
# def resolve(self, scope):
# return ' '.join(map(lambda el: el.resolve(scope) \
# if isinstance(el, Resolvable) \
# else el, self.args))
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
#
# Path: commands/nbt.py
# class NBTStorable(Resolvable):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/selector.py
# class ScoreRange(Resolvable):
#
# def __init__(self, min=None, max=None):
# assert min is not None or max is not None
# self.min = min
# self.max = max
#
# def resolve(self, scope):
# range = ''
# if self.min is not None:
# range = '%d' % self.min
# if self.max is not None and self.max != self.min:
# range += '..%d' % self.max
# elif self.max is None:
# range += '..'
# return range
. Output only the next line. | def store(self, store_type): |
Next line prediction: <|code_start|>
class Cond:
def add(self, *args):
self.parent.can_terminate = True
return self.parent.add(*((self.cond_type,) + args))
def __init__(self, parent, cond_type):
self.parent = parent
self.cond_type = cond_type
def entity(self, entityref):
return self.add('entity', ensure_selector(entityref))
def score(self, targetref, operator, sourceref):
assert isinstance(targetref, ScoreRef)
assert isinstance(sourceref, ScoreRef)
assert operator in ['<', '<=', '=', '>=', '>']
return self.add('score', targetref, operator, sourceref)
def score_range(self, scoreref, range):
assert isinstance(scoreref, ScoreRef)
assert isinstance(range, ScoreRange)
return self.add('score', scoreref, 'matches', range)
def block(self, pos, block):
assert isinstance(pos, WorldPos) and pos.block_pos
return self.add('block', pos, block)
def blocks_match(self, begin, end, dest, type):
<|code_end|>
. Use current file imports:
(from .core import Command, Resolvable, EntityRef, SimpleResolve, WorldPos
from .nbt import NBTStorable
from .scoreboard import ScoreRef
from .selector import ScoreRange)
and context including class names, function names, or small code snippets from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class SimpleResolve(Resolvable):
#
# def __init__(self, *args):
# self.args = args
#
# def resolve(self, scope):
# return ' '.join(map(lambda el: el.resolve(scope) \
# if isinstance(el, Resolvable) \
# else el, self.args))
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
#
# Path: commands/nbt.py
# class NBTStorable(Resolvable):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/selector.py
# class ScoreRange(Resolvable):
#
# def __init__(self, min=None, max=None):
# assert min is not None or max is not None
# self.min = min
# self.max = max
#
# def resolve(self, scope):
# range = ''
# if self.min is not None:
# range = '%d' % self.min
# if self.max is not None and self.max != self.min:
# range += '..%d' % self.max
# elif self.max is None:
# range += '..'
# return range
. Output only the next line. | assert type in ['all', 'masked'] |
Predict the next line after this snippet: <|code_start|>
def finish(self):
assert self.can_terminate
return Execute(self)
def as_entity(self, select_arg):
self.can_terminate = False
return self.add('as', ensure_selector(select_arg))
def at(self, select_arg):
self.can_terminate = False
return self.add('at', ensure_selector(select_arg))
def at_pos(self, pos):
self.can_terminate = False
return self.add('positioned', pos)
def at_entity_pos(self, select_arg):
self.can_terminate = False
return self.add('positioned', 'as', ensure_selector(select_arg))
def align(self, axes):
self.can_terminate = False
assert ''.join(axis for axis in axes if axis in 'xyz') == axes
return self.add('align', axes)
def facing(self, pos):
self.can_terminate = False
return self.add('facing', pos)
<|code_end|>
using the current file's imports:
from .core import Command, Resolvable, EntityRef, SimpleResolve, WorldPos
from .nbt import NBTStorable
from .scoreboard import ScoreRef
from .selector import ScoreRange
and any relevant context from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class SimpleResolve(Resolvable):
#
# def __init__(self, *args):
# self.args = args
#
# def resolve(self, scope):
# return ' '.join(map(lambda el: el.resolve(scope) \
# if isinstance(el, Resolvable) \
# else el, self.args))
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
#
# Path: commands/nbt.py
# class NBTStorable(Resolvable):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/selector.py
# class ScoreRange(Resolvable):
#
# def __init__(self, min=None, max=None):
# assert min is not None or max is not None
# self.min = min
# self.max = max
#
# def resolve(self, scope):
# range = ''
# if self.min is not None:
# range = '%d' % self.min
# if self.max is not None and self.max != self.min:
# range += '..%d' % self.max
# elif self.max is None:
# range += '..'
# return range
. Output only the next line. | def facing_entity(self, select_arg, feature): |
Given snippet: <|code_start|>
def align(self, axes):
self.can_terminate = False
assert ''.join(axis for axis in axes if axis in 'xyz') == axes
return self.add('align', axes)
def facing(self, pos):
self.can_terminate = False
return self.add('facing', pos)
def facing_entity(self, select_arg, feature):
self.can_terminate = False
assert feature == 'eyes' or feature == 'feet'
return self.add('facing', 'entity', ensure_selector(select_arg), \
feature)
def rotated(self, y, x):
self.can_terminate = False
return self.add('rotated', y, x)
def rotated_as_entity(self, select_arg):
self.can_terminate = False
return self.add('rotated', 'as', ensure_selector(select_arg))
def anchored(self, anchor):
self.can_terminate = False
assert anchor == 'feet' or anchor == 'eyes'
return self.add('anchored', anchor)
def cond(self, cond_type):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .core import Command, Resolvable, EntityRef, SimpleResolve, WorldPos
from .nbt import NBTStorable
from .scoreboard import ScoreRef
from .selector import ScoreRange
and context:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class SimpleResolve(Resolvable):
#
# def __init__(self, *args):
# self.args = args
#
# def resolve(self, scope):
# return ' '.join(map(lambda el: el.resolve(scope) \
# if isinstance(el, Resolvable) \
# else el, self.args))
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
#
# Path: commands/nbt.py
# class NBTStorable(Resolvable):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/selector.py
# class ScoreRange(Resolvable):
#
# def __init__(self, min=None, max=None):
# assert min is not None or max is not None
# self.min = min
# self.max = max
#
# def resolve(self, scope):
# range = ''
# if self.min is not None:
# range = '%d' % self.min
# if self.max is not None and self.max != self.min:
# range += '..%d' % self.max
# elif self.max is None:
# range += '..'
# return range
which might include code, classes, or functions. Output only the next line. | self.can_terminate = False |
Continue the code snippet: <|code_start|>
ASSIGN_OP = set(('*=', '/=', '%=', '+=', '-=', '<<=', '>>=', '&=', '^=', '|='))
def as_var(container):
return container.type.as_variable(container.value)
class NativeType:
def __repr__(self):
return self.__class__.__name__
def instantiate(self, compiler, args):
assert not args, "%s does not take arguments" % self
return self
@property
def typename(self):
return self.__typename
@typename.setter
def typename(self, name):
self.__typename = name
meta = self.metatype
<|code_end|>
. Use current file imports:
from .containers import Temporary
from .util import safe_typename
and context (classes, functions, or code) from other files:
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
#
# Path: cbl/util.py
# def safe_typename(type):
# return ''.join(map(lambda c: '_%s_' % op_name[c] if c in op_name else c,
# type.typename))
. Output only the next line. | if meta is not None: |
Based on the snippet: <|code_start|>ASSIGN_OP = set(('*=', '/=', '%=', '+=', '-=', '<<=', '>>=', '&=', '^=', '|='))
def as_var(container):
return container.type.as_variable(container.value)
class NativeType:
def __repr__(self):
return self.__class__.__name__
def instantiate(self, compiler, args):
assert not args, "%s does not take arguments" % self
return self
@property
def typename(self):
return self.__typename
@typename.setter
def typename(self, name):
self.__typename = name
meta = self.metatype
if meta is not None:
meta.typename = name + '--meta'
def allocate(self, compiler, namehint):
assert False, "%s is not allocatable" % self.typename
@property
def metatype(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from .containers import Temporary
from .util import safe_typename
and context (classes, functions, sometimes code) from other files:
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
#
# Path: cbl/util.py
# def safe_typename(type):
# return ''.join(map(lambda c: '_%s_' % op_name[c] if c in op_name else c,
# type.typename))
. Output only the next line. | return None |
Predict the next line for this snippet: <|code_start|> def __init__(self):
self.func_count = 0
self.command_count = 0
def open(self):
pass
def close(self):
pass
def write_function(self, nsname, command_list):
self.func_count += 1
self.command_count += len(command_list)
def write_advancement(self, advancement):
pass
def write_tag(self, type, nsname, values, replace=False):
pass
def write_mcc_meta(self, meta):
pass
class DebugWriterWrapper:
def __init__(self, writer):
self.writer = writer
@property
def func_count(self):
<|code_end|>
with the help of current file imports:
import io
import os
import json
import zipfile
from .placer import Rel
and context from other files:
# Path: packer/placer.py
# class Rel:
# def __init__(self, offset=0):
# self.offset = offset
#
# def __add__(self, other):
# return Rel(self.offset + other)
#
# def __sub__(self, other):
# return Rel(self.offset - other)
#
# def __str__(self):
# if self.offset == 0:
# return '~'
# return '~%d' % self.offset
, which may contain function names, class names, or code. Output only the next line. | return self.writer.func_count |
Predict the next line after this snippet: <|code_start|> with self.compiler.scope:
for decl in children:
self.compiler.transform(decl)
def native_definition(self, func_decl, py_code):
assert func_decl.typespace is not None
assert py_code
py_code = 'def run():\n' + py_code + '\n__result__ = run()'
code = compile(py_code, 'native.py', 'exec')
intrinsic = NativeExec(func_decl.params, code)
t = func_decl.typespace
if isinstance(func_decl, CtorDeclaration):
fn = t.lookup_constructor(func_decl.params)
elif func_decl.is_operator:
fn = t.lookup_operator(func_decl.name, func_decl.params)
else:
fn = t.lookup_function_member(func_decl.name, func_decl.params)
# Possibly refactor this
# Lookup the static members to support intrinsic singleton funcs
if fn is None:
fn = t.metatype.lookup_function_member(func_decl.name,
func_decl.params)
if fn is None:
raise TypeError('Cannot find function member for %s' % (func_decl,))
type, func = fn
func.set_as_intrinsic(intrinsic)
def type_configure(self, type_name, py_code):
exec('if True:\n' + py_code, {
'the_type': type_name,
<|code_end|>
using the current file's imports:
from collections import namedtuple
from .function_type import IntrinsicFunction
from .containers import InstanceSymbol, Temporary
from cmd_ir.core import CompileTimeFunction
from .compiler import CtorDeclaration
import contextlib
import cmd_ir.instructions as i
and any relevant context from other files:
# Path: cbl/function_type.py
# class IntrinsicFunction(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def invoke(self, compiler, container, args):
# pass
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
. Output only the next line. | 'i': i, |
Next line prediction: <|code_start|> def __init__(self, params, code):
self.param_t = namedtuple('Args', (p.name for p in params))
self.code = code
def invoke(self, compiler, instance, args):
# "this" not present in static functions
have_this = isinstance(instance, InstanceSymbol)
if have_this:
thisarg = args[0]
args = args[1:] # remove 'this' arg
scope = dict(args=self.param_t(*args),
i=i,
compiler=compiler,
_instance=instance,
compiletime=_compiletime_context(compiler),
void=Temporary(compiler.type('void'), None),
__name__=__name__)
if have_this:
scope['this'] = instance.this
scope['thisarg'] = thisarg
local_res = {}
exec(self.code, scope, local_res)
return local_res['__result__']
@contextlib.contextmanager
def _compiletime_context(compiler):
# Copied from MacroType
old_func = compiler.func
old_block = compiler.block
fn = compiler.func
<|code_end|>
. Use current file imports:
(from collections import namedtuple
from .function_type import IntrinsicFunction
from .containers import InstanceSymbol, Temporary
from cmd_ir.core import CompileTimeFunction
from .compiler import CtorDeclaration
import contextlib
import cmd_ir.instructions as i)
and context including class names, function names, or small code snippets from other files:
# Path: cbl/function_type.py
# class IntrinsicFunction(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def invoke(self, compiler, container, args):
# pass
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
. Output only the next line. | in_compiletime = isinstance(fn, CompileTimeFunction) |
Given the code snippet: <|code_start|>
class NativeExec(IntrinsicFunction):
def __init__(self, params, code):
self.param_t = namedtuple('Args', (p.name for p in params))
self.code = code
def invoke(self, compiler, instance, args):
# "this" not present in static functions
have_this = isinstance(instance, InstanceSymbol)
if have_this:
thisarg = args[0]
args = args[1:] # remove 'this' arg
scope = dict(args=self.param_t(*args),
i=i,
compiler=compiler,
_instance=instance,
compiletime=_compiletime_context(compiler),
void=Temporary(compiler.type('void'), None),
__name__=__name__)
if have_this:
scope['this'] = instance.this
scope['thisarg'] = thisarg
local_res = {}
exec(self.code, scope, local_res)
<|code_end|>
, generate the next line using the imports in this file:
from collections import namedtuple
from .function_type import IntrinsicFunction
from .containers import InstanceSymbol, Temporary
from cmd_ir.core import CompileTimeFunction
from .compiler import CtorDeclaration
import contextlib
import cmd_ir.instructions as i
and context (functions, classes, or occasionally code) from other files:
# Path: cbl/function_type.py
# class IntrinsicFunction(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def invoke(self, compiler, container, args):
# pass
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
. Output only the next line. | return local_res['__result__'] |
Based on the snippet: <|code_start|>
class Scoreboard(Command):
allows_negative = False
def __init__(self, varref, value):
assert isinstance(varref, ScoreRef)
assert isinstance(value, int)
assert self.allows_negative or value >= 0
self.var = varref
self.value = value
def resolve(self, scope):
return 'scoreboard players %s %s %d' % (
self.op, self.var.resolve(scope), self.value)
class SetConst(Scoreboard):
op = 'set'
allows_negative = True
class AddConst(Scoreboard):
op = 'add'
class RemConst(Scoreboard):
op = 'remove'
class GetValue(Command):
def __init__(self, scoreref):
assert isinstance(scoreref, ScoreRef)
<|code_end|>
, predict the immediate next line with the help of imports:
from .core import Command, Resolvable, EntityRef, GlobalEntity
and context (classes, functions, sometimes code) from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class GlobalEntity(EntityRef):
#
# def __init__(self, namespace):
# self.namespace = namespace
#
# def is_single_entity(self, scope):
# return True
#
# def resolve(self, scope):
# return scope.global_entity(self.namespace)
. Output only the next line. | self.ref = scoreref |
Predict the next line after this snippet: <|code_start|> return 'scoreboard players %s %s %d' % (
self.op, self.var.resolve(scope), self.value)
class SetConst(Scoreboard):
op = 'set'
allows_negative = True
class AddConst(Scoreboard):
op = 'add'
class RemConst(Scoreboard):
op = 'remove'
class GetValue(Command):
def __init__(self, scoreref):
assert isinstance(scoreref, ScoreRef)
self.ref = scoreref
def resolve(self, scope):
return 'scoreboard players get %s' % self.ref.resolve(scope)
class Operation(Command):
def __init__(self, left, right):
assert isinstance(left, ScoreRef)
assert isinstance(right, ScoreRef)
self.left = left
self.right = right
def resolve(self, scope):
<|code_end|>
using the current file's imports:
from .core import Command, Resolvable, EntityRef, GlobalEntity
and any relevant context from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class GlobalEntity(EntityRef):
#
# def __init__(self, namespace):
# self.namespace = namespace
#
# def is_single_entity(self, scope):
# return True
#
# def resolve(self, scope):
# return scope.global_entity(self.namespace)
. Output only the next line. | return 'scoreboard players operation %s %s %s' % ( |
Here is a snippet: <|code_start|>
class Scoreboard(Command):
allows_negative = False
def __init__(self, varref, value):
assert isinstance(varref, ScoreRef)
assert isinstance(value, int)
assert self.allows_negative or value >= 0
self.var = varref
self.value = value
def resolve(self, scope):
<|code_end|>
. Write the next line using the current file imports:
from .core import Command, Resolvable, EntityRef, GlobalEntity
and context from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class GlobalEntity(EntityRef):
#
# def __init__(self, namespace):
# self.namespace = namespace
#
# def is_single_entity(self, scope):
# return True
#
# def resolve(self, scope):
# return scope.global_entity(self.namespace)
, which may include functions, classes, or code. Output only the next line. | return 'scoreboard players %s %s %d' % ( |
Predict the next line for this snippet: <|code_start|> assert isinstance(scoreref, ScoreRef)
self.ref = scoreref
def resolve(self, scope):
return 'scoreboard players get %s' % self.ref.resolve(scope)
class Operation(Command):
def __init__(self, left, right):
assert isinstance(left, ScoreRef)
assert isinstance(right, ScoreRef)
self.left = left
self.right = right
def resolve(self, scope):
return 'scoreboard players operation %s %s %s' % (
self.left.resolve(scope), self.op, self.right.resolve(scope))
class OpAssign(Operation): op = '='
class OpAdd(Operation): op = '+='
class OpSub(Operation): op = '-='
class OpMul(Operation): op = '*='
class OpDiv(Operation): op = '/='
class OpMod(Operation): op = '%='
class OpIfLt(Operation): op = '<'
class OpIfGt(Operation): op = '>'
class OpSwap(Operation): op = '><'
class ObjectiveRef(Resolvable):
def __init__(self, name):
<|code_end|>
with the help of current file imports:
from .core import Command, Resolvable, EntityRef, GlobalEntity
and context from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class GlobalEntity(EntityRef):
#
# def __init__(self, namespace):
# self.namespace = namespace
#
# def is_single_entity(self, scope):
# return True
#
# def resolve(self, scope):
# return scope.global_entity(self.namespace)
, which may contain function names, class names, or code. Output only the next line. | assert type(name) == str |
Using the snippet: <|code_start|> def match_arguments(self, compiler, container, args):
assert False
class FunctionType(NativeType, Invokable):
def __init__(self, ret_type, params, inline, is_async):
self.ret_type = ret_type
self.params = tuple(params)
self.is_inline = inline
self.is_async = is_async
self.is_intrinsic = False
def param_str(self):
return '(%s)' % ', '.join('%s %s%s' % (p.type.typename,
'&' if p.by_ref else '',
p.name) \
for p in self.params)
def allocate(self, compiler, namehint):
return FunctionContainer(self, compiler, namehint)
def intrinsic_invoke(self, container, args):
assert self.is_intrinsic, "Function is not intrinsic"
return container.value.intrinsic_invoke(container, args)
def invoke(self, container, args, ret_args):
assert not self.is_intrinsic, "Cannot call invoke on intrinsic"
return container.value.invoke(args, ret_args)
def match_arguments(self, compiler, container, args):
<|code_end|>
, determine the next line of code. You have imports:
import abc
import cmd_ir.instructions as i
from .native_type import NativeType
from .containers import InstanceSymbol, Parameter, Temporary
from .macro_type import MacroType
and context (class names, function names, or code) available:
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
. Output only the next line. | matcher = FunctionMatcher(compiler, container.value.name) |
Given the code snippet: <|code_start|>
class Invokable:
def match_arguments(self, compiler, container, args):
assert False
class FunctionType(NativeType, Invokable):
def __init__(self, ret_type, params, inline, is_async):
self.ret_type = ret_type
self.params = tuple(params)
self.is_inline = inline
self.is_async = is_async
self.is_intrinsic = False
def param_str(self):
return '(%s)' % ', '.join('%s %s%s' % (p.type.typename,
'&' if p.by_ref else '',
p.name) \
for p in self.params)
<|code_end|>
, generate the next line using the imports in this file:
import abc
import cmd_ir.instructions as i
from .native_type import NativeType
from .containers import InstanceSymbol, Parameter, Temporary
from .macro_type import MacroType
and context (functions, classes, or occasionally code) from other files:
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
. Output only the next line. | def allocate(self, compiler, namehint): |
Using the snippet: <|code_start|> if param.type != arg.type:
match_all = False
break
if match_all:
return c, args
for c in candidates:
new_args = []
fail = False
for param, arg in zip(c.type.params, args):
new_arg = arg.type.coerce_to(self.compiler, arg, param.type)
if not new_arg:
fail = True
break
new_args.append(new_arg)
if not fail:
return c, new_args
arg_types = ', '.join(a.type.typename for a in args)
err = "Failed to find funtion overload of %s\n" % self.func_name
err += "Unable to satisfy arguments types: (%s)\n" % (arg_types,)
err += "Tried candidates:\n"
for c in self.candidates:
err += " %s%s\n" % (self.func_name, c.type.param_str())
raise TypeError(err)
class FunctionDispatchType(NativeType, Invokable):
def match_arguments(self, compiler, container, args):
# TODO possibly refactor
has_this = isinstance(container, InstanceSymbol)
if container.value._static:
<|code_end|>
, determine the next line of code. You have imports:
import abc
import cmd_ir.instructions as i
from .native_type import NativeType
from .containers import InstanceSymbol, Parameter, Temporary
from .macro_type import MacroType
and context (class names, function names, or code) available:
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
. Output only the next line. | assert not has_this |
Continue the code snippet: <|code_start|> def str_pairs(items):
output = []
for key, value in items:
if type(value) == dict:
value = '{%s}' % str_pairs(value.items())
output.append('%s=%s' % (key, value))
return ','.join(output)
return '%s[%s]' % (output, str_pairs(kwargs.items()))
class Selector(EntityRef):
def __init__(self, type, args=None):
assert type in 'aespr'
self.type = type
assert args is None or isinstance(args, SelectorArgs)
self.args = args
def resolve_params(self, scope):
if not self.args:
return {}
return self.args.resolve(scope)
def is_single_entity(self, scope):
if self.type in 'spr':
return True
params = self.resolve_params(scope)
return 'limit' in params and params['limit'] == '1'
def resolve(self, scope):
<|code_end|>
. Use current file imports:
from .core import Resolvable, EntityRef
from .scoreboard import ObjectiveRef
and context (classes, functions, or code) from other files:
# Path: commands/core.py
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# Path: commands/scoreboard.py
# class ObjectiveRef(Resolvable):
#
# def __init__(self, name):
# assert type(name) == str
# self.objective = name
#
# def resolve(self, scope):
# return scope.objective(self.objective)
. Output only the next line. | return make_selector(self.type, **self.resolve_params(scope)) |
Predict the next line for this snippet: <|code_start|>
def resolve(self, scope):
return {'scores': { self.objective.resolve(scope):
self.range.resolve(scope) }}
class SelEquals(SelRange):
def __init__(self, objective, value):
super().__init__(objective, value, value)
class ComboSelectorArgs(SelectorArgs):
@staticmethod
def new(first, second):
if first is None: return second
if second is None: return first
return ComboSelectorArgs(first, second)
def __init__(self, first, second):
self.first = first
self.second = second
def resolve(self, scope):
sel = {}
sel.update(self.first.resolve(scope))
sel.update(self.second.resolve(scope))
return sel
class SelNbt(SelectorArgs):
def __init__(self, path, value):
<|code_end|>
with the help of current file imports:
from .core import Resolvable, EntityRef
from .scoreboard import ObjectiveRef
and context from other files:
# Path: commands/core.py
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# Path: commands/scoreboard.py
# class ObjectiveRef(Resolvable):
#
# def __init__(self, name):
# assert type(name) == str
# self.objective = name
#
# def resolve(self, scope):
# return scope.objective(self.objective)
, which may contain function names, class names, or code. Output only the next line. | self.nbt_spec = {} |
Predict the next line for this snippet: <|code_start|>
def resolve_params(self, scope):
if not self.args:
return {}
return self.args.resolve(scope)
def is_single_entity(self, scope):
if self.type in 'spr':
return True
params = self.resolve_params(scope)
return 'limit' in params and params['limit'] == '1'
def resolve(self, scope):
return make_selector(self.type, **self.resolve_params(scope))
class SelectorArgs(Resolvable):
pass
class SimpleSelectorArgs(SelectorArgs):
def __init__(self, args):
self.args = args
def resolve(self, scope):
return dict(self.args)
class ScoreRange(Resolvable):
def __init__(self, min=None, max=None):
assert min is not None or max is not None
self.min = min
<|code_end|>
with the help of current file imports:
from .core import Resolvable, EntityRef
from .scoreboard import ObjectiveRef
and context from other files:
# Path: commands/core.py
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# Path: commands/scoreboard.py
# class ObjectiveRef(Resolvable):
#
# def __init__(self, name):
# assert type(name) == str
# self.objective = name
#
# def resolve(self, scope):
# return scope.objective(self.objective)
, which may contain function names, class names, or code. Output only the next line. | self.max = max |
Here is a snippet: <|code_start|> return self.proxy(scope).as_text(scope)
class DataGet(Command):
def __init__(self, target, path, scale=1):
assert isinstance(target, NBTStorable)
assert isinstance(scale, (int, float)) or scale is None
self.target = target
self.path = path
self.scale = None if scale is None else \
int(scale) if scale == int(scale) else scale
def resolve(self, scope):
scale = ' %s' % self.scale if self.scale is not None else ''
return 'data get %s %s%s' % (self.target.resolve(scope),
self.path.resolve(scope), scale)
class DataMerge(Command):
def __init__(self, ref, nbt):
assert isinstance(ref, NBTStorable)
self.ref = ref
self.nbt = nbt
def resolve(self, scope):
return 'data merge %s %s' % (self.ref.resolve(scope),
self.nbt.resolve(scope))
class DataModify(Command):
<|code_end|>
. Write the next line using the current file imports:
from .core import Resolvable, Command, EntityRef, WorldPos
and context from other files:
# Path: commands/core.py
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class Command(Resolvable):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
, which may include functions, classes, or code. Output only the next line. | def __init__(self, ref, path, action, *rest): |
Here is a snippet: <|code_start|>
class StackPath(ArrayPath):
name = 'stack'
def StackFrame(index):
class StackFramePath(ArrayPath):
name = 'stack[%d].stack' % (-index - 1)
return StackFramePath
StackFrameHead = StackFrame(0)
class GlobalPath(SubPath):
name = 'global'
def __init__(self, name=None, key=None):
super().__init__('.' + name if name is not None else None, key)
class NBTStorable(Resolvable):
pass
class EntityReference(NBTStorable):
def __init__(self, target):
assert isinstance(target, EntityRef)
self.target = target
def resolve(self, scope):
assert self.target.is_single_entity(scope)
return 'entity %s' % self.target.resolve(scope)
<|code_end|>
. Write the next line using the current file imports:
from .core import Resolvable, Command, EntityRef, WorldPos
and context from other files:
# Path: commands/core.py
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class Command(Resolvable):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
, which may include functions, classes, or code. Output only the next line. | def as_text(self, scope): |
Given the code snippet: <|code_start|>
def __init__(self, name=None, key=None):
super().__init__('.' + name if name is not None else None, key)
class NBTStorable(Resolvable):
pass
class EntityReference(NBTStorable):
def __init__(self, target):
assert isinstance(target, EntityRef)
self.target = target
def resolve(self, scope):
assert self.target.is_single_entity(scope)
return 'entity %s' % self.target.resolve(scope)
def as_text(self, scope):
assert self.target.is_single_entity(scope)
return {'entity': self.target.resolve(scope)}
class BlockReference(NBTStorable):
def __init__(self, pos):
assert isinstance(pos, WorldPos) and pos.block_pos
self.pos = pos
def resolve(self, scope):
return 'block %s' % self.pos.resolve(scope)
<|code_end|>
, generate the next line using the imports in this file:
from .core import Resolvable, Command, EntityRef, WorldPos
and context (functions, classes, or occasionally code) from other files:
# Path: commands/core.py
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class Command(Resolvable):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
. Output only the next line. | def as_text(self, scope): |
Predict the next line for this snippet: <|code_start|>
def __init__(self, pos):
assert isinstance(pos, WorldPos) and pos.block_pos
self.pos = pos
def resolve(self, scope):
return 'block %s' % self.pos.resolve(scope)
def as_text(self, scope):
return {'block': self.pos.resolve(scope)}
class Storage(NBTStorable):
def __init__(self, namespace=None):
self.namespace = namespace
def resolve(self, scope):
return 'storage %s' % scope.storage(self.namespace)
def as_text(self, scope):
return {'storage': scope.storage(self.namespace)}
class GlobalNBT(NBTStorable):
def __init__(self, namespace):
self.namespace = namespace
def proxy(self, scope):
return scope.global_nbt(self.namespace)
<|code_end|>
with the help of current file imports:
from .core import Resolvable, Command, EntityRef, WorldPos
and context from other files:
# Path: commands/core.py
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# class Command(Resolvable):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class WorldPos(Resolvable):
#
# def __init__(self, x, y, z, block_pos=False):
# is_anchor = self._check_coord(x, True, not block_pos)
# was_anchor = self._check_coord(y, is_anchor, not block_pos)
# is_anchor = self._check_coord(z, was_anchor, not block_pos)
# if was_anchor:
# assert is_anchor
# self.x, self.y, self.z = x, y, z
# self.block_pos = block_pos
#
# def _check_coord(self, val, allow_anchor, allow_float):
# if isinstance(val, AnchorRelCoord):
# assert allow_anchor
# return True
# if type(val) == float:
# assert allow_float
# return False
# if type(val) == int:
# return False
# if isinstance(val, WorldRelCoord):
# return False
# assert False, val
#
# @property
# def ref(self):
# from .nbt import BlockReference
# return BlockReference(self)
#
# def resolve(self, scope):
# return '%s %s %s' % (self.x, self.y, self.z)
, which may contain function names, class names, or code. Output only the next line. | def resolve(self, scope): |
Predict the next line for this snippet: <|code_start|> if op == '=':
assert right.type is self, right
assert right.value.var is not None
left.value.var = right.value.var
return left
return super().dispatch_operator(compiler, op, left, right)
class StringInstance:
def __init__(self, val=None):
self._str = val
def __repr__(self):
return 'StringInstance(%s)' % self._str
class StringType(NativeType):
def allocate(self, compiler, namehint):
return StringInstance()
def effective_var_size(self):
# We allow using StringType in a struct as long as the usage is only
# within macros
return 0
def _copy_impl(self, compiler, this, other):
return other
def as_ir_variable(self, instance):
# e.g. LiteralString
<|code_end|>
with the help of current file imports:
from .containers import LiteralString, Temporary
from .native_type import NativeType, MetaType
from cmd_ir.reader import Reader
import cmd_ir.instructions as i
and context from other files:
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
#
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# class MetaType(NativeType):
#
# def __init__(self, the_type):
# self.the_type = the_type
#
# def call_constructor(self, compiler, container, args):
# the_type = container.type.the_type
# obj = the_type.allocate(compiler, safe_typename(the_type) + '_inst')
# tmp = Temporary(the_type, obj)
# the_type.run_constructor(compiler, tmp, args)
# return tmp
#
# Path: cmd_ir/reader.py
# class Reader:
#
# def __init__(self):
# self.parser = lark_parser()
# self.env = []
#
# def set_env(self, name, value):
# self.env.append((name, value))
#
# def read(self, text):
# tree = self.parser.parse(text)
# builder = BuildProgram()
# self.preprocess(builder.top)
# builder.visit(tree)
# builder.top.end()
# return builder.top
#
# def preprocess(self, top):
# for name, value in self.env:
# top.store(name, value)
#
# def read_blocks(self, func, blocks):
# tree = self.parser.parse('%HOOK BLOCKS ' + blocks)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# # Return blocks in order of occurence
# return builder.visit(tree)
#
# def read_instruction(self, func, insn, moreargs=()):
# tree = self.parser.parse('%HOOK INSN ' + insn)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# builder._hook_more_args = moreargs
# # the "start" visitor returns a list with one element - the insn
# return builder.visit(tree)[0]
, which may contain function names, class names, or code. Output only the next line. | if type(instance) == str: |
Given the following code snippet before the placeholder: <|code_start|>
def dispatch_operator(self, compiler, op, left, right=None):
if op == '=':
assert right.type is self, right
assert right.value.var is not None
left.value.var = right.value.var
return left
return super().dispatch_operator(compiler, op, left, right)
class StringInstance:
def __init__(self, val=None):
self._str = val
def __repr__(self):
return 'StringInstance(%s)' % self._str
class StringType(NativeType):
def allocate(self, compiler, namehint):
return StringInstance()
def effective_var_size(self):
# We allow using StringType in a struct as long as the usage is only
# within macros
return 0
def _copy_impl(self, compiler, this, other):
return other
<|code_end|>
, predict the next line using imports from the current file:
from .containers import LiteralString, Temporary
from .native_type import NativeType, MetaType
from cmd_ir.reader import Reader
import cmd_ir.instructions as i
and context including class names, function names, and sometimes code from other files:
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
#
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# class MetaType(NativeType):
#
# def __init__(self, the_type):
# self.the_type = the_type
#
# def call_constructor(self, compiler, container, args):
# the_type = container.type.the_type
# obj = the_type.allocate(compiler, safe_typename(the_type) + '_inst')
# tmp = Temporary(the_type, obj)
# the_type.run_constructor(compiler, tmp, args)
# return tmp
#
# Path: cmd_ir/reader.py
# class Reader:
#
# def __init__(self):
# self.parser = lark_parser()
# self.env = []
#
# def set_env(self, name, value):
# self.env.append((name, value))
#
# def read(self, text):
# tree = self.parser.parse(text)
# builder = BuildProgram()
# self.preprocess(builder.top)
# builder.visit(tree)
# builder.top.end()
# return builder.top
#
# def preprocess(self, top):
# for name, value in self.env:
# top.store(name, value)
#
# def read_blocks(self, func, blocks):
# tree = self.parser.parse('%HOOK BLOCKS ' + blocks)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# # Return blocks in order of occurence
# return builder.visit(tree)
#
# def read_instruction(self, func, insn, moreargs=()):
# tree = self.parser.parse('%HOOK INSN ' + insn)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# builder._hook_more_args = moreargs
# # the "start" visitor returns a list with one element - the insn
# return builder.visit(tree)[0]
. Output only the next line. | def as_ir_variable(self, instance): |
Given snippet: <|code_start|>
@property
def metatype(self):
return MetaType(self)
def allocate(self, compiler, namehint):
return IRTypeInstance(namehint)
def effective_var_size(self):
# We allow using IRType in a struct as long as the usage is only
# within macros
return 0
def as_ir_variable(self, instance):
assert instance.var is not None, "Cannot convert %s to variable" % (
instance._name)
return instance.var
def run_constructor(self, compiler, container, args):
assert len(args) >= 1, (self, args)
s = args[0]
if s.type == compiler.type('string'):
if isinstance(s, LiteralString):
v = s.value
else:
v = s.type.as_ir_variable(s.value)
assert isinstance(v, i.VirtualString)
v = str(v)
moreargs = [a.type.as_ir_variable(a.value) for a in args[1:]]
container.value.ctor(compiler, v, moreargs)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .containers import LiteralString, Temporary
from .native_type import NativeType, MetaType
from cmd_ir.reader import Reader
import cmd_ir.instructions as i
and context:
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
#
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# class MetaType(NativeType):
#
# def __init__(self, the_type):
# self.the_type = the_type
#
# def call_constructor(self, compiler, container, args):
# the_type = container.type.the_type
# obj = the_type.allocate(compiler, safe_typename(the_type) + '_inst')
# tmp = Temporary(the_type, obj)
# the_type.run_constructor(compiler, tmp, args)
# return tmp
#
# Path: cmd_ir/reader.py
# class Reader:
#
# def __init__(self):
# self.parser = lark_parser()
# self.env = []
#
# def set_env(self, name, value):
# self.env.append((name, value))
#
# def read(self, text):
# tree = self.parser.parse(text)
# builder = BuildProgram()
# self.preprocess(builder.top)
# builder.visit(tree)
# builder.top.end()
# return builder.top
#
# def preprocess(self, top):
# for name, value in self.env:
# top.store(name, value)
#
# def read_blocks(self, func, blocks):
# tree = self.parser.parse('%HOOK BLOCKS ' + blocks)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# # Return blocks in order of occurence
# return builder.visit(tree)
#
# def read_instruction(self, func, insn, moreargs=()):
# tree = self.parser.parse('%HOOK INSN ' + insn)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# builder._hook_more_args = moreargs
# # the "start" visitor returns a list with one element - the insn
# return builder.visit(tree)[0]
which might include code, classes, or functions. Output only the next line. | else: |
Given snippet: <|code_start|>
_READER_ = Reader()
class IRTypeInstance:
def __init__(self, name):
self._name = name
self.var = None
def ctor(self, compiler, insn_str, moreargs):
insn = _READER_.read_instruction(compiler.func, insn_str, moreargs)
self.var = compiler.define(self._name, insn)
def __repr__(self):
return 'IRTypeInstance(%s)' % self.var
class IRType(NativeType):
@property
def metatype(self):
return MetaType(self)
def allocate(self, compiler, namehint):
return IRTypeInstance(namehint)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .containers import LiteralString, Temporary
from .native_type import NativeType, MetaType
from cmd_ir.reader import Reader
import cmd_ir.instructions as i
and context:
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
#
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# class MetaType(NativeType):
#
# def __init__(self, the_type):
# self.the_type = the_type
#
# def call_constructor(self, compiler, container, args):
# the_type = container.type.the_type
# obj = the_type.allocate(compiler, safe_typename(the_type) + '_inst')
# tmp = Temporary(the_type, obj)
# the_type.run_constructor(compiler, tmp, args)
# return tmp
#
# Path: cmd_ir/reader.py
# class Reader:
#
# def __init__(self):
# self.parser = lark_parser()
# self.env = []
#
# def set_env(self, name, value):
# self.env.append((name, value))
#
# def read(self, text):
# tree = self.parser.parse(text)
# builder = BuildProgram()
# self.preprocess(builder.top)
# builder.visit(tree)
# builder.top.end()
# return builder.top
#
# def preprocess(self, top):
# for name, value in self.env:
# top.store(name, value)
#
# def read_blocks(self, func, blocks):
# tree = self.parser.parse('%HOOK BLOCKS ' + blocks)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# # Return blocks in order of occurence
# return builder.visit(tree)
#
# def read_instruction(self, func, insn, moreargs=()):
# tree = self.parser.parse('%HOOK INSN ' + insn)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# builder._hook_more_args = moreargs
# # the "start" visitor returns a list with one element - the insn
# return builder.visit(tree)[0]
which might include code, classes, or functions. Output only the next line. | def effective_var_size(self): |
Continue the code snippet: <|code_start|>class StringInstance:
def __init__(self, val=None):
self._str = val
def __repr__(self):
return 'StringInstance(%s)' % self._str
class StringType(NativeType):
def allocate(self, compiler, namehint):
return StringInstance()
def effective_var_size(self):
# We allow using StringType in a struct as long as the usage is only
# within macros
return 0
def _copy_impl(self, compiler, this, other):
return other
def as_ir_variable(self, instance):
# e.g. LiteralString
if type(instance) == str:
return i.VirtualString(instance)
assert instance._str is not None, "String has no value"
return instance._str
def run_constructor(self, compiler, container, args):
if len(args) != 1:
<|code_end|>
. Use current file imports:
from .containers import LiteralString, Temporary
from .native_type import NativeType, MetaType
from cmd_ir.reader import Reader
import cmd_ir.instructions as i
and context (classes, functions, or code) from other files:
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
#
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# class MetaType(NativeType):
#
# def __init__(self, the_type):
# self.the_type = the_type
#
# def call_constructor(self, compiler, container, args):
# the_type = container.type.the_type
# obj = the_type.allocate(compiler, safe_typename(the_type) + '_inst')
# tmp = Temporary(the_type, obj)
# the_type.run_constructor(compiler, tmp, args)
# return tmp
#
# Path: cmd_ir/reader.py
# class Reader:
#
# def __init__(self):
# self.parser = lark_parser()
# self.env = []
#
# def set_env(self, name, value):
# self.env.append((name, value))
#
# def read(self, text):
# tree = self.parser.parse(text)
# builder = BuildProgram()
# self.preprocess(builder.top)
# builder.visit(tree)
# builder.top.end()
# return builder.top
#
# def preprocess(self, top):
# for name, value in self.env:
# top.store(name, value)
#
# def read_blocks(self, func, blocks):
# tree = self.parser.parse('%HOOK BLOCKS ' + blocks)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# # Return blocks in order of occurence
# return builder.visit(tree)
#
# def read_instruction(self, func, insn, moreargs=()):
# tree = self.parser.parse('%HOOK INSN ' + insn)
# builder = BuildProgram()
# builder.func = func
# builder.holder = func
# builder._hook_more_args = moreargs
# # the "start" visitor returns a list with one element - the insn
# return builder.visit(tree)[0]
. Output only the next line. | return super().run_constructor(compiler, container, args) |
Continue the code snippet: <|code_start|> def __init__(self, ret_type, params, body, typescope, compiletime):
super().__init__(ret_type, params, True, False)
self._typescope = typescope
if type(body) == tuple:
self._body, self._init_list = body
else:
self._body, self._init_list = body, False
self.compiletime = compiletime
def allocate(self, compiler, namehint):
func = super().allocate(compiler, namehint)
func.set_as_intrinsic(IntrinsicCallable(self.__expand))
return func
def __expand(self, compiler, container, args):
if self.compiletime:
return self.__expand_compiletime(compiler, args)
else:
return self.__expand_macro(compiler, args)
def __expand_macro(self, compiler, args, ret_does_return=False):
with compiler._process_body_main(self.ret_type,
return_var=False, ret_does_return=ret_does_return) as ret:
with compiler.types.typescope(self._typescope):
compiler._alloc_and_copy_params(self.params, args)
if self._init_list != False:
compiler.construct_this(self._init_list)
compiler.transform(self._body)
if ret is None:
return Temporary(compiler.type('void'), None)
<|code_end|>
. Use current file imports:
from .function_type import FunctionType, Invokable, IntrinsicCallable
from .containers import Temporary
and context (classes, functions, or code) from other files:
# Path: cbl/function_type.py
# class FunctionType(NativeType, Invokable):
#
# def __init__(self, ret_type, params, inline, is_async):
# self.ret_type = ret_type
# self.params = tuple(params)
# self.is_inline = inline
# self.is_async = is_async
# self.is_intrinsic = False
#
# def param_str(self):
# return '(%s)' % ', '.join('%s %s%s' % (p.type.typename,
# '&' if p.by_ref else '',
# p.name) \
# for p in self.params)
#
# def allocate(self, compiler, namehint):
# return FunctionContainer(self, compiler, namehint)
#
# def intrinsic_invoke(self, container, args):
# assert self.is_intrinsic, "Function is not intrinsic"
# return container.value.intrinsic_invoke(container, args)
#
# def invoke(self, container, args, ret_args):
# assert not self.is_intrinsic, "Cannot call invoke on intrinsic"
# return container.value.invoke(args, ret_args)
#
# def match_arguments(self, compiler, container, args):
# matcher = FunctionMatcher(compiler, container.value.name)
# matcher.add_candidate(container)
# return matcher.satisfy(args)
#
# class Invokable:
#
# def match_arguments(self, compiler, container, args):
# assert False
#
# class IntrinsicCallable(IntrinsicFunction):
#
# def __init__(self, func):
# assert callable(func)
# self.__func = func
#
# def invoke(self, compiler, container, args):
# ret = self.__func(compiler, container, args)
# assert ret is not None
# return ret
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
. Output only the next line. | return ret |
Based on the snippet: <|code_start|>
class MacroType(FunctionType, Invokable):
def __init__(self, ret_type, params, body, typescope, compiletime):
super().__init__(ret_type, params, True, False)
self._typescope = typescope
if type(body) == tuple:
self._body, self._init_list = body
else:
self._body, self._init_list = body, False
self.compiletime = compiletime
def allocate(self, compiler, namehint):
func = super().allocate(compiler, namehint)
func.set_as_intrinsic(IntrinsicCallable(self.__expand))
return func
<|code_end|>
, predict the immediate next line with the help of imports:
from .function_type import FunctionType, Invokable, IntrinsicCallable
from .containers import Temporary
and context (classes, functions, sometimes code) from other files:
# Path: cbl/function_type.py
# class FunctionType(NativeType, Invokable):
#
# def __init__(self, ret_type, params, inline, is_async):
# self.ret_type = ret_type
# self.params = tuple(params)
# self.is_inline = inline
# self.is_async = is_async
# self.is_intrinsic = False
#
# def param_str(self):
# return '(%s)' % ', '.join('%s %s%s' % (p.type.typename,
# '&' if p.by_ref else '',
# p.name) \
# for p in self.params)
#
# def allocate(self, compiler, namehint):
# return FunctionContainer(self, compiler, namehint)
#
# def intrinsic_invoke(self, container, args):
# assert self.is_intrinsic, "Function is not intrinsic"
# return container.value.intrinsic_invoke(container, args)
#
# def invoke(self, container, args, ret_args):
# assert not self.is_intrinsic, "Cannot call invoke on intrinsic"
# return container.value.invoke(args, ret_args)
#
# def match_arguments(self, compiler, container, args):
# matcher = FunctionMatcher(compiler, container.value.name)
# matcher.add_candidate(container)
# return matcher.satisfy(args)
#
# class Invokable:
#
# def match_arguments(self, compiler, container, args):
# assert False
#
# class IntrinsicCallable(IntrinsicFunction):
#
# def __init__(self, func):
# assert callable(func)
# self.__func = func
#
# def invoke(self, compiler, container, args):
# ret = self.__func(compiler, container, args)
# assert ret is not None
# return ret
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
. Output only the next line. | def __expand(self, compiler, container, args): |
Given snippet: <|code_start|>
class MacroType(FunctionType, Invokable):
def __init__(self, ret_type, params, body, typescope, compiletime):
super().__init__(ret_type, params, True, False)
self._typescope = typescope
if type(body) == tuple:
self._body, self._init_list = body
else:
self._body, self._init_list = body, False
self.compiletime = compiletime
def allocate(self, compiler, namehint):
func = super().allocate(compiler, namehint)
func.set_as_intrinsic(IntrinsicCallable(self.__expand))
return func
def __expand(self, compiler, container, args):
if self.compiletime:
return self.__expand_compiletime(compiler, args)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .function_type import FunctionType, Invokable, IntrinsicCallable
from .containers import Temporary
and context:
# Path: cbl/function_type.py
# class FunctionType(NativeType, Invokable):
#
# def __init__(self, ret_type, params, inline, is_async):
# self.ret_type = ret_type
# self.params = tuple(params)
# self.is_inline = inline
# self.is_async = is_async
# self.is_intrinsic = False
#
# def param_str(self):
# return '(%s)' % ', '.join('%s %s%s' % (p.type.typename,
# '&' if p.by_ref else '',
# p.name) \
# for p in self.params)
#
# def allocate(self, compiler, namehint):
# return FunctionContainer(self, compiler, namehint)
#
# def intrinsic_invoke(self, container, args):
# assert self.is_intrinsic, "Function is not intrinsic"
# return container.value.intrinsic_invoke(container, args)
#
# def invoke(self, container, args, ret_args):
# assert not self.is_intrinsic, "Cannot call invoke on intrinsic"
# return container.value.invoke(args, ret_args)
#
# def match_arguments(self, compiler, container, args):
# matcher = FunctionMatcher(compiler, container.value.name)
# matcher.add_candidate(container)
# return matcher.satisfy(args)
#
# class Invokable:
#
# def match_arguments(self, compiler, container, args):
# assert False
#
# class IntrinsicCallable(IntrinsicFunction):
#
# def __init__(self, func):
# assert callable(func)
# self.__func = func
#
# def invoke(self, compiler, container, args):
# ret = self.__func(compiler, container, args)
# assert ret is not None
# return ret
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
which might include code, classes, or functions. Output only the next line. | else: |
Predict the next line after this snippet: <|code_start|> def __init__(self, ret_type, params, body, typescope, compiletime):
super().__init__(ret_type, params, True, False)
self._typescope = typescope
if type(body) == tuple:
self._body, self._init_list = body
else:
self._body, self._init_list = body, False
self.compiletime = compiletime
def allocate(self, compiler, namehint):
func = super().allocate(compiler, namehint)
func.set_as_intrinsic(IntrinsicCallable(self.__expand))
return func
def __expand(self, compiler, container, args):
if self.compiletime:
return self.__expand_compiletime(compiler, args)
else:
return self.__expand_macro(compiler, args)
def __expand_macro(self, compiler, args, ret_does_return=False):
with compiler._process_body_main(self.ret_type,
return_var=False, ret_does_return=ret_does_return) as ret:
with compiler.types.typescope(self._typescope):
compiler._alloc_and_copy_params(self.params, args)
if self._init_list != False:
compiler.construct_this(self._init_list)
compiler.transform(self._body)
if ret is None:
return Temporary(compiler.type('void'), None)
<|code_end|>
using the current file's imports:
from .function_type import FunctionType, Invokable, IntrinsicCallable
from .containers import Temporary
and any relevant context from other files:
# Path: cbl/function_type.py
# class FunctionType(NativeType, Invokable):
#
# def __init__(self, ret_type, params, inline, is_async):
# self.ret_type = ret_type
# self.params = tuple(params)
# self.is_inline = inline
# self.is_async = is_async
# self.is_intrinsic = False
#
# def param_str(self):
# return '(%s)' % ', '.join('%s %s%s' % (p.type.typename,
# '&' if p.by_ref else '',
# p.name) \
# for p in self.params)
#
# def allocate(self, compiler, namehint):
# return FunctionContainer(self, compiler, namehint)
#
# def intrinsic_invoke(self, container, args):
# assert self.is_intrinsic, "Function is not intrinsic"
# return container.value.intrinsic_invoke(container, args)
#
# def invoke(self, container, args, ret_args):
# assert not self.is_intrinsic, "Cannot call invoke on intrinsic"
# return container.value.invoke(args, ret_args)
#
# def match_arguments(self, compiler, container, args):
# matcher = FunctionMatcher(compiler, container.value.name)
# matcher.add_candidate(container)
# return matcher.satisfy(args)
#
# class Invokable:
#
# def match_arguments(self, compiler, container, args):
# assert False
#
# class IntrinsicCallable(IntrinsicFunction):
#
# def __init__(self, func):
# assert callable(func)
# self.__func = func
#
# def invoke(self, compiler, container, args):
# ret = self.__func(compiler, container, args)
# assert ret is not None
# return ret
#
# Path: cbl/containers.py
# class AsyncReturn:
# class DelegatedWrite:
# def __init__(self, realret, callback):
# def must_await(self):
# def type(self):
# def value(self):
# def write(self, compiler, other):
. Output only the next line. | return ret |
Next line prediction: <|code_start|> self.ref = None
self.using_temp = False
def __enter__(self):
self.ref = self.var._direct_ref()
if self.ref is None:
self.using_temp = True
self.ref = self.out.allocate_temp()
if self.read:
self.var._write_to_reference(self.ref, self.out)
return self.ref
def __exit__(self, *args):
# if not a direct reference, must write back
if self.write and self.using_temp:
self.var._read_from_reference(self.ref, self.out)
if self.using_temp:
self.out.free_temp(self.ref)
class Variable(NativeType, metaclass=abc.ABCMeta):
def __init__(self, vartype):
assert isinstance(vartype, VarType)
self.type = vartype
self.__use_w = 0
self.__use_r = 0
@property
@abc.abstractmethod
def namespace(self):
<|code_end|>
. Use current file imports:
(import abc
import commands as c
import copy
from .core_types import InsnArg, NativeType
from .nbt import NBTType)
and context including class names, function names, or small code snippets from other files:
# Path: cmd_ir/core_types.py
# class InsnArg:
#
# @classmethod
# def _init_from_parser(cls, value):
# return value
#
# class NativeType(InsnArg):
#
# @classmethod
# def typename(cls):
# return cls.__name__
#
# def clone(self):
# raise TypeError(self.typename() + ' does not support cloning')
#
# def inline_copy(self):
# import copy
# return copy.copy(self)
#
# def write_out(self, out):
# pass
#
# Path: cmd_ir/nbt.py
# class NBTType(NativeType):
#
# __LOOKUP = {}
#
# def __init__(self, typename, compound=False):
# self.name = typename
# self._compound = compound
# self.__LOOKUP[typename] = self
#
# @property
# def exec_store_name(self):
# assert self.isnumeric
# # Currently we have the same names
# return self.name
#
# @property
# def isnumeric(self):
# return not self._compound and self.name != 'string'
#
# def __str__(self):
# return 'NBTType(%s)' % self.name
#
# def serialize(self):
# return self.name
#
# @classmethod
# def _init_from_parser(cls, value):
# return cls.__LOOKUP[value]
#
# def new(self, *args):
# # There are better ways of doing this
# if self is self.byte:
# impl = NBTByte
# elif self is self.short:
# impl = NBTShort
# elif self is self.int:
# impl = NBTInt
# elif self is self.long:
# impl = NBTLong
# elif self is self.float:
# impl = NBTFloat
# elif self is self.double:
# impl = NBTDouble
# elif self is self.string:
# impl = NBTString
# elif self is self.list:
# impl = NBTList
# elif self is self.compound:
# impl = NBTCompound
# else:
# assert False, str(self)
# return impl(*args)
#
# byte = None
# short = None
# int = None
# long = None
# float = None
# double = None
# string = None
# list = None
# compound = None
. Output only the next line. | pass |
Given the following code snippet before the placeholder: <|code_start|>
class Conversions:
def to_int(self, val):
raise TypeError('%s cannot convert %s to int' % (self, val))
@property
def scale(self):
<|code_end|>
, predict the next line using imports from the current file:
import abc
import commands as c
import copy
from .core_types import InsnArg, NativeType
from .nbt import NBTType
and context including class names, function names, and sometimes code from other files:
# Path: cmd_ir/core_types.py
# class InsnArg:
#
# @classmethod
# def _init_from_parser(cls, value):
# return value
#
# class NativeType(InsnArg):
#
# @classmethod
# def typename(cls):
# return cls.__name__
#
# def clone(self):
# raise TypeError(self.typename() + ' does not support cloning')
#
# def inline_copy(self):
# import copy
# return copy.copy(self)
#
# def write_out(self, out):
# pass
#
# Path: cmd_ir/nbt.py
# class NBTType(NativeType):
#
# __LOOKUP = {}
#
# def __init__(self, typename, compound=False):
# self.name = typename
# self._compound = compound
# self.__LOOKUP[typename] = self
#
# @property
# def exec_store_name(self):
# assert self.isnumeric
# # Currently we have the same names
# return self.name
#
# @property
# def isnumeric(self):
# return not self._compound and self.name != 'string'
#
# def __str__(self):
# return 'NBTType(%s)' % self.name
#
# def serialize(self):
# return self.name
#
# @classmethod
# def _init_from_parser(cls, value):
# return cls.__LOOKUP[value]
#
# def new(self, *args):
# # There are better ways of doing this
# if self is self.byte:
# impl = NBTByte
# elif self is self.short:
# impl = NBTShort
# elif self is self.int:
# impl = NBTInt
# elif self is self.long:
# impl = NBTLong
# elif self is self.float:
# impl = NBTFloat
# elif self is self.double:
# impl = NBTDouble
# elif self is self.string:
# impl = NBTString
# elif self is self.list:
# impl = NBTList
# elif self is self.compound:
# impl = NBTCompound
# else:
# assert False, str(self)
# return impl(*args)
#
# byte = None
# short = None
# int = None
# long = None
# float = None
# double = None
# string = None
# list = None
# compound = None
. Output only the next line. | raise TypeError('%s cannot scale values' % self) |
Predict the next line after this snippet: <|code_start|> self.read = read
self.ref = None
self.using_temp = False
def __enter__(self):
self.ref = self.var._direct_ref()
if self.ref is None:
self.using_temp = True
self.ref = self.out.allocate_temp()
if self.read:
self.var._write_to_reference(self.ref, self.out)
return self.ref
def __exit__(self, *args):
# if not a direct reference, must write back
if self.write and self.using_temp:
self.var._read_from_reference(self.ref, self.out)
if self.using_temp:
self.out.free_temp(self.ref)
class Variable(NativeType, metaclass=abc.ABCMeta):
def __init__(self, vartype):
assert isinstance(vartype, VarType)
self.type = vartype
self.__use_w = 0
self.__use_r = 0
@property
@abc.abstractmethod
<|code_end|>
using the current file's imports:
import abc
import commands as c
import copy
from .core_types import InsnArg, NativeType
from .nbt import NBTType
and any relevant context from other files:
# Path: cmd_ir/core_types.py
# class InsnArg:
#
# @classmethod
# def _init_from_parser(cls, value):
# return value
#
# class NativeType(InsnArg):
#
# @classmethod
# def typename(cls):
# return cls.__name__
#
# def clone(self):
# raise TypeError(self.typename() + ' does not support cloning')
#
# def inline_copy(self):
# import copy
# return copy.copy(self)
#
# def write_out(self, out):
# pass
#
# Path: cmd_ir/nbt.py
# class NBTType(NativeType):
#
# __LOOKUP = {}
#
# def __init__(self, typename, compound=False):
# self.name = typename
# self._compound = compound
# self.__LOOKUP[typename] = self
#
# @property
# def exec_store_name(self):
# assert self.isnumeric
# # Currently we have the same names
# return self.name
#
# @property
# def isnumeric(self):
# return not self._compound and self.name != 'string'
#
# def __str__(self):
# return 'NBTType(%s)' % self.name
#
# def serialize(self):
# return self.name
#
# @classmethod
# def _init_from_parser(cls, value):
# return cls.__LOOKUP[value]
#
# def new(self, *args):
# # There are better ways of doing this
# if self is self.byte:
# impl = NBTByte
# elif self is self.short:
# impl = NBTShort
# elif self is self.int:
# impl = NBTInt
# elif self is self.long:
# impl = NBTLong
# elif self is self.float:
# impl = NBTFloat
# elif self is self.double:
# impl = NBTDouble
# elif self is self.string:
# impl = NBTString
# elif self is self.list:
# impl = NBTList
# elif self is self.compound:
# impl = NBTCompound
# else:
# assert False, str(self)
# return impl(*args)
#
# byte = None
# short = None
# int = None
# long = None
# float = None
# double = None
# string = None
# list = None
# compound = None
. Output only the next line. | def namespace(self): |
Given snippet: <|code_start|> args = []
argnames = ''
func_preamble_only = True
insn_name = 'pure_func'
def preapply(self, seq):
seq.holder.set_pure()
class InlineInsn(PreambleInsn):
"""Marks the function as inline-able. invoke calls to this function will
result in the body of the function being inserted at the call site"""
args = []
argnames = ''
func_preamble_only = True
insn_name = 'inline'
def preapply(self, seq):
seq.holder.set_inline()
class RunCallbackOnExit(PreambleInsn):
"""Converts this function into an async function - one that
does not return immediately, but instead invokes a callback
when it eventually exits. Call this function with deferred_invoke."""
args = []
argnames = ''
func_preamble_only = True
insn_name = 'run_callback_on_exit'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ._core import PreambleInsn
from .control_flow import RunDeferredCallback
from ..core_types import VirtualString
and context:
# Path: cmd_ir/instructions/_core.py
# class PreambleInsn(Insn, metaclass=abc.ABCMeta):
#
# is_preamble_insn = True
# top_preamble_only = False
# func_preamble_only = False
#
# def apply(self, out, func):
# assert False, "This is a preamble insn, %s" % self
#
# def run(self, ev):
# assert False, "Not a compile time instruction, %s" % self
#
# def activate(self, seq):
# assert isinstance(seq, Preamble), self
# if self.top_preamble_only:
# assert seq.is_top, self
# if self.func_preamble_only:
# assert not seq.is_top, self
# return self.preapply(seq)
#
# @abc.abstractmethod
# def preapply(self, preamble):
# pass
#
# def postapply(self, out, func):
# pass
#
# Path: cmd_ir/instructions/control_flow.py
# class RunDeferredCallback(RuntimeInsn):
# """(Internal) Copies the callback function from the stackframe
# into the zero tick block. See deferred_invoke."""
#
# args = []
# argnames = ''
# insn_name = 'run_deferred_callback'
#
# def apply(self, out, func):
# storage = c.GlobalNBT(func.namespace)
# out.write(_zt.cmd_set_from(c.StackFrameHead(-1), storage))
#
# Path: cmd_ir/core_types.py
# class VirtualString(NativeType):
#
# def __init__(self, val):
# assert type(val) == str, val
# self.val = val
#
# def __str__(self):
# return self.val
#
# def clone(self):
# return self
#
# def serialize(self):
# return '"%s"' % self.val.replace('\\', '\\\\').replace('"', '\\"')
which might include code, classes, or functions. Output only the next line. | def preapply(self, seq): |
Given the following code snippet before the placeholder: <|code_start|>
args = [VirtualString]
argnames = 'namespace'
argdocs = ["The namespace"]
func_preamble_only = True
insn_name = 'namespace'
def preapply(self, seq):
seq.holder._set_namespace(self.namespace.val)
class PureInsn(PreambleInsn):
"""Marks the function as a pure function (i.e. no side-effects). No checks
are done to ensure it is side-effect free, allowing for functions with
irrelevant side-effects (e.g. caching) to be marked as pure."""
args = []
argnames = ''
func_preamble_only = True
insn_name = 'pure_func'
def preapply(self, seq):
seq.holder.set_pure()
class InlineInsn(PreambleInsn):
"""Marks the function as inline-able. invoke calls to this function will
result in the body of the function being inserted at the call site"""
args = []
argnames = ''
func_preamble_only = True
<|code_end|>
, predict the next line using imports from the current file:
from ._core import PreambleInsn
from .control_flow import RunDeferredCallback
from ..core_types import VirtualString
and context including class names, function names, and sometimes code from other files:
# Path: cmd_ir/instructions/_core.py
# class PreambleInsn(Insn, metaclass=abc.ABCMeta):
#
# is_preamble_insn = True
# top_preamble_only = False
# func_preamble_only = False
#
# def apply(self, out, func):
# assert False, "This is a preamble insn, %s" % self
#
# def run(self, ev):
# assert False, "Not a compile time instruction, %s" % self
#
# def activate(self, seq):
# assert isinstance(seq, Preamble), self
# if self.top_preamble_only:
# assert seq.is_top, self
# if self.func_preamble_only:
# assert not seq.is_top, self
# return self.preapply(seq)
#
# @abc.abstractmethod
# def preapply(self, preamble):
# pass
#
# def postapply(self, out, func):
# pass
#
# Path: cmd_ir/instructions/control_flow.py
# class RunDeferredCallback(RuntimeInsn):
# """(Internal) Copies the callback function from the stackframe
# into the zero tick block. See deferred_invoke."""
#
# args = []
# argnames = ''
# insn_name = 'run_deferred_callback'
#
# def apply(self, out, func):
# storage = c.GlobalNBT(func.namespace)
# out.write(_zt.cmd_set_from(c.StackFrameHead(-1), storage))
#
# Path: cmd_ir/core_types.py
# class VirtualString(NativeType):
#
# def __init__(self, val):
# assert type(val) == str, val
# self.val = val
#
# def __str__(self):
# return self.val
#
# def clone(self):
# return self
#
# def serialize(self):
# return '"%s"' % self.val.replace('\\', '\\\\').replace('"', '\\"')
. Output only the next line. | insn_name = 'inline' |
Given the following code snippet before the placeholder: <|code_start|>"""Function Properties"""
class ExternInsn(PreambleInsn):
"""Marks the function as externally visible. The function will not be
renamed on name conflict and will not be removed during optimization."""
args = []
argnames = ''
func_preamble_only = True
<|code_end|>
, predict the next line using imports from the current file:
from ._core import PreambleInsn
from .control_flow import RunDeferredCallback
from ..core_types import VirtualString
and context including class names, function names, and sometimes code from other files:
# Path: cmd_ir/instructions/_core.py
# class PreambleInsn(Insn, metaclass=abc.ABCMeta):
#
# is_preamble_insn = True
# top_preamble_only = False
# func_preamble_only = False
#
# def apply(self, out, func):
# assert False, "This is a preamble insn, %s" % self
#
# def run(self, ev):
# assert False, "Not a compile time instruction, %s" % self
#
# def activate(self, seq):
# assert isinstance(seq, Preamble), self
# if self.top_preamble_only:
# assert seq.is_top, self
# if self.func_preamble_only:
# assert not seq.is_top, self
# return self.preapply(seq)
#
# @abc.abstractmethod
# def preapply(self, preamble):
# pass
#
# def postapply(self, out, func):
# pass
#
# Path: cmd_ir/instructions/control_flow.py
# class RunDeferredCallback(RuntimeInsn):
# """(Internal) Copies the callback function from the stackframe
# into the zero tick block. See deferred_invoke."""
#
# args = []
# argnames = ''
# insn_name = 'run_deferred_callback'
#
# def apply(self, out, func):
# storage = c.GlobalNBT(func.namespace)
# out.write(_zt.cmd_set_from(c.StackFrameHead(-1), storage))
#
# Path: cmd_ir/core_types.py
# class VirtualString(NativeType):
#
# def __init__(self, val):
# assert type(val) == str, val
# self.val = val
#
# def __str__(self):
# return self.val
#
# def clone(self):
# return self
#
# def serialize(self):
# return '"%s"' % self.val.replace('\\', '\\\\').replace('"', '\\"')
. Output only the next line. | insn_name = 'extern' |
Given snippet: <|code_start|> def lazy_load_get(self):
if self.getter is None:
# TODO customize return type
self.getter = self.compiler.extern_function('_internal/array_get', (
(i.VarType.nbt, 'byval'), (self.index_type, 'byval')), (i.VarType.i32,))
def lazy_load_set(self):
if self.setter is None:
# TODO customise value type
self.setter = self.compiler.extern_function('_internal/array_set', (
(i.VarType.nbt, 'byref'), (self.index_type, 'byval'),
(i.VarType.i32, 'byval')), None)
@classmethod
def gen_getter(cls, top, size):
func = top.define_function('_internal/array_get')
arrparam = func.preamble.define(i.ParameterInsn(i.VarType.nbt, 'byval'))
indexparam = func.preamble.define(i.ParameterInsn(cls.index_type, 'byval'))
retvar = func.preamble.define(i.ReturnVarInsn(i.VarType.i32))
cls._gen_for(size, func, 'get', indexparam, cls._gen_getter, arrparam, retvar)
@classmethod
def gen_setter(cls, top, size):
func = top.define_function('_internal/array_set')
arrparam = func.preamble.define(i.ParameterInsn(i.VarType.nbt, 'byref'))
indexparam = func.preamble.define(i.ParameterInsn(cls.index_type, 'byval'))
valparam = func.preamble.define(i.ParameterInsn(i.VarType.i32, 'byval'))
cls._gen_for(size, func, 'set', indexparam, cls._gen_setter, arrparam, valparam)
@staticmethod
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import namedtuple
from .native_type import NativeType
from .containers import DelegatedWrite
import cmd_ir.instructions as i
and context:
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# Path: cbl/containers.py
# class DelegatedWrite:
#
# def write(self, compiler, other):
# assert False
which might include code, classes, or functions. Output only the next line. | def _gen_getter(block, indexvar, indexval, arr, retvar): |
Continue the code snippet: <|code_start|> # Copy to local variable due to register allocation speedup
index = func.preamble.define(i.DefineVariable(indexparam.type))
entry.add(i.SetScore(index, indexparam))
def pair_name(pair):
return '%s_%d_%d' % (prefix, pair.min, pair.max)
def branch(func, index, pair):
return i.RangeBr(index, pair.min, pair.max,
func.get_or_create_block(pair_name(pair)), None)
def callback(pair):
block = func.get_or_create_block(pair_name(pair))
block.defined = True
if pair.left:
block.add(branch(func, index, pair.left))
if pair.right:
block.add(branch(func, index, pair.right))
if pair.min == pair.max:
gen_callback(block, index, pair.min, *cb_args)
root = generate_bin_tree(size, callback)
entry.add(i.Call(func.get_or_create_block(pair_name(root))))
entry.add(i.Return())
func.end()
def generate_bin_tree(size, callback):
assert size > 0
old_pairs = []
for n in range(size):
<|code_end|>
. Use current file imports:
from collections import namedtuple
from .native_type import NativeType
from .containers import DelegatedWrite
import cmd_ir.instructions as i
and context (classes, functions, or code) from other files:
# Path: cbl/native_type.py
# class NativeType:
#
# def __repr__(self):
# return self.__class__.__name__
#
# def instantiate(self, compiler, args):
# assert not args, "%s does not take arguments" % self
# return self
#
# @property
# def typename(self):
# return self.__typename
#
# @typename.setter
# def typename(self, name):
# self.__typename = name
# meta = self.metatype
# if meta is not None:
# meta.typename = name + '--meta'
#
# def allocate(self, compiler, namehint):
# assert False, "%s is not allocatable" % self.typename
#
# @property
# def metatype(self):
# return None
#
# @property
# def ir_type(self):
# raise TypeError('%s does not have an IR type' % self)
#
# def get_property(self, compiler, container, prop):
# raise TypeError('Unknown property %s on %s' % (prop, self))
#
# def dispatch_operator(self, compiler, op, left, right=None):
# if op in ASSIGN_OP:
# # Remove '=' from op
# return self._assign_op(compiler, op[:-1], left, right)
# raise TypeError('Invalid operation "%s" on %s' % (op, self))
#
# def _assign_op(self, compiler, op, left, right):
# tmp = self.dispatch_operator(compiler, op, left, right)
# return self.dispatch_operator(compiler, '=', left, tmp)
#
# def ir_types(self):
# return (self.ir_type,)
#
# def as_variables(self, instance):
# return (self.as_variable(instance),)
#
# def as_variable(self, instance):
# raise TypeError('%s cannot be converted to a variable' % self)
#
# def as_ir_variable(self, instance):
# return self.as_variable(instance)
#
# # Convert a sequence of variables (e.g. from as_variables()) back into
# # Our high-level value
# def from_variables(self, compiler, vars):
# it = iter(vars)
#
# # The default implementation is to call allocate but provide variables
# # via the pool of yet-to-consume variables
# def shift_var(subname, var_type):
# var = next(it)
# # verify IR type is consistent
# assert var.type == var_type
# return var
#
# with compiler.set_create_var(shift_var):
# value = self.allocate(compiler, 'restored')
# # Check we consumed all the variables
# assert all(False for _ in it)
# return value
#
# def effective_var_size(self):
# if self.ir_type:
# return 1
# assert False
#
# def run_constructor(self, compiler, container, arguments):
# assert not arguments, (self, arguments)
#
# def do_construction(self, compiler, instance, member_inits):
# assert not member_inits
#
# def coerce_to(self, compiler, container, type):
# if type == self:
# return container
# return None
#
# Path: cbl/containers.py
# class DelegatedWrite:
#
# def write(self, compiler, other):
# assert False
. Output only the next line. | pair = Pair(None, None, n, n) |
Given snippet: <|code_start|> extra.append(child.resolve(scope))
if not self.style:
return extra
if extra:
if len(extra) == 1 and type(extra[0]) == dict:
text.update(extra[0])
else:
text['extra'] = extra
return text
def _resolve_style(self, key, value, scope):
if key == 'clickEvent':
assert isinstance(value, TextClickAction)
return value.resolve(scope)
return value
class TextStringComponent(TextComponent):
def __init__(self, stringval):
self.val = stringval
def resolve(self, scope):
return {'text': self.val}
class TextNBTComponent(TextComponent):
def __init__(self, storage, path):
assert isinstance(storage, NBTStorable)
assert isinstance(path, Path)
self.storage = storage
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
from .core import Command, EntityRef, Resolvable
from .scoreboard import ScoreRef
from .nbt import Path, NBTStorable
and context:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/nbt.py
# class Path(NbtPath):
#
# def resolve(self, scope):
# return scope.custom_nbt_path(self.path)
#
# class NBTStorable(Resolvable):
# pass
which might include code, classes, or functions. Output only the next line. | self.path = path |
Here is a snippet: <|code_start|> return value.resolve(scope)
return value
class TextStringComponent(TextComponent):
def __init__(self, stringval):
self.val = stringval
def resolve(self, scope):
return {'text': self.val}
class TextNBTComponent(TextComponent):
def __init__(self, storage, path):
assert isinstance(storage, NBTStorable)
assert isinstance(path, Path)
self.storage = storage
self.path = path
def resolve(self, scope):
obj = {'nbt': self.path.resolve(scope) }
obj.update(self.storage.as_text(scope))
return obj
class TextScoreComponent(TextComponent):
def __init__(self, ref):
assert isinstance(ref, ScoreRef)
self.ref = ref
<|code_end|>
. Write the next line using the current file imports:
import json
from .core import Command, EntityRef, Resolvable
from .scoreboard import ScoreRef
from .nbt import Path, NBTStorable
and context from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/nbt.py
# class Path(NbtPath):
#
# def resolve(self, scope):
# return scope.custom_nbt_path(self.path)
#
# class NBTStorable(Resolvable):
# pass
, which may include functions, classes, or code. Output only the next line. | def resolve(self, scope): |
Given the following code snippet before the placeholder: <|code_start|>
class Tellraw(Command):
def __init__(self, text, target):
assert isinstance(text, TextComponentHolder)
assert isinstance(target, EntityRef)
self.text = text
self.target = target
def resolve(self, scope):
<|code_end|>
, predict the next line using imports from the current file:
import json
from .core import Command, EntityRef, Resolvable
from .scoreboard import ScoreRef
from .nbt import Path, NBTStorable
and context including class names, function names, and sometimes code from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/nbt.py
# class Path(NbtPath):
#
# def resolve(self, scope):
# return scope.custom_nbt_path(self.path)
#
# class NBTStorable(Resolvable):
# pass
. Output only the next line. | return 'tellraw %s %s' % (self.target.resolve(scope), |
Next line prediction: <|code_start|>
class Tellraw(Command):
def __init__(self, text, target):
assert isinstance(text, TextComponentHolder)
assert isinstance(target, EntityRef)
self.text = text
self.target = target
def resolve(self, scope):
return 'tellraw %s %s' % (self.target.resolve(scope),
self.text.resolve_str(scope))
class TextComponent(Resolvable):
pass
<|code_end|>
. Use current file imports:
(import json
from .core import Command, EntityRef, Resolvable
from .scoreboard import ScoreRef
from .nbt import Path, NBTStorable)
and context including class names, function names, or small code snippets from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/nbt.py
# class Path(NbtPath):
#
# def resolve(self, scope):
# return scope.custom_nbt_path(self.path)
#
# class NBTStorable(Resolvable):
# pass
. Output only the next line. | class TextComponentHolder(TextComponent): |
Given the following code snippet before the placeholder: <|code_start|>
class Tellraw(Command):
def __init__(self, text, target):
assert isinstance(text, TextComponentHolder)
assert isinstance(target, EntityRef)
self.text = text
self.target = target
def resolve(self, scope):
return 'tellraw %s %s' % (self.target.resolve(scope),
self.text.resolve_str(scope))
class TextComponent(Resolvable):
pass
class TextComponentHolder(TextComponent):
def __init__(self, style, children):
self.style = style
self.children = children
def resolve_str(self, scope):
return json.dumps(self.resolve(scope), separators=(',', ':'))
def resolve(self, scope):
text = {}
for key, value in self.style.items():
text[key] = self._resolve_style(key, value, scope)
<|code_end|>
, predict the next line using imports from the current file:
import json
from .core import Command, EntityRef, Resolvable
from .scoreboard import ScoreRef
from .nbt import Path, NBTStorable
and context including class names, function names, and sometimes code from other files:
# Path: commands/core.py
# class Command(Resolvable):
# pass
#
# class EntityRef(Resolvable, metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def is_single_entity(self, scope):
# pass
#
# @property
# def ref(self):
# from .nbt import EntityReference
# return EntityReference(self)
#
# class Resolvable(metaclass=abc.ABCMeta):
#
# @abc.abstractmethod
# def resolve(self, scope):
# pass
#
# Path: commands/scoreboard.py
# class ScoreRef(Resolvable):
#
# def __init__(self, target, objective):
# assert isinstance(target, EntityRef)
# assert isinstance(objective, ObjectiveRef)
# self.target = target
# self.objective = objective
#
# def resolve(self, scope):
# return '%s %s' % (self.target.resolve(scope),
# self.objective.resolve(scope))
#
# Path: commands/nbt.py
# class Path(NbtPath):
#
# def resolve(self, scope):
# return scope.custom_nbt_path(self.path)
#
# class NBTStorable(Resolvable):
# pass
. Output only the next line. | extra = [] |
Next line prediction: <|code_start|>
def make_block_name(block_id, props):
prop_dict = {}
for prop in props:
key, value = prop.split('=')
<|code_end|>
. Use current file imports:
(from ..ir import IR)
and context including class names, function names, or small code snippets from other files:
# Path: c_comp/ir.py
# class IR:
#
# _counter = 0
#
# FunctionBegin = namedtuple('FunctionBegin', 'name storage pragma')
# FunctionEnd = namedtuple('FunctionEnd', '')
#
# Label = namedtuple('Label', 'label')
# EntityLocalVar = namedtuple('EntityLocalVar', 'name offset specific')
#
# Jump = namedtuple('Jump', 'dest')
# JumpIf = namedtuple('JumpIf', 'dest cond')
# JumpIfNot = namedtuple('JumpIfNot', 'dest cond')
#
# Push = namedtuple('Push', 'src')
# Pop = namedtuple('Pop', 'dest')
# Call = namedtuple('Call', 'name')
# Return = namedtuple('Return', '')
# Print = namedtuple('Print', 'args')
#
# Move = namedtuple('Move', 'src dest')
#
# Sync = namedtuple('Sync', '')
# Test = namedtuple('Test', 'cmd dest')
# Asm = namedtuple('Asm', 'args')
# ExecSel = namedtuple('ExecSel', 'label exec_type sel_type args')
# ExecEnd = namedtuple('ExecSelEnd', 'label')
# ExecChain = namedtuple('ExecChain', 'label exec_type args')
#
# StackPointer = namedtuple('StackPointer', 'type')(IntType())
# BasePointer = namedtuple('BasePointer', 'type')(IntType())
# GlobalIndex = namedtuple('GlobalIndex', 'type')(IntType())
# EntityLocalBase = namedtuple('EntityLocalBase', 'type')(IntType())
# ReturnRegister = namedtuple('ReturnRegister', 'type')(IntType())
#
# SlotOffset = namedtuple('SlotOffset', 'base offset type')
# GlobalSlot = namedtuple('GlobalSlot', 'offset type')
# EntityLocalSlot = namedtuple('EntityLocalSlot', 'offset type')
# Dereference = namedtuple('Dereference', 'addr type')
# Free = namedtuple('Free', 'slot')
#
# class Slot(namedtuple('Slot', 'idx type')):
# def __new__(cls, type):
# IR._counter += 1
# return tuple.__new__(cls, (IR._counter, type))
#
# Operation = namedtuple('Operation', 'op left right dest')
# UnaryOperation = namedtuple('UnaryOperation', 'op val dest')
#
# LiteralString = namedtuple('LiteralString', 'val type')
# LiteralInt = namedtuple('LiteralInt', 'val type')
#
# class Op:
#
# Add = namedtuple('Add', '')()
# Sub = namedtuple('Sub', '')()
# Mul = namedtuple('Mul', '')()
# Div = namedtuple('Div', '')()
# Mod = namedtuple('Mod', '')()
# Shl = namedtuple('Shl', '')()
# Shr = namedtuple('Shr', '')()
# And = namedtuple('And', '')()
# Xor = namedtuple('Xor', '')()
# Or = namedtuple('Or', '')()
# Eq = namedtuple('Eq', '')()
# Neq = namedtuple('Neq', '')()
# Lt = namedtuple('Lt', '')()
# Gt = namedtuple('Gt', '')()
# LtEq = namedtuple('LtEq', '')()
# GtEq = namedtuple('GtEq', '')()
# LogOr = namedtuple('LogOr', '')()
# LogAnd = namedtuple('LogAnd', '')()
#
# @classmethod
# def lookup(cls, op):
# return {
# '+': cls.Add,
# '-': cls.Sub,
# '*': cls.Mul,
# '/': cls.Div,
# '%': cls.Mod,
# '<<': cls.Shl,
# '>>': cls.Shr,
# '&': cls.And,
# '^': cls.Xor,
# '|': cls.Or,
# '==': cls.Eq,
# '!=': cls.Neq,
# '<': cls.Lt,
# '>': cls.Gt,
# '<=': cls.LtEq,
# '>=': cls.GtEq,
# '||': cls.LogOr,
# '&&': cls.LogAnd
# }[op]
#
# class UnaryOp:
#
# AddrOf = namedtuple('AddrOf', '')()
# Deref = namedtuple('Deref', '')()
# IntPromote = namedtuple('IntPromote', '')()
# Negate = namedtuple('Negate', '')()
# Not = namedtuple('Not', '')()
# LogNot = namedtuple('LogNot', '')()
#
#
# @classmethod
# def lookup(cls, op):
# return {
# '&': cls.AddrOf,
# '*': cls.Deref,
# '+': cls.IntPromote,
# '-': cls.Negate,
# '~': cls.Not,
# '!': cls.LogNot
# }[op]
. Output only the next line. | prop_dict[key.strip()] = value.strip() |
Based on the snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.argument('command', nargs=-1)
@standard_options()
<|code_end|>
, predict the immediate next line with the help of imports:
import click
import sys
from aeriscloud.cli.aeris.sync import sync
from aeriscloud.cli.helpers import standard_options, Command
from aeriscloud.utils import quote
and context (classes, functions, sometimes code) from other files:
# Path: aeriscloud/cli/aeris/sync.py
# def sync(box, direction):
# if not box.project.rsync_enabled():
# return None
#
# if direction == 'down':
# click.secho('Syncing files down from the box...',
# fg='cyan', bold=True)
# if box.rsync_down():
# click.secho('Sync down done!', fg='green', bold=True)
# else:
# click.secho('Sync down failed!', fg='red', bold=True)
# return False
# elif direction == 'up':
# click.secho('Syncing files up to the box...',
# fg='cyan', bold=True)
# if box.rsync_up():
# click.secho('Sync up done!', fg='green', bold=True)
# else:
# click.secho('Sync up failed!', fg='red', bold=True)
# return False
# else:
# click.secho('error: invalid direction %s' % direction,
# fg='red', bold=True)
# return False
#
# return True
#
# Path: aeriscloud/cli/helpers.py
# def standard_options(multiple=False, start_prompt=True):
# """
# Add the standard --project and --box options to a command
# :param multiple: Whether to find a single or multiple boxes
# :param start_prompt: When using single boxes, ask the user to start it if
# offline
# """
# if multiple:
# return _multi_box_decorator
# else:
# return _single_box_decorator(start_prompt)
#
# class Command(click.Command):
# # This is inherited by the Context to switch between pure POSIX and
# # argparse-like argument parsing. Setting it to false will push any
# # unknown flag to the argument located where the flag was declared
# allow_interspersed_args = config.get('config', 'posix', default=False)
#
# def __init__(self, *args, **kwargs):
# cs = dict(help_option_names=['-h', '--help'])
# super(Command, self).__init__(context_settings=cs,
# *args, **kwargs)
#
# Path: aeriscloud/utils.py
# def quote(s):
# """Return a shell-escaped version of the string *s*."""
# if not s:
# return "''"
# if _find_unsafe(s) is None:
# return s
#
# # use single quotes, and put single quotes into double quotes
# # the string $'b is then quoted as '$'"'"'b'
# return "'" + s.replace("'", "'\"'\"'") + "'"
. Output only the next line. | def cli(box, command): |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.option('-i', '--ip', is_flag=True,
help='Use the machine IP instead of the aeris.cd domain')
<|code_end|>
with the help of current file imports:
import click
from aeriscloud.cli.helpers import standard_options, Command
and context from other files:
# Path: aeriscloud/cli/helpers.py
# def standard_options(multiple=False, start_prompt=True):
# """
# Add the standard --project and --box options to a command
# :param multiple: Whether to find a single or multiple boxes
# :param start_prompt: When using single boxes, ask the user to start it if
# offline
# """
# if multiple:
# return _multi_box_decorator
# else:
# return _single_box_decorator(start_prompt)
#
# class Command(click.Command):
# # This is inherited by the Context to switch between pure POSIX and
# # argparse-like argument parsing. Setting it to false will push any
# # unknown flag to the argument located where the flag was declared
# allow_interspersed_args = config.get('config', 'posix', default=False)
#
# def __init__(self, *args, **kwargs):
# cs = dict(help_option_names=['-h', '--help'])
# super(Command, self).__init__(context_settings=cs,
# *args, **kwargs)
, which may contain function names, class names, or code. Output only the next line. | @click.argument('endpoint', default='') |
Here is a snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.option('-i', '--ip', is_flag=True,
help='Use the machine IP instead of the aeris.cd domain')
@click.argument('endpoint', default='')
@standard_options(multiple=False)
<|code_end|>
. Write the next line using the current file imports:
import click
from aeriscloud.cli.helpers import standard_options, Command
and context from other files:
# Path: aeriscloud/cli/helpers.py
# def standard_options(multiple=False, start_prompt=True):
# """
# Add the standard --project and --box options to a command
# :param multiple: Whether to find a single or multiple boxes
# :param start_prompt: When using single boxes, ask the user to start it if
# offline
# """
# if multiple:
# return _multi_box_decorator
# else:
# return _single_box_decorator(start_prompt)
#
# class Command(click.Command):
# # This is inherited by the Context to switch between pure POSIX and
# # argparse-like argument parsing. Setting it to false will push any
# # unknown flag to the argument located where the flag was declared
# allow_interspersed_args = config.get('config', 'posix', default=False)
#
# def __init__(self, *args, **kwargs):
# cs = dict(help_option_names=['-h', '--help'])
# super(Command, self).__init__(context_settings=cs,
# *args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | def cli(box, endpoint, ip): |
Given the code snippet: <|code_start|>
def gen_subcommands(self, multi_cmd, ctx):
for cmd_name in multi_cmd.list_commands(ctx):
subctx = multi_cmd.make_context('%s %s' % (
ctx.info_name,
cmd_name
), [''])
self.add_block(subcommand_header.format(
name=subctx.info_name,
ref_name=subctx.info_name.replace(' ', '-'),
subline=(len(subctx.info_name)+4) * '-'
), cmd_name)
# get command and retrieve help
cmd = multi_cmd.get_command(subctx, cmd_name)
self.add_block(cmd.get_help(subctx), cmd_name, indent=2)
if isinstance(cmd, Group):
self.gen_subcommands(cmd, subctx)
def add_block(self, text, source, indent=0):
for line in text.split('\n'):
self.add_line((u' ' * indent) + line.decode('utf-8'), source)
command_header = """
.. _command-{name}:
``{name}``
<|code_end|>
, generate the next line using the imports in this file:
from click.core import Group
from sphinx.ext.autodoc import Documenter
from aeriscloud.cli.main import get_cli
and context (functions, classes, or occasionally code) from other files:
# Path: aeriscloud/cli/main.py
# def get_cli(command_name):
# command_dir = os.path.join(module_path(), 'cli', command_name)
# return AerisCLI(command_dir, help=cmd_help[command_name])
. Output only the next line. | {subline} |
Here is a snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.argument('extra', nargs=-1)
@standard_options()
<|code_end|>
. Write the next line using the current file imports:
import click
from aeriscloud.cli.helpers import standard_options, Command, render_cli
from aeriscloud.utils import timestamp
and context from other files:
# Path: aeriscloud/cli/helpers.py
# def standard_options(multiple=False, start_prompt=True):
# """
# Add the standard --project and --box options to a command
# :param multiple: Whether to find a single or multiple boxes
# :param start_prompt: When using single boxes, ask the user to start it if
# offline
# """
# if multiple:
# return _multi_box_decorator
# else:
# return _single_box_decorator(start_prompt)
#
# class Command(click.Command):
# # This is inherited by the Context to switch between pure POSIX and
# # argparse-like argument parsing. Setting it to false will push any
# # unknown flag to the argument located where the flag was declared
# allow_interspersed_args = config.get('config', 'posix', default=False)
#
# def __init__(self, *args, **kwargs):
# cs = dict(help_option_names=['-h', '--help'])
# super(Command, self).__init__(context_settings=cs,
# *args, **kwargs)
#
# def render_cli(template, **kwargs):
# env = jinja_env('aeriscloud.cli', 'templates')
# template = env.get_template(template + '.j2')
# kwargs['fg'] = JinjaColors()
# kwargs['bold'] = click.style('', bold=True, reset=False)
# kwargs['reset'] = click.style('')
# return template.render(**kwargs)
#
# Path: aeriscloud/utils.py
# def timestamp(text, **kwargs):
# """
# Writes text with a timestamp
# :param text:
# :return:
# """
# for line in text.split('\n'):
# # TODO: something we could do is detect the last ansi code on each
# # line and report it to the next line so that multiline codes
# # are not reset/lost
# secho('[%s] ' % (now().format('HH:mm:ss')), fg='reset', nl=False)
# secho(line, **kwargs)
, which may include functions, classes, or code. Output only the next line. | def cli(box, extra): |
Using the snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.argument('extra', nargs=-1)
@standard_options()
<|code_end|>
, determine the next line of code. You have imports:
import click
from aeriscloud.cli.helpers import standard_options, Command, render_cli
from aeriscloud.utils import timestamp
and context (class names, function names, or code) available:
# Path: aeriscloud/cli/helpers.py
# def standard_options(multiple=False, start_prompt=True):
# """
# Add the standard --project and --box options to a command
# :param multiple: Whether to find a single or multiple boxes
# :param start_prompt: When using single boxes, ask the user to start it if
# offline
# """
# if multiple:
# return _multi_box_decorator
# else:
# return _single_box_decorator(start_prompt)
#
# class Command(click.Command):
# # This is inherited by the Context to switch between pure POSIX and
# # argparse-like argument parsing. Setting it to false will push any
# # unknown flag to the argument located where the flag was declared
# allow_interspersed_args = config.get('config', 'posix', default=False)
#
# def __init__(self, *args, **kwargs):
# cs = dict(help_option_names=['-h', '--help'])
# super(Command, self).__init__(context_settings=cs,
# *args, **kwargs)
#
# def render_cli(template, **kwargs):
# env = jinja_env('aeriscloud.cli', 'templates')
# template = env.get_template(template + '.j2')
# kwargs['fg'] = JinjaColors()
# kwargs['bold'] = click.style('', bold=True, reset=False)
# kwargs['reset'] = click.style('')
# return template.render(**kwargs)
#
# Path: aeriscloud/utils.py
# def timestamp(text, **kwargs):
# """
# Writes text with a timestamp
# :param text:
# :return:
# """
# for line in text.split('\n'):
# # TODO: something we could do is detect the last ansi code on each
# # line and report it to the next line so that multiline codes
# # are not reset/lost
# secho('[%s] ' % (now().format('HH:mm:ss')), fg='reset', nl=False)
# secho(line, **kwargs)
. Output only the next line. | def cli(box, extra): |
Given the code snippet: <|code_start|> return {'content-type': 'application/json'}
def get_vms(self):
url = self._api_url + '/api/vms'
r = self._do_request('get', url, headers=self.get_headers())
if r.status_code == 400:
return r.text.strip('"'), None
r.raise_for_status()
return r.json()
def signup(self, password, fullname=None):
if not self._api_url:
return
url = self._api_url + '/api/signup'
payload = {
'username': self._username,
'password': password,
'details': {
'email': self._email,
'localip': local_ip(),
'fullname': fullname
}
}
<|code_end|>
, generate the next line using the imports in this file:
import json
import os
import sys
import requests
from .config import config, expose_url, \
configparser, data_dir
from .log import get_logger
from .utils import local_ip
from requests.exceptions import Timeout, ConnectionError
from requests.auth import HTTPBasicAuth
and context (functions, classes, or occasionally code) from other files:
# Path: aeriscloud/config.py
# def module_path():
# def __init__(self):
# def load(self):
# def has(self, section, option):
# def get(self, section, option, **kwargs):
# def set(self, section, option, value):
# def unset(self, section, option):
# def save(self):
# def dump(self):
# def complete(self):
# def inventory_path():
# def config_dir():
# def data_dir():
# def config_ini_path():
# def projects_path():
# def basebox_bucket():
# def default_organization():
# def expose_username():
# def expose_url():
# def has_github_integration():
# def verbosity(val=None):
# class Config(object):
#
# Path: aeriscloud/log.py
# def get_logger(name=None, parent=_logger):
# if name:
# if not hasattr(parent, 'getChild'):
# return parent.manager.getLogger('.'.join([parent.name, name]))
# return parent.getChild(name)
# return parent
#
# Path: aeriscloud/utils.py
# def local_ip():
# """
# Retrieve the first ip from the interface linked to the default route
#
# :return str
# """
# sys_name = system()
# if sys_name == 'Darwin':
# # OSX
# route = Command('route')
# ifconfig = Command('ifconfig')
#
# iface = [
# line.strip()
# for line in route('-n', 'get', 'default')
# if line.strip().startswith('interface')
# ][0].split(':')[1].strip()
# return [
# line.strip()
# for line in ifconfig(iface)
# if line.strip().startswith('inet ')
# ][0].split(' ')[1]
# elif sys_name == 'Linux':
# try:
# ip = Command('ip')
# iface = [
# line.strip()
# for line in ip('route')
# if line.strip().startswith('default ')
# ][0].split(' ')[4]
# except CommandNotFound:
# route = Command('route')
# iface = [
# line.strip()
# for line in route('-n')
# if line.startswith('0.0.0.0')
# ][0].split(' ').pop()
#
# try:
# # try with IP
# ip = Command('ip')
# return [
# line.strip()
# for line in ip('addr', 'show', iface)
# if line.strip().startswith('inet ')
# ][0].split(' ')[1].split('/')[0]
# except CommandNotFound:
# pass
#
# # fallback to ifconfig
# ifconfig = Command('ifconfig')
# return [
# line.strip()
# for line in ifconfig(iface)
# if line.strip().startswith('inet ')
# ][0].split(' ')[1]
#
# return None
. Output only the next line. | r = self._requests.post(url, |
Based on the snippet: <|code_start|> self._config.read(self.file())
def file(self):
return os.path.join(data_dir(), 'expose.ini')
def save(self):
with open(self.file(), 'w') as f:
self._config.write(f)
return True
def start(self):
config.set('aeris', 'enabled', 'true')
config.save()
def stop(self):
config.set('aeris', 'enabled', 'false')
config.save()
def enabled(self):
default = 'true'
if not config.get('aeris', 'url', default=None):
default = 'false'
return config.get('aeris', 'enabled', default=default) == 'true'
def announce(self):
client = expose_client()
if not client:
return False
service_list = [{'service': service['service'],
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import os
import sys
import requests
from .config import config, expose_url, \
configparser, data_dir
from .log import get_logger
from .utils import local_ip
from requests.exceptions import Timeout, ConnectionError
from requests.auth import HTTPBasicAuth
and context (classes, functions, sometimes code) from other files:
# Path: aeriscloud/config.py
# def module_path():
# def __init__(self):
# def load(self):
# def has(self, section, option):
# def get(self, section, option, **kwargs):
# def set(self, section, option, value):
# def unset(self, section, option):
# def save(self):
# def dump(self):
# def complete(self):
# def inventory_path():
# def config_dir():
# def data_dir():
# def config_ini_path():
# def projects_path():
# def basebox_bucket():
# def default_organization():
# def expose_username():
# def expose_url():
# def has_github_integration():
# def verbosity(val=None):
# class Config(object):
#
# Path: aeriscloud/log.py
# def get_logger(name=None, parent=_logger):
# if name:
# if not hasattr(parent, 'getChild'):
# return parent.manager.getLogger('.'.join([parent.name, name]))
# return parent.getChild(name)
# return parent
#
# Path: aeriscloud/utils.py
# def local_ip():
# """
# Retrieve the first ip from the interface linked to the default route
#
# :return str
# """
# sys_name = system()
# if sys_name == 'Darwin':
# # OSX
# route = Command('route')
# ifconfig = Command('ifconfig')
#
# iface = [
# line.strip()
# for line in route('-n', 'get', 'default')
# if line.strip().startswith('interface')
# ][0].split(':')[1].strip()
# return [
# line.strip()
# for line in ifconfig(iface)
# if line.strip().startswith('inet ')
# ][0].split(' ')[1]
# elif sys_name == 'Linux':
# try:
# ip = Command('ip')
# iface = [
# line.strip()
# for line in ip('route')
# if line.strip().startswith('default ')
# ][0].split(' ')[4]
# except CommandNotFound:
# route = Command('route')
# iface = [
# line.strip()
# for line in route('-n')
# if line.startswith('0.0.0.0')
# ][0].split(' ').pop()
#
# try:
# # try with IP
# ip = Command('ip')
# return [
# line.strip()
# for line in ip('addr', 'show', iface)
# if line.strip().startswith('inet ')
# ][0].split(' ')[1].split('/')[0]
# except CommandNotFound:
# pass
#
# # fallback to ifconfig
# ifconfig = Command('ifconfig')
# return [
# line.strip()
# for line in ifconfig(iface)
# if line.strip().startswith('inet ')
# ][0].split(' ')[1]
#
# return None
. Output only the next line. | 'port': service['port']} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.