Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|>
class ExposeError(RuntimeError):
def __init__(self, e):
super(RuntimeError, self).__init__(e.message)
self.e = e
class ExposeTimeout(ExposeError):
pass
class ExposeConnectionError(ExposeError):
pass
class Expose(object):
def __init__(self):
self._config = configparser.SafeConfigParser()
self._logger = get_logger('expose')
if not os.path.isdir(data_dir()):
os.makedirs(data_dir())
if os.path.exists(self.file()):
<|code_end|>
. Use current file 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 including class names, function names, or small code snippets 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. | self.load() |
Given the following code snippet before the placeholder: <|code_start|>
return None, r.json()
def get_user(self, username):
url = self._api_url + '/api/users/%s' % username
r = self._requests.get(url, headers=self.get_headers('token'))
if r.status_code == 401:
return None
r.raise_for_status()
return r.json()
def update(self):
url = self._api_url + '/api/update'
payload = {
'localip': local_ip()
}
r = self._requests.post(url,
data=json.dumps(payload),
headers=self.get_headers('token'))
r.raise_for_status()
return r.json()
def service(self, services, replace=False):
if replace:
<|code_end|>
, predict the next line using imports from the current 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 including class names, function names, and 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. | url = self._api_url + '/api/replace' |
Continue the code snippet: <|code_start|> for service in self.list()]
return client.service(service_list, replace=True)
def add(self, box, announce=True):
project_name = box.project.name()
forwards = box.forwards()
if 'web' not in forwards:
return
port = forwards['web']['host_port']
if not self._config.has_section(project_name):
self._config.add_section(project_name)
self._logger.info('adding %s-%s (port %s)' %
(project_name, box.name(), port))
self._config.set(project_name, box.name(), port)
self.save()
if self.enabled() and announce:
self.announce()
def remove(self, box, announce=False):
project_name = box.project.name()
if not self._config.has_section(project_name):
return
<|code_end|>
. Use current file 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, or 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. | self._config.remove_option(project_name, box.name()) |
Predict the next line after this snippet: <|code_start|>
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'],
'port': service['port']}
for service in self.list()]
return client.service(service_list, replace=True)
def add(self, box, announce=True):
project_name = box.project.name()
forwards = box.forwards()
if 'web' not in forwards:
return
port = forwards['web']['host_port']
if not self._config.has_section(project_name):
self._config.add_section(project_name)
self._logger.info('adding %s-%s (port %s)' %
<|code_end|>
using the current file's 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 any relevant context 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. | (project_name, box.name(), port)) |
Using the snippet: <|code_start|>#!/usr/bin/env python
# we could import the flake8 package, but somehow their public API is just
# useless as their default reporter print directly to stdout with no way
# to catch what it is doing, just run the binary and work with it's output
python = ShCommand(os.path.join(aeriscloud_path, 'venv/bin/python'))
def _run_flake8():
click.echo('Running flake8 on codebase ... ', nl=False)
flake8_bin = os.path.join(aeriscloud_path, 'venv/bin/flake8')
keys = ['file', 'row', 'col', 'message']
reports = [dict(zip(keys, line.strip().split(':')))
for line in python(flake8_bin, '--max-complexity', 11,
module_path(), _ok_code=[0, 1])]
errors = 0
last_file = None
<|code_end|>
, determine the next line of code. You have imports:
import click
import os
import glob
import re
import sys
from sh import Command as ShCommand, ErrorReturnCode
from aeriscloud.ansible import ansible_env, get_env_path, \
ansible_path, organization_path
from aeriscloud.cli.helpers import Command
from aeriscloud.config import module_path, aeriscloud_path
and context (class names, function names, or code) available:
# Path: aeriscloud/ansible.py
# def ansible_env(env):
# def __init__(self, inventory, hostname):
# def ssh_host(self):
# def ssh_key(self):
# def ssh_user(self):
# def variables(self):
# def get_organization_list():
# def get_env_path(organization):
# def get_env_file(organization, environment):
# def list_jobs():
# def get_job_file(job):
# def get_inventory_file(inventory):
# def get_inventory_list():
# def run_job(job, inventory, *args, **kwargs):
# def run_env(organization, environment, inventory, *args, **kwargs):
# def run_playbook(playbook, inventory, *args, **kwargs):
# def run(inventory, shell_cmd, limit, *args, **kwargs):
# def shell(inventory, *args, **kwargs):
# def __init__(self, inventory_path):
# def get_ansible_inventory(self):
# def get_hosts(self, pattern='all'):
# def get_groups(self):
# class ACHost(object):
# class Inventory(object):
#
# Path: aeriscloud/cli/helpers.py
# 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/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):
. Output only the next line. | if reports: |
Predict the next line after this snippet: <|code_start|>
click.echo(' line %s char %s: %s' % (
click.style(report['row'], fg='green'),
click.style(report['col'], fg='green'),
click.style(report['message'], fg='red'),
))
errors += 1
click.echo('')
else:
click.echo('[%s]' % click.style('OK', fg='green'))
return errors
def _run_nosetests():
click.echo('Running unit tests ... ', nl=False)
nose_bin = os.path.join(aeriscloud_path, 'venv/bin/nosetests')
errors = 0
try:
python(nose_bin, '-v', '--with-id', module_path(),
_err_to_out=True, _ok_code=[0])
click.echo('[%s]' % click.style('OK', fg='green'))
except ErrorReturnCode as e:
click.echo('[%s]\n' % click.style('FAIL', fg='red'))
for line in e.stdout.split('\n')[:-2]:
if line.startswith('#'):
print(line)
<|code_end|>
using the current file's imports:
import click
import os
import glob
import re
import sys
from sh import Command as ShCommand, ErrorReturnCode
from aeriscloud.ansible import ansible_env, get_env_path, \
ansible_path, organization_path
from aeriscloud.cli.helpers import Command
from aeriscloud.config import module_path, aeriscloud_path
and any relevant context from other files:
# Path: aeriscloud/ansible.py
# def ansible_env(env):
# def __init__(self, inventory, hostname):
# def ssh_host(self):
# def ssh_key(self):
# def ssh_user(self):
# def variables(self):
# def get_organization_list():
# def get_env_path(organization):
# def get_env_file(organization, environment):
# def list_jobs():
# def get_job_file(job):
# def get_inventory_file(inventory):
# def get_inventory_list():
# def run_job(job, inventory, *args, **kwargs):
# def run_env(organization, environment, inventory, *args, **kwargs):
# def run_playbook(playbook, inventory, *args, **kwargs):
# def run(inventory, shell_cmd, limit, *args, **kwargs):
# def shell(inventory, *args, **kwargs):
# def __init__(self, inventory_path):
# def get_ansible_inventory(self):
# def get_hosts(self, pattern='all'):
# def get_groups(self):
# class ACHost(object):
# class Inventory(object):
#
# Path: aeriscloud/cli/helpers.py
# 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/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):
. Output only the next line. | (id, name, test_file, ellipsis, res) = line.rstrip().split(' ') |
Given the code snippet: <|code_start|>def _run_ansible_lint(organization):
al_bin = os.path.join(aeriscloud_path, 'venv/bin/ansible-lint')
env = ansible_env(os.environ.copy())
if organization:
environment_files = glob.glob(get_env_path(organization) + '/*.yml')
else:
environment_files = glob.glob(organization_path + '/*/*.yml')
if not environment_files:
return 0
args = environment_files + ['-r', os.path.join(ansible_path, 'rules')]
click.echo('Running ansible-lint ... ', nl=False)
errors = 0
try:
python(al_bin, *args,
_env=env, _err_to_out=True, _ok_code=[0])
click.echo('[%s]' % click.style('OK', fg='green'))
except ErrorReturnCode as e:
parser = re.compile(
r'^\[(?P<error_code>[^\]]+)\] (?P<error_message>[^\n]+)\n'
r'%s(?P<file_name>[^:]+):(?P<line_number>[0-9]+)\n'
r'Task/Handler: (?P<task_name>[^\n]+)\n\n' % (ansible_path + '/'),
re.MULTILINE
)
<|code_end|>
, generate the next line using the imports in this file:
import click
import os
import glob
import re
import sys
from sh import Command as ShCommand, ErrorReturnCode
from aeriscloud.ansible import ansible_env, get_env_path, \
ansible_path, organization_path
from aeriscloud.cli.helpers import Command
from aeriscloud.config import module_path, aeriscloud_path
and context (functions, classes, or occasionally code) from other files:
# Path: aeriscloud/ansible.py
# def ansible_env(env):
# def __init__(self, inventory, hostname):
# def ssh_host(self):
# def ssh_key(self):
# def ssh_user(self):
# def variables(self):
# def get_organization_list():
# def get_env_path(organization):
# def get_env_file(organization, environment):
# def list_jobs():
# def get_job_file(job):
# def get_inventory_file(inventory):
# def get_inventory_list():
# def run_job(job, inventory, *args, **kwargs):
# def run_env(organization, environment, inventory, *args, **kwargs):
# def run_playbook(playbook, inventory, *args, **kwargs):
# def run(inventory, shell_cmd, limit, *args, **kwargs):
# def shell(inventory, *args, **kwargs):
# def __init__(self, inventory_path):
# def get_ansible_inventory(self):
# def get_hosts(self, pattern='all'):
# def get_groups(self):
# class ACHost(object):
# class Inventory(object):
#
# Path: aeriscloud/cli/helpers.py
# 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/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):
. Output only the next line. | click.echo('[%s]\n' % click.style('FAIL', fg='red')) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# we could import the flake8 package, but somehow their public API is just
# useless as their default reporter print directly to stdout with no way
# to catch what it is doing, just run the binary and work with it's output
python = ShCommand(os.path.join(aeriscloud_path, 'venv/bin/python'))
def _run_flake8():
click.echo('Running flake8 on codebase ... ', nl=False)
flake8_bin = os.path.join(aeriscloud_path, 'venv/bin/flake8')
keys = ['file', 'row', 'col', 'message']
reports = [dict(zip(keys, line.strip().split(':')))
for line in python(flake8_bin, '--max-complexity', 11,
module_path(), _ok_code=[0, 1])]
errors = 0
last_file = None
if reports:
click.echo('[%s]\n' % click.style('FAIL', fg='red'))
<|code_end|>
with the help of current file imports:
import click
import os
import glob
import re
import sys
from sh import Command as ShCommand, ErrorReturnCode
from aeriscloud.ansible import ansible_env, get_env_path, \
ansible_path, organization_path
from aeriscloud.cli.helpers import Command
from aeriscloud.config import module_path, aeriscloud_path
and context from other files:
# Path: aeriscloud/ansible.py
# def ansible_env(env):
# def __init__(self, inventory, hostname):
# def ssh_host(self):
# def ssh_key(self):
# def ssh_user(self):
# def variables(self):
# def get_organization_list():
# def get_env_path(organization):
# def get_env_file(organization, environment):
# def list_jobs():
# def get_job_file(job):
# def get_inventory_file(inventory):
# def get_inventory_list():
# def run_job(job, inventory, *args, **kwargs):
# def run_env(organization, environment, inventory, *args, **kwargs):
# def run_playbook(playbook, inventory, *args, **kwargs):
# def run(inventory, shell_cmd, limit, *args, **kwargs):
# def shell(inventory, *args, **kwargs):
# def __init__(self, inventory_path):
# def get_ansible_inventory(self):
# def get_hosts(self, pattern='all'):
# def get_groups(self):
# class ACHost(object):
# class Inventory(object):
#
# Path: aeriscloud/cli/helpers.py
# 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/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):
, which may contain function names, class names, or code. Output only the next line. | for report in reports: |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# we could import the flake8 package, but somehow their public API is just
# useless as their default reporter print directly to stdout with no way
# to catch what it is doing, just run the binary and work with it's output
python = ShCommand(os.path.join(aeriscloud_path, 'venv/bin/python'))
def _run_flake8():
click.echo('Running flake8 on codebase ... ', nl=False)
flake8_bin = os.path.join(aeriscloud_path, 'venv/bin/flake8')
keys = ['file', 'row', 'col', 'message']
<|code_end|>
, generate the next line using the imports in this file:
import click
import os
import glob
import re
import sys
from sh import Command as ShCommand, ErrorReturnCode
from aeriscloud.ansible import ansible_env, get_env_path, \
ansible_path, organization_path
from aeriscloud.cli.helpers import Command
from aeriscloud.config import module_path, aeriscloud_path
and context (functions, classes, or occasionally code) from other files:
# Path: aeriscloud/ansible.py
# def ansible_env(env):
# def __init__(self, inventory, hostname):
# def ssh_host(self):
# def ssh_key(self):
# def ssh_user(self):
# def variables(self):
# def get_organization_list():
# def get_env_path(organization):
# def get_env_file(organization, environment):
# def list_jobs():
# def get_job_file(job):
# def get_inventory_file(inventory):
# def get_inventory_list():
# def run_job(job, inventory, *args, **kwargs):
# def run_env(organization, environment, inventory, *args, **kwargs):
# def run_playbook(playbook, inventory, *args, **kwargs):
# def run(inventory, shell_cmd, limit, *args, **kwargs):
# def shell(inventory, *args, **kwargs):
# def __init__(self, inventory_path):
# def get_ansible_inventory(self):
# def get_hosts(self, pattern='all'):
# def get_groups(self):
# class ACHost(object):
# class Inventory(object):
#
# Path: aeriscloud/cli/helpers.py
# 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/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):
. Output only the next line. | reports = [dict(zip(keys, line.strip().split(':'))) |
Predict the next line after this snippet: <|code_start|>
click.echo('')
else:
click.echo('[%s]' % click.style('OK', fg='green'))
return errors
def _run_nosetests():
click.echo('Running unit tests ... ', nl=False)
nose_bin = os.path.join(aeriscloud_path, 'venv/bin/nosetests')
errors = 0
try:
python(nose_bin, '-v', '--with-id', module_path(),
_err_to_out=True, _ok_code=[0])
click.echo('[%s]' % click.style('OK', fg='green'))
except ErrorReturnCode as e:
click.echo('[%s]\n' % click.style('FAIL', fg='red'))
for line in e.stdout.split('\n')[:-2]:
if line.startswith('#'):
print(line)
(id, name, test_file, ellipsis, res) = line.rstrip().split(' ')
if res == 'ok':
res = click.style(res, fg='green', bold=True)
elif res == 'FAIL':
res = click.style(res, fg='red', bold=True)
<|code_end|>
using the current file's imports:
import click
import os
import glob
import re
import sys
from sh import Command as ShCommand, ErrorReturnCode
from aeriscloud.ansible import ansible_env, get_env_path, \
ansible_path, organization_path
from aeriscloud.cli.helpers import Command
from aeriscloud.config import module_path, aeriscloud_path
and any relevant context from other files:
# Path: aeriscloud/ansible.py
# def ansible_env(env):
# def __init__(self, inventory, hostname):
# def ssh_host(self):
# def ssh_key(self):
# def ssh_user(self):
# def variables(self):
# def get_organization_list():
# def get_env_path(organization):
# def get_env_file(organization, environment):
# def list_jobs():
# def get_job_file(job):
# def get_inventory_file(inventory):
# def get_inventory_list():
# def run_job(job, inventory, *args, **kwargs):
# def run_env(organization, environment, inventory, *args, **kwargs):
# def run_playbook(playbook, inventory, *args, **kwargs):
# def run(inventory, shell_cmd, limit, *args, **kwargs):
# def shell(inventory, *args, **kwargs):
# def __init__(self, inventory_path):
# def get_ansible_inventory(self):
# def get_hosts(self, pattern='all'):
# def get_groups(self):
# class ACHost(object):
# class Inventory(object):
#
# Path: aeriscloud/cli/helpers.py
# 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/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):
. Output only the next line. | line = ' '.join([ |
Based on the snippet: <|code_start|> last_file = None
if reports:
click.echo('[%s]\n' % click.style('FAIL', fg='red'))
for report in reports:
report_file = report['file'][len(module_path()) + 1:]
if report_file != last_file:
click.secho(' Errors in file: %s' % report_file,
fg='blue', bold=True)
last_file = report_file
click.echo(' line %s char %s: %s' % (
click.style(report['row'], fg='green'),
click.style(report['col'], fg='green'),
click.style(report['message'], fg='red'),
))
errors += 1
click.echo('')
else:
click.echo('[%s]' % click.style('OK', fg='green'))
return errors
def _run_nosetests():
click.echo('Running unit tests ... ', nl=False)
nose_bin = os.path.join(aeriscloud_path, 'venv/bin/nosetests')
errors = 0
<|code_end|>
, predict the immediate next line with the help of imports:
import click
import os
import glob
import re
import sys
from sh import Command as ShCommand, ErrorReturnCode
from aeriscloud.ansible import ansible_env, get_env_path, \
ansible_path, organization_path
from aeriscloud.cli.helpers import Command
from aeriscloud.config import module_path, aeriscloud_path
and context (classes, functions, sometimes code) from other files:
# Path: aeriscloud/ansible.py
# def ansible_env(env):
# def __init__(self, inventory, hostname):
# def ssh_host(self):
# def ssh_key(self):
# def ssh_user(self):
# def variables(self):
# def get_organization_list():
# def get_env_path(organization):
# def get_env_file(organization, environment):
# def list_jobs():
# def get_job_file(job):
# def get_inventory_file(inventory):
# def get_inventory_list():
# def run_job(job, inventory, *args, **kwargs):
# def run_env(organization, environment, inventory, *args, **kwargs):
# def run_playbook(playbook, inventory, *args, **kwargs):
# def run(inventory, shell_cmd, limit, *args, **kwargs):
# def shell(inventory, *args, **kwargs):
# def __init__(self, inventory_path):
# def get_ansible_inventory(self):
# def get_hosts(self, pattern='all'):
# def get_groups(self):
# class ACHost(object):
# class Inventory(object):
#
# Path: aeriscloud/cli/helpers.py
# 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/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):
. Output only the next line. | try: |
Based on the snippet: <|code_start|>
def services(organization, env='production'):
service_list = {}
if not organization:
return service_list
service_file = os.path.join(organization_path,
organization,
'env_%s.yml' % env)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from .ansible import organization_path
and context (classes, functions, sometimes code) from other files:
# Path: aeriscloud/ansible.py
# def ansible_env(env):
# def __init__(self, inventory, hostname):
# def ssh_host(self):
# def ssh_key(self):
# def ssh_user(self):
# def variables(self):
# def get_organization_list():
# def get_env_path(organization):
# def get_env_file(organization, environment):
# def list_jobs():
# def get_job_file(job):
# def get_inventory_file(inventory):
# def get_inventory_list():
# def run_job(job, inventory, *args, **kwargs):
# def run_env(organization, environment, inventory, *args, **kwargs):
# def run_playbook(playbook, inventory, *args, **kwargs):
# def run(inventory, shell_cmd, limit, *args, **kwargs):
# def shell(inventory, *args, **kwargs):
# def __init__(self, inventory_path):
# def get_ansible_inventory(self):
# def get_hosts(self, pattern='all'):
# def get_groups(self):
# class ACHost(object):
# class Inventory(object):
. Output only the next line. | with open(service_file) as f: |
Based on the snippet: <|code_start|>
def _search_variables(search_path, variable):
files = set()
cmd = "grep -rI '%s = ' %s" % (variable, quote(search_path))
try:
grep = subprocess32.check_output(cmd, shell=True)
except subprocess32.CalledProcessError:
return []
for line in grep.split('\n'):
if not line.strip():
continue
filename = line[:line.find(':')].strip()
if filename.startswith('.'):
continue
files.add(filename)
return files
def _replace_variable(filename, variable, value):
tmp_filename = os.path.join(
os.path.dirname(filename),
'.' + os.path.basename(filename) + '.swp'
)
expr = re.compile('^(.*' + variable + '\s*=\s*[\'"]?)([^\s\'"]*)(.*)$')
with open(filename) as input:
with open(tmp_filename, 'w') as output:
for line in input:
<|code_end|>
, predict the immediate next line with the help of imports:
import click
import os
import re
import subprocess32
import sys
from aeriscloud.cli.helpers import Command, standard_options, \
error, fatal, info, success, bold
from aeriscloud.utils import local_ip, quote
and context (classes, functions, sometimes code) from other files:
# Path: aeriscloud/cli/helpers.py
# 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 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)
#
# def error(text, **kwargs):
# click.secho(text, fg='red', err=True, **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# def info(text, **kwargs):
# click.secho(text, fg='cyan', **kwargs)
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def bold(text, **kwargs):
# return click.style(text, bold=True, **kwargs)
#
# 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
#
# 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. | if variable in line.decode('utf-8-sig'): |
Predict the next line after this snippet: <|code_start|>
return None, None
def _search_variables(search_path, variable):
files = set()
cmd = "grep -rI '%s = ' %s" % (variable, quote(search_path))
try:
grep = subprocess32.check_output(cmd, shell=True)
except subprocess32.CalledProcessError:
return []
for line in grep.split('\n'):
if not line.strip():
continue
filename = line[:line.find(':')].strip()
if filename.startswith('.'):
continue
files.add(filename)
return files
def _replace_variable(filename, variable, value):
tmp_filename = os.path.join(
os.path.dirname(filename),
'.' + os.path.basename(filename) + '.swp'
)
expr = re.compile('^(.*' + variable + '\s*=\s*[\'"]?)([^\s\'"]*)(.*)$')
<|code_end|>
using the current file's imports:
import click
import os
import re
import subprocess32
import sys
from aeriscloud.cli.helpers import Command, standard_options, \
error, fatal, info, success, bold
from aeriscloud.utils import local_ip, quote
and any relevant context from other files:
# Path: aeriscloud/cli/helpers.py
# 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 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)
#
# def error(text, **kwargs):
# click.secho(text, fg='red', err=True, **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# def info(text, **kwargs):
# click.secho(text, fg='cyan', **kwargs)
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def bold(text, **kwargs):
# return click.style(text, bold=True, **kwargs)
#
# 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
#
# 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. | with open(filename) as input: |
Given the code snippet: <|code_start|>def _get_url(server, box):
if not box.project.initialized():
error("This project doesn't contain a %s file." % (
bold(".aeriscloud.yml")))
return None
if server == 'local':
return _get_local_url(box)
elif server == 'aeris.cd':
return _get_aeris_url(box)
elif server == 'production':
return box.project.get_production_url()
else:
return None
def _get_search_path():
files = os.listdir(os.getcwd())
# Unity Project
if 'Assets' in files and 'ProjectSettings' in files:
return os.path.join(os.getcwd(), 'Assets'), 'Unity'
return None, None
def _search_variables(search_path, variable):
files = set()
cmd = "grep -rI '%s = ' %s" % (variable, quote(search_path))
<|code_end|>
, generate the next line using the imports in this file:
import click
import os
import re
import subprocess32
import sys
from aeriscloud.cli.helpers import Command, standard_options, \
error, fatal, info, success, bold
from aeriscloud.utils import local_ip, quote
and context (functions, classes, or occasionally code) from other files:
# Path: aeriscloud/cli/helpers.py
# 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 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)
#
# def error(text, **kwargs):
# click.secho(text, fg='red', err=True, **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# def info(text, **kwargs):
# click.secho(text, fg='cyan', **kwargs)
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def bold(text, **kwargs):
# return click.style(text, bold=True, **kwargs)
#
# 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
#
# 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. | try: |
Predict the next line after this snippet: <|code_start|>from __future__ import print_function
def _get_local_url(box):
forwards = box.forwards()
if 'web' not in forwards:
raise RuntimeError('Box has no exposed web app')
port = forwards['web']['host_port']
return "http://%s:%s" % (local_ip(), port)
def _get_aeris_url(box):
return box.browse()
<|code_end|>
using the current file's imports:
import click
import os
import re
import subprocess32
import sys
from aeriscloud.cli.helpers import Command, standard_options, \
error, fatal, info, success, bold
from aeriscloud.utils import local_ip, quote
and any relevant context from other files:
# Path: aeriscloud/cli/helpers.py
# 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 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)
#
# def error(text, **kwargs):
# click.secho(text, fg='red', err=True, **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# def info(text, **kwargs):
# click.secho(text, fg='cyan', **kwargs)
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def bold(text, **kwargs):
# return click.style(text, bold=True, **kwargs)
#
# 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
#
# 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 _get_url(server, box): |
Given the code snippet: <|code_start|> if 'Assets' in files and 'ProjectSettings' in files:
return os.path.join(os.getcwd(), 'Assets'), 'Unity'
return None, None
def _search_variables(search_path, variable):
files = set()
cmd = "grep -rI '%s = ' %s" % (variable, quote(search_path))
try:
grep = subprocess32.check_output(cmd, shell=True)
except subprocess32.CalledProcessError:
return []
for line in grep.split('\n'):
if not line.strip():
continue
filename = line[:line.find(':')].strip()
if filename.startswith('.'):
continue
files.add(filename)
return files
def _replace_variable(filename, variable, value):
tmp_filename = os.path.join(
os.path.dirname(filename),
'.' + os.path.basename(filename) + '.swp'
<|code_end|>
, generate the next line using the imports in this file:
import click
import os
import re
import subprocess32
import sys
from aeriscloud.cli.helpers import Command, standard_options, \
error, fatal, info, success, bold
from aeriscloud.utils import local_ip, quote
and context (functions, classes, or occasionally code) from other files:
# Path: aeriscloud/cli/helpers.py
# 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 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)
#
# def error(text, **kwargs):
# click.secho(text, fg='red', err=True, **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# def info(text, **kwargs):
# click.secho(text, fg='cyan', **kwargs)
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def bold(text, **kwargs):
# return click.style(text, bold=True, **kwargs)
#
# 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
#
# 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. | ) |
Predict the next line after this snippet: <|code_start|>def _get_local_url(box):
forwards = box.forwards()
if 'web' not in forwards:
raise RuntimeError('Box has no exposed web app')
port = forwards['web']['host_port']
return "http://%s:%s" % (local_ip(), port)
def _get_aeris_url(box):
return box.browse()
def _get_url(server, box):
if not box.project.initialized():
error("This project doesn't contain a %s file." % (
bold(".aeriscloud.yml")))
return None
if server == 'local':
return _get_local_url(box)
elif server == 'aeris.cd':
return _get_aeris_url(box)
elif server == 'production':
return box.project.get_production_url()
else:
return None
<|code_end|>
using the current file's imports:
import click
import os
import re
import subprocess32
import sys
from aeriscloud.cli.helpers import Command, standard_options, \
error, fatal, info, success, bold
from aeriscloud.utils import local_ip, quote
and any relevant context from other files:
# Path: aeriscloud/cli/helpers.py
# 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 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)
#
# def error(text, **kwargs):
# click.secho(text, fg='red', err=True, **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# def info(text, **kwargs):
# click.secho(text, fg='cyan', **kwargs)
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def bold(text, **kwargs):
# return click.style(text, bold=True, **kwargs)
#
# 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
#
# 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 _get_search_path(): |
Next line prediction: <|code_start|> fatal("Unsupported platform.")
unity_path = os.path.join(unity_path, "Unity.app/Contents/MacOS/Unity")
command = "{unity_path} -quit -batchmode " \
"-executeMethod {method} " \
"-logFile ./build.log " \
"-projectPath {current_dir}" \
.format(unity_path=quote(unity_path),
method=methods[platform],
current_dir=quote(os.getcwd()))
info("""The following command will be executed:
{0}.""".format(bold(command)))
returncode = subprocess32.call(command, shell=True)
if returncode != 0:
error("An error occurred, please check the content "
"of the {0} log file.".format(bold('build.log')))
sys.exit(returncode)
if platform == 'ios':
os.chdir(os.path.join(os.getcwd(), 'Build', 'iPhone'))
command = "xcodebuild -scheme Unity-iPhone archive " \
"-archivePath Unity-iPhone.xcarchive"
info("""The following command will be executed:
{0}.""".format(bold(command)))
subprocess32.check_call(command, shell=True)
command = "xcodebuild -exportArchive " \
"-exportFormat ipa " \
"-archivePath \"Unity-iPhone.xcarchive\" " \
"-exportPath \"Unity-iPhone.ipa\" " \
<|code_end|>
. Use current file imports:
(import click
import os
import re
import subprocess32
import sys
from aeriscloud.cli.helpers import Command, standard_options, \
error, fatal, info, success, bold
from aeriscloud.utils import local_ip, quote)
and context including class names, function names, or small code snippets from other files:
# Path: aeriscloud/cli/helpers.py
# 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 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)
#
# def error(text, **kwargs):
# click.secho(text, fg='red', err=True, **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# def info(text, **kwargs):
# click.secho(text, fg='cyan', **kwargs)
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def bold(text, **kwargs):
# return click.style(text, bold=True, **kwargs)
#
# 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
#
# 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. | "-exportProvisioningProfile \"wildcard_Development\"" |
Here is a snippet: <|code_start|>from __future__ import print_function
def _get_local_url(box):
forwards = box.forwards()
if 'web' not in forwards:
raise RuntimeError('Box has no exposed web app')
port = forwards['web']['host_port']
return "http://%s:%s" % (local_ip(), port)
def _get_aeris_url(box):
return box.browse()
def _get_url(server, box):
<|code_end|>
. Write the next line using the current file imports:
import click
import os
import re
import subprocess32
import sys
from aeriscloud.cli.helpers import Command, standard_options, \
error, fatal, info, success, bold
from aeriscloud.utils import local_ip, quote
and context from other files:
# Path: aeriscloud/cli/helpers.py
# 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 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)
#
# def error(text, **kwargs):
# click.secho(text, fg='red', err=True, **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# def info(text, **kwargs):
# click.secho(text, fg='cyan', **kwargs)
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def bold(text, **kwargs):
# return click.style(text, bold=True, **kwargs)
#
# 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
#
# 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("'", "'\"'\"'") + "'"
, which may include functions, classes, or code. Output only the next line. | if not box.project.initialized(): |
Here is a snippet: <|code_start|>
def _build_unity(platform, unity_path):
methods = {
'ios': 'BuildEditorScript.PerformiOSBuild',
'android': 'BuildEditorScript.PerformAndroidBuild',
'osx': 'BuildEditorScript.PerformMacOSXBuild'
}
if platform not in methods:
fatal("Unsupported platform.")
unity_path = os.path.join(unity_path, "Unity.app/Contents/MacOS/Unity")
command = "{unity_path} -quit -batchmode " \
"-executeMethod {method} " \
"-logFile ./build.log " \
"-projectPath {current_dir}" \
.format(unity_path=quote(unity_path),
method=methods[platform],
current_dir=quote(os.getcwd()))
info("""The following command will be executed:
{0}.""".format(bold(command)))
returncode = subprocess32.call(command, shell=True)
if returncode != 0:
error("An error occurred, please check the content "
"of the {0} log file.".format(bold('build.log')))
sys.exit(returncode)
if platform == 'ios':
os.chdir(os.path.join(os.getcwd(), 'Build', 'iPhone'))
command = "xcodebuild -scheme Unity-iPhone archive " \
<|code_end|>
. Write the next line using the current file imports:
import click
import os
import re
import subprocess32
import sys
from aeriscloud.cli.helpers import Command, standard_options, \
error, fatal, info, success, bold
from aeriscloud.utils import local_ip, quote
and context from other files:
# Path: aeriscloud/cli/helpers.py
# 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 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)
#
# def error(text, **kwargs):
# click.secho(text, fg='red', err=True, **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# def info(text, **kwargs):
# click.secho(text, fg='cyan', **kwargs)
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def bold(text, **kwargs):
# return click.style(text, bold=True, **kwargs)
#
# 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
#
# 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("'", "'\"'\"'") + "'"
, which may include functions, classes, or code. Output only the next line. | "-archivePath Unity-iPhone.xcarchive" |
Here is a snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.argument('command', nargs=-1)
@standard_options()
<|code_end|>
. Write the next line using the current file 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 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("'", "'\"'\"'") + "'"
, which may include functions, classes, or code. Output only the next line. | def cli(box, command): |
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): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.argument('command', nargs=-1)
@standard_options()
<|code_end|>
. Use current file 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, or 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): |
Using the snippet: <|code_start|>#!/usr/bin/env python
def _display_option(section, option, value):
if sys.stdout.isatty():
click.echo('%s.%s = %s' % (
click.style(section, fg='blue'),
<|code_end|>
, determine the next line of code. You have imports:
import click
import sys
from aeriscloud.cli.helpers import Command
from aeriscloud.config import config
and context (class names, function names, or code) available:
# Path: aeriscloud/cli/helpers.py
# 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/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):
. Output only the next line. | click.style(option, fg='blue'), |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
def _display_option(section, option, value):
if sys.stdout.isatty():
click.echo('%s.%s = %s' % (
click.style(section, fg='blue'),
click.style(option, fg='blue'),
click.style(value, fg='green')
))
else:
# remove spaces when piped so that users can send that
# to cut/awk/etc...
click.echo('%s.%s=%s' % (section, option, value))
<|code_end|>
. Use current file imports:
import click
import sys
from aeriscloud.cli.helpers import Command
from aeriscloud.config import config
and context (classes, functions, or code) from other files:
# Path: aeriscloud/cli/helpers.py
# 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/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):
. Output only the next line. | def _unset_option(option): |
Given snippet: <|code_start|>#!/usr/bin/env python
def _parse_provision(ctx, param, value):
if not value:
return []
provisioners = value.split(',')
for provisioner in provisioners:
if provisioner not in ['ansible', 'shell']:
raise click.BadParameter('provisioner must be on of ansible or '
'shell')
return provisioners
@click.command(cls=Command)
@click.option('--provision-with', default=None, callback=_parse_provision)
@standard_options(start_prompt=False)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import standard_options, Command, start_box, fatal
and context:
# 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 start_box(box, provision_with=None):
# # if the vm is suspended, just resume it
# res = 0
#
# provision = provision_with or []
#
# if 'shell' not in provision and box.status() != 'not created':
# provision.append('shell')
#
# extra_args = []
# if provision:
# extra_args = ['--provision-with', ','.join(provision)]
#
# manual_provision = False
# if box.status() == 'saved':
# manual_provision = True
# click.echo('Resuming box %s' % box.name())
#
# if not box.is_running():
# try:
# extra_args_copy = extra_args[:]
# if '--provision-with' in extra_args_copy:
# extra_args_copy.insert(0, '--provision')
# res = box.up(*extra_args_copy)
# except (ExposeTimeout, ExposeConnectionError):
# warning('warning: expose is not available at the moment')
# else:
# hist = box.history()
# if not hist or (
# 'failed_at' in hist[-1] and
# hist[-1]['failed_at']
# ) or hist[-1]['stats'][box.name()]['unreachable'] > 0:
# # run provisioning if last one failed
# res = box.vagrant('provision')
#
# box.expose() # just in case
#
# if manual_provision:
# box.vagrant('provision', *extra_args)
#
# if res == 0 or res is True:
# timestamp(render_cli('provision-success', box=box))
# else:
# timestamp(render_cli('provision-failure'))
#
# # refresh cache
# list_vms(clear_cache_only=True)
#
# return res
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
which might include code, classes, or functions. Output only the next line. | def cli(box, provision_with): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
def _parse_provision(ctx, param, value):
if not value:
return []
provisioners = value.split(',')
for provisioner in provisioners:
if provisioner not in ['ansible', 'shell']:
raise click.BadParameter('provisioner must be on of ansible or '
'shell')
return provisioners
@click.command(cls=Command)
<|code_end|>
using the current file's imports:
import click
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import standard_options, Command, start_box, fatal
and any relevant 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 start_box(box, provision_with=None):
# # if the vm is suspended, just resume it
# res = 0
#
# provision = provision_with or []
#
# if 'shell' not in provision and box.status() != 'not created':
# provision.append('shell')
#
# extra_args = []
# if provision:
# extra_args = ['--provision-with', ','.join(provision)]
#
# manual_provision = False
# if box.status() == 'saved':
# manual_provision = True
# click.echo('Resuming box %s' % box.name())
#
# if not box.is_running():
# try:
# extra_args_copy = extra_args[:]
# if '--provision-with' in extra_args_copy:
# extra_args_copy.insert(0, '--provision')
# res = box.up(*extra_args_copy)
# except (ExposeTimeout, ExposeConnectionError):
# warning('warning: expose is not available at the moment')
# else:
# hist = box.history()
# if not hist or (
# 'failed_at' in hist[-1] and
# hist[-1]['failed_at']
# ) or hist[-1]['stats'][box.name()]['unreachable'] > 0:
# # run provisioning if last one failed
# res = box.vagrant('provision')
#
# box.expose() # just in case
#
# if manual_provision:
# box.vagrant('provision', *extra_args)
#
# if res == 0 or res is True:
# timestamp(render_cli('provision-success', box=box))
# else:
# timestamp(render_cli('provision-failure'))
#
# # refresh cache
# list_vms(clear_cache_only=True)
#
# return res
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
. Output only the next line. | @click.option('--provision-with', default=None, callback=_parse_provision) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
def _parse_provision(ctx, param, value):
if not value:
return []
provisioners = value.split(',')
for provisioner in provisioners:
if provisioner not in ['ansible', 'shell']:
raise click.BadParameter('provisioner must be on of ansible or '
'shell')
return provisioners
@click.command(cls=Command)
<|code_end|>
. Use current file imports:
import click
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import standard_options, Command, start_box, fatal
and context (classes, functions, or code) 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 start_box(box, provision_with=None):
# # if the vm is suspended, just resume it
# res = 0
#
# provision = provision_with or []
#
# if 'shell' not in provision and box.status() != 'not created':
# provision.append('shell')
#
# extra_args = []
# if provision:
# extra_args = ['--provision-with', ','.join(provision)]
#
# manual_provision = False
# if box.status() == 'saved':
# manual_provision = True
# click.echo('Resuming box %s' % box.name())
#
# if not box.is_running():
# try:
# extra_args_copy = extra_args[:]
# if '--provision-with' in extra_args_copy:
# extra_args_copy.insert(0, '--provision')
# res = box.up(*extra_args_copy)
# except (ExposeTimeout, ExposeConnectionError):
# warning('warning: expose is not available at the moment')
# else:
# hist = box.history()
# if not hist or (
# 'failed_at' in hist[-1] and
# hist[-1]['failed_at']
# ) or hist[-1]['stats'][box.name()]['unreachable'] > 0:
# # run provisioning if last one failed
# res = box.vagrant('provision')
#
# box.expose() # just in case
#
# if manual_provision:
# box.vagrant('provision', *extra_args)
#
# if res == 0 or res is True:
# timestamp(render_cli('provision-success', box=box))
# else:
# timestamp(render_cli('provision-failure'))
#
# # refresh cache
# list_vms(clear_cache_only=True)
#
# return res
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
. Output only the next line. | @click.option('--provision-with', default=None, callback=_parse_provision) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
def _parse_provision(ctx, param, value):
if not value:
return []
provisioners = value.split(',')
for provisioner in provisioners:
if provisioner not in ['ansible', 'shell']:
raise click.BadParameter('provisioner must be on of ansible or '
<|code_end|>
, predict the immediate next line with the help of imports:
import click
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import standard_options, Command, start_box, fatal
and context (classes, functions, sometimes code) 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 start_box(box, provision_with=None):
# # if the vm is suspended, just resume it
# res = 0
#
# provision = provision_with or []
#
# if 'shell' not in provision and box.status() != 'not created':
# provision.append('shell')
#
# extra_args = []
# if provision:
# extra_args = ['--provision-with', ','.join(provision)]
#
# manual_provision = False
# if box.status() == 'saved':
# manual_provision = True
# click.echo('Resuming box %s' % box.name())
#
# if not box.is_running():
# try:
# extra_args_copy = extra_args[:]
# if '--provision-with' in extra_args_copy:
# extra_args_copy.insert(0, '--provision')
# res = box.up(*extra_args_copy)
# except (ExposeTimeout, ExposeConnectionError):
# warning('warning: expose is not available at the moment')
# else:
# hist = box.history()
# if not hist or (
# 'failed_at' in hist[-1] and
# hist[-1]['failed_at']
# ) or hist[-1]['stats'][box.name()]['unreachable'] > 0:
# # run provisioning if last one failed
# res = box.vagrant('provision')
#
# box.expose() # just in case
#
# if manual_provision:
# box.vagrant('provision', *extra_args)
#
# if res == 0 or res is True:
# timestamp(render_cli('provision-success', box=box))
# else:
# timestamp(render_cli('provision-failure'))
#
# # refresh cache
# list_vms(clear_cache_only=True)
#
# return res
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
. Output only the next line. | 'shell') |
Based on the snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.option('--force', is_flag=True,
help='Connect anyway if project server is not set')
<|code_end|>
, predict the immediate next line with the help of imports:
import click
import sys
from aeriscloud.cli.helpers import standard_options, Command, render_cli
and context (classes, functions, sometimes code) 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)
. Output only the next line. | @click.argument('command', nargs=-1) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.option('--force', is_flag=True,
help='Connect anyway if project server is not set')
<|code_end|>
. Use current file imports:
import click
import sys
from aeriscloud.cli.helpers import standard_options, Command, render_cli
and context (classes, functions, or code) 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)
. Output only the next line. | @click.argument('command', nargs=-1) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.option('--force', is_flag=True,
help='Connect anyway if project server is not set')
<|code_end|>
, predict the next line using imports from the current file:
import click
import sys
from aeriscloud.cli.helpers import standard_options, Command, render_cli
and context including class names, function names, and sometimes code 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)
. Output only the next line. | @click.argument('command', nargs=-1) |
Here is a snippet: <|code_start|>
class Github:
def __init__(self, _ask_credentials=None, _ask_2fa=None):
self.last_error = None
self._ask_credentials = _ask_credentials
self._ask_2fa = _ask_2fa
self.gh = GitHub(token=self._get_authorization_token())
self.user = self.gh.user()
def _get_authorization_token(self):
if not config.has('github', 'token') or \
not config.get('github', 'token'):
if not self._ask_credentials:
raise RuntimeError('Github Token is not set in the '
'configuration and no function was set to '
<|code_end|>
. Write the next line using the current file imports:
from github3 import authorize, GitHubError, GitHub
from platform import node
from .config import config
and context 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):
, which may include functions, classes, or code. Output only the next line. | 'ask for credentials') |
Given the following code snippet before the placeholder: <|code_start|>
ansible_path = os.path.join(aeriscloud_path, 'ansible')
plugin_path = os.path.join(ansible_path, 'plugins')
job_path = os.path.join(ansible_path, 'jobs')
inventory_path = os.path.join(data_dir(), 'inventory')
organization_path = os.path.join(data_dir(), 'organizations')
logger = get_logger('ansible')
def ansible_env(env):
env['PATH'] = os.pathsep.join([
os.path.join(aeriscloud_path, 'venv/bin'),
env['PATH']
])
# disable buffering for ansible
env['PYTHONUNBUFFERED'] = '1'
env['ANSIBLE_BASE_PATH'] = ansible_path
env['ANSIBLE_ACTION_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'actions')] +
constants.DEFAULT_ACTION_PLUGIN_PATH
)
env['ANSIBLE_CALLBACK_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'callbacks')] +
<|code_end|>
, predict the next line using imports from the current file:
import os
from subprocess32 import Popen, PIPE, call
from ansible import constants
from .config import aeriscloud_path, verbosity, data_dir
from .log import get_logger
from .utils import quote, timestamp
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
and context including class names, function names, and 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 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("'", "'\"'\"'") + "'"
#
# 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. | constants.DEFAULT_CALLBACK_PLUGIN_PATH |
Predict the next line for this snippet: <|code_start|>from __future__ import print_function, absolute_import
ansible_path = os.path.join(aeriscloud_path, 'ansible')
plugin_path = os.path.join(ansible_path, 'plugins')
job_path = os.path.join(ansible_path, 'jobs')
inventory_path = os.path.join(data_dir(), 'inventory')
organization_path = os.path.join(data_dir(), 'organizations')
logger = get_logger('ansible')
def ansible_env(env):
env['PATH'] = os.pathsep.join([
os.path.join(aeriscloud_path, 'venv/bin'),
<|code_end|>
with the help of current file imports:
import os
from subprocess32 import Popen, PIPE, call
from ansible import constants
from .config import aeriscloud_path, verbosity, data_dir
from .log import get_logger
from .utils import quote, timestamp
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
and context 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 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("'", "'\"'\"'") + "'"
#
# 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 contain function names, class names, or code. Output only the next line. | env['PATH'] |
Given the following code snippet before the placeholder: <|code_start|>ansible_path = os.path.join(aeriscloud_path, 'ansible')
plugin_path = os.path.join(ansible_path, 'plugins')
job_path = os.path.join(ansible_path, 'jobs')
inventory_path = os.path.join(data_dir(), 'inventory')
organization_path = os.path.join(data_dir(), 'organizations')
logger = get_logger('ansible')
def ansible_env(env):
env['PATH'] = os.pathsep.join([
os.path.join(aeriscloud_path, 'venv/bin'),
env['PATH']
])
# disable buffering for ansible
env['PYTHONUNBUFFERED'] = '1'
env['ANSIBLE_BASE_PATH'] = ansible_path
env['ANSIBLE_ACTION_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'actions')] +
constants.DEFAULT_ACTION_PLUGIN_PATH
)
env['ANSIBLE_CALLBACK_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'callbacks')] +
constants.DEFAULT_CALLBACK_PLUGIN_PATH
)
env['ANSIBLE_CONNECTION_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'connections')] +
constants.DEFAULT_CONNECTION_PLUGIN_PATH
<|code_end|>
, predict the next line using imports from the current file:
import os
from subprocess32 import Popen, PIPE, call
from ansible import constants
from .config import aeriscloud_path, verbosity, data_dir
from .log import get_logger
from .utils import quote, timestamp
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
and context including class names, function names, and 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 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("'", "'\"'\"'") + "'"
#
# 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. | ) |
Next line prediction: <|code_start|>from __future__ import print_function, absolute_import
ansible_path = os.path.join(aeriscloud_path, 'ansible')
plugin_path = os.path.join(ansible_path, 'plugins')
job_path = os.path.join(ansible_path, 'jobs')
inventory_path = os.path.join(data_dir(), 'inventory')
organization_path = os.path.join(data_dir(), 'organizations')
logger = get_logger('ansible')
def ansible_env(env):
env['PATH'] = os.pathsep.join([
os.path.join(aeriscloud_path, 'venv/bin'),
env['PATH']
])
# disable buffering for ansible
env['PYTHONUNBUFFERED'] = '1'
env['ANSIBLE_BASE_PATH'] = ansible_path
<|code_end|>
. Use current file imports:
(import os
from subprocess32 import Popen, PIPE, call
from ansible import constants
from .config import aeriscloud_path, verbosity, data_dir
from .log import get_logger
from .utils import quote, timestamp
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager)
and context including class names, function names, or small code snippets 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 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("'", "'\"'\"'") + "'"
#
# 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. | env['ANSIBLE_ACTION_PLUGINS'] = ':'.join( |
Continue the code snippet: <|code_start|>
ansible_path = os.path.join(aeriscloud_path, 'ansible')
plugin_path = os.path.join(ansible_path, 'plugins')
job_path = os.path.join(ansible_path, 'jobs')
inventory_path = os.path.join(data_dir(), 'inventory')
organization_path = os.path.join(data_dir(), 'organizations')
logger = get_logger('ansible')
def ansible_env(env):
env['PATH'] = os.pathsep.join([
os.path.join(aeriscloud_path, 'venv/bin'),
env['PATH']
])
# disable buffering for ansible
env['PYTHONUNBUFFERED'] = '1'
env['ANSIBLE_BASE_PATH'] = ansible_path
env['ANSIBLE_ACTION_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'actions')] +
constants.DEFAULT_ACTION_PLUGIN_PATH
)
env['ANSIBLE_CALLBACK_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'callbacks')] +
constants.DEFAULT_CALLBACK_PLUGIN_PATH
<|code_end|>
. Use current file imports:
import os
from subprocess32 import Popen, PIPE, call
from ansible import constants
from .config import aeriscloud_path, verbosity, data_dir
from .log import get_logger
from .utils import quote, timestamp
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
and context (classes, functions, or 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 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("'", "'\"'\"'") + "'"
#
# 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. | ) |
Given snippet: <|code_start|> ])
# disable buffering for ansible
env['PYTHONUNBUFFERED'] = '1'
env['ANSIBLE_BASE_PATH'] = ansible_path
env['ANSIBLE_ACTION_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'actions')] +
constants.DEFAULT_ACTION_PLUGIN_PATH
)
env['ANSIBLE_CALLBACK_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'callbacks')] +
constants.DEFAULT_CALLBACK_PLUGIN_PATH
)
env['ANSIBLE_CONNECTION_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'connections')] +
constants.DEFAULT_CONNECTION_PLUGIN_PATH
)
env['ANSIBLE_FILTER_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'filters')] +
constants.DEFAULT_FILTER_PLUGIN_PATH
)
env['ANSIBLE_LOOKUP_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'lookups')] +
constants.DEFAULT_LOOKUP_PLUGIN_PATH
)
env['ANSIBLE_VARS_PLUGINS'] = ':'.join(
[os.path.join(plugin_path, 'vars')] +
constants.DEFAULT_VARS_PLUGIN_PATH
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from subprocess32 import Popen, PIPE, call
from ansible import constants
from .config import aeriscloud_path, verbosity, data_dir
from .log import get_logger
from .utils import quote, timestamp
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory as AnsibleInventory
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
and context:
# 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 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("'", "'\"'\"'") + "'"
#
# 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 might include code, classes, or functions. Output only the next line. | env['ANSIBLE_NOCOWS'] = '1' |
Given the code snippet: <|code_start|>#!/usr/bin/env python
status_table = CLITable('project', 'name', 'image', 'status')
def _status_sort(status):
return '%s-%s' % (status['project'], status['name'])
@click.command(cls=Command)
@click.option('--show-all', is_flag=True, default=False,
<|code_end|>
, generate the next line using the imports in this file:
import click
from aeriscloud.cli.helpers import standard_options, Command, CLITable
and context (functions, classes, or occasionally code) 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)
#
# class CLITable(object):
# """
# Helps displaying a dynamically sized table a la docker ps
# """
# COL_PADDING = 2
#
# def __init__(self, *cols):
# self._cols = cols
# self._header_out = False
#
# def _str(self, data, size):
# str_real_len = len(strip_ansi(data))
# return data + (' ' * (size - str_real_len))
#
# def _compute_col_sizes(self, data):
# sizes = {}
# # prepend data with header
# data = [dict(zip(self._cols, self._cols))] + data
# for row in data:
# for name, row_data in row.iteritems():
# real_len = len(strip_ansi(row_data))
# if name not in sizes or real_len > sizes[name]:
# sizes[name] = real_len
# # filter unknown values
# self._sizes = dict([
# (key, length + self.COL_PADDING)
# for key, length in sizes.iteritems()
# if key in self._cols
# ])
#
# def _header(self):
# if self._header_out:
# return
#
# self._header_out = True
# for name in self._cols:
# click.echo(self._str(name.upper(), self._sizes[name]), nl=False)
# click.echo('')
#
# def echo(self, data):
# if not isinstance(data, list):
# data = [data]
#
# self._compute_col_sizes(data)
# self._header()
#
# for row in data:
# for name in self._cols:
# row_data = ''
# if name in row:
# row_data = row[name]
# click.echo(self._str(row_data, self._sizes[name]), nl=False)
# click.echo('')
. Output only the next line. | help='Show boxes that are not created in virtualbox') |
Given the code snippet: <|code_start|>#!/usr/bin/env python
status_table = CLITable('project', 'name', 'image', 'status')
def _status_sort(status):
return '%s-%s' % (status['project'], status['name'])
@click.command(cls=Command)
@click.option('--show-all', is_flag=True, default=False,
help='Show boxes that are not created in virtualbox')
@standard_options(multiple=True)
<|code_end|>
, generate the next line using the imports in this file:
import click
from aeriscloud.cli.helpers import standard_options, Command, CLITable
and context (functions, classes, or occasionally code) 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)
#
# class CLITable(object):
# """
# Helps displaying a dynamically sized table a la docker ps
# """
# COL_PADDING = 2
#
# def __init__(self, *cols):
# self._cols = cols
# self._header_out = False
#
# def _str(self, data, size):
# str_real_len = len(strip_ansi(data))
# return data + (' ' * (size - str_real_len))
#
# def _compute_col_sizes(self, data):
# sizes = {}
# # prepend data with header
# data = [dict(zip(self._cols, self._cols))] + data
# for row in data:
# for name, row_data in row.iteritems():
# real_len = len(strip_ansi(row_data))
# if name not in sizes or real_len > sizes[name]:
# sizes[name] = real_len
# # filter unknown values
# self._sizes = dict([
# (key, length + self.COL_PADDING)
# for key, length in sizes.iteritems()
# if key in self._cols
# ])
#
# def _header(self):
# if self._header_out:
# return
#
# self._header_out = True
# for name in self._cols:
# click.echo(self._str(name.upper(), self._sizes[name]), nl=False)
# click.echo('')
#
# def echo(self, data):
# if not isinstance(data, list):
# data = [data]
#
# self._compute_col_sizes(data)
# self._header()
#
# for row in data:
# for name in self._cols:
# row_data = ''
# if name in row:
# row_data = row[name]
# click.echo(self._str(row_data, self._sizes[name]), nl=False)
# click.echo('')
. Output only the next line. | def cli(boxes, show_all): |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.option('-q', '--quiet', is_flag=True)
@standard_options()
<|code_end|>
, predict the next line using imports from the current file:
import arrow
import click
import re
import sys
from aeriscloud.cli.helpers import standard_options, Command, render_cli
and context including class names, function names, and sometimes code 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)
. Output only the next line. | def cli(box, quiet): |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.option('-q', '--quiet', is_flag=True)
@standard_options()
<|code_end|>
using the current file's imports:
import arrow
import click
import re
import sys
from aeriscloud.cli.helpers import standard_options, Command, render_cli
and any relevant 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)
. Output only the next line. | def cli(box, quiet): |
Given snippet: <|code_start|>#!/usr/bin/env python
@click.command(cls=Command)
@click.option('-q', '--quiet', is_flag=True)
@standard_options()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import arrow
import click
import re
import sys
from aeriscloud.cli.helpers import standard_options, Command, render_cli
and context:
# 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)
which might include code, classes, or functions. Output only the next line. | def cli(box, quiet): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
class BoxCommandAutoRestart(AutoRestartTrick):
def __init__(self, box, command, **kwargs):
AutoRestartTrick.__init__(self, [], **kwargs)
self.box = box
<|code_end|>
, generate the next line using the imports in this file:
import click
import os
import signal
import sys
import time
from watchdog.observers import Observer
from watchdog.tricks import AutoRestartTrick
from aeriscloud.cli.aeris.sync import sync
from aeriscloud.cli.helpers import standard_options, Command
and context (functions, classes, or occasionally 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)
. Output only the next line. | self.command = command |
Using the snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
class BoxCommandAutoRestart(AutoRestartTrick):
def __init__(self, box, command, **kwargs):
AutoRestartTrick.__init__(self, [], **kwargs)
<|code_end|>
, determine the next line of code. You have imports:
import click
import os
import signal
import sys
import time
from watchdog.observers import Observer
from watchdog.tricks import AutoRestartTrick
from aeriscloud.cli.aeris.sync import sync
from aeriscloud.cli.helpers import standard_options, Command
and context (class names, function names, or code) available:
# 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)
. Output only the next line. | self.box = box |
Given snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
class BoxCommandAutoRestart(AutoRestartTrick):
def __init__(self, box, command, **kwargs):
AutoRestartTrick.__init__(self, [], **kwargs)
self.box = box
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import os
import signal
import sys
import time
from watchdog.observers import Observer
from watchdog.tricks import AutoRestartTrick
from aeriscloud.cli.aeris.sync import sync
from aeriscloud.cli.helpers import standard_options, Command
and context:
# 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)
which might include code, classes, or functions. Output only the next line. | self.command = command |
Using the snippet: <|code_start|>#!/usr/bin/env python
# Import the CLI system
cmd_help = {
'aeris': 'Manage your local development environments',
'cloud': 'Manage your remote servers and datacenters'
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
from .helpers import AerisCLI
from ..config import module_path
and context (class names, function names, or code) available:
# Path: aeriscloud/cli/helpers.py
# class AerisCLI(click.MultiCommand):
# def __init__(self, command_dir, *args, **kwargs):
# cs = dict(help_option_names=['-h', '--help'])
# params = [
# click.Option(
# param_decls=['-v', '--verbose'],
# count=True,
# help='Make commands verbose, use '
# 'multiple time for higher verbosity'
# ),
# click.Option(
# param_decls=['--log-file'],
# help='When using the verbose flag, redirects '
# 'output to this file'
# )
# ]
# super(AerisCLI, self).__init__(context_settings=cs, params=params,
# *args, **kwargs)
# self.command_dir = command_dir
#
# no_setup = 'AC_NO_ASSISTANT' in os.environ \
# and os.environ['AC_NO_ASSISTANT'] == '1'
# if not no_setup and sys.stdout.isatty() and not config.complete():
# click.echo('''
# It seems it is the first time you are launching AerisCloud, or new
# configuration options were added since the last update. We can guide
# you through a series of questions to setup your configuration.
# ''', err=True)
# if not click.confirm('Run configuration assistant', default=True):
# return
# from .config import assistant
#
# assistant()
#
# def list_commands(self, ctx):
# excluded = ['complete', 'test']
#
# rv = [filename[:-3].replace('_', '-') for filename in
# os.listdir(self.command_dir)
# if filename.endswith('.py') and
# filename[:-3] not in excluded and
# not filename.startswith('__')]
# rv.sort()
# return rv
#
# def get_command(self, ctx, name):
# ns = {}
# fn = os.path.join(self.command_dir, name.replace('-', '_') + '.py')
#
# if not os.path.exists(fn):
# click.echo('error: unknown command: %s' % name)
# sys.exit(1)
#
# with open(fn) as f:
# code = compile(f.read(), fn, 'exec')
# eval(code, ns, ns)
# return ns['cli']
#
# def invoke(self, ctx): # noqa
# # setup logging
# if 'verbose' in ctx.params and ctx.params['verbose']:
# level = max(10, 40 - ctx.params['verbose'] * 10)
# set_log_level(level)
# verbosity(ctx.params['verbose'])
# if 'log_file' in ctx.params and ctx.params['log_file']:
# set_log_file(ctx.params['log_file'])
#
# # try running the command
# try:
# super(AerisCLI, self).invoke(ctx)
# except SystemExit:
# raise
# except click.UsageError as e:
# click.secho('error: %s' % e.message, err=True, fg='red')
# click.echo(e.ctx.command.get_help(e.ctx), err=True)
# sys.exit(e.exit_code)
# except (ExposeTimeout, ExposeConnectionError):
# warning('warning: expose is not available at the moment')
# except KeyboardInterrupt:
# logger.error('keyboard interrupt while running subcommand "%s"',
# ctx.invoked_subcommand, exc_info=sys.exc_info())
# warning('\nwarning: ctrl+c pressed, aborting')
# except:
# log_id = None
# if config.has('config', 'raven'):
# from raven import Client
# client = Client('requests+' + config.get('config', 'raven'))
# log_id = client.get_ident(client.captureException(
# tags={
# 'python': sys.version,
# 'aeriscloud': ac_version,
# 'platform': sys.platform
# },
# extra={
# 'user': os.environ['USER']
# }
# ))
#
# logger.error('uncaught exception while running subcommand "%s"',
# ctx.invoked_subcommand, exc_info=sys.exc_info())
# if log_id:
# fatal('error: an internal exception caused "%s" '
# 'to exit unexpectedly (log id: %s)' % (ctx.info_name,
# log_id))
# else:
# fatal('error: an internal exception caused "%s" '
# 'to exit unexpectedly' % ctx.info_name)
#
# Path: aeriscloud/config.py
# @memoized
# def module_path():
# return os.path.dirname(__file__)
. Output only the next line. | } |
Here is a snippet: <|code_start|>#!/usr/bin/env python
def check_expose(func):
@click.pass_context
def _deco(ctx, *args, **kwargs):
if not expose.enabled():
click.secho('warning: aeris.cd is not enabled', fg='yellow')
<|code_end|>
. Write the next line using the current file imports:
import click
import sys
from functools import update_wrapper
from json import dumps
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import Command, CLITable, success, fatal
from aeriscloud.config import expose_url, expose_username
from aeriscloud.expose import expose_client, expose
and context from other files:
# Path: aeriscloud/cli/helpers.py
# 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)
#
# class CLITable(object):
# """
# Helps displaying a dynamically sized table a la docker ps
# """
# COL_PADDING = 2
#
# def __init__(self, *cols):
# self._cols = cols
# self._header_out = False
#
# def _str(self, data, size):
# str_real_len = len(strip_ansi(data))
# return data + (' ' * (size - str_real_len))
#
# def _compute_col_sizes(self, data):
# sizes = {}
# # prepend data with header
# data = [dict(zip(self._cols, self._cols))] + data
# for row in data:
# for name, row_data in row.iteritems():
# real_len = len(strip_ansi(row_data))
# if name not in sizes or real_len > sizes[name]:
# sizes[name] = real_len
# # filter unknown values
# self._sizes = dict([
# (key, length + self.COL_PADDING)
# for key, length in sizes.iteritems()
# if key in self._cols
# ])
#
# def _header(self):
# if self._header_out:
# return
#
# self._header_out = True
# for name in self._cols:
# click.echo(self._str(name.upper(), self._sizes[name]), nl=False)
# click.echo('')
#
# def echo(self, data):
# if not isinstance(data, list):
# data = [data]
#
# self._compute_col_sizes(data)
# self._header()
#
# for row in data:
# for name in self._cols:
# row_data = ''
# if name in row:
# row_data = row[name]
# click.echo(self._str(row_data, self._sizes[name]), nl=False)
# click.echo('')
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# Path: aeriscloud/config.py
# def expose_url():
# return config.get('aeris', 'url', default=None)
#
# def expose_username():
# email = config.get('aeris', 'email', default=None)
# if not email:
# return None
# return email.split('@')[0]
#
# Path: aeriscloud/expose.py
# class ExposeError(RuntimeError):
# class ExposeTimeout(ExposeError):
# class ExposeConnectionError(ExposeError):
# class Expose(object):
# class Client:
# def __init__(self, e):
# def __init__(self):
# def load(self):
# def file(self):
# def save(self):
# def start(self):
# def stop(self):
# def enabled(self):
# def announce(self):
# def add(self, box, announce=True):
# def remove(self, box, announce=False):
# def list(self):
# def __init__(self, email, username=None, password=None, token=None,
# api_url=None, fullname=None):
# def get_email(self):
# def _do_request(self, type, *args, **kwargs):
# def set_token(self, token):
# def get_headers(self, type=None):
# def get_vms(self):
# def signup(self, password, fullname=None):
# def get_user(self, username):
# def update(self):
# def service(self, services, replace=False):
# def get_token(self, password=None):
# def expose_client():
, which may include functions, classes, or code. Output only the next line. | sys.exit(1) |
Using the snippet: <|code_start|>#!/usr/bin/env python
def check_expose(func):
@click.pass_context
def _deco(ctx, *args, **kwargs):
if not expose.enabled():
<|code_end|>
, determine the next line of code. You have imports:
import click
import sys
from functools import update_wrapper
from json import dumps
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import Command, CLITable, success, fatal
from aeriscloud.config import expose_url, expose_username
from aeriscloud.expose import expose_client, expose
and context (class names, function names, or code) available:
# Path: aeriscloud/cli/helpers.py
# 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)
#
# class CLITable(object):
# """
# Helps displaying a dynamically sized table a la docker ps
# """
# COL_PADDING = 2
#
# def __init__(self, *cols):
# self._cols = cols
# self._header_out = False
#
# def _str(self, data, size):
# str_real_len = len(strip_ansi(data))
# return data + (' ' * (size - str_real_len))
#
# def _compute_col_sizes(self, data):
# sizes = {}
# # prepend data with header
# data = [dict(zip(self._cols, self._cols))] + data
# for row in data:
# for name, row_data in row.iteritems():
# real_len = len(strip_ansi(row_data))
# if name not in sizes or real_len > sizes[name]:
# sizes[name] = real_len
# # filter unknown values
# self._sizes = dict([
# (key, length + self.COL_PADDING)
# for key, length in sizes.iteritems()
# if key in self._cols
# ])
#
# def _header(self):
# if self._header_out:
# return
#
# self._header_out = True
# for name in self._cols:
# click.echo(self._str(name.upper(), self._sizes[name]), nl=False)
# click.echo('')
#
# def echo(self, data):
# if not isinstance(data, list):
# data = [data]
#
# self._compute_col_sizes(data)
# self._header()
#
# for row in data:
# for name in self._cols:
# row_data = ''
# if name in row:
# row_data = row[name]
# click.echo(self._str(row_data, self._sizes[name]), nl=False)
# click.echo('')
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# Path: aeriscloud/config.py
# def expose_url():
# return config.get('aeris', 'url', default=None)
#
# def expose_username():
# email = config.get('aeris', 'email', default=None)
# if not email:
# return None
# return email.split('@')[0]
#
# Path: aeriscloud/expose.py
# class ExposeError(RuntimeError):
# class ExposeTimeout(ExposeError):
# class ExposeConnectionError(ExposeError):
# class Expose(object):
# class Client:
# def __init__(self, e):
# def __init__(self):
# def load(self):
# def file(self):
# def save(self):
# def start(self):
# def stop(self):
# def enabled(self):
# def announce(self):
# def add(self, box, announce=True):
# def remove(self, box, announce=False):
# def list(self):
# def __init__(self, email, username=None, password=None, token=None,
# api_url=None, fullname=None):
# def get_email(self):
# def _do_request(self, type, *args, **kwargs):
# def set_token(self, token):
# def get_headers(self, type=None):
# def get_vms(self):
# def signup(self, password, fullname=None):
# def get_user(self, username):
# def update(self):
# def service(self, services, replace=False):
# def get_token(self, password=None):
# def expose_client():
. Output only the next line. | click.secho('warning: aeris.cd is not enabled', fg='yellow') |
Here is a snippet: <|code_start|>#!/usr/bin/env python
def check_expose(func):
@click.pass_context
def _deco(ctx, *args, **kwargs):
if not expose.enabled():
click.secho('warning: aeris.cd is not enabled', fg='yellow')
sys.exit(1)
try:
<|code_end|>
. Write the next line using the current file imports:
import click
import sys
from functools import update_wrapper
from json import dumps
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import Command, CLITable, success, fatal
from aeriscloud.config import expose_url, expose_username
from aeriscloud.expose import expose_client, expose
and context from other files:
# Path: aeriscloud/cli/helpers.py
# 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)
#
# class CLITable(object):
# """
# Helps displaying a dynamically sized table a la docker ps
# """
# COL_PADDING = 2
#
# def __init__(self, *cols):
# self._cols = cols
# self._header_out = False
#
# def _str(self, data, size):
# str_real_len = len(strip_ansi(data))
# return data + (' ' * (size - str_real_len))
#
# def _compute_col_sizes(self, data):
# sizes = {}
# # prepend data with header
# data = [dict(zip(self._cols, self._cols))] + data
# for row in data:
# for name, row_data in row.iteritems():
# real_len = len(strip_ansi(row_data))
# if name not in sizes or real_len > sizes[name]:
# sizes[name] = real_len
# # filter unknown values
# self._sizes = dict([
# (key, length + self.COL_PADDING)
# for key, length in sizes.iteritems()
# if key in self._cols
# ])
#
# def _header(self):
# if self._header_out:
# return
#
# self._header_out = True
# for name in self._cols:
# click.echo(self._str(name.upper(), self._sizes[name]), nl=False)
# click.echo('')
#
# def echo(self, data):
# if not isinstance(data, list):
# data = [data]
#
# self._compute_col_sizes(data)
# self._header()
#
# for row in data:
# for name in self._cols:
# row_data = ''
# if name in row:
# row_data = row[name]
# click.echo(self._str(row_data, self._sizes[name]), nl=False)
# click.echo('')
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# Path: aeriscloud/config.py
# def expose_url():
# return config.get('aeris', 'url', default=None)
#
# def expose_username():
# email = config.get('aeris', 'email', default=None)
# if not email:
# return None
# return email.split('@')[0]
#
# Path: aeriscloud/expose.py
# class ExposeError(RuntimeError):
# class ExposeTimeout(ExposeError):
# class ExposeConnectionError(ExposeError):
# class Expose(object):
# class Client:
# def __init__(self, e):
# def __init__(self):
# def load(self):
# def file(self):
# def save(self):
# def start(self):
# def stop(self):
# def enabled(self):
# def announce(self):
# def add(self, box, announce=True):
# def remove(self, box, announce=False):
# def list(self):
# def __init__(self, email, username=None, password=None, token=None,
# api_url=None, fullname=None):
# def get_email(self):
# def _do_request(self, type, *args, **kwargs):
# def set_token(self, token):
# def get_headers(self, type=None):
# def get_vms(self):
# def signup(self, password, fullname=None):
# def get_user(self, username):
# def update(self):
# def service(self, services, replace=False):
# def get_token(self, password=None):
# def expose_client():
, which may include functions, classes, or code. Output only the next line. | return ctx.invoke(func, *args, **kwargs) |
Using the snippet: <|code_start|>#!/usr/bin/env python
def check_expose(func):
@click.pass_context
def _deco(ctx, *args, **kwargs):
if not expose.enabled():
click.secho('warning: aeris.cd is not enabled', fg='yellow')
sys.exit(1)
try:
<|code_end|>
, determine the next line of code. You have imports:
import click
import sys
from functools import update_wrapper
from json import dumps
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import Command, CLITable, success, fatal
from aeriscloud.config import expose_url, expose_username
from aeriscloud.expose import expose_client, expose
and context (class names, function names, or code) available:
# Path: aeriscloud/cli/helpers.py
# 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)
#
# class CLITable(object):
# """
# Helps displaying a dynamically sized table a la docker ps
# """
# COL_PADDING = 2
#
# def __init__(self, *cols):
# self._cols = cols
# self._header_out = False
#
# def _str(self, data, size):
# str_real_len = len(strip_ansi(data))
# return data + (' ' * (size - str_real_len))
#
# def _compute_col_sizes(self, data):
# sizes = {}
# # prepend data with header
# data = [dict(zip(self._cols, self._cols))] + data
# for row in data:
# for name, row_data in row.iteritems():
# real_len = len(strip_ansi(row_data))
# if name not in sizes or real_len > sizes[name]:
# sizes[name] = real_len
# # filter unknown values
# self._sizes = dict([
# (key, length + self.COL_PADDING)
# for key, length in sizes.iteritems()
# if key in self._cols
# ])
#
# def _header(self):
# if self._header_out:
# return
#
# self._header_out = True
# for name in self._cols:
# click.echo(self._str(name.upper(), self._sizes[name]), nl=False)
# click.echo('')
#
# def echo(self, data):
# if not isinstance(data, list):
# data = [data]
#
# self._compute_col_sizes(data)
# self._header()
#
# for row in data:
# for name in self._cols:
# row_data = ''
# if name in row:
# row_data = row[name]
# click.echo(self._str(row_data, self._sizes[name]), nl=False)
# click.echo('')
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# Path: aeriscloud/config.py
# def expose_url():
# return config.get('aeris', 'url', default=None)
#
# def expose_username():
# email = config.get('aeris', 'email', default=None)
# if not email:
# return None
# return email.split('@')[0]
#
# Path: aeriscloud/expose.py
# class ExposeError(RuntimeError):
# class ExposeTimeout(ExposeError):
# class ExposeConnectionError(ExposeError):
# class Expose(object):
# class Client:
# def __init__(self, e):
# def __init__(self):
# def load(self):
# def file(self):
# def save(self):
# def start(self):
# def stop(self):
# def enabled(self):
# def announce(self):
# def add(self, box, announce=True):
# def remove(self, box, announce=False):
# def list(self):
# def __init__(self, email, username=None, password=None, token=None,
# api_url=None, fullname=None):
# def get_email(self):
# def _do_request(self, type, *args, **kwargs):
# def set_token(self, token):
# def get_headers(self, type=None):
# def get_vms(self):
# def signup(self, password, fullname=None):
# def get_user(self, username):
# def update(self):
# def service(self, services, replace=False):
# def get_token(self, password=None):
# def expose_client():
. Output only the next line. | return ctx.invoke(func, *args, **kwargs) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
def check_expose(func):
@click.pass_context
def _deco(ctx, *args, **kwargs):
if not expose.enabled():
click.secho('warning: aeris.cd is not enabled', fg='yellow')
<|code_end|>
, predict the immediate next line with the help of imports:
import click
import sys
from functools import update_wrapper
from json import dumps
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import Command, CLITable, success, fatal
from aeriscloud.config import expose_url, expose_username
from aeriscloud.expose import expose_client, expose
and context (classes, functions, sometimes code) from other files:
# Path: aeriscloud/cli/helpers.py
# 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)
#
# class CLITable(object):
# """
# Helps displaying a dynamically sized table a la docker ps
# """
# COL_PADDING = 2
#
# def __init__(self, *cols):
# self._cols = cols
# self._header_out = False
#
# def _str(self, data, size):
# str_real_len = len(strip_ansi(data))
# return data + (' ' * (size - str_real_len))
#
# def _compute_col_sizes(self, data):
# sizes = {}
# # prepend data with header
# data = [dict(zip(self._cols, self._cols))] + data
# for row in data:
# for name, row_data in row.iteritems():
# real_len = len(strip_ansi(row_data))
# if name not in sizes or real_len > sizes[name]:
# sizes[name] = real_len
# # filter unknown values
# self._sizes = dict([
# (key, length + self.COL_PADDING)
# for key, length in sizes.iteritems()
# if key in self._cols
# ])
#
# def _header(self):
# if self._header_out:
# return
#
# self._header_out = True
# for name in self._cols:
# click.echo(self._str(name.upper(), self._sizes[name]), nl=False)
# click.echo('')
#
# def echo(self, data):
# if not isinstance(data, list):
# data = [data]
#
# self._compute_col_sizes(data)
# self._header()
#
# for row in data:
# for name in self._cols:
# row_data = ''
# if name in row:
# row_data = row[name]
# click.echo(self._str(row_data, self._sizes[name]), nl=False)
# click.echo('')
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# Path: aeriscloud/config.py
# def expose_url():
# return config.get('aeris', 'url', default=None)
#
# def expose_username():
# email = config.get('aeris', 'email', default=None)
# if not email:
# return None
# return email.split('@')[0]
#
# Path: aeriscloud/expose.py
# class ExposeError(RuntimeError):
# class ExposeTimeout(ExposeError):
# class ExposeConnectionError(ExposeError):
# class Expose(object):
# class Client:
# def __init__(self, e):
# def __init__(self):
# def load(self):
# def file(self):
# def save(self):
# def start(self):
# def stop(self):
# def enabled(self):
# def announce(self):
# def add(self, box, announce=True):
# def remove(self, box, announce=False):
# def list(self):
# def __init__(self, email, username=None, password=None, token=None,
# api_url=None, fullname=None):
# def get_email(self):
# def _do_request(self, type, *args, **kwargs):
# def set_token(self, token):
# def get_headers(self, type=None):
# def get_vms(self):
# def signup(self, password, fullname=None):
# def get_user(self, username):
# def update(self):
# def service(self, services, replace=False):
# def get_token(self, password=None):
# def expose_client():
. Output only the next line. | sys.exit(1) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
def check_expose(func):
@click.pass_context
def _deco(ctx, *args, **kwargs):
if not expose.enabled():
click.secho('warning: aeris.cd is not enabled', fg='yellow')
sys.exit(1)
<|code_end|>
. Use current file imports:
import click
import sys
from functools import update_wrapper
from json import dumps
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import Command, CLITable, success, fatal
from aeriscloud.config import expose_url, expose_username
from aeriscloud.expose import expose_client, expose
and context (classes, functions, or code) from other files:
# Path: aeriscloud/cli/helpers.py
# 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)
#
# class CLITable(object):
# """
# Helps displaying a dynamically sized table a la docker ps
# """
# COL_PADDING = 2
#
# def __init__(self, *cols):
# self._cols = cols
# self._header_out = False
#
# def _str(self, data, size):
# str_real_len = len(strip_ansi(data))
# return data + (' ' * (size - str_real_len))
#
# def _compute_col_sizes(self, data):
# sizes = {}
# # prepend data with header
# data = [dict(zip(self._cols, self._cols))] + data
# for row in data:
# for name, row_data in row.iteritems():
# real_len = len(strip_ansi(row_data))
# if name not in sizes or real_len > sizes[name]:
# sizes[name] = real_len
# # filter unknown values
# self._sizes = dict([
# (key, length + self.COL_PADDING)
# for key, length in sizes.iteritems()
# if key in self._cols
# ])
#
# def _header(self):
# if self._header_out:
# return
#
# self._header_out = True
# for name in self._cols:
# click.echo(self._str(name.upper(), self._sizes[name]), nl=False)
# click.echo('')
#
# def echo(self, data):
# if not isinstance(data, list):
# data = [data]
#
# self._compute_col_sizes(data)
# self._header()
#
# for row in data:
# for name in self._cols:
# row_data = ''
# if name in row:
# row_data = row[name]
# click.echo(self._str(row_data, self._sizes[name]), nl=False)
# click.echo('')
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# Path: aeriscloud/config.py
# def expose_url():
# return config.get('aeris', 'url', default=None)
#
# def expose_username():
# email = config.get('aeris', 'email', default=None)
# if not email:
# return None
# return email.split('@')[0]
#
# Path: aeriscloud/expose.py
# class ExposeError(RuntimeError):
# class ExposeTimeout(ExposeError):
# class ExposeConnectionError(ExposeError):
# class Expose(object):
# class Client:
# def __init__(self, e):
# def __init__(self):
# def load(self):
# def file(self):
# def save(self):
# def start(self):
# def stop(self):
# def enabled(self):
# def announce(self):
# def add(self, box, announce=True):
# def remove(self, box, announce=False):
# def list(self):
# def __init__(self, email, username=None, password=None, token=None,
# api_url=None, fullname=None):
# def get_email(self):
# def _do_request(self, type, *args, **kwargs):
# def set_token(self, token):
# def get_headers(self, type=None):
# def get_vms(self):
# def signup(self, password, fullname=None):
# def get_user(self, username):
# def update(self):
# def service(self, services, replace=False):
# def get_token(self, password=None):
# def expose_client():
. Output only the next line. | try: |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
def check_expose(func):
@click.pass_context
def _deco(ctx, *args, **kwargs):
if not expose.enabled():
click.secho('warning: aeris.cd is not enabled', fg='yellow')
sys.exit(1)
try:
return ctx.invoke(func, *args, **kwargs)
except HTTPError as e:
fatal(e.message)
return update_wrapper(_deco, func)
@click.group()
<|code_end|>
. Use current file imports:
import click
import sys
from functools import update_wrapper
from json import dumps
from requests.exceptions import HTTPError
from aeriscloud.cli.helpers import Command, CLITable, success, fatal
from aeriscloud.config import expose_url, expose_username
from aeriscloud.expose import expose_client, expose
and context (classes, functions, or code) from other files:
# Path: aeriscloud/cli/helpers.py
# 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)
#
# class CLITable(object):
# """
# Helps displaying a dynamically sized table a la docker ps
# """
# COL_PADDING = 2
#
# def __init__(self, *cols):
# self._cols = cols
# self._header_out = False
#
# def _str(self, data, size):
# str_real_len = len(strip_ansi(data))
# return data + (' ' * (size - str_real_len))
#
# def _compute_col_sizes(self, data):
# sizes = {}
# # prepend data with header
# data = [dict(zip(self._cols, self._cols))] + data
# for row in data:
# for name, row_data in row.iteritems():
# real_len = len(strip_ansi(row_data))
# if name not in sizes or real_len > sizes[name]:
# sizes[name] = real_len
# # filter unknown values
# self._sizes = dict([
# (key, length + self.COL_PADDING)
# for key, length in sizes.iteritems()
# if key in self._cols
# ])
#
# def _header(self):
# if self._header_out:
# return
#
# self._header_out = True
# for name in self._cols:
# click.echo(self._str(name.upper(), self._sizes[name]), nl=False)
# click.echo('')
#
# def echo(self, data):
# if not isinstance(data, list):
# data = [data]
#
# self._compute_col_sizes(data)
# self._header()
#
# for row in data:
# for name in self._cols:
# row_data = ''
# if name in row:
# row_data = row[name]
# click.echo(self._str(row_data, self._sizes[name]), nl=False)
# click.echo('')
#
# def success(text, **kwargs):
# click.secho(text, fg='green', **kwargs)
#
# def fatal(text, code=1, **kwargs):
# error(text, **kwargs)
# sys.exit(code)
#
# Path: aeriscloud/config.py
# def expose_url():
# return config.get('aeris', 'url', default=None)
#
# def expose_username():
# email = config.get('aeris', 'email', default=None)
# if not email:
# return None
# return email.split('@')[0]
#
# Path: aeriscloud/expose.py
# class ExposeError(RuntimeError):
# class ExposeTimeout(ExposeError):
# class ExposeConnectionError(ExposeError):
# class Expose(object):
# class Client:
# def __init__(self, e):
# def __init__(self):
# def load(self):
# def file(self):
# def save(self):
# def start(self):
# def stop(self):
# def enabled(self):
# def announce(self):
# def add(self, box, announce=True):
# def remove(self, box, announce=False):
# def list(self):
# def __init__(self, email, username=None, password=None, token=None,
# api_url=None, fullname=None):
# def get_email(self):
# def _do_request(self, type, *args, **kwargs):
# def set_token(self, token):
# def get_headers(self, type=None):
# def get_vms(self):
# def signup(self, password, fullname=None):
# def get_user(self, username):
# def update(self):
# def service(self, services, replace=False):
# def get_token(self, password=None):
# def expose_client():
. Output only the next line. | def cli(): |
Given snippet: <|code_start|>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
@click.command(cls=Command)
@click.argument('direction', required=False, default='up',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import sys
from aeriscloud.cli.helpers import standard_options, Command
and context:
# 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 might include code, classes, or functions. Output only the next line. | type=click.Choice(['up', 'down'])) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
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:
<|code_end|>
with the help of current file imports:
import click
import sys
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.secho('Sync up failed!', fg='red', bold=True) |
Given snippet: <|code_start|>
# python3 compat
if sys.version_info[0] < 3:
else:
@memoized
def module_path():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import os
import ConfigParser as configparser
import configparser
from appdirs import user_config_dir, user_data_dir
from .utils import memoized
and context:
# Path: aeriscloud/utils.py
# def memoized(func):
# _cache = {}
#
# def _deco(*args, **kwargs):
# if 'clear_cache' in kwargs or 'clear_cache_only' in kwargs:
# _cache.clear()
# if 'clear_cache_only' in kwargs:
# return # we don't care about the output
# del kwargs['clear_cache']
# if not isinstance(args, collections.Hashable):
# return func(*args, **kwargs)
# if args in _cache:
# return _cache[args]
# else:
# value = func(*args, **kwargs)
# _cache[args] = value
# return value
#
# return update_wrapper(_deco, func)
which might include code, classes, or functions. Output only the next line. | return os.path.dirname(__file__) |
Given snippet: <|code_start|> 'invoicing_customer_name': u'Matti Mallikas',
'invoicing_customer_name_extension': u'Masa',
'invoicing_customer_address_line': u'Pajukuja 1',
'invoicing_customer_additional_address_line': None,
'invoicing_customer_post_number': u'53100',
'invoicing_customer_town': u'Lappeenranta',
'invoicing_customer_country_code': u'FI',
'delivery_address_name': u'Netvisor Oy',
'delivery_address_name_extension':
u'Ohjelmistokehitys ja tuotanto',
'delivery_address_line': u'Snelmanninkatu 12',
'delivery_address_post_number': u'53100',
'delivery_address_town': u'LPR',
'delivery_address_country_code': u'FI',
'payment_term_net_days': 14,
'payment_term_cash_discount_days': 5,
'payment_term_cash_discount': decimal.Decimal('9'),
'invoice_lines': [
{
'identifier': '1697',
'name': 'Omena',
'unit_price': {
'amount': decimal.Decimal('6.90'),
'type': 'net'
},
'vat_percentage': {
'percentage': decimal.Decimal('22'),
'code': 'KOMY',
},
'quantity': decimal.Decimal('2'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import decimal
import pytest
from datetime import date
from marshmallow import ValidationError
from netvisor.exc import InvalidData
from ..utils import get_request_content, get_response_content
and context:
# Path: netvisor/exc.py
# class InvalidData(NetvisorError):
# pass
#
# Path: tests/utils.py
# def get_request_content(filename):
# filename = os.path.join(get_requests_dir(), filename)
# return read_file(filename)
#
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
which might include code, classes, or functions. Output only the next line. | 'discount_percentage': decimal.Decimal('0'), |
Using the snippet: <|code_start|>
class TestSalesInvoiceService(object):
def test_get(self, netvisor, responses):
responses.add(
method='GET',
url='http://koulutus.netvisor.fi/GetSalesInvoice.nv?NetvisorKey=5',
body=get_response_content('GetSalesInvoice.xml'),
content_type='text/html; charset=utf-8',
match_querystring=True
)
sales_invoice = netvisor.sales_invoices.get(5)
assert sales_invoice == {
'number': 3,
'date': date(2012, 1, 27),
'delivery_date': date(2012, 1, 27),
'due_date': date(2012, 2, 11),
'reference_number': u'1070',
'amount': decimal.Decimal(244.00),
'seller_identifier': u'Jarmo',
'invoice_status': u'Unsent',
'free_text_before_lines': None,
'free_text_after_lines': None,
'our_reference': None,
'your_reference': None,
'private_comment': None,
'invoicing_customer_name': u'Matti Mallikas',
<|code_end|>
, determine the next line of code. You have imports:
import decimal
import pytest
from datetime import date
from marshmallow import ValidationError
from netvisor.exc import InvalidData
from ..utils import get_request_content, get_response_content
and context (class names, function names, or code) available:
# Path: netvisor/exc.py
# class InvalidData(NetvisorError):
# pass
#
# Path: tests/utils.py
# def get_request_content(filename):
# filename = os.path.join(get_requests_dir(), filename)
# return read_file(filename)
#
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
. Output only the next line. | 'invoicing_customer_address_line': u'Pajukuja 1', |
Predict the next line after this snippet: <|code_start|> 'date': date(2008, 12, 12),
'amount': decimal.Decimal('244.00'),
'status': 'unsent',
'invoicing_customer_identifier': u'1',
'payment_term_net_days': 14,
'payment_term_cash_discount_days': 5,
'payment_term_cash_discount': decimal.Decimal('9'),
'invoice_lines': [
{
'identifier': '1697',
'name': 'Omena',
'unit_price': {
'amount': decimal.Decimal('6.90'),
'type': 'net'
},
'vat_percentage': {
'percentage': decimal.Decimal('22'),
'code': 'KOMY',
},
'quantity': decimal.Decimal('2'),
}
]
})
request = responses.calls[0].request
assert netvisor_id == 8
assert request.body == get_request_content('SalesInvoiceMinimal.xml')
@pytest.mark.parametrize('data', [
{'foo': 'bar'},
{'invoice_lines': {'foo': 'bar'}},
<|code_end|>
using the current file's imports:
import decimal
import pytest
from datetime import date
from marshmallow import ValidationError
from netvisor.exc import InvalidData
from ..utils import get_request_content, get_response_content
and any relevant context from other files:
# Path: netvisor/exc.py
# class InvalidData(NetvisorError):
# pass
#
# Path: tests/utils.py
# def get_request_content(filename):
# filename = os.path.join(get_requests_dir(), filename)
# return read_file(filename)
#
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
. Output only the next line. | {'invoice_lines': [{'foo': 'bar'}]}, |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class TestCompanyService(object):
def test_get(self, netvisor, responses):
responses.add(
method='GET',
url=(
'http://koulutus.netvisor.fi/GetCompanyInformation.nv?'
'OrganizationIdentifier=1234567-8'
),
body=get_response_content('GetCompanyInformation.xml'),
content_type='text/html; charset=utf-8',
match_querystring=True
)
company = netvisor.companies.get('1234567-8')
assert company == {
<|code_end|>
with the help of current file imports:
from datetime import date
from ..utils import get_response_content
and context from other files:
# Path: tests/utils.py
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
, which may contain function names, class names, or code. Output only the next line. | 'name': u'General Motors Finland', |
Predict the next line after this snippet: <|code_start|> 'date': date(2000, 1, 1),
'number': 13,
'description': 'Invoice 14',
'class': 'PI Purchase Invoice',
'linked_source': {'type': 'purchaseinvoice', 'key': 15},
'uri': 'https:/netvisor.com/voucher/16',
'lines': [
{
'line_sum': Decimal('-17.18'),
'description': 'Invoice 19',
'account_number': 100,
'vat_percent': 20,
'dimensions': []
},
{
'line_sum': Decimal('-21.22'),
'description': 'Invoice 23',
'account_number': 200,
'vat_percent': 24,
'dimensions': []
}
]
},
{
'status': 'invalidated',
'key': 25,
'date': date(2000, 1, 2),
'number': 26,
'description': 'Invoice 27',
'class': 'SA Sales Invoice',
<|code_end|>
using the current file's imports:
from datetime import date
from decimal import Decimal
from ..utils import get_response_content
import pytest
and any relevant context from other files:
# Path: tests/utils.py
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
. Output only the next line. | 'linked_source': {'type': 'salesinvoice', 'key': 28}, |
Predict the next line for this snippet: <|code_start|>
class TestProductService(object):
def test_get(self, netvisor, responses):
responses.add(
method='GET',
url='http://koulutus.netvisor.fi/GetProduct.nv?id=5',
body=get_response_content('GetProduct.xml'),
content_type='text/html; charset=utf-8',
match_querystring=True
)
product = netvisor.products.get(5)
assert product == {
'product_base_information': {
'netvisor_key': 165,
'product_code': u'CC',
'product_group': u'Kirjat',
'name': u'Code Complete',
'description': u'Toinen painos',
'unit_price': {
'amount': decimal.Decimal('42.5'),
'type': 'brutto'
},
'unit': u'kpl',
'unit_weight': decimal.Decimal('0.2'),
'purchase_price': decimal.Decimal('25'),
'tariff_heading': u'Code Complete',
'comission_percentage': decimal.Decimal('11'),
<|code_end|>
with the help of current file imports:
import decimal
import pytest
from netvisor.exc import InvalidData
from ..utils import get_response_content
and context from other files:
# Path: netvisor/exc.py
# class InvalidData(NetvisorError):
# pass
#
# Path: tests/utils.py
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
, which may contain function names, class names, or code. Output only the next line. | 'is_active': True, |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
class TestProductService(object):
def test_get(self, netvisor, responses):
responses.add(
method='GET',
url='http://koulutus.netvisor.fi/GetProduct.nv?id=5',
body=get_response_content('GetProduct.xml'),
content_type='text/html; charset=utf-8',
match_querystring=True
)
product = netvisor.products.get(5)
assert product == {
'product_base_information': {
'netvisor_key': 165,
'product_code': u'CC',
'product_group': u'Kirjat',
'name': u'Code Complete',
'description': u'Toinen painos',
'unit_price': {
'amount': decimal.Decimal('42.5'),
'type': 'brutto'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import decimal
import pytest
from netvisor.exc import InvalidData
from ..utils import get_response_content
and context:
# Path: netvisor/exc.py
# class InvalidData(NetvisorError):
# pass
#
# Path: tests/utils.py
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
which might include code, classes, or functions. Output only the next line. | }, |
Given snippet: <|code_start|> ])
def test_create_with_unknown_fields(self, netvisor, responses, data):
with pytest.raises(ValidationError):
netvisor.customers.create(data)
def test_update(self, netvisor, responses):
responses.add(
method='POST',
url='http://koulutus.netvisor.fi/Customer.nv?method=edit&id=8',
body=get_response_content('CustomerEdit.xml'),
content_type='text/html; charset=utf-8',
match_querystring=True
)
data = {
'customer_base_information': {
'internal_identifier': u'MM',
'external_identifier': u'1967543-8',
'name': u'Matti Meikäläinen',
'name_extension': u'Toimitusjohtaja',
'street_address': u'c/o Yritys Oy',
'additional_address_line': u'Pajukuja 1',
'city': u'Lappeenranta',
'post_number': u'53100',
'country': u'FI',
'customer_group_name': u'Alennusasiakkaat',
'phone_number': u'040 123456',
'fax_number': u'05 123456',
'email': u'matti.meikalainen@firma.fi',
'email_invoicing_address': u'maija.meikalainen@firma.fi',
'home_page_uri': u'www.firma.fi',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import decimal
import pytest
from marshmallow import ValidationError
from netvisor.exc import InvalidData
from ..utils import get_request_content, get_response_content
and context:
# Path: netvisor/exc.py
# class InvalidData(NetvisorError):
# pass
#
# Path: tests/utils.py
# def get_request_content(filename):
# filename = os.path.join(get_requests_dir(), filename)
# return read_file(filename)
#
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
which might include code, classes, or functions. Output only the next line. | 'is_active': True, |
Given snippet: <|code_start|> 'name': u'Matti Meikäläinen',
'name_extension': u'Toimitusjohtaja',
'street_address': u'c/o Yritys Oy',
'additional_address_line': u'Pajukuja 1',
'city': u'Lappeenranta',
'post_number': u'53100',
'country': u'FI',
'customer_group_name': u'Alennusasiakkaat',
'phone_number': u'040 123456',
'fax_number': u'05 123456',
'email': u'matti.meikalainen@firma.fi',
'email_invoicing_address': u'maija.meikalainen@firma.fi',
'home_page_uri': u'www.firma.fi',
'is_active': True,
},
'customer_finvoice_details': {
'finvoice_address': u'FI109700021497',
'finvoice_router_code': 'NDEAFIHH'
},
'customer_delivery_details': {
'delivery_name': u'Maija Mehiläinen',
'delivery_street_address': u'Pajukuja 2',
'delivery_city': u'Lappeenranta',
'delivery_post_number': u'53900',
'delivery_country': u'FI',
},
'customer_contact_details': {
'contact_person': u'Matti Meikäläinen',
'contact_person_email': u'matti.meikalainen@firma.fi',
'contact_person_phone': u'040 987 254',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import decimal
import pytest
from marshmallow import ValidationError
from netvisor.exc import InvalidData
from ..utils import get_request_content, get_response_content
and context:
# Path: netvisor/exc.py
# class InvalidData(NetvisorError):
# pass
#
# Path: tests/utils.py
# def get_request_content(filename):
# filename = os.path.join(get_requests_dir(), filename)
# return read_file(filename)
#
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
which might include code, classes, or functions. Output only the next line. | }, |
Using the snippet: <|code_start|> url='http://koulutus.netvisor.fi/CustomerList.nv',
body=get_response_content('CustomerList.xml'),
content_type='text/html; charset=utf-8',
match_querystring=True
)
customers = netvisor.customers.list()
assert customers == [
{
'netvisor_key': 165,
'name': u'Anni Asiakas',
'code': u'AA',
'organisation_identifier': u'12345678-9',
},
{
'netvisor_key': 166,
'name': u'Matti Mallikas',
'code': None,
'organisation_identifier': None,
}
]
def test_list_with_zero_customers(self, netvisor, responses):
responses.add(
method='GET',
url='http://koulutus.netvisor.fi/CustomerList.nv',
body=get_response_content('CustomerListMinimal.xml'),
content_type='text/html; charset=utf-8',
match_querystring=True
)
customers = netvisor.customers.list()
<|code_end|>
, determine the next line of code. You have imports:
import decimal
import pytest
from marshmallow import ValidationError
from netvisor.exc import InvalidData
from ..utils import get_request_content, get_response_content
and context (class names, function names, or code) available:
# Path: netvisor/exc.py
# class InvalidData(NetvisorError):
# pass
#
# Path: tests/utils.py
# def get_request_content(filename):
# filename = os.path.join(get_requests_dir(), filename)
# return read_file(filename)
#
# def get_response_content(filename):
# filename = os.path.join(get_responses_dir(), filename)
# return read_file(filename)
. Output only the next line. | assert customers == [] |
Based on the snippet: <|code_start|>
BoxSize = 100.
Q = numpy.zeros((100, 3))
@MPITest([1, 4])
def test_create(comm):
matter = Matter(cosmo, BoxSize, Q, comm)
cdm = CDM(cosmo, BoxSize, Q, comm)
cdm.a['S'] = 1.0
cdm.a['P'] = 1.0
baryon = Baryon(cosmo, BoxSize, Q, comm)
baryon.a['S'] = 1.0
baryon.a['P'] = 1.0
state = StateVector(cosmo, {'0': baryon, '1' : cdm}, comm)
state.a['S'] = 1.0
<|code_end|>
, predict the immediate next line with the help of imports:
from fastpm.state import StateVector, Matter, Baryon, CDM, NCDM
from runtests.mpi import MPITest
from nbodykit.cosmology import Planck15 as cosmo
import numpy
and context (classes, functions, sometimes code) from other files:
# Path: fastpm/state.py
# class StateVector(object):
# def __init__(self, cosmology, species, comm):
# """ A state vector is a dict of Species """
# self.cosmology = cosmology
# self.species = OrderedDict(sorted(species.items(), key=lambda t: t[0]))
# self.comm = comm
# self.a = dict(S=None, P=None, F=None)
#
# def __getitem__(self, spname):
# return self.species[spname]
#
# def __iter__(self):
# return iter(self.species)
#
# def __contains__(self, name):
# return name in self.species
#
# def copy(self):
# vc = {}
# for k, v in self.species.items():
# vc[k] = v.copy()
# return StateVector(self.cosmology, vc, self.comm)
#
# def to_catalog(self, **kwargs):
# from nbodykit.lab import MultipleSpeciesCatalog
# names = []
# sources = []
#
# for spname, sp in self.species.items():
# sources.append(sp.to_catalog())
# names.append(spname)
#
# cat = MultipleSpeciesCatalog(names, *sources, **kwargs)
# return cat
#
# def save(self, filename, attrs={}):
# from bigfile import FileMPI
# a = self.a['S']
# with FileMPI(self.comm, filename, create=True) as ff:
# with ff.create('Header') as bb:
# keylist = ['Om0', 'Tcmb0', 'Neff', 'Ob0', 'Ode0']
# if getattr(self.cosmology, 'm_nu', None) is not None:
# keylist.insert(3,'m_nu')
# for key in keylist:
# bb.attrs[key] = getattr(self.cosmology, key)
# bb.attrs['Time'] = a
# bb.attrs['h'] = self.cosmology.H0 / H0 # relative h
# bb.attrs['RSDFactor'] = 1.0 / (H0 * a * self.cosmology.efunc(1.0 / a - 1))
# for key in attrs:
# try:
# #best effort
# bb.attrs[key] = attrs[key]
# except:
# pass
#
# for k, v in sorted(self.species.items()):
# v.save(filename, k)
#
# class Matter(Species):
# def Omega(self, a):
# return self.cosmology.Om(z=1. / a - 1)
#
# class Baryon(Species):
# def Omega(self, a):
# return self.cosmology.Ob(z=1. / a - 1)
#
# class CDM(Species):
# def Omega(self, a):
# return self.cosmology.Odm(z=1. / a - 1)
#
# class NCDM(Species):
# def Omega(self, a):
# # FIXME: using Omega_ncdm after switching to new nbodykit cosmology.
# return self.cosmology.Onu(z=1. / a - 1)
. Output only the next line. | state.a['P'] = 1.0 |
Given the code snippet: <|code_start|>
BoxSize = 100.
Q = numpy.zeros((100, 3))
@MPITest([1, 4])
def test_create(comm):
matter = Matter(cosmo, BoxSize, Q, comm)
cdm = CDM(cosmo, BoxSize, Q, comm)
cdm.a['S'] = 1.0
cdm.a['P'] = 1.0
baryon = Baryon(cosmo, BoxSize, Q, comm)
baryon.a['S'] = 1.0
<|code_end|>
, generate the next line using the imports in this file:
from fastpm.state import StateVector, Matter, Baryon, CDM, NCDM
from runtests.mpi import MPITest
from nbodykit.cosmology import Planck15 as cosmo
import numpy
and context (functions, classes, or occasionally code) from other files:
# Path: fastpm/state.py
# class StateVector(object):
# def __init__(self, cosmology, species, comm):
# """ A state vector is a dict of Species """
# self.cosmology = cosmology
# self.species = OrderedDict(sorted(species.items(), key=lambda t: t[0]))
# self.comm = comm
# self.a = dict(S=None, P=None, F=None)
#
# def __getitem__(self, spname):
# return self.species[spname]
#
# def __iter__(self):
# return iter(self.species)
#
# def __contains__(self, name):
# return name in self.species
#
# def copy(self):
# vc = {}
# for k, v in self.species.items():
# vc[k] = v.copy()
# return StateVector(self.cosmology, vc, self.comm)
#
# def to_catalog(self, **kwargs):
# from nbodykit.lab import MultipleSpeciesCatalog
# names = []
# sources = []
#
# for spname, sp in self.species.items():
# sources.append(sp.to_catalog())
# names.append(spname)
#
# cat = MultipleSpeciesCatalog(names, *sources, **kwargs)
# return cat
#
# def save(self, filename, attrs={}):
# from bigfile import FileMPI
# a = self.a['S']
# with FileMPI(self.comm, filename, create=True) as ff:
# with ff.create('Header') as bb:
# keylist = ['Om0', 'Tcmb0', 'Neff', 'Ob0', 'Ode0']
# if getattr(self.cosmology, 'm_nu', None) is not None:
# keylist.insert(3,'m_nu')
# for key in keylist:
# bb.attrs[key] = getattr(self.cosmology, key)
# bb.attrs['Time'] = a
# bb.attrs['h'] = self.cosmology.H0 / H0 # relative h
# bb.attrs['RSDFactor'] = 1.0 / (H0 * a * self.cosmology.efunc(1.0 / a - 1))
# for key in attrs:
# try:
# #best effort
# bb.attrs[key] = attrs[key]
# except:
# pass
#
# for k, v in sorted(self.species.items()):
# v.save(filename, k)
#
# class Matter(Species):
# def Omega(self, a):
# return self.cosmology.Om(z=1. / a - 1)
#
# class Baryon(Species):
# def Omega(self, a):
# return self.cosmology.Ob(z=1. / a - 1)
#
# class CDM(Species):
# def Omega(self, a):
# return self.cosmology.Odm(z=1. / a - 1)
#
# class NCDM(Species):
# def Omega(self, a):
# # FIXME: using Omega_ncdm after switching to new nbodykit cosmology.
# return self.cosmology.Onu(z=1. / a - 1)
. Output only the next line. | baryon.a['P'] = 1.0 |
Using the snippet: <|code_start|>
BoxSize = 100.
Q = numpy.zeros((100, 3))
@MPITest([1, 4])
<|code_end|>
, determine the next line of code. You have imports:
from fastpm.state import StateVector, Matter, Baryon, CDM, NCDM
from runtests.mpi import MPITest
from nbodykit.cosmology import Planck15 as cosmo
import numpy
and context (class names, function names, or code) available:
# Path: fastpm/state.py
# class StateVector(object):
# def __init__(self, cosmology, species, comm):
# """ A state vector is a dict of Species """
# self.cosmology = cosmology
# self.species = OrderedDict(sorted(species.items(), key=lambda t: t[0]))
# self.comm = comm
# self.a = dict(S=None, P=None, F=None)
#
# def __getitem__(self, spname):
# return self.species[spname]
#
# def __iter__(self):
# return iter(self.species)
#
# def __contains__(self, name):
# return name in self.species
#
# def copy(self):
# vc = {}
# for k, v in self.species.items():
# vc[k] = v.copy()
# return StateVector(self.cosmology, vc, self.comm)
#
# def to_catalog(self, **kwargs):
# from nbodykit.lab import MultipleSpeciesCatalog
# names = []
# sources = []
#
# for spname, sp in self.species.items():
# sources.append(sp.to_catalog())
# names.append(spname)
#
# cat = MultipleSpeciesCatalog(names, *sources, **kwargs)
# return cat
#
# def save(self, filename, attrs={}):
# from bigfile import FileMPI
# a = self.a['S']
# with FileMPI(self.comm, filename, create=True) as ff:
# with ff.create('Header') as bb:
# keylist = ['Om0', 'Tcmb0', 'Neff', 'Ob0', 'Ode0']
# if getattr(self.cosmology, 'm_nu', None) is not None:
# keylist.insert(3,'m_nu')
# for key in keylist:
# bb.attrs[key] = getattr(self.cosmology, key)
# bb.attrs['Time'] = a
# bb.attrs['h'] = self.cosmology.H0 / H0 # relative h
# bb.attrs['RSDFactor'] = 1.0 / (H0 * a * self.cosmology.efunc(1.0 / a - 1))
# for key in attrs:
# try:
# #best effort
# bb.attrs[key] = attrs[key]
# except:
# pass
#
# for k, v in sorted(self.species.items()):
# v.save(filename, k)
#
# class Matter(Species):
# def Omega(self, a):
# return self.cosmology.Om(z=1. / a - 1)
#
# class Baryon(Species):
# def Omega(self, a):
# return self.cosmology.Ob(z=1. / a - 1)
#
# class CDM(Species):
# def Omega(self, a):
# return self.cosmology.Odm(z=1. / a - 1)
#
# class NCDM(Species):
# def Omega(self, a):
# # FIXME: using Omega_ncdm after switching to new nbodykit cosmology.
# return self.cosmology.Onu(z=1. / a - 1)
. Output only the next line. | def test_create(comm): |
Next line prediction: <|code_start|>solver_ncdm = SolverNCDM(pm, Planck15, B=2)
wn = solver.whitenoise(400)
dlin = solver.linear(wn, EHPower(Planck15, 0))
lpt = solver.lpt(dlin, Q, stages[0])
#lpt.S = numpy.float32(lpt.S)
def monitor(action, ai, ac, af, state, event):
if pm.comm.rank == 0:
print(state.a['S'], state.a['P'], state.a['F'], state.S[0], state.P[0], action, ai, ac, af)
state1 = solver.nbody(lpt.copy(), leapfrog(stages), monitor=monitor)
state2 = solver_ncdm.nbody(lpt.copy(), leapfrog(stages), monitor=monitor)
if pm.comm.rank == 0:
print('----------------')
cat1 = ArrayCatalog({'Position' : state1.X}, BoxSize=pm.BoxSize, Nmesh=pm.Nmesh)
cat2 = ArrayCatalog({'Position' : state2.X}, BoxSize=pm.BoxSize, Nmesh=pm.Nmesh)
r1 = FFTPower(cat1, mode='1d')
r2 = FFTPower(cat2, mode='1d')
cat1.save('NCDM/core', ('Position',))
cat2.save('NCDM/ncdm', ('Position',))
r1.save('NCDM/core-power.json')
r2.save('NCDM/ncdm-power.json')
if pm.comm.rank == 0:
<|code_end|>
. Use current file imports:
(from numpy.testing import assert_allclose
from fastpm.ncdm import Solver as SolverNCDM
from fastpm.core import Solver as Solver
from fastpm.core import leapfrog
from nbodykit.cosmology import Planck15, EHPower
from nbodykit.algorithms.fof import FOF
from nbodykit.algorithms.fftpower import FFTPower
from nbodykit.source import ArrayCatalog
from pmesh.pm import ParticleMesh
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
import numpy)
and context including class names, function names, or small code snippets from other files:
# Path: fastpm/ncdm.py
# class Solver(core.Solver):
# @property
# def nbodystep(self):
# return FastPMStep(self)
#
# Path: fastpm/core.py
# class Solver(object):
# def __init__(self, pm, cosmology, B=1, a_linear=1.0):
# """
# a_linear : float
# scaling factor at the time of the linear field.
# The growth function will be calibrated such that at a_linear D1 == 0.
#
# """
# if not isinstance(cosmology, Cosmology):
# raise TypeError("only nbodykit.cosmology object is supported")
#
# fpm = ParticleMesh(Nmesh=pm.Nmesh * B, BoxSize=pm.BoxSize, dtype=pm.dtype, comm=pm.comm, resampler=pm.resampler)
# self.pm = pm
# self.fpm = fpm
# self.cosmology = cosmology
# self.a_linear = a_linear
#
# # override nbodystep in subclasses
# @property
# def nbodystep(self):
# return FastPMStep(self)
#
# def whitenoise(self, seed, unitary=False):
# return self.pm.generate_whitenoise(seed, type='complex', unitary=unitary)
#
# def linear(self, whitenoise, Pk):
# return whitenoise.apply(lambda k, v:
# Pk(sum(ki ** 2 for ki in k)**0.5) ** 0.5 * v / v.BoxSize.prod() ** 0.5)
#
# def lpt(self, linear, Q, a, order=2):
# """ This computes the 'force' from LPT as well. """
# assert order in (1, 2)
#
# from .force.lpt import lpt1, lpt2source
#
# state = StateVector(self, Q)
# pt = MatterDominated(self.cosmology.Om0, a=[a], a_normalize=self.a_linear)
# DX1 = pt.D1(a) * lpt1(linear, Q)
#
# V1 = a ** 2 * pt.f1(a) * pt.E(a) * DX1
# if order == 2:
# DX2 = pt.D2(a) * lpt1(lpt2source(linear), Q)
# V2 = a ** 2 * pt.f2(a) * pt.E(a) * DX2
# state.S[...] = DX1 + DX2
# state.P[...] = V1 + V2
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1 + pt.gf2(a) / pt.D2(a) * DX2)
# else:
# state.S[...] = DX1
# state.P[...] = V1
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1)
#
# state.a['S'] = a
# state.a['P'] = a
#
# return state
#
# def nbody(self, state, stepping, monitor=None):
# step = self.nbodystep
# for action, ai, ac, af in stepping:
# step.run(action, ai, ac, af, state, monitor)
#
# return state
#
# Path: fastpm/core.py
# def leapfrog(stages):
# """ Generate a leap frog stepping scheme.
#
# Parameters
# ----------
# stages : array_like
# Time (a) where force computing stage is requested.
# """
# if len(stages) == 0:
# return
#
# ai = stages[0]
# # first force calculation for jump starting
# yield 'F', ai, ai, ai
# x, p, f = ai, ai, ai
#
# for i in range(len(stages) - 1):
# a0 = stages[i]
# a1 = stages[i + 1]
# ah = (a0 * a1) ** 0.5
# yield 'K', p, f, ah
# p = ah
# yield 'D', x, p, a1
# x = a1
# yield 'F', f, x, a1
# f = a1
# yield 'K', p, f, a1
# p = a1
. Output only the next line. | fig = Figure() |
Based on the snippet: <|code_start|>
stages = numpy.linspace(0.1, 1.0, 20, endpoint=True)
solver = Solver(pm, Planck15, B=2)
solver_ncdm = SolverNCDM(pm, Planck15, B=2)
wn = solver.whitenoise(400)
dlin = solver.linear(wn, EHPower(Planck15, 0))
lpt = solver.lpt(dlin, Q, stages[0])
#lpt.S = numpy.float32(lpt.S)
def monitor(action, ai, ac, af, state, event):
if pm.comm.rank == 0:
print(state.a['S'], state.a['P'], state.a['F'], state.S[0], state.P[0], action, ai, ac, af)
state1 = solver.nbody(lpt.copy(), leapfrog(stages), monitor=monitor)
state2 = solver_ncdm.nbody(lpt.copy(), leapfrog(stages), monitor=monitor)
if pm.comm.rank == 0:
print('----------------')
cat1 = ArrayCatalog({'Position' : state1.X}, BoxSize=pm.BoxSize, Nmesh=pm.Nmesh)
cat2 = ArrayCatalog({'Position' : state2.X}, BoxSize=pm.BoxSize, Nmesh=pm.Nmesh)
r1 = FFTPower(cat1, mode='1d')
r2 = FFTPower(cat2, mode='1d')
cat1.save('NCDM/core', ('Position',))
cat2.save('NCDM/ncdm', ('Position',))
r1.save('NCDM/core-power.json')
<|code_end|>
, predict the immediate next line with the help of imports:
from numpy.testing import assert_allclose
from fastpm.ncdm import Solver as SolverNCDM
from fastpm.core import Solver as Solver
from fastpm.core import leapfrog
from nbodykit.cosmology import Planck15, EHPower
from nbodykit.algorithms.fof import FOF
from nbodykit.algorithms.fftpower import FFTPower
from nbodykit.source import ArrayCatalog
from pmesh.pm import ParticleMesh
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
import numpy
and context (classes, functions, sometimes code) from other files:
# Path: fastpm/ncdm.py
# class Solver(core.Solver):
# @property
# def nbodystep(self):
# return FastPMStep(self)
#
# Path: fastpm/core.py
# class Solver(object):
# def __init__(self, pm, cosmology, B=1, a_linear=1.0):
# """
# a_linear : float
# scaling factor at the time of the linear field.
# The growth function will be calibrated such that at a_linear D1 == 0.
#
# """
# if not isinstance(cosmology, Cosmology):
# raise TypeError("only nbodykit.cosmology object is supported")
#
# fpm = ParticleMesh(Nmesh=pm.Nmesh * B, BoxSize=pm.BoxSize, dtype=pm.dtype, comm=pm.comm, resampler=pm.resampler)
# self.pm = pm
# self.fpm = fpm
# self.cosmology = cosmology
# self.a_linear = a_linear
#
# # override nbodystep in subclasses
# @property
# def nbodystep(self):
# return FastPMStep(self)
#
# def whitenoise(self, seed, unitary=False):
# return self.pm.generate_whitenoise(seed, type='complex', unitary=unitary)
#
# def linear(self, whitenoise, Pk):
# return whitenoise.apply(lambda k, v:
# Pk(sum(ki ** 2 for ki in k)**0.5) ** 0.5 * v / v.BoxSize.prod() ** 0.5)
#
# def lpt(self, linear, Q, a, order=2):
# """ This computes the 'force' from LPT as well. """
# assert order in (1, 2)
#
# from .force.lpt import lpt1, lpt2source
#
# state = StateVector(self, Q)
# pt = MatterDominated(self.cosmology.Om0, a=[a], a_normalize=self.a_linear)
# DX1 = pt.D1(a) * lpt1(linear, Q)
#
# V1 = a ** 2 * pt.f1(a) * pt.E(a) * DX1
# if order == 2:
# DX2 = pt.D2(a) * lpt1(lpt2source(linear), Q)
# V2 = a ** 2 * pt.f2(a) * pt.E(a) * DX2
# state.S[...] = DX1 + DX2
# state.P[...] = V1 + V2
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1 + pt.gf2(a) / pt.D2(a) * DX2)
# else:
# state.S[...] = DX1
# state.P[...] = V1
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1)
#
# state.a['S'] = a
# state.a['P'] = a
#
# return state
#
# def nbody(self, state, stepping, monitor=None):
# step = self.nbodystep
# for action, ai, ac, af in stepping:
# step.run(action, ai, ac, af, state, monitor)
#
# return state
#
# Path: fastpm/core.py
# def leapfrog(stages):
# """ Generate a leap frog stepping scheme.
#
# Parameters
# ----------
# stages : array_like
# Time (a) where force computing stage is requested.
# """
# if len(stages) == 0:
# return
#
# ai = stages[0]
# # first force calculation for jump starting
# yield 'F', ai, ai, ai
# x, p, f = ai, ai, ai
#
# for i in range(len(stages) - 1):
# a0 = stages[i]
# a1 = stages[i + 1]
# ah = (a0 * a1) ** 0.5
# yield 'K', p, f, ah
# p = ah
# yield 'D', x, p, a1
# x = a1
# yield 'F', f, x, a1
# f = a1
# yield 'K', p, f, a1
# p = a1
. Output only the next line. | r2.save('NCDM/ncdm-power.json') |
Given snippet: <|code_start|>
class Step(object):
pass
class Solver(object):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy
from pmesh.pm import ParticleMesh
from .background import PerturbationGrowth
from nbodykit.cosmology import Cosmology
from .state import StateVector, Matter, Baryon, CDM, NCDM
from .force.lpt import lpt1, lpt2source
from .force.gravity import longrange_batch
and context:
# Path: fastpm/background.py
# class Perturbation:
# class MatterDominated(Perturbation):
# class RadiationDominated(Perturbation):
# def __init__(self, a, a_normalize=1.0):
# def D1(self, a, order=0):
# def D2(self, a, order=0):
# def f1(self, a):
# def f2(self, a):
# def Gp(self, a):
# def Gp2(self, a):
# def gp(self, a):
# def gp2(self, a):
# def Gf(self, a):
# def Gf2(self, a):
# def gf(self, a):
# def gf2(self, a):
# def E(self, a, order=0):
# def Hfac(self, a):
# def ode(self, y, lna):
# def _solve(self, y0, a_normalize):
# def __init__(self, Omega0_m, Omega0_lambda=None, Omega0_k=0, a=None, a_normalize=1.0):
# def get_initial_condition(self):
# def efunc(self, a):
# def efunc_prime(self, a):
# def Om(self, a):
# def __init__(self, cosmo, a=None, a_normalize=1.0):
# def get_initial_condition(self):
# def efunc(self, a):
# def efunc_prime(self, a):
# def Om(self, a):
# D1, F1, D2, F2 = y
# D1, F1, D2, F2 = yi
#
# Path: fastpm/state.py
# class StateVector(object):
# def __init__(self, cosmology, species, comm):
# """ A state vector is a dict of Species """
# self.cosmology = cosmology
# self.species = OrderedDict(sorted(species.items(), key=lambda t: t[0]))
# self.comm = comm
# self.a = dict(S=None, P=None, F=None)
#
# def __getitem__(self, spname):
# return self.species[spname]
#
# def __iter__(self):
# return iter(self.species)
#
# def __contains__(self, name):
# return name in self.species
#
# def copy(self):
# vc = {}
# for k, v in self.species.items():
# vc[k] = v.copy()
# return StateVector(self.cosmology, vc, self.comm)
#
# def to_catalog(self, **kwargs):
# from nbodykit.lab import MultipleSpeciesCatalog
# names = []
# sources = []
#
# for spname, sp in self.species.items():
# sources.append(sp.to_catalog())
# names.append(spname)
#
# cat = MultipleSpeciesCatalog(names, *sources, **kwargs)
# return cat
#
# def save(self, filename, attrs={}):
# from bigfile import FileMPI
# a = self.a['S']
# with FileMPI(self.comm, filename, create=True) as ff:
# with ff.create('Header') as bb:
# keylist = ['Om0', 'Tcmb0', 'Neff', 'Ob0', 'Ode0']
# if getattr(self.cosmology, 'm_nu', None) is not None:
# keylist.insert(3,'m_nu')
# for key in keylist:
# bb.attrs[key] = getattr(self.cosmology, key)
# bb.attrs['Time'] = a
# bb.attrs['h'] = self.cosmology.H0 / H0 # relative h
# bb.attrs['RSDFactor'] = 1.0 / (H0 * a * self.cosmology.efunc(1.0 / a - 1))
# for key in attrs:
# try:
# #best effort
# bb.attrs[key] = attrs[key]
# except:
# pass
#
# for k, v in sorted(self.species.items()):
# v.save(filename, k)
#
# class Matter(Species):
# def Omega(self, a):
# return self.cosmology.Om(z=1. / a - 1)
#
# class Baryon(Species):
# def Omega(self, a):
# return self.cosmology.Ob(z=1. / a - 1)
#
# class CDM(Species):
# def Omega(self, a):
# return self.cosmology.Odm(z=1. / a - 1)
#
# class NCDM(Species):
# def Omega(self, a):
# # FIXME: using Omega_ncdm after switching to new nbodykit cosmology.
# return self.cosmology.Onu(z=1. / a - 1)
which might include code, classes, or functions. Output only the next line. | def __init__(self, pm, cosmology, B=1): |
Predict the next line after this snippet: <|code_start|>
pm = ParticleMesh(BoxSize=32., Nmesh=[16, 16, 16])
def test_solver():
Plin = LinearPower(Planck15, redshift=0, transfer='EisensteinHu')
solver = Solver(pm, Planck15, B=2)
Q = pm.generate_uniform_particle_grid(shift=0)
wn = solver.whitenoise(1234)
dlin = solver.linear(wn, lambda k: Plin(k))
<|code_end|>
using the current file's imports:
from fastpm.core import leapfrog, autostages
from fastpm.hold import Solver
from pmesh.pm import ParticleMesh
from nbodykit.cosmology import Planck15, LinearPower
import numpy
and any relevant context from other files:
# Path: fastpm/core.py
# def leapfrog(stages):
# """ Generate a leap frog stepping scheme.
#
# Parameters
# ----------
# stages : array_like
# Time (a) where force computing stage is requested.
# """
# if len(stages) == 0:
# return
#
# ai = stages[0]
# # first force calculation for jump starting
# yield 'F', ai, ai, ai
# x, p, f = ai, ai, ai
#
# for i in range(len(stages) - 1):
# a0 = stages[i]
# a1 = stages[i + 1]
# ah = (a0 * a1) ** 0.5
# yield 'K', p, f, ah
# p = ah
# yield 'D', x, p, a1
# x = a1
# yield 'F', f, x, a1
# f = a1
# yield 'K', p, f, a1
# p = a1
#
# def autostages(knots, N, astart=None, N0=None):
# """ Generate an optimized list of N stages that includes time steps at the knots.
#
# Parameters
# ----------
# astart : float, or None
# starting time, default is knots[0]
# N : int
# total number of stages
# N0 : int or None
# at least add this many stages before the earlist knot, default None;
# useful only if astart != min(knots), and len(knots) > 1
# knots : list
# stages that must exist
#
#
# >>> autostages(0.1, N=11, knots=[0.1, 0.2, 0.5, 1.0])
#
# """
#
# knots = numpy.array(knots)
# knots.sort()
#
# stages = numpy.array([], dtype='f8')
# if astart is not None and astart != knots.min():
# assert astart < knots.min()
# if N0 is None: N0 = 1
# knots = numpy.append([astart], knots)
# else:
# N0 = 1
#
# for i in range(0, len(knots) - 1):
# da = (knots[-1] - knots[i]) / (N - len(stages) - 1)
#
# N_this_span = int((knots[i + 1] - knots[i]) / da + 0.5)
# if i == 0 and N_this_span < N0:
# N_this_span = N0
#
# add = numpy.linspace(knots[i], knots[i + 1], N_this_span, endpoint=False)
#
# #print('i = =====', i)
# #print('knots[i]', knots[i], da, N_this_span, stages, add)
#
# stages = numpy.append(stages, add)
#
# stages = numpy.append(stages, [knots[-1]])
#
# return stages
#
# Path: fastpm/hold.py
# class Solver(core.Solver):
# def __init__(self, pm, cosmology, B=1, r_split=None, NTimeBin=4):
# core.Solver.__init__(self, pm, cosmology, B)
#
# if r_split is None:
# r_split = self.fpm.BoxSize[0] / self.fpm.Nmesh[0]
#
# self.r_split = r_split
# self.r_cut = r_split * 4.5
# self.r_smth = r_split / 32
# self.NTimeBin = NTimeBin
#
# @property
# def nbodystep(self):
# return PPPMStep(self)
#
# def compute_shortrange(self, tree1, tree2, factor, out=None):
# from .force.gravity import shortrange
# return shortrange(tree1, tree2,
# self.r_split, self.r_cut, self.r_smth,
# factor=factor, out=out)
#
# def compute_longrange(self, X1, delta_k, factor):
# from .force.gravity import longrange
# return longrange(X1, delta_k, split=self.r_split, factor=factor)
#
# def compute_stepsize(self, tree, P, ac, E, Eprime, factor, out=None):
# from .force.gravity import compute_stepsize
# return compute_stepsize(
# tree,
# P, ac, E, Eprime,
# self.r_cut, self.r_smth,
# factor=factor, out=out)
. Output only the next line. | state = solver.lpt(dlin, Q, a=0.3, order=2) |
Using the snippet: <|code_start|>stages = numpy.linspace(0.1, 1.0, 10, endpoint=True)
solver = Solver(pm, Planck15, B=2)
wn = solver.whitenoise(400)
dlin = solver.linear(wn, EHPower(Planck15, 0))
state = solver.lpt(dlin, Q, stages[0])
X = numpy.fromfile('pos')
V = numpy.fromfile('vel')
Q = X - V* aafqwe
start = pm.comm.rank * len(X) // pm.comm.size
end = (pm.comm.rank + 1)* len(X) // pm.comm.size
state = StateVector(Q[start:end])
state.S[...] = X[start:end] - Q[start:end]
state.P[...] = a ** h * V[start:end]
X = []
def monitor(action, ai, ac, af, state, event):
if not state.synchronized: return
X.append((state.a['S'], state.X.copy(), state.P.copy()))
state = solver.nbody(state, leapfrog(stages), monitor=monitor)
cat = ArrayCatalog({'Position' : X[-1][1]}, BoxSize=pm.BoxSize, Nmesh=pm.Nmesh)
<|code_end|>
, determine the next line of code. You have imports:
from fastpm.core import Solver, leapfrog
from nbodykit.cosmology import Planck15, EHPower
from nbodykit.algorithms.fof import FOF
from nbodykit.source import ArrayCatalog
from pmesh.pm import ParticleMesh
import numpy
and context (class names, function names, or code) available:
# Path: fastpm/core.py
# class Solver(object):
# def __init__(self, pm, cosmology, B=1, a_linear=1.0):
# """
# a_linear : float
# scaling factor at the time of the linear field.
# The growth function will be calibrated such that at a_linear D1 == 0.
#
# """
# if not isinstance(cosmology, Cosmology):
# raise TypeError("only nbodykit.cosmology object is supported")
#
# fpm = ParticleMesh(Nmesh=pm.Nmesh * B, BoxSize=pm.BoxSize, dtype=pm.dtype, comm=pm.comm, resampler=pm.resampler)
# self.pm = pm
# self.fpm = fpm
# self.cosmology = cosmology
# self.a_linear = a_linear
#
# # override nbodystep in subclasses
# @property
# def nbodystep(self):
# return FastPMStep(self)
#
# def whitenoise(self, seed, unitary=False):
# return self.pm.generate_whitenoise(seed, type='complex', unitary=unitary)
#
# def linear(self, whitenoise, Pk):
# return whitenoise.apply(lambda k, v:
# Pk(sum(ki ** 2 for ki in k)**0.5) ** 0.5 * v / v.BoxSize.prod() ** 0.5)
#
# def lpt(self, linear, Q, a, order=2):
# """ This computes the 'force' from LPT as well. """
# assert order in (1, 2)
#
# from .force.lpt import lpt1, lpt2source
#
# state = StateVector(self, Q)
# pt = MatterDominated(self.cosmology.Om0, a=[a], a_normalize=self.a_linear)
# DX1 = pt.D1(a) * lpt1(linear, Q)
#
# V1 = a ** 2 * pt.f1(a) * pt.E(a) * DX1
# if order == 2:
# DX2 = pt.D2(a) * lpt1(lpt2source(linear), Q)
# V2 = a ** 2 * pt.f2(a) * pt.E(a) * DX2
# state.S[...] = DX1 + DX2
# state.P[...] = V1 + V2
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1 + pt.gf2(a) / pt.D2(a) * DX2)
# else:
# state.S[...] = DX1
# state.P[...] = V1
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1)
#
# state.a['S'] = a
# state.a['P'] = a
#
# return state
#
# def nbody(self, state, stepping, monitor=None):
# step = self.nbodystep
# for action, ai, ac, af in stepping:
# step.run(action, ai, ac, af, state, monitor)
#
# return state
#
# def leapfrog(stages):
# """ Generate a leap frog stepping scheme.
#
# Parameters
# ----------
# stages : array_like
# Time (a) where force computing stage is requested.
# """
# if len(stages) == 0:
# return
#
# ai = stages[0]
# # first force calculation for jump starting
# yield 'F', ai, ai, ai
# x, p, f = ai, ai, ai
#
# for i in range(len(stages) - 1):
# a0 = stages[i]
# a1 = stages[i + 1]
# ah = (a0 * a1) ** 0.5
# yield 'K', p, f, ah
# p = ah
# yield 'D', x, p, a1
# x = a1
# yield 'F', f, x, a1
# f = a1
# yield 'K', p, f, a1
# p = a1
. Output only the next line. | fof = FOF(cat, linking_length=0.2, nmin=12) |
Predict the next line after this snippet: <|code_start|>
pm = ParticleMesh(BoxSize=128, Nmesh=[128, 128, 128])
Q = pm.generate_uniform_particle_grid()
stages = numpy.linspace(0.1, 1.0, 10, endpoint=True)
solver = Solver(pm, Planck15, B=2)
wn = solver.whitenoise(400)
dlin = solver.linear(wn, EHPower(Planck15, 0))
state = solver.lpt(dlin, Q, stages[0])
X = numpy.fromfile('pos')
V = numpy.fromfile('vel')
Q = X - V* aafqwe
start = pm.comm.rank * len(X) // pm.comm.size
end = (pm.comm.rank + 1)* len(X) // pm.comm.size
state = StateVector(Q[start:end])
state.S[...] = X[start:end] - Q[start:end]
state.P[...] = a ** h * V[start:end]
<|code_end|>
using the current file's imports:
from fastpm.core import Solver, leapfrog
from nbodykit.cosmology import Planck15, EHPower
from nbodykit.algorithms.fof import FOF
from nbodykit.source import ArrayCatalog
from pmesh.pm import ParticleMesh
import numpy
and any relevant context from other files:
# Path: fastpm/core.py
# class Solver(object):
# def __init__(self, pm, cosmology, B=1, a_linear=1.0):
# """
# a_linear : float
# scaling factor at the time of the linear field.
# The growth function will be calibrated such that at a_linear D1 == 0.
#
# """
# if not isinstance(cosmology, Cosmology):
# raise TypeError("only nbodykit.cosmology object is supported")
#
# fpm = ParticleMesh(Nmesh=pm.Nmesh * B, BoxSize=pm.BoxSize, dtype=pm.dtype, comm=pm.comm, resampler=pm.resampler)
# self.pm = pm
# self.fpm = fpm
# self.cosmology = cosmology
# self.a_linear = a_linear
#
# # override nbodystep in subclasses
# @property
# def nbodystep(self):
# return FastPMStep(self)
#
# def whitenoise(self, seed, unitary=False):
# return self.pm.generate_whitenoise(seed, type='complex', unitary=unitary)
#
# def linear(self, whitenoise, Pk):
# return whitenoise.apply(lambda k, v:
# Pk(sum(ki ** 2 for ki in k)**0.5) ** 0.5 * v / v.BoxSize.prod() ** 0.5)
#
# def lpt(self, linear, Q, a, order=2):
# """ This computes the 'force' from LPT as well. """
# assert order in (1, 2)
#
# from .force.lpt import lpt1, lpt2source
#
# state = StateVector(self, Q)
# pt = MatterDominated(self.cosmology.Om0, a=[a], a_normalize=self.a_linear)
# DX1 = pt.D1(a) * lpt1(linear, Q)
#
# V1 = a ** 2 * pt.f1(a) * pt.E(a) * DX1
# if order == 2:
# DX2 = pt.D2(a) * lpt1(lpt2source(linear), Q)
# V2 = a ** 2 * pt.f2(a) * pt.E(a) * DX2
# state.S[...] = DX1 + DX2
# state.P[...] = V1 + V2
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1 + pt.gf2(a) / pt.D2(a) * DX2)
# else:
# state.S[...] = DX1
# state.P[...] = V1
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1)
#
# state.a['S'] = a
# state.a['P'] = a
#
# return state
#
# def nbody(self, state, stepping, monitor=None):
# step = self.nbodystep
# for action, ai, ac, af in stepping:
# step.run(action, ai, ac, af, state, monitor)
#
# return state
#
# def leapfrog(stages):
# """ Generate a leap frog stepping scheme.
#
# Parameters
# ----------
# stages : array_like
# Time (a) where force computing stage is requested.
# """
# if len(stages) == 0:
# return
#
# ai = stages[0]
# # first force calculation for jump starting
# yield 'F', ai, ai, ai
# x, p, f = ai, ai, ai
#
# for i in range(len(stages) - 1):
# a0 = stages[i]
# a1 = stages[i + 1]
# ah = (a0 * a1) ** 0.5
# yield 'K', p, f, ah
# p = ah
# yield 'D', x, p, a1
# x = a1
# yield 'F', f, x, a1
# f = a1
# yield 'K', p, f, a1
# p = a1
. Output only the next line. | X = [] |
Given the code snippet: <|code_start|>
@MPITest([1, 4])
def test_ncdm(comm):
pm = ParticleMesh(BoxSize=512., Nmesh=[8, 8, 8], comm=comm)
<|code_end|>
, generate the next line using the imports in this file:
from runtests.mpi import MPITest
from fastpm.core import leapfrog, autostages
from fastpm.background import PerturbationGrowth
from pmesh.pm import ParticleMesh
from nbodykit.cosmology import Planck15, LinearPower
from numpy.testing import assert_allclose
from fastpm.ncdm import Solver
import numpy
and context (functions, classes, or occasionally code) from other files:
# Path: fastpm/core.py
# def leapfrog(stages):
# """ Generate a leap frog stepping scheme.
#
# Parameters
# ----------
# stages : array_like
# Time (a) where force computing stage is requested.
# """
# if len(stages) == 0:
# return
#
# ai = stages[0]
# # first force calculation for jump starting
# yield 'F', ai, ai, ai
# x, p, f = ai, ai, ai
#
# for i in range(len(stages) - 1):
# a0 = stages[i]
# a1 = stages[i + 1]
# ah = (a0 * a1) ** 0.5
# yield 'K', p, f, ah
# p = ah
# yield 'D', x, p, a1
# x = a1
# yield 'F', f, x, a1
# f = a1
# yield 'K', p, f, a1
# p = a1
#
# def autostages(knots, N, astart=None, N0=None):
# """ Generate an optimized list of N stages that includes time steps at the knots.
#
# Parameters
# ----------
# astart : float, or None
# starting time, default is knots[0]
# N : int
# total number of stages
# N0 : int or None
# at least add this many stages before the earlist knot, default None;
# useful only if astart != min(knots), and len(knots) > 1
# knots : list
# stages that must exist
#
#
# >>> autostages(0.1, N=11, knots=[0.1, 0.2, 0.5, 1.0])
#
# """
#
# knots = numpy.array(knots)
# knots.sort()
#
# stages = numpy.array([], dtype='f8')
# if astart is not None and astart != knots.min():
# assert astart < knots.min()
# if N0 is None: N0 = 1
# knots = numpy.append([astart], knots)
# else:
# N0 = 1
#
# for i in range(0, len(knots) - 1):
# da = (knots[-1] - knots[i]) / (N - len(stages) - 1)
#
# N_this_span = int((knots[i + 1] - knots[i]) / da + 0.5)
# if i == 0 and N_this_span < N0:
# N_this_span = N0
#
# add = numpy.linspace(knots[i], knots[i + 1], N_this_span, endpoint=False)
#
# #print('i = =====', i)
# #print('knots[i]', knots[i], da, N_this_span, stages, add)
#
# stages = numpy.append(stages, add)
#
# stages = numpy.append(stages, [knots[-1]])
#
# return stages
#
# Path: fastpm/background.py
# class Perturbation:
# class MatterDominated(Perturbation):
# class RadiationDominated(Perturbation):
# def __init__(self, a, a_normalize=1.0):
# def D1(self, a, order=0):
# def D2(self, a, order=0):
# def f1(self, a):
# def f2(self, a):
# def Gp(self, a):
# def Gp2(self, a):
# def gp(self, a):
# def gp2(self, a):
# def Gf(self, a):
# def Gf2(self, a):
# def gf(self, a):
# def gf2(self, a):
# def E(self, a, order=0):
# def Hfac(self, a):
# def ode(self, y, lna):
# def _solve(self, y0, a_normalize):
# def __init__(self, Omega0_m, Omega0_lambda=None, Omega0_k=0, a=None, a_normalize=1.0):
# def get_initial_condition(self):
# def efunc(self, a):
# def efunc_prime(self, a):
# def Om(self, a):
# def __init__(self, cosmo, a=None, a_normalize=1.0):
# def get_initial_condition(self):
# def efunc(self, a):
# def efunc_prime(self, a):
# def Om(self, a):
# D1, F1, D2, F2 = y
# D1, F1, D2, F2 = yi
#
# Path: fastpm/ncdm.py
# class Solver(core.Solver):
# @property
# def nbodystep(self):
# return FastPMStep(self)
. Output only the next line. | Plin = LinearPower(Planck15, redshift=0, transfer='EisensteinHu') |
Given snippet: <|code_start|>class FastPMCatalogSource(CatalogSource):
def __repr__(self):
return "FastPMSimulation()" %self.attrs
def __init__(self, linear, astart=0.1, aend=1.0, boost=2, Nsteps=5, cosmo=None):
self.comm = linear.comm
if cosmo is None:
cosmo = linear.Plin.cosmo
self.cosmo = cosmo
# the linear density field mesh
self.linear = linear
self.attrs.update(linear.attrs)
asteps = numpy.linspace(astart, aend, Nsteps)
self.attrs['astart'] = astart
self.attrs['aend'] = aend
self.attrs['Nsteps'] = Nsteps
self.attrs['asteps'] = asteps
self.attrs['boost'] = boost
solver = Solver(self.linear.pm, cosmology=self.cosmo, B=boost)
Q = self.linear.pm.generate_uniform_particle_grid(shift=0.5)
self.linear = linear
dlin = self.linear.to_field(mode='complex')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from fastpm.core import Solver, leapfrog
from nbodykit.base.catalog import CatalogSource, column
import numpy
and context:
# Path: fastpm/core.py
# class Solver(object):
# def __init__(self, pm, cosmology, B=1, a_linear=1.0):
# """
# a_linear : float
# scaling factor at the time of the linear field.
# The growth function will be calibrated such that at a_linear D1 == 0.
#
# """
# if not isinstance(cosmology, Cosmology):
# raise TypeError("only nbodykit.cosmology object is supported")
#
# fpm = ParticleMesh(Nmesh=pm.Nmesh * B, BoxSize=pm.BoxSize, dtype=pm.dtype, comm=pm.comm, resampler=pm.resampler)
# self.pm = pm
# self.fpm = fpm
# self.cosmology = cosmology
# self.a_linear = a_linear
#
# # override nbodystep in subclasses
# @property
# def nbodystep(self):
# return FastPMStep(self)
#
# def whitenoise(self, seed, unitary=False):
# return self.pm.generate_whitenoise(seed, type='complex', unitary=unitary)
#
# def linear(self, whitenoise, Pk):
# return whitenoise.apply(lambda k, v:
# Pk(sum(ki ** 2 for ki in k)**0.5) ** 0.5 * v / v.BoxSize.prod() ** 0.5)
#
# def lpt(self, linear, Q, a, order=2):
# """ This computes the 'force' from LPT as well. """
# assert order in (1, 2)
#
# from .force.lpt import lpt1, lpt2source
#
# state = StateVector(self, Q)
# pt = MatterDominated(self.cosmology.Om0, a=[a], a_normalize=self.a_linear)
# DX1 = pt.D1(a) * lpt1(linear, Q)
#
# V1 = a ** 2 * pt.f1(a) * pt.E(a) * DX1
# if order == 2:
# DX2 = pt.D2(a) * lpt1(lpt2source(linear), Q)
# V2 = a ** 2 * pt.f2(a) * pt.E(a) * DX2
# state.S[...] = DX1 + DX2
# state.P[...] = V1 + V2
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1 + pt.gf2(a) / pt.D2(a) * DX2)
# else:
# state.S[...] = DX1
# state.P[...] = V1
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1)
#
# state.a['S'] = a
# state.a['P'] = a
#
# return state
#
# def nbody(self, state, stepping, monitor=None):
# step = self.nbodystep
# for action, ai, ac, af in stepping:
# step.run(action, ai, ac, af, state, monitor)
#
# return state
#
# def leapfrog(stages):
# """ Generate a leap frog stepping scheme.
#
# Parameters
# ----------
# stages : array_like
# Time (a) where force computing stage is requested.
# """
# if len(stages) == 0:
# return
#
# ai = stages[0]
# # first force calculation for jump starting
# yield 'F', ai, ai, ai
# x, p, f = ai, ai, ai
#
# for i in range(len(stages) - 1):
# a0 = stages[i]
# a1 = stages[i + 1]
# ah = (a0 * a1) ** 0.5
# yield 'K', p, f, ah
# p = ah
# yield 'D', x, p, a1
# x = a1
# yield 'F', f, x, a1
# f = a1
# yield 'K', p, f, a1
# p = a1
which might include code, classes, or functions. Output only the next line. | state = solver.lpt(dlin, Q, a=astart, order=2) |
Based on the snippet: <|code_start|>
pm = ParticleMesh(BoxSize=128., Nmesh=[8, 8, 8])
def test_glass():
X = generate_glass_particle_grid(pm, 123)
<|code_end|>
, predict the immediate next line with the help of imports:
from fastpm.glass import generate_glass_particle_grid, ParticleMesh
from numpy.testing import assert_allclose
import numpy
and context (classes, functions, sometimes code) from other files:
# Path: fastpm/glass.py
# def generate_glass_particle_grid(pm, seed, B=2, spread=3.0, N=3):
# def __init__(self, pm, B=2):
# def nbodystep(self):
# def run(self, seed, Q, stages, spread=3.0, N=3):
# def Kick(self, state, ai, ac, af):
# def Drift(self, state, ai, ac, af):
# def Force(self, state, ai, ac, af):
# Q = pm.generate_uniform_particle_grid(shift=0)
# X = glass.X % pm.BoxSize
# X = layout.exchange(X)
# Q = Q
# X = state.X
# X1 = layout.exchange(X)
# class Solver(core.Solver):
# class GlassStep(core.FastPMStep):
. Output only the next line. | assert pm.comm.allreduce(len(X)) == pm.Nmesh.prod() |
Based on the snippet: <|code_start|>
pm = ParticleMesh(BoxSize=128., Nmesh=[8, 8, 8])
def test_glass():
X = generate_glass_particle_grid(pm, 123)
<|code_end|>
, predict the immediate next line with the help of imports:
from fastpm.glass import generate_glass_particle_grid, ParticleMesh
from numpy.testing import assert_allclose
import numpy
and context (classes, functions, sometimes code) from other files:
# Path: fastpm/glass.py
# def generate_glass_particle_grid(pm, seed, B=2, spread=3.0, N=3):
# def __init__(self, pm, B=2):
# def nbodystep(self):
# def run(self, seed, Q, stages, spread=3.0, N=3):
# def Kick(self, state, ai, ac, af):
# def Drift(self, state, ai, ac, af):
# def Force(self, state, ai, ac, af):
# Q = pm.generate_uniform_particle_grid(shift=0)
# X = glass.X % pm.BoxSize
# X = layout.exchange(X)
# Q = Q
# X = state.X
# X1 = layout.exchange(X)
# class Solver(core.Solver):
# class GlassStep(core.FastPMStep):
. Output only the next line. | assert pm.comm.allreduce(len(X)) == pm.Nmesh.prod() |
Using the snippet: <|code_start|>
# compute the force first as we didn't save it
yield ('F', stages[-1], stages[-1], stages[-1])
for action, ai, ac, af in list(leapfrog(stages))[::-1]:
if action == 'D':
yield action, af, ac, ai
for action, af, ac, ai in stack:
assert action == 'F'
yield action, af, ac, ai
stack = []
elif action == 'F':
# need to do F after D to ensure the time tag is right.
assert ac == af
stack.append((action, af, ai, ai))
else:
yield action, af, ac, ai
print(list(leapfrog(stages)))
print('----')
print(list(gorfpael(stages)))
print('++++')
print(list(leapfrog(stages[::-1])))
state = solver.nbody(lpt.copy(), leapfrog(stages), monitor=monitor)
if pm.comm.rank == 0:
print('----------------')
reverse = solver.nbody(state, leapfrog(stages[::-1]), monitor=monitor)
#print((lpt.X - reverse.X).max())
<|code_end|>
, determine the next line of code. You have imports:
from numpy.testing import assert_allclose
from fastpm.core import Solver, leapfrog
from nbodykit.cosmology import Planck15, EHPower
from nbodykit.lab import FOF
from nbodykit.lab import ArrayCatalog
from pmesh.pm import ParticleMesh
import numpy
and context (class names, function names, or code) available:
# Path: fastpm/core.py
# class Solver(object):
# def __init__(self, pm, cosmology, B=1, a_linear=1.0):
# """
# a_linear : float
# scaling factor at the time of the linear field.
# The growth function will be calibrated such that at a_linear D1 == 0.
#
# """
# if not isinstance(cosmology, Cosmology):
# raise TypeError("only nbodykit.cosmology object is supported")
#
# fpm = ParticleMesh(Nmesh=pm.Nmesh * B, BoxSize=pm.BoxSize, dtype=pm.dtype, comm=pm.comm, resampler=pm.resampler)
# self.pm = pm
# self.fpm = fpm
# self.cosmology = cosmology
# self.a_linear = a_linear
#
# # override nbodystep in subclasses
# @property
# def nbodystep(self):
# return FastPMStep(self)
#
# def whitenoise(self, seed, unitary=False):
# return self.pm.generate_whitenoise(seed, type='complex', unitary=unitary)
#
# def linear(self, whitenoise, Pk):
# return whitenoise.apply(lambda k, v:
# Pk(sum(ki ** 2 for ki in k)**0.5) ** 0.5 * v / v.BoxSize.prod() ** 0.5)
#
# def lpt(self, linear, Q, a, order=2):
# """ This computes the 'force' from LPT as well. """
# assert order in (1, 2)
#
# from .force.lpt import lpt1, lpt2source
#
# state = StateVector(self, Q)
# pt = MatterDominated(self.cosmology.Om0, a=[a], a_normalize=self.a_linear)
# DX1 = pt.D1(a) * lpt1(linear, Q)
#
# V1 = a ** 2 * pt.f1(a) * pt.E(a) * DX1
# if order == 2:
# DX2 = pt.D2(a) * lpt1(lpt2source(linear), Q)
# V2 = a ** 2 * pt.f2(a) * pt.E(a) * DX2
# state.S[...] = DX1 + DX2
# state.P[...] = V1 + V2
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1 + pt.gf2(a) / pt.D2(a) * DX2)
# else:
# state.S[...] = DX1
# state.P[...] = V1
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1)
#
# state.a['S'] = a
# state.a['P'] = a
#
# return state
#
# def nbody(self, state, stepping, monitor=None):
# step = self.nbodystep
# for action, ai, ac, af in stepping:
# step.run(action, ai, ac, af, state, monitor)
#
# return state
#
# def leapfrog(stages):
# """ Generate a leap frog stepping scheme.
#
# Parameters
# ----------
# stages : array_like
# Time (a) where force computing stage is requested.
# """
# if len(stages) == 0:
# return
#
# ai = stages[0]
# # first force calculation for jump starting
# yield 'F', ai, ai, ai
# x, p, f = ai, ai, ai
#
# for i in range(len(stages) - 1):
# a0 = stages[i]
# a1 = stages[i + 1]
# ah = (a0 * a1) ** 0.5
# yield 'K', p, f, ah
# p = ah
# yield 'D', x, p, a1
# x = a1
# yield 'F', f, x, a1
# f = a1
# yield 'K', p, f, a1
# p = a1
. Output only the next line. | assert_allclose(lpt.X, reverse.X) |
Based on the snippet: <|code_start|># This script tests if full reversability like
# JANUS is achieved by FastPM, without
# using int64 fixed point.
#
# JANUS: https://arxiv.org/pdf/1704.07715v1.pdf
#
# We do not need the high precision int64 representable
# because we only use very few steps (I think)
# Using float32 increases the error to about 1e-5.
pm = ParticleMesh(BoxSize=64, Nmesh=[64, 64, 64], dtype='f8')
Q = pm.generate_uniform_particle_grid()
stages = numpy.linspace(0.1, 1.0, 10, endpoint=True)
solver = Solver(pm, Planck15, B=2)
wn = solver.whitenoise(400)
dlin = solver.linear(wn, EHPower(Planck15, 0))
lpt = solver.lpt(dlin, Q, stages[0])
#lpt.S = numpy.float32(lpt.S)
def monitor(action, ai, ac, af, state, event):
if pm.comm.rank == 0:
<|code_end|>
, predict the immediate next line with the help of imports:
from numpy.testing import assert_allclose
from fastpm.core import Solver, leapfrog
from nbodykit.cosmology import Planck15, EHPower
from nbodykit.lab import FOF
from nbodykit.lab import ArrayCatalog
from pmesh.pm import ParticleMesh
import numpy
and context (classes, functions, sometimes code) from other files:
# Path: fastpm/core.py
# class Solver(object):
# def __init__(self, pm, cosmology, B=1, a_linear=1.0):
# """
# a_linear : float
# scaling factor at the time of the linear field.
# The growth function will be calibrated such that at a_linear D1 == 0.
#
# """
# if not isinstance(cosmology, Cosmology):
# raise TypeError("only nbodykit.cosmology object is supported")
#
# fpm = ParticleMesh(Nmesh=pm.Nmesh * B, BoxSize=pm.BoxSize, dtype=pm.dtype, comm=pm.comm, resampler=pm.resampler)
# self.pm = pm
# self.fpm = fpm
# self.cosmology = cosmology
# self.a_linear = a_linear
#
# # override nbodystep in subclasses
# @property
# def nbodystep(self):
# return FastPMStep(self)
#
# def whitenoise(self, seed, unitary=False):
# return self.pm.generate_whitenoise(seed, type='complex', unitary=unitary)
#
# def linear(self, whitenoise, Pk):
# return whitenoise.apply(lambda k, v:
# Pk(sum(ki ** 2 for ki in k)**0.5) ** 0.5 * v / v.BoxSize.prod() ** 0.5)
#
# def lpt(self, linear, Q, a, order=2):
# """ This computes the 'force' from LPT as well. """
# assert order in (1, 2)
#
# from .force.lpt import lpt1, lpt2source
#
# state = StateVector(self, Q)
# pt = MatterDominated(self.cosmology.Om0, a=[a], a_normalize=self.a_linear)
# DX1 = pt.D1(a) * lpt1(linear, Q)
#
# V1 = a ** 2 * pt.f1(a) * pt.E(a) * DX1
# if order == 2:
# DX2 = pt.D2(a) * lpt1(lpt2source(linear), Q)
# V2 = a ** 2 * pt.f2(a) * pt.E(a) * DX2
# state.S[...] = DX1 + DX2
# state.P[...] = V1 + V2
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1 + pt.gf2(a) / pt.D2(a) * DX2)
# else:
# state.S[...] = DX1
# state.P[...] = V1
# state.F[...] = a ** 2 * pt.E(a) * (pt.gf(a) / pt.D1(a) * DX1)
#
# state.a['S'] = a
# state.a['P'] = a
#
# return state
#
# def nbody(self, state, stepping, monitor=None):
# step = self.nbodystep
# for action, ai, ac, af in stepping:
# step.run(action, ai, ac, af, state, monitor)
#
# return state
#
# def leapfrog(stages):
# """ Generate a leap frog stepping scheme.
#
# Parameters
# ----------
# stages : array_like
# Time (a) where force computing stage is requested.
# """
# if len(stages) == 0:
# return
#
# ai = stages[0]
# # first force calculation for jump starting
# yield 'F', ai, ai, ai
# x, p, f = ai, ai, ai
#
# for i in range(len(stages) - 1):
# a0 = stages[i]
# a1 = stages[i + 1]
# ah = (a0 * a1) ** 0.5
# yield 'K', p, f, ah
# p = ah
# yield 'D', x, p, a1
# x = a1
# yield 'F', f, x, a1
# f = a1
# yield 'K', p, f, a1
# p = a1
. Output only the next line. | print(state.a['S'], state.a['P'], state.a['F'], state.S[0], state.P[0], action, ai, ac, af) |
Next line prediction: <|code_start|>
class StateVector(object):
def __init__(self, solver, Q):
self.solver = solver
self.pm = solver.pm
self.Q = Q
self.csize = solver.pm.comm.allreduce(len(self.Q))
self.dtype = self.Q.dtype
self.cosmology = solver.cosmology
self.H0 = 100. # in km/s / Mpc/h units
# G * (mass of a particle)
self.GM0 = self.H0 ** 2 / ( 4 * numpy.pi ) * 1.5 * self.cosmology.Om0 * self.pm.BoxSize.prod() / self.csize
self.S = numpy.zeros_like(self.Q)
self.P = numpy.zeros_like(self.Q)
self.F = numpy.zeros_like(self.Q)
self.RHO = numpy.zeros_like(self.Q[..., 0])
<|code_end|>
. Use current file imports:
(import numpy
from pmesh.pm import ParticleMesh
from .background import MatterDominated
from nbodykit.cosmology import Cosmology
from nbodykit.lab import ArrayCatalog
from bigfile import FileMPI
from .force.lpt import lpt1, lpt2source
from .force.gravity import longrange)
and context including class names, function names, or small code snippets from other files:
# Path: fastpm/background.py
# class MatterDominated(Perturbation):
# """
#
# Perturbation with matter dominated initial condition.
#
# This is usually referred to the single fluid approximation as well.
#
# The result here is accurate upto numerical precision. If Omega0_m
#
# Parameters
# ----------
# Omega0_m :
# matter density at redshift 0
#
# Omega0_lambda :
# Lambda density at redshift 0, default None; set to ensure flat universe.
#
# Omega0_k:
# Curvature density at redshift 0, default : 0
#
# a : array_like
# a list of time steps where the factors are exact.
# other a values are interpolated.
# """
# def __init__(self, Omega0_m, Omega0_lambda=None, Omega0_k=0, a=None, a_normalize=1.0):
# if Omega0_lambda is None:
# Omega0_lambda = 1 - Omega0_k - Omega0_m
#
# self.Omega0_lambda = Omega0_lambda
# self.Omega0_m = Omega0_m
# self.Omega0_k = Omega0_k
# # Om0 is added for backward compatiblity
# self.Om0 = Omega0_m
# Perturbation.__init__(self, a, a_normalize)
#
# def get_initial_condition(self):
# a0 = np.exp(self.lna[0])
#
# # matter dominated initial conditions
# y0 = [a0, a0, -3./7 * a0**2, -6. / 7 *a0**2]
# return y0
#
# def efunc(self, a):
# return (self.Omega0_m / a**3+ self.Omega0_k / a**2 + self.Omega0_lambda) ** 0.5
#
# def efunc_prime(self, a):
# return 0.5 / self.efunc(a) * (-3 * self.Omega0_m / (a**4) + -2 * self.Omega0_k / (a**3))
#
# def Om(self, a):
# return (self.Omega0_m / a ** 3) / self.efunc(a) ** 2
. Output only the next line. | self.a = dict(S=None, P=None, F=None) |
Based on the snippet: <|code_start|># This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
class TestExternalAddressbookGetContacts(unittest.TestCase):
"""Some test cases for
alot.addressbook.external.ExternalAddressbook.get_contacts"""
regex = '(?P<name>.*)\t(?P<email>.*)'
@staticmethod
def _patch_call_cmd(return_value):
return mock.patch('alot.addressbook.external.call_cmd',
mock.Mock(return_value=return_value))
def test_raises_if_external_command_exits_with_non_zero_status(self):
abook = external.ExternalAddressbook('foobar', '')
with self._patch_call_cmd(('', '', 42)):
with self.assertRaises(external.AddressbookError) as contextmgr:
abook.get_contacts()
expected = 'abook command "foobar" returned with return code 42'
self.assertEqual(contextmgr.exception.args[0], expected)
def test_stderr_of_failing_command_is_part_of_exception_message(self):
stderr = 'some text printed on stderr of external command'
abook = external.ExternalAddressbook('foobar', '')
with self._patch_call_cmd(('', stderr, 42)):
with self.assertRaises(external.AddressbookError) as contextmgr:
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import unittest
from unittest import mock
from alot.addressbook import external
and context (classes, functions, sometimes code) from other files:
# Path: alot/addressbook/external.py
# class ExternalAddressbook(AddressBook):
# def __init__(self, commandline, regex, reflags=0,
# external_filtering=True,
# **kwargs):
# def get_contacts(self):
# def lookup(self, prefix): # pragma: no cover
# def _call_and_parse(self, commandline):
. Output only the next line. | abook.get_contacts() |
Given the following code snippet before the placeholder: <|code_start|>
address = None
"""this accounts main email address"""
aliases = []
"""list of alternative addresses"""
alias_regexp = ""
"""regex matching alternative addresses"""
realname = None
"""real name used to format from-headers"""
encrypt_to_self = None
"""encrypt outgoing encrypted emails to this account's private key"""
gpg_key = None
"""gpg fingerprint for this account's private key"""
signature = None
"""signature to append to outgoing mails"""
signature_filename = None
"""filename of signature file in attachment"""
signature_as_attachment = None
"""attach signature file instead of appending its content to body text"""
abook = None
"""addressbook (:class:`addressbook.AddressBook`)
managing this accounts contacts"""
def __init__(self, address=None, aliases=None, alias_regexp=None,
realname=None, gpg_key=None, signature=None,
signature_filename=None, signature_as_attachment=False,
sent_box=None, sent_tags=None, draft_box=None,
draft_tags=None, replied_tags=None, passed_tags=None,
abook=None, sign_by_default=False,
encrypt_by_default="none", encrypt_to_self=None,
<|code_end|>
, predict the next line using imports from the current file:
import abc
import glob
import logging
import mailbox
import operator
import os
import re
from .helper import call_cmd_async
from .helper import split_commandstring
and context including class names, function names, and sometimes code from other files:
# Path: alot/helper.py
# async def call_cmd_async(cmdlist, stdin=None, env=None):
# """Given a command, call that command asynchronously and return the output.
#
# This function only handles `OSError` when creating the subprocess, any
# other exceptions raised either durring subprocess creation or while
# exchanging data with the subprocess are the caller's responsibility to
# handle.
#
# If such an `OSError` is caught, then returncode will be set to 1, and the
# error value will be set to the str() value of the exception.
#
# :type cmdlist: list of str
# :param stdin: string to pipe to the process
# :type stdin: str
# :return: Tuple of stdout, stderr, returncode
# :rtype: tuple[str, str, int]
# """
# termenc = urwid.util.detected_encoding
# cmdlist = [s.encode(termenc) for s in cmdlist]
#
# environment = os.environ.copy()
# if env is not None:
# environment.update(env)
# logging.debug('ENV = %s', environment)
# logging.debug('CMD = %s', cmdlist)
# try:
# proc = await asyncio.create_subprocess_exec(
# *cmdlist,
# env=environment,
# stdout=asyncio.subprocess.PIPE,
# stderr=asyncio.subprocess.PIPE,
# stdin=asyncio.subprocess.PIPE if stdin else None)
# except OSError as e:
# return ('', str(e), 1)
# out, err = await proc.communicate(stdin.encode(termenc) if stdin else None)
# return (out.decode(termenc), err.decode(termenc), proc.returncode)
#
# Path: alot/helper.py
# def split_commandstring(cmdstring):
# """
# split command string into a list of strings to pass on to subprocess.Popen
# and the like. This simply calls shlex.split but works also with unicode
# bytestrings.
# """
# assert isinstance(cmdstring, str)
# return shlex.split(cmdstring)
. Output only the next line. | message_id_domain=None, |
Given the following code snippet before the placeholder: <|code_start|> self.alias_regexp = alias_regexp
self.realname = realname
self.encrypt_to_self = encrypt_to_self
self.gpg_key = gpg_key
self.signature = signature
self.signature_filename = signature_filename
self.signature_as_attachment = signature_as_attachment
self.sign_by_default = sign_by_default
self.sent_box = sent_box
self.sent_tags = sent_tags
self.draft_box = draft_box
self.draft_tags = draft_tags
self.replied_tags = replied_tags
self.passed_tags = passed_tags
self.abook = abook
self.message_id_domain = message_id_domain
# Handle encrypt_by_default in an backwards compatible way. The
# logging info call can later be upgraded to warning or error.
encrypt_by_default = encrypt_by_default.lower()
msg = "Deprecation warning: The format for the encrypt_by_default " \
"option changed. Please use 'none', 'all' or 'trusted'."
if encrypt_by_default in ("true", "yes", "1"):
encrypt_by_default = "all"
logging.info(msg)
elif encrypt_by_default in ("false", "no", "0"):
encrypt_by_default = "none"
logging.info(msg)
self.encrypt_by_default = encrypt_by_default
# cache alias_regexp regexes
if self.alias_regexp != "":
<|code_end|>
, predict the next line using imports from the current file:
import abc
import glob
import logging
import mailbox
import operator
import os
import re
from .helper import call_cmd_async
from .helper import split_commandstring
and context including class names, function names, and sometimes code from other files:
# Path: alot/helper.py
# async def call_cmd_async(cmdlist, stdin=None, env=None):
# """Given a command, call that command asynchronously and return the output.
#
# This function only handles `OSError` when creating the subprocess, any
# other exceptions raised either durring subprocess creation or while
# exchanging data with the subprocess are the caller's responsibility to
# handle.
#
# If such an `OSError` is caught, then returncode will be set to 1, and the
# error value will be set to the str() value of the exception.
#
# :type cmdlist: list of str
# :param stdin: string to pipe to the process
# :type stdin: str
# :return: Tuple of stdout, stderr, returncode
# :rtype: tuple[str, str, int]
# """
# termenc = urwid.util.detected_encoding
# cmdlist = [s.encode(termenc) for s in cmdlist]
#
# environment = os.environ.copy()
# if env is not None:
# environment.update(env)
# logging.debug('ENV = %s', environment)
# logging.debug('CMD = %s', cmdlist)
# try:
# proc = await asyncio.create_subprocess_exec(
# *cmdlist,
# env=environment,
# stdout=asyncio.subprocess.PIPE,
# stderr=asyncio.subprocess.PIPE,
# stdin=asyncio.subprocess.PIPE if stdin else None)
# except OSError as e:
# return ('', str(e), 1)
# out, err = await proc.communicate(stdin.encode(termenc) if stdin else None)
# return (out.decode(termenc), err.decode(termenc), proc.returncode)
#
# Path: alot/helper.py
# def split_commandstring(cmdstring):
# """
# split command string into a list of strings to pass on to subprocess.Popen
# and the like. This simply calls shlex.split but works also with unicode
# bytestrings.
# """
# assert isinstance(cmdstring, str)
# return shlex.split(cmdstring)
. Output only the next line. | self._alias_regexp = re.compile( |
Next line prediction: <|code_start|>
class Spider(CrawlSpider):
# Public
name = 'pfizer'
allowed_domains = ['pfizer.com']
def __init__(self, conf=None, conn=None):
# Save conf/conn
self.conf = conf
self.conn = conn
# Make urls
self.start_urls = [
'http://www.pfizer.com/research/clinical_trials/find_a_trial?recr=0',
]
# Make rules
self.rules = [
Rule(LinkExtractor(
allow=r'find_a_trial/NCT\d+',
), callback=parse_record),
Rule(LinkExtractor(
allow=r'page=\d+',
)),
]
# Inherit parent
<|code_end|>
. Use current file imports:
(from scrapy.spiders import Rule
from scrapy.spiders import CrawlSpider
from scrapy.linkextractors import LinkExtractor
from .parser import parse_record)
and context including class names, function names, or small code snippets from other files:
# Path: collectors/pfizer/parser.py
# def parse_record(res):
#
# # Init data
# data = {}
#
# # Description
#
# key = 'study_type'
# path = '.field-name-field-study-type .field-item::text'
# value = res.css(path).extract_first()
# data[key] = value
#
# key = 'organization_id'
# path = '.field-name-field-organization-id .field-item::text'
# value = res.css(path).extract_first()
# data[key] = value
#
# key = 'nct_id'
# path = '.field-name-field-clinical-trial-id .field-item::text'
# value = res.css(path).extract_first()
# data[key] = value
#
# key = 'status'
# path = '//label[text() = "Status"]/../text()'
# value = ''.join(res.xpath(path).extract()).strip()
# data[key] = value
#
# key = 'study_start_date'
# path = '.field-name-field-study-start-date .field-item span::text'
# value = res.css(path).extract_first()
# data[key] = value
#
# key = 'study_end_date'
# path = '.field-name-field-study-end-date .field-item span::text'
# value = res.css(path).extract_first()
# data[key] = value
#
# # Eligibility
#
# key = 'eligibility_criteria'
# path = '.field-name-field-criteria .field-item *::text'
# value = ''.join(res.css(path).extract())
# data[key] = value
#
# key = 'gender'
# path = '.field-name-field-gender .field-item::text'
# value = res.css(path).extract_first()
# data[key] = value
#
# key = 'age_range'
# path = '//label[text() = "Age Range:"]/../text()'
# value = ''.join(res.xpath(path).extract()).strip()
# data[key] = value
#
# key = 'healthy_volunteers_allowed'
# path = '.field-name-field-healthy-volunteers-allowed .field-item::text'
# value = res.css(path).extract_first()
# data[key] = value
#
# # Create record
# record = Record.create(res.url, data)
#
# return record
. Output only the next line. | super(Spider, self).__init__() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, generate the next line using the imports in this file:
from scrapy.crawler import CrawlerProcess
from .spider import Spider
and context (functions, classes, or occasionally code) from other files:
# Path: collectors/pubmed/spider.py
# class Spider(CrawlSpider):
#
# # Public
#
# name = 'pubmed'
# allowed_domains = ['eutils.ncbi.nlm.nih.gov']
#
# def __init__(self, conf=None, conn=None, date_from=None, date_to=None):
#
# # Save conf/conn
# self.conf = conf
# self.conn = conn
#
# # Make start urls
# self.start_urls = _make_start_urls(
# prefix='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi/',
# template='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi/?db=pubmed&id={pmid}&retmode=xml',
# date_from=date_from, date_to=date_to)
#
# # Set parser
# self.parse = parse_record
#
# # Inherit parent
# super(Spider, self).__init__()
. Output only the next line. | from __future__ import unicode_literals |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# Module API
def collect(conf, conn):
process = CrawlerProcess(conf['SCRAPY_SETTINGS'])
process.crawl(Spider, conn=conn)
<|code_end|>
, predict the immediate next line with the help of imports:
from scrapy.crawler import CrawlerProcess
from .spider import Spider
and context (classes, functions, sometimes code) from other files:
# Path: collectors/takeda/spider.py
# class Spider(CrawlSpider):
#
# # Public
#
# name = 'takeda'
# allowed_domains = ['takedaclinicaltrials.com']
#
# def __init__(self, conf=None, conn=None):
#
# # Save conf/conn
# self.conf = conf
# self.conn = conn
#
# # Make urls
# self.start_urls = [
# 'http://www.takedaclinicaltrials.com/browse/?protocol_id=',
# ]
#
# # Make rules
# self.rules = [
# Rule(LinkExtractor(
# allow=r'browse/summary/',
# ), callback=parse_record),
# Rule(LinkExtractor(
# allow=r'browse',
# )),
# ]
#
# # Inherit parent
# super(Spider, self).__init__()
. Output only the next line. | process.start() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# Module API
def parse_record(res):
# Init data
data = {}
# Description
<|code_end|>
, generate the next line using the imports in this file:
from .record import Record
and context (functions, classes, or occasionally code) from other files:
# Path: collectors/pfizer/record.py
# class Record(base.Record):
#
# # Config
#
# table = 'pfizer'
#
# # General
#
# nct_id = Text(primary_key=True)
# title = Text()
#
# # Description
#
# study_type = Text()
# organization_id = Text()
# status = Text()
# study_start_date = Date('%B, %Y')
# study_end_date = Date('%B, %Y')
#
# # Eligibility
#
# eligibility_criteria = Text()
# gender = Text()
# age_range = Text()
# healthy_volunteers_allowed = Boolean('Accepts Healthy Volunteers')
. Output only the next line. | key = 'study_type' |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
. Use current file imports:
(from collectors.gsk.parser import parse_record)
and context including class names, function names, or small code snippets from other files:
# Path: collectors/gsk/parser.py
# def parse_record(res):
# fields_to_remove = [
# 'explanation',
# ]
#
# # Init data
# data = {}
#
# # Parse rawdata
# kpath = 'td.rowlabel'
# vpath = 'td.rowlabel+td'
# rawdata = _parse_data(res, kpath, vpath)
# for key, value in rawdata:
#
# # General
#
# if key == 'study_id':
# value = 'GSK%s' % value
#
# # Protocol summary
#
# if key == 'secondary_ids':
# newvalue = []
# for element in re.split(r'\t+', value):
# newvalue.append(element.strip())
# value = newvalue
#
# if key == 'oversight_authority':
# newvalue = []
# for element in re.split(r'\t+', value):
# newvalue.append(element.strip())
# value = newvalue
#
# if key == 'primary_outcomes':
# newvalue = []
# for element in re.split(r'\t+', value):
# elementdata = []
# for subelement in element.splitlines():
# subelement = subelement.strip()
# if subelement:
# elementdata.append(subelement)
# newvalue.append(elementdata)
# value = newvalue
#
# if key == 'secondary_outcomes':
# newvalue = []
# for element in re.split(r'\t+', value):
# elementdata = []
# for subelement in element.splitlines():
# subelement = subelement.strip()
# if subelement:
# elementdata.append(subelement)
# newvalue.append(elementdata)
# value = newvalue
#
# if key == 'arms':
# newvalue = []
# for element in re.split(r'\t+', value):
# elementdata = []
# for subelement in element.splitlines():
# subelement = subelement.strip()
# if subelement:
# elementdata.append(subelement)
# newvalue.append(elementdata)
# value = newvalue
#
# if key == 'interventions':
# newvalue = []
# for element in re.split(r'\t+', value):
# elementdata = []
# for subelement in element.splitlines():
# subelement = subelement.strip()
# if subelement:
# elementdata.append(subelement)
# newvalue.append(elementdata)
# value = newvalue
#
# if key == 'conditions':
# newvalue = []
# for element in re.split(r'\t+', value):
# newvalue.append(element.strip())
# value = newvalue
#
# if key == 'keywords':
# newvalue = []
# for element in re.split(r'\t+', value):
# newvalue.append(element.strip())
# value = newvalue
#
# # Collect plain values
# data[key] = value
#
# # Date information
# nodes = res.css('#ps tr.header td')
# try:
# data['first_received'] = nodes[0].xpath('text()').extract_first()
# data['last_updated'] = nodes[1].xpath('text()').extract_first()
# except Exception:
# pass
#
# # Results URL
# urls = res.css('#rs td a::attr(href)').extract()
# if urls:
# assert len(urls) == 1, 'Multiple URLs found on %s' % res.url
# data['results_url'] = urlparse.urljoin(res.url, urls[0])
#
# # Remove data
# for key in fields_to_remove:
# if key in data:
# del data[key]
#
# # Create record
# record = Record.create(res.url, data)
#
# return record
. Output only the next line. | from __future__ import unicode_literals |
Given snippet: <|code_start|>
# Module API
class Spider(CrawlSpider):
# Public
name = 'takeda'
allowed_domains = ['takedaclinicaltrials.com']
def __init__(self, conf=None, conn=None):
# Save conf/conn
self.conf = conf
self.conn = conn
# Make urls
self.start_urls = [
'http://www.takedaclinicaltrials.com/browse/?protocol_id=',
]
# Make rules
self.rules = [
Rule(LinkExtractor(
allow=r'browse/summary/',
), callback=parse_record),
Rule(LinkExtractor(
allow=r'browse',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from scrapy.spiders import Rule
from scrapy.spiders import CrawlSpider
from scrapy.linkextractors import LinkExtractor
from .parser import parse_record
and context:
# Path: collectors/takeda/parser.py
# def parse_record(res):
#
# # Init data
# data = {}
#
# # Parse rawdata
# gpath = 'h1'
# kpath = 'p.eyebrowbold'
# vpath = 'p.eyebrowbold+*'
# rawdata = _parse_data(res, gpath, kpath, vpath)
# for group, key, value in rawdata:
#
# # General
#
# if key == 'compound':
# value = value.split(',')
#
# # Recruitment
#
# if key == 'locations':
# value = value.split(',')
#
# # Collect plain values
# data[key] = value
#
# # Extract results URL
# selector = '#results div a::attr(href)'
# value = res.css(selector).extract_first()
# if value:
# url = urlparse.urljoin(res.url, value)
# data['download_the_clinical_trial_summary'] = url
# else:
# try:
# del data['download_the_clinical_trial_summary']
# except KeyError:
# pass
#
# # Create record
# record = Record.create(res.url, data)
#
# return record
which might include code, classes, or functions. Output only the next line. | )), |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
class TestHRACollector(object):
def test_make_request_url(self):
<|code_end|>
using the current file's imports:
import mock
import pytest
import datetime
import requests
from collections import defaultdict
from collectors.hra.collector import collect, _make_request_url
and any relevant context from other files:
# Path: collectors/hra/collector.py
# def collect(conf, conn, date_from=None, date_to=None):
#
# # Start collector
# date_from = _get_date_from(conn, date_from)
# date_to = _get_date_to(conn, date_to)
# base.helpers.start(conf, 'hra', {'date_from': date_from, 'date_to': date_to})
#
# # Get parameters
# URL = conf['HRA_URL']
# USER = conf['HRA_USER']
# PASS = conf['HRA_PASS']
#
# count = 0
# chunk_days = 100
# session = requests.Session()
# loop_date_from = date_from
# while True:
# if loop_date_from > date_to:
# break
# loop_date_to = min(loop_date_from + datetime.timedelta(days=chunk_days), date_to)
# url = _make_request_url(URL, loop_date_from, loop_date_to)
# response = session.get(url, auth=(USER, PASS))
# response.raise_for_status()
# base.config.SENTRY.extra_context({
# 'url': response.url,
# })
# for item in response.json():
# record = parse_record(response.url, item)
# if not record:
# continue
# record.write(conf, conn)
# count += 1
# if not count % 100:
# logger.info('Collected "%s" hra records', count)
# loop_date_from = loop_date_to + datetime.timedelta(days=1)
# time.sleep(1)
#
# # Stop collector
# base.helpers.stop(conf, 'hra', {'collected': count})
#
# def _make_request_url(prefix, date_from, date_to):
# query = OrderedDict()
# query['datePublishedFrom'] = date_from.strftime('%Y-%m-%d')
# query['datePublishedTo'] = date_to.strftime('%Y-%m-%d')
# url = '%s?%s' % (prefix, urlencode(query))
# return url
. Output only the next line. | date_from = datetime.date(2015, 1, 1) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
class TestHRACollector(object):
def test_make_request_url(self):
date_from = datetime.date(2015, 1, 1)
date_to = datetime.date(2015, 12, 31)
actual = _make_request_url('prefix', date_from, date_to)
expect = 'prefix?datePublishedFrom=2015-01-01&datePublishedTo=2015-12-31'
assert actual == expect
@mock.patch('requests.Session.get')
def test_collect_skips_deffered_records(self, session_get_mock, conn, conf, deferred_item_stub):
response_mock = mock.Mock()
response_mock.json.return_value = [
<|code_end|>
using the current file's imports:
import mock
import pytest
import datetime
import requests
from collections import defaultdict
from collectors.hra.collector import collect, _make_request_url
and any relevant context from other files:
# Path: collectors/hra/collector.py
# def collect(conf, conn, date_from=None, date_to=None):
#
# # Start collector
# date_from = _get_date_from(conn, date_from)
# date_to = _get_date_to(conn, date_to)
# base.helpers.start(conf, 'hra', {'date_from': date_from, 'date_to': date_to})
#
# # Get parameters
# URL = conf['HRA_URL']
# USER = conf['HRA_USER']
# PASS = conf['HRA_PASS']
#
# count = 0
# chunk_days = 100
# session = requests.Session()
# loop_date_from = date_from
# while True:
# if loop_date_from > date_to:
# break
# loop_date_to = min(loop_date_from + datetime.timedelta(days=chunk_days), date_to)
# url = _make_request_url(URL, loop_date_from, loop_date_to)
# response = session.get(url, auth=(USER, PASS))
# response.raise_for_status()
# base.config.SENTRY.extra_context({
# 'url': response.url,
# })
# for item in response.json():
# record = parse_record(response.url, item)
# if not record:
# continue
# record.write(conf, conn)
# count += 1
# if not count % 100:
# logger.info('Collected "%s" hra records', count)
# loop_date_from = loop_date_to + datetime.timedelta(days=1)
# time.sleep(1)
#
# # Stop collector
# base.helpers.stop(conf, 'hra', {'collected': count})
#
# def _make_request_url(prefix, date_from, date_to):
# query = OrderedDict()
# query['datePublishedFrom'] = date_from.strftime('%Y-%m-%d')
# query['datePublishedTo'] = date_to.strftime('%Y-%m-%d')
# url = '%s?%s' % (prefix, urlencode(query))
# return url
. Output only the next line. | deferred_item_stub |
Here is a snippet: <|code_start|> day=medline['DateCompleted']['Day']['#text'])
if 'DateRevised' in medline:
data['date_revised'] = '{year}-{month}-{day}'.format(
year=medline['DateRevised']['Year']['#text'],
month=medline['DateRevised']['Month']['#text'],
day=medline['DateRevised']['Day']['#text'])
if medline['MedlineJournalInfo'].get('Country'):
data['country'] = medline['MedlineJournalInfo']['Country']['#text']
if 'MedlineTA' in medline['MedlineJournalInfo']:
data['medline_ta'] = medline['MedlineJournalInfo']['MedlineTA']['#text']
if 'NlmUniqueID' in medline['MedlineJournalInfo']:
data['nlm_unique_id'] = medline['MedlineJournalInfo']['NlmUniqueID']['#text']
if 'ISSNLinking' in medline['MedlineJournalInfo']:
data['issn_linking'] = medline['MedlineJournalInfo']['ISSNLinking']['#text']
if 'MeshHeadingList' in medline:
data['mesh_headings'] = medline['MeshHeadingList']
# Journal
if 'ISSN' in journal:
data['journal_issn'] = journal['ISSN']['#text']
if 'Title' in journal:
data['journal_title'] = journal['Title']['#text']
if 'ISOAbbreviation' in journal:
data['journal_iso'] = journal['ISOAbbreviation']['#text']
# Article
if 'ArticleTitle' in article:
data['article_title'] = article['ArticleTitle']['#text']
<|code_end|>
. Write the next line using the current file imports:
import xmltodict
from dateutil.parser import parse as date_parse
from .record import Record
and context from other files:
# Path: collectors/pubmed/record.py
# class Record(base.Record):
#
# # Config
#
# table = 'pubmed'
#
# # Medline
#
# pmid = Text(primary_key=True)
# date_created = Date('%Y-%m-%d')
# date_completed = Date('%Y-%m-%d')
# date_revised = Date('%Y-%m-%d')
# country = Text()
# medline_ta = Text()
# nlm_unique_id = Text()
# issn_linking = Text()
# mesh_headings = Json()
#
# # Journal
#
# journal_issn = Text()
# journal_title = Text()
# journal_iso = Text()
#
# # Article
#
# article_title = Text()
# article_abstract = Text()
# article_authors = Array()
# article_language = Text()
# article_publication_type_list = Array()
# article_vernacular_title = Text()
# article_date = Date('%Y-%m-%d')
#
# # Pubmed
#
# publication_status = Text()
# article_ids = Json()
# registry_ids = Json()
, which may include functions, classes, or code. Output only the next line. | if 'Abstract' in article: |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
<|code_end|>
. Write the next line using the current file imports:
from collectors.takeda.parser import parse_record
and context from other files:
# Path: collectors/takeda/parser.py
# def parse_record(res):
#
# # Init data
# data = {}
#
# # Parse rawdata
# gpath = 'h1'
# kpath = 'p.eyebrowbold'
# vpath = 'p.eyebrowbold+*'
# rawdata = _parse_data(res, gpath, kpath, vpath)
# for group, key, value in rawdata:
#
# # General
#
# if key == 'compound':
# value = value.split(',')
#
# # Recruitment
#
# if key == 'locations':
# value = value.split(',')
#
# # Collect plain values
# data[key] = value
#
# # Extract results URL
# selector = '#results div a::attr(href)'
# value = res.css(selector).extract_first()
# if value:
# url = urlparse.urljoin(res.url, value)
# data['download_the_clinical_trial_summary'] = url
# else:
# try:
# del data['download_the_clinical_trial_summary']
# except KeyError:
# pass
#
# # Create record
# record = Record.create(res.url, data)
#
# return record
, which may include functions, classes, or code. Output only the next line. | class TestTakedaParser(object): |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
<|code_end|>
. Write the next line using the current file imports:
import io
import logging
import zipfile
import requests
from .record import Record
and context from other files:
# Path: collectors/icdpcs/record.py
# class Record(base.Record):
#
# # Config
#
# table = 'icdpcs'
#
# # General
#
# code = Text(primary_key=True)
# is_header = Boolean('0')
# short_description = Text()
# long_description = Text()
# version = Text()
# last_updated = Date('%Y-%m-%d')
, which may include functions, classes, or code. Output only the next line. | logger = logging.getLogger(__name__) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# Tests
def test_make_start_urls():
result = _make_start_urls(
'https://www.clinicaltrialsregister.eu/ctr-search/search',
<|code_end|>
using the current file's imports:
from importlib import import_module
from collectors.euctr.spider import _make_start_urls
and any relevant context from other files:
# Path: collectors/euctr/spider.py
# def _make_start_urls(prefix, date_from=None, date_to=None):
# """ Return start_urls.
# """
# if date_from is None:
# date_from = str(date.today() - timedelta(days=1))
# if date_to is None:
# date_to = str(date.today())
# query = OrderedDict()
# query['query'] = ''
# query['dateFrom'] = date_from
# query['dateTo'] = date_to
# return [prefix + '?' + urlencode(query)]
. Output only the next line. | '2015-01-01', '2015-01-02') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.