Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|> self.assertEqual(expected, result)
cookie = response.headers['Set-Cookie']
self.assertTrue(cookie)
headers = {'Cookie': cookie}
# Get our characters.
response = self.fetch('/characters', headers=headers)
result = json.loads(response.body)
self.assertTrue(len(result) > 0)
character = result[0]
# Get the zone our character is in:
response = self.fetch('/zone/%s/zone' % character, headers=headers)
result = json.loads(response.body)
expected = {'zone': 'playerinstance-GhibliHills-%s' % (character,)}
self.assertEqual(result, expected)
zone = result['zone']
# Normally, the client would ask the masterzoneserver for the
# url of the zone. This is not necessary for this test
# since we already know where it is.
# Get the zone's objects.
response = self.fetch('/objects', headers=headers)
self.fetch('/logout', headers=headers)
<|code_end|>
with the help of current file imports:
import unittest
import sys
import json
import settings
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from urllib import urlencode
from authserver import PingHandler, AuthHandler, LogoutHandler, CharacterHandler
from charserver import CharacterZoneHandler
from zoneserver import ObjectsHandler, CharStatusHandler, MovementHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and context from other files:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: charserver.py
# class CharacterZoneHandler(BaseHandler):
# '''CharacterZoneHandler gets zone information for a given character.'''
#
# def get(self, character):
# self.write(json.dumps(self.get_zone(character)))
# self.set_header('Content-Type', 'application/json')
#
# def get_zone(self, charname):
# '''Queries the database for information pertaining directly
# to the character.
# It currently only returns the zone the character is in.'''
# return {'zone':'playerinstance-GhibliHills-%s' % (charname,)}
#
# # TODO: Add character online/offline status
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# class MovementHandler(BaseHandler):
# '''A stupid HTTP-based handler for handling character movement.'''
# @tornado.web.authenticated
# def post(self):
# character = self.get_argument('character', '')
# user = self.get_secure_cookie('user')
# self.char_controller = CharacterController()
# # if not self.char_controller.is_owner(user, character):
# # self.set_status(403)
# # self.write("User %s does not own Character %s." % (user, character))
# # return False
#
# xmod = int(self.get_argument('x', 0))
# ymod = int(self.get_argument('y', 0))
# zmod = int(self.get_argument('z', 0))
# logging.info("Locmod is: %d, %d, %d" % (xmod, ymod, zmod))
#
# result = self.char_controller.set_movement(character, xmod, ymod, zmod, user=user)
#
# logging.info("Tried to set movement, result was: %s" % result)
#
# if result is not False:
# retval = result.json_dumps()
# else:
# retval = json.dumps(result, cls=ComplexEncoder)
#
# self.content_type = 'application/json'
# self.write(retval)
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
, which may contain function names, class names, or code. Output only the next line. | if __name__ == '__main__': |
Next line prediction: <|code_start|>
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
set_up_db()
class TestFullIntegration(AsyncHTTPTestCase):
def get_app(self):
handlers = []
handlers.append((r"/ping", PingHandler))
handlers.append((r"/login", AuthHandler))
handlers.append((r"/logout", LogoutHandler))
handlers.append((r"/characters", CharacterHandler))
handlers.append((r"/zone/(.*)/zone", CharacterZoneHandler))
handlers.append((r"/characters", CharacterHandler))
handlers.append((r"/objects", ObjectsHandler))
handlers.append((r"/setstatus", CharStatusHandler))
handlers.append((r"/movement", MovementHandler))
<|code_end|>
. Use current file imports:
(import unittest
import sys
import json
import settings
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from urllib import urlencode
from authserver import PingHandler, AuthHandler, LogoutHandler, CharacterHandler
from charserver import CharacterZoneHandler
from zoneserver import ObjectsHandler, CharStatusHandler, MovementHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User)
and context including class names, function names, or small code snippets from other files:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: charserver.py
# class CharacterZoneHandler(BaseHandler):
# '''CharacterZoneHandler gets zone information for a given character.'''
#
# def get(self, character):
# self.write(json.dumps(self.get_zone(character)))
# self.set_header('Content-Type', 'application/json')
#
# def get_zone(self, charname):
# '''Queries the database for information pertaining directly
# to the character.
# It currently only returns the zone the character is in.'''
# return {'zone':'playerinstance-GhibliHills-%s' % (charname,)}
#
# # TODO: Add character online/offline status
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# class MovementHandler(BaseHandler):
# '''A stupid HTTP-based handler for handling character movement.'''
# @tornado.web.authenticated
# def post(self):
# character = self.get_argument('character', '')
# user = self.get_secure_cookie('user')
# self.char_controller = CharacterController()
# # if not self.char_controller.is_owner(user, character):
# # self.set_status(403)
# # self.write("User %s does not own Character %s." % (user, character))
# # return False
#
# xmod = int(self.get_argument('x', 0))
# ymod = int(self.get_argument('y', 0))
# zmod = int(self.get_argument('z', 0))
# logging.info("Locmod is: %d, %d, %d" % (xmod, ymod, zmod))
#
# result = self.char_controller.set_movement(character, xmod, ymod, zmod, user=user)
#
# logging.info("Tried to set movement, result was: %s" % result)
#
# if result is not False:
# retval = result.json_dumps()
# else:
# retval = json.dumps(result, cls=ComplexEncoder)
#
# self.content_type = 'application/json'
# self.write(retval)
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
. Output only the next line. | return Application(handlers, cookie_secret=settings.COOKIE_SECRET) |
Predict the next line after this snippet: <|code_start|>
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
set_up_db()
class TestFullIntegration(AsyncHTTPTestCase):
def get_app(self):
handlers = []
handlers.append((r"/ping", PingHandler))
handlers.append((r"/login", AuthHandler))
handlers.append((r"/logout", LogoutHandler))
handlers.append((r"/characters", CharacterHandler))
handlers.append((r"/zone/(.*)/zone", CharacterZoneHandler))
handlers.append((r"/characters", CharacterHandler))
handlers.append((r"/objects", ObjectsHandler))
handlers.append((r"/setstatus", CharStatusHandler))
handlers.append((r"/movement", MovementHandler))
<|code_end|>
using the current file's imports:
import unittest
import sys
import json
import settings
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from urllib import urlencode
from authserver import PingHandler, AuthHandler, LogoutHandler, CharacterHandler
from charserver import CharacterZoneHandler
from zoneserver import ObjectsHandler, CharStatusHandler, MovementHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and any relevant context from other files:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: charserver.py
# class CharacterZoneHandler(BaseHandler):
# '''CharacterZoneHandler gets zone information for a given character.'''
#
# def get(self, character):
# self.write(json.dumps(self.get_zone(character)))
# self.set_header('Content-Type', 'application/json')
#
# def get_zone(self, charname):
# '''Queries the database for information pertaining directly
# to the character.
# It currently only returns the zone the character is in.'''
# return {'zone':'playerinstance-GhibliHills-%s' % (charname,)}
#
# # TODO: Add character online/offline status
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# class MovementHandler(BaseHandler):
# '''A stupid HTTP-based handler for handling character movement.'''
# @tornado.web.authenticated
# def post(self):
# character = self.get_argument('character', '')
# user = self.get_secure_cookie('user')
# self.char_controller = CharacterController()
# # if not self.char_controller.is_owner(user, character):
# # self.set_status(403)
# # self.write("User %s does not own Character %s." % (user, character))
# # return False
#
# xmod = int(self.get_argument('x', 0))
# ymod = int(self.get_argument('y', 0))
# zmod = int(self.get_argument('z', 0))
# logging.info("Locmod is: %d, %d, %d" % (xmod, ymod, zmod))
#
# result = self.char_controller.set_movement(character, xmod, ymod, zmod, user=user)
#
# logging.info("Tried to set movement, result was: %s" % result)
#
# if result is not False:
# retval = result.json_dumps()
# else:
# retval = json.dumps(result, cls=ComplexEncoder)
#
# self.content_type = 'application/json'
# self.write(retval)
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
. Output only the next line. | return Application(handlers, cookie_secret=settings.COOKIE_SECRET) |
Given snippet: <|code_start|>
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
set_up_db()
class TestFullIntegration(AsyncHTTPTestCase):
def get_app(self):
handlers = []
handlers.append((r"/ping", PingHandler))
handlers.append((r"/login", AuthHandler))
handlers.append((r"/logout", LogoutHandler))
handlers.append((r"/characters", CharacterHandler))
handlers.append((r"/zone/(.*)/zone", CharacterZoneHandler))
handlers.append((r"/characters", CharacterHandler))
handlers.append((r"/objects", ObjectsHandler))
handlers.append((r"/setstatus", CharStatusHandler))
handlers.append((r"/movement", MovementHandler))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import sys
import json
import settings
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from urllib import urlencode
from authserver import PingHandler, AuthHandler, LogoutHandler, CharacterHandler
from charserver import CharacterZoneHandler
from zoneserver import ObjectsHandler, CharStatusHandler, MovementHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and context:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: charserver.py
# class CharacterZoneHandler(BaseHandler):
# '''CharacterZoneHandler gets zone information for a given character.'''
#
# def get(self, character):
# self.write(json.dumps(self.get_zone(character)))
# self.set_header('Content-Type', 'application/json')
#
# def get_zone(self, charname):
# '''Queries the database for information pertaining directly
# to the character.
# It currently only returns the zone the character is in.'''
# return {'zone':'playerinstance-GhibliHills-%s' % (charname,)}
#
# # TODO: Add character online/offline status
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# class MovementHandler(BaseHandler):
# '''A stupid HTTP-based handler for handling character movement.'''
# @tornado.web.authenticated
# def post(self):
# character = self.get_argument('character', '')
# user = self.get_secure_cookie('user')
# self.char_controller = CharacterController()
# # if not self.char_controller.is_owner(user, character):
# # self.set_status(403)
# # self.write("User %s does not own Character %s." % (user, character))
# # return False
#
# xmod = int(self.get_argument('x', 0))
# ymod = int(self.get_argument('y', 0))
# zmod = int(self.get_argument('z', 0))
# logging.info("Locmod is: %d, %d, %d" % (xmod, ymod, zmod))
#
# result = self.char_controller.set_movement(character, xmod, ymod, zmod, user=user)
#
# logging.info("Tried to set movement, result was: %s" % result)
#
# if result is not False:
# retval = result.json_dumps()
# else:
# retval = json.dumps(result, cls=ComplexEncoder)
#
# self.content_type = 'application/json'
# self.write(retval)
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
which might include code, classes, or functions. Output only the next line. | return Application(handlers, cookie_secret=settings.COOKIE_SECRET) |
Given snippet: <|code_start|>#!/usr/bin/env python2.7
'''Test the full client access sequence.
It is pretty much the anti-pattern of testing.
'''
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
set_up_db()
class TestFullIntegration(AsyncHTTPTestCase):
def get_app(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import sys
import json
import settings
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from urllib import urlencode
from authserver import PingHandler, AuthHandler, LogoutHandler, CharacterHandler
from charserver import CharacterZoneHandler
from zoneserver import ObjectsHandler, CharStatusHandler, MovementHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and context:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: charserver.py
# class CharacterZoneHandler(BaseHandler):
# '''CharacterZoneHandler gets zone information for a given character.'''
#
# def get(self, character):
# self.write(json.dumps(self.get_zone(character)))
# self.set_header('Content-Type', 'application/json')
#
# def get_zone(self, charname):
# '''Queries the database for information pertaining directly
# to the character.
# It currently only returns the zone the character is in.'''
# return {'zone':'playerinstance-GhibliHills-%s' % (charname,)}
#
# # TODO: Add character online/offline status
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# class MovementHandler(BaseHandler):
# '''A stupid HTTP-based handler for handling character movement.'''
# @tornado.web.authenticated
# def post(self):
# character = self.get_argument('character', '')
# user = self.get_secure_cookie('user')
# self.char_controller = CharacterController()
# # if not self.char_controller.is_owner(user, character):
# # self.set_status(403)
# # self.write("User %s does not own Character %s." % (user, character))
# # return False
#
# xmod = int(self.get_argument('x', 0))
# ymod = int(self.get_argument('y', 0))
# zmod = int(self.get_argument('z', 0))
# logging.info("Locmod is: %d, %d, %d" % (xmod, ymod, zmod))
#
# result = self.char_controller.set_movement(character, xmod, ymod, zmod, user=user)
#
# logging.info("Tried to set movement, result was: %s" % result)
#
# if result is not False:
# retval = result.json_dumps()
# else:
# retval = json.dumps(result, cls=ComplexEncoder)
#
# self.content_type = 'application/json'
# self.write(retval)
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
which might include code, classes, or functions. Output only the next line. | handlers = [] |
Using the snippet: <|code_start|> self.objects[o.id]['me_obj'] = o
self.objects[o.id]['body'].position = o.loc.x, o.loc.y
else:
# This object is not in our physics scene yet
self.insert_space_object(o)
self.last_update = datetime.datetime.now()
def step(self):
'''Step the scene simulation forward until we're satisfied.'''
dt = 1.0/60.0
for x in range(1):
self.space.step(dt)
def update_database(self):
'''Send any changes we made to our internal scene to the database,
so that any movement or bumping or jostling is persisted into the zone.'''
for _id, o in self.objects.items():
body = o['body']
me_obj = o['me_obj']
newx, newy = body.position
oldx, oldy = me_obj.loc.x, me_obj.loc.y
if newx != oldx or newy != oldy:
me_obj.loc.x = newx
me_obj.loc.y = newy
me_obj.set_modified()
def start(self):
print "Running PhysicsServer."
super(PhysicsServer, self).start()
<|code_end|>
, determine the next line of code. You have imports:
from uuid import uuid4
from pymunk import Vec2d
from settings import CLIENT_UPDATE_FREQ, DATETIME_FORMAT
from basetickserver import BaseTickServer
import datetime
import pymunk as pm
import sys
and context (class names, function names, or code) available:
# Path: settings.py
# CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
#
# DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f'
#
# Path: basetickserver.py
# class BaseTickServer(object):
# '''This is a class that should be subclassed and tick() defined to do something
# every "tick".'''
#
# def __init__(self):
# self.tick_freq_multiplier = 1
#
# def tick(self):
# '''Do things every tick. Should be overridden.'''
# pass
#
# def start(self):
# self.current_tick = 0
# skip_ticks = CLIENT_UPDATE_FREQ
# max_frameskip = 5
#
# next_tick = 0
# self.running = True
#
# while self.running:
# loops = 0
# self.current_tick += 1
# while (self.current_tick > next_tick) and (loops < max_frameskip):
# # dt = ((current_tick + skip_ticks) - next_tick) / skip_ticks
# self.tick()
# next_tick += skip_ticks
# loops += 1
. Output only the next line. | if __name__ == "__main__": |
Next line prediction: <|code_start|> def update_scene(self):
'''Update the internal scene with any changes to the zone's objects.
This is like get_objects() from the client, only directly grabbing from the server.'''
# Get all the objects since our last update.
for o in Object.objects(last_modified__gte=self.last_update, physical=True):
if o.id in self.objects:
# This object is already in our scene, let's update its position
# with what the database says its position is.
self.objects[o.id]['me_obj'] = o
self.objects[o.id]['body'].position = o.loc.x, o.loc.y
else:
# This object is not in our physics scene yet
self.insert_space_object(o)
self.last_update = datetime.datetime.now()
def step(self):
'''Step the scene simulation forward until we're satisfied.'''
dt = 1.0/60.0
for x in range(1):
self.space.step(dt)
def update_database(self):
'''Send any changes we made to our internal scene to the database,
so that any movement or bumping or jostling is persisted into the zone.'''
for _id, o in self.objects.items():
body = o['body']
me_obj = o['me_obj']
newx, newy = body.position
oldx, oldy = me_obj.loc.x, me_obj.loc.y
if newx != oldx or newy != oldy:
<|code_end|>
. Use current file imports:
(from uuid import uuid4
from pymunk import Vec2d
from settings import CLIENT_UPDATE_FREQ, DATETIME_FORMAT
from basetickserver import BaseTickServer
import datetime
import pymunk as pm
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: settings.py
# CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
#
# DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f'
#
# Path: basetickserver.py
# class BaseTickServer(object):
# '''This is a class that should be subclassed and tick() defined to do something
# every "tick".'''
#
# def __init__(self):
# self.tick_freq_multiplier = 1
#
# def tick(self):
# '''Do things every tick. Should be overridden.'''
# pass
#
# def start(self):
# self.current_tick = 0
# skip_ticks = CLIENT_UPDATE_FREQ
# max_frameskip = 5
#
# next_tick = 0
# self.running = True
#
# while self.running:
# loops = 0
# self.current_tick += 1
# while (self.current_tick > next_tick) and (loops < max_frameskip):
# # dt = ((current_tick + skip_ticks) - next_tick) / skip_ticks
# self.tick()
# next_tick += skip_ticks
# loops += 1
. Output only the next line. | me_obj.loc.x = newx |
Continue the code snippet: <|code_start|># This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
# System imports
# PySide imports
# from PySide.QtCore import *
# from PySide.QtGui import *
# Project imports
DEBUG = __debug__
class QtClient(QWidget):
@Slot()
def open_login(self):
self.login_form = LoginForm()
self.login_form.show()
@Slot()
def login(self):
print "Logged In!"
<|code_end|>
. Use current file imports:
import functools
import datetime
import sys
from PySide.QtCore import Qt, SIGNAL, QSize, QTimer, Slot, Signal
from PySide.QtGui import QDialog, QIcon, QLabel, QLineEdit, QPushButton,\
QVBoxLayout, QApplication, QTreeWidget, QTreeWidgetItem,\
QWidget, QGraphicsScene, QGraphicsView, QGraphicsWidget,\
QGraphicsPixmapItem, QPainter
from client import Client
from settings import CLIENT_UPDATE_FREQ
from helpers import euclidian
from requests.exceptions import ConnectionError
and context (classes, functions, or code) from other files:
# Path: client.py
# class InteractiveClient(Cmd):
# def precmd(self, line):
# def postcmd(self, stop, line):
# def format_prompt(self, username='', character='', zone=''):
# def logged_in(self):
# def do_register(self, args, opts=None):
# def do_login(self, args, opts=None):
# def login(self, username, password, charnum=None):
# def do_create_character(self, args, opts=None):
# def do_update(self, args=None):
# def format_messages(self):
# def do_map(self, args):
# def clean_dict(self, dirty):
# def format_object(self, objdata):
# def get_match(self, objname):
# def do_detail(self, args):
#
# Path: settings.py
# CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
#
# Path: helpers.py
# def euclidian(x1, y1, x2, y2):
# from math import sqrt
# return sqrt(((x1-x2)**2) + ((y1-y2)**2))
. Output only the next line. | self.charselect = CharacterSelect() |
Based on the snippet: <|code_start|># pb = QPushButton("Push!")
# stylesheet = '''
# QPushButton {
# border: 2px solid #8f8f91;
# border-radius: 6px;
# background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
# stop: 0 #f6f7fa, stop: 1 #dadbde);
# min-width: 80px;
# }
#
# QPushButton:pressed {
# background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
# stop: 0 #dadbde, stop: 1 #f6f7fa);
# }
#
# QPushButton:flat {
# border: none; /* no border for a flat push button */
# }
# QPushButton:default {
# border-color: navy; /* make the default button prominent */
# }
# '''
# pb.setStyleSheet(stylesheet)
# self.scene.addWidget(pb)
layout = QVBoxLayout()
for w in (self.view, ):
layout.addWidget(w)
self.setLayout(layout)
<|code_end|>
, predict the immediate next line with the help of imports:
import functools
import datetime
import sys
from PySide.QtCore import Qt, SIGNAL, QSize, QTimer, Slot, Signal
from PySide.QtGui import QDialog, QIcon, QLabel, QLineEdit, QPushButton,\
QVBoxLayout, QApplication, QTreeWidget, QTreeWidgetItem,\
QWidget, QGraphicsScene, QGraphicsView, QGraphicsWidget,\
QGraphicsPixmapItem, QPainter
from client import Client
from settings import CLIENT_UPDATE_FREQ
from helpers import euclidian
from requests.exceptions import ConnectionError
and context (classes, functions, sometimes code) from other files:
# Path: client.py
# class InteractiveClient(Cmd):
# def precmd(self, line):
# def postcmd(self, stop, line):
# def format_prompt(self, username='', character='', zone=''):
# def logged_in(self):
# def do_register(self, args, opts=None):
# def do_login(self, args, opts=None):
# def login(self, username, password, charnum=None):
# def do_create_character(self, args, opts=None):
# def do_update(self, args=None):
# def format_messages(self):
# def do_map(self, args):
# def clean_dict(self, dirty):
# def format_object(self, objdata):
# def get_match(self, objname):
# def do_detail(self, args):
#
# Path: settings.py
# CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
#
# Path: helpers.py
# def euclidian(x1, y1, x2, y2):
# from math import sqrt
# return sqrt(((x1-x2)**2) + ((y1-y2)**2))
. Output only the next line. | self.loading = self.scene.addText("Loading...") |
Based on the snippet: <|code_start|># border: 2px solid #8f8f91;
# border-radius: 6px;
# background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
# stop: 0 #f6f7fa, stop: 1 #dadbde);
# min-width: 80px;
# }
#
# QPushButton:pressed {
# background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
# stop: 0 #dadbde, stop: 1 #f6f7fa);
# }
#
# QPushButton:flat {
# border: none; /* no border for a flat push button */
# }
# QPushButton:default {
# border-color: navy; /* make the default button prominent */
# }
# '''
# pb.setStyleSheet(stylesheet)
# self.scene.addWidget(pb)
layout = QVBoxLayout()
for w in (self.view, ):
layout.addWidget(w)
self.setLayout(layout)
self.loading = self.scene.addText("Loading...")
self.loading.setHtml("<h1>Loading...</h1>")
<|code_end|>
, predict the immediate next line with the help of imports:
import functools
import datetime
import sys
from PySide.QtCore import Qt, SIGNAL, QSize, QTimer, Slot, Signal
from PySide.QtGui import QDialog, QIcon, QLabel, QLineEdit, QPushButton,\
QVBoxLayout, QApplication, QTreeWidget, QTreeWidgetItem,\
QWidget, QGraphicsScene, QGraphicsView, QGraphicsWidget,\
QGraphicsPixmapItem, QPainter
from client import Client
from settings import CLIENT_UPDATE_FREQ
from helpers import euclidian
from requests.exceptions import ConnectionError
and context (classes, functions, sometimes code) from other files:
# Path: client.py
# class InteractiveClient(Cmd):
# def precmd(self, line):
# def postcmd(self, stop, line):
# def format_prompt(self, username='', character='', zone=''):
# def logged_in(self):
# def do_register(self, args, opts=None):
# def do_login(self, args, opts=None):
# def login(self, username, password, charnum=None):
# def do_create_character(self, args, opts=None):
# def do_update(self, args=None):
# def format_messages(self):
# def do_map(self, args):
# def clean_dict(self, dirty):
# def format_object(self, objdata):
# def get_match(self, objname):
# def do_detail(self, args):
#
# Path: settings.py
# CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
#
# Path: helpers.py
# def euclidian(x1, y1, x2, y2):
# from math import sqrt
# return sqrt(((x1-x2)**2) + ((y1-y2)**2))
. Output only the next line. | self.last_update = datetime.datetime.now() |
Predict the next line for this snippet: <|code_start|> # Zone crashed, remove it from the process list.
s.twiddler.removeProcessFromGroup(processgroup, zoneid)
except(xmlrpclib.Fault), exc:
if "STILL_RUNNING" in exc.faultString:
# Process still running just fine, return true.
print "Still running, leaving it alone."
retval = True
else:
print "Restarting stopped/crashed zone."
# Removing the process worked, delete the zone from the database.
Zone.query.filter_by(zoneid=zoneid).delete()
session.commit()
# Start zone again
retval = _add_process(s, processgroup, zoneid, settings, port)
else:
print exc
print exc.faultCode, exc.faultString
raise
finally:
session.commit()
return retval
def start_zone(port=1300, zonename="defaultzone", instancetype="playerinstance", owner="Groxnor", processgroup='zones', autorestart=False):
s = xmlrpclib.ServerProxy('http://localhost:9001')
try:
version = s.twiddler.getAPIVersion()
except(socket.error), exc:
raise UserWarning("Could not connect to supervisor: %s" % exc)
<|code_end|>
with the help of current file imports:
import xmlrpclib
import supervisor
import socket
from supervisor.xmlrpc import SupervisorTransport
from settings import ZONESTARTPORT, ZONEENDPORT
from elixir_models import Zone, session
from settings import PROTOCOL, HOSTNAME
and context from other files:
# Path: settings.py
# ZONESTARTPORT = 1300
#
# ZONEENDPORT = 1400
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
, which may contain function names, class names, or code. Output only the next line. | if float(version) >= 0.3: |
Based on the snippet: <|code_start|> return retval
def start_zone(port=1300, zonename="defaultzone", instancetype="playerinstance", owner="Groxnor", processgroup='zones', autorestart=False):
s = xmlrpclib.ServerProxy('http://localhost:9001')
try:
version = s.twiddler.getAPIVersion()
except(socket.error), exc:
raise UserWarning("Could not connect to supervisor: %s" % exc)
if float(version) >= 0.3:
# Query through all our zones to get a good port number.
taken_ports = [p[0] for p in session.query(Zone.port).all()]
for port in xrange(ZONESTARTPORT, ZONEENDPORT):
if port not in taken_ports:
break
print "Chose port # %d" % port
command = '/usr/bin/python zoneserver.py --port=%d --zonename=%s --instancetype=%s --owner=%s' % (int(port), zonename, instancetype, owner)
zoneid = '-'.join((instancetype, zonename, owner))
settings = {'command': command, 'autostart': str(True), 'autorestart': str(autorestart), 'redirect_stderr': str(True)}
addtogroup = _add_process(s, processgroup, zoneid, settings, port)
# Start up a scriptserver:
settings['command'] = '/usr/bin/python scriptserver.py %s' % zoneid
zonescriptserver = _add_process(s, processgroup, zoneid+"-scriptserver", settings, 1)
if addtogroup:
serverurl = "%s://%s:%d" % (PROTOCOL, HOSTNAME, port)
return serverurl
<|code_end|>
, predict the immediate next line with the help of imports:
import xmlrpclib
import supervisor
import socket
from supervisor.xmlrpc import SupervisorTransport
from settings import ZONESTARTPORT, ZONEENDPORT
from elixir_models import Zone, session
from settings import PROTOCOL, HOSTNAME
and context (classes, functions, sometimes code) from other files:
# Path: settings.py
# ZONESTARTPORT = 1300
#
# ZONEENDPORT = 1400
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
. Output only the next line. | else: |
Based on the snippet: <|code_start|># ##### END AGPL LICENSE BLOCK #####
def _add_process(twiddlerproxy, processgroup, zoneid, settings, port):
'''Adds a zone process to supervisor and does some checks to only start it
if it isn't already running, and restart it if it's not.'''
s = twiddlerproxy
try:
retval = s.twiddler.addProgramToGroup(processgroup, zoneid, settings)
print "Added successfully."
zone = Zone.query.filter_by(zoneid=zoneid).first()
if zone:
# This zone already exists, so update the port number.
zone.port = port
else:
# This zone doesn't exist. Create a new one.
Zone(zoneid=zoneid, port=port)
session.commit()
except(xmlrpclib.Fault), exc:
if "BAD_NAME" in exc.faultString:
try:
# Zone crashed, remove it from the process list.
s.twiddler.removeProcessFromGroup(processgroup, zoneid)
except(xmlrpclib.Fault), exc:
<|code_end|>
, predict the immediate next line with the help of imports:
import xmlrpclib
import supervisor
import socket
from supervisor.xmlrpc import SupervisorTransport
from settings import ZONESTARTPORT, ZONEENDPORT
from elixir_models import Zone, session
from settings import PROTOCOL, HOSTNAME
and context (classes, functions, sometimes code) from other files:
# Path: settings.py
# ZONESTARTPORT = 1300
#
# ZONEENDPORT = 1400
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
. Output only the next line. | if "STILL_RUNNING" in exc.faultString: |
Here is a snippet: <|code_start|># published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
def _add_process(twiddlerproxy, processgroup, zoneid, settings, port):
'''Adds a zone process to supervisor and does some checks to only start it
if it isn't already running, and restart it if it's not.'''
s = twiddlerproxy
try:
retval = s.twiddler.addProgramToGroup(processgroup, zoneid, settings)
print "Added successfully."
zone = Zone.query.filter_by(zoneid=zoneid).first()
if zone:
# This zone already exists, so update the port number.
zone.port = port
<|code_end|>
. Write the next line using the current file imports:
import xmlrpclib
import supervisor
import socket
from supervisor.xmlrpc import SupervisorTransport
from settings import ZONESTARTPORT, ZONEENDPORT
from elixir_models import Zone, session
from settings import PROTOCOL, HOSTNAME
and context from other files:
# Path: settings.py
# ZONESTARTPORT = 1300
#
# ZONEENDPORT = 1400
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
, which may include functions, classes, or code. Output only the next line. | else: |
Predict the next line for this snippet: <|code_start|>
sys.path.append(".")
test_db = SqliteExtDatabase(':memory:', fields={'json':'json'})
class TestCharacterZoneHandler(AsyncHTTPTestCase):
def get_app(self):
return Application([('/(.*)/zone', CharacterZoneHandler)], cookie_secret=settings.COOKIE_SECRET)
def setUp(self):
super(TestCharacterZoneHandler, self).setUp()
app = Application([('/(.*)/zone', CharacterZoneHandler)], cookie_secret=settings.COOKIE_SECRET)
req = Mock()
req.cookies = {}
self.character_zone_handler = CharacterZoneHandler(app, req)
def test_get(self):
with test_database(test_db, (User, Character)):
charname = "testcharname"
result = json.loads(self.fetch('/%s/zone' % charname).body)
expected = {'zone': 'playerinstance-GhibliHills-%s' % charname}
self.assertEqual(result, expected)
def test_get_zone(self):
<|code_end|>
with the help of current file imports:
import unittest
import json
import sys
import settings
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from elixir_models import setup as elixir_setup, User, Character
from playhouse.sqlite_ext import SqliteExtDatabase
from playhouse.test_utils import test_database
from charserver import CharacterZoneHandler
and context from other files:
# Path: elixir_models.py
# def setup(db_uri='simplemmo.sqlite', echo=False):
# print "dburi:", db_uri
# global db
# db.init(db_uri)
# db.connect()
# db.create_tables([User, Character, Zone, Message, Object], True)
#
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
#
# Path: charserver.py
# class CharacterZoneHandler(BaseHandler):
# '''CharacterZoneHandler gets zone information for a given character.'''
#
# def get(self, character):
# self.write(json.dumps(self.get_zone(character)))
# self.set_header('Content-Type', 'application/json')
#
# def get_zone(self, charname):
# '''Queries the database for information pertaining directly
# to the character.
# It currently only returns the zone the character is in.'''
# return {'zone':'playerinstance-GhibliHills-%s' % (charname,)}
#
# # TODO: Add character online/offline status
, which may contain function names, class names, or code. Output only the next line. | with test_database(test_db, (User, Character)): |
Predict the next line for this snippet: <|code_start|> mock_set_secure_cookie = Mock()
with patch.object(settings, 'ADMINISTRATORS', MockAdmin):
with patch.object(self.auth_handler, 'set_secure_cookie', mock_set_secure_cookie):
self.auth_handler.set_admin(user)
mock_set_secure_cookie.assert_called_once_with('admin', 'true')
def test_set_admin_not_administrator(self):
# Mock auth_handler.clear_cookie
user = "user"
MockAdmin = Mock()
MockAdmin.__iter__ = Mock(return_value=iter([]))
mock_clear_cookie = Mock()
with patch.object(settings, 'ADMINISTRATORS', MockAdmin):
with patch.object(self.auth_handler, 'clear_cookie', mock_clear_cookie):
self.auth_handler.set_admin(user)
mock_clear_cookie.assert_called_once_with('admin')
def test_set_current_user(self):
user = "username"
mock_set_secure_cookie = Mock()
with patch.object(self.auth_handler, 'set_secure_cookie', mock_set_secure_cookie):
self.auth_handler.set_current_user(user)
mock_set_secure_cookie.assert_called_once_with("user", user, domain=None)
<|code_end|>
with the help of current file imports:
import unittest
import sys
import authserver
import settings
from tornado.web import Application
from mock import Mock, patch
from authserver import AuthHandler, RegistrationHandler
from sqlalchemy.exc import IntegrityError
and context from other files:
# Path: authserver.py
# class AuthHandler(BaseHandler):
# '''AuthHandler authenticates a user and sets a session in the database.
#
# .. http:post:: /login
#
# Creates a User in the AuthenticationServer's database.
#
# **Example request**:
#
# .. sourcecode:: http
#
# POST /login HTTP/1.1
#
# username=asdf&password=asdf
#
# **Example response**:
#
# .. sourcecode:: http
#
# HTTP/1.1 200 OK
# Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
#
# Login successful.
#
#
# :param username: The name of the user to log in as.
# :param password: The password to use for authenticating the user.
#
# :status 200: Login successful.
# :status 401: Login failed due to bad username and/or password
# '''
# def post(self):
# username = self.get_argument("username", "")
# password = self.get_argument("password", "")
# auth = self.authenticate(username, password)
# if auth:
# self.set_current_user(username)
# self.set_admin(username)
# self.write('Login successful.')
# else:
# raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
#
# def authenticate(self, username, password):
# '''Compares a username/password pair against that in the database.
# If they match, return True.
# Else, return False.'''
# # Do some database stuff here to verify the user.
# user = User.get(username=username)
# if not user:
# return False
# return UserController.check_password(plaintext=password, hashed=user.password)
#
# def set_admin(self, user):
# # Look up username in admins list in database
# # if present, set secure cookie for admin
# if user in settings.ADMINISTRATORS:
# self.set_secure_cookie("admin", 'true')
# else:
# self.clear_cookie("admin")
#
# def set_current_user(self, user):
# if user:
# self.set_secure_cookie("user", user, domain=None)
# else:
# self.clear_cookie("user")
#
# class RegistrationHandler(BaseHandler):
# '''RegistrationHandler creates Users.
#
# .. http:post:: /register
#
# Creates a User in the AuthenticationServer's database.
#
# **Example request**:
#
# .. sourcecode:: http
#
# POST /register HTTP/1.1
#
# username=asdf&password=asdf
#
# **Example response**:
#
# .. sourcecode:: http
#
# HTTP/1.1 200 OK
#
# Registration succeeded.
#
#
# :param username: The name of the user to create.
# :param password: The password to use for authenticating the user.
# :param email: Optional. An email to associate with the user.
#
# :status 200: Registration succeeded.
# :status 400: A required parameter was missing.
# :status 401: The User already exists.
# '''
# def post(self):
# username = self.get_argument("username", "")
# password = self.get_argument("password", "")
# email = self.get_argument("email", "")
#
# if not username:
# return self.HTTPError(400, "A user name is required.")
#
# if not password:
# return self.HTTPError(400, "A password is required.")
#
# user = self.register_user(username, password, email=email)
# logging.info("User was %s" % user)
# if user:
# return self.write('Registration successful.')
# else:
# return self.HTTPError(401, "User already exists.")
#
# def register_user(self, username, password, email=None):
# if User.select().where(User.username==username).exists():
# return False
#
# user = User(username=username,
# password=UserController.hash_password(password),
# email=email)
# user.save()
# return user
, which may contain function names, class names, or code. Output only the next line. | def test_set_current_user_with_none(self): |
Given the code snippet: <|code_start|> req = Mock()
self.auth_handler = AuthHandler(app, req)
patch('authserver.UserController').start()
def test_authenticate(self):
# Mock out the User object
first = Mock(return_value=Mock())
MockUser = Mock()
MockUser.query.filter_by().first = first
# Test
with patch.object(authserver, 'User', MockUser):
result = self.auth_handler.authenticate("username", "password")
self.assertTrue(result)
def test_authenticate_invalid_password(self):
'''There is a good username and password in the database.
But we give a real username, and a bad password.
We should not be allowed to log in.'''
username = "username"
password = "password"
# Mock out the User object
MockUser = Mock()
first = Mock(return_value=None)
MockUser.get = first
# Test
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import sys
import authserver
import settings
from tornado.web import Application
from mock import Mock, patch
from authserver import AuthHandler, RegistrationHandler
from sqlalchemy.exc import IntegrityError
and context (functions, classes, or occasionally code) from other files:
# Path: authserver.py
# class AuthHandler(BaseHandler):
# '''AuthHandler authenticates a user and sets a session in the database.
#
# .. http:post:: /login
#
# Creates a User in the AuthenticationServer's database.
#
# **Example request**:
#
# .. sourcecode:: http
#
# POST /login HTTP/1.1
#
# username=asdf&password=asdf
#
# **Example response**:
#
# .. sourcecode:: http
#
# HTTP/1.1 200 OK
# Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
#
# Login successful.
#
#
# :param username: The name of the user to log in as.
# :param password: The password to use for authenticating the user.
#
# :status 200: Login successful.
# :status 401: Login failed due to bad username and/or password
# '''
# def post(self):
# username = self.get_argument("username", "")
# password = self.get_argument("password", "")
# auth = self.authenticate(username, password)
# if auth:
# self.set_current_user(username)
# self.set_admin(username)
# self.write('Login successful.')
# else:
# raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
#
# def authenticate(self, username, password):
# '''Compares a username/password pair against that in the database.
# If they match, return True.
# Else, return False.'''
# # Do some database stuff here to verify the user.
# user = User.get(username=username)
# if not user:
# return False
# return UserController.check_password(plaintext=password, hashed=user.password)
#
# def set_admin(self, user):
# # Look up username in admins list in database
# # if present, set secure cookie for admin
# if user in settings.ADMINISTRATORS:
# self.set_secure_cookie("admin", 'true')
# else:
# self.clear_cookie("admin")
#
# def set_current_user(self, user):
# if user:
# self.set_secure_cookie("user", user, domain=None)
# else:
# self.clear_cookie("user")
#
# class RegistrationHandler(BaseHandler):
# '''RegistrationHandler creates Users.
#
# .. http:post:: /register
#
# Creates a User in the AuthenticationServer's database.
#
# **Example request**:
#
# .. sourcecode:: http
#
# POST /register HTTP/1.1
#
# username=asdf&password=asdf
#
# **Example response**:
#
# .. sourcecode:: http
#
# HTTP/1.1 200 OK
#
# Registration succeeded.
#
#
# :param username: The name of the user to create.
# :param password: The password to use for authenticating the user.
# :param email: Optional. An email to associate with the user.
#
# :status 200: Registration succeeded.
# :status 400: A required parameter was missing.
# :status 401: The User already exists.
# '''
# def post(self):
# username = self.get_argument("username", "")
# password = self.get_argument("password", "")
# email = self.get_argument("email", "")
#
# if not username:
# return self.HTTPError(400, "A user name is required.")
#
# if not password:
# return self.HTTPError(400, "A password is required.")
#
# user = self.register_user(username, password, email=email)
# logging.info("User was %s" % user)
# if user:
# return self.write('Registration successful.')
# else:
# return self.HTTPError(401, "User already exists.")
#
# def register_user(self, username, password, email=None):
# if User.select().where(User.username==username).exists():
# return False
#
# user = User(username=username,
# password=UserController.hash_password(password),
# email=email)
# user.save()
# return user
. Output only the next line. | with patch.object(authserver, 'User', MockUser): |
Next line prediction: <|code_start|>#!/usr/bin/env python2.7
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
set_up_db()
<|code_end|>
. Use current file imports:
(import unittest
import sys
import settings
from tornado.web import Application, decode_signed_value
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from authserver import PingHandler, AuthHandler, RegistrationHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User)
and context including class names, function names, or small code snippets from other files:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
. Output only the next line. | class TestPingHandler(AsyncHTTPTestCase): |
Based on the snippet: <|code_start|>#!/usr/bin/env python2.7
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import sys
import settings
from tornado.web import Application, decode_signed_value
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from authserver import PingHandler, AuthHandler, RegistrationHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and context (classes, functions, sometimes code) from other files:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
. Output only the next line. | set_up_db() |
Given the code snippet: <|code_start|>#!/usr/bin/env python2.7
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
set_up_db()
class TestPingHandler(AsyncHTTPTestCase):
def get_app(self):
return Application([('/', PingHandler)])
def test_get(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import sys
import settings
from tornado.web import Application, decode_signed_value
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from authserver import PingHandler, AuthHandler, RegistrationHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and context (functions, classes, or occasionally code) from other files:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
. Output only the next line. | response = self.fetch('/').body |
Using the snippet: <|code_start|>
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
set_up_db()
class TestPingHandler(AsyncHTTPTestCase):
def get_app(self):
return Application([('/', PingHandler)])
def test_get(self):
response = self.fetch('/').body
expected = 'pong'
self.assertEqual(expected, response)
# Some helpers for authentication:
def add_user(username, password):
'''Add a user to the database.
If it already exists, delete it first.
Also mark it for cleanup later.'''
<|code_end|>
, determine the next line of code. You have imports:
import unittest
import sys
import settings
from tornado.web import Application, decode_signed_value
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from authserver import PingHandler, AuthHandler, RegistrationHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and context (class names, function names, or code) available:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
. Output only the next line. | delete_user(username, password) |
Here is a snippet: <|code_start|>#!/usr/bin/env python2.7
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
<|code_end|>
. Write the next line using the current file imports:
import unittest
import sys
import settings
from tornado.web import Application, decode_signed_value
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from authserver import PingHandler, AuthHandler, RegistrationHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and context from other files:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
, which may include functions, classes, or code. Output only the next line. | set_up_db() |
Given snippet: <|code_start|>#!/usr/bin/env python2.7
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
set_up_db()
class TestPingHandler(AsyncHTTPTestCase):
def get_app(self):
return Application([('/', PingHandler)])
def test_get(self):
response = self.fetch('/').body
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import sys
import settings
from tornado.web import Application, decode_signed_value
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from authserver import PingHandler, AuthHandler, RegistrationHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and context:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
which might include code, classes, or functions. Output only the next line. | expected = 'pong' |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python2.7
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
# metadata.bind.echo = True
setup_all()
create_all()
# Call it the first time for tests that don't care if they have clean data.
set_up_db()
<|code_end|>
using the current file's imports:
import unittest
import sys
import settings
from tornado.web import Application, decode_signed_value
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from authserver import PingHandler, AuthHandler, RegistrationHandler
from elixir import session
from elixir_models import metadata, setup_all, create_all
from elixir_models import User
and any relevant context from other files:
# Path: authserver.py
# class UserController(object):
# class RegistrationHandler(BaseHandler):
# class AuthHandler(BaseHandler):
# class LogoutHandler(BaseHandler):
# class CharacterHandler(BaseHandler):
# def hash_password(cls, password):
# def check_password(cls, plaintext, hashed):
# def post(self):
# def register_user(self, username, password, email=None):
# def post(self):
# def authenticate(self, username, password):
# def set_admin(self, user):
# def set_current_user(self, user):
# def get(self):
# def get(self):
# def get_characters(self, username):
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
. Output only the next line. | class TestPingHandler(AsyncHTTPTestCase): |
Given snippet: <|code_start|># 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARN)
define("dburi", default='simplemmo.sqlite', help="Where is the database?", type=str)
client = False
try:
if settings.SENTRY:
try:
r = requests.get(settings.SENTRY_SERVER)
sentry_up = 'Sentry' in r.content
except requests.ConnectionError:
sentry_up = False
if sentry_up:
client = Client(settings.SENTRY_DSN)
if settings.SENTRY_LOG:
handler = SentryHandler(client)
setup_logging(handler)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import settings
import logging
import requests
import os
import uuid
from tornado.web import Application, RequestHandler
from tornado.options import options, define
from tornado.ioloop import IOLoop
from elixir_models import setup
from raven import Client
from raven.handlers.logging import SentryHandler
from raven.conf import setup_logging
from subprocess import Popen, PIPE
from zipfile import ZipFile
and context:
# Path: elixir_models.py
# def setup(db_uri='simplemmo.sqlite', echo=False):
# print "dburi:", db_uri
# global db
# db.init(db_uri)
# db.connect()
# db.create_tables([User, Character, Zone, Message, Object], True)
which might include code, classes, or functions. Output only the next line. | except ImportError: |
Here is a snippet: <|code_start|>
sys.path.append(".")
class TestZoneScriptRunner(unittest.TestCase):
def test___init__(self):
zoneid = "zoneid"
with patch('scriptserver.Object'):
with patch.object(ZoneScriptRunner, 'load_scripts') as mock_load_scripts:
zone_script_runner = ZoneScriptRunner(zoneid)
self.assertTrue(zone_script_runner)
self.assertEqual(1, mock_load_scripts.call_count)
<|code_end|>
. Write the next line using the current file imports:
import unittest
import sys
from mock import patch, Mock
from scriptserver import ZoneScriptRunner
and context from other files:
# Path: scriptserver.py
# class ZoneScriptRunner(BaseTickServer):
# '''This is a class that holds all sorts of methods for running scripts for
# a zone. It does not talk to the HTTP handler(s) directly, but instead uses
# the same database. It might take player movement updates directly in the
# future for speed, but this is unlikely.'''
#
# def __init__(self, zoneid):
# super(ZoneScriptRunner, self).__init__()
#
# # While the zone is not loaded, wait.
# logger.info("Waiting for zone to complete loading.")
# while not Object.get_objects(name="Loading Complete."):
# time.sleep(.1)
#
# # Watch the script path for any changes, and reboot the scriptserver if they do.
# self.observer = Observer()
# self.observer.schedule(ScriptEventHandler(), path=settings.SCRIPT_PATH, recursive=True)
# self.observer.start()
#
# self.load_scripts()
# logger.info("Started with data for zone: %s" % zoneid)
#
# def load_scripts(self):
# '''(Re)Load scripts for objects in this zone.'''
# self.scripts = {}
#
# # Query DB for a list of all objects' script names,
# # ordered according to proximity to players
# logger.info(Object.get_objects(scripted=True))
# for o in Object.get_objects(scripted=True):
# logger.info("Scripted Object: {0}".format(o.name))
# # Store list of script names in self
#
# # For each script name in the list:
# for script in o.scripts:
# logger.info("Importing %s" % script)
# if script not in self.scripts:
# self.scripts[script] = []
#
# # Import those by name via __import__
# scriptclass = script.split('.')[-1]
# module = __import__(script, globals(), locals(), [scriptclass], -1)
# # For each entry in the script's dir()
# for key in dir(module):
# C = getattr(module, key)
#
# # No sense in instantiating the default Script instance.
# if C == Script:
# continue
#
# try:
# # Does this object have the attributes that scripts need?
# if not all((C.tick, C.activate, C.create)):
# continue
# except AttributeError:
# continue
#
# # Store object instance in a list.
# self.scripts[script].append(C(mongo_engine_object=o))
# return self.scripts
#
#
# def tick(self):
# '''Iterate through all known scripts and call their tick method.'''
# # Tick all the things
# logger.info(self.scripts)
# for scriptname, scripts in self.scripts.items():
# for script in scripts:
# logger.debug("Ticking {0}".format(script))
# # TODO: Pass some locals or somesuch so that they can query the db
# script.tick()
#
# # Clean up mongodb's messages by deleting all but the most recent 100 non-player messages
# for m in Message.select().where(Message.player_generated==False).order_by('-sent')[settings.MAX_ZONE_OBJECT_MESSAGE_COUNT:]:
# logger.info("Deleting message from %s" % m.sent.time())
# m.delete()
#
# def start(self):
# logger.info("Running ZoneScript Server.")
# super(ZoneScriptRunner, self).start()
, which may include functions, classes, or code. Output only the next line. | def test_load_scripts(self): |
Given snippet: <|code_start|> It's mostly just used for detecting if an object is really a script or not.
'''
def __init__(self, mongo_engine_object=None):
self.me_obj = mongo_engine_object
print "Initted with %s" % self.me_obj
def create(self):
'''Create this Script's ScriptedObject database object.'''
pass
def activate(self, *args, **kwargs):
'''Do something when the scripted object is activated/clicked/etc.
Script.tick() and Script.activate() are not usually called from
the same instance.
Do not rely on saved instance state. Store it in the database.
'''
pass
def roll(self, dicestring):
'''Roll dice specified by dicestring and return the value.
Does not allow more dice than the MAX_DICE_AMOUNT setting
to be rolled at once.'''
rolls, num, sides, mod = parse(dicestring)
num = int(num)
sides = int(sides)
mod = int(mod)
if num > MAX_DICE_AMOUNT:
raise UserWarning("Cannot roll more than %d dice at once." % MAX_DICE_AMOUNT)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import re
import random
from elixir_models import Message
from settings import MAX_DICE_AMOUNT
from elixir_models import Object
from helpers import manhattan
and context:
# Path: elixir_models.py
# class Message(BaseModel):
# '''A text message from a player, for cross-zone messaging.'''
#
# date_sent = DateTimeField(default=datetime.datetime.now)
# sender = CharField()
# recipient = CharField(null=True, default=u'')
# channel = IntegerField(null=True, default=0)
# body = CharField(null=True, default=u'')
#
# Path: settings.py
# MAX_DICE_AMOUNT = 100
#
# Path: elixir_models.py
# class Object(BaseModel):
# '''In-world objects.'''
#
# name = CharField()
# resource = CharField(default="none")
# owner = CharField(null=True)
#
# loc_x = FloatField(default=0)
# loc_y = FloatField(default=0)
# loc_z = FloatField(default=0)
#
# rot_x = FloatField(default=0)
# rot_y = FloatField(default=0)
# rot_z = FloatField(default=0)
#
# scale_x = FloatField(default=1)
# scale_y = FloatField(default=1)
# scale_z = FloatField(default=1)
#
# speed = FloatField(default=1)
# vel_x = FloatField(default=0)
# vel_y = FloatField(default=0)
# vel_z = FloatField(default=0)
#
# states = JSONField(default=[])
# physical = BooleanField(default=True)
# last_modified = DateTimeField(default=datetime.datetime.now)
#
# scripts = JSONField(default=[])
#
# @property
# def loc(self):
# return (self.loc_x, self.loc_y, self.loc_z)
#
# @loc.setter
# def loc(self, val):
# self.loc_x, self.loc_y, self.loc_z = val
#
# def set_modified(self, date_time=None):
# if date_time is None:
# date_time = datetime.datetime.now()
# self.last_modified = date_time
# self.save()
#
# @staticmethod
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# # TODO: Needs integration test.
# obj = Object.select()
#
# if since is not None:
# obj = obj.where(Object.last_modified>=since)
#
# if physical is not None:
# obj = obj.where(Object.physical==physical)
#
# if player is not None:
# obj = obj.where(Object.states.contains('player')).where(Object.name==player)
#
# if scripted is not None:
# obj = obj.where(Object.scripts!=None) # TODO: Have this only return objects with scripts.
#
# if name is not None:
# obj = obj.where(Object.name==name)
#
# obj = obj.order_by(Object.last_modified.desc())
#
# if limit is not None:
# obj = obj.limit(limit)
#
# if limit == 1:
# return obj
#
# return [o for o in obj]
which might include code, classes, or functions. Output only the next line. | rolls = [] |
Predict the next line after this snippet: <|code_start|>
def parse(s):
result = re.search(r'^((?P<rolls>\d+)#)?(?P<dice>\d*)d(?P<sides>\d+)(?P<mod>[+-]\d+)?$', s)
return (result.group('rolls') or 0,
result.group('dice') or 1,
result.group('sides') or 2,
result.group('mod') or 0)
<|code_end|>
using the current file's imports:
import datetime
import re
import random
from elixir_models import Message
from settings import MAX_DICE_AMOUNT
from elixir_models import Object
from helpers import manhattan
and any relevant context from other files:
# Path: elixir_models.py
# class Message(BaseModel):
# '''A text message from a player, for cross-zone messaging.'''
#
# date_sent = DateTimeField(default=datetime.datetime.now)
# sender = CharField()
# recipient = CharField(null=True, default=u'')
# channel = IntegerField(null=True, default=0)
# body = CharField(null=True, default=u'')
#
# Path: settings.py
# MAX_DICE_AMOUNT = 100
#
# Path: elixir_models.py
# class Object(BaseModel):
# '''In-world objects.'''
#
# name = CharField()
# resource = CharField(default="none")
# owner = CharField(null=True)
#
# loc_x = FloatField(default=0)
# loc_y = FloatField(default=0)
# loc_z = FloatField(default=0)
#
# rot_x = FloatField(default=0)
# rot_y = FloatField(default=0)
# rot_z = FloatField(default=0)
#
# scale_x = FloatField(default=1)
# scale_y = FloatField(default=1)
# scale_z = FloatField(default=1)
#
# speed = FloatField(default=1)
# vel_x = FloatField(default=0)
# vel_y = FloatField(default=0)
# vel_z = FloatField(default=0)
#
# states = JSONField(default=[])
# physical = BooleanField(default=True)
# last_modified = DateTimeField(default=datetime.datetime.now)
#
# scripts = JSONField(default=[])
#
# @property
# def loc(self):
# return (self.loc_x, self.loc_y, self.loc_z)
#
# @loc.setter
# def loc(self, val):
# self.loc_x, self.loc_y, self.loc_z = val
#
# def set_modified(self, date_time=None):
# if date_time is None:
# date_time = datetime.datetime.now()
# self.last_modified = date_time
# self.save()
#
# @staticmethod
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# # TODO: Needs integration test.
# obj = Object.select()
#
# if since is not None:
# obj = obj.where(Object.last_modified>=since)
#
# if physical is not None:
# obj = obj.where(Object.physical==physical)
#
# if player is not None:
# obj = obj.where(Object.states.contains('player')).where(Object.name==player)
#
# if scripted is not None:
# obj = obj.where(Object.scripts!=None) # TODO: Have this only return objects with scripts.
#
# if name is not None:
# obj = obj.where(Object.name==name)
#
# obj = obj.order_by(Object.last_modified.desc())
#
# if limit is not None:
# obj = obj.limit(limit)
#
# if limit == 1:
# return obj
#
# return [o for o in obj]
. Output only the next line. | class Script(object): |
Here is a snippet: <|code_start|> return (result.group('rolls') or 0,
result.group('dice') or 1,
result.group('sides') or 2,
result.group('mod') or 0)
class Script(object):
'''This is a placeholder class used for doing object script things.
It's mostly just used for detecting if an object is really a script or not.
'''
def __init__(self, mongo_engine_object=None):
self.me_obj = mongo_engine_object
print "Initted with %s" % self.me_obj
def create(self):
'''Create this Script's ScriptedObject database object.'''
pass
def activate(self, *args, **kwargs):
'''Do something when the scripted object is activated/clicked/etc.
Script.tick() and Script.activate() are not usually called from
the same instance.
Do not rely on saved instance state. Store it in the database.
'''
pass
def roll(self, dicestring):
'''Roll dice specified by dicestring and return the value.
Does not allow more dice than the MAX_DICE_AMOUNT setting
to be rolled at once.'''
<|code_end|>
. Write the next line using the current file imports:
import datetime
import re
import random
from elixir_models import Message
from settings import MAX_DICE_AMOUNT
from elixir_models import Object
from helpers import manhattan
and context from other files:
# Path: elixir_models.py
# class Message(BaseModel):
# '''A text message from a player, for cross-zone messaging.'''
#
# date_sent = DateTimeField(default=datetime.datetime.now)
# sender = CharField()
# recipient = CharField(null=True, default=u'')
# channel = IntegerField(null=True, default=0)
# body = CharField(null=True, default=u'')
#
# Path: settings.py
# MAX_DICE_AMOUNT = 100
#
# Path: elixir_models.py
# class Object(BaseModel):
# '''In-world objects.'''
#
# name = CharField()
# resource = CharField(default="none")
# owner = CharField(null=True)
#
# loc_x = FloatField(default=0)
# loc_y = FloatField(default=0)
# loc_z = FloatField(default=0)
#
# rot_x = FloatField(default=0)
# rot_y = FloatField(default=0)
# rot_z = FloatField(default=0)
#
# scale_x = FloatField(default=1)
# scale_y = FloatField(default=1)
# scale_z = FloatField(default=1)
#
# speed = FloatField(default=1)
# vel_x = FloatField(default=0)
# vel_y = FloatField(default=0)
# vel_z = FloatField(default=0)
#
# states = JSONField(default=[])
# physical = BooleanField(default=True)
# last_modified = DateTimeField(default=datetime.datetime.now)
#
# scripts = JSONField(default=[])
#
# @property
# def loc(self):
# return (self.loc_x, self.loc_y, self.loc_z)
#
# @loc.setter
# def loc(self, val):
# self.loc_x, self.loc_y, self.loc_z = val
#
# def set_modified(self, date_time=None):
# if date_time is None:
# date_time = datetime.datetime.now()
# self.last_modified = date_time
# self.save()
#
# @staticmethod
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# # TODO: Needs integration test.
# obj = Object.select()
#
# if since is not None:
# obj = obj.where(Object.last_modified>=since)
#
# if physical is not None:
# obj = obj.where(Object.physical==physical)
#
# if player is not None:
# obj = obj.where(Object.states.contains('player')).where(Object.name==player)
#
# if scripted is not None:
# obj = obj.where(Object.scripts!=None) # TODO: Have this only return objects with scripts.
#
# if name is not None:
# obj = obj.where(Object.name==name)
#
# obj = obj.order_by(Object.last_modified.desc())
#
# if limit is not None:
# obj = obj.limit(limit)
#
# if limit == 1:
# return obj
#
# return [o for o in obj]
, which may include functions, classes, or code. Output only the next line. | rolls, num, sides, mod = parse(dicestring) |
Here is a snippet: <|code_start|>#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
'''CharServer
A server for retrieving information about characters.
For example, getting which zone a character is currently in.
'''
# TODO: Write a function to pull in the docstrings from defined classes here and
# append them to the module docstring
class CharacterZoneHandler(BaseHandler):
'''CharacterZoneHandler gets zone information for a given character.'''
def get(self, character):
self.write(json.dumps(self.get_zone(character)))
self.set_header('Content-Type', 'application/json')
def get_zone(self, charname):
'''Queries the database for information pertaining directly
to the character.
It currently only returns the zone the character is in.'''
<|code_end|>
. Write the next line using the current file imports:
import logging
import tornado
import json
from elixir_models import User, Character
from settings import CHARSERVERPORT
from baseserver import BaseServer, SimpleHandler, BaseHandler
and context from other files:
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
#
# Path: settings.py
# CHARSERVERPORT = 1235
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
, which may include functions, classes, or code. Output only the next line. | return {'zone':'playerinstance-GhibliHills-%s' % (charname,)} |
Based on the snippet: <|code_start|>#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
'''CharServer
A server for retrieving information about characters.
For example, getting which zone a character is currently in.
'''
# TODO: Write a function to pull in the docstrings from defined classes here and
# append them to the module docstring
class CharacterZoneHandler(BaseHandler):
'''CharacterZoneHandler gets zone information for a given character.'''
def get(self, character):
self.write(json.dumps(self.get_zone(character)))
self.set_header('Content-Type', 'application/json')
def get_zone(self, charname):
'''Queries the database for information pertaining directly
to the character.
It currently only returns the zone the character is in.'''
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import tornado
import json
from elixir_models import User, Character
from settings import CHARSERVERPORT
from baseserver import BaseServer, SimpleHandler, BaseHandler
and context (classes, functions, sometimes code) from other files:
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
#
# Path: settings.py
# CHARSERVERPORT = 1235
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
. Output only the next line. | return {'zone':'playerinstance-GhibliHills-%s' % (charname,)} |
Using the snippet: <|code_start|>#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
'''CharServer
A server for retrieving information about characters.
For example, getting which zone a character is currently in.
'''
# TODO: Write a function to pull in the docstrings from defined classes here and
# append them to the module docstring
class CharacterZoneHandler(BaseHandler):
'''CharacterZoneHandler gets zone information for a given character.'''
def get(self, character):
self.write(json.dumps(self.get_zone(character)))
self.set_header('Content-Type', 'application/json')
def get_zone(self, charname):
'''Queries the database for information pertaining directly
to the character.
It currently only returns the zone the character is in.'''
<|code_end|>
, determine the next line of code. You have imports:
import logging
import tornado
import json
from elixir_models import User, Character
from settings import CHARSERVERPORT
from baseserver import BaseServer, SimpleHandler, BaseHandler
and context (class names, function names, or code) available:
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
#
# Path: settings.py
# CHARSERVERPORT = 1235
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
. Output only the next line. | return {'zone':'playerinstance-GhibliHills-%s' % (charname,)} |
Predict the next line for this snippet: <|code_start|>#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
'''CharServer
A server for retrieving information about characters.
For example, getting which zone a character is currently in.
'''
# TODO: Write a function to pull in the docstrings from defined classes here and
# append them to the module docstring
class CharacterZoneHandler(BaseHandler):
'''CharacterZoneHandler gets zone information for a given character.'''
def get(self, character):
self.write(json.dumps(self.get_zone(character)))
self.set_header('Content-Type', 'application/json')
def get_zone(self, charname):
'''Queries the database for information pertaining directly
to the character.
It currently only returns the zone the character is in.'''
<|code_end|>
with the help of current file imports:
import logging
import tornado
import json
from elixir_models import User, Character
from settings import CHARSERVERPORT
from baseserver import BaseServer, SimpleHandler, BaseHandler
and context from other files:
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
#
# Path: settings.py
# CHARSERVERPORT = 1235
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
, which may contain function names, class names, or code. Output only the next line. | return {'zone':'playerinstance-GhibliHills-%s' % (charname,)} |
Continue the code snippet: <|code_start|>#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
'''CharServer
A server for retrieving information about characters.
For example, getting which zone a character is currently in.
'''
# TODO: Write a function to pull in the docstrings from defined classes here and
# append them to the module docstring
class CharacterZoneHandler(BaseHandler):
'''CharacterZoneHandler gets zone information for a given character.'''
def get(self, character):
self.write(json.dumps(self.get_zone(character)))
self.set_header('Content-Type', 'application/json')
def get_zone(self, charname):
'''Queries the database for information pertaining directly
to the character.
It currently only returns the zone the character is in.'''
<|code_end|>
. Use current file imports:
import logging
import tornado
import json
from elixir_models import User, Character
from settings import CHARSERVERPORT
from baseserver import BaseServer, SimpleHandler, BaseHandler
and context (classes, functions, or code) from other files:
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
#
# Path: settings.py
# CHARSERVERPORT = 1235
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
. Output only the next line. | return {'zone':'playerinstance-GhibliHills-%s' % (charname,)} |
Based on the snippet: <|code_start|>#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
'''CharServer
A server for retrieving information about characters.
For example, getting which zone a character is currently in.
'''
# TODO: Write a function to pull in the docstrings from defined classes here and
# append them to the module docstring
class CharacterZoneHandler(BaseHandler):
'''CharacterZoneHandler gets zone information for a given character.'''
def get(self, character):
self.write(json.dumps(self.get_zone(character)))
self.set_header('Content-Type', 'application/json')
def get_zone(self, charname):
'''Queries the database for information pertaining directly
to the character.
It currently only returns the zone the character is in.'''
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import tornado
import json
from elixir_models import User, Character
from settings import CHARSERVERPORT
from baseserver import BaseServer, SimpleHandler, BaseHandler
and context (classes, functions, sometimes code) from other files:
# Path: elixir_models.py
# class User(BaseModel):
# '''User contains details useful for authenticating a user for when they
# initially log in.'''
#
# username = CharField(unique=True)
# password = CharField()
# email = CharField(null=True)
# # Also has 'characters'
#
# def __repr__(self):
# uname = self.username
# s = "s"*(len(self.characters)-1)
# chars = ', '.join([c.name for c in self.characters])
# return '<User "%s" owning character%s: %s.>' % (uname, s, chars)
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
#
# Path: settings.py
# CHARSERVERPORT = 1235
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
. Output only the next line. | return {'zone':'playerinstance-GhibliHills-%s' % (charname,)} |
Predict the next line after this snippet: <|code_start|>#
# Copyright (C) 2011, 2012 Charles Nelson
#
# This program 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
from __future__ import division
'''BaseTickServer
A server that should be overridden to provide a server with its own internal loop.
'''
class BaseTickServer(object):
'''This is a class that should be subclassed and tick() defined to do something
every "tick".'''
<|code_end|>
using the current file's imports:
import time
from settings import CLIENT_UPDATE_FREQ, CLIENT_NETWORK_FPS
and any relevant context from other files:
# Path: settings.py
# CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
#
# CLIENT_NETWORK_FPS = 10
. Output only the next line. | def __init__(self): |
Predict the next line after this snippet: <|code_start|>
class Chicken(Script):
def __init__(self, *args, **kwargs):
# Overriding so people remember to do this on their scripts.
super(Chicken, self).__init__(*args, **kwargs)
self.idle_chat = ('BAWK', 'BUCAW', 'BUCK BUCK BUCK', 'BROOOOCK', 'CLUCK')
self.collide_chat = ("bump.", "bamp!", "BUMP", "THUD!!")
@classmethod
def create(cls, number=0):
obj = ScriptedObject()
obj.name = "Chicken #%d" % number
obj.resource = 'chicken'
obj.loc = (randloc(), randloc(), randloc())
<|code_end|>
using the current file's imports:
from games.objects.basescript import Script
and any relevant context from other files:
# Path: games/objects/basescript.py
# class Script(object):
# '''This is a placeholder class used for doing object script things.
# It's mostly just used for detecting if an object is really a script or not.
# '''
# def __init__(self, mongo_engine_object=None):
# self.me_obj = mongo_engine_object
# print "Initted with %s" % self.me_obj
#
# def create(self):
# '''Create this Script's ScriptedObject database object.'''
# pass
#
# def activate(self, *args, **kwargs):
# '''Do something when the scripted object is activated/clicked/etc.
# Script.tick() and Script.activate() are not usually called from
# the same instance.
# Do not rely on saved instance state. Store it in the database.
# '''
# pass
#
# def roll(self, dicestring):
# '''Roll dice specified by dicestring and return the value.
# Does not allow more dice than the MAX_DICE_AMOUNT setting
# to be rolled at once.'''
#
# rolls, num, sides, mod = parse(dicestring)
# num = int(num)
# sides = int(sides)
# mod = int(mod)
# if num > MAX_DICE_AMOUNT:
# raise UserWarning("Cannot roll more than %d dice at once." % MAX_DICE_AMOUNT)
#
# rolls = []
# for i in xrange(num):
# #print "Rolling dice #%d of %d: %f%% done." % (i, num, (float(i)/float(num))*100)
# rolls.append(random.randrange(1, int(sides)+1)+int(mod))
# return sum(rolls)
#
# def say(self, message):
# '''Write the given text to the zone message database.'''
# Message(sender=self.me_obj.name, message=message, loc_x=self.me_obj.loc_x, loc_y=self.me_obj.loc_y, loc_z=self.me_obj.loc_z, player_generated=False).save()
# print "[%s] %s: %s" % (datetime.datetime.now(), self.me_obj.name, message)
#
# def rand_say(self, sayings):
# '''Pick a random saying from sayings and say it.'''
# self.say(random.choice(sayings))
#
# def tick(self):
# pass
#
# def move(self, xmod, ymod, zmod):
# self.me_obj.loc_x += xmod
# self.me_obj.loc_y += ymod
# self.me_obj.loc_z += zmod
# self.me_obj.set_modified()
#
# from helpers import manhattan
# ourx, oury = self.me_obj.loc_x, self.me_obj.loc_y
# for o in Object.get_objects(physical=True):
# # Is the distance between that object and the character less than 3?
# if manhattan(o.loc_x, o.loc_y, ourx, oury) < 1:
# # We collided against something, so return now and don't
# # save the location changes into the database.
# return False
# else:
# # We didn't collide with any objects.
# self.me_obj.save()
# return True
#
# def wander(self):
# return self.move(random.randint(-1, 1), random.randint(-1, 1), random.randint(-1, 1))
. Output only the next line. | obj.rot = (randrot(), randrot(), randrot()) |
Given the following code snippet before the placeholder: <|code_start|>
# Try to ping the authserver
# If connecting fails, wait longer each time
retry(ping_authserver)
# Since the server is up, authenticate.
if login(USERNAME, PASSWORD) and COOKIES:
print "authenticated"
chars = get_characters()
print "Got %r as characters." % chars
global CURRENTCHAR
CURRENTCHAR = chars[0]
# CURRENTCHAR = ''.join([random.choice(list("qwertyuiopasdfghjklzxcvbnm")) for c in range(10)]).title()
zone = get_zone()
print "Got %r as zone." % zone
zoneserver = get_zoneserver(zone)
print "Got %s as zone url." % zoneserver
global CURRENTZONE
CURRENTZONE = zoneserver
objects = get_all_objects()
print pprint.pprint(objects)
print "Got %d objects from the server." % len(objects)
LASTOBJUPDATE = datetime.datetime.now()
<|code_end|>
, predict the next line using imports from the current file:
import exceptions
import json
import pdb
import datetime
import requests
import websocket
import random
import pprint
import time
from time import sleep
from settings import *
from settings import DEFAULT_USERNAME, DEFAULT_PASSWORD
from settings import AUTHSERVER, CHARSERVER, ZONESERVER
from random import randint
and context including class names, function names, and sometimes code from other files:
# Path: settings.py
# DEFAULT_USERNAME = "Username"
#
# DEFAULT_PASSWORD = "Password"
#
# Path: settings.py
# AUTHSERVER = _server_str % (PROTOCOL, HOSTNAME, AUTHSERVERPORT)
#
# CHARSERVER = _server_str % (PROTOCOL, HOSTNAME, CHARSERVERPORT)
#
# ZONESERVER = _server_str % (PROTOCOL, HOSTNAME, MASTERZONESERVERPORT)
. Output only the next line. | if set_status(): |
Next line prediction: <|code_start|># When was our last object update fetched.
LASTOBJUPDATE = None
class ConnectionError(exceptions.Exception):
def __init__(self, param):
self.param = param
return
def __str__(self):
return repr(self.param)
def retry(func, *args, **kwargs):
sleeptime = 2
server_exists = False
while not server_exists:
try:
server_exists = func(*args, **kwargs)
if server_exists:
break # If we connect succesfully, break out of the while
except Exception, exc:
# Exceptions mean we failed to connect, so retry.
if DEBUG:
print "Connecting failed:", exc
print "Reconnecting in %.01f seconds..." % sleeptime
sleep(sleeptime)
sleeptime = sleeptime**1.5
if sleeptime > CLIENT_TIMEOUT:
raise requests.exceptions.Timeout("Gave up after %d seconds." % int(CLIENT_TIMEOUT))
return True
<|code_end|>
. Use current file imports:
(import exceptions
import json
import pdb
import datetime
import requests
import websocket
import random
import pprint
import time
from time import sleep
from settings import *
from settings import DEFAULT_USERNAME, DEFAULT_PASSWORD
from settings import AUTHSERVER, CHARSERVER, ZONESERVER
from random import randint)
and context including class names, function names, or small code snippets from other files:
# Path: settings.py
# DEFAULT_USERNAME = "Username"
#
# DEFAULT_PASSWORD = "Password"
#
# Path: settings.py
# AUTHSERVER = _server_str % (PROTOCOL, HOSTNAME, AUTHSERVERPORT)
#
# CHARSERVER = _server_str % (PROTOCOL, HOSTNAME, CHARSERVERPORT)
#
# ZONESERVER = _server_str % (PROTOCOL, HOSTNAME, MASTERZONESERVERPORT)
. Output only the next line. | class InvalidResponse(Exception): |
Given the following code snippet before the placeholder: <|code_start|> zone = CURRENTZONE
if character is None:
character = CURRENTCHAR
data = {'character': character, 'status': status}
r = requests.post(''.join((zone, '/setstatus')), cookies=COOKIES, data=data)
content = json_or_exception(r)
return content
# Send an initial movement message to the zoneserver's movement handler to open the connection
def send_movement_ws(zone, character, xmod=0, ymod=0):
global MOVEMENTWEBSOCKET
if MOVEMENTWEBSOCKET is None:
connstr = zone.replace("http://", "ws://")
connstr = ''.join((connstr, "/movement"))
websocket.enableTrace(True)
print connstr
print websocket.create_connection(connstr)
MOVEMENTWEBSOCKET = create_connection(connstr)
else:
print "Using old websocket connection."
MOVEMENTWEBSOCKET.send(json.dumps({'command': 'mov', 'char':character, 'x':xmod, 'y':ymod}))
return json.loads(ws.recv())
def send_movement(zone=None, character=None, xmod=0, ymod=0, zmod=0):
if xmod is 0 and ymod is 0 and zmod is 0:
# No-op.
return
<|code_end|>
, predict the next line using imports from the current file:
import exceptions
import json
import pdb
import datetime
import requests
import websocket
import random
import pprint
import time
from time import sleep
from settings import *
from settings import DEFAULT_USERNAME, DEFAULT_PASSWORD
from settings import AUTHSERVER, CHARSERVER, ZONESERVER
from random import randint
and context including class names, function names, and sometimes code from other files:
# Path: settings.py
# DEFAULT_USERNAME = "Username"
#
# DEFAULT_PASSWORD = "Password"
#
# Path: settings.py
# AUTHSERVER = _server_str % (PROTOCOL, HOSTNAME, AUTHSERVERPORT)
#
# CHARSERVER = _server_str % (PROTOCOL, HOSTNAME, CHARSERVERPORT)
#
# ZONESERVER = _server_str % (PROTOCOL, HOSTNAME, MASTERZONESERVERPORT)
. Output only the next line. | if zone is None: |
Next line prediction: <|code_start|> content = json_or_exception(r)
return content
# We could also query any details about the character like inventory
# or money or current stats at this point
# We pick a character we want to play and query the charserver for its current zone
# charserver returns the zone id, which uniquely identifies it persistently.
def get_zone(charname=None):
if charname is None:
charname = CURRENTCHAR
r = requests.get(''.join((CHARSERVER, '/', charname, '/zone')), )
content = json_or_exception(r)
return content['zone']
# We then send a request to the master zone server for the url to the given zone
# If it's online already, send us the URL
# If it's not online, spin one up and send it when ready.
def get_zoneserver(zone):
r = requests.get(''.join((ZONESERVER, '/', zone)), cookies=COOKIES)
print r.status_code, r.content
content = json_or_exception(r)
return content
# Request all objects in the zone. (Terrain, props, players are all objects)
# Bulk of loading screen goes here while we download object info.
def get_all_objects(zone=None):
if zone is None:
zone = CURRENTZONE
<|code_end|>
. Use current file imports:
(import exceptions
import json
import pdb
import datetime
import requests
import websocket
import random
import pprint
import time
from time import sleep
from settings import *
from settings import DEFAULT_USERNAME, DEFAULT_PASSWORD
from settings import AUTHSERVER, CHARSERVER, ZONESERVER
from random import randint)
and context including class names, function names, or small code snippets from other files:
# Path: settings.py
# DEFAULT_USERNAME = "Username"
#
# DEFAULT_PASSWORD = "Password"
#
# Path: settings.py
# AUTHSERVER = _server_str % (PROTOCOL, HOSTNAME, AUTHSERVERPORT)
#
# CHARSERVER = _server_str % (PROTOCOL, HOSTNAME, CHARSERVERPORT)
#
# ZONESERVER = _server_str % (PROTOCOL, HOSTNAME, MASTERZONESERVERPORT)
. Output only the next line. | print zone |
Predict the next line after this snippet: <|code_start|># A global for storing the current zone URL we're in.
CURRENTZONE = ""
# A global for storing the current character.
CURRENTCHAR = ""
# A global websocket connection for movement updates
MOVEMENTWEBSOCKET = None
# When was our last object update fetched.
LASTOBJUPDATE = None
class ConnectionError(exceptions.Exception):
def __init__(self, param):
self.param = param
return
def __str__(self):
return repr(self.param)
def retry(func, *args, **kwargs):
sleeptime = 2
server_exists = False
while not server_exists:
try:
server_exists = func(*args, **kwargs)
if server_exists:
break # If we connect succesfully, break out of the while
except Exception, exc:
# Exceptions mean we failed to connect, so retry.
if DEBUG:
<|code_end|>
using the current file's imports:
import exceptions
import json
import pdb
import datetime
import requests
import websocket
import random
import pprint
import time
from time import sleep
from settings import *
from settings import DEFAULT_USERNAME, DEFAULT_PASSWORD
from settings import AUTHSERVER, CHARSERVER, ZONESERVER
from random import randint
and any relevant context from other files:
# Path: settings.py
# DEFAULT_USERNAME = "Username"
#
# DEFAULT_PASSWORD = "Password"
#
# Path: settings.py
# AUTHSERVER = _server_str % (PROTOCOL, HOSTNAME, AUTHSERVERPORT)
#
# CHARSERVER = _server_str % (PROTOCOL, HOSTNAME, CHARSERVERPORT)
#
# ZONESERVER = _server_str % (PROTOCOL, HOSTNAME, MASTERZONESERVERPORT)
. Output only the next line. | print "Connecting failed:", exc |
Continue the code snippet: <|code_start|>
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
setup_all()
create_all()
def set_user_cookie(app, request, username):
r = RequestHandler(app, request)
r.set_secure_cookie('user', username)
authcookie = r._new_cookies[0]
cookiestring = authcookie.items()[0][1]
request.cookies.update({'user': cookiestring})
return request
class TestObjectsHandler(AsyncHTTPTestCase):
def get_app(self):
return Application([('/login', AuthHandler), ('/objects', ObjectsHandler),], cookie_secret=settings.COOKIE_SECRET)
def setUp(self):
super(TestObjectsHandler, self).setUp()
set_up_db()
self.zonename = "defaultzone"
self.zoneid = "playerinstance-%s-username" % self.zonename
def tearDown(self):
<|code_end|>
. Use current file imports:
import unittest
import json
import sys
import settings
import mongoengine as me
import mongoengine as me
import zoneserver
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from elixir_models import metadata, setup_all, create_all
from zoneserver import ObjectsHandler, CharStatusHandler
from authserver import AuthHandler
from tornado.web import RequestHandler
from importlib import import_module
from test_authserver import add_user
from importlib import import_module
from test_authserver import add_user
from mock import patch
and context (classes, functions, or code) from other files:
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# Path: authserver.py
# class AuthHandler(BaseHandler):
# '''AuthHandler authenticates a user and sets a session in the database.
#
# .. http:post:: /login
#
# Creates a User in the AuthenticationServer's database.
#
# **Example request**:
#
# .. sourcecode:: http
#
# POST /login HTTP/1.1
#
# username=asdf&password=asdf
#
# **Example response**:
#
# .. sourcecode:: http
#
# HTTP/1.1 200 OK
# Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
#
# Login successful.
#
#
# :param username: The name of the user to log in as.
# :param password: The password to use for authenticating the user.
#
# :status 200: Login successful.
# :status 401: Login failed due to bad username and/or password
# '''
# def post(self):
# username = self.get_argument("username", "")
# password = self.get_argument("password", "")
# auth = self.authenticate(username, password)
# if auth:
# self.set_current_user(username)
# self.set_admin(username)
# self.write('Login successful.')
# else:
# raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
#
# def authenticate(self, username, password):
# '''Compares a username/password pair against that in the database.
# If they match, return True.
# Else, return False.'''
# # Do some database stuff here to verify the user.
# user = User.get(username=username)
# if not user:
# return False
# return UserController.check_password(plaintext=password, hashed=user.password)
#
# def set_admin(self, user):
# # Look up username in admins list in database
# # if present, set secure cookie for admin
# if user in settings.ADMINISTRATORS:
# self.set_secure_cookie("admin", 'true')
# else:
# self.clear_cookie("admin")
#
# def set_current_user(self, user):
# if user:
# self.set_secure_cookie("user", user, domain=None)
# else:
# self.clear_cookie("user")
. Output only the next line. | super(TestObjectsHandler, self).tearDown() |
Next line prediction: <|code_start|># along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
setup_all()
create_all()
def set_user_cookie(app, request, username):
r = RequestHandler(app, request)
r.set_secure_cookie('user', username)
authcookie = r._new_cookies[0]
cookiestring = authcookie.items()[0][1]
request.cookies.update({'user': cookiestring})
return request
class TestObjectsHandler(AsyncHTTPTestCase):
def get_app(self):
return Application([('/login', AuthHandler), ('/objects', ObjectsHandler),], cookie_secret=settings.COOKIE_SECRET)
<|code_end|>
. Use current file imports:
(import unittest
import json
import sys
import settings
import mongoengine as me
import mongoengine as me
import zoneserver
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from elixir_models import metadata, setup_all, create_all
from zoneserver import ObjectsHandler, CharStatusHandler
from authserver import AuthHandler
from tornado.web import RequestHandler
from importlib import import_module
from test_authserver import add_user
from importlib import import_module
from test_authserver import add_user
from mock import patch)
and context including class names, function names, or small code snippets from other files:
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# Path: authserver.py
# class AuthHandler(BaseHandler):
# '''AuthHandler authenticates a user and sets a session in the database.
#
# .. http:post:: /login
#
# Creates a User in the AuthenticationServer's database.
#
# **Example request**:
#
# .. sourcecode:: http
#
# POST /login HTTP/1.1
#
# username=asdf&password=asdf
#
# **Example response**:
#
# .. sourcecode:: http
#
# HTTP/1.1 200 OK
# Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
#
# Login successful.
#
#
# :param username: The name of the user to log in as.
# :param password: The password to use for authenticating the user.
#
# :status 200: Login successful.
# :status 401: Login failed due to bad username and/or password
# '''
# def post(self):
# username = self.get_argument("username", "")
# password = self.get_argument("password", "")
# auth = self.authenticate(username, password)
# if auth:
# self.set_current_user(username)
# self.set_admin(username)
# self.write('Login successful.')
# else:
# raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
#
# def authenticate(self, username, password):
# '''Compares a username/password pair against that in the database.
# If they match, return True.
# Else, return False.'''
# # Do some database stuff here to verify the user.
# user = User.get(username=username)
# if not user:
# return False
# return UserController.check_password(plaintext=password, hashed=user.password)
#
# def set_admin(self, user):
# # Look up username in admins list in database
# # if present, set secure cookie for admin
# if user in settings.ADMINISTRATORS:
# self.set_secure_cookie("admin", 'true')
# else:
# self.clear_cookie("admin")
#
# def set_current_user(self, user):
# if user:
# self.set_secure_cookie("user", user, domain=None)
# else:
# self.clear_cookie("user")
. Output only the next line. | def setUp(self): |
Predict the next line after this snippet: <|code_start|> with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
setup_all()
create_all()
def set_user_cookie(app, request, username):
r = RequestHandler(app, request)
r.set_secure_cookie('user', username)
authcookie = r._new_cookies[0]
cookiestring = authcookie.items()[0][1]
request.cookies.update({'user': cookiestring})
return request
class TestObjectsHandler(AsyncHTTPTestCase):
def get_app(self):
return Application([('/login', AuthHandler), ('/objects', ObjectsHandler),], cookie_secret=settings.COOKIE_SECRET)
def setUp(self):
super(TestObjectsHandler, self).setUp()
set_up_db()
self.zonename = "defaultzone"
self.zoneid = "playerinstance-%s-username" % self.zonename
def tearDown(self):
super(TestObjectsHandler, self).tearDown()
def setup_mongo(self):
try:
<|code_end|>
using the current file's imports:
import unittest
import json
import sys
import settings
import mongoengine as me
import mongoengine as me
import zoneserver
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from elixir_models import metadata, setup_all, create_all
from zoneserver import ObjectsHandler, CharStatusHandler
from authserver import AuthHandler
from tornado.web import RequestHandler
from importlib import import_module
from test_authserver import add_user
from importlib import import_module
from test_authserver import add_user
from mock import patch
and any relevant context from other files:
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# Path: authserver.py
# class AuthHandler(BaseHandler):
# '''AuthHandler authenticates a user and sets a session in the database.
#
# .. http:post:: /login
#
# Creates a User in the AuthenticationServer's database.
#
# **Example request**:
#
# .. sourcecode:: http
#
# POST /login HTTP/1.1
#
# username=asdf&password=asdf
#
# **Example response**:
#
# .. sourcecode:: http
#
# HTTP/1.1 200 OK
# Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
#
# Login successful.
#
#
# :param username: The name of the user to log in as.
# :param password: The password to use for authenticating the user.
#
# :status 200: Login successful.
# :status 401: Login failed due to bad username and/or password
# '''
# def post(self):
# username = self.get_argument("username", "")
# password = self.get_argument("password", "")
# auth = self.authenticate(username, password)
# if auth:
# self.set_current_user(username)
# self.set_admin(username)
# self.write('Login successful.')
# else:
# raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
#
# def authenticate(self, username, password):
# '''Compares a username/password pair against that in the database.
# If they match, return True.
# Else, return False.'''
# # Do some database stuff here to verify the user.
# user = User.get(username=username)
# if not user:
# return False
# return UserController.check_password(plaintext=password, hashed=user.password)
#
# def set_admin(self, user):
# # Look up username in admins list in database
# # if present, set secure cookie for admin
# if user in settings.ADMINISTRATORS:
# self.set_secure_cookie("admin", 'true')
# else:
# self.clear_cookie("admin")
#
# def set_current_user(self, user):
# if user:
# self.set_secure_cookie("user", user, domain=None)
# else:
# self.clear_cookie("user")
. Output only the next line. | me.connect(self.zoneid) |
Here is a snippet: <|code_start|> authcookie = r._new_cookies[0]
cookiestring = authcookie.items()[0][1]
request.cookies.update({'user': cookiestring})
return request
class TestObjectsHandler(AsyncHTTPTestCase):
def get_app(self):
return Application([('/login', AuthHandler), ('/objects', ObjectsHandler),], cookie_secret=settings.COOKIE_SECRET)
def setUp(self):
super(TestObjectsHandler, self).setUp()
set_up_db()
self.zonename = "defaultzone"
self.zoneid = "playerinstance-%s-username" % self.zonename
def tearDown(self):
super(TestObjectsHandler, self).tearDown()
def setup_mongo(self):
try:
me.connect(self.zoneid)
except me.ConnectionError:
self.skipTest("MongoDB server not running.")
# Initialize the zone's setup things.
zonemodule = import_module('games.zones.'+self.zonename)
zonemodule.Zone()
<|code_end|>
. Write the next line using the current file imports:
import unittest
import json
import sys
import settings
import mongoengine as me
import mongoengine as me
import zoneserver
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from elixir_models import metadata, setup_all, create_all
from zoneserver import ObjectsHandler, CharStatusHandler
from authserver import AuthHandler
from tornado.web import RequestHandler
from importlib import import_module
from test_authserver import add_user
from importlib import import_module
from test_authserver import add_user
from mock import patch
and context from other files:
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# Path: authserver.py
# class AuthHandler(BaseHandler):
# '''AuthHandler authenticates a user and sets a session in the database.
#
# .. http:post:: /login
#
# Creates a User in the AuthenticationServer's database.
#
# **Example request**:
#
# .. sourcecode:: http
#
# POST /login HTTP/1.1
#
# username=asdf&password=asdf
#
# **Example response**:
#
# .. sourcecode:: http
#
# HTTP/1.1 200 OK
# Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
#
# Login successful.
#
#
# :param username: The name of the user to log in as.
# :param password: The password to use for authenticating the user.
#
# :status 200: Login successful.
# :status 401: Login failed due to bad username and/or password
# '''
# def post(self):
# username = self.get_argument("username", "")
# password = self.get_argument("password", "")
# auth = self.authenticate(username, password)
# if auth:
# self.set_current_user(username)
# self.set_admin(username)
# self.write('Login successful.')
# else:
# raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
#
# def authenticate(self, username, password):
# '''Compares a username/password pair against that in the database.
# If they match, return True.
# Else, return False.'''
# # Do some database stuff here to verify the user.
# user = User.get(username=username)
# if not user:
# return False
# return UserController.check_password(plaintext=password, hashed=user.password)
#
# def set_admin(self, user):
# # Look up username in admins list in database
# # if present, set secure cookie for admin
# if user in settings.ADMINISTRATORS:
# self.set_secure_cookie("admin", 'true')
# else:
# self.clear_cookie("admin")
#
# def set_current_user(self, user):
# if user:
# self.set_secure_cookie("user", user, domain=None)
# else:
# self.clear_cookie("user")
, which may include functions, classes, or code. Output only the next line. | def sign_in(self): |
Next line prediction: <|code_start|># GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
sys.path.append(".")
def set_up_db():
'''Connects to an in-memory SQLite database,
with the purpose of emptying it and recreating it.'''
metadata.bind = "sqlite:///:memory:"
setup_all()
create_all()
def set_user_cookie(app, request, username):
r = RequestHandler(app, request)
r.set_secure_cookie('user', username)
authcookie = r._new_cookies[0]
cookiestring = authcookie.items()[0][1]
request.cookies.update({'user': cookiestring})
return request
class TestObjectsHandler(AsyncHTTPTestCase):
<|code_end|>
. Use current file imports:
(import unittest
import json
import sys
import settings
import mongoengine as me
import mongoengine as me
import zoneserver
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from elixir_models import metadata, setup_all, create_all
from zoneserver import ObjectsHandler, CharStatusHandler
from authserver import AuthHandler
from tornado.web import RequestHandler
from importlib import import_module
from test_authserver import add_user
from importlib import import_module
from test_authserver import add_user
from mock import patch)
and context including class names, function names, or small code snippets from other files:
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
#
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
# '''ObjectsHandler returns a list of objects and their data.'''
# target_object = Object
#
# class CharStatusHandler(BaseHandler):
# '''Manages if a character is active in the zone or not.'''
#
# @tornado.web.authenticated
# def post(self):
# user = self.get_secure_cookie('user')
# character = self.get_argument('character', '')
# status = self.get_argument('status', '')
# self.char_controller = CharacterController()
#
# # If the character is not owned by this user, disallow it.
# # if not self.char_controller.is_owner(user, character):
# # retval = False
#
# retval = False
# # Only allow setting the status to online or offline.
# if status in ("online", "offline"):
# if self.char_controller.set_char_status(character, status, user=user):
# retval = True
#
# self.write(json.dumps(retval))
#
# Path: authserver.py
# class AuthHandler(BaseHandler):
# '''AuthHandler authenticates a user and sets a session in the database.
#
# .. http:post:: /login
#
# Creates a User in the AuthenticationServer's database.
#
# **Example request**:
#
# .. sourcecode:: http
#
# POST /login HTTP/1.1
#
# username=asdf&password=asdf
#
# **Example response**:
#
# .. sourcecode:: http
#
# HTTP/1.1 200 OK
# Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
#
# Login successful.
#
#
# :param username: The name of the user to log in as.
# :param password: The password to use for authenticating the user.
#
# :status 200: Login successful.
# :status 401: Login failed due to bad username and/or password
# '''
# def post(self):
# username = self.get_argument("username", "")
# password = self.get_argument("password", "")
# auth = self.authenticate(username, password)
# if auth:
# self.set_current_user(username)
# self.set_admin(username)
# self.write('Login successful.')
# else:
# raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
#
# def authenticate(self, username, password):
# '''Compares a username/password pair against that in the database.
# If they match, return True.
# Else, return False.'''
# # Do some database stuff here to verify the user.
# user = User.get(username=username)
# if not user:
# return False
# return UserController.check_password(plaintext=password, hashed=user.password)
#
# def set_admin(self, user):
# # Look up username in admins list in database
# # if present, set secure cookie for admin
# if user in settings.ADMINISTRATORS:
# self.set_secure_cookie("admin", 'true')
# else:
# self.clear_cookie("admin")
#
# def set_current_user(self, user):
# if user:
# self.set_secure_cookie("user", user, domain=None)
# else:
# self.clear_cookie("user")
. Output only the next line. | def get_app(self): |
Predict the next line after this snippet: <|code_start|> Returns the zone URL for the new zone server.'''
# Make sure the instance type is allowed
# Make sure the name exists
# Make sure owner is real
zoneid = '-'.join((instance_type, name, owner))
# If it's in the database, it's probably still up:
try:
zone = Zone.get(zoneid=zoneid)
except Zone.DoesNotExist:
zone = None
serverurl = None
if zone:
port = zone.port
serverurl = zone.url
try:
status = requests.get(serverurl).status_code
if status == 200:
logging.info("Server was already up and in the db: %s" % serverurl)
except (requests.ConnectionError, requests.URLRequired):
serverurl = None
# Server is not already up
if not serverurl:
# Try to start a zone server
if START_ZONE_WITH == SUPERVISORD:
logging.info("Starting process with supervisord.")
try:
<|code_end|>
using the current file's imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and any relevant context from other files:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
. Output only the next line. | serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner) |
Here is a snippet: <|code_start|> self.write(self.get_url(zoneid))
except UserWarning, exc:
if "timed out." in exc:
raise tornado.web.HTTPError(504, exc)
def get_url(self, zoneid):
'''Gets the zone URL from the database based on its id.
ZoneServer ports start at 1300.'''
logging.info("Launching zone %s" % zoneid)
instance_type, name, owner = zoneid.split("-")
return self.launch_zone(instance_type, name, owner)
def launch_zone(self, instance_type, name, owner):
'''Starts a zone given the type of instance, name and character that owns it.
Returns the zone URL for the new zone server.'''
# Make sure the instance type is allowed
# Make sure the name exists
# Make sure owner is real
zoneid = '-'.join((instance_type, name, owner))
# If it's in the database, it's probably still up:
try:
zone = Zone.get(zoneid=zoneid)
except Zone.DoesNotExist:
zone = None
serverurl = None
if zone:
port = zone.port
<|code_end|>
. Write the next line using the current file imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context from other files:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
, which may include functions, classes, or code. Output only the next line. | serverurl = zone.url |
Predict the next line for this snippet: <|code_start|># along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
'''MasterZoneServer
A server providing URLs to ZoneServers.
'''
NEXTCLEANUP = time.time()+(5*60)
JOBS = []
logging.getLogger('connectionpool').setLevel(logging.ERROR)
class ZoneHandler(BaseHandler):
'''ZoneHandler gets the URL for a given zone ID, or spins up a new
instance of the zone for that player.'''
@tornado.web.authenticated
def get(self, zoneid):
self.cleanup()
# Check that the authed user owns that zoneid in the database.
try:
self.write(self.get_url(zoneid))
except UserWarning, exc:
if "timed out." in exc:
<|code_end|>
with the help of current file imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context from other files:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
, which may contain function names, class names, or code. Output only the next line. | raise tornado.web.HTTPError(504, exc) |
Based on the snippet: <|code_start|> if START_ZONE_WITH == DOCKER:
logs = z.logs()
logging.info(logs)
print(logs)
for line in z.logs().split("\n"):
if line.strip() == "":
continue
logging.info("ZONE: {}".format(line))
time.sleep(.1)
if time.time() > starttime+ZONESTARTUPTIME:
logging.info("ZoneServer never came up after %d seconds." % ZONESTARTUPTIME)
raise tornado.web.HTTPError(504, "Launching zone %s timed out." % serverurl)
logging.info("Starting zone %s (%s) took %f seconds and %d requests." % (zoneid, serverurl, time.time()-starttime, numrequests))
print "Starting zone %s (%s) took %f seconds and %d requests." % (zoneid, serverurl, time.time()-starttime, numrequests)
# If successful, write our URL to the database and return it
# Store useful information in the database.
logging.info(serverurl)
try:
zone = Zone.get(zoneid=zoneid)
except Zone.DoesNotExist:
zone = Zone()
zone.zoneid=zoneid
zone.port=serverurl.split(":")[-1]
zone.character=Character.get(name=owner)
zone.url=serverurl
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context (classes, functions, sometimes code) from other files:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
. Output only the next line. | zone.save() |
Given snippet: <|code_start|>
# Server is not already up
if not serverurl:
# Try to start a zone server
if START_ZONE_WITH == SUPERVISORD:
logging.info("Starting process with supervisord.")
try:
serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
except UserWarning, exc:
if "Zone already exists in process list." in exc:
print exc
logging.info("Zone is already up.")
pass
else:
raise
elif START_ZONE_WITH == SUBPROCESS:
logging.info("Starting process with subprocess.")
s = start_scriptserver(zonename=name, instancetype=instance_type, owner=owner)
z, serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
JOBS.extend([z, s])
elif START_ZONE_WITH == DOCKER:
logging.info("Starting process with docker.")
z, serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
s = start_scriptserver(zonename=name, instancetype=instance_type, owner=owner)
# Wait for server to come up
# Just query it on "/" every hundred ms or so.
starttime = time.time()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
which might include code, classes, or functions. Output only the next line. | status = 0 |
Given snippet: <|code_start|> try:
serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
except UserWarning, exc:
if "Zone already exists in process list." in exc:
print exc
logging.info("Zone is already up.")
pass
else:
raise
elif START_ZONE_WITH == SUBPROCESS:
logging.info("Starting process with subprocess.")
s = start_scriptserver(zonename=name, instancetype=instance_type, owner=owner)
z, serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
JOBS.extend([z, s])
elif START_ZONE_WITH == DOCKER:
logging.info("Starting process with docker.")
z, serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
s = start_scriptserver(zonename=name, instancetype=instance_type, owner=owner)
# Wait for server to come up
# Just query it on "/" every hundred ms or so.
starttime = time.time()
status = 0
numrequests = 0
logging.info("Waiting for server on %s" % serverurl)
while status != 200:
try:
status = requests.get(serverurl).status_code
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
which might include code, classes, or functions. Output only the next line. | numrequests += 1 |
Given snippet: <|code_start|> print exc
logging.info("Zone is already up.")
pass
else:
raise
elif START_ZONE_WITH == SUBPROCESS:
logging.info("Starting process with subprocess.")
s = start_scriptserver(zonename=name, instancetype=instance_type, owner=owner)
z, serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
JOBS.extend([z, s])
elif START_ZONE_WITH == DOCKER:
logging.info("Starting process with docker.")
z, serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
s = start_scriptserver(zonename=name, instancetype=instance_type, owner=owner)
# Wait for server to come up
# Just query it on "/" every hundred ms or so.
starttime = time.time()
status = 0
numrequests = 0
logging.info("Waiting for server on %s" % serverurl)
while status != 200:
try:
status = requests.get(serverurl).status_code
numrequests += 1
except(requests.ConnectionError):
# Not up yet...
if START_ZONE_WITH == DOCKER:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
which might include code, classes, or functions. Output only the next line. | logs = z.logs() |
Continue the code snippet: <|code_start|> serverurl = zone.url
try:
status = requests.get(serverurl).status_code
if status == 200:
logging.info("Server was already up and in the db: %s" % serverurl)
except (requests.ConnectionError, requests.URLRequired):
serverurl = None
# Server is not already up
if not serverurl:
# Try to start a zone server
if START_ZONE_WITH == SUPERVISORD:
logging.info("Starting process with supervisord.")
try:
serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
except UserWarning, exc:
if "Zone already exists in process list." in exc:
print exc
logging.info("Zone is already up.")
pass
else:
raise
elif START_ZONE_WITH == SUBPROCESS:
logging.info("Starting process with subprocess.")
s = start_scriptserver(zonename=name, instancetype=instance_type, owner=owner)
z, serverurl = start_zone(zonename=name, instancetype=instance_type, owner=owner)
JOBS.extend([z, s])
elif START_ZONE_WITH == DOCKER:
<|code_end|>
. Use current file imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context (classes, functions, or code) from other files:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
. Output only the next line. | logging.info("Starting process with docker.") |
Given the code snippet: <|code_start|># GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####
'''MasterZoneServer
A server providing URLs to ZoneServers.
'''
NEXTCLEANUP = time.time()+(5*60)
JOBS = []
logging.getLogger('connectionpool').setLevel(logging.ERROR)
class ZoneHandler(BaseHandler):
'''ZoneHandler gets the URL for a given zone ID, or spins up a new
instance of the zone for that player.'''
@tornado.web.authenticated
def get(self, zoneid):
self.cleanup()
# Check that the authed user owns that zoneid in the database.
try:
<|code_end|>
, generate the next line using the imports in this file:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context (functions, classes, or occasionally code) from other files:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
. Output only the next line. | self.write(self.get_url(zoneid)) |
Based on the snippet: <|code_start|> self.write(self.get_url(zoneid))
except UserWarning, exc:
if "timed out." in exc:
raise tornado.web.HTTPError(504, exc)
def get_url(self, zoneid):
'''Gets the zone URL from the database based on its id.
ZoneServer ports start at 1300.'''
logging.info("Launching zone %s" % zoneid)
instance_type, name, owner = zoneid.split("-")
return self.launch_zone(instance_type, name, owner)
def launch_zone(self, instance_type, name, owner):
'''Starts a zone given the type of instance, name and character that owns it.
Returns the zone URL for the new zone server.'''
# Make sure the instance type is allowed
# Make sure the name exists
# Make sure owner is real
zoneid = '-'.join((instance_type, name, owner))
# If it's in the database, it's probably still up:
try:
zone = Zone.get(zoneid=zoneid)
except Zone.DoesNotExist:
zone = None
serverurl = None
if zone:
port = zone.port
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context (classes, functions, sometimes code) from other files:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
. Output only the next line. | serverurl = zone.url |
Using the snippet: <|code_start|> # Check that the authed user owns that zoneid in the database.
try:
self.write(self.get_url(zoneid))
except UserWarning, exc:
if "timed out." in exc:
raise tornado.web.HTTPError(504, exc)
def get_url(self, zoneid):
'''Gets the zone URL from the database based on its id.
ZoneServer ports start at 1300.'''
logging.info("Launching zone %s" % zoneid)
instance_type, name, owner = zoneid.split("-")
return self.launch_zone(instance_type, name, owner)
def launch_zone(self, instance_type, name, owner):
'''Starts a zone given the type of instance, name and character that owns it.
Returns the zone URL for the new zone server.'''
# Make sure the instance type is allowed
# Make sure the name exists
# Make sure owner is real
zoneid = '-'.join((instance_type, name, owner))
# If it's in the database, it's probably still up:
try:
zone = Zone.get(zoneid=zoneid)
except Zone.DoesNotExist:
zone = None
serverurl = None
<|code_end|>
, determine the next line of code. You have imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context (class names, function names, or code) available:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
. Output only the next line. | if zone: |
Here is a snippet: <|code_start|> print "Starting zone %s (%s) took %f seconds and %d requests." % (zoneid, serverurl, time.time()-starttime, numrequests)
# If successful, write our URL to the database and return it
# Store useful information in the database.
logging.info(serverurl)
try:
zone = Zone.get(zoneid=zoneid)
except Zone.DoesNotExist:
zone = Zone()
zone.zoneid=zoneid
zone.port=serverurl.split(":")[-1]
zone.character=Character.get(name=owner)
zone.url=serverurl
zone.save()
logging.info("Zone server came up at %s." % serverurl)
return serverurl
def cleanup(self):
# Every 5 minutes...
global NEXTCLEANUP
if NEXTCLEANUP < time.time():
NEXTCLEANUP = time.time()+(5*60)
# If pid not in database
# Kill the process by pid
if __name__ == "__main__":
handlers = []
handlers.append((r"/", lambda x, y: SimpleHandler(__doc__, x, y)))
<|code_end|>
. Write the next line using the current file imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context from other files:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
, which may include functions, classes, or code. Output only the next line. | handlers.append((r"/(.*)", ZoneHandler)) |
Continue the code snippet: <|code_start|> return serverurl
def cleanup(self):
# Every 5 minutes...
global NEXTCLEANUP
if NEXTCLEANUP < time.time():
NEXTCLEANUP = time.time()+(5*60)
# If pid not in database
# Kill the process by pid
if __name__ == "__main__":
handlers = []
handlers.append((r"/", lambda x, y: SimpleHandler(__doc__, x, y)))
handlers.append((r"/(.*)", ZoneHandler))
server = BaseServer(handlers)
# On startup, iterate through entries in zones table. See if they are up, if not, delete them.
for port in [z.port for z in Zone.select()]:
serverurl = "%s://%s:%d" % (PROTOCOL, HOSTNAME, port)
try:
requests.get(serverurl)
except(requests.ConnectionError):
# Server is down, remove it from the zones table.
Zone.get(port=port).delete_instance()
server.listen(MASTERZONESERVERPORT)
print "Starting up Master Zoneserver..."
try:
<|code_end|>
. Use current file imports:
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
from start_supervisord_process import start_zone
from start_subprocess import start_zone, start_scriptserver
from start_zone_docker import start_zone, start_scriptserver
and context (classes, functions, or code) from other files:
# Path: settings.py
# MASTERZONESERVERPORT = 1236
#
# PROTOCOL = "http"
#
# HOSTNAME = "localhost"
#
# ZONESTARTUPTIME = 20
#
# START_ZONE_WITH = SUBPROCESS
#
# SUPERVISORD = 'supervisord' # Constant
#
# SUBPROCESS = 'subprocess' # Constant
#
# DOCKER = 'docker' # Constant
#
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class Zone(BaseModel):
# '''Zone stores connection information about the zoneservers.'''
#
# zoneid = CharField(unique=True)
# port = IntegerField(unique=False)
# url = CharField(unique=True, null=True)
#
# character = ForeignKeyField(Character, related_name='zones')
#
# class Character(BaseModel):
# '''Character contains the details for characters that users may control.'''
#
# name = CharField(unique=True)
#
# speed = FloatField(default=1)
#
# user = ForeignKeyField(User, related_name='characters')
# # Also has 'zones'
#
#
# def __repr__(self):
# return '<Character "%s" owned by "%s">' % (self.name, self.user.username)
. Output only the next line. | server.start() |
Predict the next line after this snippet: <|code_start|>
class ChatBot(Script):
idle_chat = ["Try clicking on me.", "Maybe Right Click>Activate?"]
activation = ['Nice! You activated me.']
@classmethod
def create(cls):
obj = Object()
obj.name = "Linnea"
obj.resource = 'girl'
<|code_end|>
using the current file's imports:
from elixir_models import Object
from games.objects.basescript import Script
and any relevant context from other files:
# Path: elixir_models.py
# class Object(BaseModel):
# '''In-world objects.'''
#
# name = CharField()
# resource = CharField(default="none")
# owner = CharField(null=True)
#
# loc_x = FloatField(default=0)
# loc_y = FloatField(default=0)
# loc_z = FloatField(default=0)
#
# rot_x = FloatField(default=0)
# rot_y = FloatField(default=0)
# rot_z = FloatField(default=0)
#
# scale_x = FloatField(default=1)
# scale_y = FloatField(default=1)
# scale_z = FloatField(default=1)
#
# speed = FloatField(default=1)
# vel_x = FloatField(default=0)
# vel_y = FloatField(default=0)
# vel_z = FloatField(default=0)
#
# states = JSONField(default=[])
# physical = BooleanField(default=True)
# last_modified = DateTimeField(default=datetime.datetime.now)
#
# scripts = JSONField(default=[])
#
# @property
# def loc(self):
# return (self.loc_x, self.loc_y, self.loc_z)
#
# @loc.setter
# def loc(self, val):
# self.loc_x, self.loc_y, self.loc_z = val
#
# def set_modified(self, date_time=None):
# if date_time is None:
# date_time = datetime.datetime.now()
# self.last_modified = date_time
# self.save()
#
# @staticmethod
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# # TODO: Needs integration test.
# obj = Object.select()
#
# if since is not None:
# obj = obj.where(Object.last_modified>=since)
#
# if physical is not None:
# obj = obj.where(Object.physical==physical)
#
# if player is not None:
# obj = obj.where(Object.states.contains('player')).where(Object.name==player)
#
# if scripted is not None:
# obj = obj.where(Object.scripts!=None) # TODO: Have this only return objects with scripts.
#
# if name is not None:
# obj = obj.where(Object.name==name)
#
# obj = obj.order_by(Object.last_modified.desc())
#
# if limit is not None:
# obj = obj.limit(limit)
#
# if limit == 1:
# return obj
#
# return [o for o in obj]
#
# Path: games/objects/basescript.py
# class Script(object):
# '''This is a placeholder class used for doing object script things.
# It's mostly just used for detecting if an object is really a script or not.
# '''
# def __init__(self, mongo_engine_object=None):
# self.me_obj = mongo_engine_object
# print "Initted with %s" % self.me_obj
#
# def create(self):
# '''Create this Script's ScriptedObject database object.'''
# pass
#
# def activate(self, *args, **kwargs):
# '''Do something when the scripted object is activated/clicked/etc.
# Script.tick() and Script.activate() are not usually called from
# the same instance.
# Do not rely on saved instance state. Store it in the database.
# '''
# pass
#
# def roll(self, dicestring):
# '''Roll dice specified by dicestring and return the value.
# Does not allow more dice than the MAX_DICE_AMOUNT setting
# to be rolled at once.'''
#
# rolls, num, sides, mod = parse(dicestring)
# num = int(num)
# sides = int(sides)
# mod = int(mod)
# if num > MAX_DICE_AMOUNT:
# raise UserWarning("Cannot roll more than %d dice at once." % MAX_DICE_AMOUNT)
#
# rolls = []
# for i in xrange(num):
# #print "Rolling dice #%d of %d: %f%% done." % (i, num, (float(i)/float(num))*100)
# rolls.append(random.randrange(1, int(sides)+1)+int(mod))
# return sum(rolls)
#
# def say(self, message):
# '''Write the given text to the zone message database.'''
# Message(sender=self.me_obj.name, message=message, loc_x=self.me_obj.loc_x, loc_y=self.me_obj.loc_y, loc_z=self.me_obj.loc_z, player_generated=False).save()
# print "[%s] %s: %s" % (datetime.datetime.now(), self.me_obj.name, message)
#
# def rand_say(self, sayings):
# '''Pick a random saying from sayings and say it.'''
# self.say(random.choice(sayings))
#
# def tick(self):
# pass
#
# def move(self, xmod, ymod, zmod):
# self.me_obj.loc_x += xmod
# self.me_obj.loc_y += ymod
# self.me_obj.loc_z += zmod
# self.me_obj.set_modified()
#
# from helpers import manhattan
# ourx, oury = self.me_obj.loc_x, self.me_obj.loc_y
# for o in Object.get_objects(physical=True):
# # Is the distance between that object and the character less than 3?
# if manhattan(o.loc_x, o.loc_y, ourx, oury) < 1:
# # We collided against something, so return now and don't
# # save the location changes into the database.
# return False
# else:
# # We didn't collide with any objects.
# self.me_obj.save()
# return True
#
# def wander(self):
# return self.move(random.randint(-1, 1), random.randint(-1, 1), random.randint(-1, 1))
. Output only the next line. | obj.loc_x, obj.loc_y, obj.loc_z = 0, 0, 0 |
Next line prediction: <|code_start|> '''
def post(self):
username = self.get_argument("username", "")
password = self.get_argument("password", "")
auth = self.authenticate(username, password)
if auth:
self.set_current_user(username)
self.set_admin(username)
self.write('Login successful.')
else:
raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
def authenticate(self, username, password):
'''Compares a username/password pair against that in the database.
If they match, return True.
Else, return False.'''
# Do some database stuff here to verify the user.
user = User.get(username=username)
if not user:
return False
return UserController.check_password(plaintext=password, hashed=user.password)
def set_admin(self, user):
# Look up username in admins list in database
# if present, set secure cookie for admin
if user in settings.ADMINISTRATORS:
self.set_secure_cookie("admin", 'true')
else:
self.clear_cookie("admin")
<|code_end|>
. Use current file imports:
(import json
import logging
import tornado
import settings
from passlib.context import CryptContext
from sqlalchemy.exc import IntegrityError
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Character, User, db)
and context including class names, function names, or small code snippets from other files:
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
. Output only the next line. | def set_current_user(self, user): |
Based on the snippet: <|code_start|> .. http:post:: /logout
Creates a User in the AuthenticationServer's database.
**Example request**:
.. sourcecode:: http
GET /logout HTTP/1.1
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Set-Cookie: user=; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
:status 200: Successfully logged out.
'''
def get(self):
self.clear_cookie("user")
class CharacterHandler(BaseHandler):
'''CharacterHandler gets a list of characters for the given user account.
GET /characters'''
@tornado.web.authenticated
def get(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import logging
import tornado
import settings
from passlib.context import CryptContext
from sqlalchemy.exc import IntegrityError
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Character, User, db
and context (classes, functions, sometimes code) from other files:
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
. Output only the next line. | self.write(json.dumps(self.get_characters(self.get_current_user()))) |
Using the snippet: <|code_start|> def post(self):
username = self.get_argument("username", "")
password = self.get_argument("password", "")
auth = self.authenticate(username, password)
if auth:
self.set_current_user(username)
self.set_admin(username)
self.write('Login successful.')
else:
raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
def authenticate(self, username, password):
'''Compares a username/password pair against that in the database.
If they match, return True.
Else, return False.'''
# Do some database stuff here to verify the user.
user = User.get(username=username)
if not user:
return False
return UserController.check_password(plaintext=password, hashed=user.password)
def set_admin(self, user):
# Look up username in admins list in database
# if present, set secure cookie for admin
if user in settings.ADMINISTRATORS:
self.set_secure_cookie("admin", 'true')
else:
self.clear_cookie("admin")
def set_current_user(self, user):
<|code_end|>
, determine the next line of code. You have imports:
import json
import logging
import tornado
import settings
from passlib.context import CryptContext
from sqlalchemy.exc import IntegrityError
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Character, User, db
and context (class names, function names, or code) available:
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
. Output only the next line. | if user: |
Given the code snippet: <|code_start|> HTTP/1.1 200 OK
Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
Login successful.
:param username: The name of the user to log in as.
:param password: The password to use for authenticating the user.
:status 200: Login successful.
:status 401: Login failed due to bad username and/or password
'''
def post(self):
username = self.get_argument("username", "")
password = self.get_argument("password", "")
auth = self.authenticate(username, password)
if auth:
self.set_current_user(username)
self.set_admin(username)
self.write('Login successful.')
else:
raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
def authenticate(self, username, password):
'''Compares a username/password pair against that in the database.
If they match, return True.
Else, return False.'''
# Do some database stuff here to verify the user.
user = User.get(username=username)
if not user:
<|code_end|>
, generate the next line using the imports in this file:
import json
import logging
import tornado
import settings
from passlib.context import CryptContext
from sqlalchemy.exc import IntegrityError
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Character, User, db
and context (functions, classes, or occasionally code) from other files:
# Path: baseserver.py
# class BaseServer(Application):
# def __init__(self, extra_handlers):
# '''Expects a list of tuple handlers like:
# [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
# '''
# url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
#
# app_settings = {
# "cookie_secret": settings.COOKIE_SECRET,
# "login_url": ''.join((url, "/login")),
# }
#
# handlers = []
# handlers.append((r"/version", VersionHandler))
# handlers.append((r"/source", SelfServe))
# handlers.append((r"/ping", PingHandler))
# handlers.append((r"/", PingHandler))
#
# handlers.extend(extra_handlers)
#
# options.parse_command_line()
# dburi = options.dburi
#
# # Connect to the elixir db
# setup(db_uri=dburi)
#
# Application.__init__(self, handlers, debug=True, **app_settings)
#
# def start(self):
# IOLoop.current().start()
#
# class SimpleHandler(BaseHandler):
# def __init__(self, output, *args):
# self.output = output
# RequestHandler.__init__(self, *args)
#
# def get(self):
# self.write(self.output)
#
# class BaseHandler(RequestHandler):
# def _handle_request_exception(self, e):
# if client:
# client.captureException()
# RequestHandler._handle_request_exception(self, e)
#
# def get_login_url(self):
# return u"/login"
#
# def get_current_user(self):
# user_json = self.get_secure_cookie("user")
# if user_json:
# return user_json
# else:
# return None
#
# def HTTPError(self, code, message):
# def write_error(status_code, **kwargs):
# self.write(message)
# self.write_error = write_error
# self.send_error(code)
# self.write_error = old_write_error
#
# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
# class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
# def default(self, obj):
# def exists(cls, *args, **kwargs):
# def json_dumps(self):
# def __repr__(self):
# def __repr__(self):
# def loc(self):
# def loc(self, val):
# def set_modified(self, date_time=None):
# def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
. Output only the next line. | return False |
Next line prediction: <|code_start|>
logger = logging.getLogger(__name__)
class IncidentUpdateCreateForm(forms.ModelForm):
class Meta:
model = IncidentUpdate
fields = ['status', 'description']
class IncidentCreateForm(forms.ModelForm):
class Meta:
model = Incident
<|code_end|>
. Use current file imports:
(from django import forms
from status.models import Incident, IncidentUpdate
from braces.forms import UserKwargModelFormMixin
import logging)
and context including class names, function names, or small code snippets from other files:
# Path: status/models.py
# class Incident(BaseModel):
# """ Creates an incident. Incidents are displayed at the top of the page until closed. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# hidden = models.BooleanField(default=False)
#
# def __unicode__(self):
# return "%s - %s" % (self.user, self.name)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.pk, ])
#
# def get_first_update(self):
# try:
# first = self.incidentupdate_set.first()
# except IncidentUpdate.DoesNotExist:
# first = None
# return first
#
# def get_latest_update(self):
# try:
# latest = self.incidentupdate_set.latest()
# except IncidentUpdate.DoesNotExist:
# latest = None
# return latest
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident'
# verbose_name_plural = 'Incidents'
# ordering = ['-created', ]
#
# class IncidentUpdate(BaseModel):
# """ Updates about an incident. """
# incident = models.ForeignKey(Incident)
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# status = models.ForeignKey(Status)
# description = models.TextField()
#
# def __unicode__(self):
# return "%s - %s: %s" % (self.user, self.status, self.description)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.incident.pk, ])
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident Update'
# verbose_name_plural = 'Incident Updates'
# ordering = ['created', ]
#
# def save(self, *args, **kwargs):
# """ Update the parent incident update time too. """
# self.incident.updated = timezone.now()
# self.incident.save()
# super(IncidentUpdate, self).save(*args, **kwargs)
. Output only the next line. | fields = ['name'] |
Given snippet: <|code_start|> i.save()
f = form2.save(commit=False)
f.incident = i
f.user = request.user
f.save()
if settings.SLACK_CHANNEL and settings.SLACK_TOKEN:
if len(f.description) > 50:
description = f.description[:50] + '...'
else:
description = f.description
try:
message = "<https://%s%s|%s> (%s): %s" % (
get_current_site(request),
reverse('status:incident_detail', args=[i.pk, ]),
i.name,
f.status.name,
description
)
send_to_slack(message, username=settings.SLACK_USERNAME, channel=settings.SLACK_CHANNEL)
except Exception as e:
logger.warn('Unable to send to slack: %s' % (e))
return HttpResponseRedirect('/')
else:
form = IncidentCreateForm()
form2 = IncidentUpdateCreateForm()
request_context = RequestContext(request)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import date, timedelta
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.template import RequestContext, Template
from django.template.loader import get_template
from django.utils.decorators import method_decorator
from django.views.generic import (
MonthArchiveView, YearArchiveView, CreateView, DeleteView, DetailView, ListView, TemplateView
)
from stronghold.decorators import public
from status.models import Incident, IncidentUpdate
from status.forms import IncidentCreateForm, IncidentUpdateCreateForm
import slack
import slack.chat
import logging
and context:
# Path: status/models.py
# class Incident(BaseModel):
# """ Creates an incident. Incidents are displayed at the top of the page until closed. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# hidden = models.BooleanField(default=False)
#
# def __unicode__(self):
# return "%s - %s" % (self.user, self.name)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.pk, ])
#
# def get_first_update(self):
# try:
# first = self.incidentupdate_set.first()
# except IncidentUpdate.DoesNotExist:
# first = None
# return first
#
# def get_latest_update(self):
# try:
# latest = self.incidentupdate_set.latest()
# except IncidentUpdate.DoesNotExist:
# latest = None
# return latest
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident'
# verbose_name_plural = 'Incidents'
# ordering = ['-created', ]
#
# class IncidentUpdate(BaseModel):
# """ Updates about an incident. """
# incident = models.ForeignKey(Incident)
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# status = models.ForeignKey(Status)
# description = models.TextField()
#
# def __unicode__(self):
# return "%s - %s: %s" % (self.user, self.status, self.description)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.incident.pk, ])
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident Update'
# verbose_name_plural = 'Incident Updates'
# ordering = ['created', ]
#
# def save(self, *args, **kwargs):
# """ Update the parent incident update time too. """
# self.incident.updated = timezone.now()
# self.incident.save()
# super(IncidentUpdate, self).save(*args, **kwargs)
#
# Path: status/forms.py
# class IncidentCreateForm(forms.ModelForm):
# class Meta:
# model = Incident
# fields = ['name']
#
# class IncidentUpdateCreateForm(forms.ModelForm):
# class Meta:
# model = IncidentUpdate
# fields = ['status', 'description']
which might include code, classes, or functions. Output only the next line. | request_context.push({'form': form, 'form2': form2}) |
Based on the snippet: <|code_start|>
logger = logging.getLogger(__name__)
def send_to_slack(message, channel='engineering', username='statusbot', emoji=':statusbot:', override_debug=False):
slack.api_token = settings.SLACK_TOKEN
if settings.DEBUG and not override_debug:
logger.info('Diverting from %s to dev while in debug mode as %s: %s' % (channel, username, message))
slack.chat.post_message('dev', 'DEBUG: ' + message, username=username, icon_emoji=emoji)
else:
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import date, timedelta
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.template import RequestContext, Template
from django.template.loader import get_template
from django.utils.decorators import method_decorator
from django.views.generic import (
MonthArchiveView, YearArchiveView, CreateView, DeleteView, DetailView, ListView, TemplateView
)
from stronghold.decorators import public
from status.models import Incident, IncidentUpdate
from status.forms import IncidentCreateForm, IncidentUpdateCreateForm
import slack
import slack.chat
import logging
and context (classes, functions, sometimes code) from other files:
# Path: status/models.py
# class Incident(BaseModel):
# """ Creates an incident. Incidents are displayed at the top of the page until closed. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# hidden = models.BooleanField(default=False)
#
# def __unicode__(self):
# return "%s - %s" % (self.user, self.name)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.pk, ])
#
# def get_first_update(self):
# try:
# first = self.incidentupdate_set.first()
# except IncidentUpdate.DoesNotExist:
# first = None
# return first
#
# def get_latest_update(self):
# try:
# latest = self.incidentupdate_set.latest()
# except IncidentUpdate.DoesNotExist:
# latest = None
# return latest
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident'
# verbose_name_plural = 'Incidents'
# ordering = ['-created', ]
#
# class IncidentUpdate(BaseModel):
# """ Updates about an incident. """
# incident = models.ForeignKey(Incident)
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# status = models.ForeignKey(Status)
# description = models.TextField()
#
# def __unicode__(self):
# return "%s - %s: %s" % (self.user, self.status, self.description)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.incident.pk, ])
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident Update'
# verbose_name_plural = 'Incident Updates'
# ordering = ['created', ]
#
# def save(self, *args, **kwargs):
# """ Update the parent incident update time too. """
# self.incident.updated = timezone.now()
# self.incident.save()
# super(IncidentUpdate, self).save(*args, **kwargs)
#
# Path: status/forms.py
# class IncidentCreateForm(forms.ModelForm):
# class Meta:
# model = Incident
# fields = ['name']
#
# class IncidentUpdateCreateForm(forms.ModelForm):
# class Meta:
# model = IncidentUpdate
# fields = ['status', 'description']
. Output only the next line. | logger.info('Sending to channel %s as %s: %s' % (channel, username, message)) |
Based on the snippet: <|code_start|>
class HomeView(TemplateView):
http_method_names = ['get', ]
template_name = 'status/home.html'
@method_decorator(public)
def dispatch(self, *args, **kwargs):
return super(HomeView, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
incident_list = Incident.objects.filter(hidden=False).order_by('-updated')
context.update({
'incident_list': incident_list
})
if hasattr(settings, 'STATUS_TICKET_URL'):
context.update({'STATUS_TICKET_URL': settings.STATUS_TICKET_URL})
if hasattr(settings, 'STATUS_LOGO_URL'):
context.update({'STATUS_LOGO_URL': settings.STATUS_LOGO_URL})
if hasattr(settings, 'STATUS_TITLE'):
context.update({'STATUS_TITLE': settings.STATUS_TITLE})
status_level = 'success'
for incident in incident_list:
try:
if incident.get_latest_update().status.type == 'danger':
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import date, timedelta
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.template import RequestContext, Template
from django.template.loader import get_template
from django.utils.decorators import method_decorator
from django.views.generic import (
MonthArchiveView, YearArchiveView, CreateView, DeleteView, DetailView, ListView, TemplateView
)
from stronghold.decorators import public
from status.models import Incident, IncidentUpdate
from status.forms import IncidentCreateForm, IncidentUpdateCreateForm
import slack
import slack.chat
import logging
and context (classes, functions, sometimes code) from other files:
# Path: status/models.py
# class Incident(BaseModel):
# """ Creates an incident. Incidents are displayed at the top of the page until closed. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# hidden = models.BooleanField(default=False)
#
# def __unicode__(self):
# return "%s - %s" % (self.user, self.name)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.pk, ])
#
# def get_first_update(self):
# try:
# first = self.incidentupdate_set.first()
# except IncidentUpdate.DoesNotExist:
# first = None
# return first
#
# def get_latest_update(self):
# try:
# latest = self.incidentupdate_set.latest()
# except IncidentUpdate.DoesNotExist:
# latest = None
# return latest
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident'
# verbose_name_plural = 'Incidents'
# ordering = ['-created', ]
#
# class IncidentUpdate(BaseModel):
# """ Updates about an incident. """
# incident = models.ForeignKey(Incident)
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# status = models.ForeignKey(Status)
# description = models.TextField()
#
# def __unicode__(self):
# return "%s - %s: %s" % (self.user, self.status, self.description)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.incident.pk, ])
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident Update'
# verbose_name_plural = 'Incident Updates'
# ordering = ['created', ]
#
# def save(self, *args, **kwargs):
# """ Update the parent incident update time too. """
# self.incident.updated = timezone.now()
# self.incident.save()
# super(IncidentUpdate, self).save(*args, **kwargs)
#
# Path: status/forms.py
# class IncidentCreateForm(forms.ModelForm):
# class Meta:
# model = Incident
# fields = ['name']
#
# class IncidentUpdateCreateForm(forms.ModelForm):
# class Meta:
# model = IncidentUpdate
# fields = ['status', 'description']
. Output only the next line. | status_level = 'danger' |
Given the following code snippet before the placeholder: <|code_start|>
class IncidentArchiveMonthView(MonthArchiveView):
make_object_list = True
queryset = Incident.objects.all()
date_field = 'updated'
month_format = '%m'
@method_decorator(public)
def dispatch(self, *args, **kwargs):
return super(IncidentArchiveMonthView, self).dispatch(*args, **kwargs)
class HomeView(TemplateView):
http_method_names = ['get', ]
template_name = 'status/home.html'
@method_decorator(public)
def dispatch(self, *args, **kwargs):
return super(HomeView, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
incident_list = Incident.objects.filter(hidden=False).order_by('-updated')
context.update({
'incident_list': incident_list
})
if hasattr(settings, 'STATUS_TICKET_URL'):
context.update({'STATUS_TICKET_URL': settings.STATUS_TICKET_URL})
<|code_end|>
, predict the next line using imports from the current file:
from datetime import date, timedelta
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.template import RequestContext, Template
from django.template.loader import get_template
from django.utils.decorators import method_decorator
from django.views.generic import (
MonthArchiveView, YearArchiveView, CreateView, DeleteView, DetailView, ListView, TemplateView
)
from stronghold.decorators import public
from status.models import Incident, IncidentUpdate
from status.forms import IncidentCreateForm, IncidentUpdateCreateForm
import slack
import slack.chat
import logging
and context including class names, function names, and sometimes code from other files:
# Path: status/models.py
# class Incident(BaseModel):
# """ Creates an incident. Incidents are displayed at the top of the page until closed. """
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# name = models.CharField(max_length=255)
# hidden = models.BooleanField(default=False)
#
# def __unicode__(self):
# return "%s - %s" % (self.user, self.name)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.pk, ])
#
# def get_first_update(self):
# try:
# first = self.incidentupdate_set.first()
# except IncidentUpdate.DoesNotExist:
# first = None
# return first
#
# def get_latest_update(self):
# try:
# latest = self.incidentupdate_set.latest()
# except IncidentUpdate.DoesNotExist:
# latest = None
# return latest
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident'
# verbose_name_plural = 'Incidents'
# ordering = ['-created', ]
#
# class IncidentUpdate(BaseModel):
# """ Updates about an incident. """
# incident = models.ForeignKey(Incident)
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# status = models.ForeignKey(Status)
# description = models.TextField()
#
# def __unicode__(self):
# return "%s - %s: %s" % (self.user, self.status, self.description)
#
# def get_absolute_url(self):
# return reverse('status:incident_detail', args=[self.incident.pk, ])
#
# class Meta:
# get_latest_by = 'created'
# verbose_name = 'Incident Update'
# verbose_name_plural = 'Incident Updates'
# ordering = ['created', ]
#
# def save(self, *args, **kwargs):
# """ Update the parent incident update time too. """
# self.incident.updated = timezone.now()
# self.incident.save()
# super(IncidentUpdate, self).save(*args, **kwargs)
#
# Path: status/forms.py
# class IncidentCreateForm(forms.ModelForm):
# class Meta:
# model = Incident
# fields = ['name']
#
# class IncidentUpdateCreateForm(forms.ModelForm):
# class Meta:
# model = IncidentUpdate
# fields = ['status', 'description']
. Output only the next line. | if hasattr(settings, 'STATUS_LOGO_URL'): |
Given the following code snippet before the placeholder: <|code_start|>
app = Flask(__name__)
app.secret_key = os.environ['SECRET_KEY']
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
app.config['DEBUG'] = 'DEBUG' in os.environ
app.wsgi_app = ProxyFix(app.wsgi_app)
if 'SSLIFY' in os.environ:
SSLify(app)
def get_service_modules():
for filename in glob.glob(os.path.join('services', '*.py')):
<|code_end|>
, predict the next line using imports from the current file:
import glob
import os
from flask import Flask
from werkzeug.contrib.fixers import ProxyFix
from flask_sslify import SSLify
from foauth.providers import OAuthMeta
and context including class names, function names, and sometimes code from other files:
# Path: foauth/providers.py
# class OAuthMeta(type):
# def __init__(cls, name, bases, attrs):
# if 'alias' not in attrs:
# cls.alias = cls.__name__.lower()
# if 'api_domain' in attrs and 'api_domains' not in attrs:
# cls.api_domains = [cls.api_domain]
# if 'provider_url' in attrs and 'favicon_url' not in attrs:
# # Use a favicon service when no favicon is supplied
# domain = urlparse.urlparse(cls.provider_url).netloc
# cls.favicon_url = 'https://www.google.com/s2/favicons?domain=%s' % domain
#
# if 'name' not in attrs:
# cls.name = cls.__name__
. Output only the next line. | module_name = os.path.splitext(os.path.split(filename)[1])[0] |
Predict the next line after this snippet: <|code_start|>
class ContentTypeManager(models.Manager):
def get_queryset(self):
super_ = super(ContentTypeManager, self)
qs = super_.get_queryset()
if not settings.PAGES_PAGE_USE_EXT_CONTENT_TYPES:
return qs.filter(is_extended=False)
<|code_end|>
using the current file's imports:
import django
from django.db import models
from pages.conf import settings
and any relevant context from other files:
# Path: pages/conf.py
# class PagesAppConf(AppConf):
# class Meta:
# DEFAULT_LANGUAGE = getattr(settings, 'PAGES_DEFAULT_LANGUAGE', 'en')
# USE_FALLBACK_LANGUAGE = getattr(settings, 'PAGES_USE_FALLBACK_LANGUAGE', True)
# FALLBACK_LANGUAGE = getattr(settings, 'PAGES_FALLBACK_LANGUAGE', 'en')
# FALLBACK_LANGUAGE_COOKIE_NAME = getattr(settings, 'PAGES_FALLBACK_LANGUAGE', 'pages_fallback_language')
# ALLOW_DJANGO_TEMPLATES = getattr(settings, 'PAGES_ALLOW_DJANGO_TEMPLATES', False)
# USE_SITE_ID = getattr(settings, 'PAGES_USE_SITE_ID', False)
# HIDE_SITES = getattr(settings, 'PAGES_HIDE_SITES', True)
# DEFAULT_TEMPLATE = getattr(settings, 'PAGES_DEFAULT_TEMPLATE', 'pages/page.html')
# RAISE_403 = getattr(settings, 'PAGES_RAISE_403', True)
# RENDER_403 = getattr(settings, 'PAGES_RENDER_403', False)
# TEMPLATE_403 = getattr(settings, 'PAGES_TEMPLATE_403', 'pages/403.html')
# PAGE_SLUG_NAME = getattr(settings, 'PAGES_PAGE_SLUG_NAME', 'slug')
# HOME_PAGE_SLUG = getattr(settings, 'PAGES_HOME_PAGE_SLUG', 'home')
# CACHE_BACKEND = getattr(settings, 'PAGES_CACHE_BACKEND', 'default')
# CACHE_PREFIX = getattr(settings, 'PAGES_CACHE_PREFIX', 'pages_')
# CACHE_DELETE = getattr(settings, 'PAGES_CACHE_DELETE', False)
# PAGE_CACHE_KEY = getattr(settings, 'PAGES_PAGE_CACHE_KEY', 'page_cache_key_')
# PAGE_VERSION_KEY = getattr(settings, 'PAGES_PAGE_VERSION_KEY', 'page_version_key_')
# PAGE_CACHE_TIMEOUT = getattr(settings, 'PAGES_PAGE_CACHE_TIMEOUT', 31536000) # timeout 1 year by default
# PAGE_HTTP_MAX_AGE = getattr(settings, 'PAGES_PAGE_CACHE_TIMEOUT', 3600) # timeout 1 hour by default
# PAGE_USE_EXT_CONTENT_TYPES = getattr(settings, 'PAGES_PAGE_USE_EXT_CONTENT_TYPES', False)
# PAGE_EXT_CONTENT_TYPES = getattr(settings, 'PAGES_PAGE_EXT_CONTENT_TYPES', None)
# PAGE_EXT_CONTENT_INLINES = getattr(settings, 'PAGES_PAGE_EXT_CONTENT_INLINES', None)
# PAGE_USE_META_TITLE_FOR_SLUG = getattr(settings, 'PAGES_PAGE_USE_META_TITLE_FOR_SLUG', True)
# PAGE_ACTIVE_CSS_CLASS = getattr(settings, 'PAGES_PAGE_ACTIVE_CSS_CLASS', 'active')
. Output only the next line. | else: |
Next line prediction: <|code_start|>
register = template.Library()
@register.simple_tag(takes_context=True)
def page_video_by_id(context, oid):
obj = get_page_object_by_id(context, 'video', oid)
if obj is None:
return None
return obj
@register.assignment_tag(takes_context=True)
<|code_end|>
. Use current file imports:
(from django import template
from pages.templatetags.pages_tags import get_page_object_by_id)
and context including class names, function names, or small code snippets from other files:
# Path: pages/templatetags/pages_tags.py
# @register.assignment_tag(takes_context=True)
# def get_page_object_by_id(context, object_type, oid):
# """
# **Arguments**
#
# ``object_type``
# object type
#
# ``oid``
# id for object selection
#
# :return selected object
# """
# if type(oid) != int:
# raise template.TemplateSyntaxError('page_object_by_id tag requires a integer argument')
#
# selected_object = None
#
# try:
# try:
# for obj in context['page']['content'][object_type]:
# sid = '{0:>s}:{1:>s}:{2:>s}:{3:>d}'.format(
# obj.language, context['page']['page'].name, obj.type, oid
# )
# if obj.sid == sid:
# selected_object = obj
# break
# except TypeError:
# pass
# except KeyError:
# try:
# try:
# for obj in context['page']['ext_content'][object_type]:
# sid = '{0:>s}:{1:>s}:{2:>s}:{3:>d}'.format(
# obj.language, context['page']['page'].name, obj.type, oid
# )
# if obj.sid == sid:
# selected_object = obj
# break
# except TypeError:
# pass
# except KeyError:
# raise template.TemplateSyntaxError('wrong content type: {0:>s}'.format(object_type))
# return selected_object
. Output only the next line. | def get_page_video_by_id(context, oid): |
Using the snippet: <|code_start|>
class PageContentInline(admin.StackedInline):
model = PageContent
# max_num = 1
extra = 1
class PageContentAdmin(admin.ModelAdmin):
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from pages.models import PageContent
and context (class names, function names, or code) available:
# Path: pages/models/pagecontent.py
# class PageContent(models.Model):
# page = models.ForeignKey(Page, verbose_name=_('Page'))
# type = models.ForeignKey(PageContentType)
# objects = models.Manager()
#
# def __str__(self):
# """id string of instance"""
# return '{0}:{1}:{2}'.format(self.page, self.type, self.pk)
#
# def save(self, *args, **kwargs):
# """Override the default ``save`` method."""
#
# # Call parent's ``save`` method
# super(PageContent, self).save(*args, **kwargs)
#
# class Meta:
# app_label = 'pages'
# verbose_name = _('Content')
# verbose_name_plural = _('Content')
# unique_together = ('page', 'type',)
. Output only the next line. | list_display = ['__str__'] |
Predict the next line for this snippet: <|code_start|>from __future__ import unicode_literals
class EvolutionsApp2TestModel(models.Model):
char_field = models.CharField(max_length=10)
fkey = models.ForeignKey(EvolutionsAppTestModel,
on_delete=models.CASCADE,
null=True)
class EvolutionsApp2TestModel2(models.Model):
fkey = models.ForeignKey(EvolutionsApp2TestModel,
on_delete=models.CASCADE,
null=True)
<|code_end|>
with the help of current file imports:
from django.db import models
from django_evolution.tests.evolutions_app.models import EvolutionsAppTestModel
and context from other files:
# Path: django_evolution/tests/evolutions_app/models.py
# class EvolutionsAppTestModel(models.Model):
# char_field = models.CharField(max_length=10, null=True)
# char_field2 = models.CharField(max_length=20, null=True)
, which may contain function names, class names, or code. Output only the next line. | int_field = models.IntegerField(default=100) |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
django_version = django.VERSION[:2]
if django_version >= (2, 0):
drop_index_sql = 'DROP INDEX IF EXISTS'
else:
drop_index_sql = 'DROP INDEX'
if django_version < (2, 0) or django_version >= (3, 1):
DESC = ' DESC'
else:
<|code_end|>
, generate the next line using the imports in this file:
import django
from django_evolution.tests.utils import (make_generate_constraint_name,
make_generate_index_name,
make_generate_unique_constraint_name)
and context (functions, classes, or occasionally code) from other files:
# Path: django_evolution/tests/utils.py
# def make_generate_constraint_name(connection):
# """Return a constraint generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_constraint_name` that doesn't
# need to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_constraint_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_constraint_name, connection)
#
# def make_generate_index_name(connection):
# """Return an index generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_index_name` that doesn't need
# to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_index_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_index_name, connection)
#
# def make_generate_unique_constraint_name(connection):
# """Return a constraint generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_constraint_name` that doesn't
# need to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_constraint_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_unique_constraint_name, connection)
. Output only the next line. | DESC = 'DESC' |
Given snippet: <|code_start|>from __future__ import unicode_literals
MUTATIONS = [
ChangeMeta('Permission', 'unique_together',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django_evolution.mutations import ChangeMeta
and context:
# Path: django_evolution/mutations.py
# class ChangeMeta(BaseModelMutation):
# """A mutation that changes meta proeprties on a model."""
#
# simulation_failure_error = (
# 'Cannot change the "%(prop_name)s" meta property on model '
# '"%(app_label)s.%(model_name)s".'
# )
#
# error_vars = dict({
# 'prop_name': 'prop_name',
# }, **BaseModelMutation.error_vars)
#
# def __init__(self, model_name, prop_name, new_value):
# """Initialize the mutation.
#
# Args:
# model_name (unicode):
# The name of the model to change meta properties on.
#
# prop_name (unicode):
# The name of the property to change.
#
# new_value (object):
# The new value for the property.
# """
# super(ChangeMeta, self).__init__(model_name)
#
# self.prop_name = prop_name
# self.new_value = new_value
#
# def get_hint_params(self):
# """Return parameters for the mutation's hinted evolution.
#
# Returns:
# list of unicode:
# A list of parameter strings to pass to the mutation's constructor
# in a hinted evolution.
# """
# if self.prop_name in ('index_together', 'unique_together'):
# # Make sure these always appear as lists and not tuples, for
# # compatibility.
# norm_value = list(self.new_value)
# elif self.prop_name == 'constraints':
# # Django >= 2.2
# norm_value = [
# OrderedDict(sorted(six.iteritems(constraint_data),
# key=lambda pair: pair[0]))
# for constraint_data in self.new_value
# ]
# elif self.prop_name == 'indexes':
# # Django >= 1.11
# norm_value = [
# OrderedDict(sorted(six.iteritems(index_data),
# key=lambda pair: pair[0]))
# for index_data in self.new_value
# ]
# else:
# norm_value = self.new_value
#
# return [
# self.serialize_value(self.model_name),
# self.serialize_value(self.prop_name),
# self.serialize_value(norm_value),
# ]
#
# def simulate(self, simulation):
# """Simulate the mutation.
#
# This will alter the database schema to change metadata on the specified
# model.
#
# Args:
# simulation (Simulation):
# The state for the simulation.
#
# Raises:
# django_evolution.errors.SimulationFailure:
# The simulation failed. The reason is in the exception's
# message.
# """
# model_sig = simulation.get_model_sig(self.model_name)
# evolver = simulation.get_evolver()
# prop_name = self.prop_name
#
# if not evolver.supported_change_meta.get(prop_name):
# simulation.fail('The property cannot be modified on this '
# 'database.')
#
# if prop_name == 'index_together':
# model_sig.index_together = self.new_value
# elif prop_name == 'unique_together':
# model_sig.apply_unique_together(self.new_value)
# elif prop_name == 'constraints':
# # Django >= 2.2
# constraint_sigs = []
#
# for constraint_data in self.new_value:
# constraint_attrs = constraint_data.copy()
# constraint_attrs.pop('name')
# constraint_attrs.pop('type')
#
# constraint_sigs.append(
# ConstraintSignature(
# name=constraint_data['name'],
# constraint_type=constraint_data['type'],
# attrs=constraint_attrs))
#
# model_sig.constraint_sigs = constraint_sigs
# elif prop_name == 'indexes':
# # Django >= 1.11
# model_sig.index_sigs = [
# IndexSignature(name=index.get('name'),
# fields=index['fields'])
# for index in self.new_value
# ]
# else:
# simulation.fail('The property cannot be changed on a model.')
#
# def mutate(self, mutator, model):
# """Schedule a model meta property change on the mutator.
#
# This will instruct the mutator to change a meta property on a model. It
# will be scheduled and later executed on the database, if not optimized
# out.
#
# Args:
# mutator (django_evolution.mutators.ModelMutator):
# The mutator to perform an operation on.
#
# model (MockModel):
# The model being mutated.
# """
# mutator.change_meta(self, self.prop_name, self.new_value)
which might include code, classes, or functions. Output only the next line. | [('content_type', 'codename')]), |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
django_version = django.VERSION[:2]
if django_version < (2, 0) or django_version >= (3, 1):
DESC = ' DESC'
else:
DESC = 'DESC'
<|code_end|>
, predict the next line using imports from the current file:
import django
from django_evolution.tests.utils import (make_generate_constraint_name,
make_generate_index_name,
make_generate_unique_constraint_name)
and context including class names, function names, and sometimes code from other files:
# Path: django_evolution/tests/utils.py
# def make_generate_constraint_name(connection):
# """Return a constraint generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_constraint_name` that doesn't
# need to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_constraint_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_constraint_name, connection)
#
# def make_generate_index_name(connection):
# """Return an index generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_index_name` that doesn't need
# to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_index_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_index_name, connection)
#
# def make_generate_unique_constraint_name(connection):
# """Return a constraint generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_constraint_name` that doesn't
# need to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_constraint_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_unique_constraint_name, connection)
. Output only the next line. | def add_field(connection): |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals
django_version = django.VERSION[:2]
if django_version < (2, 0) or django_version >= (3, 1):
DESC = ' DESC'
else:
<|code_end|>
, predict the next line using imports from the current file:
import django
from django_evolution.tests.utils import (make_generate_constraint_name,
make_generate_index_name,
make_generate_unique_constraint_name)
and context including class names, function names, and sometimes code from other files:
# Path: django_evolution/tests/utils.py
# def make_generate_constraint_name(connection):
# """Return a constraint generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_constraint_name` that doesn't
# need to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_constraint_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_constraint_name, connection)
#
# def make_generate_index_name(connection):
# """Return an index generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_index_name` that doesn't need
# to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_index_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_index_name, connection)
#
# def make_generate_unique_constraint_name(connection):
# """Return a constraint generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_constraint_name` that doesn't
# need to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_constraint_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_unique_constraint_name, connection)
. Output only the next line. | DESC = 'DESC' |
Given snippet: <|code_start|>from __future__ import unicode_literals
django_version = django.VERSION[:2]
sqlite_version = Database.sqlite_version_info[:2]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import django
from django.db.backends.sqlite3.base import Database
from django_evolution.tests.utils import (make_generate_index_name,
make_generate_unique_constraint_name)
and context:
# Path: django_evolution/tests/utils.py
# def make_generate_index_name(connection):
# """Return an index generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_index_name` that doesn't need
# to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_index_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_index_name, connection)
#
# def make_generate_unique_constraint_name(connection):
# """Return a constraint generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_constraint_name` that doesn't
# need to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_constraint_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_unique_constraint_name, connection)
which might include code, classes, or functions. Output only the next line. | if django_version < (2, 0) or django_version >= (3, 1): |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
django_version = django.VERSION[:2]
sqlite_version = Database.sqlite_version_info[:2]
<|code_end|>
, generate the next line using the imports in this file:
import re
import django
from django.db.backends.sqlite3.base import Database
from django_evolution.tests.utils import (make_generate_index_name,
make_generate_unique_constraint_name)
and context (functions, classes, or occasionally code) from other files:
# Path: django_evolution/tests/utils.py
# def make_generate_index_name(connection):
# """Return an index generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_index_name` that doesn't need
# to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_index_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_index_name, connection)
#
# def make_generate_unique_constraint_name(connection):
# """Return a constraint generation function for the given database type.
#
# This is used by the test data modules as a convenience to allow
# for a local version of :py:func:`generate_constraint_name` that doesn't
# need to be passed a database connection on every call.
#
# Args:
# connection (django.db.backends.base.base.BaseDatabaseWrapper):
# The database connection.
#
# Returns:
# callable:
# A version of :py:func:`generate_constraint_name` that doesn't need the
# ``db_type`` parameter.
# """
# return partial(generate_unique_constraint_name, connection)
. Output only the next line. | if django_version < (2, 0) or django_version >= (3, 1): |
Continue the code snippet: <|code_start|>
if app_label:
q = q & Q(app_label=app_label)
evolutions = list(Evolution.objects.filter(q).values('pk'))
if len(evolutions) == 0:
if app_label:
raise CommandError(
"Unable to find evolution '%s' for app label '%s'" %
(evolution_label, app_label))
else:
raise CommandError(
"Unable to find evolution '%s'" % evolution_label)
if len(evolutions) > 1:
if app_label:
raise CommandError(
"Too many evolutions named '%s' for app label '%s'" %
(evolution_label, app_label))
else:
raise CommandError(
"Too many evolutions named '%s'" % evolution_label)
to_wipe_ids.append(evolutions[0]['pk'])
if to_wipe_ids:
if options['interactive']:
confirm = input("""
You have requested to delete %s evolution(s). This may cause permanent
problems, and should only be done after a FULL BACKUP and under direct
<|code_end|>
. Use current file imports:
from django.core.management.base import CommandError
from django.db.models import Q
from django_evolution.compat.commands import BaseCommand
from django_evolution.compat.six.moves import input
from django_evolution.compat.translation import gettext as _
from django_evolution.models import Evolution
and context (classes, functions, or code) from other files:
# Path: django_evolution/compat/commands.py
# class BaseCommand(DjangoBaseCommand):
# """Base command compatible with a range of Django versions.
#
# This is a version of :py:class:`django.core.management.base.BaseCommand`
# that supports the modern way of adding arguments while retaining
# compatibility with older versions of Django. See the parent class's
# documentation for details on usage.
# """
#
# @property
# def use_argparse(self):
# """Whether argparse should be used for argument parsing.
#
# This is used internally by Django.
# """
# return not bool(self.__class__.__dict__.get('option_list'))
#
# def create_parser(self, *args, **kwargs):
# """Create a parser for the command.
#
# This is a wrapper around Django's method that ensures compatibility
# with old-style (<= 1.6)) and new-style (>= 1.7) argument parsing
# logic.
#
# Args:
# *args (tuple):
# Positional arguments to pass to the parent method.
#
# **kwargs (dict):
# Keyword arguments to pass to the parent method.
#
# Return:
# object:
# The argument parser. This will be a
# :py:class:`optparse.OptionParser` or a
# :py:class:`argparse.ArgumentParser`.
# """
# # Start off by disabling add_arguments() from being invoked by the
# # parent. We want to call this ourselves.
# old_add_arguments = self.add_arguments
# self.add_arguments = lambda *args: None
#
# parser = super(BaseCommand, self).create_parser(*args, **kwargs)
#
# self.add_arguments = old_add_arguments
#
# # Now invoke add_arguments() ourselves, using a wrapper for older
# # versions of Django.
# if isinstance(parser, OptionParser):
# self.add_arguments(OptionParserWrapper(parser))
# else:
# self.add_arguments(parser)
#
# return parser
#
# def add_arguments(self, parser):
# """Add arguments to the command.
#
# By default, this does nothing. Subclasses can override to add
# additional arguments.
#
# Args:
# parser (object):
# The argument parser. This will be a
# :py:class:`optparse.OptionParser` or a
# :py:class:`argparse.ArgumentParser`.
# """
# # This is intentionally meant to be blank by default.
# pass
#
# def __getattribute__(self, name):
# """Return an attribute from the command.
#
# If the attribute name is "option_list", some special work will be
# done to ensure we're returning a valid list that the caller can work
# with, even if the options were created in :py:meth:`add_arguments`.
#
# Args:
# name (unicode):
# The attribute name.
#
# Returns:
# object:
# The attribute value.
# """
# if (name == 'option_list' and
# not getattr(self, '_use_real_option_list', False)):
# # The parser is going to turn around and fetch self.option_list
# # (which will contain the defaults for the class, or the options
# # defined by the subclass if it hasn't been updated yet). We need
# # to make sure it gets the real copy.
# self._use_real_option_list = True
# parser = self.create_parser('', self.__class__.__module__)
# self._use_real_option_list = False
#
# assert isinstance(parser, OptionParser)
#
# # We're going to get more than the options defined for the
# # command. We'll also get the built-in --help and --version
# # options, which are special and will break call_command(), as
# # they don't have a destination variable and aren't listed in the
# # command's option_list normally. So filter those out.
# return [
# option
# for option in parser.option_list
# if option.get_opt_string() not in ('--help', '--version')
# ]
#
# return super(BaseCommand, self).__getattribute__(name)
#
# Path: django_evolution/compat/translation.py
#
# Path: django_evolution/models.py
# class Evolution(models.Model):
# version = models.ForeignKey(Version,
# related_name='evolutions',
# on_delete=models.CASCADE)
# app_label = models.CharField(max_length=200)
# label = models.CharField(max_length=100)
#
# def __str__(self):
# return 'Evolution %s, applied to %s' % (self.label, self.app_label)
#
# class Meta:
# db_table = 'django_evolution'
# ordering = ('id',)
. Output only the next line. | guidance. |
Here is a snippet: <|code_start|> for evolution_label in evolution_labels:
q = Q(label=evolution_label)
if app_label:
q = q & Q(app_label=app_label)
evolutions = list(Evolution.objects.filter(q).values('pk'))
if len(evolutions) == 0:
if app_label:
raise CommandError(
"Unable to find evolution '%s' for app label '%s'" %
(evolution_label, app_label))
else:
raise CommandError(
"Unable to find evolution '%s'" % evolution_label)
if len(evolutions) > 1:
if app_label:
raise CommandError(
"Too many evolutions named '%s' for app label '%s'" %
(evolution_label, app_label))
else:
raise CommandError(
"Too many evolutions named '%s'" % evolution_label)
to_wipe_ids.append(evolutions[0]['pk'])
if to_wipe_ids:
if options['interactive']:
confirm = input("""
<|code_end|>
. Write the next line using the current file imports:
from django.core.management.base import CommandError
from django.db.models import Q
from django_evolution.compat.commands import BaseCommand
from django_evolution.compat.six.moves import input
from django_evolution.compat.translation import gettext as _
from django_evolution.models import Evolution
and context from other files:
# Path: django_evolution/compat/commands.py
# class BaseCommand(DjangoBaseCommand):
# """Base command compatible with a range of Django versions.
#
# This is a version of :py:class:`django.core.management.base.BaseCommand`
# that supports the modern way of adding arguments while retaining
# compatibility with older versions of Django. See the parent class's
# documentation for details on usage.
# """
#
# @property
# def use_argparse(self):
# """Whether argparse should be used for argument parsing.
#
# This is used internally by Django.
# """
# return not bool(self.__class__.__dict__.get('option_list'))
#
# def create_parser(self, *args, **kwargs):
# """Create a parser for the command.
#
# This is a wrapper around Django's method that ensures compatibility
# with old-style (<= 1.6)) and new-style (>= 1.7) argument parsing
# logic.
#
# Args:
# *args (tuple):
# Positional arguments to pass to the parent method.
#
# **kwargs (dict):
# Keyword arguments to pass to the parent method.
#
# Return:
# object:
# The argument parser. This will be a
# :py:class:`optparse.OptionParser` or a
# :py:class:`argparse.ArgumentParser`.
# """
# # Start off by disabling add_arguments() from being invoked by the
# # parent. We want to call this ourselves.
# old_add_arguments = self.add_arguments
# self.add_arguments = lambda *args: None
#
# parser = super(BaseCommand, self).create_parser(*args, **kwargs)
#
# self.add_arguments = old_add_arguments
#
# # Now invoke add_arguments() ourselves, using a wrapper for older
# # versions of Django.
# if isinstance(parser, OptionParser):
# self.add_arguments(OptionParserWrapper(parser))
# else:
# self.add_arguments(parser)
#
# return parser
#
# def add_arguments(self, parser):
# """Add arguments to the command.
#
# By default, this does nothing. Subclasses can override to add
# additional arguments.
#
# Args:
# parser (object):
# The argument parser. This will be a
# :py:class:`optparse.OptionParser` or a
# :py:class:`argparse.ArgumentParser`.
# """
# # This is intentionally meant to be blank by default.
# pass
#
# def __getattribute__(self, name):
# """Return an attribute from the command.
#
# If the attribute name is "option_list", some special work will be
# done to ensure we're returning a valid list that the caller can work
# with, even if the options were created in :py:meth:`add_arguments`.
#
# Args:
# name (unicode):
# The attribute name.
#
# Returns:
# object:
# The attribute value.
# """
# if (name == 'option_list' and
# not getattr(self, '_use_real_option_list', False)):
# # The parser is going to turn around and fetch self.option_list
# # (which will contain the defaults for the class, or the options
# # defined by the subclass if it hasn't been updated yet). We need
# # to make sure it gets the real copy.
# self._use_real_option_list = True
# parser = self.create_parser('', self.__class__.__module__)
# self._use_real_option_list = False
#
# assert isinstance(parser, OptionParser)
#
# # We're going to get more than the options defined for the
# # command. We'll also get the built-in --help and --version
# # options, which are special and will break call_command(), as
# # they don't have a destination variable and aren't listed in the
# # command's option_list normally. So filter those out.
# return [
# option
# for option in parser.option_list
# if option.get_opt_string() not in ('--help', '--version')
# ]
#
# return super(BaseCommand, self).__getattribute__(name)
#
# Path: django_evolution/compat/translation.py
#
# Path: django_evolution/models.py
# class Evolution(models.Model):
# version = models.ForeignKey(Version,
# related_name='evolutions',
# on_delete=models.CASCADE)
# app_label = models.CharField(max_length=200)
# label = models.CharField(max_length=100)
#
# def __str__(self):
# return 'Evolution %s, applied to %s' % (self.label, self.app_label)
#
# class Meta:
# db_table = 'django_evolution'
# ordering = ('id',)
, which may include functions, classes, or code. Output only the next line. | You have requested to delete %s evolution(s). This may cause permanent |
Given the following code snippet before the placeholder: <|code_start|> q = q & Q(app_label=app_label)
evolutions = list(Evolution.objects.filter(q).values('pk'))
if len(evolutions) == 0:
if app_label:
raise CommandError(
"Unable to find evolution '%s' for app label '%s'" %
(evolution_label, app_label))
else:
raise CommandError(
"Unable to find evolution '%s'" % evolution_label)
if len(evolutions) > 1:
if app_label:
raise CommandError(
"Too many evolutions named '%s' for app label '%s'" %
(evolution_label, app_label))
else:
raise CommandError(
"Too many evolutions named '%s'" % evolution_label)
to_wipe_ids.append(evolutions[0]['pk'])
if to_wipe_ids:
if options['interactive']:
confirm = input("""
You have requested to delete %s evolution(s). This may cause permanent
problems, and should only be done after a FULL BACKUP and under direct
guidance.
<|code_end|>
, predict the next line using imports from the current file:
from django.core.management.base import CommandError
from django.db.models import Q
from django_evolution.compat.commands import BaseCommand
from django_evolution.compat.six.moves import input
from django_evolution.compat.translation import gettext as _
from django_evolution.models import Evolution
and context including class names, function names, and sometimes code from other files:
# Path: django_evolution/compat/commands.py
# class BaseCommand(DjangoBaseCommand):
# """Base command compatible with a range of Django versions.
#
# This is a version of :py:class:`django.core.management.base.BaseCommand`
# that supports the modern way of adding arguments while retaining
# compatibility with older versions of Django. See the parent class's
# documentation for details on usage.
# """
#
# @property
# def use_argparse(self):
# """Whether argparse should be used for argument parsing.
#
# This is used internally by Django.
# """
# return not bool(self.__class__.__dict__.get('option_list'))
#
# def create_parser(self, *args, **kwargs):
# """Create a parser for the command.
#
# This is a wrapper around Django's method that ensures compatibility
# with old-style (<= 1.6)) and new-style (>= 1.7) argument parsing
# logic.
#
# Args:
# *args (tuple):
# Positional arguments to pass to the parent method.
#
# **kwargs (dict):
# Keyword arguments to pass to the parent method.
#
# Return:
# object:
# The argument parser. This will be a
# :py:class:`optparse.OptionParser` or a
# :py:class:`argparse.ArgumentParser`.
# """
# # Start off by disabling add_arguments() from being invoked by the
# # parent. We want to call this ourselves.
# old_add_arguments = self.add_arguments
# self.add_arguments = lambda *args: None
#
# parser = super(BaseCommand, self).create_parser(*args, **kwargs)
#
# self.add_arguments = old_add_arguments
#
# # Now invoke add_arguments() ourselves, using a wrapper for older
# # versions of Django.
# if isinstance(parser, OptionParser):
# self.add_arguments(OptionParserWrapper(parser))
# else:
# self.add_arguments(parser)
#
# return parser
#
# def add_arguments(self, parser):
# """Add arguments to the command.
#
# By default, this does nothing. Subclasses can override to add
# additional arguments.
#
# Args:
# parser (object):
# The argument parser. This will be a
# :py:class:`optparse.OptionParser` or a
# :py:class:`argparse.ArgumentParser`.
# """
# # This is intentionally meant to be blank by default.
# pass
#
# def __getattribute__(self, name):
# """Return an attribute from the command.
#
# If the attribute name is "option_list", some special work will be
# done to ensure we're returning a valid list that the caller can work
# with, even if the options were created in :py:meth:`add_arguments`.
#
# Args:
# name (unicode):
# The attribute name.
#
# Returns:
# object:
# The attribute value.
# """
# if (name == 'option_list' and
# not getattr(self, '_use_real_option_list', False)):
# # The parser is going to turn around and fetch self.option_list
# # (which will contain the defaults for the class, or the options
# # defined by the subclass if it hasn't been updated yet). We need
# # to make sure it gets the real copy.
# self._use_real_option_list = True
# parser = self.create_parser('', self.__class__.__module__)
# self._use_real_option_list = False
#
# assert isinstance(parser, OptionParser)
#
# # We're going to get more than the options defined for the
# # command. We'll also get the built-in --help and --version
# # options, which are special and will break call_command(), as
# # they don't have a destination variable and aren't listed in the
# # command's option_list normally. So filter those out.
# return [
# option
# for option in parser.option_list
# if option.get_opt_string() not in ('--help', '--version')
# ]
#
# return super(BaseCommand, self).__getattribute__(name)
#
# Path: django_evolution/compat/translation.py
#
# Path: django_evolution/models.py
# class Evolution(models.Model):
# version = models.ForeignKey(Version,
# related_name='evolutions',
# on_delete=models.CASCADE)
# app_label = models.CharField(max_length=200)
# label = models.CharField(max_length=100)
#
# def __str__(self):
# return 'Evolution %s, applied to %s' % (self.label, self.app_label)
#
# class Meta:
# db_table = 'django_evolution'
# ordering = ('id',)
. Output only the next line. | Are you sure you want to wipe these evolutions from the database? |
Using the snippet: <|code_start|>from __future__ import unicode_literals
MUTATIONS = [
ChangeMeta('ContentType', 'unique_together', [('app_label', 'model')]),
<|code_end|>
, determine the next line of code. You have imports:
from django_evolution.mutations import ChangeMeta
and context (class names, function names, or code) available:
# Path: django_evolution/mutations.py
# class ChangeMeta(BaseModelMutation):
# """A mutation that changes meta proeprties on a model."""
#
# simulation_failure_error = (
# 'Cannot change the "%(prop_name)s" meta property on model '
# '"%(app_label)s.%(model_name)s".'
# )
#
# error_vars = dict({
# 'prop_name': 'prop_name',
# }, **BaseModelMutation.error_vars)
#
# def __init__(self, model_name, prop_name, new_value):
# """Initialize the mutation.
#
# Args:
# model_name (unicode):
# The name of the model to change meta properties on.
#
# prop_name (unicode):
# The name of the property to change.
#
# new_value (object):
# The new value for the property.
# """
# super(ChangeMeta, self).__init__(model_name)
#
# self.prop_name = prop_name
# self.new_value = new_value
#
# def get_hint_params(self):
# """Return parameters for the mutation's hinted evolution.
#
# Returns:
# list of unicode:
# A list of parameter strings to pass to the mutation's constructor
# in a hinted evolution.
# """
# if self.prop_name in ('index_together', 'unique_together'):
# # Make sure these always appear as lists and not tuples, for
# # compatibility.
# norm_value = list(self.new_value)
# elif self.prop_name == 'constraints':
# # Django >= 2.2
# norm_value = [
# OrderedDict(sorted(six.iteritems(constraint_data),
# key=lambda pair: pair[0]))
# for constraint_data in self.new_value
# ]
# elif self.prop_name == 'indexes':
# # Django >= 1.11
# norm_value = [
# OrderedDict(sorted(six.iteritems(index_data),
# key=lambda pair: pair[0]))
# for index_data in self.new_value
# ]
# else:
# norm_value = self.new_value
#
# return [
# self.serialize_value(self.model_name),
# self.serialize_value(self.prop_name),
# self.serialize_value(norm_value),
# ]
#
# def simulate(self, simulation):
# """Simulate the mutation.
#
# This will alter the database schema to change metadata on the specified
# model.
#
# Args:
# simulation (Simulation):
# The state for the simulation.
#
# Raises:
# django_evolution.errors.SimulationFailure:
# The simulation failed. The reason is in the exception's
# message.
# """
# model_sig = simulation.get_model_sig(self.model_name)
# evolver = simulation.get_evolver()
# prop_name = self.prop_name
#
# if not evolver.supported_change_meta.get(prop_name):
# simulation.fail('The property cannot be modified on this '
# 'database.')
#
# if prop_name == 'index_together':
# model_sig.index_together = self.new_value
# elif prop_name == 'unique_together':
# model_sig.apply_unique_together(self.new_value)
# elif prop_name == 'constraints':
# # Django >= 2.2
# constraint_sigs = []
#
# for constraint_data in self.new_value:
# constraint_attrs = constraint_data.copy()
# constraint_attrs.pop('name')
# constraint_attrs.pop('type')
#
# constraint_sigs.append(
# ConstraintSignature(
# name=constraint_data['name'],
# constraint_type=constraint_data['type'],
# attrs=constraint_attrs))
#
# model_sig.constraint_sigs = constraint_sigs
# elif prop_name == 'indexes':
# # Django >= 1.11
# model_sig.index_sigs = [
# IndexSignature(name=index.get('name'),
# fields=index['fields'])
# for index in self.new_value
# ]
# else:
# simulation.fail('The property cannot be changed on a model.')
#
# def mutate(self, mutator, model):
# """Schedule a model meta property change on the mutator.
#
# This will instruct the mutator to change a meta property on a model. It
# will be scheduled and later executed on the database, if not optimized
# out.
#
# Args:
# mutator (django_evolution.mutators.ModelMutator):
# The mutator to perform an operation on.
#
# model (MockModel):
# The model being mutated.
# """
# mutator.change_meta(self, self.prop_name, self.new_value)
. Output only the next line. | ] |
Here is a snippet: <|code_start|> "AP selection phase. This option is part of Lure10 attack."),
action='store_true')
parser.add_argument(
"-lE",
"--lure10-exploit",
help=("Fool the Windows Location Service of nearby Windows users "
"to believe it is within an area that was previously captured "
"with --lure10-capture. Part of the Lure10 attack."))
parser.add_argument(
"--logging",
help="Log activity to file",
action="store_true")
parser.add_argument(
"-dK",
"--disable-karma",
help="Disables KARMA attack",
action="store_true")
parser.add_argument(
"-lP",
"--logpath",
default=None,
help="Determine the full path of the logfile.")
parser.add_argument(
"-cP",
"--credential-log-path",
help="Determine the full path of the file that will store any captured credentials",
default=None)
parser.add_argument(
"--payload-path",
help=("Payload path for scenarios serving a payload"))
<|code_end|>
. Write the next line using the current file imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
, which may include functions, classes, or code. Output only the next line. | parser.add_argument("-cM", "--channel-monitor", |
Based on the snippet: <|code_start|> parser.add_argument(
"--payload-path",
help=("Payload path for scenarios serving a payload"))
parser.add_argument("-cM", "--channel-monitor",
help="Monitor if target access point changes the channel.",
action="store_true")
parser.add_argument("-wP", "--wps-pbc",
help="Monitor if the button on a WPS-PBC Registrar is pressed.",
action="store_true")
parser.add_argument("-wAI", "--wpspbc-assoc-interface",
help="The WLAN interface used for associating to the WPS AccessPoint.",
)
parser.add_argument(
"-kB",
"--known-beacons",
help="Broadcast a number of beacon frames advertising popular WLANs",
action='store_true')
parser.add_argument(
"-fH",
"--force-hostapd",
help="Force the usage of hostapd installed in the system",
action='store_true')
parser.add_argument("-pPD",
"--phishing-pages-directory",
help="Search for phishing pages in this location")
parser.add_argument(
"--dnsmasq-conf",
help="Determine the full path of a custom dnmasq.conf file",
default='/tmp/dnsmasq.conf')
parser.add_argument(
<|code_end|>
, predict the immediate next line with the help of imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context (classes, functions, sometimes code) from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | "-pE", |
Predict the next line for this snippet: <|code_start|> parser.add_argument(
"-p",
"--phishingscenario",
help=("Choose the phishing scenario to run." +
"This option will skip the scenario selection phase. " +
"Example: -p firmware_upgrade"))
parser.add_argument(
"-pK",
"--presharedkey",
help=("Add WPA/WPA2 protection on the rogue Access Point. " +
"Example: -pK s3cr3tp4ssw0rd"))
parser.add_argument(
"-hC",
"--handshake-capture",
help=("Capture of the WPA/WPA2 handshakes for verifying passphrase. " +
"Requires cowpatty. " +
"Example : -hC capture.pcap"))
parser.add_argument(
"-qS",
"--quitonsuccess",
help=("Stop the script after successfully retrieving one pair of "
"credentials"),
action='store_true')
parser.add_argument(
"-lC",
"--lure10-capture",
help=("Capture the BSSIDs of the APs that are discovered during "
"AP selection phase. This option is part of Lure10 attack."),
action='store_true')
parser.add_argument(
<|code_end|>
with the help of current file imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
, which may contain function names, class names, or code. Output only the next line. | "-lE", |
Using the snippet: <|code_start|> "--lure10-exploit",
help=("Fool the Windows Location Service of nearby Windows users "
"to believe it is within an area that was previously captured "
"with --lure10-capture. Part of the Lure10 attack."))
parser.add_argument(
"--logging",
help="Log activity to file",
action="store_true")
parser.add_argument(
"-dK",
"--disable-karma",
help="Disables KARMA attack",
action="store_true")
parser.add_argument(
"-lP",
"--logpath",
default=None,
help="Determine the full path of the logfile.")
parser.add_argument(
"-cP",
"--credential-log-path",
help="Determine the full path of the file that will store any captured credentials",
default=None)
parser.add_argument(
"--payload-path",
help=("Payload path for scenarios serving a payload"))
parser.add_argument("-cM", "--channel-monitor",
help="Monitor if target access point changes the channel.",
action="store_true")
parser.add_argument("-wP", "--wps-pbc",
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context (class names, function names, or code) available:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | help="Monitor if the button on a WPS-PBC Registrar is pressed.", |
Given the following code snippet before the placeholder: <|code_start|> "-kN",
"--keepnetworkmanager",
action='store_true',
help=("Do not kill NetworkManager"))
parser.add_argument(
"-nE",
"--noextensions",
help=("Do not load any extensions."),
action='store_true')
parser.add_argument(
"-nD",
"--nodeauth",
help=("Skip the deauthentication phase."),
action='store_true')
parser.add_argument(
"-dC",
"--deauth-channels",
nargs="+",
type=int,
help=("Channels to deauth. " +
"Example: --deauth-channels 1,3,7"))
parser.add_argument(
"-e",
"--essid",
help=("Enter the ESSID of the rogue Access Point. " +
"This option will skip Access Point selection phase. " +
"Example: --essid 'Free WiFi'"))
parser.add_argument(
"-dE",
"--deauth-essid",
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context including class names, function names, and sometimes code from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | help=("Deauth all the BSSIDs in the WLAN with that ESSID.")) |
Next line prediction: <|code_start|> "-nD",
"--nodeauth",
help=("Skip the deauthentication phase."),
action='store_true')
parser.add_argument(
"-dC",
"--deauth-channels",
nargs="+",
type=int,
help=("Channels to deauth. " +
"Example: --deauth-channels 1,3,7"))
parser.add_argument(
"-e",
"--essid",
help=("Enter the ESSID of the rogue Access Point. " +
"This option will skip Access Point selection phase. " +
"Example: --essid 'Free WiFi'"))
parser.add_argument(
"-dE",
"--deauth-essid",
help=("Deauth all the BSSIDs in the WLAN with that ESSID."))
parser.add_argument(
"-p",
"--phishingscenario",
help=("Choose the phishing scenario to run." +
"This option will skip the scenario selection phase. " +
"Example: -p firmware_upgrade"))
parser.add_argument(
"-pK",
"--presharedkey",
<|code_end|>
. Use current file imports:
(import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC))
and context including class names, function names, or small code snippets from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | help=("Add WPA/WPA2 protection on the rogue Access Point. " + |
Using the snippet: <|code_start|> parser.add_argument(
"-nD",
"--nodeauth",
help=("Skip the deauthentication phase."),
action='store_true')
parser.add_argument(
"-dC",
"--deauth-channels",
nargs="+",
type=int,
help=("Channels to deauth. " +
"Example: --deauth-channels 1,3,7"))
parser.add_argument(
"-e",
"--essid",
help=("Enter the ESSID of the rogue Access Point. " +
"This option will skip Access Point selection phase. " +
"Example: --essid 'Free WiFi'"))
parser.add_argument(
"-dE",
"--deauth-essid",
help=("Deauth all the BSSIDs in the WLAN with that ESSID."))
parser.add_argument(
"-p",
"--phishingscenario",
help=("Choose the phishing scenario to run." +
"This option will skip the scenario selection phase. " +
"Example: -p firmware_upgrade"))
parser.add_argument(
"-pK",
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context (class names, function names, or code) available:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | "--presharedkey", |
Given snippet: <|code_start|>logger = logging.getLogger(__name__)
def parse_args():
# Create the arguments
parser = argparse.ArgumentParser()
# Interface selection
parser.add_argument(
"-i",
"--interface",
help=("Manually choose an interface that supports both AP and monitor " +
"modes for spawning the rogue AP as well as mounting additional " +
"Wi-Fi attacks from Extensions (i.e. deauth). " +
"Example: -i wlan1"))
parser.add_argument(
"-eI",
"--extensionsinterface",
help=("Manually choose an interface that supports monitor mode for " +
"deauthenticating the victims. " + "Example: -eI wlan1"))
parser.add_argument(
"-aI",
"--apinterface",
type=opmode.validate_ap_interface,
help=("Manually choose an interface that supports AP mode for " +
"spawning the rogue AP. " + "Example: -aI wlan0"))
parser.add_argument(
"-iI",
"--internetinterface",
help=("Choose an interface that is connected on the Internet" +
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
which might include code, classes, or functions. Output only the next line. | "Example: -iI ppp0")) |
Given snippet: <|code_start|> parser.add_argument(
"--logging",
help="Log activity to file",
action="store_true")
parser.add_argument(
"-dK",
"--disable-karma",
help="Disables KARMA attack",
action="store_true")
parser.add_argument(
"-lP",
"--logpath",
default=None,
help="Determine the full path of the logfile.")
parser.add_argument(
"-cP",
"--credential-log-path",
help="Determine the full path of the file that will store any captured credentials",
default=None)
parser.add_argument(
"--payload-path",
help=("Payload path for scenarios serving a payload"))
parser.add_argument("-cM", "--channel-monitor",
help="Monitor if target access point changes the channel.",
action="store_true")
parser.add_argument("-wP", "--wps-pbc",
help="Monitor if the button on a WPS-PBC Registrar is pressed.",
action="store_true")
parser.add_argument("-wAI", "--wpspbc-assoc-interface",
help="The WLAN interface used for associating to the WPS AccessPoint.",
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
which might include code, classes, or functions. Output only the next line. | ) |
Predict the next line after this snippet: <|code_start|> parser.add_argument(
"-aI",
"--apinterface",
type=opmode.validate_ap_interface,
help=("Manually choose an interface that supports AP mode for " +
"spawning the rogue AP. " + "Example: -aI wlan0"))
parser.add_argument(
"-iI",
"--internetinterface",
help=("Choose an interface that is connected on the Internet" +
"Example: -iI ppp0"))
parser.add_argument(
"-pI",
"--protectinterface",
nargs='+',
help=("Specify the interface(s) that will have their connection protected (i.e. NetworkManager will be prevented from controlling them). " +
"Example: -pI wlan1 wlan2"))
# MAC address randomization
parser.add_argument(
"-iAM",
"--mac-ap-interface",
help=("Specify the MAC address of the AP interface"))
parser.add_argument(
"-iEM",
"--mac-extensions-interface",
help=("Specify the MAC address of the extensions interface"))
parser.add_argument(
"-iNM",
"--no-mac-randomization",
<|code_end|>
using the current file's imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and any relevant context from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | help=("Do not change any MAC address"), |
Given snippet: <|code_start|> help=("Skip the deauthentication phase."),
action='store_true')
parser.add_argument(
"-dC",
"--deauth-channels",
nargs="+",
type=int,
help=("Channels to deauth. " +
"Example: --deauth-channels 1,3,7"))
parser.add_argument(
"-e",
"--essid",
help=("Enter the ESSID of the rogue Access Point. " +
"This option will skip Access Point selection phase. " +
"Example: --essid 'Free WiFi'"))
parser.add_argument(
"-dE",
"--deauth-essid",
help=("Deauth all the BSSIDs in the WLAN with that ESSID."))
parser.add_argument(
"-p",
"--phishingscenario",
help=("Choose the phishing scenario to run." +
"This option will skip the scenario selection phase. " +
"Example: -p firmware_upgrade"))
parser.add_argument(
"-pK",
"--presharedkey",
help=("Add WPA/WPA2 protection on the rogue Access Point. " +
"Example: -pK s3cr3tp4ssw0rd"))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
which might include code, classes, or functions. Output only the next line. | parser.add_argument( |
Given the following code snippet before the placeholder: <|code_start|> "--credential-log-path",
help="Determine the full path of the file that will store any captured credentials",
default=None)
parser.add_argument(
"--payload-path",
help=("Payload path for scenarios serving a payload"))
parser.add_argument("-cM", "--channel-monitor",
help="Monitor if target access point changes the channel.",
action="store_true")
parser.add_argument("-wP", "--wps-pbc",
help="Monitor if the button on a WPS-PBC Registrar is pressed.",
action="store_true")
parser.add_argument("-wAI", "--wpspbc-assoc-interface",
help="The WLAN interface used for associating to the WPS AccessPoint.",
)
parser.add_argument(
"-kB",
"--known-beacons",
help="Broadcast a number of beacon frames advertising popular WLANs",
action='store_true')
parser.add_argument(
"-fH",
"--force-hostapd",
help="Force the usage of hostapd installed in the system",
action='store_true')
parser.add_argument("-pPD",
"--phishing-pages-directory",
help="Search for phishing pages in this location")
parser.add_argument(
"--dnsmasq-conf",
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context including class names, function names, and sometimes code from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | help="Determine the full path of a custom dnmasq.conf file", |
Using the snippet: <|code_start|> "--quitonsuccess",
help=("Stop the script after successfully retrieving one pair of "
"credentials"),
action='store_true')
parser.add_argument(
"-lC",
"--lure10-capture",
help=("Capture the BSSIDs of the APs that are discovered during "
"AP selection phase. This option is part of Lure10 attack."),
action='store_true')
parser.add_argument(
"-lE",
"--lure10-exploit",
help=("Fool the Windows Location Service of nearby Windows users "
"to believe it is within an area that was previously captured "
"with --lure10-capture. Part of the Lure10 attack."))
parser.add_argument(
"--logging",
help="Log activity to file",
action="store_true")
parser.add_argument(
"-dK",
"--disable-karma",
help="Disables KARMA attack",
action="store_true")
parser.add_argument(
"-lP",
"--logpath",
default=None,
help="Determine the full path of the logfile.")
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context (class names, function names, or code) available:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | parser.add_argument( |
Using the snippet: <|code_start|>
logger = logging.getLogger(__name__)
def parse_args():
# Create the arguments
parser = argparse.ArgumentParser()
# Interface selection
parser.add_argument(
"-i",
"--interface",
help=("Manually choose an interface that supports both AP and monitor " +
"modes for spawning the rogue AP as well as mounting additional " +
"Wi-Fi attacks from Extensions (i.e. deauth). " +
"Example: -i wlan1"))
parser.add_argument(
"-eI",
"--extensionsinterface",
help=("Manually choose an interface that supports monitor mode for " +
"deauthenticating the victims. " + "Example: -eI wlan1"))
parser.add_argument(
"-aI",
"--apinterface",
type=opmode.validate_ap_interface,
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context (class names, function names, or code) available:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | help=("Manually choose an interface that supports AP mode for " + |
Given the following code snippet before the placeholder: <|code_start|> "credentials"),
action='store_true')
parser.add_argument(
"-lC",
"--lure10-capture",
help=("Capture the BSSIDs of the APs that are discovered during "
"AP selection phase. This option is part of Lure10 attack."),
action='store_true')
parser.add_argument(
"-lE",
"--lure10-exploit",
help=("Fool the Windows Location Service of nearby Windows users "
"to believe it is within an area that was previously captured "
"with --lure10-capture. Part of the Lure10 attack."))
parser.add_argument(
"--logging",
help="Log activity to file",
action="store_true")
parser.add_argument(
"-dK",
"--disable-karma",
help="Disables KARMA attack",
action="store_true")
parser.add_argument(
"-lP",
"--logpath",
default=None,
help="Determine the full path of the logfile.")
parser.add_argument(
"-cP",
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import curses
import fcntl
import logging
import logging.config
import os
import signal
import socket
import struct
import subprocess
import sys
import time
import wifiphisher.common.accesspoint as accesspoint
import wifiphisher.common.extensions as extensions
import wifiphisher.common.firewall as firewall
import wifiphisher.common.globals as universal
import wifiphisher.common.interfaces as interfaces
import wifiphisher.common.macmatcher as macmatcher
import wifiphisher.common.opmode as opmode
import wifiphisher.common.phishinghttp as phishinghttp
import wifiphisher.common.phishingpage as phishingpage
import wifiphisher.common.recon as recon
import wifiphisher.common.tui as tui
import wifiphisher.common.victim as victim
from shutil import copyfile
from subprocess import PIPE, Popen, check_output
from threading import Thread
from six.moves import range, input
from wifiphisher.common.constants import (BIRTHDAY, CHANNEL, DEAUTH_EXTENSION, DEFAULT_EXTENSIONS,
DEV, DN, G, HANDSHAKE_VALIDATE_EXTENSION,
INTERFERING_PROCS, KNOWN_BEACONS_EXTENSION,
LOGGING_CONFIG, LURE10_EXTENSION, MAC_PREFIX_FILE,
NETWORK_GW_IP, NEW_YEAR, O, PORT, R, ROGUEHOSTAPDINFO,
SSL_PORT, T, W, WEBSITE, WPSPBC)
and context including class names, function names, and sometimes code from other files:
# Path: wifiphisher/common/constants.py
# BIRTHDAY = "01-05"
#
# CHANNEL = 6
#
# DEAUTH_EXTENSION = "deauth"
#
# DEFAULT_EXTENSIONS = [DEAUTH_EXTENSION]
#
# DEV = 1
#
# DN = open(os.devnull, 'w')
#
# G = '\033[32m' # green
#
# HANDSHAKE_VALIDATE_EXTENSION = "handshakeverify"
#
# INTERFERING_PROCS = [
# "wpa_action", "wpa_supplicant", "wpa_cli", "dhclient", "ifplugd", "dhcdbd",
# "dhcpcd", "udhcpc", "avahi-autoipd", "avahi-daemon", "wlassistant",
# "wifibox", "NetworkManager", "knetworkmanager"
# ]
#
# KNOWN_BEACONS_EXTENSION = "knownbeacons"
#
# LOGGING_CONFIG = {
# 'version': 1,
# # Defined the handlers
# 'handlers': {
# 'file': {
# 'class': 'logging.handlers.RotatingFileHandler',
# 'level': LOG_LEVEL,
# 'formatter': 'detailed',
# 'filename': LOG_FILEPATH,
# 'backupCount': 3,
# },
# },
# # fomatters for the handlers
# 'formatters': {
# 'detailed': {
# 'format': '%(asctime)s - %(name) 32s - %(levelname)s - %(message)s'
# },
# },
# 'root': {
# 'level': 'DEBUG',
# 'handlers': [
# 'file',
# ],
# },
# "loggers": {},
# 'disable_existing_loggers': False
# }
#
# LURE10_EXTENSION = "lure10"
#
# MAC_PREFIX_FILE = dir_of_data + "wifiphisher-mac-prefixes"
#
# NETWORK_GW_IP = "10.0.0.1"
#
# NEW_YEAR = "01-01"
#
# O = '\033[33m' # orange
#
# PORT = 8080
#
# R = '\033[31m' # red
#
# ROGUEHOSTAPDINFO = "roguehostapdinfo"
#
# SSL_PORT = 443
#
# T = '\033[93m' # tan
#
# W = '\033[0m' # white (normal)
#
# WEBSITE = "https://wifiphisher.org"
#
# WPSPBC = "wpspbc"
. Output only the next line. | "--credential-log-path", |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.