Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> @pytest.mark.usefixtures('is_linux') def test_uses_default_when_node_and_npm_are_not_available(find_exe_mck): find_exe_mck.return_value = None assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT @pytest.mark.usefixtures('is_win32') def test...
prefix_dir.join('package.json').write('{"name": "t", "version": "1.0.0"}')
Given snippet: <|code_start|>def is_linux(): with mock.patch.object(sys, 'platform', 'linux'): yield @pytest.fixture def is_win32(): with mock.patch.object(sys, 'platform', 'win32'): yield @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck...
def test_sets_default_on_windows(find_exe_mck):
Using the snippet: <|code_start|>def is_win32(): with mock.patch.object(sys, 'platform', 'win32'): yield @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.mark.usefixtures('is_linux') def test_sets_system_when_node_and_npm_...
def test_healthy_system_node(tmpdir):
Given snippet: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = node.get_default_version.__wrapped__ @pytest.fixture def is_linux(): with mock.patch.object(sys, 'platform', 'linux'): yield @pytest.fixture def is_win32(): with mock.patch.object(sys, 'platform', 'win3...
def find_exe_mck():
Continue the code snippet: <|code_start|>from __future__ import annotations ENVIRONMENT_DIR = None get_default_version = helpers.basic_get_default_version healthy = helpers.basic_healthy install_environment = helpers.no_install <|code_end|> . Use current file imports: from typing import Sequence from pre_commit.h...
def run_hook(
Continue the code snippet: <|code_start|>from __future__ import annotations ENVIRONMENT_DIR = None get_default_version = helpers.basic_get_default_version healthy = helpers.basic_healthy install_environment = helpers.no_install <|code_end|> . Use current file imports: from typing import Sequence from pre_commit.h...
def run_hook(
Based on the snippet: <|code_start|> foo_file.write(FOO_CONTENTS.replace('1', 'a')) _test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'a'), 'AM') with staged_files_only(patch_dir): _test_foo_state(foo_staged) # Modify in the same place as the stashed diff with open(foo_stag...
assert status == actual_status
Given snippet: <|code_start|> test_foo_something_unstaged(foo_staged, patch_dir) def test_foo_something_unstaged_diff_color_always(foo_staged, patch_dir): cmd_output('git', 'config', '--local', 'color.diff', 'always') test_foo_something_unstaged(foo_staged, patch_dir) def test_foo_both_modify_non_conflic...
_test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'a'), 'AM')
Using the snippet: <|code_start|> FOO_CONTENTS = '\n'.join(('1', '2', '3', '4', '5', '6', '7', '8', '')) @pytest.fixture def patch_dir(tempdir_factory): return tempdir_factory.get() def get_short_git_status(): git_status = cmd_output('git', 'status', '-s')[1] line_parts = [line.split() for line in git...
):
Predict the next line after this snippet: <|code_start|> FOO_CONTENTS = '\n'.join(('1', '2', '3', '4', '5', '6', '7', '8', '')) @pytest.fixture def patch_dir(tempdir_factory): return tempdir_factory.get() def get_short_git_status(): git_status = cmd_output('git', 'status', '-s')[1] line_parts = [line...
encoding='UTF-8',
Next line prediction: <|code_start|> with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write(f'{FOO_CONTENTS}9\n') _test_foo_state(foo_staged, f'{FOO_CONTENTS}9\n', 'AM') with staged_files_only(patch_dir): _test_foo_state(foo_staged) # Modify the file as part of the "pr...
_test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'b'), 'AM')
Next line prediction: <|code_start|> FOO_CONTENTS = '\n'.join(('1', '2', '3', '4', '5', '6', '7', '8', '')) @pytest.fixture def patch_dir(tempdir_factory): return tempdir_factory.get() def get_short_git_status(): git_status = cmd_output('git', 'status', '-s')[1] line_parts = [line.split() for line in...
encoding='UTF-8',
Predict the next line for this snippet: <|code_start|> foo_contents=FOO_CONTENTS, status='A', encoding='UTF-8', ): assert os.path.exists(path.foo_filename) with open(path.foo_filename, encoding=encoding) as f: assert f.read() == foo_contents actual_status = get_short_git_statu...
_test_foo_state(foo_staged, 'herp\nderp\n', 'AM')
Given the following code snippet before the placeholder: <|code_start|> return tempdir_factory.get() def get_short_git_status(): git_status = cmd_output('git', 'status', '-s')[1] line_parts = [line.split() for line in git_status.splitlines()] return {v: k for k, v in line_parts} @pytest.fixture def f...
def test_foo_staged(foo_staged):
Here is a snippet: <|code_start|>from __future__ import annotations def _test(*, before, patch, expected): env = before.copy() with envcontext(patch, _env=env): assert env == expected assert env == before def test_trivial(): _test(before={}, patch={}, expected={}) def test_noop(): _...
patch=[('foo', 'bar')],
Given the following code snippet before the placeholder: <|code_start|> _test( before={}, patch=[('PATH', ('~/bin:', Var('PATH')))], expected={'PATH': '~/bin:'}, ) def test_templated_environment_variable_defaults(): _test( before={}, patch=[('PATH', ('~/bin:', Var('P...
expected={'foo': 'baz', 'herp': 'foo: bar'},
Given the code snippet: <|code_start|> expected={'PATH': '~/bin:/usr/local/bin:/usr/bin'}, ) def test_templated_environ_sources_from_previous(): _test( before={'foo': 'bar'}, patch=( ('foo', 'baz'), ('herp', ('foo: ', Var('foo'))), ), expected={'f...
assert os.environ == {'FOO': 'bar', 'HERP': 'derp'}
Based on the snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('ctx', 'expected'), ( pytest.param( ( ('PRE_COMMIT_USE_MICROMAMBA', envcontext.UNSET), ('PRE_COMMIT_USE_MAMBA', envcontext.UNSET), ), ...
),
Given the code snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('ctx', 'expected'), ( pytest.param( ( ('PRE_COMMIT_USE_MICROMAMBA', envcontext.UNSET), ('PRE_COMMIT_USE_MAMBA', envcontext.UNSET), ), ...
(
Next line prediction: <|code_start|>from __future__ import annotations ENVIRONMENT_DIR = 'dotnetenv' BIN_DIR = 'bin' get_default_version = helpers.basic_get_default_version healthy = helpers.basic_healthy def get_env_patch(venv: str) -> PatchesT: return ( ('PATH', (os.path.join(venv, BIN_DIR), os.path...
@contextlib.contextmanager
Given the code snippet: <|code_start|>from __future__ import annotations ENVIRONMENT_DIR = 'dotnetenv' BIN_DIR = 'bin' get_default_version = helpers.basic_get_default_version healthy = helpers.basic_healthy def get_env_patch(venv: str) -> PatchesT: return ( ('PATH', (os.path.join(venv, BIN_DIR), os.pa...
@contextlib.contextmanager
Next line prediction: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('url', 'expected'), ( ('/im/a/path/on/disk', 'unknown_src_dir'), ('file:///im/a/path/on/disk', 'unknown_src_dir'), ('git@github.com:golang/lint', 'github.com/golang/lint'), ('git...
('ssh://git@github.com/golang/lint', 'github.com/golang/lint'),
Here is a snippet: <|code_start|>from __future__ import annotations def test_read_pyvenv_cfg(tmpdir): pyvenv_cfg = tmpdir.join('pyvenv.cfg') pyvenv_cfg.write( '# I am a comment\n' '\n' 'foo = bar\n' 'version-info=123\n', ) <|code_end|> . Write the next line using the cur...
expected = {'foo': 'bar', 'version-info': '123'}
Next line prediction: <|code_start|> expected_path = fr'{home}\python343' else: # pragma: nt no cover path = '~/.pyenv/versions/3.4.3/bin/python' expected_path = f'{home}/.pyenv/versions/3.4.3/bin/python' result = python.norm_version(path) assert result == expected_path def test_no...
('/usr/bin/python3.7m', '/usr/bin/python3.7m', 'python3.7m'),
Next line prediction: <|code_start|>) def test_find_by_sys_executable(exe, realpath, expected): with mock.patch.object(sys, 'executable', exe): with mock.patch.object(os.path, 'realpath', return_value=realpath): with mock.patch.object(python, 'find_executable', lambda x: x): asse...
def test_healthy_venv_creator(python_dir):
Given snippet: <|code_start|> pyvenv_cfg = tmpdir.join('pyvenv.cfg') pyvenv_cfg.write( '# I am a comment\n' '\n' 'foo = bar\n' 'version-info=123\n', ) expected = {'foo': 'bar', 'version-info': '123'} assert python._read_pyvenv_cfg(pyvenv_cfg) == expected def test_rea...
def test_norm_version_of_default_is_sys_executable():
Given snippet: <|code_start|> hook_id = 'parse-file-no-opts-args' expected_args = ['--no-cache'] _test_r_parsing( tempdir_factory, store, hook_id, expected_args=expected_args, ) def test_r_parsing_expr_no_opts_no_args1(tempdir_factory, store): hook_id = 'parse-expr-no-opts-no-args-1' _t...
'The only valid syntax is `Rscript -e {expr}`',
Given the code snippet: <|code_start|>from __future__ import annotations def _test_r_parsing( tempdir_factory, store, hook_id, expected_hook_expr={}, expected_args={}, config={}, expect_path_prefix=True, ): repo_path = 'r_hooks_repo' path = make_repo(tempdir_factory, repo_path) ...
expected_cmd,
Predict the next line after this snippet: <|code_start|> def test_r_parsing_expr_args_in_entry2(tempdir_factory, store): with pytest.raises(ValueError) as execinfo: r._entry_validate(['Rscript', '-e', 'expr1', '--another-arg']) msg = execinfo.value.args assert msg == ('You can supply at most one e...
_test_r_parsing(
Predict the next line after this snippet: <|code_start|> assert ret == expected def test_r_parsing_file_no_opts_no_args(tempdir_factory, store): hook_id = 'parse-file-no-opts-no-args' _test_r_parsing(tempdir_factory, store, hook_id) def test_r_parsing_file_opts_no_args(tempdir_factory, store): with p...
tempdir_factory, store, hook_id, expected_hook_expr=('-e', '1+1'),
Next line prediction: <|code_start|>from __future__ import annotations Loader = getattr(yaml, 'CSafeLoader', yaml.SafeLoader) yaml_load = functools.partial(yaml.load, Loader=Loader) Dumper = getattr(yaml, 'CSafeDumper', yaml.SafeDumper) def yaml_dump(o: Any, **kwargs: Any) -> str: # when python/mypy#1484 is s...
return f'<unprintable {type(exc).__name__} object>'.encode()
Given the code snippet: <|code_start|>from __future__ import annotations def norm_slash(*args): return tuple(x.replace('/', os.sep) for x in args) @pytest.mark.parametrize( ('prefix', 'path_end', 'expected_output'), ( norm_slash('foo', '', 'foo'), <|code_end|> , generate the next line using t...
norm_slash('foo', 'bar', 'foo/bar'),
Next line prediction: <|code_start|>from __future__ import annotations ENVIRONMENT_DIR = None get_default_version = helpers.basic_get_default_version healthy = helpers.basic_healthy install_environment = helpers.no_install def run_hook( hook: Hook, file_args: Sequence[str], color: bool, ) -...
out += b'\n'.join(f.encode() for f in file_args) + b'\n'
Next line prediction: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('in_text', 'in_color', 'in_use_color', 'expected'), ( ('foo', GREEN, True, f'{GREEN}foo\033[m'), ('foo', GREEN, False, 'foo'), ), ) def test_format_color(in_text, in_color, in_use_color, expect...
def test_use_color_no_tty():
Given the code snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('in_text', 'in_color', 'in_use_color', 'expected'), ( ('foo', GREEN, True, f'{GREEN}foo\033[m'), ('foo', GREEN, False, 'foo'), <|code_end|> , generate the next line using the imports in this file...
),
Given snippet: <|code_start|> assert ret == expected def test_use_color_never(): assert use_color('never') is False def test_use_color_always(): assert use_color('always') is True def test_use_color_no_tty(): with mock.patch.object(sys.stderr, 'isatty', return_value=False): assert use_color...
def test_use_color_dumb_term():
Given the code snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('in_text', 'in_color', 'in_use_color', 'expected'), ( ('foo', GREEN, True, f'{GREEN}foo\033[m'), ('foo', GREEN, False, 'foo'), ), ) def test_format_color(in_text, in_color, in_use_color, expe...
def test_use_color_tty_with_color_support():
Based on the snippet: <|code_start|>from __future__ import annotations def _log_record(message, level): return logging.LogRecord('name', level, '', 1, message, {}, None) def test_logging_handler_color(cap_out): handler = LoggingHandler(True) <|code_end|> , predict the immediate next line with the help of ...
handler.emit(_log_record('hi', logging.WARNING))
Continue the code snippet: <|code_start|> return len(full_cmd.encode('utf-16le')) // 2 else: return len(full_cmd.encode(sys.getfilesystemencoding())) class ArgumentTooLongError(RuntimeError): pass def partition( cmd: Sequence[str], varargs: Sequence[str], target_concur...
arg = varargs.pop()
Given the following code snippet before the placeholder: <|code_start|>from __future__ import annotations TArg = TypeVar('TArg') TRet = TypeVar('TRet') def _environ_size(_env: MutableMapping[str, str] | None = None) -> int: environ = _env if _env is not None else getattr(os, 'environb', os.environ) size = ...
return size
Given the following code snippet before the placeholder: <|code_start|>from __future__ import annotations TArg = TypeVar('TArg') TRet = TypeVar('TRet') def _environ_size(_env: MutableMapping[str, str] | None = None) -> int: environ = _env if _env is not None else getattr(os, 'environb', os.environ) size = ...
return 2 ** 12
Using the snippet: <|code_start|>from __future__ import annotations @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' <|code_end|> , determine the ne...
return os.path.normpath('/home/me')
Here is a snippet: <|code_start|>from __future__ import annotations @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' return os.path.normpath...
with mock.patch.object(os.path, 'expanduser', fake_expanduser):
Continue the code snippet: <|code_start|>from __future__ import annotations @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' return os.path....
with mock.patch.object(os.path, 'expanduser', fake_expanduser):
Predict the next line after this snippet: <|code_start|>def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' return os.path.normpath('/home/me') with mock.patch...
def test_exe_exists_false_if_homedir(find_exe_mck, homedir_mck):
Continue the code snippet: <|code_start|>@pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' return os.path.normpath('/home/me') with mock.patch.object(os.path, 'expanduser', fake_expanduser): yield def test_exe_exists_does_not_exist(find_exe_mck, homedir_mc...
def test_exe_exists_commonpath_raises_ValueError(find_exe_mck, homedir_mck):
Predict the next line for this snippet: <|code_start|> src = tmpdir.join('src').ensure_dir() cmd_output('git', 'init', str(src)) git_commit(cwd=str(src)) cmd_output('git', 'worktree', 'add', '.git/trees/foo', 'HEAD', cwd=src) with src.join('.git/trees/foo').as_cwd(): assert git.get_root() =...
def test_cherry_pick_conflict(in_merge_conflict):
Using the snippet: <|code_start|> def test_is_in_merge_conflict(in_merge_conflict): assert git.is_in_merge_conflict() is True def test_is_in_merge_conflict_submodule(in_conflicting_submodule): assert git.is_in_merge_conflict() is True def test_cherry_pick_conflict(in_merge_conflict): cmd_output('git', ...
assert ret == {'conflict_file', 'other_file'}
Continue the code snippet: <|code_start|> cmd_output('git', 'rm', '--cached', 'test') assert git.get_staged_files() == [] def test_is_not_in_merge_conflict(in_git_dir): assert git.is_in_merge_conflict() is False def test_is_in_merge_conflict(in_merge_conflict): assert git.is_in_merge_conflict() is Tr...
resolve_conflict()
Next line prediction: <|code_start|> config = { 'repos': [ { 'repo': 'meta', 'hooks': [ { 'id': 'check-useless-excludes', 'types': ['python'], }, ], ...
'exclude_types': ['yaml'],
Using the snippet: <|code_start|> out, _ = capsys.readouterr() assert 'check-useless-excludes does not apply to this repository' in out def test_hook_types_excludes_everything(capsys, in_git_dir, mock_store_dir): config = { 'repos': [ { 'repo': 'meta', 'h...
{
Here is a snippet: <|code_start|> ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(find_exe_mck): find_exe_mck.return_val...
end
Next line prediction: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(fi...
Gem::Specification.new do |s|
Using the snippet: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(find_...
s.version = '0.0.0'
Here is a snippet: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(find_...
find_exe_mck.return_value = '/path/to/exe'
Based on the snippet: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(fi...
@pytest.fixture
Here is a snippet: <|code_start|>from __future__ import annotations def test_sample_config(capsys): ret = sample_config() <|code_end|> . Write the next line using the current file imports: from pre_commit.commands.sample_config import sample_config and context from other files: # Path: pre_commit/commands/sam...
assert ret == 0
Given snippet: <|code_start|>def test_negate_by_line_all_match(cap_out): ret = pygrep.main(('pattern', 'f4', 'f5', 'f6', '--negate')) out = cap_out.get() assert ret == 0 assert out == '' @pytest.mark.usefixtures('some_files') def test_negate_by_file_no_match(cap_out): ret = pygrep.main(('baz', 'f4...
out = cap_out.get()
Predict the next line for this snippet: <|code_start|>from __future__ import annotations logger = logging.getLogger('pre_commit') LOG_LEVEL_COLORS = { 'DEBUG': '', <|code_end|> with the help of current file imports: import contextlib import logging from typing import Generator from pre_commit import color fro...
'INFO': '',
Given the following code snippet before the placeholder: <|code_start|># Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. #This code is shared with tackpy (somewhat), so I'd rather make minimal #changes, and preserve the use of a2b_base64 throughout. def a2b_base64(s): ...
return bytesToBase64(b)
Given the following code snippet before the placeholder: <|code_start|> alertStr = str(self.description) return alertStr class TLSAuthenticationError(TLSError): """The handshake succeeded, but the other party's authentication was inadequate. This exception will only be raised when a ...
class TLSAuthorizationError(TLSAuthenticationError):
Here is a snippet: <|code_start|> memAvailable = 0 memInfo = os.popen('free -t -m').read() for line in memInfo.splitlines(): if line.rstrip().startswith('Mem:'): memAvailable = int(line.split()[1]) # Give room for swap space if memAvailable < 900: sys.exit('Less than 1GB ...
userQuestion += "\033[1mWhich Interface Should be Used(web admin and spoofing)\033[0m: "
Here is a snippet: <|code_start|> else: break bro.install(chosenInterface, 'localhost') if criticalStackInstalled == False and installCriticalStack.lower() == 'y': criticalStack.install(csKey) else: print "Skipping Critical Stack...
while True:
Given the code snippet: <|code_start|> def getIP(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) except: return '' def validateIP(ip): if re.match(r'^(\d{1,3}\.){3}\d{1...
question += "\033[1m3 - \033[4mWeb Server Only\033[0m: Elasticsearch, Kibana, Apache\n"
Given snippet: <|code_start|> if installFileCheck.lower() not in ('y', 'n', ''): print "Must choose Y or N." else: break if installFileCheck.lower() == 'y': installFileCheck = 'y' while True: fileCheckKey = get_user_i...
criticalStackInstalled = True
Next line prediction: <|code_start|>#!/usr/bin/env python # Local Installer Scripts # Issue: When using OpenDNS, no hostname resolution class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' ...
try:
Using the snippet: <|code_start|> memAvailable = 0 memInfo = os.popen('free -t -m').read() for line in memInfo.splitlines(): if line.rstrip().startswith('Mem:'): memAvailable = int(line.split()[1]) # Give room for swap space if memAvailable < 900: sys.exit('Less than 1GB ...
userQuestion += "\033[1mWhich Interface Should be Used(web admin and spoofing)\033[0m: "
Using the snippet: <|code_start|> def getIP(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) except: return '' def validateIP(ip): if re.match(r'^(\d{1,3}\.){3}\d{1,3}$'...
question += "\033[1m3 - \033[4mWeb Server Only\033[0m: Elasticsearch, Kibana, Apache\n"
Given snippet: <|code_start|> installCriticalStack = get_user_input( "\033[1mInstall Critical Stack Threat Intel For Bro IDS (Y/n)\033[0m: ") if installCriticalStack.lower() not in ('y', 'n', ''): print("Must choose Y or N.") else: ...
if installFail2Ban.lower() not in ('y', 'n', ''):
Given the following code snippet before the placeholder: <|code_start|> class GoogleCloudDatastore(Storage): def __init__(self, namespace=None): self._logger = logging.getLogger("flask-blogging") self._client = datastore.Client(namespace=namespace) def _get_new_post_id(self): key = se...
return int(counter)
Continue the code snippet: <|code_start|>try: except ImportError: pass <|code_end|> . Use current file imports: from builtins import str from collections import defaultdict, OrderedDict from sqlalchemy.ext.automap import automap_base from .storage import Storage from .signals import sqla_initialized import sy...
this = sys.modules[__name__]
Using the snippet: <|code_start|>try: except ImportError: pass this = sys.modules[__name__] this.Post = None this.Tag = None def _as_int(s): try: n = int(s) if s is not None else None return n except ValueError: <|code_end|> , determine the next line of code. You have imports: from b...
return None
Given the following code snippet before the placeholder: <|code_start|> { 'AttributeName': 'post_id', 'AttributeType': 'S' }, { 'AttributeName': 'user_id', 'Attribut...
'AttributeName': 'tag_id',
Here is a snippet: <|code_start|> <div> <div> <div>selected</div> </div> </div> <!-- comment --> <div>not selected</div> <p>not selected</p>""" expected = expected_result(""" <div> <div> selected </div> </div> <div> selected </div>"...
<div>
Predict the next line for this snippet: <|code_start|> <div> <div> selected </div> </div> <div> selected </div>""") assert query_html_doc(html_body, '/html/body/div/descendant::div') == expected assert query_html_doc(html_body, '/html/body/div/~::div') == expected def test...
</div>""")
Predict the next line for this snippet: <|code_start|> <p> daughter </p> </div>""") def test_parent_axis_returns_parents_for_multiple_matching_nodes(): html_body = """ <div id="first"> <p> </p> </div> <div id="second"> <p> </p> </div>""" assert query_html...
</div>
Given the code snippet: <|code_start|> actual_without = query_context_node(html_without, 'child::para[position()=5][attribute::type="warning"]') assert actual_with == expected_result(""" <para type="warning"> para five </para>""") assert actual_without == expected_result('') def test_selects_...
<context>
Given snippet: <|code_start|> html = """ <root> <notpara/> <para>selected</para> </root>""" soup = make_soup(html) assert query_context_node(soup.root.notpara, '/descendant::para') == expected_result(""" <para> selected </para>""") def test_selects_all_the_item_elements...
<context>
Next line prediction: <|code_start|> selected </item>""") def test_selects_the_first_para_child_of_the_context_node(): html = """ <context> <para>selected</para> <para>not selected</para> </context>""" assert query_context_node(html, 'child::para[position()=1]') == expected_res...
<context>
Using the snippet: <|code_start|> <context> <para>not selected</para> <foo> <notpara>not selected</notpara> <para>selected</para> </foo> <bar> <para>also selected</para> </bar> </context>""" assert query_context_node(html, 'child::*/...
<notpara/>
Predict the next line for this snippet: <|code_start|> exports = ('class_', 'even', 'odd') def class_(*args): if len(args) == 1: tag = get_context_node() name = args[0] elif len(args) == 2: HqueryEvaluationError.must_be_node_set(args[0]) tag = args[0][0] name = args[1] ...
def odd():
Given the following code snippet before the placeholder: <|code_start|> raise HqueryEvaluationError('replace() expects 3 or 4 arguments; was passed {0}'.format(argc)) input = string_value(args[0]) pattern = args[1] replacement = args[2] if argc == 4: flags = _xpath_flags_to_re_flags(args...
else:
Given the following code snippet before the placeholder: <|code_start|> return re.sub(pattern, replacement, input, flags=flags) def string_join(sequence, *args): if len(args) > 0: delimiter = args[0] else: delimiter = '' return delimiter.join([string_value(x) for x in sequence]) def t...
def _xpath_flags_to_re_flags(flags):
Given the following code snippet before the placeholder: <|code_start|> input = string_value(get_context_node()) pattern = args[0] else: input = string_value(args[0]) pattern = args[1] if scenario == 3: flags = _xpath_flags_to_re_flags(args[2]) return boolean(...
else:
Continue the code snippet: <|code_start|> if scenario == 1: input = string_value(get_context_node()) pattern = args[0] else: input = string_value(args[0]) pattern = args[1] if scenario == 3: flags = _xpath_flags_to_re_flags(args[2]) return boolean(re.searc...
delimiter = args[0]
Predict the next line after this snippet: <|code_start|> def test_union_decomposition_with_parentheses(): html_body = """ <h1>heading</h1> <p>content</p> <h1>another heading</h1>""" assert query_html_doc(html_body, '(//h1 | //p) => ("fizz" | "buzz")') == expected_result(""" fizz buzz f...
h1 heading
Continue the code snippet: <|code_start|> <h1>heading</h1> <p>content</p> <h1>another heading</h1>""" assert query_html_doc(html_body, '(//h1 | //p) => ("fizz" | "buzz")') == expected_result(""" fizz buzz fizz""") def test_union_decomposition_naked(): html_body = """ <h1>heading</h1...
one
Continue the code snippet: <|code_start|> context_stack = [] class ExpressionContext: def __init__(self, node, position=1, size=1, preserve_space=None): self.node = node self.position = position self.size = size if preserve_space is not None: self.preserve_space = pres...
except ExpressionStackEmptyError:
Given the following code snippet before the placeholder: <|code_start|>class ExpressionContext: def __init__(self, node, position=1, size=1, preserve_space=None): self.node = node self.position = position self.size = size if preserve_space is not None: self.preserve_spac...
except IndexError:
Continue the code snippet: <|code_start|> self.return_expression = None self.sequence_expression = None self.sequence_variable = None def __str__(self): return '{0}{1}return <expr>'.format( '' if self.sequence_expression is None else 'for ${0}:=<expr> '.format(self.seque...
result = self._evaluate_without_iteration()
Given snippet: <|code_start|> class Flwor: def __init__(self): self.global_variables = [] self.per_iteration_variables = [] self.return_expression = None self.sequence_expression = None self.sequence_variable = None def __str__(self): <|code_end|> , continue by predic...
return '{0}{1}return <expr>'.format(
Given the code snippet: <|code_start|> class Flwor: def __init__(self): self.global_variables = [] <|code_end|> , generate the next line using the imports in this file: from hq.hquery.object_type import debug_dump_anything from hq.hquery.sequences import make_sequence, sequence_concat from hq.hquery.synt...
self.per_iteration_variables = []
Given the following code snippet before the placeholder: <|code_start|> class Flwor: def __init__(self): self.global_variables = [] self.per_iteration_variables = [] self.return_expression = None self.sequence_expression = None self.sequence_variable = None def __str_...
)
Given snippet: <|code_start|> self.sequence_variable = variable_name self.sequence_expression = expression_fn def set_return_expression(self, expression_fn): if self.return_expression is not None: raise HquerySyntaxError('More than one return clause found for FLWOR {0}'.format(s...
return result
Based on the snippet: <|code_start|> self.global_variables.append(var_tuple) else: self.per_iteration_variables.append(var_tuple) def debug_dump(self): return debug_dump_long_string(str(self)) def evaluate(self): verbose_print('Evaluating FLWOR {0}'.format(self...
if self.return_expression is not None:
Predict the next line for this snippet: <|code_start|> self._push_global_variables() sequence = make_sequence(self.sequence_expression()) verbose_print('Iterating over sequence containing {0} items'.format(len(sequence))) result = [] for item in sequence: ...
def _push_global_variables(self):
Given the following code snippet before the placeholder: <|code_start|> def test_escapes_work_in_string_literals(): assert query_html_doc('', '"foo&#10;bar"') == expected_result(""" foo bar""") assert query_html_doc('', "'foo&#10;bar'") == expected_result(""" foo <|code_end|> , predict the next lin...
bar""")
Predict the next line for this snippet: <|code_start|> def test_escapes_work_in_string_literals(): assert query_html_doc('', '"foo&#10;bar"') == expected_result(""" foo <|code_end|> with the help of current file imports: from test.common_test_util import expected_result from test.hquery.hquery_test_util impo...
bar""")
Given the code snippet: <|code_start|> variable_stack = [] NAME, VALUE = range(2) class variable_scope: def __enter__(self): self.mark = len(variable_stack) def __exit__(self, *args): del variable_stack[self.mark:] def push_variable(name, value): global variable_stack verbose_print(...
return variable_stack[index][VALUE]
Continue the code snippet: <|code_start|> assert query_html_doc('', 'string(1 = -1)') == expected_result('false') def test_string_value_of_an_element_with_mixed_content_inserts_proper_spaces_between_text_runs(): html_body = '<p>once <a href>twice</a> thrice</p>' assert query_html_doc(html_body, 'string(//p...
<p>foo bar</p>