Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|>"""
.. module:: logger
:synopsis: Output which sends events to the standard logging output
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
<|code_end|>
with the help of current file imports:
from twisted.python import log
from duct.objects import Output
and context from other files:
# Path: duct/objects.py
# class Output(object):
# """Output parent class
#
# Outputs can inherit this object which provides a construct
# for a working output
#
# :param config: Dictionary config for this queue (usually read from the
# yaml configuration)
# :param duct: A DuctService object for interacting with the queue manager
# """
# def __init__(self, config, duct):
# self.config = config
# self.duct = duct
# self.events = []
# self.maxsize = 0
#
# def createClient(self):
# """Deferred which sets up the output
# """
# pass
#
# def eventsReceived(self, events):
# """Receives a list of events and queues them
#
# Arguments:
# events -- list of `duct.objects.Event`
# """
# # Make sure queue isn't oversized
# if self.maxsize > 0:
# if (self.maxsize < 1) or (len(self.events) < self.maxsize):
# self.events.extend(events)
# else:
# self.events.extend(events)
#
# def stop(self):
# """Called when the service shuts down
# """
# pass
, which may contain function names, class names, or code. Output only the next line. | class Logger(Output): |
Given the code snippet: <|code_start|>
class Options(usage.Options):
optParameters = [
["config", "c", "duct.yml", "Config file"],
]
@implementer(IServiceMaker, IPlugin)
class DuctServiceMaker(object):
tapname = "duct"
description = "A monitoring and data-moving-around-places agent"
options = Options
def makeService(self, options):
<|code_end|>
, generate the next line using the imports in this file:
from zope.interface import implementer
from twisted.python import usage
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from duct.configuration import ConfigFile
import duct
and context (functions, classes, or occasionally code) from other files:
# Path: duct/configuration.py
# class ConfigFile(object):
# """Duct configuration file parser and accessor
# """
# def __init__(self, path):
# if os.path.exists(path):
# with open(path, 'rt') as conf:
# self.raw_config = yaml.load(conf)
#
# if not self.raw_config:
# self.raw_config = {}
# log.msg("Warning: No configuration content")
# else:
# raise Exception("Configuration file '%s' not found" % path)
#
# self.known_items = {
# 'sources': list,
# 'outputs': list,
# 'interval': (float, int,),
# 'ttl': (float, int,),
# 'blueprint': list,
# 'ssh_key': str,
# 'ssh_user': str,
# 'toolbox': dict
# }
#
# self._parse_config()
#
# def _validate_type(self, item, vtype):
# if not isinstance(vtype, tuple):
# vtype = (vtype, )
#
# parse = False
# for vt in vtype:
# try:
# assert isinstance(self.raw_config.get(item, vt()), vtype)
# parse = True
# except AssertionError:
# pass
#
# if not parse:
# raise ConfigurationError(
# "%s must be one of type %s" % (item, repr(vtype)))
#
# def _validate_config(self):
# for key, val in self.known_items.items():
# self._validate_type(key, val)
#
# def _parse_config(self):
# self._merge_includes()
#
# self._validate_config()
#
# self._build_blueprints()
#
# def _merge_includes(self):
# both = lambda i1, i2, t: isinstance(i1, t) and isinstance(i2, t)
#
# paths = self.raw_config.get('include_path', [])
# if not isinstance(paths, list):
# paths = [paths]
#
# paths2 = self.raw_config.get('include', [])
# if not isinstance(paths2, list):
# paths2 = [paths2]
#
# paths.extend(paths2)
#
#
# for ipath in paths:
# if os.path.exists(ipath):
# files = [os.path.join(ipath, fi) for fi in os.listdir(ipath)
# if fi.endswith('.yml') or fi.endswith('.yaml')]
#
# for conf_file in files:
# with open(conf_file, 'rt') as yaml_path:
# conf = yaml.load(yaml_path)
# for key, val in conf.items():
# if key in self.raw_config:
# if both(val, self.raw_config[key], dict):
# # Merge dicts
# for k2, v2 in val.items():
# self.raw_config[key][k2] = v2
#
# elif both(val, self.raw_config[key], list):
# # Extend lists
# self.raw_config[key].extend(val)
# else:
# # Overwrite
# self.raw_config[key] = val
# else:
# self.raw_config[key] = val
# log.msg('Loadded additional configuration from %s'
# % conf_file)
# else:
# log.msg(
# 'Config Error: include_path %s does not exist' % ipath)
#
# def _build_blueprints(self):
# # Turn toolboxes into a dict
# toolboxes = self.raw_config.get('toolbox', {})
# blueprints = self.raw_config.get('blueprint', [])
#
# if blueprints:
# # Make sure raw config stubs exist if we have any blueprints
# if 'sources' not in self.raw_config:
# self.raw_config['sources'] = []
#
# for blueprint in blueprints:
# tbs = blueprint['toolbox']
# # Listify it so we can inherit multiple toolboxes
# if not isinstance(toolboxes, list):
# tbs = [tbs]
#
# tbs = [toolboxes[tool] for tool in tbs]
#
# # Compute a dot product of all the config settings vectors
# inversions = []
# for key, val in blueprint.get('sets', {}).items():
# inversions.append([(key, jay) for jay in val])
#
# for options in itertools.product(*inversions):
# for toolbox in tbs:
# for source in toolbox.get('sources', []):
# # Make a copy of the source dict
# mysource = copy.copy(source)
#
# # Merge toolbox defaults
# for key, val in toolbox.get('defaults', {}).items():
# mysource[key] = val
#
# # Merge blueprint defaults
# for key, val in blueprint.get('defaults', {}).items():
# mysource[key] = val
#
# # Merge set permutation
# for key, val in options:
# mysource[key] = val
#
# # Bolt it into our real config file
# self.raw_config['sources'].append(mysource)
#
# # Free a tiny bit of memory
# if 'toolbox' in self.raw_config:
# del self.raw_config['toolbox']
#
# if 'blueprint' in self.raw_config:
# del self.raw_config['blueprint']
#
# def get(self, item, default=None):
# """Returns `item` from configuration if it exists, otherwise returns
# `default`
# """
# return self.raw_config.get(item, default)
#
# def __getitem__(self, item):
# return self.raw_config[item]
. Output only the next line. | return duct.makeService(ConfigFile(options['config'])) |
Given the following code snippet before the placeholder: <|code_start|>"""
.. module:: bosun
:synopsis: Bosun output
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
<|code_end|>
, predict the next line using imports from the current file:
import json
import base64
from twisted.internet import defer
from duct.outputs import opentsdb
from duct.utils import HTTPRequest
and context including class names, function names, and sometimes code from other files:
# Path: duct/outputs/opentsdb.py
# class OpenTSDB(Output):
# def __init__(self, *a):
# def createClient(self):
# def stop(self):
# def transformEvent(self, ev):
# def sendEvents(self, events):
# def tick(self):
#
# Path: duct/utils.py
# class HTTPRequest(object):
# """Helper class for creating HTTP requests.
# Accepts a `timeout` to cancel requests which take too long
# """
# def __init__(self, timeout=120):
# self.timeout = timeout
# self.timedout = None
#
# def abort_request(self, request):
# """Called to abort request on timeout"""
# self.timedout = True
# if not request.called:
# try:
# request.cancel()
# except error.AlreadyCancelled:
# return
#
# @defer.inlineCallbacks
# def response(self, request):
# """Response received
# """
# if request.length:
# de = defer.Deferred()
# request.deliverBody(BodyReceiver(de))
# body = yield de
# body = body.read()
# else:
# body = ""
#
# if (request.code < 200) or (request.code > 299):
# raise Exception((request.code, body))
#
# defer.returnValue(body)
#
# def request(self, url, method='GET', headers={}, data=None, socket=None,
# follow_redirect=False):
# """Perform an HTTP request
# """
# self.timedout = False
#
# if socket:
# agent = SocketyAgent(reactor, socket)
# else:
# if url[:5] == 'https':
# if SSL:
# agent = Agent(reactor, WebClientContextFactory())
# else:
# raise Exception('HTTPS requested but not supported')
# else:
# agent = Agent(reactor)
#
# request = agent.request(method.encode(), url.encode(),
# Headers(headers),
# StringProducer(data) if data else None)
#
# if self.timeout:
# timer = reactor.callLater(self.timeout, self.abort_request,
# request)
#
# def timeoutProxy(request):
# """Wrapper function to time-out requests
# """
# if timer.active():
# timer.cancel()
#
# if follow_redirect and (request.code in (301, 302,)):
# location = request.headers.getRawHeaders('location')
# url = request.request.absoluteURI
# if location:
# if not location[0].startswith("http"):
# # Well this isn't really allowed
# if location[0].startswith("/"):
# hp = '/'.join(url.split('/')[:3])
# url = hp + location[0]
# else:
# url = url.rstrip('/') + '/' + location[0]
# else:
# url = location[0]
#
# log.msg("Redirecting to %s" % url)
#
# return self.request(url, method=method, headers=headers,
# data=data, socket=socket,
# follow_redirect=follow_redirect)
# else:
# raise Exception("Server responded with %s code but no"
# " location header" % request.code)
#
# return self.response(request)
#
# def requestAborted(failure):
# """Request was aborted due to timeout
# """
# if timer.active():
# timer.cancel()
#
# failure.trap(defer.CancelledError,
# error.ConnectingCancelledError)
#
# raise Timeout(
# "Request took longer than %s seconds" % self.timeout)
#
# request.addCallback(timeoutProxy).addErrback(requestAborted)
# else:
# request.addCallback(self.response)
#
# return request
#
#
# def getBody(self, url, method='GET', headers={}, data=None, socket=None):
# """Make an HTTP request and return the body
# """
#
# if 'User-Agent' not in headers:
# headers['User-Agent'] = ['Ductd/1']
#
# return self.request(url, method, headers, data, socket)
#
# @defer.inlineCallbacks
# def getJson(self, url, method='GET', headers={}, data=None, socket=None):
# """Fetch a JSON result via HTTP
# """
# if 'Content-Type' not in headers:
# headers['Content-Type'] = ['application/json']
#
# body = yield self.getBody(url, method, headers, data, socket)
#
# try:
# if not body:
# defer.returnValue({})
# response = json.loads(body)
# except ValueError:
# raise ValueError("Response was not JSON: %s" % repr(body))
#
# defer.returnValue(response)
. Output only the next line. | class Bosun(opentsdb.OpenTSDB): |
Given the following code snippet before the placeholder: <|code_start|> :type maxsize: int.
:param maxrate: Maximum rate of documents added to index (default: 100)
:type maxrate: int.
:param interval: Queue check interval in seconds (default: 1.0)
:type interval: int.
:param user: Optional basic auth username
:type user: str.
:param password: Optional basic auth password
:type password: str.
:param debug: Log tracebacks from OpenTSDB
:type debug: bool.
"""
def __init__(self, *a):
opentsdb.OpenTSDB.__init__(self, *a)
self.url = self.url.rstrip('/')
self.metacache = {}
def createMetadata(self, metas):
"""Create metadata objects for new service keys
"""
headers = {}
path = '/api/metadata/put'
if self.user:
authorization = base64.b64encode('%s:%s' % (self.user,
self.password)
).decode()
headers['Authorization'] = ['Basic ' + authorization]
<|code_end|>
, predict the next line using imports from the current file:
import json
import base64
from twisted.internet import defer
from duct.outputs import opentsdb
from duct.utils import HTTPRequest
and context including class names, function names, and sometimes code from other files:
# Path: duct/outputs/opentsdb.py
# class OpenTSDB(Output):
# def __init__(self, *a):
# def createClient(self):
# def stop(self):
# def transformEvent(self, ev):
# def sendEvents(self, events):
# def tick(self):
#
# Path: duct/utils.py
# class HTTPRequest(object):
# """Helper class for creating HTTP requests.
# Accepts a `timeout` to cancel requests which take too long
# """
# def __init__(self, timeout=120):
# self.timeout = timeout
# self.timedout = None
#
# def abort_request(self, request):
# """Called to abort request on timeout"""
# self.timedout = True
# if not request.called:
# try:
# request.cancel()
# except error.AlreadyCancelled:
# return
#
# @defer.inlineCallbacks
# def response(self, request):
# """Response received
# """
# if request.length:
# de = defer.Deferred()
# request.deliverBody(BodyReceiver(de))
# body = yield de
# body = body.read()
# else:
# body = ""
#
# if (request.code < 200) or (request.code > 299):
# raise Exception((request.code, body))
#
# defer.returnValue(body)
#
# def request(self, url, method='GET', headers={}, data=None, socket=None,
# follow_redirect=False):
# """Perform an HTTP request
# """
# self.timedout = False
#
# if socket:
# agent = SocketyAgent(reactor, socket)
# else:
# if url[:5] == 'https':
# if SSL:
# agent = Agent(reactor, WebClientContextFactory())
# else:
# raise Exception('HTTPS requested but not supported')
# else:
# agent = Agent(reactor)
#
# request = agent.request(method.encode(), url.encode(),
# Headers(headers),
# StringProducer(data) if data else None)
#
# if self.timeout:
# timer = reactor.callLater(self.timeout, self.abort_request,
# request)
#
# def timeoutProxy(request):
# """Wrapper function to time-out requests
# """
# if timer.active():
# timer.cancel()
#
# if follow_redirect and (request.code in (301, 302,)):
# location = request.headers.getRawHeaders('location')
# url = request.request.absoluteURI
# if location:
# if not location[0].startswith("http"):
# # Well this isn't really allowed
# if location[0].startswith("/"):
# hp = '/'.join(url.split('/')[:3])
# url = hp + location[0]
# else:
# url = url.rstrip('/') + '/' + location[0]
# else:
# url = location[0]
#
# log.msg("Redirecting to %s" % url)
#
# return self.request(url, method=method, headers=headers,
# data=data, socket=socket,
# follow_redirect=follow_redirect)
# else:
# raise Exception("Server responded with %s code but no"
# " location header" % request.code)
#
# return self.response(request)
#
# def requestAborted(failure):
# """Request was aborted due to timeout
# """
# if timer.active():
# timer.cancel()
#
# failure.trap(defer.CancelledError,
# error.ConnectingCancelledError)
#
# raise Timeout(
# "Request took longer than %s seconds" % self.timeout)
#
# request.addCallback(timeoutProxy).addErrback(requestAborted)
# else:
# request.addCallback(self.response)
#
# return request
#
#
# def getBody(self, url, method='GET', headers={}, data=None, socket=None):
# """Make an HTTP request and return the body
# """
#
# if 'User-Agent' not in headers:
# headers['User-Agent'] = ['Ductd/1']
#
# return self.request(url, method, headers, data, socket)
#
# @defer.inlineCallbacks
# def getJson(self, url, method='GET', headers={}, data=None, socket=None):
# """Fetch a JSON result via HTTP
# """
# if 'Content-Type' not in headers:
# headers['Content-Type'] = ['application/json']
#
# body = yield self.getBody(url, method, headers, data, socket)
#
# try:
# if not body:
# defer.returnValue({})
# response = json.loads(body)
# except ValueError:
# raise ValueError("Response was not JSON: %s" % repr(body))
#
# defer.returnValue(response)
. Output only the next line. | return HTTPRequest().getBody(self.url + path, 'POST', headers=headers, |
Next line prediction: <|code_start|>"""
.. module:: null
:synopsis: Null event output. Does nothing
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
<|code_end|>
. Use current file imports:
(from duct.objects import Output)
and context including class names, function names, or small code snippets from other files:
# Path: duct/objects.py
# class Output(object):
# """Output parent class
#
# Outputs can inherit this object which provides a construct
# for a working output
#
# :param config: Dictionary config for this queue (usually read from the
# yaml configuration)
# :param duct: A DuctService object for interacting with the queue manager
# """
# def __init__(self, config, duct):
# self.config = config
# self.duct = duct
# self.events = []
# self.maxsize = 0
#
# def createClient(self):
# """Deferred which sets up the output
# """
# pass
#
# def eventsReceived(self, events):
# """Receives a list of events and queues them
#
# Arguments:
# events -- list of `duct.objects.Event`
# """
# # Make sure queue isn't oversized
# if self.maxsize > 0:
# if (self.maxsize < 1) or (len(self.events) < self.maxsize):
# self.events.extend(events)
# else:
# self.events.extend(events)
#
# def stop(self):
# """Called when the service shuts down
# """
# pass
. Output only the next line. | class Null(Output): |
Here is a snippet: <|code_start|> return lambda events: caller(self, events)
def start(self):
"""Called when source is started
"""
pass
@defer.inlineCallbacks
def startTimer(self):
"""Starts the timer for this source"""
yield defer.maybeDeferred(self.start)
self.timerDeferred = self.timer.start(self.inter)
if self.use_ssh and self.ssh_connector:
yield defer.maybeDeferred(self.ssh_client.connect)
def stop(self):
"""Called when source is stopped
"""
pass
def stopTimer(self):
"""Stops the timer for this source"""
self.timerDeferred = None
if self.timer.running:
self.timer.stop()
return defer.maybeDeferred(self.stop)
<|code_end|>
. Write the next line using the current file imports:
import hashlib
import time
import socket
import traceback
from twisted.internet import task, defer
from twisted.python import log
from duct.utils import fork
from duct.protocol import ssh
and context from other files:
# Path: duct/utils.py
# def fork(executable, args=(), env={}, path=None, timeout=3600):
# """fork
# Provides a deferred wrapper function with a timeout function
#
# :param executable: Executable
# :type executable: str.
# :param args: Tupple of arguments
# :type args: tupple.
# :param env: Environment dictionary
# :type env: dict.
# :param timeout: Kill the child process if timeout is exceeded
# :type timeout: int.
# """
# de = defer.Deferred()
# proc = ProcessProtocol(de, timeout)
# reactor.spawnProcess(proc, executable, (executable,)+tuple(args), env,
# path)
# return de
#
# Path: duct/protocol/ssh.py
# class FakeLog(object):
# class SSHCommandProtocol(protocol.Protocol):
# class SSHClient(object):
# def msg(self, *a):
# def callWithLogger(self, *a, **kw):
# def __init__(self):
# def connectionMade(self):
# def dataReceived(self, data):
# def extReceived(self, _code, data):
# def connectionLost(self, reason=protocol.connectionDone):
# def __init__(self, hostname, username, port, password=None,
# knownhosts=None):
# def verifyHostKey(self, _ui, hostname, ip, key):
# def gotHasKey(result):
# def addKeyFile(self, kfile, password=None):
# def addKeyString(self, kstring, password=None):
# def _get_endpoint(self):
# def connect(self):
# def connected(protocol):
# def conLost(reason):
# def connectionLost(self, transport, reason):
# def fork(self, command, args=(), env={}, path=None, _timeout=3600):
# def finished(result):
# def connected(connection):
, which may include functions, classes, or code. Output only the next line. | def fork(self, *a, **kw): |
Using the snippet: <|code_start|> """Receives a list of events and queues them
Arguments:
events -- list of `duct.objects.Event`
"""
# Make sure queue isn't oversized
if self.maxsize > 0:
if (self.maxsize < 1) or (len(self.events) < self.maxsize):
self.events.extend(events)
else:
self.events.extend(events)
def stop(self):
"""Called when the service shuts down
"""
pass
class Source(object):
"""Source parent class
Sources can inherit this object which provides a number of
utility methods.
:param config: Dictionary config for this queue (usually read from the
yaml configuration)
:param queueBack: A callback method to recieve a list of Event objects
:param duct: A DuctService object for interacting with the queue manager
"""
sync = False
<|code_end|>
, determine the next line of code. You have imports:
import hashlib
import time
import socket
import traceback
from twisted.internet import task, defer
from twisted.python import log
from duct.utils import fork
from duct.protocol import ssh
and context (class names, function names, or code) available:
# Path: duct/utils.py
# def fork(executable, args=(), env={}, path=None, timeout=3600):
# """fork
# Provides a deferred wrapper function with a timeout function
#
# :param executable: Executable
# :type executable: str.
# :param args: Tupple of arguments
# :type args: tupple.
# :param env: Environment dictionary
# :type env: dict.
# :param timeout: Kill the child process if timeout is exceeded
# :type timeout: int.
# """
# de = defer.Deferred()
# proc = ProcessProtocol(de, timeout)
# reactor.spawnProcess(proc, executable, (executable,)+tuple(args), env,
# path)
# return de
#
# Path: duct/protocol/ssh.py
# class FakeLog(object):
# class SSHCommandProtocol(protocol.Protocol):
# class SSHClient(object):
# def msg(self, *a):
# def callWithLogger(self, *a, **kw):
# def __init__(self):
# def connectionMade(self):
# def dataReceived(self, data):
# def extReceived(self, _code, data):
# def connectionLost(self, reason=protocol.connectionDone):
# def __init__(self, hostname, username, port, password=None,
# knownhosts=None):
# def verifyHostKey(self, _ui, hostname, ip, key):
# def gotHasKey(result):
# def addKeyFile(self, kfile, password=None):
# def addKeyString(self, kstring, password=None):
# def _get_endpoint(self):
# def connect(self):
# def connected(protocol):
# def conLost(reason):
# def connectionLost(self, transport, reason):
# def fork(self, command, args=(), env={}, path=None, _timeout=3600):
# def finished(result):
# def connected(connection):
. Output only the next line. | ssh = False |
Predict the next line for this snippet: <|code_start|>
class TestLogs(unittest.TestCase):
def test_logfollow(self):
try:
os.unlink('test.log.lf')
os.unlink('test.log')
except:
pass
log = open('test.log', 'wt')
log.write('foo\nbar\n')
log.flush()
<|code_end|>
with the help of current file imports:
from twisted.trial import unittest
from duct.logs import follower, parsers
import datetime
import os
and context from other files:
# Path: duct/logs/follower.py
# class LogFollower(object):
# def __init__(self, logfile, parser=None, tmp_path="/var/lib/duct/",
# history=False):
# def cleanStore(self):
# def storeLast(self):
# def readLast(self):
# def get_fn(self, fn, max_lines=None):
# def get(self, max_lines=None):
#
# Path: duct/logs/parsers.py
# class ApacheLogParserError(Exception):
# class ApacheLogParser(object):
# def __init__(self, fmt):
# def _parse_date(self, date):
# def alias(self, field):
# def _parse_format(self, fmt):
# def parse(self, line):
# def pattern(self):
# def names(self):
, which may contain function names, class names, or code. Output only the next line. | f = follower.LogFollower('test.log', tmp_path=".", history=True) |
Given the code snippet: <|code_start|> self.assertEqual(r2, [])
self.assertEqual(r3[0], 'testing')
log.close()
# Move inode
os.rename('test.log', 'testold.log')
log = open('test.log', 'wt')
log.write('foo2\nbar2\n')
log.close()
r = f.get()
self.assertEqual(r[0], 'foo2')
self.assertEqual(r[1], 'bar2')
# Go backwards
log = open('test.log', 'wt')
log.write('foo3\n')
log.close()
r = f.get()
self.assertEqual(r[0], 'foo3')
os.unlink('test.log')
os.unlink('testold.log')
def test_apache_parser(self):
<|code_end|>
, generate the next line using the imports in this file:
from twisted.trial import unittest
from duct.logs import follower, parsers
import datetime
import os
and context (functions, classes, or occasionally code) from other files:
# Path: duct/logs/follower.py
# class LogFollower(object):
# def __init__(self, logfile, parser=None, tmp_path="/var/lib/duct/",
# history=False):
# def cleanStore(self):
# def storeLast(self):
# def readLast(self):
# def get_fn(self, fn, max_lines=None):
# def get(self, max_lines=None):
#
# Path: duct/logs/parsers.py
# class ApacheLogParserError(Exception):
# class ApacheLogParser(object):
# def __init__(self, fmt):
# def _parse_date(self, date):
# def alias(self, field):
# def _parse_format(self, fmt):
# def parse(self, line):
# def pattern(self):
# def names(self):
. Output only the next line. | log = parsers.ApacheLogParser('combined') |
Using the snippet: <|code_start|> pbevent.metric_d = float(event.metric)
pbevent.metric_f = float(event.metric)
if event.attributes is not None:
for key, value in event.attributes.items():
attribute = pbevent.attributes.add()
attribute.key, attribute.value = key, value
return pbevent
def encodeMessage(self, events):
"""Encode a list of Duct events with protobuf"""
encoded = [self.encodeEvent(ev) for ev in events
if ev.evtype == 'metric']
return proto_pb2.Msg(events=encoded).SerializeToString()
def decodeMessage(self, data):
"""Decode a protobuf message into a list of Duct events"""
message = proto_pb2.Msg()
message.ParseFromString(data)
return message
def sendEvents(self, events):
"""Send a Duct Event to Riemann"""
self.pressure += 1
self.sendString(self.encodeMessage(events))
<|code_end|>
, determine the next line of code. You have imports:
from duct.ihateprotobuf import proto_pb2
from duct.interfaces import IDuctProtocol
from zope.interface import implementer
from twisted.protocols.basic import Int32StringReceiver
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import protocol
from twisted.python import log
and context (class names, function names, or code) available:
# Path: duct/interfaces.py
# class IDuctProtocol(Interface):
# """Interface for Duct client protocols"""
#
# def sendEvent(self, event):
# """Sends an event to this client"""
# pass
. Output only the next line. | @implementer(IDuctProtocol) |
Using the snippet: <|code_start|>"""
.. module:: opentsdb
:synopsis: OpenTSDB output
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
<|code_end|>
, determine the next line of code. You have imports:
from twisted.internet import defer, task
from twisted.python import log
from duct.objects import Output
from duct.protocol.opentsdb import OpenTSDBClient
and context (class names, function names, or code) available:
# Path: duct/objects.py
# class Output(object):
# """Output parent class
#
# Outputs can inherit this object which provides a construct
# for a working output
#
# :param config: Dictionary config for this queue (usually read from the
# yaml configuration)
# :param duct: A DuctService object for interacting with the queue manager
# """
# def __init__(self, config, duct):
# self.config = config
# self.duct = duct
# self.events = []
# self.maxsize = 0
#
# def createClient(self):
# """Deferred which sets up the output
# """
# pass
#
# def eventsReceived(self, events):
# """Receives a list of events and queues them
#
# Arguments:
# events -- list of `duct.objects.Event`
# """
# # Make sure queue isn't oversized
# if self.maxsize > 0:
# if (self.maxsize < 1) or (len(self.events) < self.maxsize):
# self.events.extend(events)
# else:
# self.events.extend(events)
#
# def stop(self):
# """Called when the service shuts down
# """
# pass
#
# Path: duct/protocol/opentsdb.py
# class OpenTSDBClient(object):
# """Twisted ElasticSearch API
# """
# def __init__(self, url='http://localhost:4242', user=None, password=None):
# self.url = url.rstrip('/')
# self.user = user
# self.password = password
#
# def _request(self, path, data=None, method='POST'):
# headers = {}
# if self.user:
# authorization = b64encode('%s:%s' % (self.user, self.password)
# ).decode()
# headers['Authorization'] = ['Basic ' + authorization]
#
# return utils.HTTPRequest().getJson(
# self.url + path, method, headers=headers, data=data.encode())
#
# def put(self, data):
# """Put one or more metrics
# """
# return self._request('/api/put', json.dumps(data))
. Output only the next line. | class OpenTSDB(Output): |
Based on the snippet: <|code_start|> :param password: Optional basic auth password
:type password: str
:param debug: Log tracebacks from OpenTSDB
:type debug: str
"""
def __init__(self, *a):
Output.__init__(self, *a)
self.events = []
self.timer = task.LoopingCall(self.tick)
self.inter = float(self.config.get('interval', 1.0)) # tick interval
self.maxsize = int(self.config.get('maxsize', 250000))
self.user = self.config.get('user')
self.password = self.config.get('password')
self.client = None
self.url = self.config.get('url', 'http://localhost:4242')
maxrate = int(self.config.get('maxrate', 100))
if maxrate > 0:
self.queueDepth = int(maxrate * self.inter)
else:
self.queueDepth = None
def createClient(self):
"""Sets up HTTP connector and starts queue timer
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from twisted.internet import defer, task
from twisted.python import log
from duct.objects import Output
from duct.protocol.opentsdb import OpenTSDBClient
and context (classes, functions, sometimes code) from other files:
# Path: duct/objects.py
# class Output(object):
# """Output parent class
#
# Outputs can inherit this object which provides a construct
# for a working output
#
# :param config: Dictionary config for this queue (usually read from the
# yaml configuration)
# :param duct: A DuctService object for interacting with the queue manager
# """
# def __init__(self, config, duct):
# self.config = config
# self.duct = duct
# self.events = []
# self.maxsize = 0
#
# def createClient(self):
# """Deferred which sets up the output
# """
# pass
#
# def eventsReceived(self, events):
# """Receives a list of events and queues them
#
# Arguments:
# events -- list of `duct.objects.Event`
# """
# # Make sure queue isn't oversized
# if self.maxsize > 0:
# if (self.maxsize < 1) or (len(self.events) < self.maxsize):
# self.events.extend(events)
# else:
# self.events.extend(events)
#
# def stop(self):
# """Called when the service shuts down
# """
# pass
#
# Path: duct/protocol/opentsdb.py
# class OpenTSDBClient(object):
# """Twisted ElasticSearch API
# """
# def __init__(self, url='http://localhost:4242', user=None, password=None):
# self.url = url.rstrip('/')
# self.user = user
# self.password = password
#
# def _request(self, path, data=None, method='POST'):
# headers = {}
# if self.user:
# authorization = b64encode('%s:%s' % (self.user, self.password)
# ).decode()
# headers['Authorization'] = ['Basic ' + authorization]
#
# return utils.HTTPRequest().getJson(
# self.url + path, method, headers=headers, data=data.encode())
#
# def put(self, data):
# """Put one or more metrics
# """
# return self._request('/api/put', json.dumps(data))
. Output only the next line. | self.client = OpenTSDBClient(self.url, self.user, self.password) |
Predict the next line after this snippet: <|code_start|>
self.decode_samples(u)
# Sort samples by sequence number
self.samples.sort(key=lambda x: x.sequence)
def decode_samples(self, u):
"""Decode samples received
"""
for _i in range(self.sample_count):
sample_type = u.unpack_uint()
self.samples.append(self.samplers[sample_type](u))
class FlowSample(object):
"""Flow sample object
"""
def __init__(self, u):
self.size = u.unpack_uint()
self.sequence = u.unpack_uint()
self.source_id = u.unpack_uint()
self.sample_rate = u.unpack_uint()
self.sample_pool = u.unpack_uint()
self.dropped_packets = u.unpack_uint()
self.if_inIndex = u.unpack_uint()
self.if_outIndex = u.unpack_uint()
self.record_count = u.unpack_uint()
<|code_end|>
using the current file's imports:
import xdrlib
from duct.protocol.sflow.protocol import flows, counters
and any relevant context from other files:
# Path: duct/protocol/sflow/protocol/flows.py
# class IPv4Header(object):
# class ISO8023Header(object):
# class IPv6Header(object):
# class IEEE80211MACHeader(object):
# class PPPHeader(object):
# class HeaderSample(object):
# class EthernetSample(object):
# class IPV4Sample(object):
# class IPV6Sample(object):
# class SwitchSample(object):
# class RouterSample(object):
# class GatewaySample(object):
# class UserSample(object):
# class URLSample(object):
# class MPLSSample(object):
# class NATSample(object):
# class MPLSTunnelSample(object):
# class MPLSVCSample(object):
# class MPLSFTNSample(object):
# class MPLSLDPFECSample(object):
# class VLANTunnelSample(object):
# def __init__(self, data):
# def __init__(self, data):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
#
# Path: duct/protocol/sflow/protocol/counters.py
# class InterfaceCounters(object):
# class EthernetCounters(object):
# class VLANCounters(object):
# class TokenringCounters(object):
# class VGCounters(object):
# class HostCounters(object):
# class HostAdapters(object):
# class HostParent(object):
# class HostCPUCounters(object):
# class HostMemoryCounters(object):
# class DiskIOCounters(object):
# class NetIOCounters(object):
# class SocketIPv4Counters(object):
# class SocketIPv6Counters(object):
# class VirtMemoryCounters(object):
# class VirtDiskIOCounters(object):
# class VirtNetIOCounters(object):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
. Output only the next line. | self.flows = {} |
Predict the next line for this snippet: <|code_start|> self.dropped_packets = u.unpack_uint()
self.if_inIndex = u.unpack_uint()
self.if_outIndex = u.unpack_uint()
self.record_count = u.unpack_uint()
self.flows = {}
for _i in range(self.record_count):
flow_format = u.unpack_uint()
flow_head = u.unpack_opaque()
flow_u = xdrlib.Unpacker(flow_head)
d = flows.getDecoder(flow_format)
if d:
self.flows[flow_format] = d(flow_u)
class CounterSample(object):
"""Counter sample object
"""
def __init__(self, u):
self.size = u.unpack_uint()
self.sequence = u.unpack_uint()
self.source_id = u.unpack_uint()
self.record_count = u.unpack_uint()
<|code_end|>
with the help of current file imports:
import xdrlib
from duct.protocol.sflow.protocol import flows, counters
and context from other files:
# Path: duct/protocol/sflow/protocol/flows.py
# class IPv4Header(object):
# class ISO8023Header(object):
# class IPv6Header(object):
# class IEEE80211MACHeader(object):
# class PPPHeader(object):
# class HeaderSample(object):
# class EthernetSample(object):
# class IPV4Sample(object):
# class IPV6Sample(object):
# class SwitchSample(object):
# class RouterSample(object):
# class GatewaySample(object):
# class UserSample(object):
# class URLSample(object):
# class MPLSSample(object):
# class NATSample(object):
# class MPLSTunnelSample(object):
# class MPLSVCSample(object):
# class MPLSFTNSample(object):
# class MPLSLDPFECSample(object):
# class VLANTunnelSample(object):
# def __init__(self, data):
# def __init__(self, data):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
#
# Path: duct/protocol/sflow/protocol/counters.py
# class InterfaceCounters(object):
# class EthernetCounters(object):
# class VLANCounters(object):
# class TokenringCounters(object):
# class VGCounters(object):
# class HostCounters(object):
# class HostAdapters(object):
# class HostParent(object):
# class HostCPUCounters(object):
# class HostMemoryCounters(object):
# class DiskIOCounters(object):
# class NetIOCounters(object):
# class SocketIPv4Counters(object):
# class SocketIPv6Counters(object):
# class VirtMemoryCounters(object):
# class VirtDiskIOCounters(object):
# class VirtNetIOCounters(object):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
, which may contain function names, class names, or code. Output only the next line. | self.counters = {} |
Predict the next line after this snippet: <|code_start|>"""
.. module:: server
:synopsis: SFlow UDP server
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
class DatagramReceiver(DatagramProtocol):
"""DatagramReceiver for sFlow packets
"""
def datagramReceived(self, data, address):
host, _port = address
<|code_end|>
using the current file's imports:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from duct.protocol.sflow import protocol
from duct.protocol.sflow.protocol import flows, counters
and any relevant context from other files:
# Path: duct/protocol/sflow/protocol/protocol.py
# class Sflow(object):
# class FlowSample(object):
# class CounterSample(object):
# def __init__(self, payload, host):
# def sflow_v5(self, u):
# def decode_samples(self, u):
# def __init__(self, u):
# def __init__(self, u):
#
# Path: duct/protocol/sflow/protocol/flows.py
# class IPv4Header(object):
# class ISO8023Header(object):
# class IPv6Header(object):
# class IEEE80211MACHeader(object):
# class PPPHeader(object):
# class HeaderSample(object):
# class EthernetSample(object):
# class IPV4Sample(object):
# class IPV6Sample(object):
# class SwitchSample(object):
# class RouterSample(object):
# class GatewaySample(object):
# class UserSample(object):
# class URLSample(object):
# class MPLSSample(object):
# class NATSample(object):
# class MPLSTunnelSample(object):
# class MPLSVCSample(object):
# class MPLSFTNSample(object):
# class MPLSLDPFECSample(object):
# class VLANTunnelSample(object):
# def __init__(self, data):
# def __init__(self, data):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
#
# Path: duct/protocol/sflow/protocol/counters.py
# class InterfaceCounters(object):
# class EthernetCounters(object):
# class VLANCounters(object):
# class TokenringCounters(object):
# class VGCounters(object):
# class HostCounters(object):
# class HostAdapters(object):
# class HostParent(object):
# class HostCPUCounters(object):
# class HostMemoryCounters(object):
# class DiskIOCounters(object):
# class NetIOCounters(object):
# class SocketIPv4Counters(object):
# class SocketIPv6Counters(object):
# class VirtMemoryCounters(object):
# class VirtDiskIOCounters(object):
# class VirtNetIOCounters(object):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
. Output only the next line. | sflow = protocol.Sflow(data, host) |
Using the snippet: <|code_start|>"""
.. module:: server
:synopsis: SFlow UDP server
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
class DatagramReceiver(DatagramProtocol):
"""DatagramReceiver for sFlow packets
"""
def datagramReceived(self, data, address):
host, _port = address
sflow = protocol.Sflow(data, host)
for sample in sflow.samples:
if isinstance(sample, protocol.FlowSample):
self.process_flow_sample(sflow, sample)
if isinstance(sample, protocol.CounterSample):
self.process_counter_sample(sflow, sample)
def process_flow_sample(self, sflow, flow):
"""Process an incomming flow sample
"""
<|code_end|>
, determine the next line of code. You have imports:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from duct.protocol.sflow import protocol
from duct.protocol.sflow.protocol import flows, counters
and context (class names, function names, or code) available:
# Path: duct/protocol/sflow/protocol/protocol.py
# class Sflow(object):
# class FlowSample(object):
# class CounterSample(object):
# def __init__(self, payload, host):
# def sflow_v5(self, u):
# def decode_samples(self, u):
# def __init__(self, u):
# def __init__(self, u):
#
# Path: duct/protocol/sflow/protocol/flows.py
# class IPv4Header(object):
# class ISO8023Header(object):
# class IPv6Header(object):
# class IEEE80211MACHeader(object):
# class PPPHeader(object):
# class HeaderSample(object):
# class EthernetSample(object):
# class IPV4Sample(object):
# class IPV6Sample(object):
# class SwitchSample(object):
# class RouterSample(object):
# class GatewaySample(object):
# class UserSample(object):
# class URLSample(object):
# class MPLSSample(object):
# class NATSample(object):
# class MPLSTunnelSample(object):
# class MPLSVCSample(object):
# class MPLSFTNSample(object):
# class MPLSLDPFECSample(object):
# class VLANTunnelSample(object):
# def __init__(self, data):
# def __init__(self, data):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
#
# Path: duct/protocol/sflow/protocol/counters.py
# class InterfaceCounters(object):
# class EthernetCounters(object):
# class VLANCounters(object):
# class TokenringCounters(object):
# class VGCounters(object):
# class HostCounters(object):
# class HostAdapters(object):
# class HostParent(object):
# class HostCPUCounters(object):
# class HostMemoryCounters(object):
# class DiskIOCounters(object):
# class NetIOCounters(object):
# class SocketIPv4Counters(object):
# class SocketIPv6Counters(object):
# class VirtMemoryCounters(object):
# class VirtDiskIOCounters(object):
# class VirtNetIOCounters(object):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
. Output only the next line. | for v in flow.flows.values(): |
Using the snippet: <|code_start|>.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
class DatagramReceiver(DatagramProtocol):
"""DatagramReceiver for sFlow packets
"""
def datagramReceived(self, data, address):
host, _port = address
sflow = protocol.Sflow(data, host)
for sample in sflow.samples:
if isinstance(sample, protocol.FlowSample):
self.process_flow_sample(sflow, sample)
if isinstance(sample, protocol.CounterSample):
self.process_counter_sample(sflow, sample)
def process_flow_sample(self, sflow, flow):
"""Process an incomming flow sample
"""
for v in flow.flows.values():
if isinstance(v, flows.HeaderSample) and v.frame:
reactor.callLater(0, self.receive_flow, flow, v.frame,
sflow.host)
def process_counter_sample(self, sflow, counter):
"""Process an incomming counter sample
"""
<|code_end|>
, determine the next line of code. You have imports:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from duct.protocol.sflow import protocol
from duct.protocol.sflow.protocol import flows, counters
and context (class names, function names, or code) available:
# Path: duct/protocol/sflow/protocol/protocol.py
# class Sflow(object):
# class FlowSample(object):
# class CounterSample(object):
# def __init__(self, payload, host):
# def sflow_v5(self, u):
# def decode_samples(self, u):
# def __init__(self, u):
# def __init__(self, u):
#
# Path: duct/protocol/sflow/protocol/flows.py
# class IPv4Header(object):
# class ISO8023Header(object):
# class IPv6Header(object):
# class IEEE80211MACHeader(object):
# class PPPHeader(object):
# class HeaderSample(object):
# class EthernetSample(object):
# class IPV4Sample(object):
# class IPV6Sample(object):
# class SwitchSample(object):
# class RouterSample(object):
# class GatewaySample(object):
# class UserSample(object):
# class URLSample(object):
# class MPLSSample(object):
# class NATSample(object):
# class MPLSTunnelSample(object):
# class MPLSVCSample(object):
# class MPLSFTNSample(object):
# class MPLSLDPFECSample(object):
# class VLANTunnelSample(object):
# def __init__(self, data):
# def __init__(self, data):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
#
# Path: duct/protocol/sflow/protocol/counters.py
# class InterfaceCounters(object):
# class EthernetCounters(object):
# class VLANCounters(object):
# class TokenringCounters(object):
# class VGCounters(object):
# class HostCounters(object):
# class HostAdapters(object):
# class HostParent(object):
# class HostCPUCounters(object):
# class HostMemoryCounters(object):
# class DiskIOCounters(object):
# class NetIOCounters(object):
# class SocketIPv4Counters(object):
# class SocketIPv6Counters(object):
# class VirtMemoryCounters(object):
# class VirtDiskIOCounters(object):
# class VirtNetIOCounters(object):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def __init__(self, u):
# def getDecoder(fmt):
. Output only the next line. | for v in counter.counters.values(): |
Continue the code snippet: <|code_start|>"""
.. module:: elasticsearch
:synopsis: Elasticsearch protocol module
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
class ElasticSearch(object):
"""Twisted ElasticSearch API
"""
def __init__(self, url='http://localhost:9200', user=None, password=None,
index='duct-%Y.%m.%d'):
self.url = url.rstrip('/')
self.index = index
self.user = user
self.password = password
def _get_index(self):
return time.strftime(self.index)
def _request(self, path, data=None, method='GET'):
headers = {}
if self.user:
authorization = b64encode('%s:%s' % (self.user, self.password)
).decode()
headers['Authorization'] = ['Basic ' + authorization]
<|code_end|>
. Use current file imports:
import time
import uuid
import json
from base64 import b64encode
from duct import utils
and context (classes, functions, or code) from other files:
# Path: duct/utils.py
# def wait(msecs):
# def __init__(self, react, path, **kwargs):
# def _getEndpoint(self, *_a):
# def reverseNameFromIPAddress(address):
# def __init__(self):
# def reverse(self, ip):
# def _ret(result, ip):
# def __init__(self, finished):
# def dataReceived(self, data):
# def connectionLost(self, *_r):
# def __init__(self, body):
# def startProducing(self, consumer):
# def pauseProducing(self):
# def stopProducing(self):
# def __init__(self, deferred, timeout):
# def outReceived(self, data):
# def errReceived(self, data):
# def processEnded(self, reason):
# def connectionMade(self):
# def killIfAlive():
# def fork(executable, args=(), env={}, path=None, timeout=3600):
# def getContext(self, *_a):
# def __init__(self, timeout=120):
# def abort_request(self, request):
# def response(self, request):
# def request(self, url, method='GET', headers={}, data=None, socket=None,
# follow_redirect=False):
# def timeoutProxy(request):
# def requestAborted(failure):
# def getBody(self, url, method='GET', headers={}, data=None, socket=None):
# def getJson(self, url, method='GET', headers={}, data=None, socket=None):
# def __init__(self, location='/var/lib/duct/cache'):
# def _changed(self):
# def _acquire_cache(self):
# def _write_cache(self, data):
# def _persist(self):
# def _read(self):
# def _remove_key(self, key):
# def expire(self, age):
# def set(self, key, val):
# def get(self, k):
# def contains(self, k):
# def delete(self, k):
# class SocketyAgent(Agent):
# class Timeout(Exception):
# class Resolver(object):
# class BodyReceiver(protocol.Protocol):
# class StringProducer(object):
# class ProcessProtocol(protocol.ProcessProtocol):
# class WebClientContextFactory(ClientContextFactory):
# class HTTPRequest(object):
# class PersistentCache(object):
# SSL = True
# SSL = False
. Output only the next line. | return utils.HTTPRequest().getJson( |
Using the snippet: <|code_start|>
self.inter = float(self.config.get('interval', 1.0)) # tick interval
self.pressure = int(self.config.get('pressure', -1))
self.maxsize = int(self.config.get('maxsize', 250000))
self.expire = self.config.get('expire', False)
self.allow_nan = self.config.get('allow_nan', True)
self.factory = None
self.connector = None
maxrate = int(self.config.get('maxrate', 0))
if maxrate > 0:
self.queueDepth = int(maxrate * self.inter)
else:
self.queueDepth = None
self.tls = self.config.get('tls', False)
if self.tls:
self.cert = self.config['cert']
self.key = self.config['key']
def createClient(self):
"""Create a TCP connection to Riemann with automatic reconnection
"""
server = self.config.get('server', 'localhost')
port = self.config.get('port', 5555)
failover = self.config.get('failover', False)
<|code_end|>
, determine the next line of code. You have imports:
import time
import random
from twisted.internet import reactor, defer, task
from twisted.python import log
from OpenSSL import SSL
from twisted.internet import ssl
from duct.protocol import riemann
from duct.objects import Output
and context (class names, function names, or code) available:
# Path: duct/protocol/riemann.py
# class RiemannProtobufMixin(object):
# class RiemannProtocol(Int32StringReceiver, RiemannProtobufMixin):
# class RiemannClientFactory(protocol.ReconnectingClientFactory):
# class RiemannUDP(DatagramProtocol, RiemannProtobufMixin):
# def __init__(self):
# def encodeEvent(self, event):
# def encodeMessage(self, events):
# def decodeMessage(self, data):
# def sendEvents(self, events):
# def stringReceived(self, string):
# def __init__(self, hosts, failover=False):
# def buildProtocol(self, addr):
# def _do_failover(self, connector):
# def clientConnectionLost(self, connector, reason):
# def clientConnectionFailed(self, connector, reason):
# def __init__(self, host, port):
# def sendString(self, string):
#
# Path: duct/objects.py
# class Output(object):
# """Output parent class
#
# Outputs can inherit this object which provides a construct
# for a working output
#
# :param config: Dictionary config for this queue (usually read from the
# yaml configuration)
# :param duct: A DuctService object for interacting with the queue manager
# """
# def __init__(self, config, duct):
# self.config = config
# self.duct = duct
# self.events = []
# self.maxsize = 0
#
# def createClient(self):
# """Deferred which sets up the output
# """
# pass
#
# def eventsReceived(self, events):
# """Receives a list of events and queues them
#
# Arguments:
# events -- list of `duct.objects.Event`
# """
# # Make sure queue isn't oversized
# if self.maxsize > 0:
# if (self.maxsize < 1) or (len(self.events) < self.maxsize):
# self.events.extend(events)
# else:
# self.events.extend(events)
#
# def stop(self):
# """Called when the service shuts down
# """
# pass
. Output only the next line. | self.factory = riemann.RiemannClientFactory(server, failover=failover) |
Based on the snippet: <|code_start|> :synopsis: Riemann output
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
# pylint: disable=C0412
try:
except:
SSL = None
if SSL:
class ClientTLSContext(ssl.ClientContextFactory):
"""SSL Context factory
"""
def __init__(self, key, cert):
self.key = key
self.cert = cert
def getContext(self):
self.method = SSL.TLSv1_METHOD
ctx = ssl.ClientContextFactory.getContext(self)
ctx.use_certificate_file(self.cert)
ctx.use_privatekey_file(self.key)
return ctx
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import random
from twisted.internet import reactor, defer, task
from twisted.python import log
from OpenSSL import SSL
from twisted.internet import ssl
from duct.protocol import riemann
from duct.objects import Output
and context (classes, functions, sometimes code) from other files:
# Path: duct/protocol/riemann.py
# class RiemannProtobufMixin(object):
# class RiemannProtocol(Int32StringReceiver, RiemannProtobufMixin):
# class RiemannClientFactory(protocol.ReconnectingClientFactory):
# class RiemannUDP(DatagramProtocol, RiemannProtobufMixin):
# def __init__(self):
# def encodeEvent(self, event):
# def encodeMessage(self, events):
# def decodeMessage(self, data):
# def sendEvents(self, events):
# def stringReceived(self, string):
# def __init__(self, hosts, failover=False):
# def buildProtocol(self, addr):
# def _do_failover(self, connector):
# def clientConnectionLost(self, connector, reason):
# def clientConnectionFailed(self, connector, reason):
# def __init__(self, host, port):
# def sendString(self, string):
#
# Path: duct/objects.py
# class Output(object):
# """Output parent class
#
# Outputs can inherit this object which provides a construct
# for a working output
#
# :param config: Dictionary config for this queue (usually read from the
# yaml configuration)
# :param duct: A DuctService object for interacting with the queue manager
# """
# def __init__(self, config, duct):
# self.config = config
# self.duct = duct
# self.events = []
# self.maxsize = 0
#
# def createClient(self):
# """Deferred which sets up the output
# """
# pass
#
# def eventsReceived(self, events):
# """Receives a list of events and queues them
#
# Arguments:
# events -- list of `duct.objects.Event`
# """
# # Make sure queue isn't oversized
# if self.maxsize > 0:
# if (self.maxsize < 1) or (len(self.events) < self.maxsize):
# self.events.extend(events)
# else:
# self.events.extend(events)
#
# def stop(self):
# """Called when the service shuts down
# """
# pass
. Output only the next line. | class RiemannTCP(Output): |
Using the snippet: <|code_start|>COtzWOQ1H0ii478rbQAxwsOEMdR5lxEFOo8mC0p4mnWJti2DzJQorQC/fjbRRv7z
vfJamXvfEuHj3NPP9cumrskBtD+kRz/c2zgVJ8vwRgNPazdfJqGYjmFB0loVVyuu
x+hBHOD5zyMPFrJW9MNDTiTEaQREaje5tUOfNoA1Wa4s2bVLnhHCXdMSWmiDmJQp
HEYAIZI2OJhMe8V431t6dBx+nutApzParWqET5D0DWvlurDWFrHMnazh164RqsGu
E4Dg6ZsRnI+PEJmroia6gYEscUfd5QSUebxIeLhNzo1Kf5JRBW93NNxhAzn9ZJ9O
2bjvkHOJlADnfON5TsPgroXX95P/9V8DWUT+/ske1Fw43V1pIT+PtraYqrlyvow+
uJMA2q9sRLzXnFb2vg7JdD1XA4f2eUBwzbtq8wSuQexSErWaTx5uAERDnGAWyaN2
3xCYl8CTfF70xN7j39hG/pI0ghRLGVBmCJ5NRzNZ80SPBE/nzYy/X6pGV+vsjPoZ
S3dBmvlBV/HzB4ljsO2pI/VjCJVNZdOWDzy18GQ/jt8/xH8R9Ld6/6tuS0HbiefS
ZefHS5wV1KNZBK+vh08HvX/AY9WBHPH+DEbrpymn/9oAKVmhH+f73ADqVOanMPk0
-----END RSA PRIVATE KEY-----
"""
testKeyPassword = "testtest"
class FakeDuct(object):
config = {
'ssh_username': 'test',
'ssh_key': testKey,
'ssh_keypass': testKeyPassword,
}
inter = 1.0
ttl = 60.0
hostConnectorCache = {}
class Tests(unittest.TestCase):
def _qb(self, result):
pass
def test_ssh_source_setup(self):
<|code_end|>
, determine the next line of code. You have imports:
from twisted.trial import unittest
from duct.sources.linux import basic
and context (class names, function names, or code) available:
# Path: duct/sources/linux/basic.py
# class LoadAverage(Source):
# class DiskIO(Source):
# class CPU(Source):
# class Memory(Source):
# class DiskFree(Source):
# class Network(Source):
# def _parse_loadaverage(self, data):
# def get(self):
# def sshGet(self):
# def __init__(self, *a, **kw):
# def _parse_stats(self, stats):
# def sshGet(self):
# def _getstats(self):
# def get(self):
# def __init__(self, *a):
# def _read_proc_stat(self):
# def _calculate_metrics(self, stat):
# def _transpose_metrics(self, metrics, prefix):
# def sshGet(self):
# def get(self):
# def _parse_stats(self, mem):
# def get(self):
# def sshGet(self):
# def get(self):
# def _parse_stats(self, stats):
# def _readStats(self):
# def sshGet(self):
# def get(self):
. Output only the next line. | s = basic.LoadAverage({ |
Predict the next line after this snippet: <|code_start|> :type index: str
"""
def __init__(self, *a):
Output.__init__(self, *a)
self.events = []
self.timer = task.LoopingCall(self.tick)
self.inter = float(self.config.get('interval', 1.0)) # tick interval
self.maxsize = int(self.config.get('maxsize', 250000))
self.user = self.config.get('user')
self.password = self.config.get('password')
self.url = self.config.get('url', 'http://localhost:9200')
maxrate = int(self.config.get('maxrate', 100))
self.index = self.config.get('index', 'duct-%Y.%m.%d')
self.client = None
if maxrate > 0:
self.queueDepth = int(maxrate * self.inter)
else:
self.queueDepth = None
def createClient(self):
"""Sets up HTTP connector and starts queue timer
"""
<|code_end|>
using the current file's imports:
import datetime
from twisted.internet import defer, task
from twisted.python import log
from duct.protocol import elasticsearch
from duct.objects import Output
and any relevant context from other files:
# Path: duct/protocol/elasticsearch.py
# class ElasticSearch(object):
# def __init__(self, url='http://localhost:9200', user=None, password=None,
# index='duct-%Y.%m.%d'):
# def _get_index(self):
# def _request(self, path, data=None, method='GET'):
# def _gen_id(self):
# def stats(self):
# def node_stats(self):
# def insertIndex(self, index_type, data):
# def bulkIndex(self, data):
#
# Path: duct/objects.py
# class Output(object):
# """Output parent class
#
# Outputs can inherit this object which provides a construct
# for a working output
#
# :param config: Dictionary config for this queue (usually read from the
# yaml configuration)
# :param duct: A DuctService object for interacting with the queue manager
# """
# def __init__(self, config, duct):
# self.config = config
# self.duct = duct
# self.events = []
# self.maxsize = 0
#
# def createClient(self):
# """Deferred which sets up the output
# """
# pass
#
# def eventsReceived(self, events):
# """Receives a list of events and queues them
#
# Arguments:
# events -- list of `duct.objects.Event`
# """
# # Make sure queue isn't oversized
# if self.maxsize > 0:
# if (self.maxsize < 1) or (len(self.events) < self.maxsize):
# self.events.extend(events)
# else:
# self.events.extend(events)
#
# def stop(self):
# """Called when the service shuts down
# """
# pass
. Output only the next line. | self.client = elasticsearch.ElasticSearch(self.url, self.user, |
Predict the next line for this snippet: <|code_start|>"""
.. module:: elasticsearch
:synopsis: Elasticsearch event output
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
<|code_end|>
with the help of current file imports:
import datetime
from twisted.internet import defer, task
from twisted.python import log
from duct.protocol import elasticsearch
from duct.objects import Output
and context from other files:
# Path: duct/protocol/elasticsearch.py
# class ElasticSearch(object):
# def __init__(self, url='http://localhost:9200', user=None, password=None,
# index='duct-%Y.%m.%d'):
# def _get_index(self):
# def _request(self, path, data=None, method='GET'):
# def _gen_id(self):
# def stats(self):
# def node_stats(self):
# def insertIndex(self, index_type, data):
# def bulkIndex(self, data):
#
# Path: duct/objects.py
# class Output(object):
# """Output parent class
#
# Outputs can inherit this object which provides a construct
# for a working output
#
# :param config: Dictionary config for this queue (usually read from the
# yaml configuration)
# :param duct: A DuctService object for interacting with the queue manager
# """
# def __init__(self, config, duct):
# self.config = config
# self.duct = duct
# self.events = []
# self.maxsize = 0
#
# def createClient(self):
# """Deferred which sets up the output
# """
# pass
#
# def eventsReceived(self, events):
# """Receives a list of events and queues them
#
# Arguments:
# events -- list of `duct.objects.Event`
# """
# # Make sure queue isn't oversized
# if self.maxsize > 0:
# if (self.maxsize < 1) or (len(self.events) < self.maxsize):
# self.events.extend(events)
# else:
# self.events.extend(events)
#
# def stop(self):
# """Called when the service shuts down
# """
# pass
, which may contain function names, class names, or code. Output only the next line. | class ElasticSearch(Output): |
Here is a snippet: <|code_start|> IATP=0x75,
STP=0x76,
SRP=0x77,
UTI=0x78,
SMP=0x79,
SM=0x7A,
PTP=0x7B,
ISIS=0x7C,
FIRE=0x7D,
CRTP=0x7E,
CRUDP=0x7F,
SSCOPMCE=0x80,
IPLT=0x81,
SPS=0x82,
SCTP=0x84,
FC=0x85,
UDPLite=0x88,
MPLSoIP=0x89,
manet=0x8A,
HIP=0x8B,
Shim6=0x8C,
WESP=0x8D,
ROHC=0x8E),
UBInt16("checksum"),
UBInt32("src"),
UBInt32("dst"),
)
self.ip = ip.parse(data[:ip.sizeof()])
<|code_end|>
. Write the next line using the current file imports:
from construct import (BitStruct,
Bits,
Bytes,
Const,
EmbeddedBitStruct,
Enum,
Flag,
Nibble,
Padding,
Struct,
UBInt8,
UBInt16,
UBInt32)
from construct.adapters import MappingError
from duct.protocol.sflow.protocol import utils
from twisted.python import log
and context from other files:
# Path: duct/protocol/sflow/protocol/utils.py
# def unpack_address(u):
# def __init__(self, addr_int):
# def __str__(self):
# def asString(self):
# def __repr__(self):
# class IPv4Address(object):
, which may include functions, classes, or code. Output only the next line. | self.ip.src = utils.IPv4Address(self.ip.src) |
Based on the snippet: <|code_start|>"""
.. module:: opentsdb
:synopsis: OpenTSDB protocol module
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
class OpenTSDBClient(object):
"""Twisted ElasticSearch API
"""
def __init__(self, url='http://localhost:4242', user=None, password=None):
self.url = url.rstrip('/')
self.user = user
self.password = password
def _request(self, path, data=None, method='POST'):
headers = {}
if self.user:
authorization = b64encode('%s:%s' % (self.user, self.password)
).decode()
headers['Authorization'] = ['Basic ' + authorization]
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from base64 import b64encode
from duct import utils
and context (classes, functions, sometimes code) from other files:
# Path: duct/utils.py
# def wait(msecs):
# def __init__(self, react, path, **kwargs):
# def _getEndpoint(self, *_a):
# def reverseNameFromIPAddress(address):
# def __init__(self):
# def reverse(self, ip):
# def _ret(result, ip):
# def __init__(self, finished):
# def dataReceived(self, data):
# def connectionLost(self, *_r):
# def __init__(self, body):
# def startProducing(self, consumer):
# def pauseProducing(self):
# def stopProducing(self):
# def __init__(self, deferred, timeout):
# def outReceived(self, data):
# def errReceived(self, data):
# def processEnded(self, reason):
# def connectionMade(self):
# def killIfAlive():
# def fork(executable, args=(), env={}, path=None, timeout=3600):
# def getContext(self, *_a):
# def __init__(self, timeout=120):
# def abort_request(self, request):
# def response(self, request):
# def request(self, url, method='GET', headers={}, data=None, socket=None,
# follow_redirect=False):
# def timeoutProxy(request):
# def requestAborted(failure):
# def getBody(self, url, method='GET', headers={}, data=None, socket=None):
# def getJson(self, url, method='GET', headers={}, data=None, socket=None):
# def __init__(self, location='/var/lib/duct/cache'):
# def _changed(self):
# def _acquire_cache(self):
# def _write_cache(self, data):
# def _persist(self):
# def _read(self):
# def _remove_key(self, key):
# def expire(self, age):
# def set(self, key, val):
# def get(self, k):
# def contains(self, k):
# def delete(self, k):
# class SocketyAgent(Agent):
# class Timeout(Exception):
# class Resolver(object):
# class BodyReceiver(protocol.Protocol):
# class StringProducer(object):
# class ProcessProtocol(protocol.ProcessProtocol):
# class WebClientContextFactory(ClientContextFactory):
# class HTTPRequest(object):
# class PersistentCache(object):
# SSL = True
# SSL = False
. Output only the next line. | return utils.HTTPRequest().getJson( |
Given the code snippet: <|code_start|>fn = "benchmark_{0}".format(sys.platform)
if args.grad:
fn += "_grad"
elif args.george:
fn += "_george"
elif args.carma:
fn += "_carma"
fn += ".csv"
fn = os.path.join(args.outdir, fn)
print("filename: {0}".format(fn))
with open(fn, "w") as f:
f.write(header)
print(header, end="")
# Simulate a "dataset"
np.random.seed(42)
t = np.sort(np.random.rand(np.max(N)))
yerr = np.random.uniform(0.1, 0.2, len(t))
y = np.sin(t)
def numpy_compute(kernel, x, yerr):
K = kernel.get_value(x[:, None] - x[None, :])
K[np.diag_indices_from(K)] += yerr ** 2
return cho_factor(K)
def numpy_log_like(factor, y):
np.dot(y, cho_solve(factor, y)) + np.sum(np.log(np.diag(factor[0])))
for xi, j in enumerate(J):
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import argparse
import numpy as np
import george
from scipy.linalg import cho_factor, cho_solve
from celerite import terms
from celerite.timer import benchmark
from celerite.solver import CholeskySolver
from george.kernels import CeleriteKernel
and context (functions, classes, or occasionally code) from other files:
# Path: celerite/terms.py
# @property
# def terms(self):
# """A list of all the terms included in a sum of terms"""
# return [self]
. Output only the next line. | kernel = terms.RealTerm(1.0, 0.1) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["test_product", "test_jacobian"]
def test_product(seed=42):
np.random.seed(seed)
t = np.sort(np.random.uniform(0, 5, 100))
tau = t[:, None] - t[None, :]
<|code_end|>
. Use current file imports:
import pytest
import numpy as np
from itertools import product
from celerite import terms
and context (classes, functions, or code) from other files:
# Path: celerite/terms.py
# @property
# def terms(self):
# """A list of all the terms included in a sum of terms"""
# return [self]
. Output only the next line. | k1 = terms.RealTerm(log_a=0.1, log_c=0.5) |
Using the snippet: <|code_start|>
class TestLights(TestCore):
def setUp(self):
super().setUp()
[self.pyrep.step() for _ in range(10)]
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import numpy as np
from tests.core import TestCore
from pyrep.objects.light import Light
and context (class names, function names, or code) available:
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/objects/light.py
# class Light(Object):
# """A light.
# """
#
# def __init__(self, name_or_handle: Union[str, int]):
# super().__init__(name_or_handle)
#
# def _get_requested_type(self) -> ObjectType:
# return ObjectType.LIGHT
#
# # On and Off
#
# def turn_on(self):
# """ Turn the light on.
# """
# sim.simSetLightParameters(self._handle, True)
#
# def turn_off(self):
# """ Turn the light off.
# """
# sim.simSetLightParameters(self._handle, False)
#
# def is_on(self):
# """ Determines whether the light is on.
# return: Boolean
# """
# return sim.simGetLightParameters(self._handle)[0]
#
# def is_off(self):
# """ Determines whether the light is off.
# return: Boolean
# """
# return not sim.simGetLightParameters(self._handle)[0]
#
# # Get and Set Color
#
# def get_diffuse(self):
# """ Get the diffuse colors of the light.
# return: 3-vector np.array of diffuse colors
# """
# return np.asarray(sim.simGetLightParameters(self._handle)[1])
#
# def set_diffuse(self, diffuse):
# """ Set the diffuse colors of the light.
# """
# sim.simSetLightParameters(self._handle, self.is_on(), list(diffuse))
#
# def get_specular(self):
# """ Get the specular colors of the light.
# return: 3-vector np.array of specular colors
# """
# return np.asarray(sim.simGetLightParameters(self._handle)[2])
#
# def set_specular(self, specular):
# """ Set the specular colors of the light.
# """
# sim.simSetLightParameters(self._handle, self.is_on(), specularPart=list(specular))
#
# # Intensity Properties
#
# def get_intensity_properties(self):
# """ Gets light intensity properties.
#
# :return: The light intensity properties cast_shadows, spot_exponent, spot_cutoff, const_atten_factor,
# linear_atten_factor, quad_atten_factor
# """
# cast_shadows = sim.simGetObjectInt32Parameter(self._handle, sim.sim_lightintparam_pov_casts_shadows)
# spot_exponent = sim.simGetObjectFloatParameter(self._handle, sim.sim_lightfloatparam_spot_exponent)
# spot_cutoff = sim.simGetObjectFloatParameter(self._handle, sim.sim_lightfloatparam_spot_cutoff)
# const_atten_factor = sim.simGetObjectFloatParameter(self._handle, sim.sim_lightfloatparam_const_attenuation)
# linear_atten_factor = sim.simGetObjectFloatParameter(self._handle, sim.sim_lightfloatparam_lin_attenuation)
# quad_atten_factor = sim.simGetObjectFloatParameter(self._handle, sim.sim_lightfloatparam_quad_attenuation)
# return bool(cast_shadows), spot_exponent, spot_cutoff, const_atten_factor, linear_atten_factor,\
# quad_atten_factor
#
# def set_intensity_properties(self, cast_shadows=None, spot_exponent=None, spot_cutoff=None, const_atten_factor=None,
# linear_atten_factor=None, quad_atten_factor=None):
# """ Set light intensity properties.
#
# :param cast_shadows: POV-Ray light casts shadows
# :param spot_exponent: light spot exponent
# :param spot_cutoff: light spot cutoff
# :param const_atten_factor: light constant attenuation factor, currently not supported
# :param linear_atten_factor: light linear attenuation factor, currently not supported
# :param quad_atten_factor: light quadratic attenuation factor, currently not supported
# """
# if cast_shadows is not None:
# sim.simSetObjectInt32Parameter(
# self._handle, sim.sim_lightintparam_pov_casts_shadows, int(cast_shadows))
# if spot_exponent is not None:
# if spot_exponent % 1 != 0:
# warnings.warn('spot exponent must be an integer, rounding input of {} to {}'.format(
# spot_exponent, round(spot_exponent)))
# sim.simSetObjectFloatParameter(
# self._handle, sim.sim_lightfloatparam_spot_exponent, float(round(spot_exponent)))
# if spot_cutoff is not None:
# spot_cutoff = float(spot_cutoff)
# if spot_cutoff > np.pi/2:
# warnings.warn('Tried to set spot_cutoff to {}, but the maximum allowed value is pi/2,'
# 'therefore setting to pi/2'.format(spot_cutoff))
# sim.simSetObjectFloatParameter(
# self._handle, sim.sim_lightfloatparam_spot_cutoff, float(spot_cutoff))
# if const_atten_factor is not None:
# raise Exception('CoppeliaSim currently does not support setting attenuation factors')
# # sim.simSetObjectFloatParameter(
# # self._handle, sim.sim_lightfloatparam_const_attenuation, float(const_atten_factor))
# if linear_atten_factor is not None:
# raise Exception('CoppeliaSim currently does not support setting attenuation factors')
# # sim.simSetObjectFloatParameter(
# # self._handle, sim.sim_lightfloatparam_lin_attenuation, float(linear_atten_factor))
# if quad_atten_factor is not None:
# raise Exception('CoppeliaSim currently does not support setting attenuation factors')
# # sim.simSetObjectFloatParameter(
# # self._handle, sim.sim_lightfloatparam_quad_attenuation, float(quad_atten_factor))
. Output only the next line. | self.spot_light = Light('spot_light') |
Given snippet: <|code_start|>
class Camera(Object):
"""Cameras can be associated with views.
"""
def __init__(self, name_or_handle: Union[str, int]):
super().__init__(name_or_handle)
@staticmethod
def create():
raise NotImplementedError("API does not provide simCreateCamera.")
def _get_requested_type(self) -> ObjectType:
return ObjectType.CAMERA
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from typing import Union
from pyrep.objects.object import Object, object_type_to_class
from pyrep.const import ObjectType
and context:
# Path: pyrep/objects/object.py
# class Object(object):
# def __init__(self, name_or_handle: Union[str, int]):
# def __eq__(self, other: object):
# def exists(name: str) -> bool:
# def get_object_type(name: str) -> ObjectType:
# def get_object_name(name_or_handle: Union[str, int]) -> str:
# def get_object(name_or_handle: str) -> 'Object':
# def _get_requested_type(self) -> ObjectType:
# def get_type(self) -> ObjectType:
# def get_handle(self) -> int:
# def still_exists(self) -> bool:
# def get_name(self) -> str:
# def set_name(self, name: str) -> None:
# def get_position(self, relative_to=None) -> np.ndarray:
# def set_position(self, position: Union[list, np.ndarray], relative_to=None,
# reset_dynamics=True) -> None:
# def get_orientation(self, relative_to=None) -> np.ndarray:
# def set_orientation(self, orientation: Union[list, np.ndarray],
# relative_to=None, reset_dynamics=True) -> None:
# def get_quaternion(self, relative_to=None) -> np.ndarray:
# def set_quaternion(self, quaternion: Union[list, np.ndarray],
# relative_to=None, reset_dynamics=True) -> None:
# def get_pose(self, relative_to=None) -> np.ndarray:
# def set_pose(self, pose: Union[list, np.ndarray], relative_to=None,
# reset_dynamics=True) -> None:
# def get_velocity(self) -> Tuple[np.ndarray, np.ndarray]:
# def get_parent(self) -> Union['Object', None]:
# def set_parent(self, parent_object: Union['Object', None],
# keep_in_place=True) -> None:
# def get_matrix(self, relative_to=None) -> np.ndarray:
# def set_matrix(self, matrix: np.ndarray, relative_to=None) -> None:
# def is_collidable(self) -> bool:
# def set_collidable(self, value: bool) -> None:
# def get_contact(self, contact_obj=None, get_contact_normal: bool = True) -> List:
# def is_measurable(self) -> bool:
# def set_measurable(self, value: bool):
# def is_detectable(self) -> bool:
# def set_detectable(self, value: bool):
# def is_renderable(self) -> bool:
# def set_renderable(self, value: bool):
# def is_model(self) -> bool:
# def set_model(self, value: bool):
# def remove(self) -> None:
# def reset_dynamic_object(self) -> None:
# def get_bounding_box(self) -> List[float]:
# def get_extension_string(self) -> str:
# def get_configuration_tree(self) -> bytes:
# def rotate(self, rotation: List[float]) -> None:
# def check_collision(self, obj: 'Object' = None) -> bool:
# def is_model_collidable(self) -> bool:
# def set_model_collidable(self, value: bool):
# def is_model_measurable(self) -> bool:
# def set_model_measurable(self, value: bool):
# def is_model_detectable(self) -> bool:
# def set_model_detectable(self, value: bool):
# def is_model_renderable(self) -> bool:
# def set_model_renderable(self, value: bool):
# def is_model_dynamic(self) -> bool:
# def set_model_dynamic(self, value: bool):
# def is_model_respondable(self) -> bool:
# def set_model_respondable(self, value: bool):
# def save_model(self, path: str) -> None:
# def get_model_bounding_box(self) -> List[float]:
# def _get_objects_in_tree(root_object=None, object_type=ObjectType.ALL,
# exclude_base=True, first_generation_only=False
# ) -> List['Object']:
# def get_objects_in_tree(self, *args, **kwargs) -> List['Object']:
# def copy(self) -> 'Object':
# def check_distance(self, other: 'Object') -> float:
# def get_bullet_friction(self) -> float:
# def set_bullet_friction(self, friction) -> None:
# def get_explicit_handling(self) -> int:
# def set_explicit_handling(self, value: int) -> None:
# def _check_model(self) -> None:
# def _get_model_property(self, prop_type: int) -> bool:
# def _set_model_property(self, prop_type: int, value: bool) -> None:
# def _get_property(self, prop_type: int) -> bool:
# def _set_property(self, prop_type: int, value: bool) -> None:
#
# Path: pyrep/const.py
# class ObjectType(Enum):
# ALL = sim.sim_handle_all
# SHAPE = sim.sim_object_shape_type
# JOINT = sim.sim_object_joint_type
# DUMMY = sim.sim_object_dummy_type
# PROXIMITY_SENSOR = sim.sim_object_proximitysensor_type
# GRAPH = sim.sim_object_graph_type
# CAMERA = sim.sim_object_camera_type
# PATH = sim.sim_object_path_type
# VISION_SENSOR = sim.sim_object_visionsensor_type
# VOLUME = sim.sim_object_volume_type
# MILl = sim.sim_object_mill_type
# FORCE_SENSOR = sim.sim_object_forcesensor_type
# LIGHT = sim.sim_object_light_type
# MIRROR = sim.sim_object_mirror_type
# OCTREE = sim.sim_object_octree_type
which might include code, classes, or functions. Output only the next line. | object_type_to_class[ObjectType.CAMERA] = Camera |
Given snippet: <|code_start|>
class Camera(Object):
"""Cameras can be associated with views.
"""
def __init__(self, name_or_handle: Union[str, int]):
super().__init__(name_or_handle)
@staticmethod
def create():
raise NotImplementedError("API does not provide simCreateCamera.")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from typing import Union
from pyrep.objects.object import Object, object_type_to_class
from pyrep.const import ObjectType
and context:
# Path: pyrep/objects/object.py
# class Object(object):
# def __init__(self, name_or_handle: Union[str, int]):
# def __eq__(self, other: object):
# def exists(name: str) -> bool:
# def get_object_type(name: str) -> ObjectType:
# def get_object_name(name_or_handle: Union[str, int]) -> str:
# def get_object(name_or_handle: str) -> 'Object':
# def _get_requested_type(self) -> ObjectType:
# def get_type(self) -> ObjectType:
# def get_handle(self) -> int:
# def still_exists(self) -> bool:
# def get_name(self) -> str:
# def set_name(self, name: str) -> None:
# def get_position(self, relative_to=None) -> np.ndarray:
# def set_position(self, position: Union[list, np.ndarray], relative_to=None,
# reset_dynamics=True) -> None:
# def get_orientation(self, relative_to=None) -> np.ndarray:
# def set_orientation(self, orientation: Union[list, np.ndarray],
# relative_to=None, reset_dynamics=True) -> None:
# def get_quaternion(self, relative_to=None) -> np.ndarray:
# def set_quaternion(self, quaternion: Union[list, np.ndarray],
# relative_to=None, reset_dynamics=True) -> None:
# def get_pose(self, relative_to=None) -> np.ndarray:
# def set_pose(self, pose: Union[list, np.ndarray], relative_to=None,
# reset_dynamics=True) -> None:
# def get_velocity(self) -> Tuple[np.ndarray, np.ndarray]:
# def get_parent(self) -> Union['Object', None]:
# def set_parent(self, parent_object: Union['Object', None],
# keep_in_place=True) -> None:
# def get_matrix(self, relative_to=None) -> np.ndarray:
# def set_matrix(self, matrix: np.ndarray, relative_to=None) -> None:
# def is_collidable(self) -> bool:
# def set_collidable(self, value: bool) -> None:
# def get_contact(self, contact_obj=None, get_contact_normal: bool = True) -> List:
# def is_measurable(self) -> bool:
# def set_measurable(self, value: bool):
# def is_detectable(self) -> bool:
# def set_detectable(self, value: bool):
# def is_renderable(self) -> bool:
# def set_renderable(self, value: bool):
# def is_model(self) -> bool:
# def set_model(self, value: bool):
# def remove(self) -> None:
# def reset_dynamic_object(self) -> None:
# def get_bounding_box(self) -> List[float]:
# def get_extension_string(self) -> str:
# def get_configuration_tree(self) -> bytes:
# def rotate(self, rotation: List[float]) -> None:
# def check_collision(self, obj: 'Object' = None) -> bool:
# def is_model_collidable(self) -> bool:
# def set_model_collidable(self, value: bool):
# def is_model_measurable(self) -> bool:
# def set_model_measurable(self, value: bool):
# def is_model_detectable(self) -> bool:
# def set_model_detectable(self, value: bool):
# def is_model_renderable(self) -> bool:
# def set_model_renderable(self, value: bool):
# def is_model_dynamic(self) -> bool:
# def set_model_dynamic(self, value: bool):
# def is_model_respondable(self) -> bool:
# def set_model_respondable(self, value: bool):
# def save_model(self, path: str) -> None:
# def get_model_bounding_box(self) -> List[float]:
# def _get_objects_in_tree(root_object=None, object_type=ObjectType.ALL,
# exclude_base=True, first_generation_only=False
# ) -> List['Object']:
# def get_objects_in_tree(self, *args, **kwargs) -> List['Object']:
# def copy(self) -> 'Object':
# def check_distance(self, other: 'Object') -> float:
# def get_bullet_friction(self) -> float:
# def set_bullet_friction(self, friction) -> None:
# def get_explicit_handling(self) -> int:
# def set_explicit_handling(self, value: int) -> None:
# def _check_model(self) -> None:
# def _get_model_property(self, prop_type: int) -> bool:
# def _set_model_property(self, prop_type: int, value: bool) -> None:
# def _get_property(self, prop_type: int) -> bool:
# def _set_property(self, prop_type: int, value: bool) -> None:
#
# Path: pyrep/const.py
# class ObjectType(Enum):
# ALL = sim.sim_handle_all
# SHAPE = sim.sim_object_shape_type
# JOINT = sim.sim_object_joint_type
# DUMMY = sim.sim_object_dummy_type
# PROXIMITY_SENSOR = sim.sim_object_proximitysensor_type
# GRAPH = sim.sim_object_graph_type
# CAMERA = sim.sim_object_camera_type
# PATH = sim.sim_object_path_type
# VISION_SENSOR = sim.sim_object_visionsensor_type
# VOLUME = sim.sim_object_volume_type
# MILl = sim.sim_object_mill_type
# FORCE_SENSOR = sim.sim_object_forcesensor_type
# LIGHT = sim.sim_object_light_type
# MIRROR = sim.sim_object_mirror_type
# OCTREE = sim.sim_object_octree_type
which might include code, classes, or functions. Output only the next line. | def _get_requested_type(self) -> ObjectType: |
Continue the code snippet: <|code_start|>
class TestGyroscope(TestCore):
def setUp(self):
super().setUp()
<|code_end|>
. Use current file imports:
import unittest
from tests.core import TestCore
from pyrep.sensors.gyroscope import Gyroscope
and context (classes, functions, or code) from other files:
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/sensors/gyroscope.py
# class Gyroscope(Object):
# """An object able to measure angular velocities that are applied to it.
# """
# def __init__(self, name):
# super().__init__(name)
# self._ref = '%s_reference' % (self.get_name())
#
# self._last_time = sim.simGetSimulationTime()
# self._old_transformation_matrix = self.get_matrix()[:3, :4].reshape(
# (12, )).tolist()
#
# def _get_requested_type(self) -> ObjectType:
# return ObjectType(sim.simGetObjectType(self.get_handle()))
#
# def read(self):
# """Reads the angular velocities applied to gyroscope.
#
# :return: A list containing applied angular velocities along
# the sensor's x, y and z-axes.
# """
# current_time = sim.simGetSimulationTime()
# dt = current_time - self._last_time
#
# inv_old_matrix = sim.simInvertMatrix(self._old_transformation_matrix)
# transformation_matrix = self.get_matrix()[:3, :4].reshape(
# (12, )).tolist()
# mat = sim.simMultiplyMatrices(inv_old_matrix, transformation_matrix)
# euler_angles = sim.simGetEulerAnglesFromMatrix(mat)
#
# self._last_time = current_time
# self._old_transformation_matrix = transformation_matrix
#
# if dt != 0:
# return [euler_angle / dt for euler_angle in euler_angles]
# return [0.0, 0.0, 0.0]
. Output only the next line. | self.sensor = Gyroscope('gyroscope') |
Next line prediction: <|code_start|>
class TestForceSensors(TestCore):
def setUp(self):
super().setUp()
<|code_end|>
. Use current file imports:
(import unittest
from tests.core import TestCore
from pyrep.objects.force_sensor import ForceSensor)
and context including class names, function names, or small code snippets from other files:
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/objects/force_sensor.py
# class ForceSensor(Object):
# """An object able to measure forces and torques that are applied to it.
# """
#
# def _get_requested_type(self) -> ObjectType:
# return ObjectType.FORCE_SENSOR
#
# @classmethod
# def create(cls, sensor_size=0.01) -> 'ForceSensor':
# options = 0 # force and torque threshold are disabled
# intParams = [0, 0, 0, 0, 0]
# floatParams = [sensor_size, 0, 0, 0, 0]
# handle = sim.simCreateForceSensor(options=0, intParams=intParams,
# floatParams=floatParams, color=None)
# return cls(handle)
#
# def read(self) -> Tuple[List[float], List[float]]:
# """Reads the force and torque applied to a force sensor.
#
# :return: A tuple containing the applied forces along the
# sensor's x, y and z-axes, and the torques along the
# sensor's x, y and z-axes.
# """
# _, forces, torques = sim.simReadForceSensor(self._handle)
# return forces, torques
. Output only the next line. | self.sensor = ForceSensor('force_sensor') |
Based on the snippet: <|code_start|> # with self.assertRaises(PyRepError):
# d.read()
class TestSignal(TestCore):
SIGNALS = [
(IntegerSignal, 99),
(FloatSignal, 55.3),
(DoubleSignal, 22.2),
(StringSignal, 'hello')
]
def test_set_get_clear_signals(self):
for signal_class, test_value in TestSignal.SIGNALS:
with self.subTest(signal=str(signal_class)):
sig = signal_class('my_signal')
sig.set(test_value)
ret_value = sig.get()
if isinstance(test_value, float):
self.assertAlmostEqual(ret_value, test_value, places=3)
else:
self.assertEqual(ret_value, test_value)
clears = sig.clear()
self.assertEqual(clears, 1)
def test_get_signal_fails_when_empty(self):
for signal_class, test_value in TestSignal.SIGNALS:
with self.subTest(signal=str(signal_class)):
sig = signal_class('my_signal')
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from pyrep.errors import PyRepError
from tests.core import TestCore
from pyrep.misc.distance import Distance
from pyrep.misc.signals import IntegerSignal, FloatSignal
from pyrep.misc.signals import DoubleSignal, StringSignal
and context (classes, functions, sometimes code) from other files:
# Path: pyrep/errors.py
# class PyRepError(Exception):
# pass
#
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/misc/distance.py
# class Distance(object):
# """Allows registering distance objects which are measurable entity-pairs."""
#
# def __init__(self, name_or_handle: Union[str, int]):
# raise PyRepError(
# 'Currently there is an error in CoppeliaSim with distance objects. '
# 'As soon as CoppeliaSim resolves this issue, this error will be '
# 'removed.')
# self._handle: int
# if isinstance(name_or_handle, int):
# self._handle = name_or_handle
# else:
# self._handle = sim.simGetDistanceHandle(name_or_handle)
# # The entity needs to be set as explicit handling for reads to work.
# if not sim.simGetExplicitHandling(self._handle):
# sim.simSetExplicitHandling(self._handle, 1)
#
# def __eq__(self, other: object):
# if not isinstance(other, Distance):
# raise NotImplementedError
# return self.get_handle() == other.get_handle()
#
# def get_handle(self) -> int:
# """Gets the internal handle of this object.
#
# :return: The internal handle.
# """
# return self._handle
#
# def read(self) -> Union[float, None]:
# """Reads the distance of a registered distance object.
#
# :raises: PyRepError if no objects could be measured.
#
# :return: The smallest distance between the 2 entities or None if no
# measurement could be made.
# """
# num_measurements = sim.simHandleDistance(self._handle)
# if num_measurements == 0:
# raise PyRepError(
# 'Could not make a measurement. Are both entities associated '
# 'with the distance object marked as measurable?')
# return (None if num_measurements == 0
# else sim.simReadDistance(self._handle))
#
# Path: pyrep/misc/signals.py
# class IntegerSignal(Signal):
# """An integer-type signal."""
#
# def set(self, value) -> None:
# sim.simSetIntegerSignal(self._name, value)
#
# def get(self) -> int:
# ret, value = sim.simGetIntegerSignal(self._name)
# self._check_signal(ret, 'int')
# return value
#
# def clear(self) -> int:
# return sim.simClearIntegerSignal(self._name)
#
# class FloatSignal(Signal):
# """An float-type signal."""
#
# def set(self, value) -> None:
# sim.simSetFloatSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetFloatSignal(self._name)
# self._check_signal(ret, 'float')
# return value
#
# def clear(self) -> int:
# return sim.simClearFloatSignal(self._name)
#
# Path: pyrep/misc/signals.py
# class DoubleSignal(Signal):
# """An double-type signal."""
#
# def set(self, value) -> None:
# sim.simSetDoubleSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetDoubleSignal(self._name)
# self._check_signal(ret, 'double')
# return value
#
# def clear(self) -> int:
# return sim.simClearDoubleSignal(self._name)
#
# class StringSignal(Signal):
# """An string-type signal."""
#
# def set(self, value) -> None:
# sim.simSetStringSignal(self._name, value)
#
# def get(self) -> str:
# ret, value = sim.simGetStringSignal(self._name)
# self._check_signal(ret, 'string')
# return value
#
# def clear(self) -> int:
# return sim.simClearStringSignal(self._name)
. Output only the next line. | with self.assertRaises(PyRepError): |
Predict the next line after this snippet: <|code_start|>
# TODO: These tests will be re-enabled once bug has been fixed in CoppeliaSim.
class TestMisc(TestCore):
pass
# def test_get_distance(self):
# Distance('dist_cubes')
# def test_read_distance(self):
# d = Distance('dist_cubes')
# dist = d.read()
# self.assertAlmostEqual(dist, 0.1, places=3)
# def test_read_distance_not_measurable(self):
# d = Distance('dist_cubes_fail')
# with self.assertRaises(PyRepError):
# d.read()
class TestSignal(TestCore):
SIGNALS = [
<|code_end|>
using the current file's imports:
import unittest
from pyrep.errors import PyRepError
from tests.core import TestCore
from pyrep.misc.distance import Distance
from pyrep.misc.signals import IntegerSignal, FloatSignal
from pyrep.misc.signals import DoubleSignal, StringSignal
and any relevant context from other files:
# Path: pyrep/errors.py
# class PyRepError(Exception):
# pass
#
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/misc/distance.py
# class Distance(object):
# """Allows registering distance objects which are measurable entity-pairs."""
#
# def __init__(self, name_or_handle: Union[str, int]):
# raise PyRepError(
# 'Currently there is an error in CoppeliaSim with distance objects. '
# 'As soon as CoppeliaSim resolves this issue, this error will be '
# 'removed.')
# self._handle: int
# if isinstance(name_or_handle, int):
# self._handle = name_or_handle
# else:
# self._handle = sim.simGetDistanceHandle(name_or_handle)
# # The entity needs to be set as explicit handling for reads to work.
# if not sim.simGetExplicitHandling(self._handle):
# sim.simSetExplicitHandling(self._handle, 1)
#
# def __eq__(self, other: object):
# if not isinstance(other, Distance):
# raise NotImplementedError
# return self.get_handle() == other.get_handle()
#
# def get_handle(self) -> int:
# """Gets the internal handle of this object.
#
# :return: The internal handle.
# """
# return self._handle
#
# def read(self) -> Union[float, None]:
# """Reads the distance of a registered distance object.
#
# :raises: PyRepError if no objects could be measured.
#
# :return: The smallest distance between the 2 entities or None if no
# measurement could be made.
# """
# num_measurements = sim.simHandleDistance(self._handle)
# if num_measurements == 0:
# raise PyRepError(
# 'Could not make a measurement. Are both entities associated '
# 'with the distance object marked as measurable?')
# return (None if num_measurements == 0
# else sim.simReadDistance(self._handle))
#
# Path: pyrep/misc/signals.py
# class IntegerSignal(Signal):
# """An integer-type signal."""
#
# def set(self, value) -> None:
# sim.simSetIntegerSignal(self._name, value)
#
# def get(self) -> int:
# ret, value = sim.simGetIntegerSignal(self._name)
# self._check_signal(ret, 'int')
# return value
#
# def clear(self) -> int:
# return sim.simClearIntegerSignal(self._name)
#
# class FloatSignal(Signal):
# """An float-type signal."""
#
# def set(self, value) -> None:
# sim.simSetFloatSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetFloatSignal(self._name)
# self._check_signal(ret, 'float')
# return value
#
# def clear(self) -> int:
# return sim.simClearFloatSignal(self._name)
#
# Path: pyrep/misc/signals.py
# class DoubleSignal(Signal):
# """An double-type signal."""
#
# def set(self, value) -> None:
# sim.simSetDoubleSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetDoubleSignal(self._name)
# self._check_signal(ret, 'double')
# return value
#
# def clear(self) -> int:
# return sim.simClearDoubleSignal(self._name)
#
# class StringSignal(Signal):
# """An string-type signal."""
#
# def set(self, value) -> None:
# sim.simSetStringSignal(self._name, value)
#
# def get(self) -> str:
# ret, value = sim.simGetStringSignal(self._name)
# self._check_signal(ret, 'string')
# return value
#
# def clear(self) -> int:
# return sim.simClearStringSignal(self._name)
. Output only the next line. | (IntegerSignal, 99), |
Here is a snippet: <|code_start|>
# TODO: These tests will be re-enabled once bug has been fixed in CoppeliaSim.
class TestMisc(TestCore):
pass
# def test_get_distance(self):
# Distance('dist_cubes')
# def test_read_distance(self):
# d = Distance('dist_cubes')
# dist = d.read()
# self.assertAlmostEqual(dist, 0.1, places=3)
# def test_read_distance_not_measurable(self):
# d = Distance('dist_cubes_fail')
# with self.assertRaises(PyRepError):
# d.read()
class TestSignal(TestCore):
SIGNALS = [
(IntegerSignal, 99),
<|code_end|>
. Write the next line using the current file imports:
import unittest
from pyrep.errors import PyRepError
from tests.core import TestCore
from pyrep.misc.distance import Distance
from pyrep.misc.signals import IntegerSignal, FloatSignal
from pyrep.misc.signals import DoubleSignal, StringSignal
and context from other files:
# Path: pyrep/errors.py
# class PyRepError(Exception):
# pass
#
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/misc/distance.py
# class Distance(object):
# """Allows registering distance objects which are measurable entity-pairs."""
#
# def __init__(self, name_or_handle: Union[str, int]):
# raise PyRepError(
# 'Currently there is an error in CoppeliaSim with distance objects. '
# 'As soon as CoppeliaSim resolves this issue, this error will be '
# 'removed.')
# self._handle: int
# if isinstance(name_or_handle, int):
# self._handle = name_or_handle
# else:
# self._handle = sim.simGetDistanceHandle(name_or_handle)
# # The entity needs to be set as explicit handling for reads to work.
# if not sim.simGetExplicitHandling(self._handle):
# sim.simSetExplicitHandling(self._handle, 1)
#
# def __eq__(self, other: object):
# if not isinstance(other, Distance):
# raise NotImplementedError
# return self.get_handle() == other.get_handle()
#
# def get_handle(self) -> int:
# """Gets the internal handle of this object.
#
# :return: The internal handle.
# """
# return self._handle
#
# def read(self) -> Union[float, None]:
# """Reads the distance of a registered distance object.
#
# :raises: PyRepError if no objects could be measured.
#
# :return: The smallest distance between the 2 entities or None if no
# measurement could be made.
# """
# num_measurements = sim.simHandleDistance(self._handle)
# if num_measurements == 0:
# raise PyRepError(
# 'Could not make a measurement. Are both entities associated '
# 'with the distance object marked as measurable?')
# return (None if num_measurements == 0
# else sim.simReadDistance(self._handle))
#
# Path: pyrep/misc/signals.py
# class IntegerSignal(Signal):
# """An integer-type signal."""
#
# def set(self, value) -> None:
# sim.simSetIntegerSignal(self._name, value)
#
# def get(self) -> int:
# ret, value = sim.simGetIntegerSignal(self._name)
# self._check_signal(ret, 'int')
# return value
#
# def clear(self) -> int:
# return sim.simClearIntegerSignal(self._name)
#
# class FloatSignal(Signal):
# """An float-type signal."""
#
# def set(self, value) -> None:
# sim.simSetFloatSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetFloatSignal(self._name)
# self._check_signal(ret, 'float')
# return value
#
# def clear(self) -> int:
# return sim.simClearFloatSignal(self._name)
#
# Path: pyrep/misc/signals.py
# class DoubleSignal(Signal):
# """An double-type signal."""
#
# def set(self, value) -> None:
# sim.simSetDoubleSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetDoubleSignal(self._name)
# self._check_signal(ret, 'double')
# return value
#
# def clear(self) -> int:
# return sim.simClearDoubleSignal(self._name)
#
# class StringSignal(Signal):
# """An string-type signal."""
#
# def set(self, value) -> None:
# sim.simSetStringSignal(self._name, value)
#
# def get(self) -> str:
# ret, value = sim.simGetStringSignal(self._name)
# self._check_signal(ret, 'string')
# return value
#
# def clear(self) -> int:
# return sim.simClearStringSignal(self._name)
, which may include functions, classes, or code. Output only the next line. | (FloatSignal, 55.3), |
Predict the next line for this snippet: <|code_start|>
# TODO: These tests will be re-enabled once bug has been fixed in CoppeliaSim.
class TestMisc(TestCore):
pass
# def test_get_distance(self):
# Distance('dist_cubes')
# def test_read_distance(self):
# d = Distance('dist_cubes')
# dist = d.read()
# self.assertAlmostEqual(dist, 0.1, places=3)
# def test_read_distance_not_measurable(self):
# d = Distance('dist_cubes_fail')
# with self.assertRaises(PyRepError):
# d.read()
class TestSignal(TestCore):
SIGNALS = [
(IntegerSignal, 99),
(FloatSignal, 55.3),
<|code_end|>
with the help of current file imports:
import unittest
from pyrep.errors import PyRepError
from tests.core import TestCore
from pyrep.misc.distance import Distance
from pyrep.misc.signals import IntegerSignal, FloatSignal
from pyrep.misc.signals import DoubleSignal, StringSignal
and context from other files:
# Path: pyrep/errors.py
# class PyRepError(Exception):
# pass
#
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/misc/distance.py
# class Distance(object):
# """Allows registering distance objects which are measurable entity-pairs."""
#
# def __init__(self, name_or_handle: Union[str, int]):
# raise PyRepError(
# 'Currently there is an error in CoppeliaSim with distance objects. '
# 'As soon as CoppeliaSim resolves this issue, this error will be '
# 'removed.')
# self._handle: int
# if isinstance(name_or_handle, int):
# self._handle = name_or_handle
# else:
# self._handle = sim.simGetDistanceHandle(name_or_handle)
# # The entity needs to be set as explicit handling for reads to work.
# if not sim.simGetExplicitHandling(self._handle):
# sim.simSetExplicitHandling(self._handle, 1)
#
# def __eq__(self, other: object):
# if not isinstance(other, Distance):
# raise NotImplementedError
# return self.get_handle() == other.get_handle()
#
# def get_handle(self) -> int:
# """Gets the internal handle of this object.
#
# :return: The internal handle.
# """
# return self._handle
#
# def read(self) -> Union[float, None]:
# """Reads the distance of a registered distance object.
#
# :raises: PyRepError if no objects could be measured.
#
# :return: The smallest distance between the 2 entities or None if no
# measurement could be made.
# """
# num_measurements = sim.simHandleDistance(self._handle)
# if num_measurements == 0:
# raise PyRepError(
# 'Could not make a measurement. Are both entities associated '
# 'with the distance object marked as measurable?')
# return (None if num_measurements == 0
# else sim.simReadDistance(self._handle))
#
# Path: pyrep/misc/signals.py
# class IntegerSignal(Signal):
# """An integer-type signal."""
#
# def set(self, value) -> None:
# sim.simSetIntegerSignal(self._name, value)
#
# def get(self) -> int:
# ret, value = sim.simGetIntegerSignal(self._name)
# self._check_signal(ret, 'int')
# return value
#
# def clear(self) -> int:
# return sim.simClearIntegerSignal(self._name)
#
# class FloatSignal(Signal):
# """An float-type signal."""
#
# def set(self, value) -> None:
# sim.simSetFloatSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetFloatSignal(self._name)
# self._check_signal(ret, 'float')
# return value
#
# def clear(self) -> int:
# return sim.simClearFloatSignal(self._name)
#
# Path: pyrep/misc/signals.py
# class DoubleSignal(Signal):
# """An double-type signal."""
#
# def set(self, value) -> None:
# sim.simSetDoubleSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetDoubleSignal(self._name)
# self._check_signal(ret, 'double')
# return value
#
# def clear(self) -> int:
# return sim.simClearDoubleSignal(self._name)
#
# class StringSignal(Signal):
# """An string-type signal."""
#
# def set(self, value) -> None:
# sim.simSetStringSignal(self._name, value)
#
# def get(self) -> str:
# ret, value = sim.simGetStringSignal(self._name)
# self._check_signal(ret, 'string')
# return value
#
# def clear(self) -> int:
# return sim.simClearStringSignal(self._name)
, which may contain function names, class names, or code. Output only the next line. | (DoubleSignal, 22.2), |
Given the code snippet: <|code_start|>
# TODO: These tests will be re-enabled once bug has been fixed in CoppeliaSim.
class TestMisc(TestCore):
pass
# def test_get_distance(self):
# Distance('dist_cubes')
# def test_read_distance(self):
# d = Distance('dist_cubes')
# dist = d.read()
# self.assertAlmostEqual(dist, 0.1, places=3)
# def test_read_distance_not_measurable(self):
# d = Distance('dist_cubes_fail')
# with self.assertRaises(PyRepError):
# d.read()
class TestSignal(TestCore):
SIGNALS = [
(IntegerSignal, 99),
(FloatSignal, 55.3),
(DoubleSignal, 22.2),
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from pyrep.errors import PyRepError
from tests.core import TestCore
from pyrep.misc.distance import Distance
from pyrep.misc.signals import IntegerSignal, FloatSignal
from pyrep.misc.signals import DoubleSignal, StringSignal
and context (functions, classes, or occasionally code) from other files:
# Path: pyrep/errors.py
# class PyRepError(Exception):
# pass
#
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/misc/distance.py
# class Distance(object):
# """Allows registering distance objects which are measurable entity-pairs."""
#
# def __init__(self, name_or_handle: Union[str, int]):
# raise PyRepError(
# 'Currently there is an error in CoppeliaSim with distance objects. '
# 'As soon as CoppeliaSim resolves this issue, this error will be '
# 'removed.')
# self._handle: int
# if isinstance(name_or_handle, int):
# self._handle = name_or_handle
# else:
# self._handle = sim.simGetDistanceHandle(name_or_handle)
# # The entity needs to be set as explicit handling for reads to work.
# if not sim.simGetExplicitHandling(self._handle):
# sim.simSetExplicitHandling(self._handle, 1)
#
# def __eq__(self, other: object):
# if not isinstance(other, Distance):
# raise NotImplementedError
# return self.get_handle() == other.get_handle()
#
# def get_handle(self) -> int:
# """Gets the internal handle of this object.
#
# :return: The internal handle.
# """
# return self._handle
#
# def read(self) -> Union[float, None]:
# """Reads the distance of a registered distance object.
#
# :raises: PyRepError if no objects could be measured.
#
# :return: The smallest distance between the 2 entities or None if no
# measurement could be made.
# """
# num_measurements = sim.simHandleDistance(self._handle)
# if num_measurements == 0:
# raise PyRepError(
# 'Could not make a measurement. Are both entities associated '
# 'with the distance object marked as measurable?')
# return (None if num_measurements == 0
# else sim.simReadDistance(self._handle))
#
# Path: pyrep/misc/signals.py
# class IntegerSignal(Signal):
# """An integer-type signal."""
#
# def set(self, value) -> None:
# sim.simSetIntegerSignal(self._name, value)
#
# def get(self) -> int:
# ret, value = sim.simGetIntegerSignal(self._name)
# self._check_signal(ret, 'int')
# return value
#
# def clear(self) -> int:
# return sim.simClearIntegerSignal(self._name)
#
# class FloatSignal(Signal):
# """An float-type signal."""
#
# def set(self, value) -> None:
# sim.simSetFloatSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetFloatSignal(self._name)
# self._check_signal(ret, 'float')
# return value
#
# def clear(self) -> int:
# return sim.simClearFloatSignal(self._name)
#
# Path: pyrep/misc/signals.py
# class DoubleSignal(Signal):
# """An double-type signal."""
#
# def set(self, value) -> None:
# sim.simSetDoubleSignal(self._name, value)
#
# def get(self) -> float:
# ret, value = sim.simGetDoubleSignal(self._name)
# self._check_signal(ret, 'double')
# return value
#
# def clear(self) -> int:
# return sim.simClearDoubleSignal(self._name)
#
# class StringSignal(Signal):
# """An string-type signal."""
#
# def set(self, value) -> None:
# sim.simSetStringSignal(self._name, value)
#
# def get(self) -> str:
# ret, value = sim.simGetStringSignal(self._name)
# self._check_signal(ret, 'string')
# return value
#
# def clear(self) -> int:
# return sim.simClearStringSignal(self._name)
. Output only the next line. | (StringSignal, 'hello') |
Given snippet: <|code_start|>
# Pick one arm to test all of the joint group functionality.
# Simply checks for wiring mistakes between the joints.
class TestJointGroups(TestCore):
def setUp(self):
super().setUp()
self.robot = Panda()
self.num_joints = len(self.robot.joints)
def test_get_joint_types(self):
self.assertEqual(self.robot.get_joint_types(),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import numpy as np
from tests.core import TestCore
from pyrep.const import JointType
from pyrep.robots.arms.panda import Panda
and context:
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/const.py
# class JointType(Enum):
# REVOLUTE = sim.sim_joint_revolute_subtype
# PRISMATIC = sim.sim_joint_prismatic_subtype
# SPHERICAL = sim.sim_joint_spherical_subtype
#
# Path: pyrep/robots/arms/panda.py
# class Panda(Arm):
#
# def __init__(self, count: int = 0):
# super().__init__(count, 'Panda', 7)
which might include code, classes, or functions. Output only the next line. | [JointType.REVOLUTE] * self.num_joints) |
Here is a snippet: <|code_start|>
# Pick one arm to test all of the joint group functionality.
# Simply checks for wiring mistakes between the joints.
class TestJointGroups(TestCore):
def setUp(self):
super().setUp()
<|code_end|>
. Write the next line using the current file imports:
import unittest
import numpy as np
from tests.core import TestCore
from pyrep.const import JointType
from pyrep.robots.arms.panda import Panda
and context from other files:
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/const.py
# class JointType(Enum):
# REVOLUTE = sim.sim_joint_revolute_subtype
# PRISMATIC = sim.sim_joint_prismatic_subtype
# SPHERICAL = sim.sim_joint_spherical_subtype
#
# Path: pyrep/robots/arms/panda.py
# class Panda(Arm):
#
# def __init__(self, count: int = 0):
# super().__init__(count, 'Panda', 7)
, which may include functions, classes, or code. Output only the next line. | self.robot = Panda() |
Given the following code snippet before the placeholder: <|code_start|>
class TestAccelerometer(TestCore):
def setUp(self):
super().setUp()
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from tests.core import TestCore
from pyrep.sensors.accelerometer import Accelerometer
and context including class names, function names, and sometimes code from other files:
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/sensors/accelerometer.py
# class Accelerometer(Object):
# """An object able to measure accelerations that are applied to it.
# """
#
# def __init__(self, name):
# super().__init__(name)
# self._mass_object = Shape('%s_mass' % (self.get_name()))
# self._sensor = ForceSensor('%s_force_sensor' % (self.get_name()))
#
# def _get_requested_type(self) -> ObjectType:
# return ObjectType(sim.simGetObjectType(self.get_handle()))
#
# def read(self) -> List[float]:
# """Reads the acceleration applied to accelerometer.
#
# :return: A list containing applied accelerations along
# the sensor's x, y and z-axes
# """
# forces, _ = self._sensor.read()
# accel = [force / self._mass_object.get_mass() for force in forces]
# return accel
. Output only the next line. | self.sensor = Accelerometer('accelerometer') |
Given the following code snippet before the placeholder: <|code_start|>
class TestCartesianPaths(TestCore):
def setUp(self):
super().setUp()
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from tests.core import TestCore
from pyrep.objects.cartesian_path import CartesianPath
and context including class names, function names, and sometimes code from other files:
# Path: tests/core.py
# class TestCore(unittest.TestCase):
#
# def setUp(self):
# self.pyrep = PyRep()
# self.pyrep.launch(path.join(ASSET_DIR, 'test_scene.ttt'), headless=True)
# self.pyrep.step()
# self.pyrep.start()
#
# def tearDown(self):
# self.pyrep.stop()
# self.pyrep.step_ui()
# self.pyrep.shutdown()
#
# Path: pyrep/objects/cartesian_path.py
# class CartesianPath(Object):
# """An object that defines a cartesian path or trajectory in space.
# """
#
# @staticmethod
# def create(show_line: bool = True, show_orientation: bool = True,
# show_position: bool = True, closed_path: bool = False,
# automatic_orientation: bool = True, flat_path: bool = False,
# keep_x_up: bool = False, line_size: int = 1,
# length_calculation_method: int = sim.sim_distcalcmethod_dl_if_nonzero, control_point_size: float = 0.01,
# ang_to_lin_conv_coeff: float = 1., virt_dist_scale_factor: float = 1.,
# path_color: tuple = (0.1, 0.75, 1.)) -> 'CartesianPath':
# """Creates a cartesian path and inserts in the scene.
#
# :param show_line: Shows line in UI.
# :param show_position: Shows line in UI.
# :param show_orientation: Shows orientation in UI.
# :param closed_path: If set, then a path's last control point will be
# linked to its first control point to close the path and make its
# operation cyclic. A minimum of 3 control points are required for
# a path to be closed.
# :param automatic_orientation: If set, then all control points and
# Bezier point's orientation will automatically be calculated in
# order to have a point's z-axis along the path, and its y-axis
# pointing outwards its curvature (if keep x up is enabled, the
# y-axis is not particularly constrained). If disabled, the user
# determines the control point's orientation and the Bezier points'
# orientation will be interpolated from the path's control points'
# orientation.
# :param flat_path: If set, then all control points (and subsequently all
# Bezier points) will be constraint to the z=0 plane of the path
# object's local reference frame.
# :param keep_x_up: If set, then the automatic orientation functionality
# will align each Bezier point's z-axis along the path and keep its
# x-axis pointing along the path object's z-axis.
# :param line_size: Size of the line in pixels.
# :param length_calculation_method: Method for calculating the path length. See
# https://www.coppeliarobotics.com/helpFiles/en/apiConstants.htm#distanceCalculationMethods
# :param control_point_size: Size of the control points in the path.
# :param ang_to_lin_conv_coeff: The angular to linear conversion coefficient.
# :param virt_dist_scale_factor: The virtual distance scaling factor.
# :param path_color: Ambient diffuse rgb color of the path.
#
# :return: The newly created cartesian path.
# """
# attributes = 0
# if show_line:
# attributes |= sim.sim_pathproperty_show_line
# if show_orientation:
# attributes |= sim.sim_pathproperty_show_orientation
# if closed_path:
# attributes |= sim.sim_pathproperty_closed_path
# if automatic_orientation:
# attributes |= sim.sim_pathproperty_automatic_orientation
# if flat_path:
# attributes |= sim.sim_pathproperty_flat_path
# if show_position:
# attributes |= sim.sim_pathproperty_show_position
# if keep_x_up:
# attributes |= sim.sim_pathproperty_keep_x_up
#
# handle = sim.simCreatePath(attributes, [line_size, length_calculation_method, 0],
# [control_point_size, ang_to_lin_conv_coeff, virt_dist_scale_factor],
# list(path_color))
# return CartesianPath(handle)
#
# def _get_requested_type(self) -> ObjectType:
# return ObjectType.PATH
#
# def get_pose_on_path(self, relative_distance: float
# ) -> Tuple[List[float], List[float]]:
# """Retrieves the absolute interpolated pose of a point along the path.
#
# :param relative_distance: A value between 0 and 1, where 0 is the
# beginning of the path, and 1 the end of the path.
# :return: A tuple containing the x, y, z position, and the x, y, z
# orientation of the point on the path (in radians).
# """
# pos = sim.simGetPositionOnPath(self._handle, relative_distance)
# ori = sim.simGetOrientationOnPath(self._handle, relative_distance)
# return pos, ori
#
# def insert_control_points(self, poses: List[List[float]]) -> None:
# """Inserts one or several control points into the path.
#
# :param poses: A list of lists containing 6 values representing the pose
# of each of the new control points. Orientation in radians.
# """
# data = []
# for p in poses:
# data.extend(p)
# self._script_call('insertPathControlPoint@PyRep',
# ints=[self._handle, len(poses)], floats=data)
#
# def _script_call(self, func: str, ints=(), floats=(), strings=(), bytes=''):
# return sim.simExtCallScriptFunction(
# func, sim.sim_scripttype_addonscript,
# list(ints), list(floats), list(strings), bytes)
. Output only the next line. | self.cart_path = CartesianPath('cartesian_path') |
Here is a snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
. Write the next line using the current file imports:
from ddserver.utils.deps import require
import ddserver.interface.pages.index # @UnusedImport: for web application
import ddserver.interface.pages.signup # @UnusedImport: for web application
import ddserver.interface.pages.lostpasswd # @UnusedImport: for web application
import ddserver.interface.pages.login # @UnusedImport: for web application
import ddserver.interface.pages.user.account # @UnusedImport: for web application
import ddserver.interface.pages.user.hosts # @UnusedImport: for web application
import ddserver.interface.pages.user.host # @UnusedImport: for web application
import ddserver.interface.pages.admin.users # @UnusedImport: for web application
import ddserver.interface.pages.admin.suffixes # @UnusedImport: for web application
import ddserver.updater.nic # @UnusedImport: for web application
and context from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
, which may include functions, classes, or code. Output only the next line. | @require(web = 'ddserver.web:Web') |
Based on the snippet: <|code_start|> 'value']
def __init__(self, name, value):
self.name = name
self.value = value
def __str__(self):
if self.value:
return '%s %s' % (self.name, self.value)
else:
return '%s' % self.name
__repr__ = __str__
# Existing response codes
resp_good = functools.partial(Response, 'good')
resp_nochg = functools.partial(Response, 'nochg')
resp_nohost = functools.partial(Response, 'nohost', None)
resp_badauth = functools.partial(Response, 'badauth', None)
resp_badagent = functools.partial(Response, 'badagent', None)
resp_not_donator = functools.partial(Response, '!donator', None)
resp_abuse = functools.partial(Response, 'abuse', None)
resp_911 = functools.partial(Response, '911', None)
<|code_end|>
, predict the immediate next line with the help of imports:
import functools
import bottle
import formencode
from passlib.apps import custom_app_context as pwd
from ddserver.utils.deps import require
from ddserver.web import route
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @require(logger='ddserver.utils.logger:Logger', |
Predict the next line after this snippet: <|code_start|>'''
Copyright 2013 Dustin Frisch <fooker@lab.sh>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
using the current file's imports:
import uuid
import bottle
import functools
import collections
from passlib.apps import custom_app_context as pwd
from ddserver.utils.deps import export, extend, require
and any relevant context from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @export() |
Predict the next line for this snippet: <|code_start|> *args,
**kwargs):
if (bottle.request.query.username == "" or
bottle.request.query.authcode == ""):
messages.error('You have to provide username and authcode.')
bottle.redirect('/')
username = bottle.request.query.username
authcode = bottle.request.query.authcode
user = users[username]
if user == None:
messages.error('The username does not exist.')
bottle.redirect('/')
if user.authcode != authcode:
messages.error('The auth code you provided was invalid.')
bottle.redirect('/')
# Inject the user in the wrapped function
return func(*args,
user = user,
**kwargs)
return wrapped
return wrapper
<|code_end|>
with the help of current file imports:
import uuid
import bottle
import functools
import collections
from passlib.apps import custom_app_context as pwd
from ddserver.utils.deps import export, extend, require
and context from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
, which may contain function names, class names, or code. Output only the next line. | @extend('ddserver.interface.template:TemplateManager') |
Given the code snippet: <|code_start|>published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@export()
class UserManager(object):
User = collections.namedtuple('User', ['id',
'username',
'password',
'email',
'admin',
'active',
'created',
'authcode',
'maxhosts'])
<|code_end|>
, generate the next line using the imports in this file:
import uuid
import bottle
import functools
import collections
from passlib.apps import custom_app_context as pwd
from ddserver.utils.deps import export, extend, require
and context (functions, classes, or occasionally code) from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @require(db = 'ddserver.db:Database') |
Predict the next line after this snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@route('/admin/users/<mode>')
@authorized_admin()
<|code_end|>
using the current file's imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require
from ddserver.interface.user import authorized_admin
from ddserver.interface import validation
from ddserver.interface.validation import validate
and any relevant context from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# class UserManager(object):
# def __getitem__(self,
# key,
# db):
# def login(self,
# session,
# messages,
# username,
# password):
# def logout(self,
# session,
# messages):
# def generate_authcode(self, username, db):
# def authorized(self, session):
# def authorized(admin = False):
# def wrapper(func):
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# def authorized_by_code():
# def wrapper(func):
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# def template_auth(templates):
# def __(users):
. Output only the next line. | @require(db = 'ddserver.db:Database', |
Based on the snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@route('/admin/users/<mode>')
<|code_end|>
, predict the immediate next line with the help of imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require
from ddserver.interface.user import authorized_admin
from ddserver.interface import validation
from ddserver.interface.validation import validate
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# class UserManager(object):
# def __getitem__(self,
# key,
# db):
# def login(self,
# session,
# messages,
# username,
# password):
# def logout(self,
# session,
# messages):
# def generate_authcode(self, username, db):
# def authorized(self, session):
# def authorized(admin = False):
# def wrapper(func):
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# def authorized_by_code():
# def wrapper(func):
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# def template_auth(templates):
# def __(users):
. Output only the next line. | @authorized_admin() |
Next line prediction: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@route('/user/host/<host_id>', method = 'GET')
@authorized()
<|code_end|>
. Use current file imports:
(import bottle
import formencode
from ddserver.web import route
from ddserver.utils.deps import extend, require
from ddserver.interface.user import authorized
from ddserver.interface import validation
from ddserver.interface.validation import validate
from passlib.apps import custom_app_context as pwd)
and context including class names, function names, or small code snippets from other files:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# @property
# @require(session = 'ddserver.interface.session:SessionManager')
# def authorized(self, session):
# if session.username:
# return self[session.username]
. Output only the next line. | @require(db = 'ddserver.db:Database', |
Given the code snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@route('/user/host/<host_id>', method = 'GET')
<|code_end|>
, generate the next line using the imports in this file:
import bottle
import formencode
from ddserver.web import route
from ddserver.utils.deps import extend, require
from ddserver.interface.user import authorized
from ddserver.interface import validation
from ddserver.interface.validation import validate
from passlib.apps import custom_app_context as pwd
and context (functions, classes, or occasionally code) from other files:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# @property
# @require(session = 'ddserver.interface.session:SessionManager')
# def authorized(self, session):
# if session.username:
# return self[session.username]
. Output only the next line. | @authorized() |
Given the following code snippet before the placeholder: <|code_start|>'''
Copyright 2013 Dustin Frisch <fooker@lab.sh>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
, predict the next line using imports from the current file:
import enum
import collections
from ddserver.utils.deps import export, require, extend
and context including class names, function names, and sometimes code from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
. Output only the next line. | @export() |
Based on the snippet: <|code_start|>it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@export()
class MessageManager(object):
Level = enum.Enum('success',
'error')
Message = collections.namedtuple('Message', ['level',
'message'])
def __init__(self):
self.__messages = []
<|code_end|>
, predict the immediate next line with the help of imports:
import enum
import collections
from ddserver.utils.deps import export, require, extend
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
. Output only the next line. | @require(session = 'ddserver.interface.session:SessionManager') |
Here is a snippet: <|code_start|> if not session.messages:
session.messages = []
session.messages.append(self.Message(level = level,
message = message))
session.save()
def success(self, message):
self.__push(self.Level.success, message)
def error(self, message):
self.__push(self.Level.error, message)
@require(session = 'ddserver.interface.session:SessionManager')
def popall(self, session):
if not session.messages:
return []
messages = session.messages
session.messages = []
session.save()
return messages
<|code_end|>
. Write the next line using the current file imports:
import enum
import collections
from ddserver.utils.deps import export, require, extend
and context from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
, which may include functions, classes, or code. Output only the next line. | @extend('ddserver.interface.template:TemplateManager') |
Using the snippet: <|code_start|>'''
Copyright 2013 Dustin Frisch<fooker@lab.sh>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
, determine the next line of code. You have imports:
import ddserver.interface.pages.index # @UnusedImport: for web application
import ddserver.interface.pages.signup # @UnusedImport: for web application
import ddserver.interface.pages.lostpasswd # @UnusedImport: for web application
import ddserver.interface.pages.login # @UnusedImport: for web application
import ddserver.interface.pages.user.account # @UnusedImport: for web application
import ddserver.interface.pages.user.hosts # @UnusedImport: for web application
import ddserver.interface.pages.user.host # @UnusedImport: for web application
import ddserver.interface.pages.admin.users # @UnusedImport: for web application
import ddserver.interface.pages.admin.suffixes # @UnusedImport: for web application
from ddserver.utils.deps import require
and context (class names, function names, or code) available:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @require(web = 'ddserver.web:Web') |
Here is a snippet: <|code_start|> ''' Provides a route to static files (like css, images, etc). '''
return bottle.static_file(path,
root = config.wsgi.static_files)
@route('/', method = 'GET')
@require(db = 'ddserver.db:Database',
templates = 'ddserver.interface.template:TemplateManager',
session = 'ddserver.interface.session:SessionManager')
def get_index(db,
templates,
session):
''' Display the index page. '''
if session.username:
(users, zones, hosts, userhosts) = get_statistics()
return templates['index.html'](users = users,
zones = zones,
hosts = hosts,
userhosts = userhosts,
current_ip = bottle.request.remote_addr)
else:
return templates['index.html']()
@require(db = 'ddserver.db:Database')
<|code_end|>
. Write the next line using the current file imports:
import os
import bottle
from ddserver.web import route
from ddserver.interface.user import authorized
from ddserver.utils.deps import require, extend
and context from other files:
# Path: ddserver/interface/user.py
# @property
# @require(session = 'ddserver.interface.session:SessionManager')
# def authorized(self, session):
# if session.username:
# return self[session.username]
#
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
, which may include functions, classes, or code. Output only the next line. | @authorized() |
Continue the code snippet: <|code_start|>it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@extend('ddserver.config:ConfigDeclaration')
def config_wsgi(config_decl):
with config_decl.declare('wsgi') as s:
s('static_files',
conv = str,
default = '/usr/share/ddserver/static')
@route('/static/<path:path>', method = 'GET')
<|code_end|>
. Use current file imports:
import os
import bottle
from ddserver.web import route
from ddserver.interface.user import authorized
from ddserver.utils.deps import require, extend
and context (classes, functions, or code) from other files:
# Path: ddserver/interface/user.py
# @property
# @require(session = 'ddserver.interface.session:SessionManager')
# def authorized(self, session):
# if session.username:
# return self[session.username]
#
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
. Output only the next line. | @require(config = 'ddserver.config:Config') |
Here is a snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
. Write the next line using the current file imports:
import os
import bottle
from ddserver.web import route
from ddserver.interface.user import authorized
from ddserver.utils.deps import require, extend
and context from other files:
# Path: ddserver/interface/user.py
# @property
# @require(session = 'ddserver.interface.session:SessionManager')
# def authorized(self, session):
# if session.username:
# return self[session.username]
#
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
, which may include functions, classes, or code. Output only the next line. | @extend('ddserver.config:ConfigDeclaration') |
Given the following code snippet before the placeholder: <|code_start|>'''
Copyright 2013 Dustin Frisch<fooker@lab.sh>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
, predict the next line using imports from the current file:
import contextlib
import threading
import MySQLdb.cursors
from ddserver.utils.deps import extend, export, require
and context including class names, function names, and sometimes code from other files:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @extend('ddserver.config:ConfigDeclaration') |
Continue the code snippet: <|code_start|>
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@extend('ddserver.config:ConfigDeclaration')
def config_db(config_decl):
with config_decl.declare('db') as s:
s('host',
conv = str,
default = 'localhost')
s('port',
conv = int,
default = 3306)
s('name',
conv = str,
default = 'ddserver')
s('username',
conv = str,
default = 'ddserver')
s('password',
conv = str)
<|code_end|>
. Use current file imports:
import contextlib
import threading
import MySQLdb.cursors
from ddserver.utils.deps import extend, export, require
and context (classes, functions, or code) from other files:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @export() |
Predict the next line for this snippet: <|code_start|>
@extend('ddserver.config:ConfigDeclaration')
def config_db(config_decl):
with config_decl.declare('db') as s:
s('host',
conv = str,
default = 'localhost')
s('port',
conv = int,
default = 3306)
s('name',
conv = str,
default = 'ddserver')
s('username',
conv = str,
default = 'ddserver')
s('password',
conv = str)
@export()
class Database(object):
thread_local = threading.local()
@contextlib.contextmanager
<|code_end|>
with the help of current file imports:
import contextlib
import threading
import MySQLdb.cursors
from ddserver.utils.deps import extend, export, require
and context from other files:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
, which may contain function names, class names, or code. Output only the next line. | @require(config = 'ddserver.config:Config') |
Using the snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@route('/login', method = 'POST')
@validate('/',
username = validation.ValidUsername(min = 1, max = 255),
password = validation.String())
<|code_end|>
, determine the next line of code. You have imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
and context (class names, function names, or code) available:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @require(users = 'ddserver.interface.user:UserManager') |
Based on the snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@route('/lostpass', method = 'GET')
<|code_end|>
, predict the immediate next line with the help of imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from ddserver.interface.captcha import captcha_check
from passlib.apps import custom_app_context as pwd
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/captcha.py
# def captcha_check(__on_error__):
# ''' Checks if the captcha challenge and response in the request are matching.
#
# The challenge and response values are extracted from the POST data and
# passed to the recaptcha API.
#
# @param __on_error__: The target to redirect if the check failed
# '''
#
# def wrapper(func):
# @require(config = 'ddserver.config:Config',
# users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(config,
# users,
# messages,
# *args,
# **kwargs):
# if config.captcha.enabled:
# from recaptcha.client import captcha
#
# challenge = bottle.request.POST.pop('recaptcha_challenge_field', None)
# response = bottle.request.POST.pop('recaptcha_response_field', None)
#
# if challenge is None or response is None:
# messages.error('Captcha values are missing')
# bottle.redirect('/')
#
# result = captcha.submit(challenge,
# response,
# config.captcha.recaptcha_private_key,
# bottle.request.remote_addr)
#
# if not result.is_valid:
# messages.error('Captcha invalid')
# bottle.redirect(__on_error__)
#
# # Call the wrapped function
# return func(*args,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @require(config = 'ddserver.config:Config', |
Using the snippet: <|code_start|> users,
emails,
messages):
# Generate a authcode for the user
users.generate_authcode(data.username)
# Fetch user info
user = users[data.username]
emails.to_user('lostpasswd.mail',
user = user)
messages.success('Password recovery email has been sent.')
bottle.redirect('/')
@route('/lostpass/recover', method = 'GET')
@require(templates = 'ddserver.interface.template:TemplateManager')
def get_lostpass_setnew(templates):
username = bottle.request.query.username
authcode = bottle.request.query.authcode
return templates['resetpass.html'](username = username,
authcode = authcode)
@route('/lostpass/setnew', method = 'POST')
<|code_end|>
, determine the next line of code. You have imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from ddserver.interface.captcha import captcha_check
from passlib.apps import custom_app_context as pwd
and context (class names, function names, or code) available:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/captcha.py
# def captcha_check(__on_error__):
# ''' Checks if the captcha challenge and response in the request are matching.
#
# The challenge and response values are extracted from the POST data and
# passed to the recaptcha API.
#
# @param __on_error__: The target to redirect if the check failed
# '''
#
# def wrapper(func):
# @require(config = 'ddserver.config:Config',
# users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(config,
# users,
# messages,
# *args,
# **kwargs):
# if config.captcha.enabled:
# from recaptcha.client import captcha
#
# challenge = bottle.request.POST.pop('recaptcha_challenge_field', None)
# response = bottle.request.POST.pop('recaptcha_response_field', None)
#
# if challenge is None or response is None:
# messages.error('Captcha values are missing')
# bottle.redirect('/')
#
# result = captcha.submit(challenge,
# response,
# config.captcha.recaptcha_private_key,
# bottle.request.remote_addr)
#
# if not result.is_valid:
# messages.error('Captcha invalid')
# bottle.redirect(__on_error__)
#
# # Call the wrapped function
# return func(*args,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @authorized_by_code() |
Based on the snippet: <|code_start|>License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@route('/lostpass', method = 'GET')
@require(config = 'ddserver.config:Config',
templates = 'ddserver.interface.template:TemplateManager')
def get_lostpass(config,
templates):
return templates['lostpass.html']()
@route('/lostpass', method = 'POST')
<|code_end|>
, predict the immediate next line with the help of imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from ddserver.interface.captcha import captcha_check
from passlib.apps import custom_app_context as pwd
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/captcha.py
# def captcha_check(__on_error__):
# ''' Checks if the captcha challenge and response in the request are matching.
#
# The challenge and response values are extracted from the POST data and
# passed to the recaptcha API.
#
# @param __on_error__: The target to redirect if the check failed
# '''
#
# def wrapper(func):
# @require(config = 'ddserver.config:Config',
# users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(config,
# users,
# messages,
# *args,
# **kwargs):
# if config.captcha.enabled:
# from recaptcha.client import captcha
#
# challenge = bottle.request.POST.pop('recaptcha_challenge_field', None)
# response = bottle.request.POST.pop('recaptcha_response_field', None)
#
# if challenge is None or response is None:
# messages.error('Captcha values are missing')
# bottle.redirect('/')
#
# result = captcha.submit(challenge,
# response,
# config.captcha.recaptcha_private_key,
# bottle.request.remote_addr)
#
# if not result.is_valid:
# messages.error('Captcha invalid')
# bottle.redirect(__on_error__)
#
# # Call the wrapped function
# return func(*args,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @captcha_check('/lostpass') |
Next line prediction: <|code_start|>'''
Copyright 2013 Dustin Frisch <fooker@lab.sh>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
. Use current file imports:
(import ConfigParser as configparser
import collections
import contextlib
from ddserver.utils.deps import export)
and context including class names, function names, or small code snippets from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
. Output only the next line. | @export() |
Continue the code snippet: <|code_start|>
@extend('ddserver.config:ConfigDeclaration')
def config_email(config_decl):
with config_decl.declare('smtp') as s:
s('host',
conv = str,
default = 'localhost')
s('port',
conv = int,
default = 25)
with config_decl.declare('contact') as s:
s('name',
conv = str,
default = 'Your Administrator')
s('email',
conv = str)
with config_decl.declare('wsgi') as s:
s('protocol',
conv = str,
default = 'http://')
with config_decl.declare('wsgi') as s:
s('basename',
conv = str,
default = 'localhost:8080')
<|code_end|>
. Use current file imports:
import jinja2
import smtplib
from ddserver.utils.deps import export, extend, require
and context (classes, functions, or code) from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @export() |
Continue the code snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
. Use current file imports:
import jinja2
import smtplib
from ddserver.utils.deps import export, extend, require
and context (classes, functions, or code) from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @extend('ddserver.config:ConfigDeclaration') |
Based on the snippet: <|code_start|> s('port',
conv = int,
default = 25)
with config_decl.declare('contact') as s:
s('name',
conv = str,
default = 'Your Administrator')
s('email',
conv = str)
with config_decl.declare('wsgi') as s:
s('protocol',
conv = str,
default = 'http://')
with config_decl.declare('wsgi') as s:
s('basename',
conv = str,
default = 'localhost:8080')
@export()
class EmailManager(object):
def __init__(self):
self.__environment = jinja2.Environment(loader = jinja2.PackageLoader('ddserver.resources',
'email'))
<|code_end|>
, predict the immediate next line with the help of imports:
import jinja2
import smtplib
from ddserver.utils.deps import export, extend, require
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @require(config = 'ddserver.config:Config', |
Continue the code snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
. Use current file imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import extend, require
from ddserver.interface.user import authorized
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from passlib.apps import custom_app_context as pwd
and context (classes, functions, or code) from other files:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# @property
# @require(session = 'ddserver.interface.session:SessionManager')
# def authorized(self, session):
# if session.username:
# return self[session.username]
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @extend('ddserver.config:ConfigDeclaration') |
Given the code snippet: <|code_start|>License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@extend('ddserver.config:ConfigDeclaration')
def config_auth(config_decl):
with config_decl.declare('auth') as s:
s('password_min_chars',
conv = int,
default = 8)
@route('/user/account', method = 'GET')
@authorized()
<|code_end|>
, generate the next line using the imports in this file:
import bottle
from ddserver.web import route
from ddserver.utils.deps import extend, require
from ddserver.interface.user import authorized
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from passlib.apps import custom_app_context as pwd
and context (functions, classes, or occasionally code) from other files:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# @property
# @require(session = 'ddserver.interface.session:SessionManager')
# def authorized(self, session):
# if session.username:
# return self[session.username]
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @require(template = 'ddserver.interface.template:TemplateManager') |
Predict the next line after this snippet: <|code_start|>published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@extend('ddserver.config:ConfigDeclaration')
def config_auth(config_decl):
with config_decl.declare('auth') as s:
s('password_min_chars',
conv = int,
default = 8)
@route('/user/account', method = 'GET')
<|code_end|>
using the current file's imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import extend, require
from ddserver.interface.user import authorized
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from passlib.apps import custom_app_context as pwd
and any relevant context from other files:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# @property
# @require(session = 'ddserver.interface.session:SessionManager')
# def authorized(self, session):
# if session.username:
# return self[session.username]
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @authorized() |
Based on the snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@route('/admin/suffixes/list', method = 'GET')
@authorized_admin()
<|code_end|>
, predict the immediate next line with the help of imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require
from ddserver.interface.user import authorized_admin
from ddserver.interface import validation
from ddserver.interface.validation import validate
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# class UserManager(object):
# def __getitem__(self,
# key,
# db):
# def login(self,
# session,
# messages,
# username,
# password):
# def logout(self,
# session,
# messages):
# def generate_authcode(self, username, db):
# def authorized(self, session):
# def authorized(admin = False):
# def wrapper(func):
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# def authorized_by_code():
# def wrapper(func):
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# def template_auth(templates):
# def __(users):
. Output only the next line. | @require(db = 'ddserver.db:Database', |
Predict the next line for this snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@route('/admin/suffixes/list', method = 'GET')
<|code_end|>
with the help of current file imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require
from ddserver.interface.user import authorized_admin
from ddserver.interface import validation
from ddserver.interface.validation import validate
and context from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/user.py
# class UserManager(object):
# def __getitem__(self,
# key,
# db):
# def login(self,
# session,
# messages,
# username,
# password):
# def logout(self,
# session,
# messages):
# def generate_authcode(self, username, db):
# def authorized(self, session):
# def authorized(admin = False):
# def wrapper(func):
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# def authorized_by_code():
# def wrapper(func):
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# def template_auth(templates):
# def __(users):
, which may contain function names, class names, or code. Output only the next line. | @authorized_admin() |
Given snippet: <|code_start|>'''
Copyright 2013 Dustin Frisch <fooker@lab.sh>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import bottle
from ddserver.utils.deps import extend, require
from recaptcha.client import captcha
and context:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
which might include code, classes, or functions. Output only the next line. | @extend('ddserver.config:ConfigDeclaration') |
Using the snippet: <|code_start|>
@extend('ddserver.config:ConfigDeclaration')
def config_captcha(config_decl):
with config_decl.declare('captcha') as s:
s('enabled',
conv = bool,
default = False)
s('recaptcha_public_key',
conv = str,
default = '')
s('recaptcha_private_key',
conv = str,
default = '')
def captcha_check(__on_error__):
''' Checks if the captcha challenge and response in the request are matching.
The challenge and response values are extracted from the POST data and
passed to the recaptcha API.
@param __on_error__: The target to redirect if the check failed
'''
def wrapper(func):
<|code_end|>
, determine the next line of code. You have imports:
import bottle
from ddserver.utils.deps import extend, require
from recaptcha.client import captcha
and context (class names, function names, or code) available:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @require(config = 'ddserver.config:Config', |
Based on the snippet: <|code_start|>"""
Copyright 2013 Dustin Frisch<fooker@lab.sh>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from ddserver.utils.deps import require
import ddserver.updater.nic # @UnusedImport: for web application
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @require(web='ddserver.web:Web') |
Given snippet: <|code_start|>Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@extend('ddserver.web:Middleware')
def middleware_session(middleware):
return beaker.middleware.SessionMiddleware(middleware,
{'session.cookie_expires': True})
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import bottle
import beaker.middleware
from ddserver.utils.deps import export, extend, require
and context:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
which might include code, classes, or functions. Output only the next line. | @export() |
Given the following code snippet before the placeholder: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
, predict the next line using imports from the current file:
import bottle
import beaker.middleware
from ddserver.utils.deps import export, extend, require
and context including class names, function names, and sometimes code from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @extend('ddserver.web:Middleware') |
Based on the snippet: <|code_start|>
@property
def session(self):
return bottle.request.environ.get('beaker.session')
def __getattr__(self, key):
try:
return self.session[key]
except KeyError:
return None
def __setattr__(self, key, value):
self.session[key] = value
def __delattr__(self, key):
del self.session[key]
def save(self):
self.session.save()
@extend('ddserver.interface.template:TemplateManager')
def template_session(templates):
<|code_end|>
, predict the immediate next line with the help of imports:
import bottle
import beaker.middleware
from ddserver.utils.deps import export, extend, require
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @require(session = 'ddserver.interface.session:SessionManager') |
Given the code snippet: <|code_start|>'''
Copyright 2013 Dustin Frisch <fooker@lab.sh>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
, generate the next line using the imports in this file:
from ddserver.utils.deps import export, extend, require
import functools
import jinja2
and context (functions, classes, or occasionally code) from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @export() |
Predict the next line after this snippet: <|code_start|>
def __getitem__(self, key):
''' Returns a template render function for the requested template.
@param key: the name of the template
'''
# Generate the globals and get the template from the environment
template = self.__environment.get_template(key)
c = self.__globals['config']()
# Return the render function of the template
return functools.partial(template.render, **{name : func()
for name, func
in self.__globals.iteritems()})
@property
def globals(self):
''' The registered globals to inject in each template.
All values of this dict must be functions returning the global.
'''
return self.__globals
<|code_end|>
using the current file's imports:
from ddserver.utils.deps import export, extend, require
import functools
import jinja2
and any relevant context from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @extend('ddserver.interface.template:TemplateManager') |
Given the code snippet: <|code_start|> def __getitem__(self, key):
''' Returns a template render function for the requested template.
@param key: the name of the template
'''
# Generate the globals and get the template from the environment
template = self.__environment.get_template(key)
c = self.__globals['config']()
# Return the render function of the template
return functools.partial(template.render, **{name : func()
for name, func
in self.__globals.iteritems()})
@property
def globals(self):
''' The registered globals to inject in each template.
All values of this dict must be functions returning the global.
'''
return self.__globals
@extend('ddserver.interface.template:TemplateManager')
def template_config(templates):
<|code_end|>
, generate the next line using the imports in this file:
from ddserver.utils.deps import export, extend, require
import functools
import jinja2
and context (functions, classes, or occasionally code) from other files:
# Path: ddserver/utils/deps.py
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
. Output only the next line. | @require(config = 'ddserver.config:Config') |
Predict the next line after this snippet: <|code_start|>'''
Copyright 2013 Dustin Frisch<fooker@lab.sh>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
using the current file's imports:
import sys
import logging
from ddserver.utils.deps import extend, export
and any relevant context from other files:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
. Output only the next line. | @extend('ddserver.config:ConfigDeclaration') |
Using the snippet: <|code_start|>
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@extend('ddserver.config:ConfigDeclaration')
def config_logging(config_decl):
with config_decl.declare('logging') as s:
s('verbose',
conv = bool,
default = False)
s('file',
conv = str,
default = '/var/log/ddserver.log')
<|code_end|>
, determine the next line of code. You have imports:
import sys
import logging
from ddserver.utils.deps import extend, export
and context (class names, function names, or code) available:
# Path: ddserver/utils/deps.py
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# def export(**requirements):
# ''' Decorator to export a factory.
#
# Requirements for the factory can be specified. These requirements are
# passed to the wrapped function as specified by the `require` decorator.
# '''
#
# def wrapper(func):
# return Export(factory = require(**requirements)(func))
#
# return wrapper
. Output only the next line. | @export(config = 'ddserver.config:Config') |
Based on the snippet: <|code_start|>
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
"""
# See http://doc.powerdns.com/html/backends-detail.html#pipebackend
# for further protocol specification
# Declaration of the PowerDNS pipe protocol
lexer = LexerDeclaration(splitter='\t',
messages=(MessageDeclaration('HELO',
FieldDeclaration('version', int)),
MessageDeclaration('Q',
FieldDeclaration('qname', str),
FieldDeclaration('qclass', str),
FieldDeclaration('qtype', str),
FieldDeclaration('id', int),
FieldDeclaration('remote', str)),
MessageDeclaration('AXFR',
FieldDeclaration('id', int)),
MessageDeclaration('PING')))
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
from ddserver.utils.deps import require, extend
from ddserver.utils.txtprot import (LexerDeclaration,
FormatterDeclaration,
MessageDeclaration,
FieldDeclaration)
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# Path: ddserver/utils/txtprot.py
# class LexerDeclaration(object):
# ''' Declaration of a lexer. '''
#
# def __init__(self, messages, splitter = ' '):
# ''' Declares a protocol.
#
# @param splitter: the character used to separate field in messages
# @param messages: the messages declared for this protocol
# '''
#
# self.__splitter = splitter
# self.__messages = {message.tag : message
# for message
# in messages}
#
#
# def __call__(self, line):
# ''' Lex the line. '''
#
# # Strip of surrounding white spaces and tailing new line and split the
# # message into parts separated by the splitting character
# message = line.strip().split(self.__splitter)
#
# # Split message in tag and values
# tag, values = message[0], message[1:]
#
# # Find message declaration for tag and lex the values using this message
# # declaration or return None if the tag is unknown
# if tag in self.__messages:
# return self.__messages[tag].lex(values)
#
# else:
# return None
#
#
# def __getattr__(self, key):
# ''' Returns a message declaration for the given key. '''
#
# return self.__messages[key]
#
# class FormatterDeclaration(object):
# def __init__(self, messages, splitter = ' '):
# self.__splitter = splitter
# self.__messages = {message.tag : message
# for message
# in messages}
#
#
# def __call__(self, message):
# # Find the message declaration for tag and format the values using this
# # message declaration
# load = self.__messages[message.tag].format(message)
#
# # Join the message parts separated by the splitter character
# return self.__splitter.join([message.tag] + load)
#
#
#
# def __getattr__(self, key):
# ''' Returns a message declaration for the given key. '''
#
# return self.__messages[key]
#
# class MessageDeclaration(object):
# ''' Declaration of a message type. '''
#
#
# def __init__(self, tag, *fields):
# ''' Declares a message.
#
# @param tag: the tag used to identify the message type
# @param fields: the fields declared for the message
# '''
#
# self.__tag = tag
# self.__fields = fields
#
# self.__type = collections.namedtuple(self.__tag, ['tag'] + [field.name
# for field
# in self.__fields])
#
#
# @property
# def tag(self):
# ''' Returns the tag. '''
#
# return self.__tag
#
#
# def lex(self, load):
# ''' Lex the message. '''
#
# return self(**{field.name : field.lex(value)
# for field, value
# in itertools.izip(self.__fields,
# load)})
#
#
# def format(self, message):
# ''' Format the message. '''
#
# # Format the values in the message skipping the first value as it is the tag
# return [field.format(value)
# for field, value
# in itertools.izip(self.__fields,
# message[1:])]
#
#
# def __call__(self, *args, **kwargs):
# return self.__type(tag = self.__tag, *args, **kwargs)
#
# class FieldDeclaration(object):
# ''' Declaration of a message field. '''
#
# def __init__(self, name, conv):
# ''' Declares a field.
#
# @param name: the name of the field - this name is used as property name
# of parsed messages
# @param conv: the type converter function used to parse the field - the
# function must accept a string and return a value
# '''
#
# self.__name = name
# self.__conv = conv
#
#
# @property
# def name(self):
# ''' Returns the name of the field. '''
# return self.__name
#
#
# def lex(self, value):
# ''' Lex the field. '''
#
# return self.__conv(value)
#
#
# def format(self, value):
# ''' Format the field. '''
#
# return str(value)
. Output only the next line. | formatter = FormatterDeclaration(splitter='\t', |
Given the code snippet: <|code_start|>
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
@extend('ddserver.config:ConfigDeclaration')
def config_signup(config_decl):
with config_decl.declare('signup') as s:
s('enabled',
conv = bool,
default = True)
s('allowed_maildomains',
conv = str,
default = 'any')
s('notify_admin',
conv = bool,
default = True)
@route('/signup', method = 'GET')
<|code_end|>
, generate the next line using the imports in this file:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require, extend
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from ddserver.interface.captcha import captcha_check
from passlib.apps import custom_app_context as pwd
and context (functions, classes, or occasionally code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/captcha.py
# def captcha_check(__on_error__):
# ''' Checks if the captcha challenge and response in the request are matching.
#
# The challenge and response values are extracted from the POST data and
# passed to the recaptcha API.
#
# @param __on_error__: The target to redirect if the check failed
# '''
#
# def wrapper(func):
# @require(config = 'ddserver.config:Config',
# users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(config,
# users,
# messages,
# *args,
# **kwargs):
# if config.captcha.enabled:
# from recaptcha.client import captcha
#
# challenge = bottle.request.POST.pop('recaptcha_challenge_field', None)
# response = bottle.request.POST.pop('recaptcha_response_field', None)
#
# if challenge is None or response is None:
# messages.error('Captcha values are missing')
# bottle.redirect('/')
#
# result = captcha.submit(challenge,
# response,
# config.captcha.recaptcha_private_key,
# bottle.request.remote_addr)
#
# if not result.is_valid:
# messages.error('Captcha invalid')
# bottle.redirect(__on_error__)
#
# # Call the wrapped function
# return func(*args,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @require(config = 'ddserver.config:Config', |
Based on the snippet: <|code_start|>'''
Copyright 2013 Sven Reissmann <sven@0x80.io>
This file is part of ddserver.
ddserver is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
ddserver is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ddserver. If not, see <http://www.gnu.org/licenses/>.
'''
<|code_end|>
, predict the immediate next line with the help of imports:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require, extend
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from ddserver.interface.captcha import captcha_check
from passlib.apps import custom_app_context as pwd
and context (classes, functions, sometimes code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/captcha.py
# def captcha_check(__on_error__):
# ''' Checks if the captcha challenge and response in the request are matching.
#
# The challenge and response values are extracted from the POST data and
# passed to the recaptcha API.
#
# @param __on_error__: The target to redirect if the check failed
# '''
#
# def wrapper(func):
# @require(config = 'ddserver.config:Config',
# users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(config,
# users,
# messages,
# *args,
# **kwargs):
# if config.captcha.enabled:
# from recaptcha.client import captcha
#
# challenge = bottle.request.POST.pop('recaptcha_challenge_field', None)
# response = bottle.request.POST.pop('recaptcha_response_field', None)
#
# if challenge is None or response is None:
# messages.error('Captcha values are missing')
# bottle.redirect('/')
#
# result = captcha.submit(challenge,
# response,
# config.captcha.recaptcha_private_key,
# bottle.request.remote_addr)
#
# if not result.is_valid:
# messages.error('Captcha invalid')
# bottle.redirect(__on_error__)
#
# # Call the wrapped function
# return func(*args,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @extend('ddserver.config:ConfigDeclaration') |
Given the following code snippet before the placeholder: <|code_start|> # Get user record
user = users[data.username]
messages.success('Your account has been created and will be reviewed by an administrator.')
# Notify the admin about the new account
if config.signup.notify_admin:
try:
emails.to_admin('signup_notify.mail',
user = user)
except:
messages.error('Failed to notify the administrator. Please contact %s' %
config.contact.email)
bottle.redirect('/')
@route('/signup/activate', method = 'GET')
@require(templates = 'ddserver.interface.template:TemplateManager')
def get_signup_activate(templates):
''' Displays the activation form. '''
return templates['activate.html'](username = bottle.request.query.username,
authcode = bottle.request.query.authcode)
@route('/signup/activate', method = 'POST')
<|code_end|>
, predict the next line using imports from the current file:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require, extend
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from ddserver.interface.captcha import captcha_check
from passlib.apps import custom_app_context as pwd
and context including class names, function names, and sometimes code from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/captcha.py
# def captcha_check(__on_error__):
# ''' Checks if the captcha challenge and response in the request are matching.
#
# The challenge and response values are extracted from the POST data and
# passed to the recaptcha API.
#
# @param __on_error__: The target to redirect if the check failed
# '''
#
# def wrapper(func):
# @require(config = 'ddserver.config:Config',
# users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(config,
# users,
# messages,
# *args,
# **kwargs):
# if config.captcha.enabled:
# from recaptcha.client import captcha
#
# challenge = bottle.request.POST.pop('recaptcha_challenge_field', None)
# response = bottle.request.POST.pop('recaptcha_response_field', None)
#
# if challenge is None or response is None:
# messages.error('Captcha values are missing')
# bottle.redirect('/')
#
# result = captcha.submit(challenge,
# response,
# config.captcha.recaptcha_private_key,
# bottle.request.remote_addr)
#
# if not result.is_valid:
# messages.error('Captcha invalid')
# bottle.redirect(__on_error__)
#
# # Call the wrapped function
# return func(*args,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @authorized_by_code() |
Given the code snippet: <|code_start|> conv = bool,
default = True)
@route('/signup', method = 'GET')
@require(config = 'ddserver.config:Config',
templates = 'ddserver.interface.template:TemplateManager',
messages = 'ddserver.interface.message:MessageManager',
session = 'ddserver.interface.session:SessionManager')
def get_signup(config,
templates,
messages,
session):
''' Display the sign up page. '''
if config.signup.enabled:
if not session.username:
return templates['signup.html']()
else:
messages.error('You can not signup for an account while you are logged in.')
bottle.redirect('/')
else:
return templates['nosignup.html']()
@route('/signup', method = 'POST')
<|code_end|>
, generate the next line using the imports in this file:
import bottle
from ddserver.web import route
from ddserver.utils.deps import require, extend
from ddserver.interface.user import authorized_by_code
from ddserver.interface import validation
from ddserver.interface.validation import validate
from ddserver.interface.captcha import captcha_check
from passlib.apps import custom_app_context as pwd
and context (functions, classes, or occasionally code) from other files:
# Path: ddserver/utils/deps.py
# def require(**requirements):
# ''' Decorator to inject requirements into a function.
#
# The decorated function is called with a named argument for each
# specified requirement containing the exported instances.
# '''
#
# exports = {name : Export.load(requirement)
# for name, requirement
# in requirements.iteritems()}
#
# def wrapper(func):
# def wrapped(*args, **kwargs):
# # Update the keyword arguments with the required instances
# kwargs.update({name : export.instance
# for name, export
# in exports.iteritems()
# if name not in kwargs})
#
# return func(*args,
# **kwargs)
#
# wrapped.__name__ = func.__name__
#
# return wrapped
# return wrapper
#
# def extend(self, extend):
# ''' Extends this export.
#
# The instance created by the wrapped factory is extended by passing the
# created instance to the given extend function after creation.
#
# The extend function must accept the instance as its only argument. If
# the function returns a value which is not None, the instance is replaced
# with the returned value.
# '''
#
# assert self.__instance is None
#
# self.__extends.append(extend)
#
# Path: ddserver/interface/user.py
# def authorized_by_code():
# ''' Checks if a valid username and authcode is passed. '''
#
# def wrapper(func):
# @require(users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(users,
# messages,
# *args,
# **kwargs):
# if (bottle.request.query.username == "" or
# bottle.request.query.authcode == ""):
# messages.error('You have to provide username and authcode.')
# bottle.redirect('/')
#
# username = bottle.request.query.username
# authcode = bottle.request.query.authcode
#
# user = users[username]
#
# if user == None:
# messages.error('The username does not exist.')
# bottle.redirect('/')
#
# if user.authcode != authcode:
# messages.error('The auth code you provided was invalid.')
# bottle.redirect('/')
#
# # Inject the user in the wrapped function
# return func(*args,
# user = user,
# **kwargs)
#
# return wrapped
# return wrapper
#
# Path: ddserver/interface/captcha.py
# def captcha_check(__on_error__):
# ''' Checks if the captcha challenge and response in the request are matching.
#
# The challenge and response values are extracted from the POST data and
# passed to the recaptcha API.
#
# @param __on_error__: The target to redirect if the check failed
# '''
#
# def wrapper(func):
# @require(config = 'ddserver.config:Config',
# users = 'ddserver.interface.user:UserManager',
# messages = 'ddserver.interface.message:MessageManager')
# def wrapped(config,
# users,
# messages,
# *args,
# **kwargs):
# if config.captcha.enabled:
# from recaptcha.client import captcha
#
# challenge = bottle.request.POST.pop('recaptcha_challenge_field', None)
# response = bottle.request.POST.pop('recaptcha_response_field', None)
#
# if challenge is None or response is None:
# messages.error('Captcha values are missing')
# bottle.redirect('/')
#
# result = captcha.submit(challenge,
# response,
# config.captcha.recaptcha_private_key,
# bottle.request.remote_addr)
#
# if not result.is_valid:
# messages.error('Captcha invalid')
# bottle.redirect(__on_error__)
#
# # Call the wrapped function
# return func(*args,
# **kwargs)
#
# return wrapped
# return wrapper
. Output only the next line. | @captcha_check('/signup') |
Next line prediction: <|code_start|> exposure_structure,
exposure_population,
exposure_road,
]
for layer_path, expected_definition in zip(
layer_paths, expected_definitions):
path = standard_data_path(*layer_path)
layer, _ = load_layer(path)
actual_definition = layer_definition_type(layer)
try:
self.assertEqual(expected_definition, actual_definition)
except Exception as e:
LOGGER.error('Layer path: {path}'.format(
path=path))
LOGGER.error('Expected {name}'.format(
**expected_definition))
LOGGER.error('Actual {name}'.format(
**actual_definition))
raise e
# We are using multi hazard classification so this test will fail
# the layer needs to run on impact function first or we can inject
# the classification for this test.
def test_layer_hazard_classification(self):
"""Test layer_hazard_classification method.
.. versionadded:: 4.0
"""
layer_paths = self.layer_paths_list
expected_classifications = [
<|code_end|>
. Use current file imports:
(import logging
import unittest
from safe.definitions.constants import INASAFE_TEST
from safe.definitions.exposure import (
exposure_structure,
exposure_population,
exposure_road)
from safe.definitions.exposure_classifications import (
generic_structure_classes,
generic_road_classes)
from safe.definitions.hazard import (
hazard_generic,
hazard_earthquake,
hazard_tsunami,
hazard_cyclone)
from safe.definitions.hazard_classifications import (
generic_hazard_classes,
earthquake_mmi_scale,
tsunami_hazard_classes,
cyclone_au_bom_hazard_classes)
from safe.report.extractors.util import (
layer_definition_type,
layer_hazard_classification,
resolve_from_dictionary,
retrieve_exposure_classes_lists)
from safe.test.utilities import (
standard_data_path,
get_qgis_app)
from safe.gis.tools import load_layer)
and context including class names, function names, or small code snippets from other files:
# Path: safe/definitions/hazard_classifications.py
#
# Path: safe/gis/tools.py
# def load_layer(full_layer_uri_string, name=None, provider=None):
# """Helper to load and return a single QGIS layer based on our layer URI.
#
# :param provider: The provider name to use if known to open the layer.
# Default to None, we will try to guess it, but it's much better if you
# can provide it.
# :type provider:
#
# :param name: The name of the layer. If not provided, it will be computed
# based on the URI.
# :type name: basestring
#
# :param full_layer_uri_string: Layer URI, with provider type.
# :type full_layer_uri_string: str
#
# :returns: tuple containing layer and its layer_purpose.
# :rtype: (QgsMapLayer, str)
# """
# if provider:
# # Cool !
# layer_path = full_layer_uri_string
# else:
# # Let's check if the driver is included in the path
# layer_path, provider = decode_full_layer_uri(full_layer_uri_string)
#
# if not provider:
# # Let's try to check if it's file based and look for a extension
# if '|' in layer_path:
# clean_uri = layer_path.split('|')[0]
# else:
# clean_uri = layer_path
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[
# -1] # If path was absolute
# extension = os.path.splitext(file_name)[1]
# if extension in OGR_EXTENSIONS:
# provider = 'ogr'
# elif extension in GDAL_EXTENSIONS:
# provider = 'gdal'
# else:
# provider = None
#
# if not provider:
# layer = load_layer_without_provider(layer_path)
# else:
# layer = load_layer_with_provider(layer_path, provider)
#
# if not layer or not layer.isValid():
# message = 'Layer "%s" is not valid' % layer_path
# LOGGER.debug(message)
# raise InvalidLayerError(message)
#
# # Define the name
# if not name:
# source = layer.source()
# if '|' in source:
# clean_uri = source.split('|')[0]
# else:
# clean_uri = source
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[-1] # If path was absolute
# name = os.path.splitext(file_name)[0]
# else:
# # Might be a DB, take the DB name
# source = QgsDataSourceUri(source)
# name = source.table()
#
# if not name:
# name = 'default'
#
# if qgis_version() >= 21800:
# layer.setName(name)
# else:
# layer.setLayerName(name)
#
# # update the layer keywords
# monkey_patch_keywords(layer)
# layer_purpose = layer.keywords.get('layer_purpose')
#
# return layer, layer_purpose
. Output only the next line. | generic_hazard_classes, |
Predict the next line for this snippet: <|code_start|> exposure_population,
exposure_road,
]
for layer_path, expected_definition in zip(
layer_paths, expected_definitions):
path = standard_data_path(*layer_path)
layer, _ = load_layer(path)
actual_definition = layer_definition_type(layer)
try:
self.assertEqual(expected_definition, actual_definition)
except Exception as e:
LOGGER.error('Layer path: {path}'.format(
path=path))
LOGGER.error('Expected {name}'.format(
**expected_definition))
LOGGER.error('Actual {name}'.format(
**actual_definition))
raise e
# We are using multi hazard classification so this test will fail
# the layer needs to run on impact function first or we can inject
# the classification for this test.
def test_layer_hazard_classification(self):
"""Test layer_hazard_classification method.
.. versionadded:: 4.0
"""
layer_paths = self.layer_paths_list
expected_classifications = [
generic_hazard_classes,
<|code_end|>
with the help of current file imports:
import logging
import unittest
from safe.definitions.constants import INASAFE_TEST
from safe.definitions.exposure import (
exposure_structure,
exposure_population,
exposure_road)
from safe.definitions.exposure_classifications import (
generic_structure_classes,
generic_road_classes)
from safe.definitions.hazard import (
hazard_generic,
hazard_earthquake,
hazard_tsunami,
hazard_cyclone)
from safe.definitions.hazard_classifications import (
generic_hazard_classes,
earthquake_mmi_scale,
tsunami_hazard_classes,
cyclone_au_bom_hazard_classes)
from safe.report.extractors.util import (
layer_definition_type,
layer_hazard_classification,
resolve_from_dictionary,
retrieve_exposure_classes_lists)
from safe.test.utilities import (
standard_data_path,
get_qgis_app)
from safe.gis.tools import load_layer
and context from other files:
# Path: safe/definitions/hazard_classifications.py
#
# Path: safe/gis/tools.py
# def load_layer(full_layer_uri_string, name=None, provider=None):
# """Helper to load and return a single QGIS layer based on our layer URI.
#
# :param provider: The provider name to use if known to open the layer.
# Default to None, we will try to guess it, but it's much better if you
# can provide it.
# :type provider:
#
# :param name: The name of the layer. If not provided, it will be computed
# based on the URI.
# :type name: basestring
#
# :param full_layer_uri_string: Layer URI, with provider type.
# :type full_layer_uri_string: str
#
# :returns: tuple containing layer and its layer_purpose.
# :rtype: (QgsMapLayer, str)
# """
# if provider:
# # Cool !
# layer_path = full_layer_uri_string
# else:
# # Let's check if the driver is included in the path
# layer_path, provider = decode_full_layer_uri(full_layer_uri_string)
#
# if not provider:
# # Let's try to check if it's file based and look for a extension
# if '|' in layer_path:
# clean_uri = layer_path.split('|')[0]
# else:
# clean_uri = layer_path
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[
# -1] # If path was absolute
# extension = os.path.splitext(file_name)[1]
# if extension in OGR_EXTENSIONS:
# provider = 'ogr'
# elif extension in GDAL_EXTENSIONS:
# provider = 'gdal'
# else:
# provider = None
#
# if not provider:
# layer = load_layer_without_provider(layer_path)
# else:
# layer = load_layer_with_provider(layer_path, provider)
#
# if not layer or not layer.isValid():
# message = 'Layer "%s" is not valid' % layer_path
# LOGGER.debug(message)
# raise InvalidLayerError(message)
#
# # Define the name
# if not name:
# source = layer.source()
# if '|' in source:
# clean_uri = source.split('|')[0]
# else:
# clean_uri = source
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[-1] # If path was absolute
# name = os.path.splitext(file_name)[0]
# else:
# # Might be a DB, take the DB name
# source = QgsDataSourceUri(source)
# name = source.table()
#
# if not name:
# name = 'default'
#
# if qgis_version() >= 21800:
# layer.setName(name)
# else:
# layer.setLayerName(name)
#
# # update the layer keywords
# monkey_patch_keywords(layer)
# layer_purpose = layer.keywords.get('layer_purpose')
#
# return layer, layer_purpose
, which may contain function names, class names, or code. Output only the next line. | earthquake_mmi_scale, |
Predict the next line after this snippet: <|code_start|> exposure_road,
]
for layer_path, expected_definition in zip(
layer_paths, expected_definitions):
path = standard_data_path(*layer_path)
layer, _ = load_layer(path)
actual_definition = layer_definition_type(layer)
try:
self.assertEqual(expected_definition, actual_definition)
except Exception as e:
LOGGER.error('Layer path: {path}'.format(
path=path))
LOGGER.error('Expected {name}'.format(
**expected_definition))
LOGGER.error('Actual {name}'.format(
**actual_definition))
raise e
# We are using multi hazard classification so this test will fail
# the layer needs to run on impact function first or we can inject
# the classification for this test.
def test_layer_hazard_classification(self):
"""Test layer_hazard_classification method.
.. versionadded:: 4.0
"""
layer_paths = self.layer_paths_list
expected_classifications = [
generic_hazard_classes,
earthquake_mmi_scale,
<|code_end|>
using the current file's imports:
import logging
import unittest
from safe.definitions.constants import INASAFE_TEST
from safe.definitions.exposure import (
exposure_structure,
exposure_population,
exposure_road)
from safe.definitions.exposure_classifications import (
generic_structure_classes,
generic_road_classes)
from safe.definitions.hazard import (
hazard_generic,
hazard_earthquake,
hazard_tsunami,
hazard_cyclone)
from safe.definitions.hazard_classifications import (
generic_hazard_classes,
earthquake_mmi_scale,
tsunami_hazard_classes,
cyclone_au_bom_hazard_classes)
from safe.report.extractors.util import (
layer_definition_type,
layer_hazard_classification,
resolve_from_dictionary,
retrieve_exposure_classes_lists)
from safe.test.utilities import (
standard_data_path,
get_qgis_app)
from safe.gis.tools import load_layer
and any relevant context from other files:
# Path: safe/definitions/hazard_classifications.py
#
# Path: safe/gis/tools.py
# def load_layer(full_layer_uri_string, name=None, provider=None):
# """Helper to load and return a single QGIS layer based on our layer URI.
#
# :param provider: The provider name to use if known to open the layer.
# Default to None, we will try to guess it, but it's much better if you
# can provide it.
# :type provider:
#
# :param name: The name of the layer. If not provided, it will be computed
# based on the URI.
# :type name: basestring
#
# :param full_layer_uri_string: Layer URI, with provider type.
# :type full_layer_uri_string: str
#
# :returns: tuple containing layer and its layer_purpose.
# :rtype: (QgsMapLayer, str)
# """
# if provider:
# # Cool !
# layer_path = full_layer_uri_string
# else:
# # Let's check if the driver is included in the path
# layer_path, provider = decode_full_layer_uri(full_layer_uri_string)
#
# if not provider:
# # Let's try to check if it's file based and look for a extension
# if '|' in layer_path:
# clean_uri = layer_path.split('|')[0]
# else:
# clean_uri = layer_path
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[
# -1] # If path was absolute
# extension = os.path.splitext(file_name)[1]
# if extension in OGR_EXTENSIONS:
# provider = 'ogr'
# elif extension in GDAL_EXTENSIONS:
# provider = 'gdal'
# else:
# provider = None
#
# if not provider:
# layer = load_layer_without_provider(layer_path)
# else:
# layer = load_layer_with_provider(layer_path, provider)
#
# if not layer or not layer.isValid():
# message = 'Layer "%s" is not valid' % layer_path
# LOGGER.debug(message)
# raise InvalidLayerError(message)
#
# # Define the name
# if not name:
# source = layer.source()
# if '|' in source:
# clean_uri = source.split('|')[0]
# else:
# clean_uri = source
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[-1] # If path was absolute
# name = os.path.splitext(file_name)[0]
# else:
# # Might be a DB, take the DB name
# source = QgsDataSourceUri(source)
# name = source.table()
#
# if not name:
# name = 'default'
#
# if qgis_version() >= 21800:
# layer.setName(name)
# else:
# layer.setLayerName(name)
#
# # update the layer keywords
# monkey_patch_keywords(layer)
# layer_purpose = layer.keywords.get('layer_purpose')
#
# return layer, layer_purpose
. Output only the next line. | tsunami_hazard_classes, |
Next line prediction: <|code_start|> ]
for layer_path, expected_definition in zip(
layer_paths, expected_definitions):
path = standard_data_path(*layer_path)
layer, _ = load_layer(path)
actual_definition = layer_definition_type(layer)
try:
self.assertEqual(expected_definition, actual_definition)
except Exception as e:
LOGGER.error('Layer path: {path}'.format(
path=path))
LOGGER.error('Expected {name}'.format(
**expected_definition))
LOGGER.error('Actual {name}'.format(
**actual_definition))
raise e
# We are using multi hazard classification so this test will fail
# the layer needs to run on impact function first or we can inject
# the classification for this test.
def test_layer_hazard_classification(self):
"""Test layer_hazard_classification method.
.. versionadded:: 4.0
"""
layer_paths = self.layer_paths_list
expected_classifications = [
generic_hazard_classes,
earthquake_mmi_scale,
tsunami_hazard_classes,
<|code_end|>
. Use current file imports:
(import logging
import unittest
from safe.definitions.constants import INASAFE_TEST
from safe.definitions.exposure import (
exposure_structure,
exposure_population,
exposure_road)
from safe.definitions.exposure_classifications import (
generic_structure_classes,
generic_road_classes)
from safe.definitions.hazard import (
hazard_generic,
hazard_earthquake,
hazard_tsunami,
hazard_cyclone)
from safe.definitions.hazard_classifications import (
generic_hazard_classes,
earthquake_mmi_scale,
tsunami_hazard_classes,
cyclone_au_bom_hazard_classes)
from safe.report.extractors.util import (
layer_definition_type,
layer_hazard_classification,
resolve_from_dictionary,
retrieve_exposure_classes_lists)
from safe.test.utilities import (
standard_data_path,
get_qgis_app)
from safe.gis.tools import load_layer)
and context including class names, function names, or small code snippets from other files:
# Path: safe/definitions/hazard_classifications.py
#
# Path: safe/gis/tools.py
# def load_layer(full_layer_uri_string, name=None, provider=None):
# """Helper to load and return a single QGIS layer based on our layer URI.
#
# :param provider: The provider name to use if known to open the layer.
# Default to None, we will try to guess it, but it's much better if you
# can provide it.
# :type provider:
#
# :param name: The name of the layer. If not provided, it will be computed
# based on the URI.
# :type name: basestring
#
# :param full_layer_uri_string: Layer URI, with provider type.
# :type full_layer_uri_string: str
#
# :returns: tuple containing layer and its layer_purpose.
# :rtype: (QgsMapLayer, str)
# """
# if provider:
# # Cool !
# layer_path = full_layer_uri_string
# else:
# # Let's check if the driver is included in the path
# layer_path, provider = decode_full_layer_uri(full_layer_uri_string)
#
# if not provider:
# # Let's try to check if it's file based and look for a extension
# if '|' in layer_path:
# clean_uri = layer_path.split('|')[0]
# else:
# clean_uri = layer_path
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[
# -1] # If path was absolute
# extension = os.path.splitext(file_name)[1]
# if extension in OGR_EXTENSIONS:
# provider = 'ogr'
# elif extension in GDAL_EXTENSIONS:
# provider = 'gdal'
# else:
# provider = None
#
# if not provider:
# layer = load_layer_without_provider(layer_path)
# else:
# layer = load_layer_with_provider(layer_path, provider)
#
# if not layer or not layer.isValid():
# message = 'Layer "%s" is not valid' % layer_path
# LOGGER.debug(message)
# raise InvalidLayerError(message)
#
# # Define the name
# if not name:
# source = layer.source()
# if '|' in source:
# clean_uri = source.split('|')[0]
# else:
# clean_uri = source
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[-1] # If path was absolute
# name = os.path.splitext(file_name)[0]
# else:
# # Might be a DB, take the DB name
# source = QgsDataSourceUri(source)
# name = source.table()
#
# if not name:
# name = 'default'
#
# if qgis_version() >= 21800:
# layer.setName(name)
# else:
# layer.setLayerName(name)
#
# # update the layer keywords
# monkey_patch_keywords(layer)
# layer_purpose = layer.keywords.get('layer_purpose')
#
# return layer, layer_purpose
. Output only the next line. | cyclone_au_bom_hazard_classes, |
Next line prediction: <|code_start|> self.layer_paths_list = [
['gisv4', 'hazard', 'classified_vector.geojson'],
['gisv4', 'hazard', 'earthquake.asc'],
['gisv4', 'hazard', 'tsunami_vector.geojson'],
['gisv4', 'hazard', 'cyclone_AUBOM_km_h.asc'],
['gisv4', 'exposure', 'building-points.geojson'],
['gisv4', 'exposure', 'buildings.geojson'],
['gisv4', 'exposure', 'population.geojson'],
['gisv4', 'exposure', 'roads.geojson'],
]
def test_layer_definition_type(self):
"""Test layer_definition_type method.
.. versionadded:: 4.0
"""
layer_paths = self.layer_paths_list
expected_definitions = [
hazard_generic,
hazard_earthquake,
hazard_tsunami,
hazard_cyclone,
exposure_structure,
exposure_structure,
exposure_population,
exposure_road,
]
for layer_path, expected_definition in zip(
layer_paths, expected_definitions):
path = standard_data_path(*layer_path)
<|code_end|>
. Use current file imports:
(import logging
import unittest
from safe.definitions.constants import INASAFE_TEST
from safe.definitions.exposure import (
exposure_structure,
exposure_population,
exposure_road)
from safe.definitions.exposure_classifications import (
generic_structure_classes,
generic_road_classes)
from safe.definitions.hazard import (
hazard_generic,
hazard_earthquake,
hazard_tsunami,
hazard_cyclone)
from safe.definitions.hazard_classifications import (
generic_hazard_classes,
earthquake_mmi_scale,
tsunami_hazard_classes,
cyclone_au_bom_hazard_classes)
from safe.report.extractors.util import (
layer_definition_type,
layer_hazard_classification,
resolve_from_dictionary,
retrieve_exposure_classes_lists)
from safe.test.utilities import (
standard_data_path,
get_qgis_app)
from safe.gis.tools import load_layer)
and context including class names, function names, or small code snippets from other files:
# Path: safe/definitions/hazard_classifications.py
#
# Path: safe/gis/tools.py
# def load_layer(full_layer_uri_string, name=None, provider=None):
# """Helper to load and return a single QGIS layer based on our layer URI.
#
# :param provider: The provider name to use if known to open the layer.
# Default to None, we will try to guess it, but it's much better if you
# can provide it.
# :type provider:
#
# :param name: The name of the layer. If not provided, it will be computed
# based on the URI.
# :type name: basestring
#
# :param full_layer_uri_string: Layer URI, with provider type.
# :type full_layer_uri_string: str
#
# :returns: tuple containing layer and its layer_purpose.
# :rtype: (QgsMapLayer, str)
# """
# if provider:
# # Cool !
# layer_path = full_layer_uri_string
# else:
# # Let's check if the driver is included in the path
# layer_path, provider = decode_full_layer_uri(full_layer_uri_string)
#
# if not provider:
# # Let's try to check if it's file based and look for a extension
# if '|' in layer_path:
# clean_uri = layer_path.split('|')[0]
# else:
# clean_uri = layer_path
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[
# -1] # If path was absolute
# extension = os.path.splitext(file_name)[1]
# if extension in OGR_EXTENSIONS:
# provider = 'ogr'
# elif extension in GDAL_EXTENSIONS:
# provider = 'gdal'
# else:
# provider = None
#
# if not provider:
# layer = load_layer_without_provider(layer_path)
# else:
# layer = load_layer_with_provider(layer_path, provider)
#
# if not layer or not layer.isValid():
# message = 'Layer "%s" is not valid' % layer_path
# LOGGER.debug(message)
# raise InvalidLayerError(message)
#
# # Define the name
# if not name:
# source = layer.source()
# if '|' in source:
# clean_uri = source.split('|')[0]
# else:
# clean_uri = source
# is_file_based = os.path.exists(clean_uri)
# if is_file_based:
# # Extract basename and absolute path
# file_name = os.path.split(layer_path)[-1] # If path was absolute
# name = os.path.splitext(file_name)[0]
# else:
# # Might be a DB, take the DB name
# source = QgsDataSourceUri(source)
# name = source.table()
#
# if not name:
# name = 'default'
#
# if qgis_version() >= 21800:
# layer.setName(name)
# else:
# layer.setLayerName(name)
#
# # update the layer keywords
# monkey_patch_keywords(layer)
# layer_purpose = layer.keywords.get('layer_purpose')
#
# return layer, layer_purpose
. Output only the next line. | layer, _ = load_layer(path) |
Given snippet: <|code_start|># coding=utf-8
"""Definitions relating to pre-processing."""
__copyright__ = "Copyright 2017, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
LOGGER = logging.getLogger('InaSAFE')
def check_nearby_preprocessor(impact_function):
"""Checker for the nearby preprocessor.
:param impact_function: Impact function to check.
:type impact_function: ImpactFunction
:return: If the preprocessor can run.
:rtype: bool
"""
hazard_key = layer_purpose_hazard['key']
earthquake_key = hazard_earthquake['key']
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import os
from safe.definitions.exposure import exposure_place
from safe.definitions.hazard import hazard_earthquake
from safe.definitions.layer_purposes import (
layer_purpose_exposure,
layer_purpose_hazard,
layer_purpose_nearby_places,
layer_purpose,
layer_purpose_earthquake_contour,
)
from safe.gis.raster.contour import create_smooth_contour
from safe.processors import (
function_process,
)
from safe.utilities.gis import is_raster_layer
from safe.utilities.i18n import tr
from safe.test.utilities import load_test_vector_layer
from safe.gis.tools import load_layer
and context:
# Path: safe/definitions/layer_purposes.py
which might include code, classes, or functions. Output only the next line. | exposure_key = layer_purpose_exposure['key'] |
Given snippet: <|code_start|># coding=utf-8
"""Definitions relating to pre-processing."""
__copyright__ = "Copyright 2017, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
LOGGER = logging.getLogger('InaSAFE')
def check_nearby_preprocessor(impact_function):
"""Checker for the nearby preprocessor.
:param impact_function: Impact function to check.
:type impact_function: ImpactFunction
:return: If the preprocessor can run.
:rtype: bool
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import os
from safe.definitions.exposure import exposure_place
from safe.definitions.hazard import hazard_earthquake
from safe.definitions.layer_purposes import (
layer_purpose_exposure,
layer_purpose_hazard,
layer_purpose_nearby_places,
layer_purpose,
layer_purpose_earthquake_contour,
)
from safe.gis.raster.contour import create_smooth_contour
from safe.processors import (
function_process,
)
from safe.utilities.gis import is_raster_layer
from safe.utilities.i18n import tr
from safe.test.utilities import load_test_vector_layer
from safe.gis.tools import load_layer
and context:
# Path: safe/definitions/layer_purposes.py
which might include code, classes, or functions. Output only the next line. | hazard_key = layer_purpose_hazard['key'] |
Given snippet: <|code_start|> """Fake nearby preprocessor.
We can put here the function to generate contours or nearby places.
It must return a layer with a specific layer_purpose.
:return: The output layer.
:rtype: QgsMapLayer
"""
_ = impact_function # NOQA
fake_layer = load_test_vector_layer(
'gisv4',
'impacts',
'building-points-classified-vector.geojson',
clone_to_memory=True)
return fake_layer
pre_processors_nearby_places = {
'key': 'pre_processor_nearby_places',
'name': tr('Nearby Places Pre Processor'),
'description': tr('A fake pre processor.'),
'condition': check_nearby_preprocessor,
'process': {
'type': function_process,
'function': fake_nearby_preprocessor,
},
'output': {
'type': 'layer',
'key': layer_purpose,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import os
from safe.definitions.exposure import exposure_place
from safe.definitions.hazard import hazard_earthquake
from safe.definitions.layer_purposes import (
layer_purpose_exposure,
layer_purpose_hazard,
layer_purpose_nearby_places,
layer_purpose,
layer_purpose_earthquake_contour,
)
from safe.gis.raster.contour import create_smooth_contour
from safe.processors import (
function_process,
)
from safe.utilities.gis import is_raster_layer
from safe.utilities.i18n import tr
from safe.test.utilities import load_test_vector_layer
from safe.gis.tools import load_layer
and context:
# Path: safe/definitions/layer_purposes.py
which might include code, classes, or functions. Output only the next line. | 'value': layer_purpose_nearby_places, |
Here is a snippet: <|code_start|>def fake_nearby_preprocessor(impact_function):
"""Fake nearby preprocessor.
We can put here the function to generate contours or nearby places.
It must return a layer with a specific layer_purpose.
:return: The output layer.
:rtype: QgsMapLayer
"""
_ = impact_function # NOQA
fake_layer = load_test_vector_layer(
'gisv4',
'impacts',
'building-points-classified-vector.geojson',
clone_to_memory=True)
return fake_layer
pre_processors_nearby_places = {
'key': 'pre_processor_nearby_places',
'name': tr('Nearby Places Pre Processor'),
'description': tr('A fake pre processor.'),
'condition': check_nearby_preprocessor,
'process': {
'type': function_process,
'function': fake_nearby_preprocessor,
},
'output': {
'type': 'layer',
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
from safe.definitions.exposure import exposure_place
from safe.definitions.hazard import hazard_earthquake
from safe.definitions.layer_purposes import (
layer_purpose_exposure,
layer_purpose_hazard,
layer_purpose_nearby_places,
layer_purpose,
layer_purpose_earthquake_contour,
)
from safe.gis.raster.contour import create_smooth_contour
from safe.processors import (
function_process,
)
from safe.utilities.gis import is_raster_layer
from safe.utilities.i18n import tr
from safe.test.utilities import load_test_vector_layer
from safe.gis.tools import load_layer
and context from other files:
# Path: safe/definitions/layer_purposes.py
, which may include functions, classes, or code. Output only the next line. | 'key': layer_purpose, |
Predict the next line for this snippet: <|code_start|>
def earthquake_contour_preprocessor(impact_function):
"""Preprocessor to create contour from an earthquake
:param impact_function: Impact function to run.
:type impact_function: ImpactFunction
:return: The contour layer.
:rtype: QgsMapLayer
"""
contour_path = create_smooth_contour(impact_function.hazard)
if os.path.exists(contour_path):
return load_layer(contour_path, tr('Contour'), 'ogr')[0]
pre_processor_earthquake_contour = {
'key': 'pre_processor_earthquake_contour',
'name': tr('Earthquake Contour Pre Processor'),
'description': tr(
'A pre processor to create contour from a hazard earthquake.'),
'condition': check_earthquake_contour_preprocessor,
'process': {
'type': function_process,
'function': earthquake_contour_preprocessor,
},
'output': {
'type': 'layer',
'key': layer_purpose,
<|code_end|>
with the help of current file imports:
import logging
import os
from safe.definitions.exposure import exposure_place
from safe.definitions.hazard import hazard_earthquake
from safe.definitions.layer_purposes import (
layer_purpose_exposure,
layer_purpose_hazard,
layer_purpose_nearby_places,
layer_purpose,
layer_purpose_earthquake_contour,
)
from safe.gis.raster.contour import create_smooth_contour
from safe.processors import (
function_process,
)
from safe.utilities.gis import is_raster_layer
from safe.utilities.i18n import tr
from safe.test.utilities import load_test_vector_layer
from safe.gis.tools import load_layer
and context from other files:
# Path: safe/definitions/layer_purposes.py
, which may contain function names, class names, or code. Output only the next line. | 'value': layer_purpose_earthquake_contour, |
Given the following code snippet before the placeholder: <|code_start|> description = """
<table border="0" width="100%%">
<tr><td><b>%s</b>: </td><td>%s</td></tr>
<tr><td><b>%s</b>: </td><td>%s</td></tr>
%s
%s
<tr><td><b>%s</b>: </td><td>%s</td></tr>
</table>
""" % (tr('Title'), keywords.get('title'),
tr('Purpose'), keywords.get('layer_purpose'),
subcategory,
unit,
tr('Source'), keywords.get('source'))
elif keywords:
# The layer has keywords, but the version is wrong
layer_version = keyword_version or tr('No Version')
description = tr(
'Your layer\'s keyword\'s version ({layer_version}) does not '
'match with your InaSAFE version ({inasafe_version}). If you wish '
'to use it as an exposure, hazard, or aggregation layer in an '
'analysis, please update the keywords. Click Next if you want to '
'assign keywords now.').format(
layer_version=layer_version, inasafe_version=get_version())
else:
# The layer is keywordless
if is_point_layer(layer):
geom_type = layer_geometry_point['key']
elif is_polygon_layer(layer):
geom_type = layer_geometry_polygon['key']
else:
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os
import safe.gui.tools.wizard.wizard_strings
from qgis.PyQt import QtCore
from qgis.core import QgsCoordinateTransform, QgsProject
from safe.common.version import get_version
from safe.definitions.constants import RECENT, GLOBAL
from safe.definitions.layer_modes import layer_mode_classified
from safe.definitions.layer_purposes import (
layer_geometry_line, layer_geometry_point, layer_geometry_polygon)
from safe.definitions.layer_purposes import (
layer_purpose_exposure, layer_purpose_hazard)
from safe.utilities.default_values import get_inasafe_default_value_qsetting
from safe.utilities.gis import (
is_raster_layer, is_point_layer, is_polygon_layer)
from safe.utilities.i18n import tr
from safe.utilities.resources import resources_path
from safe.utilities.utilities import is_keyword_version_supported
and context including class names, function names, and sometimes code from other files:
# Path: safe/definitions/layer_purposes.py
#
# Path: safe/definitions/layer_purposes.py
. Output only the next line. | geom_type = layer_geometry_line['key'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.