Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
if PY3:
else:
def is_empty(v):
<|code_end|>
, predict the immediate next line with the help of imports:
from turbo.util import basestring_type, unicode_type, PY3, to_basestring
from urllib.parse import quote
from urllib import quote
and context (classes, functions, sometimes code) from other files:
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | if isinstance(v, basestring_type): |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
if PY3:
else:
def is_empty(v):
if isinstance(v, basestring_type):
if not v:
return True
if v is None:
return True
return False
def utf8(v):
<|code_end|>
with the help of current file imports:
from turbo.util import basestring_type, unicode_type, PY3, to_basestring
from urllib.parse import quote
from urllib import quote
and context from other files:
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
, which may contain function names, class names, or code. Output only the next line. | return v.encode('utf-8') if isinstance(v, unicode_type) else str(v) |
Next line prediction: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
if PY3:
else:
def is_empty(v):
if isinstance(v, basestring_type):
if not v:
return True
if v is None:
return True
return False
def utf8(v):
return v.encode('utf-8') if isinstance(v, unicode_type) else str(v)
def encode_http_params(**kw):
'''
url paremeter encode
'''
try:
_fo = lambda k, v: '{name}={value}'.format(
<|code_end|>
. Use current file imports:
(from turbo.util import basestring_type, unicode_type, PY3, to_basestring
from urllib.parse import quote
from urllib import quote)
and context including class names, function names, or small code snippets from other files:
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | name=k, value=to_basestring(quote(v))) |
Using the snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
try:
except ImportError:
try:
sha1 = hashlib.sha1
except ImportError:
sha1 = sha.new
class Session(object):
__slots__ = ['store', 'handler', 'app', '_data', '_dirty', '_config',
'_initializer', 'session_id', '_session_object', '_session_name']
def __init__(self, app, handler, store, initializer, session_config=None, session_object=None):
self.handler = handler
self.app = app
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import base64
import cPickle as pickle
import pickle
import hashlib
import sha
import redis
from copy import deepcopy
from tornado.util import ObjectDict
from turbo.conf import app_config
from turbo.log import session_log
from turbo.util import utf8, to_basestring, encodebytes, decodebytes
and context (class names, function names, or code) available:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | self.store = store or DiskStore(app_config.store_config.diskpath) |
Given the following code snippet before the placeholder: <|code_start|>
class Session(object):
__slots__ = ['store', 'handler', 'app', '_data', '_dirty', '_config',
'_initializer', 'session_id', '_session_object', '_session_name']
def __init__(self, app, handler, store, initializer, session_config=None, session_object=None):
self.handler = handler
self.app = app
self.store = store or DiskStore(app_config.store_config.diskpath)
self._config = deepcopy(app_config.session_config)
if session_config:
self._config.update(session_config)
self._session_name = self._config.name
self._session_object = (session_object or CookieObject)(
app, handler, self.store, self._config)
self._data = ObjectDict()
self._initializer = initializer
self.session_id = None
self._dirty = False
self._processor()
def __getitem__(self, name):
if name not in self._data:
<|code_end|>
, predict the next line using imports from the current file:
import os
import time
import base64
import cPickle as pickle
import pickle
import hashlib
import sha
import redis
from copy import deepcopy
from tornado.util import ObjectDict
from turbo.conf import app_config
from turbo.log import session_log
from turbo.util import utf8, to_basestring, encodebytes, decodebytes
and context including class names, function names, and sometimes code from other files:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | session_log.error('%s key not exist in %s session' % |
Continue the code snippet: <|code_start|>
class SessionObject(object):
def __init__(self, app, handler, store, session_config):
self.app = app
self.handler = handler
self.store = store
self._config = deepcopy(app_config.session_config)
if session_config:
self._config.update(session_config)
self._session_name = self._config.name
def get_session_id(self):
raise NotImplementedError
def set_session_id(self, session_id):
raise NotImplementedError
def clear_session_id(self):
raise NotImplementedError
def generate_session_id(self):
"""Generate a random id for session"""
secret_key = self._config.secret_key
while True:
rand = os.urandom(16)
now = time.time()
<|code_end|>
. Use current file imports:
import os
import time
import base64
import cPickle as pickle
import pickle
import hashlib
import sha
import redis
from copy import deepcopy
from tornado.util import ObjectDict
from turbo.conf import app_config
from turbo.log import session_log
from turbo.util import utf8, to_basestring, encodebytes, decodebytes
and context (classes, functions, or code) from other files:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | session_id = sha1(utf8("%s%s%s%s" % ( |
Here is a snippet: <|code_start|> def get_session_id(self):
return self.handler.request.headers.get(self._session_name)
def set_session_id(self, sid):
self.handler.set_header(self._session_name, sid)
def clear_session_id(self):
self.handler.clear_header(self._session_name)
class Store(object):
"""Base class for session stores"""
def __contains__(self, key):
raise NotImplementedError
def __getitem__(self, key):
raise NotImplementedError
def __setitem__(self, key, value):
raise NotImplementedError
def cleanup(self, timeout):
"""removes all the expired sessions"""
raise NotImplementedError
def encode(self, session_data):
"""encodes session dict as a string"""
pickled = pickle.dumps(session_data)
<|code_end|>
. Write the next line using the current file imports:
import os
import time
import base64
import cPickle as pickle
import pickle
import hashlib
import sha
import redis
from copy import deepcopy
from tornado.util import ObjectDict
from turbo.conf import app_config
from turbo.log import session_log
from turbo.util import utf8, to_basestring, encodebytes, decodebytes
and context from other files:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
, which may include functions, classes, or code. Output only the next line. | return to_basestring(encodebytes(pickled)) |
Using the snippet: <|code_start|> def get_session_id(self):
return self.handler.request.headers.get(self._session_name)
def set_session_id(self, sid):
self.handler.set_header(self._session_name, sid)
def clear_session_id(self):
self.handler.clear_header(self._session_name)
class Store(object):
"""Base class for session stores"""
def __contains__(self, key):
raise NotImplementedError
def __getitem__(self, key):
raise NotImplementedError
def __setitem__(self, key, value):
raise NotImplementedError
def cleanup(self, timeout):
"""removes all the expired sessions"""
raise NotImplementedError
def encode(self, session_data):
"""encodes session dict as a string"""
pickled = pickle.dumps(session_data)
<|code_end|>
, determine the next line of code. You have imports:
import os
import time
import base64
import cPickle as pickle
import pickle
import hashlib
import sha
import redis
from copy import deepcopy
from tornado.util import ObjectDict
from turbo.conf import app_config
from turbo.log import session_log
from turbo.util import utf8, to_basestring, encodebytes, decodebytes
and context (class names, function names, or code) available:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | return to_basestring(encodebytes(pickled)) |
Given the following code snippet before the placeholder: <|code_start|> self.handler.set_header(self._session_name, sid)
def clear_session_id(self):
self.handler.clear_header(self._session_name)
class Store(object):
"""Base class for session stores"""
def __contains__(self, key):
raise NotImplementedError
def __getitem__(self, key):
raise NotImplementedError
def __setitem__(self, key, value):
raise NotImplementedError
def cleanup(self, timeout):
"""removes all the expired sessions"""
raise NotImplementedError
def encode(self, session_data):
"""encodes session dict as a string"""
pickled = pickle.dumps(session_data)
return to_basestring(encodebytes(pickled))
def decode(self, session_data):
"""decodes the data to get back the session dict """
<|code_end|>
, predict the next line using imports from the current file:
import os
import time
import base64
import cPickle as pickle
import pickle
import hashlib
import sha
import redis
from copy import deepcopy
from tornado.util import ObjectDict
from turbo.conf import app_config
from turbo.log import session_log
from turbo.util import utf8, to_basestring, encodebytes, decodebytes
and context including class names, function names, and sometimes code from other files:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | pickled = decodebytes(utf8(session_data)) |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
app_config.app_name = 'app_test'
app_config.web_application_setting = {
'xsrf_cookies': False,
'cookie_secret': 'adasfd'
}
<|code_end|>
, predict the next line using imports from the current file:
import multiprocessing
import os
import signal
import requests
from bson.objectid import ObjectId
from turbo import app
from turbo import register
from turbo.conf import app_config
from turbo.util import basestring_type as basestring
from util import unittest, port_is_used, get_free_tcp_port
and context including class names, function names, and sometimes code from other files:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | class HomeHandler(app.BaseHandler): |
Given snippet: <|code_start|> def POST(self):
self._params = self.parameter
print(self._params)
assert self._params['skip'] == 0
assert self._params['limit'] == 10
self._data = {
'value': self._params['who']
}
def PUT(self):
self._data = {
'api': {
'put': 'value'
}
}
def DELETE(self):
raise Exception('value error')
def wo_json(self, data):
self.write(self.json_encode(data, indent=4))
PID = None
URL = None
def run_server(port):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import multiprocessing
import os
import signal
import requests
from bson.objectid import ObjectId
from turbo import app
from turbo import register
from turbo.conf import app_config
from turbo.util import basestring_type as basestring
from util import unittest, port_is_used, get_free_tcp_port
and context:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
which might include code, classes, or functions. Output only the next line. | register.register_url('/', HomeHandler) |
Next line prediction: <|code_start|> 'xsrf_cookies': False,
'cookie_secret': 'adasfd'
}
class HomeHandler(app.BaseHandler):
def get(self):
assert not self.is_ajax()
self.write('get')
def post(self):
self.write('post')
def put(self):
self.write('put')
class ApiHandler(app.BaseHandler):
_get_required_params = [
('skip', int, 0),
('limit', int, 20),
]
_get_params = {
'need': [
('action', None),
],
'option': [
<|code_end|>
. Use current file imports:
(import multiprocessing
import os
import signal
import requests
from bson.objectid import ObjectId
from turbo import app
from turbo import register
from turbo.conf import app_config
from turbo.util import basestring_type as basestring
from util import unittest, port_is_used, get_free_tcp_port)
and context including class names, function names, or small code snippets from other files:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | ('who', basestring, 'python'), |
Given the code snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
mutation = Mutation('flux_test')
@register(mutation)
def increase_rank(rank):
return rank + 1
@register(mutation)
def decrease_rank(rank):
return rank - 1
@register_dispatch('flux_test', 'increase_rank')
def increase(rank):
pass
def decrease(rank):
<|code_end|>
, generate the next line using the imports in this file:
from util import unittest
from turbo.flux import Mutation, register, dispatch, register_dispatch, State, state
and context (functions, classes, or occasionally code) from other files:
# Path: turbo/flux.py
# def register(state):
# def outwrapper(func):
# def wrapper(*args, **kwargs):
# def __init__(self, func):
# def __call__(self, *args, **kwargs):
# def __init__(self, file_attr):
# def __get_func(self):
# def register(self, func):
# def __getattr__(self, name):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self, file_attr):
# def __setattr__(self, name, value):
# def __getattr__(self, name):
# def _name(self):
# def dispatch(name, type_name, *args, **kwargs):
# def register_dispatch(name, type_name):
# def outwrapper(func):
# def wrapper(*args, **kwargs):
# class CallFuncAsAttr(object):
# class __CallObject(object):
# class ObjectDict(dict):
# class State(object):
# class Mutation(CallFuncAsAttr):
. Output only the next line. | return dispatch('flux_test', 'decrease_rank', rank) |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
mutation = Mutation('flux_test')
@register(mutation)
def increase_rank(rank):
return rank + 1
@register(mutation)
def decrease_rank(rank):
return rank - 1
<|code_end|>
with the help of current file imports:
from util import unittest
from turbo.flux import Mutation, register, dispatch, register_dispatch, State, state
and context from other files:
# Path: turbo/flux.py
# def register(state):
# def outwrapper(func):
# def wrapper(*args, **kwargs):
# def __init__(self, func):
# def __call__(self, *args, **kwargs):
# def __init__(self, file_attr):
# def __get_func(self):
# def register(self, func):
# def __getattr__(self, name):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self, file_attr):
# def __setattr__(self, name, value):
# def __getattr__(self, name):
# def _name(self):
# def dispatch(name, type_name, *args, **kwargs):
# def register_dispatch(name, type_name):
# def outwrapper(func):
# def wrapper(*args, **kwargs):
# class CallFuncAsAttr(object):
# class __CallObject(object):
# class ObjectDict(dict):
# class State(object):
# class Mutation(CallFuncAsAttr):
, which may contain function names, class names, or code. Output only the next line. | @register_dispatch('flux_test', 'increase_rank') |
Next line prediction: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
mutation = Mutation('flux_test')
@register(mutation)
def increase_rank(rank):
return rank + 1
@register(mutation)
def decrease_rank(rank):
return rank - 1
@register_dispatch('flux_test', 'increase_rank')
def increase(rank):
pass
def decrease(rank):
return dispatch('flux_test', 'decrease_rank', rank)
<|code_end|>
. Use current file imports:
(from util import unittest
from turbo.flux import Mutation, register, dispatch, register_dispatch, State, state)
and context including class names, function names, or small code snippets from other files:
# Path: turbo/flux.py
# def register(state):
# def outwrapper(func):
# def wrapper(*args, **kwargs):
# def __init__(self, func):
# def __call__(self, *args, **kwargs):
# def __init__(self, file_attr):
# def __get_func(self):
# def register(self, func):
# def __getattr__(self, name):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self, file_attr):
# def __setattr__(self, name, value):
# def __getattr__(self, name):
# def _name(self):
# def dispatch(name, type_name, *args, **kwargs):
# def register_dispatch(name, type_name):
# def outwrapper(func):
# def wrapper(*args, **kwargs):
# class CallFuncAsAttr(object):
# class __CallObject(object):
# class ObjectDict(dict):
# class State(object):
# class Mutation(CallFuncAsAttr):
. Output only the next line. | tstate = State('test') |
Given the following code snippet before the placeholder: <|code_start|>
@register(mutation)
def decrease_rank(rank):
return rank - 1
@register_dispatch('flux_test', 'increase_rank')
def increase(rank):
pass
def decrease(rank):
return dispatch('flux_test', 'decrease_rank', rank)
tstate = State('test')
tstate.count = 0
class FluxTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_state(self):
tstate.count += 1
self.assertEqual(tstate.count, 1)
<|code_end|>
, predict the next line using imports from the current file:
from util import unittest
from turbo.flux import Mutation, register, dispatch, register_dispatch, State, state
and context including class names, function names, and sometimes code from other files:
# Path: turbo/flux.py
# def register(state):
# def outwrapper(func):
# def wrapper(*args, **kwargs):
# def __init__(self, func):
# def __call__(self, *args, **kwargs):
# def __init__(self, file_attr):
# def __get_func(self):
# def register(self, func):
# def __getattr__(self, name):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self, file_attr):
# def __setattr__(self, name, value):
# def __getattr__(self, name):
# def _name(self):
# def dispatch(name, type_name, *args, **kwargs):
# def register_dispatch(name, type_name):
# def outwrapper(func):
# def wrapper(*args, **kwargs):
# class CallFuncAsAttr(object):
# class __CallObject(object):
# class ObjectDict(dict):
# class State(object):
# class Mutation(CallFuncAsAttr):
. Output only the next line. | self.assertEqual(state.test.count, 1) |
Given the code snippet: <|code_start|> if isinstance(v, basestring_type):
return v
if isinstance(v, dict):
return to_dict_str(v, encode)
if isinstance(v, Iterable):
return to_list_str(v, encode)
if encode:
return encode(v)
else:
return default_encode(v)
def format_time(dt):
"""datetime format
"""
return time.mktime(dt.timetuple())
def to_objectid(objid):
"""字符对象转换成objectid
"""
if objid is None:
return objid
try:
objid = ObjectId(objid)
except:
<|code_end|>
, generate the next line using the imports in this file:
import inspect
import os
import sys
import time
import json
import copy
import base64
from datetime import datetime, date
from collections import Iterable
from bson.objectid import ObjectId
from turbo.log import util_log
from base64 import decodebytes, encodebytes
from base64 import encodestring as encodebytes, decodestring as decodebytes
from turbo.model import BaseModel
and context (functions, classes, or occasionally code) from other files:
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
. Output only the next line. | util_log.error('%s is invalid objectid' % objid) |
Continue the code snippet: <|code_start|># -*- coding:utf-8 -*-
_PACKAGE_SPACE = globals()
class BaseModel(turbo.model.BaseModel):
# for import_model work
package_space = _PACKAGE_SPACE
def __init__(self, db_name='test'):
<|code_end|>
. Use current file imports:
import time
import turbo.model
from datetime import datetime
from bson.objectid import ObjectId
from pymongo import ASCENDING, DESCENDING
from .settings import MONGO_DB_MAPPING as _MONGO_DB_MAPPING
and context (classes, functions, or code) from other files:
# Path: turbo/fake/project_template/models/settings.py
# MONGO_DB_MAPPING = {
# 'db': {
# 'test': _test,
# 'user': _user,
# },
# 'db_file': {
# 'test': _test_files,
# 'user': _user_files,
# }
# }
. Output only the next line. | super(BaseModel, self).__init__(db_name, _MONGO_DB_MAPPING) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding:utf-8 -*-
from __future__ import (
absolute_import,
division,
print_function,
with_statement,
)
<|code_end|>
, predict the next line using imports from the current file:
import warnings
from bson.objectid import ObjectId
from pymongo import DESCENDING, collection
from turbo import mongo_model
from turbo.mongo_model import MixinModel # noqa E401 compatibility for turbo below 0.4.5
and context including class names, function names, and sometimes code from other files:
# Path: turbo/mongo_model.py
# def _record(x):
# def convert_to_record(func):
# def wrapper(self, *args, **kwargs):
# def utctimestamp(seconds=None):
# def timestamp():
# def datetime(dt=None):
# def utcdatetime(dt=None):
# def to_one_str(cls, value, *args, **kwargs):
# def to_str(cls, values, callback=None):
# def _wrapper_to_one_str(value):
# def default_encode(v):
# def json_encode(v):
# def json_decode(v):
# def to_objectid(objid):
# def create_objectid():
# def instance(cls, name):
# def import_model(cls, ins_name):
# def default_record():
# def collection_method_call(turbo_connect_ins, name):
# def outwrapper(func):
# def wrapper(*args, **kwargs):
# def __init__(self, model_ins, db_collect=None):
# def __getattr__(self, name):
# def __getitem__(self, name):
# def _init(self, db_name, _mongo_db_mapping):
# def _to_primary_key(self, _id):
# def __setitem__(self, k, v):
# def __getitem__(self, k):
# def __str__(self):
# def sub_collection(self, name):
# def find_by_id(self, _id, column=None):
# def remove_by_id(self, _id):
# def find_new_one(self, *args, **kwargs):
# def get_as_dict(self, condition=None, column=None, skip=0, limit=0, sort=None):
# def _valide_update_document(self, document):
# def _valid_record(self, record):
# def inc(self, spec_or_id, key, num=1):
# def put(self, value, **kwargs):
# def delete(self, _id):
# def get(self, _id):
# def read(self, _id):
# def write_action_call(self, name, *args, **kwargs):
# def read_action_call(self, name, *args, **kwargs):
# class MixinModel(object):
# class MongoTurboConnect(object):
# class AbstractModel(MixinModel):
# PRIMARY_KEY_TYPE = ObjectId
#
# Path: turbo/mongo_model.py
# class MixinModel(object):
#
# @staticmethod
# def utctimestamp(seconds=None):
# if seconds:
# return long(time.mktime(time.gmtime(seconds)))
# else:
# return long(time.mktime(time.gmtime()))
#
# @staticmethod
# def timestamp():
# return long(time.time())
#
# @staticmethod
# def datetime(dt=None):
# if dt:
# return datetime.strptime(dt, '%Y-%m-%d %H:%M')
# else:
# return datetime.now()
#
# @staticmethod
# def utcdatetime(dt=None):
# if dt:
# return datetime.strptime(dt, '%Y-%m-%d %H:%M')
# else:
# return datetime.utcnow()
#
# @classmethod
# def to_one_str(cls, value, *args, **kwargs):
# """Convert single record's values to str
# """
# if kwargs.get('wrapper'):
# return cls._wrapper_to_one_str(value)
#
# return _es.to_dict_str(value)
#
# @classmethod
# def to_str(cls, values, callback=None):
# """Convert many records's values to str
# """
# if callback and callable(callback):
# if isinstance(values, dict):
# return callback(_es.to_str(values))
#
# return [callback(_es.to_str(i)) for i in values]
# return _es.to_str(values)
#
# @staticmethod
# @convert_to_record
# def _wrapper_to_one_str(value):
# return _es.to_dict_str(value)
#
# @staticmethod
# def default_encode(v):
# return _es.default_encode(v)
#
# @staticmethod
# def json_encode(v):
# return _es.json_encode(v)
#
# @staticmethod
# def json_decode(v):
# return _es.json_decode(v)
#
# @staticmethod
# def to_objectid(objid):
# return _es.to_objectid(objid)
#
# @staticmethod
# def create_objectid():
# """Create new objectid
# """
# return ObjectId()
#
# _instance = {}
#
# @classmethod
# def instance(cls, name):
# """Instantiate a model class according to import path
# args:
# name: class import path like `user.User`
# return:
# model instance
# """
# if not cls._instance.get(name):
# model_name = name.split('.')
# ins_name = '.'.join(
# ['models', model_name[0], 'model', model_name[1]])
# cls._instance[name] = cls.import_model(ins_name)()
#
# return cls._instance[name]
#
# @classmethod
# def import_model(cls, ins_name):
# """Import model class in models package
# """
# try:
# package_space = getattr(cls, 'package_space')
# except AttributeError:
# raise ValueError('package_space not exist')
# else:
# return import_object(ins_name, package_space)
#
# @staticmethod
# def default_record():
# """Generate one default record that return empty str when key not exist
# """
# return defaultdict(lambda: '')
. Output only the next line. | class BaseBaseModel(mongo_model.AbstractModel): |
Predict the next line after this snippet: <|code_start|># -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, with_statement
class EscapeTest(unittest.TestCase):
def test_inc(self):
pass
def test_to_str(self):
data = {
'v1': 10,
'v2': datetime.datetime.now(),
'v3': ObjectId(),
'v4': 'value',
}
<|code_end|>
using the current file's imports:
import datetime
import json
from copy import deepcopy
from bson.objectid import ObjectId
from turbo.util import escape, basestring_type
from util import unittest
and any relevant context from other files:
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | self.assertTrue(isinstance(json.dumps(escape.to_str( |
Given the code snippet: <|code_start|># -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, with_statement
class EscapeTest(unittest.TestCase):
def test_inc(self):
pass
def test_to_str(self):
data = {
'v1': 10,
'v2': datetime.datetime.now(),
'v3': ObjectId(),
'v4': 'value',
}
self.assertTrue(isinstance(json.dumps(escape.to_str(
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import json
from copy import deepcopy
from bson.objectid import ObjectId
from turbo.util import escape, basestring_type
from util import unittest
and context (functions, classes, or occasionally code) from other files:
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | [deepcopy(data) for i in range(10)])), basestring_type)) |
Predict the next line after this snippet: <|code_start|># -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, with_statement
app_config.app_name = 'app_test'
app_config.web_application_setting = {
'xsrf_cookies': False,
'cookie_secret': 'asdf/asdfiw872*&^2/'
}
PORT = None
<|code_end|>
using the current file's imports:
import signal
import time
import requests
import multiprocessing
import os
from turbo import app
from turbo.conf import app_config
from turbo import register
from turbo.session import RedisStore
from util import unittest, port_is_used
and any relevant context from other files:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/session.py
# class RedisStore(Store):
#
# def __init__(self, **kwargs):
# self.timeout = kwargs.get(
# 'timeout') or app_config.session_config.timeout
#
# def __contains__(self, key):
# return self.get_connection(key).exists(key)
#
# def __setitem__(self, key, value):
# conn = self.get_connection(key)
# conn.hset(key, 'data', self.encode(value))
# conn.expire(key, self.timeout)
#
# def __getitem__(self, key):
# data = self.get_connection(key).hget(key, 'data')
# if data:
# return self.decode(data)
# else:
# return ObjectDict()
#
# def __delitem__(self, key):
# self.get_connection(key).delete(key)
#
# def cleanup(self, timeout):
# pass
#
# def get_connection(self, key):
# import redis
# return redis.Redis()
. Output only the next line. | class HomeHandler(app.BaseHandler): |
Predict the next line after this snippet: <|code_start|> 'uid': None,
}
session_store = RedisStore(timeout=3600)
def get(self):
assert self.session.uid is None
assert self.session.session_id is not None
self.write('get')
def post(self):
self.session.uid = '7787'
self.write('post')
def put(self):
assert self.session.uid == '7787'
self.write('put')
def setUpModule():
global PORT
PORT = 8888
while True:
if not port_is_used(PORT):
break
PORT += 1
def run_server():
global PORT
<|code_end|>
using the current file's imports:
import signal
import time
import requests
import multiprocessing
import os
from turbo import app
from turbo.conf import app_config
from turbo import register
from turbo.session import RedisStore
from util import unittest, port_is_used
and any relevant context from other files:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/session.py
# class RedisStore(Store):
#
# def __init__(self, **kwargs):
# self.timeout = kwargs.get(
# 'timeout') or app_config.session_config.timeout
#
# def __contains__(self, key):
# return self.get_connection(key).exists(key)
#
# def __setitem__(self, key, value):
# conn = self.get_connection(key)
# conn.hset(key, 'data', self.encode(value))
# conn.expire(key, self.timeout)
#
# def __getitem__(self, key):
# data = self.get_connection(key).hget(key, 'data')
# if data:
# return self.decode(data)
# else:
# return ObjectDict()
#
# def __delitem__(self, key):
# self.get_connection(key).delete(key)
#
# def cleanup(self, timeout):
# pass
#
# def get_connection(self, key):
# import redis
# return redis.Redis()
. Output only the next line. | register.register_url('/', HomeHandler) |
Predict the next line for this snippet: <|code_start|>
class HomeHandler(app.BaseHandler):
session_initializer = {
'time': time.time(),
'uid': None,
}
def get(self):
assert self.session.uid is None
assert self.session.session_id is not None
self.write('get')
def post(self):
self.session.uid = '7787'
self.write('post')
def put(self):
assert self.session.uid == '7787'
self.write('put')
class RedisStoreHandler(app.BaseHandler):
session_initializer = {
'time': time.time(),
'uid': None,
}
<|code_end|>
with the help of current file imports:
import signal
import time
import requests
import multiprocessing
import os
from turbo import app
from turbo.conf import app_config
from turbo import register
from turbo.session import RedisStore
from util import unittest, port_is_used
and context from other files:
# Path: turbo/app.py
# class Mixin(tornado.web.RequestHandler):
# class BaseBaseHandler(Mixin):
# class BaseHandler(BaseBaseHandler):
# class ErrorHandler(tornado.web.RequestHandler):
# def to_objectid(objid):
# def to_int(value):
# def to_float(value):
# def to_bool(value):
# def to_str(v):
# def utf8(v):
# def encode_http_params(**kw):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def is_ajax(self):
# def initialize(self):
# def session(self):
# def get_template_namespace(self):
# def render_string(self, template_name, **kwargs):
# def sort_by(self, sort):
# def get_context(self):
# def wo_json(self, data):
# def ri_json(self, data):
# def parameter(self):
# def filter_parameter(key, tp, default=None):
# def head(self, *args, **kwargs):
# def get(self, *args, **kwargs):
# def post(self, *args, **kwargs):
# def delete(self, *args, **kwargs):
# def patch(self, *args, **kwargs):
# def put(self, *args, **kwargs):
# def options(self, *args, **kwargs):
# def _method_call(self, method, *args, **kwargs):
# def init_resp(code=0, msg=None):
# def wo_resp(self, resp):
# def HEAD(self, *args, **kwargs):
# def GET(self, *args, **kwargs):
# def POST(self, *args, **kwargs):
# def DELETE(self, *args, **kwargs):
# def PATCH(self, *args, **kwargs):
# def PUT(self, *args, **kwargs):
# def OPTIONS(self, *args, **kwargs):
# def route(self, route, *args, **kwargs):
# def on_finish(self):
# def _processor(self):
# def initialize(self, status_code):
# def prepare(self):
# def start(port=8888):
#
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/register.py
# def _install_app(package_space):
# def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
# def register_url(url, handler, name=None, kwargs=None):
# def register_group_urls(prefix, urls):
#
# Path: turbo/session.py
# class RedisStore(Store):
#
# def __init__(self, **kwargs):
# self.timeout = kwargs.get(
# 'timeout') or app_config.session_config.timeout
#
# def __contains__(self, key):
# return self.get_connection(key).exists(key)
#
# def __setitem__(self, key, value):
# conn = self.get_connection(key)
# conn.hset(key, 'data', self.encode(value))
# conn.expire(key, self.timeout)
#
# def __getitem__(self, key):
# data = self.get_connection(key).hget(key, 'data')
# if data:
# return self.decode(data)
# else:
# return ObjectDict()
#
# def __delitem__(self, key):
# self.get_connection(key).delete(key)
#
# def cleanup(self, timeout):
# pass
#
# def get_connection(self, key):
# import redis
# return redis.Redis()
, which may contain function names, class names, or code. Output only the next line. | session_store = RedisStore(timeout=3600) |
Based on the snippet: <|code_start|> return
fh = logging.handlers.RotatingFileHandler(
log_path, maxBytes=log_size, backupCount=log_count)
fh.setLevel(level)
fh.setFormatter(_formatter)
logger.addHandler(fh)
def _init_stream_logger(logger, level=None):
ch = logging.StreamHandler()
ch.setLevel(level or logging.DEBUG)
ch.setFormatter(_formatter)
logger.addHandler(ch)
def _module_logger(path):
file_name = os.path.basename(path)
module_name = file_name[0:file_name.rfind('.py')]
logger_name_list = [module_name]
# find project root dir util find it or to root dir '/'
while True:
# root path check
path = os.path.dirname(path)
if path == '/':
break
# project root path
dirname = os.path.basename(path)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import logging
import logging.handlers
from turbo.conf import app_config
and context (classes, functions, sometimes code) from other files:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
. Output only the next line. | if dirname == app_config.project_name: |
Given snippet: <|code_start|> )).__name__ == 'list'
)
# error test
self.assertTrue(type(es.json_decode(
es.json_encode(es.to_str(self.values), invlaid=4)
)).__name__ == 'NoneType'
)
def test_to_list_str(self):
[self.check_value_type(v) for v in es.to_list_str(self.values)]
def test_camel_to_underscore(self):
self.assertEqual(camel_to_underscore('HelloWorld'), 'hello_world')
def check_value_type(self, v):
if isinstance(v, list):
[self.check_value_type(v1) for v1 in v]
return
if isinstance(v, dict):
[self.check_value_type(v1) for k1, v1 in v.items()]
return
self.assertTrue(self.check_base_value_type(v))
def log(self, msg):
logging.info(msg)
def check_base_value_type(self, v):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import logging
import time
from datetime import datetime
from bson.objectid import ObjectId
from turbo.util import escape as es, camel_to_underscore, basestring_type as basestring, unicode_type
from util import unittest
and context:
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
which might include code, classes, or functions. Output only the next line. | return isinstance(v, int) or isinstance(v, float) or isinstance(v, basestring) or v is None |
Predict the next line after this snippet: <|code_start|> if _mongo_db_mapping is None:
raise Exception("db mapping is invalid")
# databases
db = _mongo_db_mapping['db']
# databases file
db_file = _mongo_db_mapping['db_file']
# databse name
if db_name not in db or db.get(db_name, None) is None:
raise Exception('%s is invalid databse' % db_name)
# collection name
if not self.name:
raise Exception('%s is invalid collection name' % self.name)
# collection field
if not self.field or not isinstance(self.field, dict):
raise Exception('%s is invalid collection field' % self.field)
# collect as private variable
collect = getattr(db.get(db_name, object), self.name, None)
if collect is None:
raise Exception('%s is invalid collection' % self.name)
# replace pymongo collect with custome connect
_collect = MongoTurboConnect(self, collect)
# gridfs as private variable
_gridfs = db_file.get(db_name, None)
if _gridfs is None:
<|code_end|>
using the current file's imports:
from collections import defaultdict
from datetime import datetime
from bson.objectid import ObjectId
from turbo.log import model_log
from turbo.util import escape as _es, import_object
import functools
import time
and any relevant context from other files:
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | model_log.info('%s is invalid gridfs' % _gridfs) |
Continue the code snippet: <|code_start|> if seconds:
return long(time.mktime(time.gmtime(seconds)))
else:
return long(time.mktime(time.gmtime()))
@staticmethod
def timestamp():
return long(time.time())
@staticmethod
def datetime(dt=None):
if dt:
return datetime.strptime(dt, '%Y-%m-%d %H:%M')
else:
return datetime.now()
@staticmethod
def utcdatetime(dt=None):
if dt:
return datetime.strptime(dt, '%Y-%m-%d %H:%M')
else:
return datetime.utcnow()
@classmethod
def to_one_str(cls, value, *args, **kwargs):
"""Convert single record's values to str
"""
if kwargs.get('wrapper'):
return cls._wrapper_to_one_str(value)
<|code_end|>
. Use current file imports:
from collections import defaultdict
from datetime import datetime
from bson.objectid import ObjectId
from turbo.log import model_log
from turbo.util import escape as _es, import_object
import functools
import time
and context (classes, functions, or code) from other files:
# Path: turbo/log.py
# PY3 = sys.version_info >= (3,)
# def _init_file_logger(logger, level, log_path, log_size, log_count):
# def _init_stream_logger(logger, level=None):
# def _module_logger(path):
# def getLogger(currfile=None, level=None, log_path=None, log_size=500 * 1024 * 1024, log_count=3):
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | return _es.to_dict_str(value) |
Using the snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
def _install_app(package_space):
for app in getattr(import_object('apps.settings', package_space), 'INSTALLED_APPS'):
import_object('.'.join(['apps', app]), package_space)
def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
"""insert current project root path into sys path
"""
<|code_end|>
, determine the next line of code. You have imports:
import os
from turbo.conf import app_config
from turbo.util import get_base_dir, import_object
from turbo import log
and context (class names, function names, or code) available:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/util.py
# def get_base_dir(currfile, dir_level_num=3):
# """
# find certain path according to currfile
# """
# root_path = os.path.abspath(currfile)
# for i in range(0, dir_level_num):
# root_path = os.path.dirname(root_path)
#
# return root_path
#
# def import_object(name, package_space=None):
# if name.count('.') == 0:
# return __import__(name, package_space, None)
#
# parts = name.split('.')
# obj = __import__('.'.join(parts[:-1]),
# package_space, None, [str(parts[-1])], 0)
# try:
# return getattr(obj, parts[-1])
# except AttributeError:
# raise ImportError("No module named %s" % parts[-1])
. Output only the next line. | app_config.app_name = app_name |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, division, print_function, with_statement
def _install_app(package_space):
for app in getattr(import_object('apps.settings', package_space), 'INSTALLED_APPS'):
import_object('.'.join(['apps', app]), package_space)
def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
"""insert current project root path into sys path
"""
app_config.app_name = app_name
app_config.app_setting = app_setting
<|code_end|>
with the help of current file imports:
import os
from turbo.conf import app_config
from turbo.util import get_base_dir, import_object
from turbo import log
and context from other files:
# Path: turbo/conf.py
# class ObjectDict(dict):
# class AppConfig(object):
# def __getattr__(self, name):
# def __setattr__(self, name, value):
# def __init__(self):
# def log_level(self):
#
# Path: turbo/util.py
# def get_base_dir(currfile, dir_level_num=3):
# """
# find certain path according to currfile
# """
# root_path = os.path.abspath(currfile)
# for i in range(0, dir_level_num):
# root_path = os.path.dirname(root_path)
#
# return root_path
#
# def import_object(name, package_space=None):
# if name.count('.') == 0:
# return __import__(name, package_space, None)
#
# parts = name.split('.')
# obj = __import__('.'.join(parts[:-1]),
# package_space, None, [str(parts[-1])], 0)
# try:
# return getattr(obj, parts[-1])
# except AttributeError:
# raise ImportError("No module named %s" % parts[-1])
, which may contain function names, class names, or code. Output only the next line. | app_config.project_name = os.path.basename(get_base_dir(mainfile, 2)) |
Here is a snippet: <|code_start|># -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, with_statement
if PY3:
else:
mc = MongoClient()
<|code_end|>
. Write the next line using the current file imports:
import datetime
import json
import gridfs
from bson.objectid import ObjectId
from pymongo import MongoClient
from turbo.model import BaseModel
from turbo.util import PY3, basestring_type as basestring, utf8
from util import unittest, fake_ids, fake_ids_2
from io import StringIO
from cStringIO import StringIO
and context from other files:
# Path: turbo/model.py
# class BaseModel(BaseBaseModel):
# """Business model
# """
#
# @classmethod
# def create_model(cls, name, field=None):
# """dynamic create new model
# :args field table field, if field is None or {}, this model can not use create method
# """
# if field:
# attrs = {'name': name, 'field': field}
# else:
# attrs = {'name': name, 'field': {'_id': ObjectId()}}
#
# return type(str(name), (cls, ), attrs)()
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
, which may include functions, classes, or code. Output only the next line. | class Tag(BaseModel): |
Given the following code snippet before the placeholder: <|code_start|># -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, with_statement
if PY3:
else:
mc = MongoClient()
class Tag(BaseModel):
name = 'tag'
field = {
'list': (list, []),
'imgid': (ObjectId, None),
'uid': (ObjectId, None),
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import json
import gridfs
from bson.objectid import ObjectId
from pymongo import MongoClient
from turbo.model import BaseModel
from turbo.util import PY3, basestring_type as basestring, utf8
from util import unittest, fake_ids, fake_ids_2
from io import StringIO
from cStringIO import StringIO
and context including class names, function names, and sometimes code from other files:
# Path: turbo/model.py
# class BaseModel(BaseBaseModel):
# """Business model
# """
#
# @classmethod
# def create_model(cls, name, field=None):
# """dynamic create new model
# :args field table field, if field is None or {}, this model can not use create method
# """
# if field:
# attrs = {'name': name, 'field': field}
# else:
# attrs = {'name': name, 'field': {'_id': ObjectId()}}
#
# return type(str(name), (cls, ), attrs)()
#
# Path: turbo/util.py
# PY3 = sys.version_info >= (3,)
# _UTF8_TYPES = (bytes, type(None))
# _BASESTRING_TYPES = (basestring_type, type(None))
# def to_list_str(value, encode=None):
# def to_dict_str(origin_value, encode=None):
# def default_encode(v):
# def to_str(v, encode=None):
# def format_time(dt):
# def to_objectid(objid):
# def json_encode(data, **kwargs):
# def json_decode(data, **kwargs):
# def to_int(value, default=None):
# def to_float(value, default=None):
# def to_datetime(t, micro=False):
# def to_time(t, micro=False):
# def __init__(self, module):
# def __getattr__(self, name):
# def get_base_dir(currfile, dir_level_num=3):
# def join_sys_path(currfile, dir_level_num=3):
# def import_object(name, package_space=None):
# def camel_to_underscore(name):
# def remove_folder(path, foldername):
# def remove_file(path, filename):
# def remove_extension(path, extension):
# def build_index(model_list):
# def utf8(value):
# def to_basestring(value):
# def get_func_name(func):
# class Escape(object):
. Output only the next line. | 'name': (basestring, None), |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
if news_settings.NEWS_TAGGING:
def get_extra_class(field_name):
return ADMIN_EXTRA_CLASS.get(field_name, ADMIN_EXTRA_CLASS.get('all', ''))
class NewsAdminForm(forms.ModelForm):
class Meta:
<|code_end|>
, determine the next line of code. You have imports:
from django import forms
from easy_news.models import News
from easy_news import settings as news_settings
from easy_news.settings import ADMIN_EXTRA_CLASS
from tagging.forms import TagField
and context (class names, function names, or code) available:
# Path: easy_news/models.py
# class News(models.Model):
# class Meta:
# verbose_name = _('News')
# verbose_name_plural = _('News')
# ordering = ['-date', 'title', ]
#
# show = models.BooleanField(verbose_name=_('Published'), default=True)
# title = models.CharField(max_length=500, verbose_name=_('Title'))
# slug = models.SlugField(max_length=200, verbose_name=_('Slug'), unique_for_date='date')
# author = models.CharField(max_length=100, verbose_name=_('Author'), null=True, blank=True)
#
# date = models.DateField(verbose_name=_('Publication date'), default=timezone.now)
# creation_date = models.DateField(verbose_name=_('Creation date'), auto_now_add=True)
#
# short = models.TextField(verbose_name=_('Short description'), default='', blank=True)
# text = HTMLField(verbose_name=_('main content'), default='', blank=True)
#
# if news_settings.NEWS_TAGGING:
# from tagging import fields
# tags = fields.TagField(null=True)
#
# def month(self):
# return MONTHS[self.date.month - 1]
#
# def save(self, *args, **kwds):
# need_update = False
# if self.slug is None:
# if self.id is None:
# need_update = True
# self.slug = ''
# else:
# self.slug = self.id
# super(News, self).save(*args, **kwds)
# if need_update:
# self.slug = self.id
# super(News, self).save(force_update=True)
# save.alters_data = True
#
# def get_absolute_url(self):
# return reverse('news_detail', kwargs={
# 'year': '%04d' % self.date.year,
# 'month': '%02d' % self.date.month,
# 'day': '%02d' % self.date.day,
# 'slug': self.slug,
# })
#
# @property
# def main_content(self):
# return self.text
#
# @property
# def short_description(self):
# return self.short
#
# def __str__(self):
# return self.title
#
# Path: easy_news/settings.py
# NEWS_TAGGING = getattr(settings, 'NEWS_TAGGING', True)
# NEWS_TAGGING = getattr(settings, 'NEWS_TAGGING', False)
# NEWS_TAGGING = False
# ENABLE_NEWS_LIST = getattr(settings, 'ENABLE_NEWS_LIST', True)
# ENABLE_NEWS_ARCHIVE_INDEX = getattr(settings, 'ENABLE_NEWS_ARCHIVE_INDEX', True)
# ENABLE_NEWS_DATE_ARCHIVE = getattr(settings, 'ENABLE_NEWS_DATE_ARCHIVE', True)
# ADMIN_EXTRA_CLASS = getattr(settings, 'NEWS_ADMIN_EXTRA_CLASS', {'all': ''})
# ADMIN_EXTRA_CSS = getattr(settings, 'NEWS_ADMIN_EXTRA_CSS', {'all': ['']})
#
# Path: easy_news/settings.py
# ADMIN_EXTRA_CLASS = getattr(settings, 'NEWS_ADMIN_EXTRA_CLASS', {'all': ''})
. Output only the next line. | model = News |
Predict the next line after this snippet: <|code_start|>
try:
except ImportError:
MONTHS = [
_(' January'), _(' February'), _(' March'), _(' April'), _(' May'),
_(' June'), _(' July'), _(' August'), _(' September'), _(' October'),
_(' November'), _(' December')
]
class News(models.Model):
class Meta:
verbose_name = _('News')
verbose_name_plural = _('News')
ordering = ['-date', 'title', ]
show = models.BooleanField(verbose_name=_('Published'), default=True)
title = models.CharField(max_length=500, verbose_name=_('Title'))
slug = models.SlugField(max_length=200, verbose_name=_('Slug'), unique_for_date='date')
author = models.CharField(max_length=100, verbose_name=_('Author'), null=True, blank=True)
date = models.DateField(verbose_name=_('Publication date'), default=timezone.now)
creation_date = models.DateField(verbose_name=_('Creation date'), auto_now_add=True)
short = models.TextField(verbose_name=_('Short description'), default='', blank=True)
text = HTMLField(verbose_name=_('main content'), default='', blank=True)
<|code_end|>
using the current file's imports:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from easy_news import settings as news_settings
from django.utils import timezone
from tinymce.models import HTMLField
from django.db.models.fields import TextField as HTMLField
from tagging import fields
and any relevant context from other files:
# Path: easy_news/settings.py
# NEWS_TAGGING = getattr(settings, 'NEWS_TAGGING', True)
# NEWS_TAGGING = getattr(settings, 'NEWS_TAGGING', False)
# NEWS_TAGGING = False
# ENABLE_NEWS_LIST = getattr(settings, 'ENABLE_NEWS_LIST', True)
# ENABLE_NEWS_ARCHIVE_INDEX = getattr(settings, 'ENABLE_NEWS_ARCHIVE_INDEX', True)
# ENABLE_NEWS_DATE_ARCHIVE = getattr(settings, 'ENABLE_NEWS_DATE_ARCHIVE', True)
# ADMIN_EXTRA_CLASS = getattr(settings, 'NEWS_ADMIN_EXTRA_CLASS', {'all': ''})
# ADMIN_EXTRA_CSS = getattr(settings, 'NEWS_ADMIN_EXTRA_CSS', {'all': ['']})
. Output only the next line. | if news_settings.NEWS_TAGGING: |
Given the following code snippet before the placeholder: <|code_start|>
class Make(BaseMake):
def make(self):
super(Make, self).make()
<|code_end|>
, predict the next line using imports from the current file:
from redsolutioncms.make import BaseMake
from redsolutioncms.models import CMSSettings
from easy_news.redsolution_setup.models import EasyNewsSettings
from os.path import dirname, join
and context including class names, function names, and sometimes code from other files:
# Path: easy_news/redsolution_setup/models.py
# class EasyNewsSettings(BaseSettings):
# MENU_PROXY_LEVELS = (
# ('0', _('Show only root')),
# # ('1', _('Show only years')),
# # ('2', _('Show years and months')),
# # ('3', _('Show years, months and days')),
# ('4', _('Show years, months, days and detail list of news')),
# )
#
# menu_proxy_level = models.CharField(verbose_name=_('Menu proxy level'),
# max_length=1, choices=MENU_PROXY_LEVELS, default='0')
# list_in_root = models.BooleanField(verbose_name=_('List of news in root of menu'),
# blank=True, default=True)
#
# def show_archive(self):
# return not self.list_in_root
#
# def show_root(self):
# return int(self.menu_proxy_level) >= 0
#
# def show_years(self):
# return int(self.menu_proxy_level) >= 1
#
# def show_monthes(self):
# return int(self.menu_proxy_level) >= 2
#
# def show_days(self):
# return int(self.menu_proxy_level) >= 3
#
# def show_details(self):
# return int(self.menu_proxy_level) >= 4
#
# def show_list(self):
# return self.show_years() and not self.list_in_root
#
# objects = EasyNewsSettingsManager()
. Output only the next line. | easy_news_settings = EasyNewsSettings.objects.get_settings() |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class NewsIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
def get_model(self):
<|code_end|>
, generate the next line using the imports in this file:
from haystack import indexes
from easy_news.models import News
and context (functions, classes, or occasionally code) from other files:
# Path: easy_news/models.py
# class News(models.Model):
# class Meta:
# verbose_name = _('News')
# verbose_name_plural = _('News')
# ordering = ['-date', 'title', ]
#
# show = models.BooleanField(verbose_name=_('Published'), default=True)
# title = models.CharField(max_length=500, verbose_name=_('Title'))
# slug = models.SlugField(max_length=200, verbose_name=_('Slug'), unique_for_date='date')
# author = models.CharField(max_length=100, verbose_name=_('Author'), null=True, blank=True)
#
# date = models.DateField(verbose_name=_('Publication date'), default=timezone.now)
# creation_date = models.DateField(verbose_name=_('Creation date'), auto_now_add=True)
#
# short = models.TextField(verbose_name=_('Short description'), default='', blank=True)
# text = HTMLField(verbose_name=_('main content'), default='', blank=True)
#
# if news_settings.NEWS_TAGGING:
# from tagging import fields
# tags = fields.TagField(null=True)
#
# def month(self):
# return MONTHS[self.date.month - 1]
#
# def save(self, *args, **kwds):
# need_update = False
# if self.slug is None:
# if self.id is None:
# need_update = True
# self.slug = ''
# else:
# self.slug = self.id
# super(News, self).save(*args, **kwds)
# if need_update:
# self.slug = self.id
# super(News, self).save(force_update=True)
# save.alters_data = True
#
# def get_absolute_url(self):
# return reverse('news_detail', kwargs={
# 'year': '%04d' % self.date.year,
# 'month': '%02d' % self.date.month,
# 'day': '%02d' % self.date.day,
# 'slug': self.slug,
# })
#
# @property
# def main_content(self):
# return self.text
#
# @property
# def short_description(self):
# return self.short
#
# def __str__(self):
# return self.title
. Output only the next line. | return News |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
register = template.Library()
@register.inclusion_tag('easy_news/parts/block.html')
def show_news(num_latest=5):
<|code_end|>
. Use current file imports:
from datetime import date, timedelta, datetime
from django import template
from easy_news.models import News
and context (classes, functions, or code) from other files:
# Path: easy_news/models.py
# class News(models.Model):
# class Meta:
# verbose_name = _('News')
# verbose_name_plural = _('News')
# ordering = ['-date', 'title', ]
#
# show = models.BooleanField(verbose_name=_('Published'), default=True)
# title = models.CharField(max_length=500, verbose_name=_('Title'))
# slug = models.SlugField(max_length=200, verbose_name=_('Slug'), unique_for_date='date')
# author = models.CharField(max_length=100, verbose_name=_('Author'), null=True, blank=True)
#
# date = models.DateField(verbose_name=_('Publication date'), default=timezone.now)
# creation_date = models.DateField(verbose_name=_('Creation date'), auto_now_add=True)
#
# short = models.TextField(verbose_name=_('Short description'), default='', blank=True)
# text = HTMLField(verbose_name=_('main content'), default='', blank=True)
#
# if news_settings.NEWS_TAGGING:
# from tagging import fields
# tags = fields.TagField(null=True)
#
# def month(self):
# return MONTHS[self.date.month - 1]
#
# def save(self, *args, **kwds):
# need_update = False
# if self.slug is None:
# if self.id is None:
# need_update = True
# self.slug = ''
# else:
# self.slug = self.id
# super(News, self).save(*args, **kwds)
# if need_update:
# self.slug = self.id
# super(News, self).save(force_update=True)
# save.alters_data = True
#
# def get_absolute_url(self):
# return reverse('news_detail', kwargs={
# 'year': '%04d' % self.date.year,
# 'month': '%02d' % self.date.month,
# 'day': '%02d' % self.date.day,
# 'slug': self.slug,
# })
#
# @property
# def main_content(self):
# return self.text
#
# @property
# def short_description(self):
# return self.short
#
# def __str__(self):
# return self.title
. Output only the next line. | return {'news': News.objects.filter(show=True, date__lte=datetime.now()).order_by('-date')[:num_latest]}
|
Given snippet: <|code_start|># -*- coding: utf-8 -*-
urlpatterns = [
url(r'^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})-(?P<slug>[-\w]+)/$',
DateDetailView.as_view(queryset=News.objects.filter(show=True), date_field='date', month_format='%m', slug_field='slug'),
name='news_detail')
]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
from django.conf.urls import url
from django.views.generic.dates import *
from django.views.generic.list import ListView
from easy_news.models import News
from easy_news import settings as news_settings
from .models import News
from tagging.views import TaggedObjectList
and context:
# Path: easy_news/models.py
# class News(models.Model):
# class Meta:
# verbose_name = _('News')
# verbose_name_plural = _('News')
# ordering = ['-date', 'title', ]
#
# show = models.BooleanField(verbose_name=_('Published'), default=True)
# title = models.CharField(max_length=500, verbose_name=_('Title'))
# slug = models.SlugField(max_length=200, verbose_name=_('Slug'), unique_for_date='date')
# author = models.CharField(max_length=100, verbose_name=_('Author'), null=True, blank=True)
#
# date = models.DateField(verbose_name=_('Publication date'), default=timezone.now)
# creation_date = models.DateField(verbose_name=_('Creation date'), auto_now_add=True)
#
# short = models.TextField(verbose_name=_('Short description'), default='', blank=True)
# text = HTMLField(verbose_name=_('main content'), default='', blank=True)
#
# if news_settings.NEWS_TAGGING:
# from tagging import fields
# tags = fields.TagField(null=True)
#
# def month(self):
# return MONTHS[self.date.month - 1]
#
# def save(self, *args, **kwds):
# need_update = False
# if self.slug is None:
# if self.id is None:
# need_update = True
# self.slug = ''
# else:
# self.slug = self.id
# super(News, self).save(*args, **kwds)
# if need_update:
# self.slug = self.id
# super(News, self).save(force_update=True)
# save.alters_data = True
#
# def get_absolute_url(self):
# return reverse('news_detail', kwargs={
# 'year': '%04d' % self.date.year,
# 'month': '%02d' % self.date.month,
# 'day': '%02d' % self.date.day,
# 'slug': self.slug,
# })
#
# @property
# def main_content(self):
# return self.text
#
# @property
# def short_description(self):
# return self.short
#
# def __str__(self):
# return self.title
#
# Path: easy_news/settings.py
# NEWS_TAGGING = getattr(settings, 'NEWS_TAGGING', True)
# NEWS_TAGGING = getattr(settings, 'NEWS_TAGGING', False)
# NEWS_TAGGING = False
# ENABLE_NEWS_LIST = getattr(settings, 'ENABLE_NEWS_LIST', True)
# ENABLE_NEWS_ARCHIVE_INDEX = getattr(settings, 'ENABLE_NEWS_ARCHIVE_INDEX', True)
# ENABLE_NEWS_DATE_ARCHIVE = getattr(settings, 'ENABLE_NEWS_DATE_ARCHIVE', True)
# ADMIN_EXTRA_CLASS = getattr(settings, 'NEWS_ADMIN_EXTRA_CLASS', {'all': ''})
# ADMIN_EXTRA_CSS = getattr(settings, 'NEWS_ADMIN_EXTRA_CSS', {'all': ['']})
which might include code, classes, or functions. Output only the next line. | if news_settings.ENABLE_NEWS_LIST: |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@admin.register(News)
class NewsAdmin(admin.ModelAdmin):
# @property
# def media(self):
# media = super(NewsAdmin, self).media
# media.add_css(news_settings.ADMIN_EXTRA_CSS)
# return media
list_filter = ['show']
search_fields = ['title', 'short', 'text', 'author']
list_display = ['title', 'date', 'show', 'author']
prepopulated_fields = {'slug': ('title',)}
model = News
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from .models import News
from .forms import NewsAdminForm
from easy_news import settings as news_settings
and context (class names, function names, or code) available:
# Path: easy_news/models.py
# class News(models.Model):
# class Meta:
# verbose_name = _('News')
# verbose_name_plural = _('News')
# ordering = ['-date', 'title', ]
#
# show = models.BooleanField(verbose_name=_('Published'), default=True)
# title = models.CharField(max_length=500, verbose_name=_('Title'))
# slug = models.SlugField(max_length=200, verbose_name=_('Slug'), unique_for_date='date')
# author = models.CharField(max_length=100, verbose_name=_('Author'), null=True, blank=True)
#
# date = models.DateField(verbose_name=_('Publication date'), default=timezone.now)
# creation_date = models.DateField(verbose_name=_('Creation date'), auto_now_add=True)
#
# short = models.TextField(verbose_name=_('Short description'), default='', blank=True)
# text = HTMLField(verbose_name=_('main content'), default='', blank=True)
#
# if news_settings.NEWS_TAGGING:
# from tagging import fields
# tags = fields.TagField(null=True)
#
# def month(self):
# return MONTHS[self.date.month - 1]
#
# def save(self, *args, **kwds):
# need_update = False
# if self.slug is None:
# if self.id is None:
# need_update = True
# self.slug = ''
# else:
# self.slug = self.id
# super(News, self).save(*args, **kwds)
# if need_update:
# self.slug = self.id
# super(News, self).save(force_update=True)
# save.alters_data = True
#
# def get_absolute_url(self):
# return reverse('news_detail', kwargs={
# 'year': '%04d' % self.date.year,
# 'month': '%02d' % self.date.month,
# 'day': '%02d' % self.date.day,
# 'slug': self.slug,
# })
#
# @property
# def main_content(self):
# return self.text
#
# @property
# def short_description(self):
# return self.short
#
# def __str__(self):
# return self.title
#
# Path: easy_news/forms.py
# class NewsAdminForm(forms.ModelForm):
#
# class Meta:
# model = News
# fields = '__all__'
# widgets = {
# 'title': forms.TextInput(attrs={'class': get_extra_class('title')}),
# 'author': forms.TextInput(attrs={'class': get_extra_class('author')}),
# 'short': forms.Textarea(attrs={'class': get_extra_class('short')}),
# 'slug': forms.TextInput(attrs={'class': get_extra_class('slug')})
# }
#
# if news_settings.NEWS_TAGGING:
# tags = TagField(required=False)
#
# Path: easy_news/settings.py
# NEWS_TAGGING = getattr(settings, 'NEWS_TAGGING', True)
# NEWS_TAGGING = getattr(settings, 'NEWS_TAGGING', False)
# NEWS_TAGGING = False
# ENABLE_NEWS_LIST = getattr(settings, 'ENABLE_NEWS_LIST', True)
# ENABLE_NEWS_ARCHIVE_INDEX = getattr(settings, 'ENABLE_NEWS_ARCHIVE_INDEX', True)
# ENABLE_NEWS_DATE_ARCHIVE = getattr(settings, 'ENABLE_NEWS_DATE_ARCHIVE', True)
# ADMIN_EXTRA_CLASS = getattr(settings, 'NEWS_ADMIN_EXTRA_CLASS', {'all': ''})
# ADMIN_EXTRA_CSS = getattr(settings, 'NEWS_ADMIN_EXTRA_CSS', {'all': ['']})
. Output only the next line. | form = NewsAdminForm |
Here is a snippet: <|code_start|>
class TestDatasetProvider(object):
@pytest.fixture
def dataset_provider(self):
<|code_end|>
. Write the next line using the current file imports:
import pytest
from itertools import islice
from operator import attrgetter
from types import GeneratorType
from .dataset_providers import DatasetProvider
and context from other files:
# Path: keras_image_captioning/dataset_providers.py
# class DatasetProvider(object):
# """Acts as an adapter of `Dataset` for Keras' `fit_generator` method."""
# def __init__(self,
# batch_size=None,
# dataset=None,
# image_preprocessor=None,
# caption_preprocessor=None,
# single_caption=False):
# """
# If an arg is None, it will get its value from config.active_config.
# """
# self._batch_size = batch_size or active_config().batch_size
# self._dataset = (dataset or
# get_dataset_instance(single_caption=single_caption))
# self._image_preprocessor = image_preprocessor or ImagePreprocessor()
# self._caption_preprocessor = (caption_preprocessor or
# CaptionPreprocessor())
# self._single_caption = single_caption
# self._build()
#
# @property
# def vocabs(self):
# return self._caption_preprocessor.vocabs
#
# @property
# def vocab_size(self):
# return self._caption_preprocessor.vocab_size
#
# @property
# def training_steps(self):
# return int(ceil(1. * self._dataset.training_set_size /
# self._batch_size))
#
# @property
# def validation_steps(self):
# return int(ceil(1. * self._dataset.validation_set_size /
# self._batch_size))
#
# @property
# def test_steps(self):
# return int(ceil(1. * self._dataset.test_set_size /
# self._batch_size))
#
# @property
# def training_results_dir(self):
# return self._dataset.training_results_dir
#
# @property
# def caption_preprocessor(self):
# return self._caption_preprocessor
#
# def training_set(self, include_datum=False):
# for batch in self._batch_generator(self._dataset.training_set,
# include_datum,
# random_transform=True):
# yield batch
#
# def validation_set(self, include_datum=False):
# for batch in self._batch_generator(self._dataset.validation_set,
# include_datum,
# random_transform=False):
# yield batch
#
# def test_set(self, include_datum=False):
# for batch in self._batch_generator(self._dataset.test_set,
# include_datum,
# random_transform=False):
# yield batch
#
# def _build(self):
# training_set = self._dataset.training_set
# if self._single_caption:
# training_captions = map(attrgetter('all_captions_txt'),
# training_set)
# training_captions = flatten_list_2d(training_captions)
# else:
# training_captions = map(attrgetter('caption_txt'), training_set)
# self._caption_preprocessor.fit_on_captions(training_captions)
#
# def _batch_generator(self, datum_list, include_datum=False,
# random_transform=True):
# # TODO Make it thread-safe. Currently only suitable for workers=1 in
# # fit_generator.
# datum_list = copy(datum_list)
# while True:
# np.random.shuffle(datum_list)
# datum_batch = []
# for datum in datum_list:
# datum_batch.append(datum)
# if len(datum_batch) >= self._batch_size:
# yield self._preprocess_batch(datum_batch, include_datum,
# random_transform)
# datum_batch = []
# if datum_batch:
# yield self._preprocess_batch(datum_batch, include_datum,
# random_transform)
#
# def _preprocess_batch(self, datum_batch, include_datum=False,
# random_transform=True):
# imgs_path = map(attrgetter('img_path'), datum_batch)
# captions_txt = map(attrgetter('caption_txt'), datum_batch)
#
# img_batch = self._image_preprocessor.preprocess_images(imgs_path,
# random_transform)
# caption_batch = self._caption_preprocessor.encode_captions(captions_txt)
#
# imgs_input = self._image_preprocessor.preprocess_batch(img_batch)
# captions = self._caption_preprocessor.preprocess_batch(caption_batch)
#
# captions_input, captions_output = captions
# X, y = [imgs_input, captions_input], captions_output
#
# if include_datum:
# return X, y, datum_batch
# else:
# return X, y
, which may include functions, classes, or code. Output only the next line. | return DatasetProvider(batch_size=4) |
Using the snippet: <|code_start|>
class Embed300FineRandomConfigBuilder(Embed300RandomConfigBuilder):
def __init__(self, fixed_config_keys):
super(Embed300FineRandomConfigBuilder, self).__init__(
fixed_config_keys)
self._reduce_lr_factor = lambda: uniform(0.1, 0.9)
self._reduce_lr_patience = lambda: 4
self._lemmatize_caption = lambda: False
# Values below are from an analysis of hpsearch/16
self._word_vector_init = lambda: 'glove'
self._rnn_layers = lambda: randint(2, 3)
self._learning_rate = lambda: 10 ** uniform(-4, -2.7)
self._dropout_rate = lambda: uniform(0.2, 0.5)
class FileConfigBuilder(ConfigBuilderBase):
def __init__(self, yaml_path):
self._yaml_path = yaml_path
def build_config(self):
with open(self._yaml_path) as yaml_file:
config_dict = yaml.load(yaml_file)
# For backward compatibility
for field in Config._fields:
config_dict.setdefault(field, None)
<|code_end|>
, determine the next line of code. You have imports:
import itertools
import yaml
import sys
from collections import OrderedDict, namedtuple
from datetime import timedelta
from random import choice, randint, uniform
from .common_utils import parse_timedelta
from .io_utils import write_yaml_file
and context (class names, function names, or code) available:
# Path: keras_image_captioning/common_utils.py
# def parse_timedelta(timedelta_str):
# if isinstance(timedelta_str, timedelta):
# return timedelta_str
# if not timedelta_str or timedelta_str == 'null':
# return None
#
# tokens = re.split(r' days?,? ', timedelta_str)
# if len(tokens) == 1:
# if tokens[0].find('day') == -1:
# days = '0'
# rest = tokens[0]
# else:
# days = tokens[0].split(' ')[0]
# rest = '00:00:00'
# else:
# days, rest = tokens
#
# days = int(days)
# hours, minutes, seconds = map(int, rest.split(':'))
# return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
#
# Path: keras_image_captioning/io_utils.py
# def write_yaml_file(obj, path):
# with open(path, 'w') as f:
# yaml.dump(obj, f, default_flow_style=False)
. Output only the next line. | config_dict['time_limit'] = parse_timedelta(config_dict['time_limit']) |
Given snippet: <|code_start|> config_dict = yaml.load(yaml_file)
# For backward compatibility
for field in Config._fields:
config_dict.setdefault(field, None)
config_dict['time_limit'] = parse_timedelta(config_dict['time_limit'])
return Config(**config_dict)
_active_config = VinyalsConfigBuilder().build_config()
def active_config(new_active_config=None):
if new_active_config:
global _active_config
_active_config = new_active_config
return _active_config
def init_vocab_size(vocab_size):
global _active_config
_active_config = _active_config._replace(vocab_size=vocab_size)
def write_to_file(config, yaml_path):
config_dict = dict(config._asdict())
time_limit = config_dict['time_limit']
if time_limit:
config_dict['time_limit'] = str(time_limit)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import itertools
import yaml
import sys
from collections import OrderedDict, namedtuple
from datetime import timedelta
from random import choice, randint, uniform
from .common_utils import parse_timedelta
from .io_utils import write_yaml_file
and context:
# Path: keras_image_captioning/common_utils.py
# def parse_timedelta(timedelta_str):
# if isinstance(timedelta_str, timedelta):
# return timedelta_str
# if not timedelta_str or timedelta_str == 'null':
# return None
#
# tokens = re.split(r' days?,? ', timedelta_str)
# if len(tokens) == 1:
# if tokens[0].find('day') == -1:
# days = '0'
# rest = tokens[0]
# else:
# days = tokens[0].split(' ')[0]
# rest = '00:00:00'
# else:
# days, rest = tokens
#
# days = int(days)
# hours, minutes, seconds = map(int, rest.split(':'))
# return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
#
# Path: keras_image_captioning/io_utils.py
# def write_yaml_file(obj, path):
# with open(path, 'w') as f:
# yaml.dump(obj, f, default_flow_style=False)
which might include code, classes, or functions. Output only the next line. | write_yaml_file(config_dict, yaml_path) |
Based on the snippet: <|code_start|>
@pytest.fixture
def session():
return tf.Session()
def test_categorical_crossentropy_from_logits(session):
batch, timestep, vocab_size = 8, 4, 2
shape = (batch, timestep, vocab_size)
# tf.random_normal is not used because every executing Session.run,
# the value changes.
y_true = tf.constant(np.random.normal(size=shape))
y_pred = tf.constant(np.random.normal(size=shape))
# Confirm the shape
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import pytest
import tensorflow as tf
from .losses import categorical_crossentropy_from_logits
and context (classes, functions, sometimes code) from other files:
# Path: keras_image_captioning/losses.py
# def categorical_crossentropy_from_logits(y_true, y_pred):
# # Discarding is still needed although CaptionPreprocessor.preprocess_batch
# # has added dummy words as all-zeros arrays because the sum of losses is
# # the same but the mean of losses is different.
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# loss = tf.nn.softmax_cross_entropy_with_logits(labels=y_true,
# logits=y_pred)
# return loss
. Output only the next line. | result = categorical_crossentropy_from_logits(y_true, y_pred) |
Predict the next line after this snippet: <|code_start|>
class HyperparamSearch(object):
"""Spawns and schedules training scripts."""
def __init__(self,
training_label_prefix,
dataset_name=None,
epochs=None,
time_limit=None,
num_gpus=None):
if not ((epochs is None) ^ (time_limit is None)):
raise ValueError('epochs or time_limit must present, '
'but not both!')
self._training_label_prefix = training_label_prefix
<|code_end|>
using the current file's imports:
import fire
import itertools
import os
import signal
import sh
import sys
import traceback
from concurrent.futures import ThreadPoolExecutor
from random import uniform
from threading import Lock, Semaphore
from time import sleep
from tempfile import gettempdir, NamedTemporaryFile
from .config import (active_config, write_to_file,
Embed300FineRandomConfigBuilder)
from .common_utils import parse_timedelta
from .datasets import get_dataset_instance
from .io_utils import mkdir_p, logging
and any relevant context from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# def write_to_file(config, yaml_path):
# config_dict = dict(config._asdict())
# time_limit = config_dict['time_limit']
# if time_limit:
# config_dict['time_limit'] = str(time_limit)
# write_yaml_file(config_dict, yaml_path)
#
# class Embed300FineRandomConfigBuilder(Embed300RandomConfigBuilder):
# def __init__(self, fixed_config_keys):
# super(Embed300FineRandomConfigBuilder, self).__init__(
# fixed_config_keys)
#
# self._reduce_lr_factor = lambda: uniform(0.1, 0.9)
# self._reduce_lr_patience = lambda: 4
# self._lemmatize_caption = lambda: False
#
# # Values below are from an analysis of hpsearch/16
# self._word_vector_init = lambda: 'glove'
# self._rnn_layers = lambda: randint(2, 3)
# self._learning_rate = lambda: 10 ** uniform(-4, -2.7)
# self._dropout_rate = lambda: uniform(0.2, 0.5)
#
# Path: keras_image_captioning/common_utils.py
# def parse_timedelta(timedelta_str):
# if isinstance(timedelta_str, timedelta):
# return timedelta_str
# if not timedelta_str or timedelta_str == 'null':
# return None
#
# tokens = re.split(r' days?,? ', timedelta_str)
# if len(tokens) == 1:
# if tokens[0].find('day') == -1:
# days = '0'
# rest = tokens[0]
# else:
# days = tokens[0].split(' ')[0]
# rest = '00:00:00'
# else:
# days, rest = tokens
#
# days = int(days)
# hours, minutes, seconds = map(int, rest.split(':'))
# return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
#
# Path: keras_image_captioning/datasets.py
# def get_dataset_instance(dataset_name=None, lemmatize_caption=None,
# single_caption=False):
# """
# If an arg is None, it will get its value from config.active_config.
# """
# dataset_name = dataset_name or active_config().dataset_name
# lemmatize_caption = lemmatize_caption or active_config().lemmatize_caption
#
# for dataset_class in [Flickr8kDataset]:
# if dataset_class.DATASET_NAME == dataset_name:
# return dataset_class(lemmatize_caption=lemmatize_caption,
# single_caption=single_caption)
#
# raise ValueError('Cannot find {} dataset!'.format(dataset_name))
#
# Path: keras_image_captioning/io_utils.py
# def mkdir_p(path):
# try:
# os.makedirs(path)
# except OSError as exc:
# if exc.errno == errno.EEXIST and os.path.isdir(path):
# pass
# else:
# raise
#
# def logging(*args, **kwargs):
# utc_now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
# print(utc_now, '|', *args, **kwargs)
# sys.stdout.flush()
. Output only the next line. | self._dataset_name = dataset_name or active_config().dataset_name |
Given the code snippet: <|code_start|> def config(self):
return self._config
@property
def gpu_index(self):
return self._gpu_index
@property
def config_filepath(self):
return self._config_filepath
def execute(self):
"""Execute the training."""
env = os.environ.copy()
env['CUDA_VISIBLE_DEVICES'] = str(self.gpu_index)
return self.COMMAND(training_label=self.training_label,
config_file=self.config_filepath,
_env=env,
_out=self._log_filepath,
_err_to_out=True,
_bg=self._background,
_done=self._done_callback)
def _init_config_filepath(self):
tmp_dir = os.path.join(gettempdir(), 'keras_image_captioning')
mkdir_p(tmp_dir)
config_file = NamedTemporaryFile(suffix='.yaml', dir=tmp_dir,
delete=False)
config_file.close()
self._config_filepath = config_file.name
<|code_end|>
, generate the next line using the imports in this file:
import fire
import itertools
import os
import signal
import sh
import sys
import traceback
from concurrent.futures import ThreadPoolExecutor
from random import uniform
from threading import Lock, Semaphore
from time import sleep
from tempfile import gettempdir, NamedTemporaryFile
from .config import (active_config, write_to_file,
Embed300FineRandomConfigBuilder)
from .common_utils import parse_timedelta
from .datasets import get_dataset_instance
from .io_utils import mkdir_p, logging
and context (functions, classes, or occasionally code) from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# def write_to_file(config, yaml_path):
# config_dict = dict(config._asdict())
# time_limit = config_dict['time_limit']
# if time_limit:
# config_dict['time_limit'] = str(time_limit)
# write_yaml_file(config_dict, yaml_path)
#
# class Embed300FineRandomConfigBuilder(Embed300RandomConfigBuilder):
# def __init__(self, fixed_config_keys):
# super(Embed300FineRandomConfigBuilder, self).__init__(
# fixed_config_keys)
#
# self._reduce_lr_factor = lambda: uniform(0.1, 0.9)
# self._reduce_lr_patience = lambda: 4
# self._lemmatize_caption = lambda: False
#
# # Values below are from an analysis of hpsearch/16
# self._word_vector_init = lambda: 'glove'
# self._rnn_layers = lambda: randint(2, 3)
# self._learning_rate = lambda: 10 ** uniform(-4, -2.7)
# self._dropout_rate = lambda: uniform(0.2, 0.5)
#
# Path: keras_image_captioning/common_utils.py
# def parse_timedelta(timedelta_str):
# if isinstance(timedelta_str, timedelta):
# return timedelta_str
# if not timedelta_str or timedelta_str == 'null':
# return None
#
# tokens = re.split(r' days?,? ', timedelta_str)
# if len(tokens) == 1:
# if tokens[0].find('day') == -1:
# days = '0'
# rest = tokens[0]
# else:
# days = tokens[0].split(' ')[0]
# rest = '00:00:00'
# else:
# days, rest = tokens
#
# days = int(days)
# hours, minutes, seconds = map(int, rest.split(':'))
# return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
#
# Path: keras_image_captioning/datasets.py
# def get_dataset_instance(dataset_name=None, lemmatize_caption=None,
# single_caption=False):
# """
# If an arg is None, it will get its value from config.active_config.
# """
# dataset_name = dataset_name or active_config().dataset_name
# lemmatize_caption = lemmatize_caption or active_config().lemmatize_caption
#
# for dataset_class in [Flickr8kDataset]:
# if dataset_class.DATASET_NAME == dataset_name:
# return dataset_class(lemmatize_caption=lemmatize_caption,
# single_caption=single_caption)
#
# raise ValueError('Cannot find {} dataset!'.format(dataset_name))
#
# Path: keras_image_captioning/io_utils.py
# def mkdir_p(path):
# try:
# os.makedirs(path)
# except OSError as exc:
# if exc.errno == errno.EEXIST and os.path.isdir(path):
# pass
# else:
# raise
#
# def logging(*args, **kwargs):
# utc_now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
# print(utc_now, '|', *args, **kwargs)
# sys.stdout.flush()
. Output only the next line. | write_to_file(self._config, self._config_filepath) |
Predict the next line after this snippet: <|code_start|>
class HyperparamSearch(object):
"""Spawns and schedules training scripts."""
def __init__(self,
training_label_prefix,
dataset_name=None,
epochs=None,
time_limit=None,
num_gpus=None):
if not ((epochs is None) ^ (time_limit is None)):
raise ValueError('epochs or time_limit must present, '
'but not both!')
self._training_label_prefix = training_label_prefix
self._dataset_name = dataset_name or active_config().dataset_name
self._validate_training_label_prefix()
self._epochs = epochs
self._time_limit = time_limit
fixed_config_keys = dict(dataset_name=self._dataset_name,
epochs=self._epochs,
time_limit=self._time_limit)
<|code_end|>
using the current file's imports:
import fire
import itertools
import os
import signal
import sh
import sys
import traceback
from concurrent.futures import ThreadPoolExecutor
from random import uniform
from threading import Lock, Semaphore
from time import sleep
from tempfile import gettempdir, NamedTemporaryFile
from .config import (active_config, write_to_file,
Embed300FineRandomConfigBuilder)
from .common_utils import parse_timedelta
from .datasets import get_dataset_instance
from .io_utils import mkdir_p, logging
and any relevant context from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# def write_to_file(config, yaml_path):
# config_dict = dict(config._asdict())
# time_limit = config_dict['time_limit']
# if time_limit:
# config_dict['time_limit'] = str(time_limit)
# write_yaml_file(config_dict, yaml_path)
#
# class Embed300FineRandomConfigBuilder(Embed300RandomConfigBuilder):
# def __init__(self, fixed_config_keys):
# super(Embed300FineRandomConfigBuilder, self).__init__(
# fixed_config_keys)
#
# self._reduce_lr_factor = lambda: uniform(0.1, 0.9)
# self._reduce_lr_patience = lambda: 4
# self._lemmatize_caption = lambda: False
#
# # Values below are from an analysis of hpsearch/16
# self._word_vector_init = lambda: 'glove'
# self._rnn_layers = lambda: randint(2, 3)
# self._learning_rate = lambda: 10 ** uniform(-4, -2.7)
# self._dropout_rate = lambda: uniform(0.2, 0.5)
#
# Path: keras_image_captioning/common_utils.py
# def parse_timedelta(timedelta_str):
# if isinstance(timedelta_str, timedelta):
# return timedelta_str
# if not timedelta_str or timedelta_str == 'null':
# return None
#
# tokens = re.split(r' days?,? ', timedelta_str)
# if len(tokens) == 1:
# if tokens[0].find('day') == -1:
# days = '0'
# rest = tokens[0]
# else:
# days = tokens[0].split(' ')[0]
# rest = '00:00:00'
# else:
# days, rest = tokens
#
# days = int(days)
# hours, minutes, seconds = map(int, rest.split(':'))
# return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
#
# Path: keras_image_captioning/datasets.py
# def get_dataset_instance(dataset_name=None, lemmatize_caption=None,
# single_caption=False):
# """
# If an arg is None, it will get its value from config.active_config.
# """
# dataset_name = dataset_name or active_config().dataset_name
# lemmatize_caption = lemmatize_caption or active_config().lemmatize_caption
#
# for dataset_class in [Flickr8kDataset]:
# if dataset_class.DATASET_NAME == dataset_name:
# return dataset_class(lemmatize_caption=lemmatize_caption,
# single_caption=single_caption)
#
# raise ValueError('Cannot find {} dataset!'.format(dataset_name))
#
# Path: keras_image_captioning/io_utils.py
# def mkdir_p(path):
# try:
# os.makedirs(path)
# except OSError as exc:
# if exc.errno == errno.EEXIST and os.path.isdir(path):
# pass
# else:
# raise
#
# def logging(*args, **kwargs):
# utc_now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
# print(utc_now, '|', *args, **kwargs)
# sys.stdout.flush()
. Output only the next line. | self._config_builder = Embed300FineRandomConfigBuilder( |
Using the snippet: <|code_start|> _out=self._log_filepath,
_err_to_out=True,
_bg=self._background,
_done=self._done_callback)
def _init_config_filepath(self):
tmp_dir = os.path.join(gettempdir(), 'keras_image_captioning')
mkdir_p(tmp_dir)
config_file = NamedTemporaryFile(suffix='.yaml', dir=tmp_dir,
delete=False)
config_file.close()
self._config_filepath = config_file.name
write_to_file(self._config, self._config_filepath)
def _init_log_filepath(self):
LOG_FILENAME = 'training-log.txt'
dataset = get_dataset_instance(self._config.dataset_name,
self._config.lemmatize_caption)
result_dir = os.path.join(dataset.training_results_dir,
self._training_label)
mkdir_p(result_dir)
self._log_filepath = os.path.join(result_dir, LOG_FILENAME)
def main(training_label_prefix,
dataset_name=None,
epochs=None,
time_limit=None,
num_gpus=None):
epochs = int(epochs) if epochs else None
<|code_end|>
, determine the next line of code. You have imports:
import fire
import itertools
import os
import signal
import sh
import sys
import traceback
from concurrent.futures import ThreadPoolExecutor
from random import uniform
from threading import Lock, Semaphore
from time import sleep
from tempfile import gettempdir, NamedTemporaryFile
from .config import (active_config, write_to_file,
Embed300FineRandomConfigBuilder)
from .common_utils import parse_timedelta
from .datasets import get_dataset_instance
from .io_utils import mkdir_p, logging
and context (class names, function names, or code) available:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# def write_to_file(config, yaml_path):
# config_dict = dict(config._asdict())
# time_limit = config_dict['time_limit']
# if time_limit:
# config_dict['time_limit'] = str(time_limit)
# write_yaml_file(config_dict, yaml_path)
#
# class Embed300FineRandomConfigBuilder(Embed300RandomConfigBuilder):
# def __init__(self, fixed_config_keys):
# super(Embed300FineRandomConfigBuilder, self).__init__(
# fixed_config_keys)
#
# self._reduce_lr_factor = lambda: uniform(0.1, 0.9)
# self._reduce_lr_patience = lambda: 4
# self._lemmatize_caption = lambda: False
#
# # Values below are from an analysis of hpsearch/16
# self._word_vector_init = lambda: 'glove'
# self._rnn_layers = lambda: randint(2, 3)
# self._learning_rate = lambda: 10 ** uniform(-4, -2.7)
# self._dropout_rate = lambda: uniform(0.2, 0.5)
#
# Path: keras_image_captioning/common_utils.py
# def parse_timedelta(timedelta_str):
# if isinstance(timedelta_str, timedelta):
# return timedelta_str
# if not timedelta_str or timedelta_str == 'null':
# return None
#
# tokens = re.split(r' days?,? ', timedelta_str)
# if len(tokens) == 1:
# if tokens[0].find('day') == -1:
# days = '0'
# rest = tokens[0]
# else:
# days = tokens[0].split(' ')[0]
# rest = '00:00:00'
# else:
# days, rest = tokens
#
# days = int(days)
# hours, minutes, seconds = map(int, rest.split(':'))
# return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
#
# Path: keras_image_captioning/datasets.py
# def get_dataset_instance(dataset_name=None, lemmatize_caption=None,
# single_caption=False):
# """
# If an arg is None, it will get its value from config.active_config.
# """
# dataset_name = dataset_name or active_config().dataset_name
# lemmatize_caption = lemmatize_caption or active_config().lemmatize_caption
#
# for dataset_class in [Flickr8kDataset]:
# if dataset_class.DATASET_NAME == dataset_name:
# return dataset_class(lemmatize_caption=lemmatize_caption,
# single_caption=single_caption)
#
# raise ValueError('Cannot find {} dataset!'.format(dataset_name))
#
# Path: keras_image_captioning/io_utils.py
# def mkdir_p(path):
# try:
# os.makedirs(path)
# except OSError as exc:
# if exc.errno == errno.EEXIST and os.path.isdir(path):
# pass
# else:
# raise
#
# def logging(*args, **kwargs):
# utc_now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
# print(utc_now, '|', *args, **kwargs)
# sys.stdout.flush()
. Output only the next line. | time_limit = parse_timedelta(time_limit) if time_limit else None |
Given snippet: <|code_start|>
with self.lock:
if self._stop_search:
break
training_label = self.training_label(search_index)
config = self._config_builder.build_config()
gpu_index = self._available_gpus.pop()
done_callback = self._create_done_callback(gpu_index)
command = TrainingCommand(training_label=training_label,
config=config,
gpu_index=gpu_index,
background=True,
done_callback=done_callback)
self.running_commands.append((search_index, command.execute()))
logging('Running training {}..'.format(training_label))
self._remove_finished_commands()
self._wait_running_commands()
def stop(self):
"""Stop the hyperparameter search."""
self._stop_search = True
def training_label(self, search_index):
return '{}/{:04d}'.format(self.training_label_prefix, search_index)
def _validate_training_label_prefix(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import fire
import itertools
import os
import signal
import sh
import sys
import traceback
from concurrent.futures import ThreadPoolExecutor
from random import uniform
from threading import Lock, Semaphore
from time import sleep
from tempfile import gettempdir, NamedTemporaryFile
from .config import (active_config, write_to_file,
Embed300FineRandomConfigBuilder)
from .common_utils import parse_timedelta
from .datasets import get_dataset_instance
from .io_utils import mkdir_p, logging
and context:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# def write_to_file(config, yaml_path):
# config_dict = dict(config._asdict())
# time_limit = config_dict['time_limit']
# if time_limit:
# config_dict['time_limit'] = str(time_limit)
# write_yaml_file(config_dict, yaml_path)
#
# class Embed300FineRandomConfigBuilder(Embed300RandomConfigBuilder):
# def __init__(self, fixed_config_keys):
# super(Embed300FineRandomConfigBuilder, self).__init__(
# fixed_config_keys)
#
# self._reduce_lr_factor = lambda: uniform(0.1, 0.9)
# self._reduce_lr_patience = lambda: 4
# self._lemmatize_caption = lambda: False
#
# # Values below are from an analysis of hpsearch/16
# self._word_vector_init = lambda: 'glove'
# self._rnn_layers = lambda: randint(2, 3)
# self._learning_rate = lambda: 10 ** uniform(-4, -2.7)
# self._dropout_rate = lambda: uniform(0.2, 0.5)
#
# Path: keras_image_captioning/common_utils.py
# def parse_timedelta(timedelta_str):
# if isinstance(timedelta_str, timedelta):
# return timedelta_str
# if not timedelta_str or timedelta_str == 'null':
# return None
#
# tokens = re.split(r' days?,? ', timedelta_str)
# if len(tokens) == 1:
# if tokens[0].find('day') == -1:
# days = '0'
# rest = tokens[0]
# else:
# days = tokens[0].split(' ')[0]
# rest = '00:00:00'
# else:
# days, rest = tokens
#
# days = int(days)
# hours, minutes, seconds = map(int, rest.split(':'))
# return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
#
# Path: keras_image_captioning/datasets.py
# def get_dataset_instance(dataset_name=None, lemmatize_caption=None,
# single_caption=False):
# """
# If an arg is None, it will get its value from config.active_config.
# """
# dataset_name = dataset_name or active_config().dataset_name
# lemmatize_caption = lemmatize_caption or active_config().lemmatize_caption
#
# for dataset_class in [Flickr8kDataset]:
# if dataset_class.DATASET_NAME == dataset_name:
# return dataset_class(lemmatize_caption=lemmatize_caption,
# single_caption=single_caption)
#
# raise ValueError('Cannot find {} dataset!'.format(dataset_name))
#
# Path: keras_image_captioning/io_utils.py
# def mkdir_p(path):
# try:
# os.makedirs(path)
# except OSError as exc:
# if exc.errno == errno.EEXIST and os.path.isdir(path):
# pass
# else:
# raise
#
# def logging(*args, **kwargs):
# utc_now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
# print(utc_now, '|', *args, **kwargs)
# sys.stdout.flush()
which might include code, classes, or functions. Output only the next line. | dataset = get_dataset_instance(self._dataset_name) |
Given the following code snippet before the placeholder: <|code_start|> @property
def training_label(self):
return self._training_label
@property
def config(self):
return self._config
@property
def gpu_index(self):
return self._gpu_index
@property
def config_filepath(self):
return self._config_filepath
def execute(self):
"""Execute the training."""
env = os.environ.copy()
env['CUDA_VISIBLE_DEVICES'] = str(self.gpu_index)
return self.COMMAND(training_label=self.training_label,
config_file=self.config_filepath,
_env=env,
_out=self._log_filepath,
_err_to_out=True,
_bg=self._background,
_done=self._done_callback)
def _init_config_filepath(self):
tmp_dir = os.path.join(gettempdir(), 'keras_image_captioning')
<|code_end|>
, predict the next line using imports from the current file:
import fire
import itertools
import os
import signal
import sh
import sys
import traceback
from concurrent.futures import ThreadPoolExecutor
from random import uniform
from threading import Lock, Semaphore
from time import sleep
from tempfile import gettempdir, NamedTemporaryFile
from .config import (active_config, write_to_file,
Embed300FineRandomConfigBuilder)
from .common_utils import parse_timedelta
from .datasets import get_dataset_instance
from .io_utils import mkdir_p, logging
and context including class names, function names, and sometimes code from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# def write_to_file(config, yaml_path):
# config_dict = dict(config._asdict())
# time_limit = config_dict['time_limit']
# if time_limit:
# config_dict['time_limit'] = str(time_limit)
# write_yaml_file(config_dict, yaml_path)
#
# class Embed300FineRandomConfigBuilder(Embed300RandomConfigBuilder):
# def __init__(self, fixed_config_keys):
# super(Embed300FineRandomConfigBuilder, self).__init__(
# fixed_config_keys)
#
# self._reduce_lr_factor = lambda: uniform(0.1, 0.9)
# self._reduce_lr_patience = lambda: 4
# self._lemmatize_caption = lambda: False
#
# # Values below are from an analysis of hpsearch/16
# self._word_vector_init = lambda: 'glove'
# self._rnn_layers = lambda: randint(2, 3)
# self._learning_rate = lambda: 10 ** uniform(-4, -2.7)
# self._dropout_rate = lambda: uniform(0.2, 0.5)
#
# Path: keras_image_captioning/common_utils.py
# def parse_timedelta(timedelta_str):
# if isinstance(timedelta_str, timedelta):
# return timedelta_str
# if not timedelta_str or timedelta_str == 'null':
# return None
#
# tokens = re.split(r' days?,? ', timedelta_str)
# if len(tokens) == 1:
# if tokens[0].find('day') == -1:
# days = '0'
# rest = tokens[0]
# else:
# days = tokens[0].split(' ')[0]
# rest = '00:00:00'
# else:
# days, rest = tokens
#
# days = int(days)
# hours, minutes, seconds = map(int, rest.split(':'))
# return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
#
# Path: keras_image_captioning/datasets.py
# def get_dataset_instance(dataset_name=None, lemmatize_caption=None,
# single_caption=False):
# """
# If an arg is None, it will get its value from config.active_config.
# """
# dataset_name = dataset_name or active_config().dataset_name
# lemmatize_caption = lemmatize_caption or active_config().lemmatize_caption
#
# for dataset_class in [Flickr8kDataset]:
# if dataset_class.DATASET_NAME == dataset_name:
# return dataset_class(lemmatize_caption=lemmatize_caption,
# single_caption=single_caption)
#
# raise ValueError('Cannot find {} dataset!'.format(dataset_name))
#
# Path: keras_image_captioning/io_utils.py
# def mkdir_p(path):
# try:
# os.makedirs(path)
# except OSError as exc:
# if exc.errno == errno.EEXIST and os.path.isdir(path):
# pass
# else:
# raise
#
# def logging(*args, **kwargs):
# utc_now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
# print(utc_now, '|', *args, **kwargs)
# sys.stdout.flush()
. Output only the next line. | mkdir_p(tmp_dir) |
Based on the snippet: <|code_start|>
@property
def running_commands(self):
return self._running_commands
@property
def lock(self):
return self._lock
def run(self):
"""Start the hyperparameter search."""
for search_index in itertools.count():
sleep(uniform(0.1, 1))
self._semaphore.acquire()
with self.lock:
if self._stop_search:
break
training_label = self.training_label(search_index)
config = self._config_builder.build_config()
gpu_index = self._available_gpus.pop()
done_callback = self._create_done_callback(gpu_index)
command = TrainingCommand(training_label=training_label,
config=config,
gpu_index=gpu_index,
background=True,
done_callback=done_callback)
self.running_commands.append((search_index, command.execute()))
<|code_end|>
, predict the immediate next line with the help of imports:
import fire
import itertools
import os
import signal
import sh
import sys
import traceback
from concurrent.futures import ThreadPoolExecutor
from random import uniform
from threading import Lock, Semaphore
from time import sleep
from tempfile import gettempdir, NamedTemporaryFile
from .config import (active_config, write_to_file,
Embed300FineRandomConfigBuilder)
from .common_utils import parse_timedelta
from .datasets import get_dataset_instance
from .io_utils import mkdir_p, logging
and context (classes, functions, sometimes code) from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# def write_to_file(config, yaml_path):
# config_dict = dict(config._asdict())
# time_limit = config_dict['time_limit']
# if time_limit:
# config_dict['time_limit'] = str(time_limit)
# write_yaml_file(config_dict, yaml_path)
#
# class Embed300FineRandomConfigBuilder(Embed300RandomConfigBuilder):
# def __init__(self, fixed_config_keys):
# super(Embed300FineRandomConfigBuilder, self).__init__(
# fixed_config_keys)
#
# self._reduce_lr_factor = lambda: uniform(0.1, 0.9)
# self._reduce_lr_patience = lambda: 4
# self._lemmatize_caption = lambda: False
#
# # Values below are from an analysis of hpsearch/16
# self._word_vector_init = lambda: 'glove'
# self._rnn_layers = lambda: randint(2, 3)
# self._learning_rate = lambda: 10 ** uniform(-4, -2.7)
# self._dropout_rate = lambda: uniform(0.2, 0.5)
#
# Path: keras_image_captioning/common_utils.py
# def parse_timedelta(timedelta_str):
# if isinstance(timedelta_str, timedelta):
# return timedelta_str
# if not timedelta_str or timedelta_str == 'null':
# return None
#
# tokens = re.split(r' days?,? ', timedelta_str)
# if len(tokens) == 1:
# if tokens[0].find('day') == -1:
# days = '0'
# rest = tokens[0]
# else:
# days = tokens[0].split(' ')[0]
# rest = '00:00:00'
# else:
# days, rest = tokens
#
# days = int(days)
# hours, minutes, seconds = map(int, rest.split(':'))
# return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
#
# Path: keras_image_captioning/datasets.py
# def get_dataset_instance(dataset_name=None, lemmatize_caption=None,
# single_caption=False):
# """
# If an arg is None, it will get its value from config.active_config.
# """
# dataset_name = dataset_name or active_config().dataset_name
# lemmatize_caption = lemmatize_caption or active_config().lemmatize_caption
#
# for dataset_class in [Flickr8kDataset]:
# if dataset_class.DATASET_NAME == dataset_name:
# return dataset_class(lemmatize_caption=lemmatize_caption,
# single_caption=single_caption)
#
# raise ValueError('Cannot find {} dataset!'.format(dataset_name))
#
# Path: keras_image_captioning/io_utils.py
# def mkdir_p(path):
# try:
# os.makedirs(path)
# except OSError as exc:
# if exc.errno == errno.EEXIST and os.path.isdir(path):
# pass
# else:
# raise
#
# def logging(*args, **kwargs):
# utc_now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
# print(utc_now, '|', *args, **kwargs)
# sys.stdout.flush()
. Output only the next line. | logging('Running training {}..'.format(training_label)) |
Based on the snippet: <|code_start|>
class ImagePreprocessor(object):
"""A Inception v3 image preprocessor. Implements an image augmentation
as well."""
IMAGE_SIZE = (299, 299)
def __init__(self, image_augmentation=None):
self._image_data_generator = ImageDataGenerator(rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
if image_augmentation is None:
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from functools import partial
from keras.applications import inception_v3
from keras.preprocessing import sequence as keras_seq
from keras.preprocessing.image import (ImageDataGenerator, img_to_array,
load_img)
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from .config import active_config
and context (classes, functions, sometimes code) from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
. Output only the next line. | self._image_augmentation_switch = active_config().image_augmentation |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture
def id_to_prediction():
return {
0: 'a man and a woman are eating at the restaurant',
1: 'a boy play a basketball'
}
@pytest.fixture
def id_to_references():
return {
0: ['a man and a woman are eating at the restaurant'],
1: ['a boy is playing a basketball', 'boy plays basketball']
}
class TestBLEU(object):
def test_calculate(self, id_to_prediction, id_to_references):
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import pytest
import tensorflow as tf
from .metrics import (BLEU, CIDEr, METEOR, ROUGE,
categorical_accuracy_with_variable_timestep)
and context including class names, function names, and sometimes code from other files:
# Path: keras_image_captioning/metrics.py
# class BLEU(Score):
# def __init__(self, n=4):
# implementation = bleu.Bleu(n)
# super(BLEU, self).__init__('bleu', implementation)
# self._n = n
#
# def calculate(self, id_to_prediction, id_to_references):
# name_to_score = super(BLEU, self).calculate(id_to_prediction,
# id_to_references)
# scores = name_to_score.values()[0]
# result = {}
# for i, score in enumerate(scores, start=1):
# name = '{}_{}'.format(self._score_name, i)
# result[name] = score
# return result
#
# class CIDEr(Score):
# def __init__(self):
# implementation = cider.Cider()
# super(CIDEr, self).__init__('cider', implementation)
#
# class METEOR(Score):
# def __init__(self):
# implementation = meteor.Meteor()
# super(METEOR, self).__init__('meteor', implementation)
#
# def calculate(self, id_to_prediction, id_to_references):
# if self._data_downloaded():
# return super(METEOR, self).calculate(id_to_prediction,
# id_to_references)
# else:
# return {self._score_name: 0.0}
#
# def _data_downloaded(self):
# meteor_dir = os.path.dirname(meteor.__file__)
# return (os.path.isfile(os.path.join(meteor_dir, 'meteor-1.5.jar')) and
# os.path.isfile(
# os.path.join(meteor_dir, 'data', 'paraphrase-en.gz')))
#
# class ROUGE(Score):
# def __init__(self):
# implementation = rouge.Rouge()
# super(ROUGE, self).__init__('rouge', implementation)
#
# def categorical_accuracy_with_variable_timestep(y_true, y_pred):
# # Actually discarding is not needed if the dummy is an all-zeros array
# # (It is indeed encoded in an all-zeros array by
# # CaptionPreprocessing.preprocess_batch)
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# # Flatten the timestep dimension
# shape = tf.shape(y_true)
# y_true = tf.reshape(y_true, [-1, shape[-1]])
# y_pred = tf.reshape(y_pred, [-1, shape[-1]])
#
# # Discard rows that are all zeros as they represent dummy or padding words.
# is_zero_y_true = tf.equal(y_true, 0)
# is_zero_row_y_true = tf.reduce_all(is_zero_y_true, axis=-1)
# y_true = tf.boolean_mask(y_true, ~is_zero_row_y_true)
# y_pred = tf.boolean_mask(y_pred, ~is_zero_row_y_true)
#
# accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_true, axis=1),
# tf.argmax(y_pred, axis=1)),
# dtype=tf.float32))
# return accuracy
. Output only the next line. | bleu = BLEU(n=4) |
Continue the code snippet: <|code_start|>
@pytest.fixture
def id_to_prediction():
return {
0: 'a man and a woman are eating at the restaurant',
1: 'a boy play a basketball'
}
@pytest.fixture
def id_to_references():
return {
0: ['a man and a woman are eating at the restaurant'],
1: ['a boy is playing a basketball', 'boy plays basketball']
}
class TestBLEU(object):
def test_calculate(self, id_to_prediction, id_to_references):
bleu = BLEU(n=4)
name_to_score = bleu.calculate(id_to_prediction, id_to_references)
assert len(name_to_score) == 4
assert all(type(score) == float
for score in name_to_score.values())
class TestCIDEr(object):
def test_calculate(self, id_to_prediction, id_to_references):
<|code_end|>
. Use current file imports:
import numpy as np
import pytest
import tensorflow as tf
from .metrics import (BLEU, CIDEr, METEOR, ROUGE,
categorical_accuracy_with_variable_timestep)
and context (classes, functions, or code) from other files:
# Path: keras_image_captioning/metrics.py
# class BLEU(Score):
# def __init__(self, n=4):
# implementation = bleu.Bleu(n)
# super(BLEU, self).__init__('bleu', implementation)
# self._n = n
#
# def calculate(self, id_to_prediction, id_to_references):
# name_to_score = super(BLEU, self).calculate(id_to_prediction,
# id_to_references)
# scores = name_to_score.values()[0]
# result = {}
# for i, score in enumerate(scores, start=1):
# name = '{}_{}'.format(self._score_name, i)
# result[name] = score
# return result
#
# class CIDEr(Score):
# def __init__(self):
# implementation = cider.Cider()
# super(CIDEr, self).__init__('cider', implementation)
#
# class METEOR(Score):
# def __init__(self):
# implementation = meteor.Meteor()
# super(METEOR, self).__init__('meteor', implementation)
#
# def calculate(self, id_to_prediction, id_to_references):
# if self._data_downloaded():
# return super(METEOR, self).calculate(id_to_prediction,
# id_to_references)
# else:
# return {self._score_name: 0.0}
#
# def _data_downloaded(self):
# meteor_dir = os.path.dirname(meteor.__file__)
# return (os.path.isfile(os.path.join(meteor_dir, 'meteor-1.5.jar')) and
# os.path.isfile(
# os.path.join(meteor_dir, 'data', 'paraphrase-en.gz')))
#
# class ROUGE(Score):
# def __init__(self):
# implementation = rouge.Rouge()
# super(ROUGE, self).__init__('rouge', implementation)
#
# def categorical_accuracy_with_variable_timestep(y_true, y_pred):
# # Actually discarding is not needed if the dummy is an all-zeros array
# # (It is indeed encoded in an all-zeros array by
# # CaptionPreprocessing.preprocess_batch)
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# # Flatten the timestep dimension
# shape = tf.shape(y_true)
# y_true = tf.reshape(y_true, [-1, shape[-1]])
# y_pred = tf.reshape(y_pred, [-1, shape[-1]])
#
# # Discard rows that are all zeros as they represent dummy or padding words.
# is_zero_y_true = tf.equal(y_true, 0)
# is_zero_row_y_true = tf.reduce_all(is_zero_y_true, axis=-1)
# y_true = tf.boolean_mask(y_true, ~is_zero_row_y_true)
# y_pred = tf.boolean_mask(y_pred, ~is_zero_row_y_true)
#
# accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_true, axis=1),
# tf.argmax(y_pred, axis=1)),
# dtype=tf.float32))
# return accuracy
. Output only the next line. | cider = CIDEr() |
Predict the next line after this snippet: <|code_start|> }
@pytest.fixture
def id_to_references():
return {
0: ['a man and a woman are eating at the restaurant'],
1: ['a boy is playing a basketball', 'boy plays basketball']
}
class TestBLEU(object):
def test_calculate(self, id_to_prediction, id_to_references):
bleu = BLEU(n=4)
name_to_score = bleu.calculate(id_to_prediction, id_to_references)
assert len(name_to_score) == 4
assert all(type(score) == float
for score in name_to_score.values())
class TestCIDEr(object):
def test_calculate(self, id_to_prediction, id_to_references):
cider = CIDEr()
name_to_score = cider.calculate(id_to_prediction, id_to_references)
assert all(type(score) == float
for score in name_to_score.values())
class TestMETEOR(object):
def test_calculate(self, id_to_prediction, id_to_references):
<|code_end|>
using the current file's imports:
import numpy as np
import pytest
import tensorflow as tf
from .metrics import (BLEU, CIDEr, METEOR, ROUGE,
categorical_accuracy_with_variable_timestep)
and any relevant context from other files:
# Path: keras_image_captioning/metrics.py
# class BLEU(Score):
# def __init__(self, n=4):
# implementation = bleu.Bleu(n)
# super(BLEU, self).__init__('bleu', implementation)
# self._n = n
#
# def calculate(self, id_to_prediction, id_to_references):
# name_to_score = super(BLEU, self).calculate(id_to_prediction,
# id_to_references)
# scores = name_to_score.values()[0]
# result = {}
# for i, score in enumerate(scores, start=1):
# name = '{}_{}'.format(self._score_name, i)
# result[name] = score
# return result
#
# class CIDEr(Score):
# def __init__(self):
# implementation = cider.Cider()
# super(CIDEr, self).__init__('cider', implementation)
#
# class METEOR(Score):
# def __init__(self):
# implementation = meteor.Meteor()
# super(METEOR, self).__init__('meteor', implementation)
#
# def calculate(self, id_to_prediction, id_to_references):
# if self._data_downloaded():
# return super(METEOR, self).calculate(id_to_prediction,
# id_to_references)
# else:
# return {self._score_name: 0.0}
#
# def _data_downloaded(self):
# meteor_dir = os.path.dirname(meteor.__file__)
# return (os.path.isfile(os.path.join(meteor_dir, 'meteor-1.5.jar')) and
# os.path.isfile(
# os.path.join(meteor_dir, 'data', 'paraphrase-en.gz')))
#
# class ROUGE(Score):
# def __init__(self):
# implementation = rouge.Rouge()
# super(ROUGE, self).__init__('rouge', implementation)
#
# def categorical_accuracy_with_variable_timestep(y_true, y_pred):
# # Actually discarding is not needed if the dummy is an all-zeros array
# # (It is indeed encoded in an all-zeros array by
# # CaptionPreprocessing.preprocess_batch)
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# # Flatten the timestep dimension
# shape = tf.shape(y_true)
# y_true = tf.reshape(y_true, [-1, shape[-1]])
# y_pred = tf.reshape(y_pred, [-1, shape[-1]])
#
# # Discard rows that are all zeros as they represent dummy or padding words.
# is_zero_y_true = tf.equal(y_true, 0)
# is_zero_row_y_true = tf.reduce_all(is_zero_y_true, axis=-1)
# y_true = tf.boolean_mask(y_true, ~is_zero_row_y_true)
# y_pred = tf.boolean_mask(y_pred, ~is_zero_row_y_true)
#
# accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_true, axis=1),
# tf.argmax(y_pred, axis=1)),
# dtype=tf.float32))
# return accuracy
. Output only the next line. | meteor = METEOR() |
Here is a snippet: <|code_start|> 1: ['a boy is playing a basketball', 'boy plays basketball']
}
class TestBLEU(object):
def test_calculate(self, id_to_prediction, id_to_references):
bleu = BLEU(n=4)
name_to_score = bleu.calculate(id_to_prediction, id_to_references)
assert len(name_to_score) == 4
assert all(type(score) == float
for score in name_to_score.values())
class TestCIDEr(object):
def test_calculate(self, id_to_prediction, id_to_references):
cider = CIDEr()
name_to_score = cider.calculate(id_to_prediction, id_to_references)
assert all(type(score) == float
for score in name_to_score.values())
class TestMETEOR(object):
def test_calculate(self, id_to_prediction, id_to_references):
meteor = METEOR()
name_to_score = meteor.calculate(id_to_prediction, id_to_references)
assert all(type(score) == float for score in name_to_score.values())
class TestROUGE(object):
def test_calculate(self, id_to_prediction, id_to_references):
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import pytest
import tensorflow as tf
from .metrics import (BLEU, CIDEr, METEOR, ROUGE,
categorical_accuracy_with_variable_timestep)
and context from other files:
# Path: keras_image_captioning/metrics.py
# class BLEU(Score):
# def __init__(self, n=4):
# implementation = bleu.Bleu(n)
# super(BLEU, self).__init__('bleu', implementation)
# self._n = n
#
# def calculate(self, id_to_prediction, id_to_references):
# name_to_score = super(BLEU, self).calculate(id_to_prediction,
# id_to_references)
# scores = name_to_score.values()[0]
# result = {}
# for i, score in enumerate(scores, start=1):
# name = '{}_{}'.format(self._score_name, i)
# result[name] = score
# return result
#
# class CIDEr(Score):
# def __init__(self):
# implementation = cider.Cider()
# super(CIDEr, self).__init__('cider', implementation)
#
# class METEOR(Score):
# def __init__(self):
# implementation = meteor.Meteor()
# super(METEOR, self).__init__('meteor', implementation)
#
# def calculate(self, id_to_prediction, id_to_references):
# if self._data_downloaded():
# return super(METEOR, self).calculate(id_to_prediction,
# id_to_references)
# else:
# return {self._score_name: 0.0}
#
# def _data_downloaded(self):
# meteor_dir = os.path.dirname(meteor.__file__)
# return (os.path.isfile(os.path.join(meteor_dir, 'meteor-1.5.jar')) and
# os.path.isfile(
# os.path.join(meteor_dir, 'data', 'paraphrase-en.gz')))
#
# class ROUGE(Score):
# def __init__(self):
# implementation = rouge.Rouge()
# super(ROUGE, self).__init__('rouge', implementation)
#
# def categorical_accuracy_with_variable_timestep(y_true, y_pred):
# # Actually discarding is not needed if the dummy is an all-zeros array
# # (It is indeed encoded in an all-zeros array by
# # CaptionPreprocessing.preprocess_batch)
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# # Flatten the timestep dimension
# shape = tf.shape(y_true)
# y_true = tf.reshape(y_true, [-1, shape[-1]])
# y_pred = tf.reshape(y_pred, [-1, shape[-1]])
#
# # Discard rows that are all zeros as they represent dummy or padding words.
# is_zero_y_true = tf.equal(y_true, 0)
# is_zero_row_y_true = tf.reduce_all(is_zero_y_true, axis=-1)
# y_true = tf.boolean_mask(y_true, ~is_zero_row_y_true)
# y_pred = tf.boolean_mask(y_pred, ~is_zero_row_y_true)
#
# accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_true, axis=1),
# tf.argmax(y_pred, axis=1)),
# dtype=tf.float32))
# return accuracy
, which may include functions, classes, or code. Output only the next line. | rouge = ROUGE() |
Given the following code snippet before the placeholder: <|code_start|> [0, 0, 0]]])
y_pred_np = y_true_np.copy()
_assert_accuracy(1.0, y_true_np, y_pred_np)
# Confirm the accuracy value
y_true_np = y_true_np.copy()
y_pred_np = y_true_np.copy()
y_pred_np[0, 0] = np.array([1, 0, 0]) # from [0, 1, 0]
y_pred_np[1, 1] = np.array([0, 0, 1]) # from [1, 0, 0]
_assert_accuracy(0.6, y_true_np, y_pred_np)
# Confirm that last timestep/word (dummy) is discarded
y_true_np = y_true_np.copy()
y_pred_np = y_true_np.copy()
y_true_np[:, -1, :] = np.array([[1, 0, 0], [0, 1, 0]])
y_pred_np[:, -1, :] = np.array([[0, 0, 1], [1, 0, 0]])
_assert_accuracy(1.0, y_true_np, y_pred_np)
# Confirm that the padding words don't contribute to the accuracy
y_true_np = y_true_np.copy()
y_pred_np = y_true_np.copy()
y_pred_np[1, 2] = np.array([1, 0, 0]) # from [0, 0, 0]
_assert_accuracy(1.0, y_true_np, y_pred_np)
def _assert_accuracy(accuracy_expected, y_true_np, y_pred_np):
with tf.Session() as session:
y_true = tf.constant(y_true_np)
y_pred = tf.constant(y_pred_np)
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import pytest
import tensorflow as tf
from .metrics import (BLEU, CIDEr, METEOR, ROUGE,
categorical_accuracy_with_variable_timestep)
and context including class names, function names, and sometimes code from other files:
# Path: keras_image_captioning/metrics.py
# class BLEU(Score):
# def __init__(self, n=4):
# implementation = bleu.Bleu(n)
# super(BLEU, self).__init__('bleu', implementation)
# self._n = n
#
# def calculate(self, id_to_prediction, id_to_references):
# name_to_score = super(BLEU, self).calculate(id_to_prediction,
# id_to_references)
# scores = name_to_score.values()[0]
# result = {}
# for i, score in enumerate(scores, start=1):
# name = '{}_{}'.format(self._score_name, i)
# result[name] = score
# return result
#
# class CIDEr(Score):
# def __init__(self):
# implementation = cider.Cider()
# super(CIDEr, self).__init__('cider', implementation)
#
# class METEOR(Score):
# def __init__(self):
# implementation = meteor.Meteor()
# super(METEOR, self).__init__('meteor', implementation)
#
# def calculate(self, id_to_prediction, id_to_references):
# if self._data_downloaded():
# return super(METEOR, self).calculate(id_to_prediction,
# id_to_references)
# else:
# return {self._score_name: 0.0}
#
# def _data_downloaded(self):
# meteor_dir = os.path.dirname(meteor.__file__)
# return (os.path.isfile(os.path.join(meteor_dir, 'meteor-1.5.jar')) and
# os.path.isfile(
# os.path.join(meteor_dir, 'data', 'paraphrase-en.gz')))
#
# class ROUGE(Score):
# def __init__(self):
# implementation = rouge.Rouge()
# super(ROUGE, self).__init__('rouge', implementation)
#
# def categorical_accuracy_with_variable_timestep(y_true, y_pred):
# # Actually discarding is not needed if the dummy is an all-zeros array
# # (It is indeed encoded in an all-zeros array by
# # CaptionPreprocessing.preprocess_batch)
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# # Flatten the timestep dimension
# shape = tf.shape(y_true)
# y_true = tf.reshape(y_true, [-1, shape[-1]])
# y_pred = tf.reshape(y_pred, [-1, shape[-1]])
#
# # Discard rows that are all zeros as they represent dummy or padding words.
# is_zero_y_true = tf.equal(y_true, 0)
# is_zero_row_y_true = tf.reduce_all(is_zero_y_true, axis=-1)
# y_true = tf.boolean_mask(y_true, ~is_zero_row_y_true)
# y_pred = tf.boolean_mask(y_pred, ~is_zero_row_y_true)
#
# accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_true, axis=1),
# tf.argmax(y_pred, axis=1)),
# dtype=tf.float32))
# return accuracy
. Output only the next line. | result = categorical_accuracy_with_variable_timestep(y_true, y_pred) |
Next line prediction: <|code_start|>
def test___init___with_num_gpus(self):
search = HyperparamSearch(training_label_prefix='test/hpsearch/init2',
dataset_name='flickr8k',
epochs=EPOCHS,
num_gpus=NUM_GPUS + 1)
assert search.num_gpus == NUM_GPUS + 1
def test_run(self, mocker):
if DRY_RUN:
mocker.patch.object(TrainingCommand, 'config_filepath',
mocker.PropertyMock(
return_value=NOT_EXISTING_PATH))
mocker.patch.object(HyperparamSearch, 'num_gpus',
mocker.PropertyMock(return_value=NUM_GPUS))
mocker.patch.object(itertools, 'count', lambda: range(NUM_SEARCHES))
search = HyperparamSearch(training_label_prefix='test/hpsearch/search',
dataset_name='flickr8k',
epochs=EPOCHS)
search.run()
assert all(not x[1].process.is_alive()[0]
for x in search.running_commands)
@pytest.mark.usefixtures('clean_up_training_result_dir')
class TestTrainingCommand(object):
@pytest.fixture
def config_used(self):
<|code_end|>
. Use current file imports:
(import os
import pytest
import sh
import shutil
from .config import active_config, FileConfigBuilder
from .io_utils import path_from_var_dir
from .hyperparam_search import (itertools, main, HyperparamSearch,
TrainingCommand))
and context including class names, function names, or small code snippets from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# class FileConfigBuilder(ConfigBuilderBase):
# def __init__(self, yaml_path):
# self._yaml_path = yaml_path
#
# def build_config(self):
# with open(self._yaml_path) as yaml_file:
# config_dict = yaml.load(yaml_file)
#
# # For backward compatibility
# for field in Config._fields:
# config_dict.setdefault(field, None)
#
# config_dict['time_limit'] = parse_timedelta(config_dict['time_limit'])
# return Config(**config_dict)
#
# Path: keras_image_captioning/io_utils.py
# def path_from_var_dir(*paths):
# return os.path.join(_VAR_ROOT_DIR, *paths)
#
# Path: keras_image_captioning/hyperparam_search.py
# class HyperparamSearch(object):
# class TrainingCommand(object):
# def __init__(self,
# training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def training_label_prefix(self):
# def num_gpus(self):
# def running_commands(self):
# def lock(self):
# def run(self):
# def stop(self):
# def training_label(self, search_index):
# def _validate_training_label_prefix(self):
# def _create_done_callback(self, gpu_index):
# def done_callback(cmd, success, exit_code):
# def _remove_finished_commands(self):
# def _wait_running_commands(self):
# def __init__(self,
# training_label,
# config,
# gpu_index,
# background=False,
# done_callback=None):
# def training_label(self):
# def config(self):
# def gpu_index(self):
# def config_filepath(self):
# def execute(self):
# def _init_config_filepath(self):
# def _init_log_filepath(self):
# def main(training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def handler(signum, frame):
# COMMAND = sh.python.bake('-m', 'keras_image_captioning.training')
# LOG_FILENAME = 'training-log.txt'
. Output only the next line. | config = active_config() |
Given snippet: <|code_start|> return config
@pytest.fixture
def training_command(self):
return TrainingCommand(training_label='test/hpsearch/training-command',
config=self.config_used(),
gpu_index=0,
background=True)
def test_execute(self, training_command):
finished = []
def done_callback(cmd, success, exit_code):
finished.append(True)
training_command._done_callback = done_callback
if DRY_RUN:
training_command._config_filepath = NOT_EXISTING_PATH
running_command = training_command.execute()
with pytest.raises(sh.ErrorReturnCode_1):
running_command.wait()
else:
running_command = training_command.execute()
running_command.wait()
assert len(finished) == 1 and finished[0]
def test__init_config_filepath(self, training_command, config_used):
training_command._init_config_filepath()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import pytest
import sh
import shutil
from .config import active_config, FileConfigBuilder
from .io_utils import path_from_var_dir
from .hyperparam_search import (itertools, main, HyperparamSearch,
TrainingCommand)
and context:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# class FileConfigBuilder(ConfigBuilderBase):
# def __init__(self, yaml_path):
# self._yaml_path = yaml_path
#
# def build_config(self):
# with open(self._yaml_path) as yaml_file:
# config_dict = yaml.load(yaml_file)
#
# # For backward compatibility
# for field in Config._fields:
# config_dict.setdefault(field, None)
#
# config_dict['time_limit'] = parse_timedelta(config_dict['time_limit'])
# return Config(**config_dict)
#
# Path: keras_image_captioning/io_utils.py
# def path_from_var_dir(*paths):
# return os.path.join(_VAR_ROOT_DIR, *paths)
#
# Path: keras_image_captioning/hyperparam_search.py
# class HyperparamSearch(object):
# class TrainingCommand(object):
# def __init__(self,
# training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def training_label_prefix(self):
# def num_gpus(self):
# def running_commands(self):
# def lock(self):
# def run(self):
# def stop(self):
# def training_label(self, search_index):
# def _validate_training_label_prefix(self):
# def _create_done_callback(self, gpu_index):
# def done_callback(cmd, success, exit_code):
# def _remove_finished_commands(self):
# def _wait_running_commands(self):
# def __init__(self,
# training_label,
# config,
# gpu_index,
# background=False,
# done_callback=None):
# def training_label(self):
# def config(self):
# def gpu_index(self):
# def config_filepath(self):
# def execute(self):
# def _init_config_filepath(self):
# def _init_log_filepath(self):
# def main(training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def handler(signum, frame):
# COMMAND = sh.python.bake('-m', 'keras_image_captioning.training')
# LOG_FILENAME = 'training-log.txt'
which might include code, classes, or functions. Output only the next line. | config_builder = FileConfigBuilder(training_command._config_filepath) |
Next line prediction: <|code_start|>
# Because we spawn other processes, we cannot mock anything in them. So, we
# deliberately set an invalid config path in order for the test runs fast.
# When it is needed to do the real test, set DRY_RUN to False and set
# DatasetProvider.training_steps and DatasetProvider.validation_steps to 1.
DRY_RUN = True
NOT_EXISTING_PATH = '/tmp/keras_image_captioning/this.does_not_exist'
NUM_GPUS = 2
NUM_SEARCHES = 6
EPOCHS = 2
@pytest.fixture(scope='module')
def clean_up_training_result_dir():
<|code_end|>
. Use current file imports:
(import os
import pytest
import sh
import shutil
from .config import active_config, FileConfigBuilder
from .io_utils import path_from_var_dir
from .hyperparam_search import (itertools, main, HyperparamSearch,
TrainingCommand))
and context including class names, function names, or small code snippets from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# class FileConfigBuilder(ConfigBuilderBase):
# def __init__(self, yaml_path):
# self._yaml_path = yaml_path
#
# def build_config(self):
# with open(self._yaml_path) as yaml_file:
# config_dict = yaml.load(yaml_file)
#
# # For backward compatibility
# for field in Config._fields:
# config_dict.setdefault(field, None)
#
# config_dict['time_limit'] = parse_timedelta(config_dict['time_limit'])
# return Config(**config_dict)
#
# Path: keras_image_captioning/io_utils.py
# def path_from_var_dir(*paths):
# return os.path.join(_VAR_ROOT_DIR, *paths)
#
# Path: keras_image_captioning/hyperparam_search.py
# class HyperparamSearch(object):
# class TrainingCommand(object):
# def __init__(self,
# training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def training_label_prefix(self):
# def num_gpus(self):
# def running_commands(self):
# def lock(self):
# def run(self):
# def stop(self):
# def training_label(self, search_index):
# def _validate_training_label_prefix(self):
# def _create_done_callback(self, gpu_index):
# def done_callback(cmd, success, exit_code):
# def _remove_finished_commands(self):
# def _wait_running_commands(self):
# def __init__(self,
# training_label,
# config,
# gpu_index,
# background=False,
# done_callback=None):
# def training_label(self):
# def config(self):
# def gpu_index(self):
# def config_filepath(self):
# def execute(self):
# def _init_config_filepath(self):
# def _init_log_filepath(self):
# def main(training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def handler(signum, frame):
# COMMAND = sh.python.bake('-m', 'keras_image_captioning.training')
# LOG_FILENAME = 'training-log.txt'
. Output only the next line. | result_dir = path_from_var_dir('flickr8k/training-results/test/hpsearch') |
Here is a snippet: <|code_start|> result_dir = path_from_var_dir('flickr8k/training-results/test/hpsearch')
if os.path.exists(result_dir):
shutil.rmtree(result_dir)
@pytest.mark.usefixtures('clean_up_training_result_dir')
class TestHyperparamSearch(object):
def test__init__(self, mocker):
mocker.patch.object(HyperparamSearch, 'num_gpus',
mocker.PropertyMock(return_value=NUM_GPUS))
search = HyperparamSearch(training_label_prefix='test/hpsearch/init1',
dataset_name='flickr8k',
epochs=EPOCHS)
assert search.num_gpus == NUM_GPUS
def test___init___with_num_gpus(self):
search = HyperparamSearch(training_label_prefix='test/hpsearch/init2',
dataset_name='flickr8k',
epochs=EPOCHS,
num_gpus=NUM_GPUS + 1)
assert search.num_gpus == NUM_GPUS + 1
def test_run(self, mocker):
if DRY_RUN:
mocker.patch.object(TrainingCommand, 'config_filepath',
mocker.PropertyMock(
return_value=NOT_EXISTING_PATH))
mocker.patch.object(HyperparamSearch, 'num_gpus',
mocker.PropertyMock(return_value=NUM_GPUS))
<|code_end|>
. Write the next line using the current file imports:
import os
import pytest
import sh
import shutil
from .config import active_config, FileConfigBuilder
from .io_utils import path_from_var_dir
from .hyperparam_search import (itertools, main, HyperparamSearch,
TrainingCommand)
and context from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# class FileConfigBuilder(ConfigBuilderBase):
# def __init__(self, yaml_path):
# self._yaml_path = yaml_path
#
# def build_config(self):
# with open(self._yaml_path) as yaml_file:
# config_dict = yaml.load(yaml_file)
#
# # For backward compatibility
# for field in Config._fields:
# config_dict.setdefault(field, None)
#
# config_dict['time_limit'] = parse_timedelta(config_dict['time_limit'])
# return Config(**config_dict)
#
# Path: keras_image_captioning/io_utils.py
# def path_from_var_dir(*paths):
# return os.path.join(_VAR_ROOT_DIR, *paths)
#
# Path: keras_image_captioning/hyperparam_search.py
# class HyperparamSearch(object):
# class TrainingCommand(object):
# def __init__(self,
# training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def training_label_prefix(self):
# def num_gpus(self):
# def running_commands(self):
# def lock(self):
# def run(self):
# def stop(self):
# def training_label(self, search_index):
# def _validate_training_label_prefix(self):
# def _create_done_callback(self, gpu_index):
# def done_callback(cmd, success, exit_code):
# def _remove_finished_commands(self):
# def _wait_running_commands(self):
# def __init__(self,
# training_label,
# config,
# gpu_index,
# background=False,
# done_callback=None):
# def training_label(self):
# def config(self):
# def gpu_index(self):
# def config_filepath(self):
# def execute(self):
# def _init_config_filepath(self):
# def _init_log_filepath(self):
# def main(training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def handler(signum, frame):
# COMMAND = sh.python.bake('-m', 'keras_image_captioning.training')
# LOG_FILENAME = 'training-log.txt'
, which may include functions, classes, or code. Output only the next line. | mocker.patch.object(itertools, 'count', lambda: range(NUM_SEARCHES)) |
Given snippet: <|code_start|>
assert len(finished) == 1 and finished[0]
def test__init_config_filepath(self, training_command, config_used):
training_command._init_config_filepath()
config_builder = FileConfigBuilder(training_command._config_filepath)
config = config_builder.build_config()
assert config == config_used
def test__init_log_filepath(self, training_command):
training_command._init_log_filepath()
assert training_command._log_filepath.find(
training_command.training_label) != -1
@pytest.mark.usefixtures('clean_up_training_result_dir')
def test_main(mocker):
if DRY_RUN:
mocker.patch.object(TrainingCommand, 'config_filepath',
mocker.PropertyMock(
return_value=NOT_EXISTING_PATH))
mocker.patch.object(HyperparamSearch, 'num_gpus',
mocker.PropertyMock(return_value=NUM_GPUS))
mocker.patch.object(itertools, 'count', lambda: range(NUM_SEARCHES))
# Inside main() if wait=False is passed to executor.shutdown(), the mock
# will be broken. It works only for a few miliseconds, but then poof! The
# object is restored to the original. If wait=True, the mock will work
# perfectly.
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import pytest
import sh
import shutil
from .config import active_config, FileConfigBuilder
from .io_utils import path_from_var_dir
from .hyperparam_search import (itertools, main, HyperparamSearch,
TrainingCommand)
and context:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# class FileConfigBuilder(ConfigBuilderBase):
# def __init__(self, yaml_path):
# self._yaml_path = yaml_path
#
# def build_config(self):
# with open(self._yaml_path) as yaml_file:
# config_dict = yaml.load(yaml_file)
#
# # For backward compatibility
# for field in Config._fields:
# config_dict.setdefault(field, None)
#
# config_dict['time_limit'] = parse_timedelta(config_dict['time_limit'])
# return Config(**config_dict)
#
# Path: keras_image_captioning/io_utils.py
# def path_from_var_dir(*paths):
# return os.path.join(_VAR_ROOT_DIR, *paths)
#
# Path: keras_image_captioning/hyperparam_search.py
# class HyperparamSearch(object):
# class TrainingCommand(object):
# def __init__(self,
# training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def training_label_prefix(self):
# def num_gpus(self):
# def running_commands(self):
# def lock(self):
# def run(self):
# def stop(self):
# def training_label(self, search_index):
# def _validate_training_label_prefix(self):
# def _create_done_callback(self, gpu_index):
# def done_callback(cmd, success, exit_code):
# def _remove_finished_commands(self):
# def _wait_running_commands(self):
# def __init__(self,
# training_label,
# config,
# gpu_index,
# background=False,
# done_callback=None):
# def training_label(self):
# def config(self):
# def gpu_index(self):
# def config_filepath(self):
# def execute(self):
# def _init_config_filepath(self):
# def _init_log_filepath(self):
# def main(training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def handler(signum, frame):
# COMMAND = sh.python.bake('-m', 'keras_image_captioning.training')
# LOG_FILENAME = 'training-log.txt'
which might include code, classes, or functions. Output only the next line. | main(training_label_prefix='test/hpsearch/main', dataset_name='flickr8k', |
Here is a snippet: <|code_start|>
# Because we spawn other processes, we cannot mock anything in them. So, we
# deliberately set an invalid config path in order for the test runs fast.
# When it is needed to do the real test, set DRY_RUN to False and set
# DatasetProvider.training_steps and DatasetProvider.validation_steps to 1.
DRY_RUN = True
NOT_EXISTING_PATH = '/tmp/keras_image_captioning/this.does_not_exist'
NUM_GPUS = 2
NUM_SEARCHES = 6
EPOCHS = 2
@pytest.fixture(scope='module')
def clean_up_training_result_dir():
result_dir = path_from_var_dir('flickr8k/training-results/test/hpsearch')
if os.path.exists(result_dir):
shutil.rmtree(result_dir)
@pytest.mark.usefixtures('clean_up_training_result_dir')
class TestHyperparamSearch(object):
def test__init__(self, mocker):
<|code_end|>
. Write the next line using the current file imports:
import os
import pytest
import sh
import shutil
from .config import active_config, FileConfigBuilder
from .io_utils import path_from_var_dir
from .hyperparam_search import (itertools, main, HyperparamSearch,
TrainingCommand)
and context from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# class FileConfigBuilder(ConfigBuilderBase):
# def __init__(self, yaml_path):
# self._yaml_path = yaml_path
#
# def build_config(self):
# with open(self._yaml_path) as yaml_file:
# config_dict = yaml.load(yaml_file)
#
# # For backward compatibility
# for field in Config._fields:
# config_dict.setdefault(field, None)
#
# config_dict['time_limit'] = parse_timedelta(config_dict['time_limit'])
# return Config(**config_dict)
#
# Path: keras_image_captioning/io_utils.py
# def path_from_var_dir(*paths):
# return os.path.join(_VAR_ROOT_DIR, *paths)
#
# Path: keras_image_captioning/hyperparam_search.py
# class HyperparamSearch(object):
# class TrainingCommand(object):
# def __init__(self,
# training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def training_label_prefix(self):
# def num_gpus(self):
# def running_commands(self):
# def lock(self):
# def run(self):
# def stop(self):
# def training_label(self, search_index):
# def _validate_training_label_prefix(self):
# def _create_done_callback(self, gpu_index):
# def done_callback(cmd, success, exit_code):
# def _remove_finished_commands(self):
# def _wait_running_commands(self):
# def __init__(self,
# training_label,
# config,
# gpu_index,
# background=False,
# done_callback=None):
# def training_label(self):
# def config(self):
# def gpu_index(self):
# def config_filepath(self):
# def execute(self):
# def _init_config_filepath(self):
# def _init_log_filepath(self):
# def main(training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def handler(signum, frame):
# COMMAND = sh.python.bake('-m', 'keras_image_captioning.training')
# LOG_FILENAME = 'training-log.txt'
, which may include functions, classes, or code. Output only the next line. | mocker.patch.object(HyperparamSearch, 'num_gpus', |
Using the snippet: <|code_start|>NUM_SEARCHES = 6
EPOCHS = 2
@pytest.fixture(scope='module')
def clean_up_training_result_dir():
result_dir = path_from_var_dir('flickr8k/training-results/test/hpsearch')
if os.path.exists(result_dir):
shutil.rmtree(result_dir)
@pytest.mark.usefixtures('clean_up_training_result_dir')
class TestHyperparamSearch(object):
def test__init__(self, mocker):
mocker.patch.object(HyperparamSearch, 'num_gpus',
mocker.PropertyMock(return_value=NUM_GPUS))
search = HyperparamSearch(training_label_prefix='test/hpsearch/init1',
dataset_name='flickr8k',
epochs=EPOCHS)
assert search.num_gpus == NUM_GPUS
def test___init___with_num_gpus(self):
search = HyperparamSearch(training_label_prefix='test/hpsearch/init2',
dataset_name='flickr8k',
epochs=EPOCHS,
num_gpus=NUM_GPUS + 1)
assert search.num_gpus == NUM_GPUS + 1
def test_run(self, mocker):
if DRY_RUN:
<|code_end|>
, determine the next line of code. You have imports:
import os
import pytest
import sh
import shutil
from .config import active_config, FileConfigBuilder
from .io_utils import path_from_var_dir
from .hyperparam_search import (itertools, main, HyperparamSearch,
TrainingCommand)
and context (class names, function names, or code) available:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# class FileConfigBuilder(ConfigBuilderBase):
# def __init__(self, yaml_path):
# self._yaml_path = yaml_path
#
# def build_config(self):
# with open(self._yaml_path) as yaml_file:
# config_dict = yaml.load(yaml_file)
#
# # For backward compatibility
# for field in Config._fields:
# config_dict.setdefault(field, None)
#
# config_dict['time_limit'] = parse_timedelta(config_dict['time_limit'])
# return Config(**config_dict)
#
# Path: keras_image_captioning/io_utils.py
# def path_from_var_dir(*paths):
# return os.path.join(_VAR_ROOT_DIR, *paths)
#
# Path: keras_image_captioning/hyperparam_search.py
# class HyperparamSearch(object):
# class TrainingCommand(object):
# def __init__(self,
# training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def training_label_prefix(self):
# def num_gpus(self):
# def running_commands(self):
# def lock(self):
# def run(self):
# def stop(self):
# def training_label(self, search_index):
# def _validate_training_label_prefix(self):
# def _create_done_callback(self, gpu_index):
# def done_callback(cmd, success, exit_code):
# def _remove_finished_commands(self):
# def _wait_running_commands(self):
# def __init__(self,
# training_label,
# config,
# gpu_index,
# background=False,
# done_callback=None):
# def training_label(self):
# def config(self):
# def gpu_index(self):
# def config_filepath(self):
# def execute(self):
# def _init_config_filepath(self):
# def _init_log_filepath(self):
# def main(training_label_prefix,
# dataset_name=None,
# epochs=None,
# time_limit=None,
# num_gpus=None):
# def handler(signum, frame):
# COMMAND = sh.python.bake('-m', 'keras_image_captioning.training')
# LOG_FILENAME = 'training-log.txt'
. Output only the next line. | mocker.patch.object(TrainingCommand, 'config_filepath', |
Next line prediction: <|code_start|>
class Score(object):
"""A subclass of this class is an adapter of pycocoevalcap."""
def __init__(self, score_name, implementation):
self._score_name = score_name
self._implementation = implementation
def calculate(self, id_to_prediction, id_to_references):
id_to_preds = {}
for id_, pred in id_to_prediction.items():
id_to_preds[id_] = [pred]
avg_score, scores = self._implementation.compute_score(
id_to_references, id_to_preds)
if isinstance(avg_score, (list, tuple)):
avg_score = map(float, avg_score)
else:
avg_score = float(avg_score)
return {self._score_name: avg_score}
class BLEU(Score):
def __init__(self, n=4):
<|code_end|>
. Use current file imports:
(import os
import tensorflow as tf
from pycocoevalcap.bleu import bleu
from pycocoevalcap.cider import cider
from pycocoevalcap.meteor import meteor
from pycocoevalcap.rouge import rouge)
and context including class names, function names, or small code snippets from other files:
# Path: pycocoevalcap/bleu/bleu.py
# class Bleu:
# def __init__(self, n=4):
# def compute_score(self, gts, res):
# def method(self):
#
# Path: pycocoevalcap/cider/cider.py
# class Cider:
# def __init__(self, test=None, refs=None, n=4, sigma=6.0):
# def compute_score(self, gts, res):
# def method(self):
#
# Path: pycocoevalcap/meteor/meteor.py
# METEOR_JAR = 'meteor-1.5.jar'
# class Meteor:
# def __init__(self):
# def compute_score(self, gts, res):
# def method(self):
# def _stat(self, hypothesis_str, reference_list):
# def _score(self, hypothesis_str, reference_list):
# def __del__(self):
#
# Path: pycocoevalcap/rouge/rouge.py
# def my_lcs(string, sub):
# def __init__(self):
# def calc_score(self, candidate, refs):
# def compute_score(self, gts, res):
# def method(self):
# class Rouge():
. Output only the next line. | implementation = bleu.Bleu(n) |
Next line prediction: <|code_start|> for id_, pred in id_to_prediction.items():
id_to_preds[id_] = [pred]
avg_score, scores = self._implementation.compute_score(
id_to_references, id_to_preds)
if isinstance(avg_score, (list, tuple)):
avg_score = map(float, avg_score)
else:
avg_score = float(avg_score)
return {self._score_name: avg_score}
class BLEU(Score):
def __init__(self, n=4):
implementation = bleu.Bleu(n)
super(BLEU, self).__init__('bleu', implementation)
self._n = n
def calculate(self, id_to_prediction, id_to_references):
name_to_score = super(BLEU, self).calculate(id_to_prediction,
id_to_references)
scores = name_to_score.values()[0]
result = {}
for i, score in enumerate(scores, start=1):
name = '{}_{}'.format(self._score_name, i)
result[name] = score
return result
class CIDEr(Score):
def __init__(self):
<|code_end|>
. Use current file imports:
(import os
import tensorflow as tf
from pycocoevalcap.bleu import bleu
from pycocoevalcap.cider import cider
from pycocoevalcap.meteor import meteor
from pycocoevalcap.rouge import rouge)
and context including class names, function names, or small code snippets from other files:
# Path: pycocoevalcap/bleu/bleu.py
# class Bleu:
# def __init__(self, n=4):
# def compute_score(self, gts, res):
# def method(self):
#
# Path: pycocoevalcap/cider/cider.py
# class Cider:
# def __init__(self, test=None, refs=None, n=4, sigma=6.0):
# def compute_score(self, gts, res):
# def method(self):
#
# Path: pycocoevalcap/meteor/meteor.py
# METEOR_JAR = 'meteor-1.5.jar'
# class Meteor:
# def __init__(self):
# def compute_score(self, gts, res):
# def method(self):
# def _stat(self, hypothesis_str, reference_list):
# def _score(self, hypothesis_str, reference_list):
# def __del__(self):
#
# Path: pycocoevalcap/rouge/rouge.py
# def my_lcs(string, sub):
# def __init__(self):
# def calc_score(self, candidate, refs):
# def compute_score(self, gts, res):
# def method(self):
# class Rouge():
. Output only the next line. | implementation = cider.Cider() |
Based on the snippet: <|code_start|> else:
avg_score = float(avg_score)
return {self._score_name: avg_score}
class BLEU(Score):
def __init__(self, n=4):
implementation = bleu.Bleu(n)
super(BLEU, self).__init__('bleu', implementation)
self._n = n
def calculate(self, id_to_prediction, id_to_references):
name_to_score = super(BLEU, self).calculate(id_to_prediction,
id_to_references)
scores = name_to_score.values()[0]
result = {}
for i, score in enumerate(scores, start=1):
name = '{}_{}'.format(self._score_name, i)
result[name] = score
return result
class CIDEr(Score):
def __init__(self):
implementation = cider.Cider()
super(CIDEr, self).__init__('cider', implementation)
class METEOR(Score):
def __init__(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import tensorflow as tf
from pycocoevalcap.bleu import bleu
from pycocoevalcap.cider import cider
from pycocoevalcap.meteor import meteor
from pycocoevalcap.rouge import rouge
and context (classes, functions, sometimes code) from other files:
# Path: pycocoevalcap/bleu/bleu.py
# class Bleu:
# def __init__(self, n=4):
# def compute_score(self, gts, res):
# def method(self):
#
# Path: pycocoevalcap/cider/cider.py
# class Cider:
# def __init__(self, test=None, refs=None, n=4, sigma=6.0):
# def compute_score(self, gts, res):
# def method(self):
#
# Path: pycocoevalcap/meteor/meteor.py
# METEOR_JAR = 'meteor-1.5.jar'
# class Meteor:
# def __init__(self):
# def compute_score(self, gts, res):
# def method(self):
# def _stat(self, hypothesis_str, reference_list):
# def _score(self, hypothesis_str, reference_list):
# def __del__(self):
#
# Path: pycocoevalcap/rouge/rouge.py
# def my_lcs(string, sub):
# def __init__(self):
# def calc_score(self, candidate, refs):
# def compute_score(self, gts, res):
# def method(self):
# class Rouge():
. Output only the next line. | implementation = meteor.Meteor() |
Given the code snippet: <|code_start|> return result
class CIDEr(Score):
def __init__(self):
implementation = cider.Cider()
super(CIDEr, self).__init__('cider', implementation)
class METEOR(Score):
def __init__(self):
implementation = meteor.Meteor()
super(METEOR, self).__init__('meteor', implementation)
def calculate(self, id_to_prediction, id_to_references):
if self._data_downloaded():
return super(METEOR, self).calculate(id_to_prediction,
id_to_references)
else:
return {self._score_name: 0.0}
def _data_downloaded(self):
meteor_dir = os.path.dirname(meteor.__file__)
return (os.path.isfile(os.path.join(meteor_dir, 'meteor-1.5.jar')) and
os.path.isfile(
os.path.join(meteor_dir, 'data', 'paraphrase-en.gz')))
class ROUGE(Score):
def __init__(self):
<|code_end|>
, generate the next line using the imports in this file:
import os
import tensorflow as tf
from pycocoevalcap.bleu import bleu
from pycocoevalcap.cider import cider
from pycocoevalcap.meteor import meteor
from pycocoevalcap.rouge import rouge
and context (functions, classes, or occasionally code) from other files:
# Path: pycocoevalcap/bleu/bleu.py
# class Bleu:
# def __init__(self, n=4):
# def compute_score(self, gts, res):
# def method(self):
#
# Path: pycocoevalcap/cider/cider.py
# class Cider:
# def __init__(self, test=None, refs=None, n=4, sigma=6.0):
# def compute_score(self, gts, res):
# def method(self):
#
# Path: pycocoevalcap/meteor/meteor.py
# METEOR_JAR = 'meteor-1.5.jar'
# class Meteor:
# def __init__(self):
# def compute_score(self, gts, res):
# def method(self):
# def _stat(self, hypothesis_str, reference_list):
# def _score(self, hypothesis_str, reference_list):
# def __del__(self):
#
# Path: pycocoevalcap/rouge/rouge.py
# def my_lcs(string, sub):
# def __init__(self):
# def calc_score(self, candidate, refs):
# def compute_score(self, gts, res):
# def method(self):
# class Rouge():
. Output only the next line. | implementation = rouge.Rouge() |
Next line prediction: <|code_start|>
class ImageCaptioningModel(object):
"""A very configurable model to produce captions from images."""
def __init__(self,
learning_rate=None,
vocab_size=None,
embedding_size=None,
rnn_output_size=None,
dropout_rate=None,
bidirectional_rnn=None,
rnn_type=None,
rnn_layers=None,
l1_reg=None,
l2_reg=None,
initializer=None,
word_vector_init=None):
"""
If an arg is None, it will get its value from config.active_config.
"""
<|code_end|>
. Use current file imports:
(from keras.applications.inception_v3 import InceptionV3
from keras.initializers import RandomUniform
from keras.models import Model
from keras.layers import (Dense, Embedding, GRU, Input, LSTM, RepeatVector,
TimeDistributed)
from keras.layers.merge import Concatenate
from keras.layers.normalization import BatchNormalization
from keras.layers.wrappers import Bidirectional
from keras.optimizers import Adam
from keras.regularizers import l1_l2
from .config import active_config
from .losses import categorical_crossentropy_from_logits
from .metrics import categorical_accuracy_with_variable_timestep
from .word_vectors import get_word_vector_class)
and context including class names, function names, or small code snippets from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# Path: keras_image_captioning/losses.py
# def categorical_crossentropy_from_logits(y_true, y_pred):
# # Discarding is still needed although CaptionPreprocessor.preprocess_batch
# # has added dummy words as all-zeros arrays because the sum of losses is
# # the same but the mean of losses is different.
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# loss = tf.nn.softmax_cross_entropy_with_logits(labels=y_true,
# logits=y_pred)
# return loss
#
# Path: keras_image_captioning/metrics.py
# def categorical_accuracy_with_variable_timestep(y_true, y_pred):
# # Actually discarding is not needed if the dummy is an all-zeros array
# # (It is indeed encoded in an all-zeros array by
# # CaptionPreprocessing.preprocess_batch)
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# # Flatten the timestep dimension
# shape = tf.shape(y_true)
# y_true = tf.reshape(y_true, [-1, shape[-1]])
# y_pred = tf.reshape(y_pred, [-1, shape[-1]])
#
# # Discard rows that are all zeros as they represent dummy or padding words.
# is_zero_y_true = tf.equal(y_true, 0)
# is_zero_row_y_true = tf.reduce_all(is_zero_y_true, axis=-1)
# y_true = tf.boolean_mask(y_true, ~is_zero_row_y_true)
# y_pred = tf.boolean_mask(y_pred, ~is_zero_row_y_true)
#
# accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_true, axis=1),
# tf.argmax(y_pred, axis=1)),
# dtype=tf.float32))
# return accuracy
#
# Path: keras_image_captioning/word_vectors.py
# def get_word_vector_class(name):
# if name == 'glove':
# return Glove
# elif name == 'fasttext':
# return Fasttext
# else:
# raise ValueError('Word vector = {} is not found!'.format(name))
. Output only the next line. | self._learning_rate = learning_rate or active_config().learning_rate |
Next line prediction: <|code_start|>
if self._rnn_layers < 1:
raise ValueError('rnn_layers must be >= 1!')
if self._word_vector_init is not None and self._embedding_size != 300:
raise ValueError('If word_vector_init is not None, embedding_size '
'must be 300')
@property
def keras_model(self):
if self._keras_model is None:
raise AttributeError('Execute build method first before accessing '
'keras_model!')
return self._keras_model
def build(self, vocabs=None):
if self._keras_model:
return
if vocabs is None and self._word_vector_init is not None:
raise ValueError('If word_vector_init is not None, build method '
'must be called with vocabs that are not None!')
image_input, image_embedding = self._build_image_embedding()
sentence_input, word_embedding = self._build_word_embedding(vocabs)
sequence_input = Concatenate(axis=1)([image_embedding, word_embedding])
sequence_output = self._build_sequence_model(sequence_input)
model = Model(inputs=[image_input, sentence_input],
outputs=sequence_output)
model.compile(optimizer=Adam(lr=self._learning_rate, clipnorm=5.0),
<|code_end|>
. Use current file imports:
(from keras.applications.inception_v3 import InceptionV3
from keras.initializers import RandomUniform
from keras.models import Model
from keras.layers import (Dense, Embedding, GRU, Input, LSTM, RepeatVector,
TimeDistributed)
from keras.layers.merge import Concatenate
from keras.layers.normalization import BatchNormalization
from keras.layers.wrappers import Bidirectional
from keras.optimizers import Adam
from keras.regularizers import l1_l2
from .config import active_config
from .losses import categorical_crossentropy_from_logits
from .metrics import categorical_accuracy_with_variable_timestep
from .word_vectors import get_word_vector_class)
and context including class names, function names, or small code snippets from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# Path: keras_image_captioning/losses.py
# def categorical_crossentropy_from_logits(y_true, y_pred):
# # Discarding is still needed although CaptionPreprocessor.preprocess_batch
# # has added dummy words as all-zeros arrays because the sum of losses is
# # the same but the mean of losses is different.
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# loss = tf.nn.softmax_cross_entropy_with_logits(labels=y_true,
# logits=y_pred)
# return loss
#
# Path: keras_image_captioning/metrics.py
# def categorical_accuracy_with_variable_timestep(y_true, y_pred):
# # Actually discarding is not needed if the dummy is an all-zeros array
# # (It is indeed encoded in an all-zeros array by
# # CaptionPreprocessing.preprocess_batch)
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# # Flatten the timestep dimension
# shape = tf.shape(y_true)
# y_true = tf.reshape(y_true, [-1, shape[-1]])
# y_pred = tf.reshape(y_pred, [-1, shape[-1]])
#
# # Discard rows that are all zeros as they represent dummy or padding words.
# is_zero_y_true = tf.equal(y_true, 0)
# is_zero_row_y_true = tf.reduce_all(is_zero_y_true, axis=-1)
# y_true = tf.boolean_mask(y_true, ~is_zero_row_y_true)
# y_pred = tf.boolean_mask(y_pred, ~is_zero_row_y_true)
#
# accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_true, axis=1),
# tf.argmax(y_pred, axis=1)),
# dtype=tf.float32))
# return accuracy
#
# Path: keras_image_captioning/word_vectors.py
# def get_word_vector_class(name):
# if name == 'glove':
# return Glove
# elif name == 'fasttext':
# return Fasttext
# else:
# raise ValueError('Word vector = {} is not found!'.format(name))
. Output only the next line. | loss=categorical_crossentropy_from_logits, |
Using the snippet: <|code_start|> if self._rnn_layers < 1:
raise ValueError('rnn_layers must be >= 1!')
if self._word_vector_init is not None and self._embedding_size != 300:
raise ValueError('If word_vector_init is not None, embedding_size '
'must be 300')
@property
def keras_model(self):
if self._keras_model is None:
raise AttributeError('Execute build method first before accessing '
'keras_model!')
return self._keras_model
def build(self, vocabs=None):
if self._keras_model:
return
if vocabs is None and self._word_vector_init is not None:
raise ValueError('If word_vector_init is not None, build method '
'must be called with vocabs that are not None!')
image_input, image_embedding = self._build_image_embedding()
sentence_input, word_embedding = self._build_word_embedding(vocabs)
sequence_input = Concatenate(axis=1)([image_embedding, word_embedding])
sequence_output = self._build_sequence_model(sequence_input)
model = Model(inputs=[image_input, sentence_input],
outputs=sequence_output)
model.compile(optimizer=Adam(lr=self._learning_rate, clipnorm=5.0),
loss=categorical_crossentropy_from_logits,
<|code_end|>
, determine the next line of code. You have imports:
from keras.applications.inception_v3 import InceptionV3
from keras.initializers import RandomUniform
from keras.models import Model
from keras.layers import (Dense, Embedding, GRU, Input, LSTM, RepeatVector,
TimeDistributed)
from keras.layers.merge import Concatenate
from keras.layers.normalization import BatchNormalization
from keras.layers.wrappers import Bidirectional
from keras.optimizers import Adam
from keras.regularizers import l1_l2
from .config import active_config
from .losses import categorical_crossentropy_from_logits
from .metrics import categorical_accuracy_with_variable_timestep
from .word_vectors import get_word_vector_class
and context (class names, function names, or code) available:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# Path: keras_image_captioning/losses.py
# def categorical_crossentropy_from_logits(y_true, y_pred):
# # Discarding is still needed although CaptionPreprocessor.preprocess_batch
# # has added dummy words as all-zeros arrays because the sum of losses is
# # the same but the mean of losses is different.
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# loss = tf.nn.softmax_cross_entropy_with_logits(labels=y_true,
# logits=y_pred)
# return loss
#
# Path: keras_image_captioning/metrics.py
# def categorical_accuracy_with_variable_timestep(y_true, y_pred):
# # Actually discarding is not needed if the dummy is an all-zeros array
# # (It is indeed encoded in an all-zeros array by
# # CaptionPreprocessing.preprocess_batch)
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# # Flatten the timestep dimension
# shape = tf.shape(y_true)
# y_true = tf.reshape(y_true, [-1, shape[-1]])
# y_pred = tf.reshape(y_pred, [-1, shape[-1]])
#
# # Discard rows that are all zeros as they represent dummy or padding words.
# is_zero_y_true = tf.equal(y_true, 0)
# is_zero_row_y_true = tf.reduce_all(is_zero_y_true, axis=-1)
# y_true = tf.boolean_mask(y_true, ~is_zero_row_y_true)
# y_pred = tf.boolean_mask(y_pred, ~is_zero_row_y_true)
#
# accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_true, axis=1),
# tf.argmax(y_pred, axis=1)),
# dtype=tf.float32))
# return accuracy
#
# Path: keras_image_captioning/word_vectors.py
# def get_word_vector_class(name):
# if name == 'glove':
# return Glove
# elif name == 'fasttext':
# return Fasttext
# else:
# raise ValueError('Word vector = {} is not found!'.format(name))
. Output only the next line. | metrics=[categorical_accuracy_with_variable_timestep]) |
Continue the code snippet: <|code_start|> metrics=[categorical_accuracy_with_variable_timestep])
self._keras_model = model
def _build_image_embedding(self):
image_model = InceptionV3(include_top=False, weights='imagenet',
pooling='avg')
for layer in image_model.layers:
layer.trainable = False
dense_input = BatchNormalization(axis=-1)(image_model.output)
image_dense = Dense(units=self._embedding_size,
kernel_regularizer=self._regularizer,
kernel_initializer=self._initializer
)(dense_input)
# Add timestep dimension
image_embedding = RepeatVector(1)(image_dense)
image_input = image_model.input
return image_input, image_embedding
def _build_word_embedding(self, vocabs):
sentence_input = Input(shape=[None])
if self._word_vector_init is None:
word_embedding = Embedding(
input_dim=self._vocab_size,
output_dim=self._embedding_size,
embeddings_regularizer=self._regularizer
)(sentence_input)
else:
<|code_end|>
. Use current file imports:
from keras.applications.inception_v3 import InceptionV3
from keras.initializers import RandomUniform
from keras.models import Model
from keras.layers import (Dense, Embedding, GRU, Input, LSTM, RepeatVector,
TimeDistributed)
from keras.layers.merge import Concatenate
from keras.layers.normalization import BatchNormalization
from keras.layers.wrappers import Bidirectional
from keras.optimizers import Adam
from keras.regularizers import l1_l2
from .config import active_config
from .losses import categorical_crossentropy_from_logits
from .metrics import categorical_accuracy_with_variable_timestep
from .word_vectors import get_word_vector_class
and context (classes, functions, or code) from other files:
# Path: keras_image_captioning/config.py
# def active_config(new_active_config=None):
# if new_active_config:
# global _active_config
# _active_config = new_active_config
# return _active_config
#
# Path: keras_image_captioning/losses.py
# def categorical_crossentropy_from_logits(y_true, y_pred):
# # Discarding is still needed although CaptionPreprocessor.preprocess_batch
# # has added dummy words as all-zeros arrays because the sum of losses is
# # the same but the mean of losses is different.
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# loss = tf.nn.softmax_cross_entropy_with_logits(labels=y_true,
# logits=y_pred)
# return loss
#
# Path: keras_image_captioning/metrics.py
# def categorical_accuracy_with_variable_timestep(y_true, y_pred):
# # Actually discarding is not needed if the dummy is an all-zeros array
# # (It is indeed encoded in an all-zeros array by
# # CaptionPreprocessing.preprocess_batch)
# y_true = y_true[:, :-1, :] # Discard the last timestep/word (dummy)
# y_pred = y_pred[:, :-1, :] # Discard the last timestep/word (dummy)
#
# # Flatten the timestep dimension
# shape = tf.shape(y_true)
# y_true = tf.reshape(y_true, [-1, shape[-1]])
# y_pred = tf.reshape(y_pred, [-1, shape[-1]])
#
# # Discard rows that are all zeros as they represent dummy or padding words.
# is_zero_y_true = tf.equal(y_true, 0)
# is_zero_row_y_true = tf.reduce_all(is_zero_y_true, axis=-1)
# y_true = tf.boolean_mask(y_true, ~is_zero_row_y_true)
# y_pred = tf.boolean_mask(y_pred, ~is_zero_row_y_true)
#
# accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_true, axis=1),
# tf.argmax(y_pred, axis=1)),
# dtype=tf.float32))
# return accuracy
#
# Path: keras_image_captioning/word_vectors.py
# def get_word_vector_class(name):
# if name == 'glove':
# return Glove
# elif name == 'fasttext':
# return Fasttext
# else:
# raise ValueError('Word vector = {} is not found!'.format(name))
. Output only the next line. | WordVector = get_word_vector_class(self._word_vector_init) |
Based on the snippet: <|code_start|> def transform_points(self, x_ma):
return x_ma.dot(self.lin_ag) + self.trans_g[None,:]
def compute_jacobian(self, x_ma):
return np.repeat(self.lin_ag.T[None,:,:],len(x_ma), axis=0)
class Composition(Transformation):
def __init__(self, fs):
"applied from first to last (left to right)"
self.fs = fs
def transform_points(self, x_ma):
for f in self.fs: x_ma = f.transform_points(x_ma)
return x_ma
def compute_jacobian(self, x_ma):
grads = []
for f in self.fs:
grad_mga = f.compute_jacobian(x_ma)
grads.append(grad_mga)
x_ma = f.transform_points(x_ma)
totalgrad = grads[0]
for grad in grads[1:]:
totalgrad = (grad[:,:,:,None] * totalgrad[:,None,:,:]).sum(axis=-2)
return totalgrad
def orthogonalize3_cross(mats_n33):
"turns each matrix into a rotation"
x_n3 = mats_n33[:,:,0]
# y_n3 = mats_n33[:,:,1]
z_n3 = mats_n33[:,:,2]
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from lfd.rapprentice import svds, math_utils
and context (classes, functions, sometimes code) from other files:
# Path: lfd/rapprentice/math_utils.py
# def interp2d(x,xp,yp):
# def interp_mat(x, xp):
# def normalize(x):
# def normr(x):
# def normc(x):
# def norms(x,ax):
# def intround(x):
# def deriv(x):
# def linspace2d(start,end,n):
# def remove_duplicate_rows(mat):
# def invertHmat(hmat):
# T = len(x)
# R = hmat[:3,:3]
. Output only the next line. | znew_n3 = math_utils.normr(z_n3) |
Here is a snippet: <|code_start|> total_path = []
for node in nodes[::2]:
if node%2 == 0: total_path.extend(segs[node//2])
else: total_path.extend(segs[node//2][::-1])
total_path_3d = remove_duplicate_rows(np.array([S.node[i]["xyz"] for i in total_path]))
# perturb the path, if requested
if perturb_peak_dist is not None and perturb_peak_dist != 0:
print "Perturbing the Path"
orig_path_length = np.sqrt(((total_path_3d[1:,:2] - total_path_3d[:-1,:2])**2).sum(axis=1)).sum()
perturb_centers = np.linspace(0, len(total_path_3d)-1, num_perturb_points).astype(int)
perturb_xy = np.zeros((len(total_path_3d), 2))
bandwidth = len(total_path_3d) / (num_perturb_points-1)
# add a linearly decreasing peak around each perturbation center
# (keep doing so randomly until our final rope has no loops)
for _ in range(20):
for i_center in perturb_centers:
angle = np.random.rand() * 2 * np.pi
range_min = max(0, i_center - bandwidth)
range_max = min(len(total_path_3d), i_center + bandwidth + 1)
radii = np.linspace(0, perturb_peak_dist, i_center+1-range_min)
perturb_xy[range_min:i_center+1,:] += np.c_[radii*np.cos(angle), radii*np.sin(angle)]
radii = np.linspace(perturb_peak_dist, 0, range_max-i_center)
perturb_xy[i_center+1:range_max,:] += np.c_[radii*np.cos(angle), radii*np.sin(angle)][1:,:]
unscaled_path_2d = total_path_3d[:,:2] + perturb_xy
<|code_end|>
. Write the next line using the current file imports:
import networkx as nx, numpy as np, scipy.spatial.distance as ssd, scipy.interpolate as si
import itertools
import matplotlib.pyplot as plt; plt.ion()
from collections import deque
from numpy.random import rand
from lfd.rapprentice import knot_identification
from mayavi import mlab
from mayavi import mlab
from mayavi import mlab
and context from other files:
# Path: lfd/rapprentice/knot_identification.py
# def intersect_segs(ps_n2, q_22):
# def cross(a_n2, b_n2):
# def rope_has_intersections(ctl_pts):
# def compute_dt_code(ctl_pts, plotting=False):
# def _dt_code_to_knot(dt_code):
# def dt_code_to_knot(dt_code):
# def dt_code_to_knot_wrapper(q, x):
# def identify_knot(ctl_pts):
# def main():
# TIMEOUT = 1
, which may include functions, classes, or code. Output only the next line. | if not knot_identification.rope_has_intersections(unscaled_path_2d): |
Next line prediction: <|code_start|>
def downsample_cloud(cloud_xyz):
return clouds.downsample(cloud_xyz, DS_SIZE)
def main():
scikits.cuda.linalg.init()
args = parse_arguments()
f = h5py.File(args.datafile, 'r+')
bend_coefs = np.around(loglinspace(args.bend_coef_init, args.bend_coef_final, args.n_iter),
BEND_COEF_DIGITS)
for seg_name, seg_info in f.iteritems():
if 'inv' in seg_info:
if args.replace:
del seg_info['inv']
inv_group = seg_info.create_group('inv')
else:
inv_group = seg_info['inv']
else:
inv_group = seg_info.create_group('inv')
ds_key = 'DS_SIZE_{}'.format(DS_SIZE)
if ds_key in inv_group:
scaled_x_na = inv_group[ds_key]['scaled_cloud_xyz'][:]
K_nn = inv_group[ds_key]['scaled_K_nn'][:]
else:
ds_g = inv_group.create_group(ds_key)
x_na = downsample_cloud(seg_info[args.cloud_name][:, :3])
<|code_end|>
. Use current file imports:
(import h5py
import argparse
import sys
import numpy as np
import scipy.linalg
import scikits.cuda.linalg
from pycuda import gpuarray
from scikits.cuda.linalg import pinv as cu_pinv
from settings import GRIPPER_OPEN_CLOSE_THRESH
from tps import tps_kernel_matrix, tps_kernel_matrix2
from lfd.tpsopt.registration import unit_boxify, loglinspace
from lfd.rapprentice import clouds
from culinalg_exts import get_gpu_ptrs, dot_batch_nocheck, m_dot_batch
from settings import N_ITER_CHEAP, DEFAULT_LAMBDA, DS_SIZE, BEND_COEF_DIGITS, EXACT_LAMBDA, N_ITER_EXACT)
and context including class names, function names, or small code snippets from other files:
# Path: lfd/tpsopt/registration.py
# def unit_boxify(x_na):
# ranges = x_na.ptp(axis=0)
# dlarge = ranges.argmax()
# unscaled_translation = - (x_na.min(axis=0) + x_na.max(axis=0))/2
# scaling = 1./ranges[dlarge]
# scaled_translation = unscaled_translation * scaling
# return x_na*scaling + scaled_translation, (scaling, scaled_translation)
#
# def loglinspace(a,b,n):
# "n numbers between a to b (inclusive) with constant ratio between consecutive numbers"
# return np.exp(np.linspace(np.log(a),np.log(b),n))
#
# Path: lfd/rapprentice/clouds.py
# DEFAULT_F = 535.
# X = (x - cx)*(Z/f)
# Y = (y - cy)*(Z/f)
# XYZ = np.empty((480,640,3))
# Z = XYZ[:,:,2] = depth / 1000. # convert mm -> meters
# XYZ[:,:,0] = (x - cx)*(Z/f)
# XYZ[:,:,1] = (y - cy)*(Z/f)
# def xyZ_to_XY(x,y,Z,f=DEFAULT_F):
# def XYZ_to_xy(X,Y,Z,f=DEFAULT_F):
# def depth_to_xyz(depth,f=DEFAULT_F):
# def downsample(xyz, v):
. Output only the next line. | scaled_x_na, scale_params = unit_boxify(x_na) |
Given the code snippet: <|code_start|>
mult = 5.0
GRIPPER_L_FINGER_OPEN_CLOSE_THRESH = mult * GRIPPER_OPEN_CLOSE_THRESH
# indices BEFORE transition occurs
opening_inds = np.flatnonzero((finger_traj[1:] >= GRIPPER_L_FINGER_OPEN_CLOSE_THRESH) & (finger_traj[:-1] < GRIPPER_L_FINGER_OPEN_CLOSE_THRESH))
closing_inds = np.flatnonzero((finger_traj[1:] < GRIPPER_L_FINGER_OPEN_CLOSE_THRESH) & (finger_traj[:-1] >= GRIPPER_L_FINGER_OPEN_CLOSE_THRESH))
return opening_inds, closing_inds
def gripper_joint2gripper_l_finger_joint_values(gripper_joint_vals):
"""
Only the %s_gripper_l_finger_joint%lr can be controlled (this is the joint returned by robot.GetManipulator({"l":"leftarm", "r":"rightarm"}[lr]).GetGripperIndices())
The rest of the gripper joints (like %s_gripper_joint%lr) are mimiced and cannot be controlled directly
"""
mult = 5.0
gripper_l_finger_joint_vals = mult * gripper_joint_vals
return gripper_l_finger_joint_vals
def downsample_cloud(cloud_xyz):
return clouds.downsample(cloud_xyz, DS_SIZE)
def main():
scikits.cuda.linalg.init()
args = parse_arguments()
f = h5py.File(args.datafile, 'r+')
<|code_end|>
, generate the next line using the imports in this file:
import h5py
import argparse
import sys
import numpy as np
import scipy.linalg
import scikits.cuda.linalg
from pycuda import gpuarray
from scikits.cuda.linalg import pinv as cu_pinv
from settings import GRIPPER_OPEN_CLOSE_THRESH
from tps import tps_kernel_matrix, tps_kernel_matrix2
from lfd.tpsopt.registration import unit_boxify, loglinspace
from lfd.rapprentice import clouds
from culinalg_exts import get_gpu_ptrs, dot_batch_nocheck, m_dot_batch
from settings import N_ITER_CHEAP, DEFAULT_LAMBDA, DS_SIZE, BEND_COEF_DIGITS, EXACT_LAMBDA, N_ITER_EXACT
and context (functions, classes, or occasionally code) from other files:
# Path: lfd/tpsopt/registration.py
# def unit_boxify(x_na):
# ranges = x_na.ptp(axis=0)
# dlarge = ranges.argmax()
# unscaled_translation = - (x_na.min(axis=0) + x_na.max(axis=0))/2
# scaling = 1./ranges[dlarge]
# scaled_translation = unscaled_translation * scaling
# return x_na*scaling + scaled_translation, (scaling, scaled_translation)
#
# def loglinspace(a,b,n):
# "n numbers between a to b (inclusive) with constant ratio between consecutive numbers"
# return np.exp(np.linspace(np.log(a),np.log(b),n))
#
# Path: lfd/rapprentice/clouds.py
# DEFAULT_F = 535.
# X = (x - cx)*(Z/f)
# Y = (y - cy)*(Z/f)
# XYZ = np.empty((480,640,3))
# Z = XYZ[:,:,2] = depth / 1000. # convert mm -> meters
# XYZ[:,:,0] = (x - cx)*(Z/f)
# XYZ[:,:,1] = (y - cy)*(Z/f)
# def xyZ_to_XY(x,y,Z,f=DEFAULT_F):
# def XYZ_to_xy(X,Y,Z,f=DEFAULT_F):
# def depth_to_xyz(depth,f=DEFAULT_F):
# def downsample(xyz, v):
. Output only the next line. | bend_coefs = np.around(loglinspace(args.bend_coef_init, args.bend_coef_final, args.n_iter), |
Based on the snippet: <|code_start|> 'h_inv': h_inv,
'N' : N,
'rot_coefs' : rot_coefs}
return bend_coef, res_dict
# Copied from lfd/sim_util.py:
def get_opening_closing_inds(finger_traj):
mult = 5.0
GRIPPER_L_FINGER_OPEN_CLOSE_THRESH = mult * GRIPPER_OPEN_CLOSE_THRESH
# indices BEFORE transition occurs
opening_inds = np.flatnonzero((finger_traj[1:] >= GRIPPER_L_FINGER_OPEN_CLOSE_THRESH) & (finger_traj[:-1] < GRIPPER_L_FINGER_OPEN_CLOSE_THRESH))
closing_inds = np.flatnonzero((finger_traj[1:] < GRIPPER_L_FINGER_OPEN_CLOSE_THRESH) & (finger_traj[:-1] >= GRIPPER_L_FINGER_OPEN_CLOSE_THRESH))
return opening_inds, closing_inds
def gripper_joint2gripper_l_finger_joint_values(gripper_joint_vals):
"""
Only the %s_gripper_l_finger_joint%lr can be controlled (this is the joint returned by robot.GetManipulator({"l":"leftarm", "r":"rightarm"}[lr]).GetGripperIndices())
The rest of the gripper joints (like %s_gripper_joint%lr) are mimiced and cannot be controlled directly
"""
mult = 5.0
gripper_l_finger_joint_vals = mult * gripper_joint_vals
return gripper_l_finger_joint_vals
def downsample_cloud(cloud_xyz):
<|code_end|>
, predict the immediate next line with the help of imports:
import h5py
import argparse
import sys
import numpy as np
import scipy.linalg
import scikits.cuda.linalg
from pycuda import gpuarray
from scikits.cuda.linalg import pinv as cu_pinv
from settings import GRIPPER_OPEN_CLOSE_THRESH
from tps import tps_kernel_matrix, tps_kernel_matrix2
from lfd.tpsopt.registration import unit_boxify, loglinspace
from lfd.rapprentice import clouds
from culinalg_exts import get_gpu_ptrs, dot_batch_nocheck, m_dot_batch
from settings import N_ITER_CHEAP, DEFAULT_LAMBDA, DS_SIZE, BEND_COEF_DIGITS, EXACT_LAMBDA, N_ITER_EXACT
and context (classes, functions, sometimes code) from other files:
# Path: lfd/tpsopt/registration.py
# def unit_boxify(x_na):
# ranges = x_na.ptp(axis=0)
# dlarge = ranges.argmax()
# unscaled_translation = - (x_na.min(axis=0) + x_na.max(axis=0))/2
# scaling = 1./ranges[dlarge]
# scaled_translation = unscaled_translation * scaling
# return x_na*scaling + scaled_translation, (scaling, scaled_translation)
#
# def loglinspace(a,b,n):
# "n numbers between a to b (inclusive) with constant ratio between consecutive numbers"
# return np.exp(np.linspace(np.log(a),np.log(b),n))
#
# Path: lfd/rapprentice/clouds.py
# DEFAULT_F = 535.
# X = (x - cx)*(Z/f)
# Y = (y - cy)*(Z/f)
# XYZ = np.empty((480,640,3))
# Z = XYZ[:,:,2] = depth / 1000. # convert mm -> meters
# XYZ[:,:,0] = (x - cx)*(Z/f)
# XYZ[:,:,1] = (y - cy)*(Z/f)
# def xyZ_to_XY(x,y,Z,f=DEFAULT_F):
# def XYZ_to_xy(X,Y,Z,f=DEFAULT_F):
# def depth_to_xyz(depth,f=DEFAULT_F):
# def downsample(xyz, v):
. Output only the next line. | return clouds.downsample(cloud_xyz, DS_SIZE) |
Next line prediction: <|code_start|> if joint_ind in dof_inds:
target_val = traj[start_ind, dof_inds.index(joint_ind)]
self.world.open_gripper(lr, target_val=target_val, step_viewer=step_viewer)
lr2gripper_open[lr] = True
if aug_traj.lr2close_finger_traj is not None:
for lr in aug_traj.lr2close_finger_traj.keys():
if aug_traj.lr2close_finger_traj[lr][start_ind]:
n_cnts = len(self.sim.constraints[lr])
self.world.close_gripper(lr, step_viewer=step_viewer)
if len(self.sim.constraints[lr]) == n_cnts and lr == 'l':
misgraspl = True
elif lr == 'l':
misgraspl = False
elif len(self.sim.constraints[lr]) == n_cnts and lr=='r':
misgraspr = True
else:
misgraspr = False
#misgrasp |= len(self.sim.constraints[lr]) == n_cnts
lr2gripper_open[lr] = False
misgrasp = misgraspl or misgraspr
# don't execute trajectory for finger joint if the corresponding gripper is closed
active_inds = np.ones(len(dof_inds), dtype=bool)
for lr in 'lr':
if not lr2gripper_open[lr]:
joint_ind = self.sim.robot.GetJoint("%s_gripper_l_finger_joint"%lr).GetDOFIndex()
if joint_ind in dof_inds:
active_inds[dof_inds.index(joint_ind)] = False
miniseg_traj = traj[start_ind:end_ind, active_inds]
miniseg_dof_inds = list(np.asarray(dof_inds)[active_inds])
full_traj = (miniseg_traj, miniseg_dof_inds)
<|code_end|>
. Use current file imports:
(import numpy as np
from lfd.rapprentice import eval_util
from lfd.demonstration import demonstration
from lfd.environment import simulation_object)
and context including class names, function names, or small code snippets from other files:
# Path: lfd/rapprentice/eval_util.py
# class EvalStats(object):
# def __init__(self, **kwargs):
# def get_indexed_items(itemsfile, task_list=None, task_file=None, i_start=-1, i_end=-1):
# def add_obj_to_group(group, k, v):
# def group_or_dataset_to_obj(group_or_dataset):
# def save_results_args(fname, args):
# def load_results_args(fname):
# def save_task_results_step(fname, task_index, step_index, results):
# def load_task_results_step(fname, task_index, step_index):
# def traj_collisions(sim_env, full_traj, collision_dist_threshold, upsample=0):
# def traj_is_safe(sim_env, full_traj, collision_dist_threshold, upsample=0):
#
# Path: lfd/demonstration/demonstration.py
# class Demonstration(object):
# class SceneState(object):
# class GroundTruthRopeSceneState(SceneState):
# class AugmentedTrajectory(object):
# def __init__(self, name, scene_state, aug_traj):
# def __repr__(self):
# def __init__(self, full_cloud, id=None, full_color=None, downsample_size=0):
# def get_unique_id():
# def __repr__(self):
# def __init__(self, rope_nodes, radius, upsample=0, upsample_rad=1, downsample_size=0):
# def __init__(self, lr2arm_traj=None, lr2finger_traj=None, lr2ee_traj=None, lr2open_finger_traj=None, lr2close_finger_traj=None):
# def __eq__(self, other):
# def __ne__(self, other):
# def create_from_full_traj(robot, full_traj, lr2open_finger_traj=None, lr2close_finger_traj=None):
# def get_full_traj(self, robot):
# def get_resampled_traj(self, timesteps_rs):
# def __repr__(self):
#
# Path: lfd/environment/simulation_object.py
# class SimulationObject(object):
# class XmlSimulationObject(SimulationObject):
# class BoxSimulationObject(XmlSimulationObject):
# class CylinderSimulationObject(XmlSimulationObject):
# class RopeSimulationObject(SimulationObject):
# def __init__(self, names, dynamic=True):
# def add_to_env(self, sim):
# def remove_from_env(self):
# def get_bullet_objects(self):
# def get_state(self):
# def set_state(self, tfs):
# def _get_constructor_info(self):
# def __init__(self, xml, dynamic=False):
# def add_to_env(self, sim):
# def remove_from_env(self):
# def _get_constructor_info(self):
# def __repr__(self):
# def __init__(self, name, translation, extents, dynamic=True):
# def _get_constructor_info(self):
# def __repr__(self):
# def __init__(self, name, translation, radius, height, dynamic=True):
# def _get_constructor_info(self):
# def __repr__(self):
# def __init__(self, name, ctrl_points, rope_params=None, dynamic=True, upsample=0, upsample_rad=1):
# def add_to_env(self, sim):
# def remove_from_env(self):
# def get_bullet_objects(self):
# def get_state(self):
# def set_state(self, tfs):
# def _get_constructor_info(self):
# def __repr__(self):
. Output only the next line. | feasible &= eval_util.traj_is_safe(self.sim, full_traj, 0) |
Given snippet: <|code_start|> self.world.close_gripper(lr, step_viewer=step_viewer)
if len(self.sim.constraints[lr]) == n_cnts and lr == 'l':
misgraspl = True
elif lr == 'l':
misgraspl = False
elif len(self.sim.constraints[lr]) == n_cnts and lr=='r':
misgraspr = True
else:
misgraspr = False
#misgrasp |= len(self.sim.constraints[lr]) == n_cnts
lr2gripper_open[lr] = False
misgrasp = misgraspl or misgraspr
# don't execute trajectory for finger joint if the corresponding gripper is closed
active_inds = np.ones(len(dof_inds), dtype=bool)
for lr in 'lr':
if not lr2gripper_open[lr]:
joint_ind = self.sim.robot.GetJoint("%s_gripper_l_finger_joint"%lr).GetDOFIndex()
if joint_ind in dof_inds:
active_inds[dof_inds.index(joint_ind)] = False
miniseg_traj = traj[start_ind:end_ind, active_inds]
miniseg_dof_inds = list(np.asarray(dof_inds)[active_inds])
full_traj = (miniseg_traj, miniseg_dof_inds)
feasible &= eval_util.traj_is_safe(self.sim, full_traj, 0)
if check_feasible and not feasible:
break
self.world.execute_trajectory(full_traj, step_viewer=step_viewer, interactive=interactive, sim_callback=sim_callback)
return feasible, misgrasp
def observe_scene(self):
full_cloud = self.world.observe_cloud()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from lfd.rapprentice import eval_util
from lfd.demonstration import demonstration
from lfd.environment import simulation_object
and context:
# Path: lfd/rapprentice/eval_util.py
# class EvalStats(object):
# def __init__(self, **kwargs):
# def get_indexed_items(itemsfile, task_list=None, task_file=None, i_start=-1, i_end=-1):
# def add_obj_to_group(group, k, v):
# def group_or_dataset_to_obj(group_or_dataset):
# def save_results_args(fname, args):
# def load_results_args(fname):
# def save_task_results_step(fname, task_index, step_index, results):
# def load_task_results_step(fname, task_index, step_index):
# def traj_collisions(sim_env, full_traj, collision_dist_threshold, upsample=0):
# def traj_is_safe(sim_env, full_traj, collision_dist_threshold, upsample=0):
#
# Path: lfd/demonstration/demonstration.py
# class Demonstration(object):
# class SceneState(object):
# class GroundTruthRopeSceneState(SceneState):
# class AugmentedTrajectory(object):
# def __init__(self, name, scene_state, aug_traj):
# def __repr__(self):
# def __init__(self, full_cloud, id=None, full_color=None, downsample_size=0):
# def get_unique_id():
# def __repr__(self):
# def __init__(self, rope_nodes, radius, upsample=0, upsample_rad=1, downsample_size=0):
# def __init__(self, lr2arm_traj=None, lr2finger_traj=None, lr2ee_traj=None, lr2open_finger_traj=None, lr2close_finger_traj=None):
# def __eq__(self, other):
# def __ne__(self, other):
# def create_from_full_traj(robot, full_traj, lr2open_finger_traj=None, lr2close_finger_traj=None):
# def get_full_traj(self, robot):
# def get_resampled_traj(self, timesteps_rs):
# def __repr__(self):
#
# Path: lfd/environment/simulation_object.py
# class SimulationObject(object):
# class XmlSimulationObject(SimulationObject):
# class BoxSimulationObject(XmlSimulationObject):
# class CylinderSimulationObject(XmlSimulationObject):
# class RopeSimulationObject(SimulationObject):
# def __init__(self, names, dynamic=True):
# def add_to_env(self, sim):
# def remove_from_env(self):
# def get_bullet_objects(self):
# def get_state(self):
# def set_state(self, tfs):
# def _get_constructor_info(self):
# def __init__(self, xml, dynamic=False):
# def add_to_env(self, sim):
# def remove_from_env(self):
# def _get_constructor_info(self):
# def __repr__(self):
# def __init__(self, name, translation, extents, dynamic=True):
# def _get_constructor_info(self):
# def __repr__(self):
# def __init__(self, name, translation, radius, height, dynamic=True):
# def _get_constructor_info(self):
# def __repr__(self):
# def __init__(self, name, ctrl_points, rope_params=None, dynamic=True, upsample=0, upsample_rad=1):
# def add_to_env(self, sim):
# def remove_from_env(self):
# def get_bullet_objects(self):
# def get_state(self):
# def set_state(self, tfs):
# def _get_constructor_info(self):
# def __repr__(self):
which might include code, classes, or functions. Output only the next line. | return demonstration.SceneState(full_cloud, downsample_size=self.downsample_size) |
Based on the snippet: <|code_start|> if joint_ind in dof_inds:
active_inds[dof_inds.index(joint_ind)] = False
miniseg_traj = traj[start_ind:end_ind, active_inds]
miniseg_dof_inds = list(np.asarray(dof_inds)[active_inds])
full_traj = (miniseg_traj, miniseg_dof_inds)
feasible &= eval_util.traj_is_safe(self.sim, full_traj, 0)
if check_feasible and not feasible:
break
self.world.execute_trajectory(full_traj, step_viewer=step_viewer, interactive=interactive, sim_callback=sim_callback)
return feasible, misgrasp
def observe_scene(self):
full_cloud = self.world.observe_cloud()
return demonstration.SceneState(full_cloud, downsample_size=self.downsample_size)
class GroundTruthRopeLfdEnvironment(LfdEnvironment):
def __init__(self, world, sim, upsample=0, upsample_rad=1, downsample_size=0):
"""Inits GroundTruthRopeLfdEnvironment
Args:
world: RobotWorld
sim: DynamicSimulation that should containing exactly one rope when observe_scene is called
downsample_size: if downsample_size is positive, the clouds are downsampled to a voxel size of downsample_size, else they are not downsampled
"""
super(GroundTruthRopeLfdEnvironment, self).__init__(world, sim, downsample_size=downsample_size)
self.upsample = upsample
self.upsample_rad = upsample_rad
def observe_scene(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from lfd.rapprentice import eval_util
from lfd.demonstration import demonstration
from lfd.environment import simulation_object
and context (classes, functions, sometimes code) from other files:
# Path: lfd/rapprentice/eval_util.py
# class EvalStats(object):
# def __init__(self, **kwargs):
# def get_indexed_items(itemsfile, task_list=None, task_file=None, i_start=-1, i_end=-1):
# def add_obj_to_group(group, k, v):
# def group_or_dataset_to_obj(group_or_dataset):
# def save_results_args(fname, args):
# def load_results_args(fname):
# def save_task_results_step(fname, task_index, step_index, results):
# def load_task_results_step(fname, task_index, step_index):
# def traj_collisions(sim_env, full_traj, collision_dist_threshold, upsample=0):
# def traj_is_safe(sim_env, full_traj, collision_dist_threshold, upsample=0):
#
# Path: lfd/demonstration/demonstration.py
# class Demonstration(object):
# class SceneState(object):
# class GroundTruthRopeSceneState(SceneState):
# class AugmentedTrajectory(object):
# def __init__(self, name, scene_state, aug_traj):
# def __repr__(self):
# def __init__(self, full_cloud, id=None, full_color=None, downsample_size=0):
# def get_unique_id():
# def __repr__(self):
# def __init__(self, rope_nodes, radius, upsample=0, upsample_rad=1, downsample_size=0):
# def __init__(self, lr2arm_traj=None, lr2finger_traj=None, lr2ee_traj=None, lr2open_finger_traj=None, lr2close_finger_traj=None):
# def __eq__(self, other):
# def __ne__(self, other):
# def create_from_full_traj(robot, full_traj, lr2open_finger_traj=None, lr2close_finger_traj=None):
# def get_full_traj(self, robot):
# def get_resampled_traj(self, timesteps_rs):
# def __repr__(self):
#
# Path: lfd/environment/simulation_object.py
# class SimulationObject(object):
# class XmlSimulationObject(SimulationObject):
# class BoxSimulationObject(XmlSimulationObject):
# class CylinderSimulationObject(XmlSimulationObject):
# class RopeSimulationObject(SimulationObject):
# def __init__(self, names, dynamic=True):
# def add_to_env(self, sim):
# def remove_from_env(self):
# def get_bullet_objects(self):
# def get_state(self):
# def set_state(self, tfs):
# def _get_constructor_info(self):
# def __init__(self, xml, dynamic=False):
# def add_to_env(self, sim):
# def remove_from_env(self):
# def _get_constructor_info(self):
# def __repr__(self):
# def __init__(self, name, translation, extents, dynamic=True):
# def _get_constructor_info(self):
# def __repr__(self):
# def __init__(self, name, translation, radius, height, dynamic=True):
# def _get_constructor_info(self):
# def __repr__(self):
# def __init__(self, name, ctrl_points, rope_params=None, dynamic=True, upsample=0, upsample_rad=1):
# def add_to_env(self, sim):
# def remove_from_env(self):
# def get_bullet_objects(self):
# def get_state(self):
# def set_state(self, tfs):
# def _get_constructor_info(self):
# def __repr__(self):
. Output only the next line. | rope_sim_objs = [sim_obj for sim_obj in self.sim.sim_objs if isinstance(sim_obj, simulation_object.RopeSimulationObject)] |
Given the following code snippet before the placeholder: <|code_start|> if np.linalg.norm(rc.pt - rc.rayFrom) < grab_dist_thresh:
link_tf = rc.link.GetTransform()
link_tf[:3, 3] = rc.pt
self._add_constraints(lr, rc.link, link_tf)
if self.viewer and step_viewer:
self.viewer.Step()
def execute_trajectory(self, full_traj, step_viewer=1, interactive=False,
max_cart_vel_trans_traj=.05, sim_callback=None):
# TODO: incorporate other parts of sim_full_traj_maybesim
if sim_callback is None:
sim_callback = lambda i: self.step()
traj, dof_inds = full_traj
# # clip finger joint angles to the binary gripper angles if necessary
# for lr in 'lr':
# joint_ind = self.robot.GetJoint("%s_gripper_l_finger_joint"%lr).GetDOFIndex()
# if joint_ind in dof_inds:
# ind = dof_inds.index(joint_ind)
# traj[:,ind] = np.minimum(traj[:,ind], get_binary_gripper_angle(True))
# traj[:,ind] = np.maximum(traj[:,ind], get_binary_gripper_angle(False))
# in simulation mode, we must make sure to gradually move to the new starting position
self.robot.SetActiveDOFs(dof_inds)
curr_vals = self.robot.GetActiveDOFValues()
transition_traj = np.r_[[curr_vals], [traj[0]]]
sim_util.unwrap_in_place(transition_traj, dof_inds=dof_inds)
transition_traj = ropesim.retime_traj(self.robot, dof_inds, transition_traj,
max_cart_vel=max_cart_vel_trans_traj)
<|code_end|>
, predict the next line using imports from the current file:
import openravepy
import trajoptpy
import bulletsimpy
import numpy as np
import sim_util
import settings
import importlib
from lfd.rapprentice import animate_traj, ropesim
from robot_world import RobotWorld
from lfd.rapprentice import berkeley_pr2
and context including class names, function names, and sometimes code from other files:
# Path: lfd/rapprentice/animate_traj.py
# def animate_traj(traj, robot, pause=True, step_viewer=1, restore=True, callback=None, execute_step_cond=None):
# """make sure to set active DOFs beforehand"""
# if restore: _saver = openravepy.RobotStateSaver(robot)
# if step_viewer or pause: viewer = trajoptpy.GetViewer(robot.GetEnv())
# for (i,dofs) in enumerate(traj):
# sys.stdout.write("step %i/%i\r"%(i+1,len(traj)))
# sys.stdout.flush()
# if callback is not None: callback(i)
# if execute_step_cond is not None and not execute_step_cond(i): continue
# robot.SetActiveDOFValues(dofs)
# if pause: viewer.Idle()
# elif step_viewer!=0 and (i%step_viewer==0 or i==len(traj)-1): viewer.Step()
# sys.stdout.write("\n")
#
# Path: lfd/rapprentice/ropesim.py
# def transform(hmat, p):
# def in_grasp_region(robot, lr, pt):
# def on_inner_side(pt, finger_lr):
# def retime_traj(robot, inds, traj, max_cart_vel=.02, max_finger_vel=.02, upsample_time=.1):
# def observe_cloud(pts, radius, upsample=0, upsample_rad=1):
# def __init__(self, env, robot, rope_params):
# def create(self, rope_pts):
# def __del__(self):
# def step(self):
# def settle(self, max_steps=100, tol=.001, animate=False):
# def observe_cloud(self, upsample=0, upsample_rad=1):
# def raycast_cloud(self, T_w_k=None, obj=None, z=1., endpoints=0):
# def grab_rope(self, lr):
# def release_rope(self, lr):
# def is_grabbing_rope(self, lr):
# class Simulation(object):
. Output only the next line. | animate_traj.animate_traj(transition_traj, self.robot, restore=False, pause=interactive, |
Given snippet: <|code_start|>
for rc in ray_collisions:
if np.linalg.norm(rc.pt - rc.rayFrom) < grab_dist_thresh:
link_tf = rc.link.GetTransform()
link_tf[:3, 3] = rc.pt
self._add_constraints(lr, rc.link, link_tf)
if self.viewer and step_viewer:
self.viewer.Step()
def execute_trajectory(self, full_traj, step_viewer=1, interactive=False,
max_cart_vel_trans_traj=.05, sim_callback=None):
# TODO: incorporate other parts of sim_full_traj_maybesim
if sim_callback is None:
sim_callback = lambda i: self.step()
traj, dof_inds = full_traj
# # clip finger joint angles to the binary gripper angles if necessary
# for lr in 'lr':
# joint_ind = self.robot.GetJoint("%s_gripper_l_finger_joint"%lr).GetDOFIndex()
# if joint_ind in dof_inds:
# ind = dof_inds.index(joint_ind)
# traj[:,ind] = np.minimum(traj[:,ind], get_binary_gripper_angle(True))
# traj[:,ind] = np.maximum(traj[:,ind], get_binary_gripper_angle(False))
# in simulation mode, we must make sure to gradually move to the new starting position
self.robot.SetActiveDOFs(dof_inds)
curr_vals = self.robot.GetActiveDOFValues()
transition_traj = np.r_[[curr_vals], [traj[0]]]
sim_util.unwrap_in_place(transition_traj, dof_inds=dof_inds)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import openravepy
import trajoptpy
import bulletsimpy
import numpy as np
import sim_util
import settings
import importlib
from lfd.rapprentice import animate_traj, ropesim
from robot_world import RobotWorld
from lfd.rapprentice import berkeley_pr2
and context:
# Path: lfd/rapprentice/animate_traj.py
# def animate_traj(traj, robot, pause=True, step_viewer=1, restore=True, callback=None, execute_step_cond=None):
# """make sure to set active DOFs beforehand"""
# if restore: _saver = openravepy.RobotStateSaver(robot)
# if step_viewer or pause: viewer = trajoptpy.GetViewer(robot.GetEnv())
# for (i,dofs) in enumerate(traj):
# sys.stdout.write("step %i/%i\r"%(i+1,len(traj)))
# sys.stdout.flush()
# if callback is not None: callback(i)
# if execute_step_cond is not None and not execute_step_cond(i): continue
# robot.SetActiveDOFValues(dofs)
# if pause: viewer.Idle()
# elif step_viewer!=0 and (i%step_viewer==0 or i==len(traj)-1): viewer.Step()
# sys.stdout.write("\n")
#
# Path: lfd/rapprentice/ropesim.py
# def transform(hmat, p):
# def in_grasp_region(robot, lr, pt):
# def on_inner_side(pt, finger_lr):
# def retime_traj(robot, inds, traj, max_cart_vel=.02, max_finger_vel=.02, upsample_time=.1):
# def observe_cloud(pts, radius, upsample=0, upsample_rad=1):
# def __init__(self, env, robot, rope_params):
# def create(self, rope_pts):
# def __del__(self):
# def step(self):
# def settle(self, max_steps=100, tol=.001, animate=False):
# def observe_cloud(self, upsample=0, upsample_rad=1):
# def raycast_cloud(self, T_w_k=None, obj=None, z=1., endpoints=0):
# def grab_rope(self, lr):
# def release_rope(self, lr):
# def is_grabbing_rope(self, lr):
# class Simulation(object):
which might include code, classes, or functions. Output only the next line. | transition_traj = ropesim.retime_traj(self.robot, dof_inds, transition_traj, |
Next line prediction: <|code_start|> # check that pt is behind the gripper tip
pt_local = transform(np.linalg.inv(manip.GetTransform()), pt)
if pt_local[2] > .03 + tol:
return False
# check that pt is within the finger width
if abs(pt_local[0]) > .01 + tol:
return False
# check that pt is between the fingers
if not on_inner_side(pt, "l") or not on_inner_side(pt, "r"):
return False
return True
def retime_traj(robot, inds, traj, max_cart_vel=.02, max_finger_vel=.02, upsample_time=.1):
"""retime a trajectory so that it executes slowly enough for the simulation"""
cart_traj = np.empty((len(traj), 6))
finger_traj = np.empty((len(traj),2))
leftarm, rightarm = robot.GetManipulator("leftarm"), robot.GetManipulator("rightarm")
with robot:
for i in range(len(traj)):
robot.SetDOFValues(traj[i], inds)
cart_traj[i,:3] = leftarm.GetTransform()[:3,3]
cart_traj[i,3:] = rightarm.GetTransform()[:3,3]
finger_traj[i,:1] = robot.GetDOFValues(leftarm.GetGripperIndices())
finger_traj[i,1:] = robot.GetDOFValues(rightarm.GetGripperIndices())
times = retiming.retime_with_vel_limits(np.c_[cart_traj, finger_traj], np.r_[np.repeat(max_cart_vel, 6),np.repeat(max_finger_vel,2)])
times_up = np.linspace(0, times[-1], times[-1]/upsample_time) if times[-1] > upsample_time else times
<|code_end|>
. Use current file imports:
(import bulletsimpy
import numpy as np
import trajoptpy
from lfd.rapprentice import math_utils, retiming
from openravepy import matrixFromAxisAngle)
and context including class names, function names, or small code snippets from other files:
# Path: lfd/rapprentice/math_utils.py
# def interp2d(x,xp,yp):
# def interp_mat(x, xp):
# def normalize(x):
# def normr(x):
# def normc(x):
# def norms(x,ax):
# def intround(x):
# def deriv(x):
# def linspace2d(start,end,n):
# def remove_duplicate_rows(mat):
# def invertHmat(hmat):
# T = len(x)
# R = hmat[:3,:3]
. Output only the next line. | traj_up = math_utils.interp2d(times_up, times, traj) |
Predict the next line for this snippet: <|code_start|>
DEBUG_PLOTS = False
def extract_red(rgb, depth, T_w_k):
"""
extract red points and downsample
"""
hsv = cv2.cvtColor(rgb, cv2.COLOR_BGR2HSV)
h = hsv[:,:,0]
s = hsv[:,:,1]
v = hsv[:,:,2]
red_mask = ((h<10) | (h>150)) & (s > 100) & (v > 100)
valid_mask = depth > 0
<|code_end|>
with the help of current file imports:
import cloudprocpy
import cv2, numpy as np
import interactive_roi as ir
from lfd.rapprentice import berkeley_pr2, clouds
and context from other files:
# Path: lfd/rapprentice/clouds.py
# DEFAULT_F = 535.
# X = (x - cx)*(Z/f)
# Y = (y - cy)*(Z/f)
# XYZ = np.empty((480,640,3))
# Z = XYZ[:,:,2] = depth / 1000. # convert mm -> meters
# XYZ[:,:,0] = (x - cx)*(Z/f)
# XYZ[:,:,1] = (y - cy)*(Z/f)
# def xyZ_to_XY(x,y,Z,f=DEFAULT_F):
# def XYZ_to_xy(X,Y,Z,f=DEFAULT_F):
# def depth_to_xyz(depth,f=DEFAULT_F):
# def downsample(xyz, v):
, which may contain function names, class names, or code. Output only the next line. | xyz_k = clouds.depth_to_xyz(depth, berkeley_pr2.f) |
Predict the next line for this snippet: <|code_start|> p,q = src_params
r,s = targ_params
d = len(q)
lin_in = np.eye(d)*p
trans_in = q
aff_in = Affine(lin_in, trans_in)
lin_out = np.eye(d)/r
trans_out = -s/r
aff_out = Affine(lin_out, trans_out)
return Composition([aff_in, f, aff_out])
# @profile
def tps_rpm_bij(x_nd, y_md, fsolve, gsolve,n_iter = 20, reg_init = .1, reg_final = .001, rad_init = .1,
rad_final = .005, rot_reg = 1e-3, outlierprior=1e-1, outlierfrac=2e-1, vis_cost_xy=None,
return_corr=False, check_solver=False):
"""
tps-rpm algorithm mostly as described by chui and rangaran
reg_init/reg_final: regularization on curvature
rad_init/rad_final: radius for correspondence calculation (meters)
plotting: 0 means don't plot. integer n means plot every n iterations
"""
_,d=x_nd.shape
regs = np.around(loglinspace(reg_init, reg_final, n_iter), BEND_COEF_DIGITS)
rads = loglinspace(rad_init, rad_final, n_iter)
<|code_end|>
with the help of current file imports:
import numpy as np
import scipy.spatial.distance as ssd
import tps
from lfd.tpsopt.transformations import ThinPlateSpline, fit_ThinPlateSpline
from settings import BEND_COEF_DIGITS
and context from other files:
# Path: lfd/tpsopt/transformations.py
# class ThinPlateSpline(Transformation):
# """
# members:
# x_na: centers of basis functions
# w_ng:
# lin_ag: transpose of linear part, so you take x_na.dot(lin_ag)
# trans_g: translation part
#
# """
# def __init__(self, d=3):
# "initialize as identity"
# self.x_na = np.zeros((0,d))
# self.lin_ag = np.eye(d)
# self.trans_g = np.zeros(d)
# self.w_ng = np.zeros((0,d))
#
# def transform_points(self, x_ma):
# y_ng = tps.tps_eval(x_ma, self.lin_ag, self.trans_g, self.w_ng, self.x_na)
# return y_ng
# def compute_jacobian(self, x_ma):
# grad_mga = tps.tps_grad(x_ma, self.lin_ag, self.trans_g, self.w_ng, self.x_na)
# return grad_mga
#
# def fit_ThinPlateSpline(x_na, y_ng, bend_coef=.1, rot_coef = 1e-5, wt_n=None):
# """
# x_na: source cloud
# y_nd: target cloud
# smoothing: penalize non-affine part
# angular_spring: penalize rotation
# wt_n: weight the points
# """
# f = ThinPlateSpline()
# f.lin_ag, f.trans_g, f.w_ng = tps.tps_fit3(x_na, y_ng, bend_coef, rot_coef, wt_n)
# f.x_na = x_na
# return f
, which may contain function names, class names, or code. Output only the next line. | f = ThinPlateSpline(d) |
Predict the next line after this snippet: <|code_start|> f.trans_g = np.median(y_md,axis=0) - np.median(x_nd,axis=0) * scale # align the medians
g = ThinPlateSpline(d)
g.lin_ag = np.diag(1./scale)
g.trans_g = -np.diag(1./scale).dot(f.trans_g)
# r_N = None
for i in xrange(n_iter):
xwarped_nd = f.transform_points(x_nd)
ywarped_md = g.transform_points(y_md)
fwddist_nm = ssd.cdist(xwarped_nd, y_md,'euclidean')
invdist_nm = ssd.cdist(x_nd, ywarped_md,'euclidean')
r = rads[i]
prob_nm = np.exp( -(fwddist_nm + invdist_nm) / (2*r) )
corr_nm, r_N, _ = balance_matrix(prob_nm, 10, outlierprior, outlierfrac)
corr_nm += 1e-9
wt_n = corr_nm.sum(axis=1)
wt_m = corr_nm.sum(axis=0)
xtarg_nd = (corr_nm/wt_n[:,None]).dot(y_md)
ytarg_md = (corr_nm/wt_m[None,:]).T.dot(x_nd)
fsolve.solve(wt_n, xtarg_nd, regs[i], rot_reg, f)
gsolve.solve(wt_m, ytarg_md, regs[i], rot_reg, g)
if check_solver:
<|code_end|>
using the current file's imports:
import numpy as np
import scipy.spatial.distance as ssd
import tps
from lfd.tpsopt.transformations import ThinPlateSpline, fit_ThinPlateSpline
from settings import BEND_COEF_DIGITS
and any relevant context from other files:
# Path: lfd/tpsopt/transformations.py
# class ThinPlateSpline(Transformation):
# """
# members:
# x_na: centers of basis functions
# w_ng:
# lin_ag: transpose of linear part, so you take x_na.dot(lin_ag)
# trans_g: translation part
#
# """
# def __init__(self, d=3):
# "initialize as identity"
# self.x_na = np.zeros((0,d))
# self.lin_ag = np.eye(d)
# self.trans_g = np.zeros(d)
# self.w_ng = np.zeros((0,d))
#
# def transform_points(self, x_ma):
# y_ng = tps.tps_eval(x_ma, self.lin_ag, self.trans_g, self.w_ng, self.x_na)
# return y_ng
# def compute_jacobian(self, x_ma):
# grad_mga = tps.tps_grad(x_ma, self.lin_ag, self.trans_g, self.w_ng, self.x_na)
# return grad_mga
#
# def fit_ThinPlateSpline(x_na, y_ng, bend_coef=.1, rot_coef = 1e-5, wt_n=None):
# """
# x_na: source cloud
# y_nd: target cloud
# smoothing: penalize non-affine part
# angular_spring: penalize rotation
# wt_n: weight the points
# """
# f = ThinPlateSpline()
# f.lin_ag, f.trans_g, f.w_ng = tps.tps_fit3(x_na, y_ng, bend_coef, rot_coef, wt_n)
# f.x_na = x_na
# return f
. Output only the next line. | f_test = fit_ThinPlateSpline(x_nd, xtarg_nd, bend_coef = regs[i], wt_n=wt_n, rot_coef = rot_reg) |
Here is a snippet: <|code_start|> for (t,a) in zip(times, angs):
jtp = tm.JointTrajectoryPoint()
jtp.time_from_start = rospy.Duration(t)
jtp.positions = [a]
jt.points.append(jtp)
self.diag_pub.publish(jt)
self.pr2.start_thread(GripperTrajectoryThread(self, times_up, angs_up))
#self.pr2.start_thread(GripperTrajectoryThread(self, times, angs))
def get_angle(self):
return self.pr2.joint_listener.last_msg.position[self.ros_joint_inds[0]]
def get_velocity(self):
return self.pr2.joint_listener.last_msg.velocity[self.ros_joint_inds[0]]
def get_effort(self):
return self.pr2.joint_listener.last_msg.effort[self.ros_joint_inds[0]]
def get_joint_positions(self):
return [self.get_angle()]
class Base(object):
def __init__(self, pr2):
self.pr2 = pr2
self.action_client = actionlib.SimpleActionClient('move_base',mbm.MoveBaseAction)
self.command_pub = rospy.Publisher('base_controller/command', gm.Twist)
self.traj_pub = rospy.Publisher("base_traj_controller/command", tm.JointTrajectory)
self.vel_limits = [.2,.2,.3]
self.acc_limits = [2,2,2] # note: I didn't think these thru
self.n_joints = 3
def goto_pose(self, xya, frame_id):
<|code_end|>
. Write the next line using the current file imports:
import numpy as np, os.path as osp
import openravepy as rave
import roslib
import pr2_controllers_msgs.msg as pcm
import trajectory_msgs.msg as tm
import sensor_msgs.msg as sm
import actionlib
import rospy
import geometry_msgs.msg as gm
import move_base_msgs.msg as mbm
from numpy import inf, zeros, dot, r_, pi
from numpy.linalg import norm, inv
from threading import Thread
from lfd.rapprentice import retiming, math_utils as mu,conversions as conv, func_utils, resampling
and context from other files:
# Path: lfd/rapprentice/math_utils.py
# def interp2d(x,xp,yp):
# def interp_mat(x, xp):
# def normalize(x):
# def normr(x):
# def normc(x):
# def norms(x,ax):
# def intround(x):
# def deriv(x):
# def linspace2d(start,end,n):
# def remove_duplicate_rows(mat):
# def invertHmat(hmat):
# T = len(x)
# R = hmat[:3,:3]
#
# Path: lfd/rapprentice/conversions.py
# def pose_to_trans_rot(pose):
# def hmat_to_pose(hmat):
# def pose_to_hmat(pose):
# def hmat_to_trans_rot(hmat):
# def hmats_to_transs_rots(hmats):
# def trans_rot_to_hmat(trans, rot):
# def xya_to_trans_rot(xya):
# def trans_rot_to_xya(trans, rot):
# def quat_to_yaw(q):
# def yaw_to_quat(yaw):
# def quat2mat(quat):
# def mat2quat(mat33):
# def mats2quats(mats):
# def quats2mats(quats):
# def xyzs_quats_to_poses(xyzs, quats):
# def rod2mat(rod):
# def point_stamed_to_pose_stamped(pts,orientation=(0,0,0,1)):
# def array_to_pose_array(xyz_arr, frame_id, quat_arr=None):
# def trans_rot_to_pose(trans, rot):
# H = transformations.quaternion_matrix(rot)
# H[0:3, 3] = trans
#
# Path: lfd/rapprentice/resampling.py
# def lerp(a, b, fracs):
# def adaptive_resample(x, t = None, max_err = np.inf, max_dx = np.inf, max_dt = np.inf, normfunc = None):
# def get_velocities(positions, times, tol):
# def smooth_positions(positions, tol):
# def unif_resample(x,n,weights,tol=.001,deg=3):
# def test_resample():
# def test_resample_big():
# def interp_quats(newtimes, oldtimes, oldquats):
# def interp_hmats(newtimes, oldtimes, oldhmats):
, which may include functions, classes, or code. Output only the next line. | trans,rot = conv.xya_to_trans_rot(xya) |
Using the snippet: <|code_start|> good_times = times[good_inds]
if len(good_inds) == 1:
return np.zeros(positions[0:1].shape)
(tck, _) = si.splprep(good_positions.T,s = tol**2*(n+1), u=good_times, k=deg)
#smooth_positions = np.r_[si.splev(times,tck,der=0)].T
velocities = np.r_[si.splev(times,tck,der=1)].T
return velocities
def smooth_positions(positions, tol):
times = np.arange(len(positions))
positions = np.atleast_2d(positions)
n = len(positions)
deg = min(3, n - 1)
good_inds = np.r_[True,(abs(times[1:] - times[:-1]) >= 1e-6)]
good_positions = positions[good_inds]
good_times = times[good_inds]
if len(good_inds) == 1:
return np.zeros(positions[0:1].shape)
(tck, _) = si.splprep(good_positions.T,s = tol**2*(n+1), u=good_times, k=deg)
smooth_positions = np.r_[si.splev(times,tck,der=0)].T
return smooth_positions
def unif_resample(x,n,weights,tol=.001,deg=3):
x = np.atleast_2d(x)
weights = np.atleast_2d(weights)
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import scipy.interpolate as si
from numpy import pi
from lfd.rapprentice import math_utils as mu
and context (class names, function names, or code) available:
# Path: lfd/rapprentice/math_utils.py
# def interp2d(x,xp,yp):
# def interp_mat(x, xp):
# def normalize(x):
# def normr(x):
# def normc(x):
# def norms(x,ax):
# def intround(x):
# def deriv(x):
# def linspace2d(start,end,n):
# def remove_duplicate_rows(mat):
# def invertHmat(hmat):
# T = len(x)
# R = hmat[:3,:3]
. Output only the next line. | x = mu.remove_duplicate_rows(x) |
Here is a snippet: <|code_start|> while True:
counter = 1
crossings = defaultdict(list)
# Walk along rope: for each segment, compute intersections with all other segments
for i in range(len(ctl_pts) - 1):
curr_seg = ctl_pts[i:i+2,:]
intersections, ts, us = intersect_segs(ctl_pts[:,:2], curr_seg[:,:2])
if len(intersections) == 0:
continue
if len(intersections) != 1:
LOG.debug('warning: more than one intersection for segment %d, now upsampling', i)
need_upsample_ind = i
break
# for each intersection, determine and record over/undercrossing
i_int = intersections[0]
if plotting:
handles.append(env.drawlinestrip(ctl_pts[i_int:i_int+2], 5, [1, 0, 0]))
int_point_rope = ctl_pts[i_int] + ts[i_int]*(ctl_pts[i_int+1] - ctl_pts[i_int])
int_point_curr_seg = curr_seg[0] + us[i_int]*(curr_seg[1] - curr_seg[0])
#assert np.allclose(int_point_rope[:2], int_point_curr_seg[:2])
above = int_point_curr_seg[2] > int_point_rope[2]
crossings[tuple(sorted((i, i_int)))].append(-counter if counter % 2 == 0 and above else counter)
counter += 1
if plotting: viewer.Idle()
# upsample if necessary
if need_upsample_ind is not None and upsample_iters < max_upsample_iters:
spacing = np.linspace(0, 1, len(ctl_pts))
new_spacing = np.insert(spacing, need_upsample_ind+1, (spacing[need_upsample_ind]+spacing[need_upsample_ind+1])/2.)
<|code_end|>
. Write the next line using the current file imports:
from collections import defaultdict
from lfd.rapprentice import math_utils, LOG
import multiprocessing
import numpy as np
import trajoptpy, openravepy
import snappy
import traceback
import traceback
import cPickle
and context from other files:
# Path: lfd/rapprentice/math_utils.py
# def interp2d(x,xp,yp):
# def interp_mat(x, xp):
# def normalize(x):
# def normr(x):
# def normc(x):
# def norms(x,ax):
# def intround(x):
# def deriv(x):
# def linspace2d(start,end,n):
# def remove_duplicate_rows(mat):
# def invertHmat(hmat):
# T = len(x)
# R = hmat[:3,:3]
, which may include functions, classes, or code. Output only the next line. | ctl_pts = math_utils.interp2d(new_spacing, spacing, ctl_pts) |
Given the following code snippet before the placeholder: <|code_start|>
def get_finger_rel_pts(finger_lr):
left_rel_pts = np.array([[.027,-.016, .01], [-.002,-.016, .01],
[-.002,-.016,-.01], [.027,-.016,-.01]])
if finger_lr == 'l':
return left_rel_pts
else:
rot_x_180 = np.diag([1,-1,-1])
return left_rel_pts.dot(rot_x_180.T)
def get_finger_pts_traj(robot, lr, full_traj_or_ee_finger_traj):
"""
ee_traj = sim_util.get_ee_traj(robot, lr, arm_traj)
flr2finger_pts_traj1 = get_finger_pts_traj(robot, lr, (ee_traj, finger_traj))
full_traj = sim_util.get_full_traj(robot, {lr:arm_traj}, {lr:finger_traj})
flr2finger_pts_traj2 = get_finger_pts_traj(robot, lr, full_traj)
"""
flr2finger_pts_traj = {}
assert type(full_traj_or_ee_finger_traj) == tuple
if full_traj_or_ee_finger_traj[0].ndim == 3:
ee_traj, finger_traj = full_traj_or_ee_finger_traj
assert len(ee_traj) == len(finger_traj)
for finger_lr in 'lr':
gripper_full_traj = get_full_traj(robot, {}, {lr:finger_traj})
rel_ee_traj = get_ee_traj(robot, lr, gripper_full_traj)
rel_finger_traj = get_ee_traj(robot, lr, gripper_full_traj, ee_link_name_fmt="%s"+"_gripper_%s_finger_tip_link"%finger_lr)
flr2finger_pts_traj[finger_lr] = []
for (world_from_ee, world_from_rel_ee, world_from_rel_finger) in zip(ee_traj, rel_ee_traj, rel_finger_traj):
<|code_end|>
, predict the next line using imports from the current file:
import bulletsimpy
import openravepy
import numpy as np
import re
import random
import settings
import scipy.interpolate as si
from numpy import asarray
from lfd.rapprentice import animate_traj, ropesim, math_utils as mu, plotting_openrave
from lfd.util import util
and context including class names, function names, and sometimes code from other files:
# Path: lfd/rapprentice/animate_traj.py
# def animate_traj(traj, robot, pause=True, step_viewer=1, restore=True, callback=None, execute_step_cond=None):
# """make sure to set active DOFs beforehand"""
# if restore: _saver = openravepy.RobotStateSaver(robot)
# if step_viewer or pause: viewer = trajoptpy.GetViewer(robot.GetEnv())
# for (i,dofs) in enumerate(traj):
# sys.stdout.write("step %i/%i\r"%(i+1,len(traj)))
# sys.stdout.flush()
# if callback is not None: callback(i)
# if execute_step_cond is not None and not execute_step_cond(i): continue
# robot.SetActiveDOFValues(dofs)
# if pause: viewer.Idle()
# elif step_viewer!=0 and (i%step_viewer==0 or i==len(traj)-1): viewer.Step()
# sys.stdout.write("\n")
#
# Path: lfd/rapprentice/ropesim.py
# def transform(hmat, p):
# def in_grasp_region(robot, lr, pt):
# def on_inner_side(pt, finger_lr):
# def retime_traj(robot, inds, traj, max_cart_vel=.02, max_finger_vel=.02, upsample_time=.1):
# def observe_cloud(pts, radius, upsample=0, upsample_rad=1):
# def __init__(self, env, robot, rope_params):
# def create(self, rope_pts):
# def __del__(self):
# def step(self):
# def settle(self, max_steps=100, tol=.001, animate=False):
# def observe_cloud(self, upsample=0, upsample_rad=1):
# def raycast_cloud(self, T_w_k=None, obj=None, z=1., endpoints=0):
# def grab_rope(self, lr):
# def release_rope(self, lr):
# def is_grabbing_rope(self, lr):
# class Simulation(object):
#
# Path: lfd/rapprentice/math_utils.py
# def interp2d(x,xp,yp):
# def interp_mat(x, xp):
# def normalize(x):
# def normr(x):
# def normc(x):
# def norms(x,ax):
# def intround(x):
# def deriv(x):
# def linspace2d(start,end,n):
# def remove_duplicate_rows(mat):
# def invertHmat(hmat):
# T = len(x)
# R = hmat[:3,:3]
#
# Path: lfd/rapprentice/plotting_openrave.py
# def draw_grid(env, f, mins, maxes, xres = .1, yres = .1, zres = .04, color = (1,1,0,1)):
#
# Path: lfd/util/util.py
# def redprint(msg):
# def yellowprint(msg):
# def parse_args(self, *args, **kw):
# def __init__(self, adict):
# def __init__(self):
# def __enter__(self):
# def __exit__(self, *_):
# class ArgumentParser(argparse.ArgumentParser):
# class Bunch(object):
# class suppress_stdout(object):
. Output only the next line. | ee_from_finger = mu.invertHmat(world_from_rel_ee).dot(world_from_rel_finger) |
Here is a snippet: <|code_start|>
traj[0] = transition_traj[-1]
unwrap_in_place(traj, dof_inds=dof_inds)
traj = ropesim.retime_traj(sim_env.robot, dof_inds, traj) # make the trajectory slow enough for the simulation
valid_inds = grippers_exceed_rope_length(sim_env, (traj, dof_inds), 0.05)
min_gripper_dist = [np.inf] # minimum distance between gripper when the rope capsules are too far apart
def is_rope_pulled_too_tight(i_step):
if valid_inds is None or valid_inds[i_step]: # gripper is not holding the rope or the grippers are not that far apart
return True
rope = sim_env.sim.rope
trans = rope.GetTranslations()
hhs = rope.GetHalfHeights()
rots = rope.GetRotations()
fwd_pts = (trans + hhs[:,None]*rots[:,:3,0])
bkwd_pts = (trans - hhs[:,None]*rots[:,:3,0])
pts_dists = np.apply_along_axis(np.linalg.norm, 1, fwd_pts[:-1] - bkwd_pts[1:])[:,None] # these should all be zero if the rope constraints are satisfied
if np.any(pts_dists > sim_env.sim.rope_params.radius):
if i_step == 0:
return True
ee_trajs = {}
for lr in 'lr':
ee_trajs[lr] = get_ee_traj(sim_env, lr, (traj[i_step-1:i_step+1], dof_inds), ee_link_name_fmt="%s_gripper_l_finger_tip_link")
min_gripper_dist[0] = min(min_gripper_dist[0], np.linalg.norm(ee_trajs['r'][0,:3,3] - ee_trajs['l'][0,:3,3]))
grippers_moved_closer = np.linalg.norm(ee_trajs['r'][1,:3,3] - ee_trajs['l'][1,:3,3]) < min_gripper_dist[0]
return grippers_moved_closer
return True
animate_traj.animate_traj(traj, sim_env.robot, restore=False, pause=interactive,
callback=sim_callback, step_viewer=animate_speed, execute_step_cond=is_rope_pulled_too_tight)
if min_gripper_dist[0] != np.inf:
<|code_end|>
. Write the next line using the current file imports:
import bulletsimpy
import openravepy
import numpy as np
import re
import random
import settings
import scipy.interpolate as si
from numpy import asarray
from lfd.rapprentice import animate_traj, ropesim, math_utils as mu, plotting_openrave
from lfd.util import util
and context from other files:
# Path: lfd/rapprentice/animate_traj.py
# def animate_traj(traj, robot, pause=True, step_viewer=1, restore=True, callback=None, execute_step_cond=None):
# """make sure to set active DOFs beforehand"""
# if restore: _saver = openravepy.RobotStateSaver(robot)
# if step_viewer or pause: viewer = trajoptpy.GetViewer(robot.GetEnv())
# for (i,dofs) in enumerate(traj):
# sys.stdout.write("step %i/%i\r"%(i+1,len(traj)))
# sys.stdout.flush()
# if callback is not None: callback(i)
# if execute_step_cond is not None and not execute_step_cond(i): continue
# robot.SetActiveDOFValues(dofs)
# if pause: viewer.Idle()
# elif step_viewer!=0 and (i%step_viewer==0 or i==len(traj)-1): viewer.Step()
# sys.stdout.write("\n")
#
# Path: lfd/rapprentice/ropesim.py
# def transform(hmat, p):
# def in_grasp_region(robot, lr, pt):
# def on_inner_side(pt, finger_lr):
# def retime_traj(robot, inds, traj, max_cart_vel=.02, max_finger_vel=.02, upsample_time=.1):
# def observe_cloud(pts, radius, upsample=0, upsample_rad=1):
# def __init__(self, env, robot, rope_params):
# def create(self, rope_pts):
# def __del__(self):
# def step(self):
# def settle(self, max_steps=100, tol=.001, animate=False):
# def observe_cloud(self, upsample=0, upsample_rad=1):
# def raycast_cloud(self, T_w_k=None, obj=None, z=1., endpoints=0):
# def grab_rope(self, lr):
# def release_rope(self, lr):
# def is_grabbing_rope(self, lr):
# class Simulation(object):
#
# Path: lfd/rapprentice/math_utils.py
# def interp2d(x,xp,yp):
# def interp_mat(x, xp):
# def normalize(x):
# def normr(x):
# def normc(x):
# def norms(x,ax):
# def intround(x):
# def deriv(x):
# def linspace2d(start,end,n):
# def remove_duplicate_rows(mat):
# def invertHmat(hmat):
# T = len(x)
# R = hmat[:3,:3]
#
# Path: lfd/rapprentice/plotting_openrave.py
# def draw_grid(env, f, mins, maxes, xres = .1, yres = .1, zres = .04, color = (1,1,0,1)):
#
# Path: lfd/util/util.py
# def redprint(msg):
# def yellowprint(msg):
# def parse_args(self, *args, **kw):
# def __init__(self, adict):
# def __init__(self):
# def __enter__(self):
# def __exit__(self, *_):
# class ArgumentParser(argparse.ArgumentParser):
# class Bunch(object):
# class suppress_stdout(object):
, which may include functions, classes, or code. Output only the next line. | util.yellowprint("Some steps of the trajectory were not executed because the gripper was pulling the rope too tight.") |
Based on the snippet: <|code_start|>from __future__ import division
# TODO: rapprentice.plotting_openrave and other openrave plottings should go in this file
def registration_plot_cb(sim, x_nd, y_md, f):
if sim.viewer:
handles = []
handles.append(sim.env.plot3(x_nd, 5, (1,0,0)))
handles.append(sim.env.plot3(y_md, 5, (0,0,1)))
xwarped_nd = f.transform_points(x_nd)
handles.append(sim.env.plot3(xwarped_nd, 5, (0,1,0)))
<|code_end|>
, predict the immediate next line with the help of imports:
from lfd.rapprentice import plotting_openrave
and context (classes, functions, sometimes code) from other files:
# Path: lfd/rapprentice/plotting_openrave.py
# def draw_grid(env, f, mins, maxes, xres = .1, yres = .1, zres = .04, color = (1,1,0,1)):
. Output only the next line. | handles.extend(plotting_openrave.draw_grid(sim.env, f.transform_points, x_nd.min(axis=0), x_nd.max(axis=0), xres = .1, yres = .1, zres = .04)) |
Given the following code snippet before the placeholder: <|code_start|> if task_index in result_file:
del result_file[task_index]
result_file.create_group(task_index)
task_index = str(task_index)
step_index = str(step_index)
assert task_index in result_file, "Must call this function with step_index of 0 first"
if step_index not in result_file[task_index]:
step_group = result_file[task_index].create_group(step_index)
else:
step_group = result_file[task_index][step_index]
add_obj_to_group(step_group, 'results', results)
result_file.close()
def load_task_results_step(fname, task_index, step_index):
if fname is None:
raise RuntimeError("Cannot load task results with an unspecified file name")
result_file = h5py.File(fname, 'r')
task_index = str(task_index)
step_index = str(step_index)
step_group = result_file[task_index][step_index]
results = group_or_dataset_to_obj(step_group['results'])
result_file.close()
return results
def traj_collisions(sim_env, full_traj, collision_dist_threshold, upsample=0):
"""
Returns the set of collisions.
manip = Manipulator or list of indices
"""
traj, dof_inds = full_traj
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import importlib, __builtin__
import util
import openravepy, trajoptpy
import h5py, numpy as np
from lfd.environment import sim_util
from lfd.rapprentice import math_utils as mu
from string import lower
and context including class names, function names, and sometimes code from other files:
# Path: lfd/environment/sim_util.py
# PR2_L_POSTURES = dict(
# untucked = [0.4, 1.0, 0.0, -2.05, 0.0, -0.1, 0.0],
# tucked = [0.06, 1.25, 1.79, -1.68, -1.73, -0.10, -0.09],
# up = [ 0.33, -0.35, 2.59, -0.15, 0.59, -1.41, -0.27],
# side = [ 1.832, -0.332, 1.011, -1.437, 1.1 , -2.106, 3.074]
# )
# GRIPPER_L_FINGER_OPEN_CLOSE_THRESH = mult * settings.GRIPPER_OPEN_CLOSE_THRESH
# class RopeState(object):
# class RopeParams(object):
# class SceneState(object):
# def __init__(self, init_rope_nodes, rope_params, tfs=None):
# def __init__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __init__(self, cloud, rope_nodes, rope_state, id=None, color=None):
# def get_unique_id():
# def make_table_xml(translation, extents):
# def make_box_xml(name, translation, extents):
# def make_cylinder_xml(name, translation, radius, height):
# def reset_arms_to_side(sim_env):
# def arm_moved(joint_traj):
# def split_trajectory_by_gripper(seg_info):
# def split_trajectory_by_lr_gripper(seg_info, lr):
# def get_opening_closing_inds(finger_traj):
# def gripper_joint2gripper_l_finger_joint_values(gripper_joint_vals):
# def binarize_gripper(angle):
# def get_binary_gripper_angle(open):
# def set_gripper_maybesim(sim_env, lr, is_open, prev_is_open, animate=False):
# def mirror_arm_joints(x):
# def unwrap_arm_traj_in_place(traj):
# def unwrap_in_place(t, dof_inds=None):
# def dof_inds_from_name(robot, name):
# def sim_traj_maybesim(sim_env, lr2traj, animate=False, interactive=False, max_cart_vel_trans_traj=.05):
# def sim_full_traj_maybesim(sim_env, full_traj, animate=False, interactive=False, max_cart_vel_trans_traj=.05):
# def sim_callback(i):
# def is_rope_pulled_too_tight(i_step):
# def get_full_traj(robot, lr2arm_traj, lr2finger_traj = {}):
# def merge_full_trajs(full_trajs):
# def get_ee_traj(robot, lr, arm_traj_or_full_traj, ee_link_name_fmt="%s_gripper_tool_frame"):
# def get_finger_rel_pts(finger_lr):
# def get_finger_pts_traj(robot, lr, full_traj_or_ee_finger_traj):
# def grippers_exceed_rope_length(sim_env, full_traj, thresh):
# def remove_tight_rope_pull(sim_env, full_traj):
# def load_random_start_segment(demofile):
# def load_fake_data_segment(demofile, fake_data_segment, fake_data_transform):
# def unif_resample(traj, max_diff, wt = None):
# def get_rope_transforms(sim_env):
# def replace_rope(new_rope, sim_env, rope_params, restore=False):
# def set_rope_transforms(tfs, sim_env):
# def get_rope_params(params_id):
# def tpsrpm_plot_cb(sim_env, x_nd, y_md, targ_Nd, corr_nm, wt_n, f):
# def draw_grid(sim_env, old_xyz, f, color = (1,1,0,1)):
# def draw_axis(sim_env, hmat, arrow_length=.1, arrow_width=0.005):
# def draw_finger_pts_traj(sim_env, flr2finger_pts_traj, color):
#
# Path: lfd/rapprentice/math_utils.py
# def interp2d(x,xp,yp):
# def interp_mat(x, xp):
# def normalize(x):
# def normr(x):
# def normc(x):
# def norms(x,ax):
# def intround(x):
# def deriv(x):
# def linspace2d(start,end,n):
# def remove_duplicate_rows(mat):
# def invertHmat(hmat):
# T = len(x)
# R = hmat[:3,:3]
. Output only the next line. | sim_util.unwrap_in_place(traj, dof_inds=dof_inds) |
Continue the code snippet: <|code_start|> task_index = str(task_index)
step_index = str(step_index)
assert task_index in result_file, "Must call this function with step_index of 0 first"
if step_index not in result_file[task_index]:
step_group = result_file[task_index].create_group(step_index)
else:
step_group = result_file[task_index][step_index]
add_obj_to_group(step_group, 'results', results)
result_file.close()
def load_task_results_step(fname, task_index, step_index):
if fname is None:
raise RuntimeError("Cannot load task results with an unspecified file name")
result_file = h5py.File(fname, 'r')
task_index = str(task_index)
step_index = str(step_index)
step_group = result_file[task_index][step_index]
results = group_or_dataset_to_obj(step_group['results'])
result_file.close()
return results
def traj_collisions(sim_env, full_traj, collision_dist_threshold, upsample=0):
"""
Returns the set of collisions.
manip = Manipulator or list of indices
"""
traj, dof_inds = full_traj
sim_util.unwrap_in_place(traj, dof_inds=dof_inds)
if upsample > 0:
<|code_end|>
. Use current file imports:
import argparse
import importlib, __builtin__
import util
import openravepy, trajoptpy
import h5py, numpy as np
from lfd.environment import sim_util
from lfd.rapprentice import math_utils as mu
from string import lower
and context (classes, functions, or code) from other files:
# Path: lfd/environment/sim_util.py
# PR2_L_POSTURES = dict(
# untucked = [0.4, 1.0, 0.0, -2.05, 0.0, -0.1, 0.0],
# tucked = [0.06, 1.25, 1.79, -1.68, -1.73, -0.10, -0.09],
# up = [ 0.33, -0.35, 2.59, -0.15, 0.59, -1.41, -0.27],
# side = [ 1.832, -0.332, 1.011, -1.437, 1.1 , -2.106, 3.074]
# )
# GRIPPER_L_FINGER_OPEN_CLOSE_THRESH = mult * settings.GRIPPER_OPEN_CLOSE_THRESH
# class RopeState(object):
# class RopeParams(object):
# class SceneState(object):
# def __init__(self, init_rope_nodes, rope_params, tfs=None):
# def __init__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __init__(self, cloud, rope_nodes, rope_state, id=None, color=None):
# def get_unique_id():
# def make_table_xml(translation, extents):
# def make_box_xml(name, translation, extents):
# def make_cylinder_xml(name, translation, radius, height):
# def reset_arms_to_side(sim_env):
# def arm_moved(joint_traj):
# def split_trajectory_by_gripper(seg_info):
# def split_trajectory_by_lr_gripper(seg_info, lr):
# def get_opening_closing_inds(finger_traj):
# def gripper_joint2gripper_l_finger_joint_values(gripper_joint_vals):
# def binarize_gripper(angle):
# def get_binary_gripper_angle(open):
# def set_gripper_maybesim(sim_env, lr, is_open, prev_is_open, animate=False):
# def mirror_arm_joints(x):
# def unwrap_arm_traj_in_place(traj):
# def unwrap_in_place(t, dof_inds=None):
# def dof_inds_from_name(robot, name):
# def sim_traj_maybesim(sim_env, lr2traj, animate=False, interactive=False, max_cart_vel_trans_traj=.05):
# def sim_full_traj_maybesim(sim_env, full_traj, animate=False, interactive=False, max_cart_vel_trans_traj=.05):
# def sim_callback(i):
# def is_rope_pulled_too_tight(i_step):
# def get_full_traj(robot, lr2arm_traj, lr2finger_traj = {}):
# def merge_full_trajs(full_trajs):
# def get_ee_traj(robot, lr, arm_traj_or_full_traj, ee_link_name_fmt="%s_gripper_tool_frame"):
# def get_finger_rel_pts(finger_lr):
# def get_finger_pts_traj(robot, lr, full_traj_or_ee_finger_traj):
# def grippers_exceed_rope_length(sim_env, full_traj, thresh):
# def remove_tight_rope_pull(sim_env, full_traj):
# def load_random_start_segment(demofile):
# def load_fake_data_segment(demofile, fake_data_segment, fake_data_transform):
# def unif_resample(traj, max_diff, wt = None):
# def get_rope_transforms(sim_env):
# def replace_rope(new_rope, sim_env, rope_params, restore=False):
# def set_rope_transforms(tfs, sim_env):
# def get_rope_params(params_id):
# def tpsrpm_plot_cb(sim_env, x_nd, y_md, targ_Nd, corr_nm, wt_n, f):
# def draw_grid(sim_env, old_xyz, f, color = (1,1,0,1)):
# def draw_axis(sim_env, hmat, arrow_length=.1, arrow_width=0.005):
# def draw_finger_pts_traj(sim_env, flr2finger_pts_traj, color):
#
# Path: lfd/rapprentice/math_utils.py
# def interp2d(x,xp,yp):
# def interp_mat(x, xp):
# def normalize(x):
# def normr(x):
# def normc(x):
# def norms(x,ax):
# def intround(x):
# def deriv(x):
# def linspace2d(start,end,n):
# def remove_duplicate_rows(mat):
# def invertHmat(hmat):
# T = len(x)
# R = hmat[:3,:3]
. Output only the next line. | traj_up = mu.interp2d(np.linspace(0,1,upsample), np.linspace(0,1,len(traj)), traj) |
Given snippet: <|code_start|>#!/usr/bin/env python
C_vals = [1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 10, 100, 1000]
C_strs = ['1e-05', '0.0001', '0.001', '0.01', '1.0', '10.0', '100.0', '1000.0']
feature_types = ['base', 'mul', 'mul_s', 'mul_quad', 'landmark']
MODEL_TYPE='bellman'
def estimate_performance(results_file):
if type(results_file) is str:
results_file = h5py.File(results_file, 'r')
num_knots = 0
knot_inds = []
not_inds = []
ctr = 0
n_checks = len(results_file) - 1
for (i_task, task_info) in results_file.iteritems():
sys.stdout.write("\rchecking task {} / {} ".format(ctr, n_checks))
sys.stdout.flush()
ctr += 1
if str(i_task) == 'args':
continue
# if int(i_task) > 3:
# break
N_steps = len(task_info)
final_cld = task_info[str(N_steps-1)]['next_state']['rope_nodes'][:]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import h5py
import sys
import os.path as osp
from lfd.rapprentice.knot_classifier import isKnot
from string import lower
and context:
# Path: lfd/rapprentice/knot_classifier.py
# def isKnot(rope_nodes):
# (crossings, crossings_links_inds, cross_pairs, rope_closed) = calculateCrossings(rope_nodes)
# # simplify crossings a bit
# crossings, crossings_links_inds, cross_pairs = remove_consecutive_crossings(crossings, crossings_links_inds, cross_pairs)
# crossings, crossings_links_inds, cross_pairs = remove_consecutive_cross_pairs(crossings, crossings_links_inds, cross_pairs)
# s = crossingsToString(crossings)
#
# # special cases
# if cross_pairs == set([(2, 7), (5, 10), (3, 6), (1, 8), (4, 9)]):
# return True
# if cross_pairs == set([(3, 8), (2, 5), (1, 6), (4, 7)]):
# return True
#
# knot_topologies = ['uououo', 'uoouuoou']
# for top in knot_topologies:
# flipped_top = top.replace('u','t').replace('o','u').replace('t','o')
# if top in s and crossings_match(cross_pairs, top, s):
# return True
# if top[::-1] in s and crossings_match(cross_pairs, top[::-1], s):
# return True
# if flipped_top in s and crossings_match(cross_pairs, flipped_top, s):
# return True
# if flipped_top[::-1] in s and crossings_match(cross_pairs, flipped_top[::-1], s):
# return True
#
# if rope_closed:
# return False # There is no chance of it being a knot with one end
# # of the rope crossing the knot accidentally
#
# knot_topology_variations = ['ououuouo', 'ouoououu']
# for top in knot_topology_variations:
# flipped_top = top.replace('u','t').replace('o','u').replace('t','o')
# if top in s and crossings_var_match(cross_pairs, top, s):
# return True
# if top[::-1] in s and crossings_var_match(cross_pairs, top[::-1], s):
# return True
# if flipped_top in s and crossings_var_match(cross_pairs, flipped_top, s):
# return True
# if flipped_top[::-1] in s and crossings_match(cross_pairs, flipped_top[::-1], s):
# return True
#
# return False
which might include code, classes, or functions. Output only the next line. | if isKnot(final_cld): |
Given snippet: <|code_start|> else:
return []
def parse_o(obj, o, value):
if value:
l = value.split()
if len(l) != 6:
raise BadAnnounceError("wrong # fields in o=`%s'"%value)
( obj._o_username, obj._o_sessid, obj._o_version,
obj._o_nettype, obj._o_addrfamily, obj._o_ipaddr ) = tuple(l)
def unparse_o(obj, o):
return ['%s %s %s %s %s %s' % ( obj._o_username, obj._o_sessid,
obj._o_version, obj._o_nettype,
obj._o_addrfamily, obj._o_ipaddr )]
def parse_a(obj, a, text):
words = text.split(':', 1)
if len(words) > 1:
# I don't know what is happening here, but I got a traceback here
# because 'words' was too long before the ,1 was added. The value was:
# ['alt', '1 1 ', ' 55A94DDE 98A2400C *ip address elided* 6086']
# Adding the ,1 seems to fix it but I don't know why. -glyph
attr, attrvalue = words
else:
attr, attrvalue = text, None
if attr == 'rtpmap':
payload,info = attrvalue.split(' ')
entry = rtpmap2canonical(int(payload), attrvalue)
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from rtpmidi.protocols.rtp.formats import RTPDict, PTMarker, PT_AVP
from twisted.python.util import OrderedDict
from time import time
and context:
# Path: rtpmidi/protocols/rtp/formats.py
# class PTMarker:
# class AudioPTMarker(PTMarker):
# class VideoPTMarker(PTMarker):
# class SDPGenerator:
# def __init__(self, name, pt=None, clock=8000, params=1, fmtp=None):
# def __repr__(self):
# def getSDP(self, rtp, extrartp=None):
# PT_PCMU = AudioPTMarker('PCMU', clock=8000, params=1, pt=0)
# PT_GSM = AudioPTMarker('GSM', clock=8000, params=1, pt=3)
# PT_G723 = AudioPTMarker('G723', clock=8000, params=1, pt=4)
# PT_DVI4 = AudioPTMarker('DVI4', clock=8000, params=1, pt=5)
# PT_DVI4_16K = AudioPTMarker('DVI4', clock=16000, params=1, pt=6)
# PT_LPC = AudioPTMarker('LPC', clock=8000, params=1, pt=7)
# PT_PCMA = AudioPTMarker('PCMA', clock=8000, params=1, pt=8)
# PT_G722 = AudioPTMarker('G722', clock=8000, params=1, pt=9)
# PT_L16_STEREO = AudioPTMarker('L16', clock=44100, params=2, pt=10)
# PT_L16 = AudioPTMarker('L16', clock=44100, params=1, pt=11)
# PT_QCELP = AudioPTMarker('QCELP', clock=8000, params=1, pt=12)
# PT_CN = AudioPTMarker('CN', clock=8000, params=1, pt=13)
# PT_G728 = AudioPTMarker('G728', clock=8000, params=1, pt=15)
# PT_DVI4_11K = AudioPTMarker('DVI4', clock=11025, params=1, pt=16)
# PT_DVI4_22K = AudioPTMarker('DVI4', clock=22050, params=1, pt=17)
# PT_G729 = AudioPTMarker('G729', clock=8000, params=1, pt=18)
# PT_AVP = AudioPTMarker('mpeg4-generic', clock=44100, params=1, pt=96)
# PT_SPEEX = AudioPTMarker('speex', clock=8000, params=1)
# PT_SPEEX_16K = AudioPTMarker('speex', clock=16000, params=1)
# PT_G726_40 = AudioPTMarker('G726-40', clock=8000, params=1)
# PT_1016 = AudioPTMarker('1016', clock=8000, params=1, pt=1)
# PT_G726_40 = AudioPTMarker('G726-40', clock=8000, params=1)
# PT_G726_32 = AudioPTMarker('G726-32', clock=8000, params=1)
# PT_G721 = AudioPTMarker('G721', clock=8000, params=1, pt=2)
# PT_G726_24 = AudioPTMarker('G726-24', clock=8000, params=1)
# PT_G726_16 = AudioPTMarker('G726-16', clock=8000, params=1)
# PT_G729D = AudioPTMarker('G729D', clock=8000, params=1)
# PT_G729E = AudioPTMarker('G729E', clock=8000, params=1)
# PT_GSM_EFR = AudioPTMarker('GSM-EFR', clock=8000, params=1)
# PT_ILBC = AudioPTMarker('iLBC', clock=8000, params=1)
# PT_NTE = PTMarker('telephone-event', clock=8000, params=None,
# fmtp='0-16')
# PT_RAW = AudioPTMarker('RAW_L16', clock=8000, params=1)
# PT_CELB = VideoPTMarker('CelB', clock=90000, pt=25)
# PT_JPEG = VideoPTMarker('JPEG', clock=90000, pt=26)
# PT_NV = VideoPTMarker('nv', clock=90000, pt=28)
# PT_H261 = VideoPTMarker('H261', clock=90000, pt=31)
# PT_MPV = VideoPTMarker('MPV', clock=90000, pt=32)
# PT_MP2T = VideoPTMarker('MP2T', clock=90000, pt=33)
# PT_H263 = VideoPTMarker('H263', clock=90000, pt=34)
which might include code, classes, or functions. Output only the next line. | fmt = RTPDict[entry] |
Predict the next line for this snippet: <|code_start|>def parse_o(obj, o, value):
if value:
l = value.split()
if len(l) != 6:
raise BadAnnounceError("wrong # fields in o=`%s'"%value)
( obj._o_username, obj._o_sessid, obj._o_version,
obj._o_nettype, obj._o_addrfamily, obj._o_ipaddr ) = tuple(l)
def unparse_o(obj, o):
return ['%s %s %s %s %s %s' % ( obj._o_username, obj._o_sessid,
obj._o_version, obj._o_nettype,
obj._o_addrfamily, obj._o_ipaddr )]
def parse_a(obj, a, text):
words = text.split(':', 1)
if len(words) > 1:
# I don't know what is happening here, but I got a traceback here
# because 'words' was too long before the ,1 was added. The value was:
# ['alt', '1 1 ', ' 55A94DDE 98A2400C *ip address elided* 6086']
# Adding the ,1 seems to fix it but I don't know why. -glyph
attr, attrvalue = words
else:
attr, attrvalue = text, None
if attr == 'rtpmap':
payload,info = attrvalue.split(' ')
entry = rtpmap2canonical(int(payload), attrvalue)
try:
fmt = RTPDict[entry]
except KeyError:
name,clock,params = entry
<|code_end|>
with the help of current file imports:
from rtpmidi.protocols.rtp.formats import RTPDict, PTMarker, PT_AVP
from twisted.python.util import OrderedDict
from time import time
and context from other files:
# Path: rtpmidi/protocols/rtp/formats.py
# class PTMarker:
# class AudioPTMarker(PTMarker):
# class VideoPTMarker(PTMarker):
# class SDPGenerator:
# def __init__(self, name, pt=None, clock=8000, params=1, fmtp=None):
# def __repr__(self):
# def getSDP(self, rtp, extrartp=None):
# PT_PCMU = AudioPTMarker('PCMU', clock=8000, params=1, pt=0)
# PT_GSM = AudioPTMarker('GSM', clock=8000, params=1, pt=3)
# PT_G723 = AudioPTMarker('G723', clock=8000, params=1, pt=4)
# PT_DVI4 = AudioPTMarker('DVI4', clock=8000, params=1, pt=5)
# PT_DVI4_16K = AudioPTMarker('DVI4', clock=16000, params=1, pt=6)
# PT_LPC = AudioPTMarker('LPC', clock=8000, params=1, pt=7)
# PT_PCMA = AudioPTMarker('PCMA', clock=8000, params=1, pt=8)
# PT_G722 = AudioPTMarker('G722', clock=8000, params=1, pt=9)
# PT_L16_STEREO = AudioPTMarker('L16', clock=44100, params=2, pt=10)
# PT_L16 = AudioPTMarker('L16', clock=44100, params=1, pt=11)
# PT_QCELP = AudioPTMarker('QCELP', clock=8000, params=1, pt=12)
# PT_CN = AudioPTMarker('CN', clock=8000, params=1, pt=13)
# PT_G728 = AudioPTMarker('G728', clock=8000, params=1, pt=15)
# PT_DVI4_11K = AudioPTMarker('DVI4', clock=11025, params=1, pt=16)
# PT_DVI4_22K = AudioPTMarker('DVI4', clock=22050, params=1, pt=17)
# PT_G729 = AudioPTMarker('G729', clock=8000, params=1, pt=18)
# PT_AVP = AudioPTMarker('mpeg4-generic', clock=44100, params=1, pt=96)
# PT_SPEEX = AudioPTMarker('speex', clock=8000, params=1)
# PT_SPEEX_16K = AudioPTMarker('speex', clock=16000, params=1)
# PT_G726_40 = AudioPTMarker('G726-40', clock=8000, params=1)
# PT_1016 = AudioPTMarker('1016', clock=8000, params=1, pt=1)
# PT_G726_40 = AudioPTMarker('G726-40', clock=8000, params=1)
# PT_G726_32 = AudioPTMarker('G726-32', clock=8000, params=1)
# PT_G721 = AudioPTMarker('G721', clock=8000, params=1, pt=2)
# PT_G726_24 = AudioPTMarker('G726-24', clock=8000, params=1)
# PT_G726_16 = AudioPTMarker('G726-16', clock=8000, params=1)
# PT_G729D = AudioPTMarker('G729D', clock=8000, params=1)
# PT_G729E = AudioPTMarker('G729E', clock=8000, params=1)
# PT_GSM_EFR = AudioPTMarker('GSM-EFR', clock=8000, params=1)
# PT_ILBC = AudioPTMarker('iLBC', clock=8000, params=1)
# PT_NTE = PTMarker('telephone-event', clock=8000, params=None,
# fmtp='0-16')
# PT_RAW = AudioPTMarker('RAW_L16', clock=8000, params=1)
# PT_CELB = VideoPTMarker('CelB', clock=90000, pt=25)
# PT_JPEG = VideoPTMarker('JPEG', clock=90000, pt=26)
# PT_NV = VideoPTMarker('nv', clock=90000, pt=28)
# PT_H261 = VideoPTMarker('H261', clock=90000, pt=31)
# PT_MPV = VideoPTMarker('MPV', clock=90000, pt=32)
# PT_MP2T = VideoPTMarker('MP2T', clock=90000, pt=33)
# PT_H263 = VideoPTMarker('H263', clock=90000, pt=34)
, which may contain function names, class names, or code. Output only the next line. | fmt = PTMarker(name, None, clock, params) |
Given snippet: <|code_start|>
def ntp2delta(ticks):
return (ticks - 220898800)
def rtpmap2canonical(code, entry):
if not isinstance(code, int):
raise ValueError(code)
if code < 96:
return code
else:
ocode,desc = entry.split(' ',1)
desc = desc.split('/')
if len(desc) == 2:
desc.append('1') # default channels
name,rate,channels = desc
return (name.lower(),int(rate),int(channels))
if __name__ == "__main__":
#SDP Creation
s = SDP()
s.setServerIP("127.0.0.1")
md = MediaDescription() # defaults to type 'audio'
s.addMediaDescription(md)
md.setServerIP("127.0.0.1")
md.setLocalPort(44000)
#Payload Type
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from rtpmidi.protocols.rtp.formats import RTPDict, PTMarker, PT_AVP
from twisted.python.util import OrderedDict
from time import time
and context:
# Path: rtpmidi/protocols/rtp/formats.py
# class PTMarker:
# class AudioPTMarker(PTMarker):
# class VideoPTMarker(PTMarker):
# class SDPGenerator:
# def __init__(self, name, pt=None, clock=8000, params=1, fmtp=None):
# def __repr__(self):
# def getSDP(self, rtp, extrartp=None):
# PT_PCMU = AudioPTMarker('PCMU', clock=8000, params=1, pt=0)
# PT_GSM = AudioPTMarker('GSM', clock=8000, params=1, pt=3)
# PT_G723 = AudioPTMarker('G723', clock=8000, params=1, pt=4)
# PT_DVI4 = AudioPTMarker('DVI4', clock=8000, params=1, pt=5)
# PT_DVI4_16K = AudioPTMarker('DVI4', clock=16000, params=1, pt=6)
# PT_LPC = AudioPTMarker('LPC', clock=8000, params=1, pt=7)
# PT_PCMA = AudioPTMarker('PCMA', clock=8000, params=1, pt=8)
# PT_G722 = AudioPTMarker('G722', clock=8000, params=1, pt=9)
# PT_L16_STEREO = AudioPTMarker('L16', clock=44100, params=2, pt=10)
# PT_L16 = AudioPTMarker('L16', clock=44100, params=1, pt=11)
# PT_QCELP = AudioPTMarker('QCELP', clock=8000, params=1, pt=12)
# PT_CN = AudioPTMarker('CN', clock=8000, params=1, pt=13)
# PT_G728 = AudioPTMarker('G728', clock=8000, params=1, pt=15)
# PT_DVI4_11K = AudioPTMarker('DVI4', clock=11025, params=1, pt=16)
# PT_DVI4_22K = AudioPTMarker('DVI4', clock=22050, params=1, pt=17)
# PT_G729 = AudioPTMarker('G729', clock=8000, params=1, pt=18)
# PT_AVP = AudioPTMarker('mpeg4-generic', clock=44100, params=1, pt=96)
# PT_SPEEX = AudioPTMarker('speex', clock=8000, params=1)
# PT_SPEEX_16K = AudioPTMarker('speex', clock=16000, params=1)
# PT_G726_40 = AudioPTMarker('G726-40', clock=8000, params=1)
# PT_1016 = AudioPTMarker('1016', clock=8000, params=1, pt=1)
# PT_G726_40 = AudioPTMarker('G726-40', clock=8000, params=1)
# PT_G726_32 = AudioPTMarker('G726-32', clock=8000, params=1)
# PT_G721 = AudioPTMarker('G721', clock=8000, params=1, pt=2)
# PT_G726_24 = AudioPTMarker('G726-24', clock=8000, params=1)
# PT_G726_16 = AudioPTMarker('G726-16', clock=8000, params=1)
# PT_G729D = AudioPTMarker('G729D', clock=8000, params=1)
# PT_G729E = AudioPTMarker('G729E', clock=8000, params=1)
# PT_GSM_EFR = AudioPTMarker('GSM-EFR', clock=8000, params=1)
# PT_ILBC = AudioPTMarker('iLBC', clock=8000, params=1)
# PT_NTE = PTMarker('telephone-event', clock=8000, params=None,
# fmtp='0-16')
# PT_RAW = AudioPTMarker('RAW_L16', clock=8000, params=1)
# PT_CELB = VideoPTMarker('CelB', clock=90000, pt=25)
# PT_JPEG = VideoPTMarker('JPEG', clock=90000, pt=26)
# PT_NV = VideoPTMarker('nv', clock=90000, pt=28)
# PT_H261 = VideoPTMarker('H261', clock=90000, pt=31)
# PT_MPV = VideoPTMarker('MPV', clock=90000, pt=32)
# PT_MP2T = VideoPTMarker('MP2T', clock=90000, pt=33)
# PT_H263 = VideoPTMarker('H263', clock=90000, pt=34)
which might include code, classes, or functions. Output only the next line. | md.addRtpMap(PT_AVP) |
Predict the next line for this snippet: <|code_start|>
class FakeClient(object):
def __init__(self):
pass
def send_midi_data(self, data, time):
pass
class TestMidiIn(unittest.TestCase):
def setUp(self):
fake_client = FakeClient
<|code_end|>
with the help of current file imports:
import sys
from twisted.trial import unittest
from rtpmidi.engines.midi.midi_in import MidiIn
and context from other files:
# Path: rtpmidi/engines/midi/midi_in.py
# class MidiIn(object):
# """
# Midi device input.
#
# Manages a single MIDI input (source) device.
# Can list all input devices.
# """
# def __init__(self, client, verbose=0):
# self.verbose = verbose
# #Init var
# self.midi_device_list = []
# self.midi_device = None
# self.midi_in = None
# #setting looping task
# self.releaser = task.LoopingCall(self._get_input)
# #Launching RTP Client to call after midi time start in order to sync TS
# self.client = client
# #stats
# self.nbNotes = 0
# self.fps_note = 0
# #flag ( 1 == syncronyse with remote peer )
# self.sync = 0
# self.end_flag = True
# #check activity
# self.last_activity = 0
# self.in_activity = False
# #value to set
# #in s (increase it when note frequency is high in order to reduce packet number)
# self.polling_interval = 0.015
# #in ms
# #Time out must be > to polling
# self.time_out = 5
# #Init time is for timestamp in RTP
# self.init_time = pypm.Time()
#
# def start(self):
# """
# Starts polling the selected device.
# One must first select a device !
# @rtype: bool
# Returns success.
# """
# if self.end_flag :
# if self.midi_in is not None:
# self.end_flag = False
# reactor.callInThread(self._polling)
# return True
# else:
# line = "INPUT: you have to set a midi device before start "
# line += "sending midi data"
# print line
# return False
# else:
# line = "INPUT: already sending midi data"
# return False
#
# def stop(self):
# """
# Stops polling the selected device.
# """
# if not self.end_flag:
# self.end_flag = True
#
# def _polling(self):
# """
# Starts a never ending loop in a python thread.
# @rtype: Deferred
# """
# #need by twisted to stop properly the thread
# d = defer.Deferred()
# #setting new scopes
# last_poll = self.last_activity
# midi_in = self.midi_in
# in_activity = self.in_activity
# while not self.end_flag:
# # hasattr is workaround for weird race condition on stop whereby midi_in is an int
# if hasattr(midi_in, 'Poll') and midi_in.Poll():
# last_poll = time.time() * 1000
# reactor.callInThread(self._get_input)
# in_activity = True
# if in_activity and ((time.time() * 1000) - last_poll >= self.time_out):
# #send silent packet after 3ms of inactivity
# self.client.send_silence()
# in_activity = False
# time.sleep(self.polling_interval)
# return d
#
# def get_devices(self):
# """
# Returns the list of MIDI input devices on this computer.
# @rtype: list
# """
# self.midi_device_list = []
# for loop in range(pypm.CountDevices()):
# interf, name, inp, outp, opened = pypm.GetDeviceInfo(loop)
# if inp == 1:
# self.midi_device_list.append([loop,name, opened])
# return self.midi_device_list
#
# def get_device_info(self):
# """
# Returns info about the currently selected device
# """
# return pypm.GetDeviceInfo(self.midi_device)
#
# def set_device(self, device):
# """
# Selects the MIDI device to be polled.
#
# @param device: The device number to choose.
# @type device: int
# @rtype: bool
# @return: Success or not
# """
# #check if device exist
# dev_list = [self.midi_device_list[i][0] for i in range(len(self.midi_device_list))]
# if device in dev_list: # if the number is not in list of input devices
# self.midi_device = device
# if self.midi_in is not None:
# #delete old midi device if present
# del self.midi_in
# #Initializing midi input stream
# self.midi_in = pypm.Input(self.midi_device)
# if self.verbose:
# line = " Midi device in: " + str(self.get_device_info()[1])
# print line
# return True
# else:
# print "INPUT: Invalid midi device selected"
# print dev_list
# return False
#
# def _get_input(self):
# """
# Get input from selected device
# """
# current_time = pypm.Time()
# #Reading Midi Input
# midi_data = self.midi_in.Read(1024)
# if self.verbose:
# print midi_data
# if len(midi_data) > 0:
# reactor.callFromThread(self.client.send_midi_data, midi_data, current_time)
#
# def __del__(self):
# #deleting objects
# del self.client
# del self.midi_in
, which may contain function names, class names, or code. Output only the next line. | self.midi_in = MidiIn(fake_client) |
Based on the snippet: <|code_start|> #Testing content of the list
for i in range(10):
assert(self.list_to_test[i] == 10+i),\
self.fail("Problem with content of the listcirc")
def test_flush(self):
#Test add note on first items
for i in range(10):
self.list_to_test.to_list(i)
#Flushing list
self.list_to_test.flush()
#Testing attribute
assert(len(self.list_to_test)==0), \
self.fail("Problem flushing the list")
assert(self.list_to_test.round==0), \
self.fail("Problem with round attributeflushing the list")
assert(self.list_to_test.index==0), \
self.fail("Problem with index attribute flushing the list")
class TestPacketCirc(TestCase):
"""Testing packet Circ"""
def setUp(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from twisted.trial.unittest import TestCase
from rtpmidi.engines.midi.list_circ import ListCirc, PacketCirc
from rtpmidi.engines.midi.midi_object import OldPacket
and context (classes, functions, sometimes code) from other files:
# Path: rtpmidi/engines/midi/list_circ.py
# class ListCirc(object):
#
# def __init__(self, listeSize):
# self.index = 0
# self.list = []
# self.round = 0
# self.listeSize = listeSize
#
# def to_list(self, note):
# if self.round == 1:
# self._replace_note(note)
# else:
# self._add_note(note)
#
# def _add_note(self, note):
# self.list.append(note)
#
# if self.index == self.listeSize-1:
# self.round = 1
# self.index = 0
# else:
# self.index += 1
#
# def _replace_note(self, note):
# if (self.index == self.listeSize):
# self.index = 0
# self.list[self.index] = note
# else:
# self.list[self.index] = note
# self.index += 1
#
# def flush(self):
# self.list = []
# self.round = 0
# self.index = 0
#
# def __getitem__(self,key):
# return self.list[key]
#
# def __len__(self):
# return len(self.list)
#
# class PacketCirc(ListCirc):
#
# #Recupere une note avec son compteur (numero)
# def find_packet(self, seqNo):
# """Return emplacement of selected packet index the list"""
# res = -1
#
# for i in range(len(self.list)):
# if (self.list[i].seqNo == seqNo):
# res = i
# break
#
# return res
#
# def get_packets(self, checkpoint, act_seq ):
# """Get packets from checkpoint to act seq
# this function is for simplify create_recovery_journal"""
# midi_cmd = []
# #getting pos of element
# checkpoint_pos = self.find_packet(checkpoint)
# act_seq_pos = self.find_packet(act_seq)
#
# #Take care of wrap around in seqNo
#
# if checkpoint >= act_seq:
# if checkpoint_pos < act_seq_pos:
# midi_cmd = self.list[checkpoint_pos+1:act_seq_pos+1]
# else:
# #getting checkpoint -> 0
# midi_cmd = self.list[checkpoint_pos+1:]
#
# #getting 0 -> act_seq
# midi_cmd += self.list[:act_seq_pos+1]
# else:
# #getting checkpoint -> act_seq
# [midi_cmd.append(self.list[i]) \
# for i in range(len(self.list)) \
# if self.list[i].seqNo > checkpoint and \
# self.list[i].seqNo <= act_seq]
#
#
# return midi_cmd
#
# Path: rtpmidi/engines/midi/midi_object.py
# class OldPacket(object):
#
# def __init__(self, seqNo, packet, marker=0):
# self.seqNo = seqNo
# self.packet = packet
# self.marker = marker
. Output only the next line. | self.packet_circ = PacketCirc(10) |
Predict the next line after this snippet: <|code_start|> self.list_to_test.flush()
#Testing attribute
assert(len(self.list_to_test)==0), \
self.fail("Problem flushing the list")
assert(self.list_to_test.round==0), \
self.fail("Problem with round attributeflushing the list")
assert(self.list_to_test.index==0), \
self.fail("Problem with index attribute flushing the list")
class TestPacketCirc(TestCase):
"""Testing packet Circ"""
def setUp(self):
self.packet_circ = PacketCirc(10)
#list to test the packet list
plist = [[[192, 120, 100],0],[[144, 104, 50],1], [[145, 110, 0],2], \
[[145, 112, 0],3], [[144, 124, 50],4], \
[[145, 114, 0],5], [[145, 12, 0],6]]
#test without wrap around
for i in range(10):
#modify plist for each packet
plist_1 = [ [[plist[j][0][0], plist[j][0][1], plist[j][0][2]], \
plist[j][1] + i] for j in range(len(plist)) ]
<|code_end|>
using the current file's imports:
from twisted.trial.unittest import TestCase
from rtpmidi.engines.midi.list_circ import ListCirc, PacketCirc
from rtpmidi.engines.midi.midi_object import OldPacket
and any relevant context from other files:
# Path: rtpmidi/engines/midi/list_circ.py
# class ListCirc(object):
#
# def __init__(self, listeSize):
# self.index = 0
# self.list = []
# self.round = 0
# self.listeSize = listeSize
#
# def to_list(self, note):
# if self.round == 1:
# self._replace_note(note)
# else:
# self._add_note(note)
#
# def _add_note(self, note):
# self.list.append(note)
#
# if self.index == self.listeSize-1:
# self.round = 1
# self.index = 0
# else:
# self.index += 1
#
# def _replace_note(self, note):
# if (self.index == self.listeSize):
# self.index = 0
# self.list[self.index] = note
# else:
# self.list[self.index] = note
# self.index += 1
#
# def flush(self):
# self.list = []
# self.round = 0
# self.index = 0
#
# def __getitem__(self,key):
# return self.list[key]
#
# def __len__(self):
# return len(self.list)
#
# class PacketCirc(ListCirc):
#
# #Recupere une note avec son compteur (numero)
# def find_packet(self, seqNo):
# """Return emplacement of selected packet index the list"""
# res = -1
#
# for i in range(len(self.list)):
# if (self.list[i].seqNo == seqNo):
# res = i
# break
#
# return res
#
# def get_packets(self, checkpoint, act_seq ):
# """Get packets from checkpoint to act seq
# this function is for simplify create_recovery_journal"""
# midi_cmd = []
# #getting pos of element
# checkpoint_pos = self.find_packet(checkpoint)
# act_seq_pos = self.find_packet(act_seq)
#
# #Take care of wrap around in seqNo
#
# if checkpoint >= act_seq:
# if checkpoint_pos < act_seq_pos:
# midi_cmd = self.list[checkpoint_pos+1:act_seq_pos+1]
# else:
# #getting checkpoint -> 0
# midi_cmd = self.list[checkpoint_pos+1:]
#
# #getting 0 -> act_seq
# midi_cmd += self.list[:act_seq_pos+1]
# else:
# #getting checkpoint -> act_seq
# [midi_cmd.append(self.list[i]) \
# for i in range(len(self.list)) \
# if self.list[i].seqNo > checkpoint and \
# self.list[i].seqNo <= act_seq]
#
#
# return midi_cmd
#
# Path: rtpmidi/engines/midi/midi_object.py
# class OldPacket(object):
#
# def __init__(self, seqNo, packet, marker=0):
# self.seqNo = seqNo
# self.packet = packet
# self.marker = marker
. Output only the next line. | packy = OldPacket(i, plist_1, 0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.