Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- class PVData(SurrogatePK, Model): __tablename__ = "pvdata" id = Column(db.Integer(), nullable=False, primary_key=True) created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow) dc_1_u = Column(db.Integer(), nullable=True) dc_1_i = Column(db.Float(), nullable=True) ac_1_u = Column(db.Integer(), nullable=True) ac_1_p = Column(db.Integer(), nullable=True) dc_2_u = Column(db.Integer(), nullable=True) dc_2_i = Column(db.Float(), nullable=True) ac_2_u = Column(db.Integer(), nullable=True) ac_2_p = Column(db.Integer(), nullable=True) dc_3_u = Column(db.Integer(), nullable=True) dc_3_i = Column(db.Float(), nullable=True) ac_3_u = Column(db.Integer(), nullable=True) ac_3_p = Column(db.Integer(), nullable=True) current_power = Column(db.Integer(), nullable=True) daily_energy = Column(db.Float(), nullable=True) total_energy = Column(db.Integer(), nullable=True) <|code_end|> . Use current file imports: import datetime as dt from solarpi.database import ( Column, db, Model, SurrogatePK, ) and context (classes, functions, or code) from other files: # Path: solarpi/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, _id): # def ReferenceCol(tablename, nullable=False, pk_name="id", **kwargs): . Output only the next line.
def __init__(self):
Using the snippet: <|code_start|># -*- coding: utf-8 -*- class Electricity(SurrogatePK, Model): __tablename__ = "electricity_data" id = Column(db.Integer(), nullable=False, primary_key=True) created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow) meter_180 = Column(db.Float(), nullable=True) meter_280 = Column(db.Float(), nullable=True) active_power = Column(db.Float(), nullable=True) <|code_end|> , determine the next line of code. You have imports: import datetime as dt from solarpi.database import ( Column, db, Model, SurrogatePK, ) and context (class names, function names, or code) available: # Path: solarpi/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, _id): # def ReferenceCol(tablename, nullable=False, pk_name="id", **kwargs): . Output only the next line.
def __init__(self):
Based on the snippet: <|code_start|>def get_current_year_earnings(): query = """SELECT sum( delta_280 ) * 0.1702 AS total_earnings -- EUR per kWh FROM ( SELECT max( meter_280 ) - min( meter_280 ) AS delta_280 FROM electricity_data WHERE strftime( '%Y', created_at ) = strftime('%Y', 'now') GROUP BY strftime( '%Y-%m-%d', created_at ) ) q;""" result = db.engine.execute(query).first()[0] return result @cache.cached(timeout=3600, key_prefix="total_earnings") def get_total_earnings(): query = """SELECT sum( delta_280 ) * 0.1702 as total_earnings -- EUR per kWh FROM ( SELECT max( meter_280 ) - min( meter_280 ) AS delta_280 FROM electricity_data GROUP BY strftime( '%Y-%m-%d', created_at ) <|code_end|> , predict the immediate next line with the help of imports: from datetime import datetime, timedelta from sqlalchemy import func from solarpi.electricity.models import Electricity from solarpi.extensions import cache, db and context (classes, functions, sometimes code) from other files: # Path: solarpi/electricity/models.py # class Electricity(SurrogatePK, Model): # __tablename__ = "electricity_data" # id = Column(db.Integer(), nullable=False, primary_key=True) # created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow) # meter_180 = Column(db.Float(), nullable=True) # meter_280 = Column(db.Float(), nullable=True) # active_power = Column(db.Float(), nullable=True) # # Path: solarpi/extensions.py . Output only the next line.
) q;"""
Predict the next line for this snippet: <|code_start|> @cache.cached(timeout=3600, key_prefix="last_year_export") def get_last_year_export(): current_year = datetime.now().year return ( Electricity.query.with_entities(Electricity.meter_280) .filter(func.strftime("%Y", Electricity.created_at) == str(current_year - 1)) .order_by(Electricity.id.desc()) .first() ) @cache.cached(timeout=3600, key_prefix="total_electricity") def get_total_electricity(): return Electricity.query.order_by(Electricity.id.desc()).first() @cache.cached(timeout=3600, key_prefix="current_year_earnings") def get_current_year_earnings(): query = """SELECT sum( delta_280 ) * 0.1702 AS total_earnings -- EUR per kWh FROM ( SELECT max( meter_280 ) - min( meter_280 ) AS delta_280 FROM electricity_data WHERE strftime( '%Y', created_at ) = strftime('%Y', 'now') GROUP BY <|code_end|> with the help of current file imports: from datetime import datetime, timedelta from sqlalchemy import func from solarpi.electricity.models import Electricity from solarpi.extensions import cache, db and context from other files: # Path: solarpi/electricity/models.py # class Electricity(SurrogatePK, Model): # __tablename__ = "electricity_data" # id = Column(db.Integer(), nullable=False, primary_key=True) # created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow) # meter_180 = Column(db.Float(), nullable=True) # meter_280 = Column(db.Float(), nullable=True) # active_power = Column(db.Float(), nullable=True) # # Path: solarpi/extensions.py , which may contain function names, class names, or code. Output only the next line.
strftime( '%Y-%m-%d', created_at )
Continue the code snippet: <|code_start|> blueprint = Blueprint("weather", __name__, url_prefix="/weather", static_folder="../static") @blueprint.route("/daily") @blueprint.route("/daily/<date>") def daily(date=datetime.now().strftime("%Y-%m-%d")): try: current_date = datetime.strptime(date, "%Y-%m-%d") except ValueError: current_date = datetime.strptime("2014-04-21", "%Y-%m-%d") yesterday = current_date - timedelta(days=1) tomorrow = current_date + timedelta(days=1) w = ( Weather.query.with_entities(Weather.created_at, Weather.temp) .filter(Weather.created_at > current_date.strftime("%Y-%m-%d")) .filter(Weather.created_at < tomorrow.strftime("%Y-%m-%d")) .all() ) timestamps_w = [ 1000 * calendar.timegm(datetime.strptime(d.created_at.split(".")[0], "%Y-%m-%dT%H:%M:%S").timetuple()) for d in w ] series_w = [(int(d.temp or 0)) for d in w] daily_chart_data = [list(x) for x in zip(timestamps_w, series_w)] return render_template( "weather/daily.html", data=daily_chart_data, <|code_end|> . Use current file imports: import calendar from datetime import datetime, timedelta from flask import Blueprint, render_template from solarpi.weather.models import Weather and context (classes, functions, or code) from other files: # Path: solarpi/weather/models.py # class Weather(SurrogatePK, Model): # __tablename__ = "weather_data" # # id = Column(db.Integer(), nullable=False, primary_key=True) # created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow) # temp = Column(db.Float(), nullable=True) # pressure = Column(db.Integer(), nullable=True) # temp_min = Column(db.Float(), nullable=True) # temp_max = Column(db.Float(), nullable=True) # humidity = Column(db.Integer(), nullable=True) # wind_speed = Column(db.Float(), nullable=True) # wind_gust = Column(db.Float(), nullable=True) # wind_deg = Column(db.Integer(), nullable=True) # clouds = Column(db.Integer(), nullable=True) # rain = Column(db.Integer(), nullable=True) # snow = Column(db.Integer(), nullable=True) # weather_id = Column(db.Integer(), nullable=True) . Output only the next line.
yesterday=yesterday,
Predict the next line for this snippet: <|code_start|> :return: the number of kWh for the remaining year """ query = """SELECT SUM(energy) AS prediction FROM ( SELECT max(total_energy) - min(total_energy) AS energy FROM pvdata WHERE strftime('%Y', created_at) = strftime('%Y', 'now') UNION SELECT AVG(max_rest_year - min_rest_year) AS energy FROM ( SELECT min(total_energy) min_rest_year, max(total_energy) max_rest_year FROM pvdata WHERE strftime('%j', created_at) > strftime('%j', 'now') AND strftime('%Y', created_at) < strftime('%Y', 'now') GROUP BY strftime('%Y', created_at) ) q );""" result = db.engine.execute(query) <|code_end|> with the help of current file imports: import calendar from datetime import datetime, timedelta from sqlalchemy import func from solarpi.extensions import db, cache from solarpi.pvdata.models import PVData and context from other files: # Path: solarpi/extensions.py # # Path: solarpi/pvdata/models.py # class PVData(SurrogatePK, Model): # __tablename__ = "pvdata" # # id = Column(db.Integer(), nullable=False, primary_key=True) # created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow) # dc_1_u = Column(db.Integer(), nullable=True) # dc_1_i = Column(db.Float(), nullable=True) # ac_1_u = Column(db.Integer(), nullable=True) # ac_1_p = Column(db.Integer(), nullable=True) # dc_2_u = Column(db.Integer(), nullable=True) # dc_2_i = Column(db.Float(), nullable=True) # ac_2_u = Column(db.Integer(), nullable=True) # ac_2_p = Column(db.Integer(), nullable=True) # dc_3_u = Column(db.Integer(), nullable=True) # dc_3_i = Column(db.Float(), nullable=True) # ac_3_u = Column(db.Integer(), nullable=True) # ac_3_p = Column(db.Integer(), nullable=True) # current_power = Column(db.Integer(), nullable=True) # daily_energy = Column(db.Float(), nullable=True) # total_energy = Column(db.Integer(), nullable=True) , which may contain function names, class names, or code. Output only the next line.
return result
Based on the snippet: <|code_start|> query = """SELECT SUM(energy) AS prediction FROM ( SELECT max(total_energy) - min(total_energy) AS energy FROM pvdata WHERE strftime('%Y', created_at) = strftime('%Y', 'now') UNION SELECT AVG(max_rest_year - min_rest_year) AS energy FROM ( SELECT min(total_energy) min_rest_year, max(total_energy) max_rest_year FROM pvdata WHERE strftime('%j', created_at) > strftime('%j', 'now') AND strftime('%Y', created_at) < strftime('%Y', 'now') GROUP BY strftime('%Y', created_at) ) q );""" result = db.engine.execute(query) return result <|code_end|> , predict the immediate next line with the help of imports: import calendar from datetime import datetime, timedelta from sqlalchemy import func from solarpi.extensions import db, cache from solarpi.pvdata.models import PVData and context (classes, functions, sometimes code) from other files: # Path: solarpi/extensions.py # # Path: solarpi/pvdata/models.py # class PVData(SurrogatePK, Model): # __tablename__ = "pvdata" # # id = Column(db.Integer(), nullable=False, primary_key=True) # created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow) # dc_1_u = Column(db.Integer(), nullable=True) # dc_1_i = Column(db.Float(), nullable=True) # ac_1_u = Column(db.Integer(), nullable=True) # ac_1_p = Column(db.Integer(), nullable=True) # dc_2_u = Column(db.Integer(), nullable=True) # dc_2_i = Column(db.Float(), nullable=True) # ac_2_u = Column(db.Integer(), nullable=True) # ac_2_p = Column(db.Integer(), nullable=True) # dc_3_u = Column(db.Integer(), nullable=True) # dc_3_i = Column(db.Float(), nullable=True) # ac_3_u = Column(db.Integer(), nullable=True) # ac_3_p = Column(db.Integer(), nullable=True) # current_power = Column(db.Integer(), nullable=True) # daily_energy = Column(db.Float(), nullable=True) # total_energy = Column(db.Integer(), nullable=True) . Output only the next line.
def get_efficiency(pv):
Here is a snippet: <|code_start|> class ConfigReader(object): def __init__(self, config_file_path): self._config = self._read(config_file_path) def _read(self, config_file_path): try: _, ext = os.path.splitext(config_file_path) with open(config_file_path) as fin: if ext == ".json": data = json.load(fin) else: data = yaml.safe_load(fin) <|code_end|> . Write the next line using the current file imports: import yaml import json import os.path from .util import string and context from other files: # Path: dotbot/util/string.py # def indent_lines(string, amount=2, delimiter="\n"): , which may include functions, classes, or code. Output only the next line.
return data
Based on the snippet: <|code_start|> with open(os.devnull) as devnull: git_hash = subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=os.path.dirname(os.path.abspath(__file__)), stderr=devnull, ) hash_msg = " (git %s)" % git_hash[:10] except (OSError, subprocess.CalledProcessError): hash_msg = "" print("Dotbot version %s%s" % (dotbot.__version__, hash_msg)) exit(0) if options.super_quiet: log.set_level(Level.WARNING) if options.quiet: log.set_level(Level.INFO) if options.verbose > 0: log.set_level(Level.DEBUG) if options.force_color and options.no_color: log.error("`--force-color` and `--no-color` cannot both be provided") exit(1) elif options.force_color: log.use_color(True) elif options.no_color: log.use_color(False) else: log.use_color(sys.stdout.isatty()) plugin_directories = list(options.plugin_dirs) if not options.disable_built_in_plugins: <|code_end|> , predict the immediate next line with the help of imports: import os, glob import sys import dotbot import os import subprocess from argparse import ArgumentParser, RawTextHelpFormatter from .config import ConfigReader, ReadingError from .dispatcher import Dispatcher, DispatchError from .messenger import Messenger from .messenger import Level from .util import module from .plugins import Clean, Create, Link, Shell and context (classes, functions, sometimes code) from other files: # Path: dotbot/config.py # class ConfigReader(object): # def __init__(self, config_file_path): # self._config = self._read(config_file_path) # # def _read(self, config_file_path): # try: # _, ext = os.path.splitext(config_file_path) # with open(config_file_path) as fin: # if ext == ".json": # data = json.load(fin) # else: # data = yaml.safe_load(fin) # return data # except Exception as e: # msg = string.indent_lines(str(e)) # raise ReadingError("Could not read config file:\n%s" % msg) # # def get_config(self): # return self._config # # class ReadingError(Exception): # pass # # Path: dotbot/dispatcher.py # class Dispatcher(object): # def __init__( # self, base_directory, only=None, skip=None, exit_on_failure=False, options=Namespace() # ): # self._log = Messenger() # self._setup_context(base_directory, options) # self._load_plugins() # self._only = only # self._skip = skip # self._exit = exit_on_failure # # def _setup_context(self, base_directory, options): # path = os.path.abspath(os.path.expanduser(base_directory)) # if not os.path.exists(path): # raise DispatchError("Nonexistent base directory") # self._context = Context(path, options) # # def dispatch(self, tasks): # success = True # for task in tasks: # for action in task: # if ( # self._only is not None # and action not in self._only # or self._skip is not None # and action in self._skip # ) and action != "defaults": # self._log.info("Skipping action %s" % action) # continue # handled = False # if action == "defaults": # self._context.set_defaults(task[action]) # replace, not update # handled = True # # keep going, let other plugins handle this if they want # for plugin in self._plugins: # if plugin.can_handle(action): # try: # local_success = plugin.handle(action, task[action]) # if not local_success and self._exit: # # The action has failed exit # self._log.error("Action %s failed" % action) # return False # success &= local_success # handled = True # except Exception as err: # self._log.error( # "An error was encountered while executing action %s" % action # ) # self._log.debug(err) # if self._exit: # # There was an execption exit # return False # if not handled: # success = False # self._log.error("Action %s not handled" % action) # if self._exit: # # Invalid action exit # return False # return success # # def _load_plugins(self): # self._plugins = [plugin(self._context) for plugin in Plugin.__subclasses__()] # # class DispatchError(Exception): # pass # # Path: dotbot/util/module.py # def load(path): # def load_module(module_name, path): # def load_module(module_name, path): # def load_module(module_name, path): . Output only the next line.
plugin_paths = []
Next line prediction: <|code_start|> log = Messenger() try: parser = ArgumentParser(formatter_class=RawTextHelpFormatter) add_options(parser) options = parser.parse_args() if options.version: try: with open(os.devnull) as devnull: git_hash = subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=os.path.dirname(os.path.abspath(__file__)), stderr=devnull, ) hash_msg = " (git %s)" % git_hash[:10] except (OSError, subprocess.CalledProcessError): hash_msg = "" print("Dotbot version %s%s" % (dotbot.__version__, hash_msg)) exit(0) if options.super_quiet: log.set_level(Level.WARNING) if options.quiet: log.set_level(Level.INFO) if options.verbose > 0: log.set_level(Level.DEBUG) if options.force_color and options.no_color: log.error("`--force-color` and `--no-color` cannot both be provided") exit(1) elif options.force_color: log.use_color(True) <|code_end|> . Use current file imports: (import os, glob import sys import dotbot import os import subprocess from argparse import ArgumentParser, RawTextHelpFormatter from .config import ConfigReader, ReadingError from .dispatcher import Dispatcher, DispatchError from .messenger import Messenger from .messenger import Level from .util import module from .plugins import Clean, Create, Link, Shell) and context including class names, function names, or small code snippets from other files: # Path: dotbot/config.py # class ConfigReader(object): # def __init__(self, config_file_path): # self._config = self._read(config_file_path) # # def _read(self, config_file_path): # try: # _, ext = os.path.splitext(config_file_path) # with open(config_file_path) as fin: # if ext == ".json": # data = json.load(fin) # else: # data = yaml.safe_load(fin) # return data # except Exception as e: # msg = string.indent_lines(str(e)) # raise ReadingError("Could not read config file:\n%s" % msg) # # def get_config(self): # return self._config # # class ReadingError(Exception): # pass # # Path: dotbot/dispatcher.py # class Dispatcher(object): # def __init__( # self, base_directory, only=None, skip=None, exit_on_failure=False, options=Namespace() # ): # self._log = Messenger() # self._setup_context(base_directory, options) # self._load_plugins() # self._only = only # self._skip = skip # self._exit = exit_on_failure # # def _setup_context(self, base_directory, options): # path = os.path.abspath(os.path.expanduser(base_directory)) # if not os.path.exists(path): # raise DispatchError("Nonexistent base directory") # self._context = Context(path, options) # # def dispatch(self, tasks): # success = True # for task in tasks: # for action in task: # if ( # self._only is not None # and action not in self._only # or self._skip is not None # and action in self._skip # ) and action != "defaults": # self._log.info("Skipping action %s" % action) # continue # handled = False # if action == "defaults": # self._context.set_defaults(task[action]) # replace, not update # handled = True # # keep going, let other plugins handle this if they want # for plugin in self._plugins: # if plugin.can_handle(action): # try: # local_success = plugin.handle(action, task[action]) # if not local_success and self._exit: # # The action has failed exit # self._log.error("Action %s failed" % action) # return False # success &= local_success # handled = True # except Exception as err: # self._log.error( # "An error was encountered while executing action %s" % action # ) # self._log.debug(err) # if self._exit: # # There was an execption exit # return False # if not handled: # success = False # self._log.error("Action %s not handled" % action) # if self._exit: # # Invalid action exit # return False # return success # # def _load_plugins(self): # self._plugins = [plugin(self._context) for plugin in Plugin.__subclasses__()] # # class DispatchError(Exception): # pass # # Path: dotbot/util/module.py # def load(path): # def load_module(module_name, path): # def load_module(module_name, path): # def load_module(module_name, path): . Output only the next line.
elif options.no_color:
Given snippet: <|code_start|> if options.force_color and options.no_color: log.error("`--force-color` and `--no-color` cannot both be provided") exit(1) elif options.force_color: log.use_color(True) elif options.no_color: log.use_color(False) else: log.use_color(sys.stdout.isatty()) plugin_directories = list(options.plugin_dirs) if not options.disable_built_in_plugins: plugin_paths = [] for directory in plugin_directories: for plugin_path in glob.glob(os.path.join(directory, "*.py")): plugin_paths.append(plugin_path) for plugin_path in options.plugins: plugin_paths.append(plugin_path) for plugin_path in plugin_paths: abspath = os.path.abspath(plugin_path) module.load(abspath) if not options.config_file: log.error("No configuration file specified") exit(1) tasks = read_config(options.config_file) if tasks is None: log.warning("Configuration file is empty, no work to do") tasks = [] if not isinstance(tasks, list): raise ReadingError("Configuration file must be a list of tasks") <|code_end|> , continue by predicting the next line. Consider current file imports: import os, glob import sys import dotbot import os import subprocess from argparse import ArgumentParser, RawTextHelpFormatter from .config import ConfigReader, ReadingError from .dispatcher import Dispatcher, DispatchError from .messenger import Messenger from .messenger import Level from .util import module from .plugins import Clean, Create, Link, Shell and context: # Path: dotbot/config.py # class ConfigReader(object): # def __init__(self, config_file_path): # self._config = self._read(config_file_path) # # def _read(self, config_file_path): # try: # _, ext = os.path.splitext(config_file_path) # with open(config_file_path) as fin: # if ext == ".json": # data = json.load(fin) # else: # data = yaml.safe_load(fin) # return data # except Exception as e: # msg = string.indent_lines(str(e)) # raise ReadingError("Could not read config file:\n%s" % msg) # # def get_config(self): # return self._config # # class ReadingError(Exception): # pass # # Path: dotbot/dispatcher.py # class Dispatcher(object): # def __init__( # self, base_directory, only=None, skip=None, exit_on_failure=False, options=Namespace() # ): # self._log = Messenger() # self._setup_context(base_directory, options) # self._load_plugins() # self._only = only # self._skip = skip # self._exit = exit_on_failure # # def _setup_context(self, base_directory, options): # path = os.path.abspath(os.path.expanduser(base_directory)) # if not os.path.exists(path): # raise DispatchError("Nonexistent base directory") # self._context = Context(path, options) # # def dispatch(self, tasks): # success = True # for task in tasks: # for action in task: # if ( # self._only is not None # and action not in self._only # or self._skip is not None # and action in self._skip # ) and action != "defaults": # self._log.info("Skipping action %s" % action) # continue # handled = False # if action == "defaults": # self._context.set_defaults(task[action]) # replace, not update # handled = True # # keep going, let other plugins handle this if they want # for plugin in self._plugins: # if plugin.can_handle(action): # try: # local_success = plugin.handle(action, task[action]) # if not local_success and self._exit: # # The action has failed exit # self._log.error("Action %s failed" % action) # return False # success &= local_success # handled = True # except Exception as err: # self._log.error( # "An error was encountered while executing action %s" % action # ) # self._log.debug(err) # if self._exit: # # There was an execption exit # return False # if not handled: # success = False # self._log.error("Action %s not handled" % action) # if self._exit: # # Invalid action exit # return False # return success # # def _load_plugins(self): # self._plugins = [plugin(self._context) for plugin in Plugin.__subclasses__()] # # class DispatchError(Exception): # pass # # Path: dotbot/util/module.py # def load(path): # def load_module(module_name, path): # def load_module(module_name, path): # def load_module(module_name, path): which might include code, classes, or functions. Output only the next line.
if options.base_directory:
Given the code snippet: <|code_start|> def main(): log = Messenger() try: parser = ArgumentParser(formatter_class=RawTextHelpFormatter) add_options(parser) options = parser.parse_args() if options.version: try: with open(os.devnull) as devnull: git_hash = subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=os.path.dirname(os.path.abspath(__file__)), stderr=devnull, ) hash_msg = " (git %s)" % git_hash[:10] except (OSError, subprocess.CalledProcessError): hash_msg = "" print("Dotbot version %s%s" % (dotbot.__version__, hash_msg)) exit(0) if options.super_quiet: log.set_level(Level.WARNING) if options.quiet: log.set_level(Level.INFO) if options.verbose > 0: log.set_level(Level.DEBUG) if options.force_color and options.no_color: log.error("`--force-color` and `--no-color` cannot both be provided") exit(1) <|code_end|> , generate the next line using the imports in this file: import os, glob import sys import dotbot import os import subprocess from argparse import ArgumentParser, RawTextHelpFormatter from .config import ConfigReader, ReadingError from .dispatcher import Dispatcher, DispatchError from .messenger import Messenger from .messenger import Level from .util import module from .plugins import Clean, Create, Link, Shell and context (functions, classes, or occasionally code) from other files: # Path: dotbot/config.py # class ConfigReader(object): # def __init__(self, config_file_path): # self._config = self._read(config_file_path) # # def _read(self, config_file_path): # try: # _, ext = os.path.splitext(config_file_path) # with open(config_file_path) as fin: # if ext == ".json": # data = json.load(fin) # else: # data = yaml.safe_load(fin) # return data # except Exception as e: # msg = string.indent_lines(str(e)) # raise ReadingError("Could not read config file:\n%s" % msg) # # def get_config(self): # return self._config # # class ReadingError(Exception): # pass # # Path: dotbot/dispatcher.py # class Dispatcher(object): # def __init__( # self, base_directory, only=None, skip=None, exit_on_failure=False, options=Namespace() # ): # self._log = Messenger() # self._setup_context(base_directory, options) # self._load_plugins() # self._only = only # self._skip = skip # self._exit = exit_on_failure # # def _setup_context(self, base_directory, options): # path = os.path.abspath(os.path.expanduser(base_directory)) # if not os.path.exists(path): # raise DispatchError("Nonexistent base directory") # self._context = Context(path, options) # # def dispatch(self, tasks): # success = True # for task in tasks: # for action in task: # if ( # self._only is not None # and action not in self._only # or self._skip is not None # and action in self._skip # ) and action != "defaults": # self._log.info("Skipping action %s" % action) # continue # handled = False # if action == "defaults": # self._context.set_defaults(task[action]) # replace, not update # handled = True # # keep going, let other plugins handle this if they want # for plugin in self._plugins: # if plugin.can_handle(action): # try: # local_success = plugin.handle(action, task[action]) # if not local_success and self._exit: # # The action has failed exit # self._log.error("Action %s failed" % action) # return False # success &= local_success # handled = True # except Exception as err: # self._log.error( # "An error was encountered while executing action %s" % action # ) # self._log.debug(err) # if self._exit: # # There was an execption exit # return False # if not handled: # success = False # self._log.error("Action %s not handled" % action) # if self._exit: # # Invalid action exit # return False # return success # # def _load_plugins(self): # self._plugins = [plugin(self._context) for plugin in Plugin.__subclasses__()] # # class DispatchError(Exception): # pass # # Path: dotbot/util/module.py # def load(path): # def load_module(module_name, path): # def load_module(module_name, path): # def load_module(module_name, path): . Output only the next line.
elif options.force_color:
Predict the next line after this snippet: <|code_start|> try: with open(os.devnull) as devnull: git_hash = subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=os.path.dirname(os.path.abspath(__file__)), stderr=devnull, ) hash_msg = " (git %s)" % git_hash[:10] except (OSError, subprocess.CalledProcessError): hash_msg = "" print("Dotbot version %s%s" % (dotbot.__version__, hash_msg)) exit(0) if options.super_quiet: log.set_level(Level.WARNING) if options.quiet: log.set_level(Level.INFO) if options.verbose > 0: log.set_level(Level.DEBUG) if options.force_color and options.no_color: log.error("`--force-color` and `--no-color` cannot both be provided") exit(1) elif options.force_color: log.use_color(True) elif options.no_color: log.use_color(False) else: log.use_color(sys.stdout.isatty()) plugin_directories = list(options.plugin_dirs) <|code_end|> using the current file's imports: import os, glob import sys import dotbot import os import subprocess from argparse import ArgumentParser, RawTextHelpFormatter from .config import ConfigReader, ReadingError from .dispatcher import Dispatcher, DispatchError from .messenger import Messenger from .messenger import Level from .util import module from .plugins import Clean, Create, Link, Shell and any relevant context from other files: # Path: dotbot/config.py # class ConfigReader(object): # def __init__(self, config_file_path): # self._config = self._read(config_file_path) # # def _read(self, config_file_path): # try: # _, ext = os.path.splitext(config_file_path) # with open(config_file_path) as fin: # if ext == ".json": # data = json.load(fin) # else: # data = yaml.safe_load(fin) # return data # except Exception as e: # msg = string.indent_lines(str(e)) # raise ReadingError("Could not read config file:\n%s" % msg) # # def get_config(self): # return self._config # # class ReadingError(Exception): # pass # # Path: dotbot/dispatcher.py # class Dispatcher(object): # def __init__( # self, base_directory, only=None, skip=None, exit_on_failure=False, options=Namespace() # ): # self._log = Messenger() # self._setup_context(base_directory, options) # self._load_plugins() # self._only = only # self._skip = skip # self._exit = exit_on_failure # # def _setup_context(self, base_directory, options): # path = os.path.abspath(os.path.expanduser(base_directory)) # if not os.path.exists(path): # raise DispatchError("Nonexistent base directory") # self._context = Context(path, options) # # def dispatch(self, tasks): # success = True # for task in tasks: # for action in task: # if ( # self._only is not None # and action not in self._only # or self._skip is not None # and action in self._skip # ) and action != "defaults": # self._log.info("Skipping action %s" % action) # continue # handled = False # if action == "defaults": # self._context.set_defaults(task[action]) # replace, not update # handled = True # # keep going, let other plugins handle this if they want # for plugin in self._plugins: # if plugin.can_handle(action): # try: # local_success = plugin.handle(action, task[action]) # if not local_success and self._exit: # # The action has failed exit # self._log.error("Action %s failed" % action) # return False # success &= local_success # handled = True # except Exception as err: # self._log.error( # "An error was encountered while executing action %s" % action # ) # self._log.debug(err) # if self._exit: # # There was an execption exit # return False # if not handled: # success = False # self._log.error("Action %s not handled" % action) # if self._exit: # # Invalid action exit # return False # return success # # def _load_plugins(self): # self._plugins = [plugin(self._context) for plugin in Plugin.__subclasses__()] # # class DispatchError(Exception): # pass # # Path: dotbot/util/module.py # def load(path): # def load_module(module_name, path): # def load_module(module_name, path): # def load_module(module_name, path): . Output only the next line.
if not options.disable_built_in_plugins:
Here is a snippet: <|code_start|> class Dispatcher(object): def __init__( self, base_directory, only=None, skip=None, exit_on_failure=False, options=Namespace() ): self._log = Messenger() self._setup_context(base_directory, options) self._load_plugins() self._only = only self._skip = skip self._exit = exit_on_failure def _setup_context(self, base_directory, options): path = os.path.abspath(os.path.expanduser(base_directory)) if not os.path.exists(path): raise DispatchError("Nonexistent base directory") self._context = Context(path, options) def dispatch(self, tasks): success = True for task in tasks: for action in task: if ( self._only is not None and action not in self._only or self._skip is not None <|code_end|> . Write the next line using the current file imports: import os from argparse import Namespace from .plugin import Plugin from .messenger import Messenger from .context import Context and context from other files: # Path: dotbot/plugin.py # class Plugin(object): # """ # Abstract base class for commands that process directives. # """ # # def __init__(self, context): # self._context = context # self._log = Messenger() # # def can_handle(self, directive): # """ # Returns true if the Plugin can handle the directive. # """ # raise NotImplementedError # # def handle(self, directive, data): # """ # Executes the directive. # # Returns true if the Plugin successfully handled the directive. # """ # raise NotImplementedError # # Path: dotbot/context.py # class Context(object): # """ # Contextual data and information for plugins. # """ # # def __init__(self, base_directory, options=Namespace()): # self._base_directory = base_directory # self._defaults = {} # self._options = options # pass # # def set_base_directory(self, base_directory): # self._base_directory = base_directory # # def base_directory(self, canonical_path=True): # base_directory = self._base_directory # if canonical_path: # base_directory = os.path.realpath(base_directory) # return base_directory # # def set_defaults(self, defaults): # self._defaults = defaults # # def defaults(self): # return copy.deepcopy(self._defaults) # # def options(self): # return copy.deepcopy(self._options) , which may include functions, classes, or code. Output only the next line.
and action in self._skip
Continue the code snippet: <|code_start|> if not os.path.exists(path): raise DispatchError("Nonexistent base directory") self._context = Context(path, options) def dispatch(self, tasks): success = True for task in tasks: for action in task: if ( self._only is not None and action not in self._only or self._skip is not None and action in self._skip ) and action != "defaults": self._log.info("Skipping action %s" % action) continue handled = False if action == "defaults": self._context.set_defaults(task[action]) # replace, not update handled = True # keep going, let other plugins handle this if they want for plugin in self._plugins: if plugin.can_handle(action): try: local_success = plugin.handle(action, task[action]) if not local_success and self._exit: # The action has failed exit self._log.error("Action %s failed" % action) return False success &= local_success <|code_end|> . Use current file imports: import os from argparse import Namespace from .plugin import Plugin from .messenger import Messenger from .context import Context and context (classes, functions, or code) from other files: # Path: dotbot/plugin.py # class Plugin(object): # """ # Abstract base class for commands that process directives. # """ # # def __init__(self, context): # self._context = context # self._log = Messenger() # # def can_handle(self, directive): # """ # Returns true if the Plugin can handle the directive. # """ # raise NotImplementedError # # def handle(self, directive, data): # """ # Executes the directive. # # Returns true if the Plugin successfully handled the directive. # """ # raise NotImplementedError # # Path: dotbot/context.py # class Context(object): # """ # Contextual data and information for plugins. # """ # # def __init__(self, base_directory, options=Namespace()): # self._base_directory = base_directory # self._defaults = {} # self._options = options # pass # # def set_base_directory(self, base_directory): # self._base_directory = base_directory # # def base_directory(self, canonical_path=True): # base_directory = self._base_directory # if canonical_path: # base_directory = os.path.realpath(base_directory) # return base_directory # # def set_defaults(self, defaults): # self._defaults = defaults # # def defaults(self): # return copy.deepcopy(self._defaults) # # def options(self): # return copy.deepcopy(self._options) . Output only the next line.
handled = True
Based on the snippet: <|code_start|> class Messenger(with_metaclass(Singleton, object)): def __init__(self, level=Level.LOWINFO): self.set_level(level) self.use_color(True) def set_level(self, level): self._level = level def use_color(self, yesno): self._use_color = yesno def log(self, level, message): <|code_end|> , predict the immediate next line with the help of imports: from ..util.singleton import Singleton from ..util.compat import with_metaclass from .color import Color from .level import Level and context (classes, functions, sometimes code) from other files: # Path: dotbot/util/compat.py # def with_metaclass(meta, *bases): # class metaclass(meta): # def __new__(cls, name, this_bases, d): # return meta(name, bases, d) # # return type.__new__(metaclass, "temporary_class", (), {}) # # Path: dotbot/messenger/color.py # class Color(object): # NONE = "" # RESET = "\033[0m" # RED = "\033[91m" # GREEN = "\033[92m" # YELLOW = "\033[93m" # BLUE = "\033[94m" # MAGENTA = "\033[95m" . Output only the next line.
if level >= self._level:
Given the following code snippet before the placeholder: <|code_start|> class Messenger(with_metaclass(Singleton, object)): def __init__(self, level=Level.LOWINFO): self.set_level(level) self.use_color(True) def set_level(self, level): self._level = level def use_color(self, yesno): self._use_color = yesno def log(self, level, message): if level >= self._level: print("%s%s%s" % (self._color(level), message, self._reset())) def debug(self, message): self.log(Level.DEBUG, message) <|code_end|> , predict the next line using imports from the current file: from ..util.singleton import Singleton from ..util.compat import with_metaclass from .color import Color from .level import Level and context including class names, function names, and sometimes code from other files: # Path: dotbot/util/compat.py # def with_metaclass(meta, *bases): # class metaclass(meta): # def __new__(cls, name, this_bases, d): # return meta(name, bases, d) # # return type.__new__(metaclass, "temporary_class", (), {}) # # Path: dotbot/messenger/color.py # class Color(object): # NONE = "" # RESET = "\033[0m" # RED = "\033[91m" # GREEN = "\033[92m" # YELLOW = "\033[93m" # BLUE = "\033[94m" # MAGENTA = "\033[95m" . Output only the next line.
def lowinfo(self, message):
Given the following code snippet before the placeholder: <|code_start|># Script to compare Snack formant methods on Windows # There is a known discrepancy between Snack formants calculated using # the full Snack Tcl library ('tcl' method) and the Windows standalone # executable ('exe' method) # Licensed under Apache v2 (see LICENSE) wav_dir = 'test/data/sound-files' # Find all .wav files in test/data directory wav_files = glob.glob(os.path.join(wav_dir, '*.wav')) for wav_file in wav_files: print('Processing wav file {}'.format(wav_file)) # Generate raw Snack formant samples # Use VoiceSauce default parameter values estimates_raw_tcl = snack_raw_formants(wav_file, 'tcl', frame_shift=1, window_size=25, pre_emphasis=0.96, lpc_order=12, tcl_shell_cmd = 'tclsh') estimates_raw_exe = snack_raw_formants(wav_file, 'exe', frame_shift=1, window_size=25, pre_emphasis=0.96, lpc_order=12) <|code_end|> , predict the next line using imports from the current file: import sys import os import glob import numpy as np import matplotlib.pyplot as plt from opensauce.snack import snack_raw_formants, sformant_names and context including class names, function names, and sometimes code from other files: # Path: opensauce/snack.py # def snack_pitch(wav_fn, method, data_len, frame_shift=1, # window_size=25, max_pitch=500, min_pitch=40, # tcl_shell_cmd=None): # def snack_raw_pitch(wav_fn, method, frame_shift=1, window_size=25, # max_pitch=500, min_pitch=40, tcl_shell_cmd=None): # def snack_raw_pitch_exe(wav_fn, frame_shift, window_size, max_pitch, min_pitch): # pragma: no cover # def snack_raw_pitch_python(wav_fn, frame_shift, window_size, max_pitch, min_pitch): # def snack_raw_pitch_tcl(wav_fn, frame_shift, window_size, max_pitch, min_pitch, tcl_shell_cmd): # def snack_formants(wav_fn, method, data_len, frame_shift=1, # window_size=25, pre_emphasis=0.96, lpc_order=12, # tcl_shell_cmd=None): # def snack_raw_formants(wav_fn, method, frame_shift=1, window_size=25, # pre_emphasis=0.96, lpc_order=12, tcl_shell_cmd=None): # def snack_raw_formants_exe(wav_fn, frame_shift, window_size, pre_emphasis, lpc_order): # pragma: no cover # def snack_raw_formants_python(wav_fn, frame_shift, window_size, pre_emphasis, lpc_order): # def snack_raw_formants_tcl(wav_fn, frame_shift, window_size, pre_emphasis, lpc_order, tcl_shell_cmd): . Output only the next line.
fig = plt.figure(figsize=(8,8))
Given snippet: <|code_start|> def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--preserve', dest='preserve', default=False, action='store_true', help='Exit normally if any accounts already exist.', ) parser.add_argument( '--currency', dest='currency', help='Account currencies, can be specified multiple times. Defaults to the default currency setting.', nargs='+', ) def handle(self, *args, **options): if options.get('preserve') and Account.objects.count(): self.stdout.write('Exiting normally because accounts already exist and --preserve flag was present') if options.get('currency'): currency = options['currency'] else: try: currency = Settings.objects.get().default_currency except Settings.DoesNotExist: raise CommandError('No currency specified by either --currency or by the swiftwind settings.') kw = dict(currencies=currency) T = Account.TYPES assets = Account.objects.create(name='Assets', code='1', type=T.asset, **kw) liabilities = Account.objects.create(name='Liabilities', code='2', type=T.liability, **kw) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf import settings from django.core.management.base import BaseCommand, CommandError from hordak.models import Account from swiftwind.settings.models import Settings and context: # Path: swiftwind/settings/models.py # class Settings(models.Model): # """Store application-wide settings # # Each field is one setting. Only once instance of Settings can be created. # # The model is intentionally named Settings rather than Setting (as would # be the Django convention), as a single model holds many settings. # """ # default_currency = models.CharField(max_length=3, choices=CURRENCY_CHOICES, default='EUR') # additional_currencies = ArrayField(base_field=models.CharField(choices=CURRENCY_CHOICES, default=[], max_length=3), # choices=CURRENCY_CHOICES, # needed? # default=[], blank=True) # payment_information = models.TextField(default='', blank=True, # help_text='Enter information on how payment should be made, such as the ' # 'bank account details housemates should pay into.') # email_from_address = models.EmailField(default='', blank=True, # help_text='What email address should emails appear to be sent from?') # use_https = models.BooleanField(default=False) # # tellerio_enable = models.BooleanField(default=False, verbose_name='Enable daily teller.io imports') # tellerio_token = models.CharField(max_length=100) # tellerio_account_id = models.CharField(max_length=100) # # from_email = models.EmailField(default='', blank=True) # smtp_host = models.CharField(max_length=100, default='', blank=True) # smtp_port = models.IntegerField(default=None, blank=True, null=True) # smtp_user = models.CharField(max_length=100, default='', blank=True) # smtp_password = models.CharField(max_length=100, default='', blank=True) # smtp_use_tls = models.BooleanField(default=False) # smtp_use_ssl = models.BooleanField(default=False) # smtp_subject_prefix = models.CharField(max_length=100, default='[swiftwind] ', blank=True) # # objects = SettingsManager() # # class Meta: # verbose_name_plural = 'settings' # # def save(self, *args, **kwargs): # if not self.pk and Settings.objects.exists(): # raise CannotCreateMultipleSettingsInstances('Only one Settings instance maybe created') # super(Settings, self).save(*args, **kwargs) # # TODO: Push changes into cache (possibly following a refresh_from_db() call) # # @property # def currencies(self): # return sorted({self.default_currency} | set(self.additional_currencies)) which might include code, classes, or functions. Output only the next line.
equity = Account.objects.create(name='Equity', code='3', type=T.equity, **kw)
Here is a snippet: <|code_start|> @shared_task @transaction.atomic() def notify_housemates(): for billing_cycle in BillingCycle.objects.filter(transactions_created=True, statements_sent=False): billing_cycle.notify_housemates() @shared_task @transaction.atomic() def import_tellerio(): settings = Settings.objects.get() if settings.tellerio_enable: <|code_end|> . Write the next line using the current file imports: from celery import shared_task from django.db import transaction from hordak.data_sources import tellerio from hordak.models.core import Account from swiftwind.billing_cycle.models import BillingCycle from swiftwind.settings.models import Settings and context from other files: # Path: swiftwind/settings/models.py # class Settings(models.Model): # """Store application-wide settings # # Each field is one setting. Only once instance of Settings can be created. # # The model is intentionally named Settings rather than Setting (as would # be the Django convention), as a single model holds many settings. # """ # default_currency = models.CharField(max_length=3, choices=CURRENCY_CHOICES, default='EUR') # additional_currencies = ArrayField(base_field=models.CharField(choices=CURRENCY_CHOICES, default=[], max_length=3), # choices=CURRENCY_CHOICES, # needed? # default=[], blank=True) # payment_information = models.TextField(default='', blank=True, # help_text='Enter information on how payment should be made, such as the ' # 'bank account details housemates should pay into.') # email_from_address = models.EmailField(default='', blank=True, # help_text='What email address should emails appear to be sent from?') # use_https = models.BooleanField(default=False) # # tellerio_enable = models.BooleanField(default=False, verbose_name='Enable daily teller.io imports') # tellerio_token = models.CharField(max_length=100) # tellerio_account_id = models.CharField(max_length=100) # # from_email = models.EmailField(default='', blank=True) # smtp_host = models.CharField(max_length=100, default='', blank=True) # smtp_port = models.IntegerField(default=None, blank=True, null=True) # smtp_user = models.CharField(max_length=100, default='', blank=True) # smtp_password = models.CharField(max_length=100, default='', blank=True) # smtp_use_tls = models.BooleanField(default=False) # smtp_use_ssl = models.BooleanField(default=False) # smtp_subject_prefix = models.CharField(max_length=100, default='[swiftwind] ', blank=True) # # objects = SettingsManager() # # class Meta: # verbose_name_plural = 'settings' # # def save(self, *args, **kwargs): # if not self.pk and Settings.objects.exists(): # raise CannotCreateMultipleSettingsInstances('Only one Settings instance maybe created') # super(Settings, self).save(*args, **kwargs) # # TODO: Push changes into cache (possibly following a refresh_from_db() call) # # @property # def currencies(self): # return sorted({self.default_currency} | set(self.additional_currencies)) , which may include functions, classes, or code. Output only the next line.
first_billing_cycle = BillingCycle.objects.first()
Predict the next line for this snippet: <|code_start|> # Create your models here. class SettingsManager(models.Manager): def get(self): # TODO: Pull from cache try: <|code_end|> with the help of current file imports: from django.contrib.postgres.fields import ArrayField from django.db import models from djmoney.settings import CURRENCY_CHOICES from swiftwind.core.exceptions import CannotCreateMultipleSettingsInstances and context from other files: # Path: swiftwind/core/exceptions.py # class CannotCreateMultipleSettingsInstances(Exception): pass , which may contain function names, class names, or code. Output only the next line.
return super(SettingsManager, self).get()
Predict the next line after this snippet: <|code_start|> class DashboardViewTestCase(DataProvider, TestCase): def setUp(self): self.url = reverse('dashboard:dashboard') Command().handle(currency='GBP') <|code_end|> using the current file's imports: from django.test import TestCase from django.urls import reverse from swiftwind.core.management.commands.swiftwind_create_accounts import Command from swiftwind.utilities.testing import DataProvider and any relevant context from other files: # Path: swiftwind/core/management/commands/swiftwind_create_accounts.py # class Command(BaseCommand): # help = 'Create the initial chart of accounts' # # def add_arguments(self, parser): # super(Command, self).add_arguments(parser) # parser.add_argument( # '--preserve', dest='preserve', default=False, action='store_true', # help='Exit normally if any accounts already exist.', # ) # parser.add_argument( # '--currency', dest='currency', # help='Account currencies, can be specified multiple times. Defaults to the default currency setting.', # nargs='+', # ) # # def handle(self, *args, **options): # if options.get('preserve') and Account.objects.count(): # self.stdout.write('Exiting normally because accounts already exist and --preserve flag was present') # # if options.get('currency'): # currency = options['currency'] # else: # try: # currency = Settings.objects.get().default_currency # except Settings.DoesNotExist: # raise CommandError('No currency specified by either --currency or by the swiftwind settings.') # # kw = dict(currencies=currency) # # T = Account.TYPES # assets = Account.objects.create(name='Assets', code='1', type=T.asset, **kw) # liabilities = Account.objects.create(name='Liabilities', code='2', type=T.liability, **kw) # equity = Account.objects.create(name='Equity', code='3', type=T.equity, **kw) # income = Account.objects.create(name='Income', code='4', type=T.income, **kw) # expenses = Account.objects.create(name='Expenses', code='5', type=T.expense, **kw) # # bank = Account.objects.create(name='Bank', code='1', is_bank_account=True, type='AS', parent=assets, **kw) # # housemate_income = Account.objects.create(name='Housemate Income', code='1', parent=income, **kw) # other_income = Account.objects.create(name='Other Income', code='2', parent=income, **kw) # # current_liabilities = Account.objects.create(name='Current Liabilities', code='1', parent=liabilities, **kw) # long_term_liabilities = Account.objects.create(name='Long Term Liabilities', code='2', parent=liabilities, **kw) # # gas_payable = Account.objects.create(name='Gas Payable', code='1', parent=current_liabilities, **kw) # electricity_payable = Account.objects.create(name='Electricity Payable', code='2', parent=current_liabilities, **kw) # council_tax_payable = Account.objects.create(name='Council Tax Payable', code='3', parent=current_liabilities, **kw) # internet_payable = Account.objects.create(name='Internet Payable', code='4', parent=current_liabilities, **kw) # # retained_earnings = Account.objects.create(name='Retained Earnings', code='1', parent=equity, **kw) # # rent = Account.objects.create(name='Rent', code='1', parent=expenses, **kw) # utilities = Account.objects.create(name='Utilities', code='2', parent=expenses, **kw) # food = Account.objects.create(name='Food', code='3', parent=expenses, **kw) # other_expenses = Account.objects.create(name='Other Expenses', code='4', parent=expenses, **kw) # # gas_expense = Account.objects.create(name='Gas Expense', code='1', parent=utilities, **kw) # electricity_expense = Account.objects.create(name='Electricity Expense', code='2', parent=utilities, **kw) # council_tax_expense = Account.objects.create(name='Council Tax Expense', code='3', parent=utilities, **kw) # internet_expense = Account.objects.create(name='Internet Expense', code='4', parent=utilities, **kw) # # Path: swiftwind/utilities/testing.py # class DataProvider(HordakDataProvider): # # def housemate(self, user=None, account=None, user_kwargs=None, account_kwargs=None): # try: # housemate_income = Account.objects.get(name='Housemate Income') # except Account.DoesNotExist: # housemate_income = None # # return Housemate.objects.create( # user=user or self.user(**(user_kwargs or {})), # account=account or self.account( # type=Account.TYPES.income, # parent=housemate_income, # **(account_kwargs or {}) # ), # ) . Output only the next line.
def test_get(self):
Given the code snippet: <|code_start|> class DashboardViewTestCase(DataProvider, TestCase): def setUp(self): self.url = reverse('dashboard:dashboard') Command().handle(currency='GBP') def test_get(self): <|code_end|> , generate the next line using the imports in this file: from django.test import TestCase from django.urls import reverse from swiftwind.core.management.commands.swiftwind_create_accounts import Command from swiftwind.utilities.testing import DataProvider and context (functions, classes, or occasionally code) from other files: # Path: swiftwind/core/management/commands/swiftwind_create_accounts.py # class Command(BaseCommand): # help = 'Create the initial chart of accounts' # # def add_arguments(self, parser): # super(Command, self).add_arguments(parser) # parser.add_argument( # '--preserve', dest='preserve', default=False, action='store_true', # help='Exit normally if any accounts already exist.', # ) # parser.add_argument( # '--currency', dest='currency', # help='Account currencies, can be specified multiple times. Defaults to the default currency setting.', # nargs='+', # ) # # def handle(self, *args, **options): # if options.get('preserve') and Account.objects.count(): # self.stdout.write('Exiting normally because accounts already exist and --preserve flag was present') # # if options.get('currency'): # currency = options['currency'] # else: # try: # currency = Settings.objects.get().default_currency # except Settings.DoesNotExist: # raise CommandError('No currency specified by either --currency or by the swiftwind settings.') # # kw = dict(currencies=currency) # # T = Account.TYPES # assets = Account.objects.create(name='Assets', code='1', type=T.asset, **kw) # liabilities = Account.objects.create(name='Liabilities', code='2', type=T.liability, **kw) # equity = Account.objects.create(name='Equity', code='3', type=T.equity, **kw) # income = Account.objects.create(name='Income', code='4', type=T.income, **kw) # expenses = Account.objects.create(name='Expenses', code='5', type=T.expense, **kw) # # bank = Account.objects.create(name='Bank', code='1', is_bank_account=True, type='AS', parent=assets, **kw) # # housemate_income = Account.objects.create(name='Housemate Income', code='1', parent=income, **kw) # other_income = Account.objects.create(name='Other Income', code='2', parent=income, **kw) # # current_liabilities = Account.objects.create(name='Current Liabilities', code='1', parent=liabilities, **kw) # long_term_liabilities = Account.objects.create(name='Long Term Liabilities', code='2', parent=liabilities, **kw) # # gas_payable = Account.objects.create(name='Gas Payable', code='1', parent=current_liabilities, **kw) # electricity_payable = Account.objects.create(name='Electricity Payable', code='2', parent=current_liabilities, **kw) # council_tax_payable = Account.objects.create(name='Council Tax Payable', code='3', parent=current_liabilities, **kw) # internet_payable = Account.objects.create(name='Internet Payable', code='4', parent=current_liabilities, **kw) # # retained_earnings = Account.objects.create(name='Retained Earnings', code='1', parent=equity, **kw) # # rent = Account.objects.create(name='Rent', code='1', parent=expenses, **kw) # utilities = Account.objects.create(name='Utilities', code='2', parent=expenses, **kw) # food = Account.objects.create(name='Food', code='3', parent=expenses, **kw) # other_expenses = Account.objects.create(name='Other Expenses', code='4', parent=expenses, **kw) # # gas_expense = Account.objects.create(name='Gas Expense', code='1', parent=utilities, **kw) # electricity_expense = Account.objects.create(name='Electricity Expense', code='2', parent=utilities, **kw) # council_tax_expense = Account.objects.create(name='Council Tax Expense', code='3', parent=utilities, **kw) # internet_expense = Account.objects.create(name='Internet Expense', code='4', parent=utilities, **kw) # # Path: swiftwind/utilities/testing.py # class DataProvider(HordakDataProvider): # # def housemate(self, user=None, account=None, user_kwargs=None, account_kwargs=None): # try: # housemate_income = Account.objects.get(name='Housemate Income') # except Account.DoesNotExist: # housemate_income = None # # return Housemate.objects.create( # user=user or self.user(**(user_kwargs or {})), # account=account or self.account( # type=Account.TYPES.income, # parent=housemate_income, # **(account_kwargs or {}) # ), # ) . Output only the next line.
self.login()
Based on the snippet: <|code_start|> class GeneralSettingsForm(forms.ModelForm): default_currency = forms.ChoiceField(choices=CURRENCY_CHOICES, initial='EUR') additional_currencies = forms.MultipleChoiceField(choices=CURRENCY_CHOICES, widget=forms.SelectMultiple(), required=False) class Meta: model = Settings fields = [ 'default_currency', 'additional_currencies', 'payment_information', ] class TechnicalSettingsForm(forms.ModelForm): site_name = forms.CharField(max_length=50, initial='Swiftwind', help_text='What name shall we display to users of this software?') site_domain = forms.CharField(max_length=100, validators=[_simple_domain_name_validator], help_text='What is the domain name you use for this site?') use_https = forms.BooleanField(initial=False, required=False, help_text='Is this site being served over HTTPS?') class Meta: model = Settings fields = [ 'use_https', ] <|code_end|> , predict the immediate next line with the help of imports: from django import forms from django.contrib.sites.models import _simple_domain_name_validator, Site from djmoney.settings import CURRENCY_CHOICES from swiftwind.settings.models import Settings and context (classes, functions, sometimes code) from other files: # Path: swiftwind/settings/models.py # class Settings(models.Model): # """Store application-wide settings # # Each field is one setting. Only once instance of Settings can be created. # # The model is intentionally named Settings rather than Setting (as would # be the Django convention), as a single model holds many settings. # """ # default_currency = models.CharField(max_length=3, choices=CURRENCY_CHOICES, default='EUR') # additional_currencies = ArrayField(base_field=models.CharField(choices=CURRENCY_CHOICES, default=[], max_length=3), # choices=CURRENCY_CHOICES, # needed? # default=[], blank=True) # payment_information = models.TextField(default='', blank=True, # help_text='Enter information on how payment should be made, such as the ' # 'bank account details housemates should pay into.') # email_from_address = models.EmailField(default='', blank=True, # help_text='What email address should emails appear to be sent from?') # use_https = models.BooleanField(default=False) # # tellerio_enable = models.BooleanField(default=False, verbose_name='Enable daily teller.io imports') # tellerio_token = models.CharField(max_length=100) # tellerio_account_id = models.CharField(max_length=100) # # from_email = models.EmailField(default='', blank=True) # smtp_host = models.CharField(max_length=100, default='', blank=True) # smtp_port = models.IntegerField(default=None, blank=True, null=True) # smtp_user = models.CharField(max_length=100, default='', blank=True) # smtp_password = models.CharField(max_length=100, default='', blank=True) # smtp_use_tls = models.BooleanField(default=False) # smtp_use_ssl = models.BooleanField(default=False) # smtp_subject_prefix = models.CharField(max_length=100, default='[swiftwind] ', blank=True) # # objects = SettingsManager() # # class Meta: # verbose_name_plural = 'settings' # # def save(self, *args, **kwargs): # if not self.pk and Settings.objects.exists(): # raise CannotCreateMultipleSettingsInstances('Only one Settings instance maybe created') # super(Settings, self).save(*args, **kwargs) # # TODO: Push changes into cache (possibly following a refresh_from_db() call) # # @property # def currencies(self): # return sorted({self.default_currency} | set(self.additional_currencies)) . Output only the next line.
def __init__(self, *args, **kwargs):
Given the code snippet: <|code_start|> class RedisSub(databench.Analysis): def __init__(self): # create a connection to redis self.redis_client = redis_creator().pubsub() <|code_end|> , generate the next line using the imports in this file: import databench import tornado.gen from analyses.redispub.analysis import redis_creator and context (functions, classes, or occasionally code) from other files: # Path: analyses/redispub/analysis.py # def redis_creator(): # """Uses environment variables to create a redis client.""" # # rediscloudenv = os.getenv('REDISCLOUD_URL') # if rediscloudenv: # url = urlparse(rediscloudenv) # r = redis.Redis(host=url.hostname, port=url.port, # password=url.password) # else: # r = redis.StrictRedis() # # return r . Output only the next line.
self.redis_client.subscribe('someStatsProvider')
Using the snippet: <|code_start|> def can_handle_character(self, character): return character in Tube.__punctuation_characters def can_handle_contact(self, contact, clock): return contact.has('tubestation') def num_required_contacts(self): return 1 def transform(self, character, contacts, clock): contact = contacts[0] station = contact.get('tubestation') if contact.has_state('lasttube'): station = contact.get_state('lasttube') stations = self.__nearest_stations(station, len(Tube.__punctuation_characters)) index = Tube.__punctuation_characters.index(character) destination = stations[index] contact.set_state('lasttube', destination) contact.set_busy_func('tube', lambda clk: clock.jump_forward(12) > clk) return Instruction('tube', character, clock, contact, {'from_station': station, 'to_station': destination}) def __nearest_stations(self, station, qty): point1 = self._stations[station] distances = {} for name in self._stations: <|code_end|> , determine the next line of code. You have imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction from LatLon import LatLon import csv, os and context (class names, function names, or code) available: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
if name == station:
Predict the next line after this snippet: <|code_start|> # Tube station data from http://commons.wikimedia.org/wiki/London_Underground_geographic_maps/CSV class Tube(Transformer): __punctuation_characters = ['.', ',', '?', '!', ';', ':', '-'] def __init__(self): self.__import_stations() def can_handle_character(self, character): return character in Tube.__punctuation_characters def can_handle_contact(self, contact, clock): <|code_end|> using the current file's imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction from LatLon import LatLon import csv, os and any relevant context from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
return contact.has('tubestation')
Here is a snippet: <|code_start|> class Tweet(Transformer): def can_handle_character(self, character): return character == ' ' def can_handle_contact(self, contact, clock): return (contact.has('twitter') and contact.get('twitter') == True) def num_required_contacts(self): return 1 def transform(self, character, contacts, clock): <|code_end|> . Write the next line using the current file imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) , which may include functions, classes, or code. Output only the next line.
contact = contacts[0]
Here is a snippet: <|code_start|> class BankWire(Transformer): def can_handle_character(self, character): return utils.is_character_rare2(character) def can_handle_contact(self, contact, clock): return contact.has('name') def num_required_contacts(self): return 2 def transform(self, character, contacts, clock): <|code_end|> . Write the next line using the current file imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) , which may include functions, classes, or code. Output only the next line.
contact_from, contact_to, odd = utils.rare2_character_transform(character, contacts, 'name')
Given the code snippet: <|code_start|> class BankWire(Transformer): def can_handle_character(self, character): return utils.is_character_rare2(character) def can_handle_contact(self, contact, clock): <|code_end|> , generate the next line using the imports in this file: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context (functions, classes, or occasionally code) from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
return contact.has('name')
Based on the snippet: <|code_start|> class FBMsg(Transformer): def can_handle_character(self, character): return utils.is_character_common(character) <|code_end|> , predict the immediate next line with the help of imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context (classes, functions, sometimes code) from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
def can_handle_contact(self, contact, clock):
Given the following code snippet before the placeholder: <|code_start|> class SMS(Transformer): def can_handle_character(self, character): return utils.is_character_common(character) <|code_end|> , predict the next line using imports from the current file: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context including class names, function names, and sometimes code from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
def can_handle_contact(self, contact, clock):
Continue the code snippet: <|code_start|> class SMS(Transformer): def can_handle_character(self, character): return utils.is_character_common(character) <|code_end|> . Use current file imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context (classes, functions, or code) from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
def can_handle_contact(self, contact, clock):
Next line prediction: <|code_start|> class DebitCard(Transformer): def can_handle_character(self, character): return utils.is_character_digit1(character) def can_handle_contact(self, contact, clock): return True def num_required_contacts(self): return 1 def transform(self, character, contacts, clock): <|code_end|> . Use current file imports: (from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils) and context including class names, function names, or small code snippets from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
contact = contacts[0]
Based on the snippet: <|code_start|> class DebitCard(Transformer): def can_handle_character(self, character): return utils.is_character_digit1(character) def can_handle_contact(self, contact, clock): return True def num_required_contacts(self): <|code_end|> , predict the immediate next line with the help of imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context (classes, functions, sometimes code) from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
return 1
Predict the next line after this snippet: <|code_start|> class ContactlessCard(Transformer): def can_handle_character(self, character): return utils.is_character_digit2(character) def can_handle_contact(self, contact, clock): return (contact.has('contactless') and contact.get('contactless') == True) def num_required_contacts(self): return 1 <|code_end|> using the current file's imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and any relevant context from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
def transform(self, character, contacts, clock):
Predict the next line for this snippet: <|code_start|> class Paypal(Transformer): def can_handle_character(self, character): return utils.is_character_rare3(character) def can_handle_contact(self, contact, clock): <|code_end|> with the help of current file imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) , which may contain function names, class names, or code. Output only the next line.
return contact.has('email')
Given the code snippet: <|code_start|> class Phone(Transformer): def can_handle_character(self, character): return utils.is_character_rare1(character) def can_handle_contact(self, contact, clock): <|code_end|> , generate the next line using the imports in this file: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context (functions, classes, or occasionally code) from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) . Output only the next line.
return contact.has('phone')
Predict the next line for this snippet: <|code_start|> class Phone(Transformer): def can_handle_character(self, character): return utils.is_character_rare1(character) def can_handle_contact(self, contact, clock): <|code_end|> with the help of current file imports: from ..lib.transformer import Transformer from ..lib.instruction import Instruction import utils and context from other files: # Path: sexting/lib/transformer.py # class Transformer(object): # # def can_handle_character(self, character): # False # # def can_handle_contact(self, contact, clock): # False # # def num_required_contacts(self): # 0 # # def transform(self, character, contacts, clock): # return 'Character: {0}'.format(character) # # Path: sexting/lib/instruction.py # class Instruction(object): # # def __init__(self, medium, character, clock, contact, data = {}): # self._medium = medium # self._character = character # self._clock = clock # self._contact = contact # self._data = data # # def medium(self): # return self._medium # # def character(self): # return self._character # # def clock(self): # return self._clock # # def contact(self): # return self._contact # # def data(self, key): # return self._data[key] # # def __str__(self): # data = ', '.join(map(lambda k: "{0}: {1}".format(k, self._data[k]), self._data)) # return "For: '{0}', at {1}, {2}, should {3} ({4})".format(self._character, self._clock.block_range_str(), self._contact.get('name'), self._medium, data) , which may contain function names, class names, or code. Output only the next line.
return contact.has('phone')
Using the snippet: <|code_start|>def get_devices(request): return render(request, "devices.html", { 'messagestore': jobs.get_messages(), 'devices': get_entries(), }) @require_POST @login_required def refresh_devices(request): try: utils.exec_upri_config('parse_user_agents') except utils.AnsibleError as ae: logger.exception(ae) devices = get_entries() response = [ { 'slug': dev.slug, 'mode': dev.mode, 'mode_url': reverse('upri_devices_mode'), 'name_url': reverse('upri_device_name', kwargs={'slug': dev.slug}), 'name': get_device_name(dev), 'changing': dev.changing } for dev in devices ] return JsonResponse(response, safe=False) <|code_end|> , determine the next line of code. You have imports: import json import logging import time import lib.utils as utils import netifaces as ni from datetime import datetime, time, timedelta from socket import AF_INET from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import Http404, HttpResponse, JsonResponse from django.shortcuts import render from django.template import loader from django.template.defaultfilters import date as _localdate from django.utils.timezone import now as django_now from django.utils.translation import ugettext_lazy as _ from django.views.decorators.http import require_http_methods, require_POST from lib import jobs from www.templatetags.base_extras import get_device_name from . import jobs as devicejobs from .models import DeviceEntry and context (class names, function names, or code) available: # Path: upribox_interface/devices/models.py # class DeviceEntry(models.Model): # ip = models.CharField(max_length=20, unique=False) # mac = models.CharField(max_length=20, null=False, unique=True) # dhcp_fingerprint = models.CharField(max_length=256, null=True) # dhcp_vendor = models.CharField(max_length=256, null=True) # user_agent = models.ManyToManyField(UserAgent) # hostname = models.CharField(max_length=256, null=True) # MODES = ( # ('SL', "Silent"), # ('NJ', "Ninja"), # ('NO', "No Mode") # ) # mode = models.CharField(max_length=2, choices=MODES, default='SL') # chosen_name = models.CharField(max_length=256, null=True) # slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id, always_update=False, null=True) # changing = models.NullBooleanField(null=True, default=False) # last_seen = models.DateTimeField(default=timezone.now) # # objects = DeviceManager() . Output only the next line.
@login_required
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals logger = logging.getLogger('uprilogger') class VpnProfileForm(forms.Form): profilename = forms.CharField( required=True, label=ugettext_lazy("Name:"), max_length=64, <|code_end|> using the current file's imports: import logging from django import forms from django.utils.translation import ugettext_lazy from lib import domain from lib.utils import get_fact from .models import VpnProfile and any relevant context from other files: # Path: upribox_interface/vpn/models.py # class VpnProfile(models.Model): # profilename = models.CharField(max_length=32) # config = models.TextField() # creation_date = models.DateField(auto_now_add=True) # # first slug - this field is used to reference the object, e.g. when creating a download link or when deleting # slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id) # # second slug - this field is used for the download link # download_slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id, always_update=True, null=True) # download_valid_until = models.DateTimeField(null=True) # dyndomain = models.CharField(max_length=256) # # class Meta: # ordering = ["creation_date"] . Output only the next line.
)
Given the code snippet: <|code_start|>from __future__ import unicode_literals logger = logging.getLogger('uprilogger') @login_required def check_connection(request): if request.method != 'POST': raise Http404() # Check VPN connectivity # Get log lines with TLS-auth error before connection try: with open(settings.OPENVPN_LOGFILE) as f: log_lines_before = f.readlines() except IOError: return HttpResponse('{{"status": "error", "msg": "{}"}}'.format(_("openvpn.log konnte nicht geöffnet werden."))) # Send request to upribox API try: r = requests.get("https://api.upribox.org/connectivity/", timeout=7, verify=settings.SSL_PINNING_PATH) except: return HttpResponse('{{"status": "error", "msg": "{}"}}'.format(_("Verbindung zu api.upribox.org fehlgeschlagen."))) # Get log lines with TLS-auth error after connection try: <|code_end|> , generate the next line using the imports in this file: import logging import time import requests import lib.utils as utils from datetime import timedelta from os.path import exists from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import Http404, HttpResponse, JsonResponse from django.shortcuts import render from django.utils import timezone from django.utils.translation import ugettext as _ from django.views.decorators.http import (require_GET, require_http_methods, require_POST) from lib import jobs from . import jobs as vpnjobs from .forms import VpnProfileForm from .models import VpnProfile and context (functions, classes, or occasionally code) from other files: # Path: upribox_interface/vpn/forms.py # class VpnProfileForm(forms.Form): # # profilename = forms.CharField( # required=True, # label=ugettext_lazy("Name:"), # max_length=64, # ) # # dyndomain = forms.CharField( # required=True, # label=ugettext_lazy("Domain:"), # max_length=64, # ) # # def __init__(self, *args, **kwargs): # super(VpnProfileForm, self).__init__(*args, **kwargs) # # upri_dns_domain = None # # try: # upri_dns_domain = get_fact('dns', 'dns', 'hostname') # except: # logger.error('Kein upri DNS fact gefunden.') # # if upri_dns_domain: # self.fields['dyndomain'].widget = forms.HiddenInput() # self.fields['dyndomain'].initial = upri_dns_domain # self.fields['dyndomain'].label = "" # # def clean_profilename(self): # profilename = self.cleaned_data['profilename'] # try: # VpnProfile.objects.get(profilename=profilename) # raise forms.ValidationError(ugettext_lazy("Profil existiert bereits")) # except VpnProfile.DoesNotExist: # return profilename # # def clean_dyndomain(self): # # dyndomain = self.cleaned_data['dyndomain'] # # errors = [] # check = domain.Domain(dyndomain) # # if not check.is_valid(): # if not check.has_allowed_length(): # errors.append(forms.ValidationError(ugettext_lazy("Die Domain darf maximal 255 Zeichen lang sein"))) # if not check.has_only_allowed_chars(): # errors.append(forms.ValidationError(ugettext_lazy("Die Domain darf lediglich Buchstaben, Ziffern, Punkte und Minusse enthalten"))) # if not errors: # errors.append(forms.ValidationError(ugettext_lazy("Die Domain ist nicht gültig"))) # # raise forms.ValidationError(errors) # # return check.get_match() #dyndomain # # Path: upribox_interface/vpn/models.py # class VpnProfile(models.Model): # profilename = models.CharField(max_length=32) # config = models.TextField() # creation_date = models.DateField(auto_now_add=True) # # first slug - this field is used to reference the object, e.g. when creating a download link or when deleting # slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id) # # second slug - this field is used for the download link # download_slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id, always_update=True, null=True) # download_valid_until = models.DateTimeField(null=True) # dyndomain = models.CharField(max_length=256) # # class Meta: # ordering = ["creation_date"] . Output only the next line.
with open(settings.OPENVPN_LOGFILE) as f:
Based on the snippet: <|code_start|> response = HttpResponse(profile.config, content_type='application/x-openvpn-profile') response['Content-Disposition'] = 'attachment; filename="upribox-%s.ovpn"' % profile.profilename return response else: # link timed out raise Http404() except VpnProfile.DoesNotExist: # no profile found for slug => does not exist or link timed out raise Http404() @require_POST @login_required def vpn_create_download(request, slug): try: # create new link and set timeout date profile = VpnProfile.objects.get(slug=slug) profile.download_valid_until = timezone.now() + timedelta(seconds=settings.VPN_LINK_TIMEOUT) profile.save() logger.info("created download link %s (valid until %s) for vpn profile %s..." % (profile.download_slug, profile.download_valid_until, slug)) # render profile return render(request, "vpn_profile.html", {'profile': profile}) except VpnProfile.DoesNotExist: raise Http404() @login_required def vpn_toggle(request): <|code_end|> , predict the immediate next line with the help of imports: import logging import time import requests import lib.utils as utils from datetime import timedelta from os.path import exists from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import Http404, HttpResponse, JsonResponse from django.shortcuts import render from django.utils import timezone from django.utils.translation import ugettext as _ from django.views.decorators.http import (require_GET, require_http_methods, require_POST) from lib import jobs from . import jobs as vpnjobs from .forms import VpnProfileForm from .models import VpnProfile and context (classes, functions, sometimes code) from other files: # Path: upribox_interface/vpn/forms.py # class VpnProfileForm(forms.Form): # # profilename = forms.CharField( # required=True, # label=ugettext_lazy("Name:"), # max_length=64, # ) # # dyndomain = forms.CharField( # required=True, # label=ugettext_lazy("Domain:"), # max_length=64, # ) # # def __init__(self, *args, **kwargs): # super(VpnProfileForm, self).__init__(*args, **kwargs) # # upri_dns_domain = None # # try: # upri_dns_domain = get_fact('dns', 'dns', 'hostname') # except: # logger.error('Kein upri DNS fact gefunden.') # # if upri_dns_domain: # self.fields['dyndomain'].widget = forms.HiddenInput() # self.fields['dyndomain'].initial = upri_dns_domain # self.fields['dyndomain'].label = "" # # def clean_profilename(self): # profilename = self.cleaned_data['profilename'] # try: # VpnProfile.objects.get(profilename=profilename) # raise forms.ValidationError(ugettext_lazy("Profil existiert bereits")) # except VpnProfile.DoesNotExist: # return profilename # # def clean_dyndomain(self): # # dyndomain = self.cleaned_data['dyndomain'] # # errors = [] # check = domain.Domain(dyndomain) # # if not check.is_valid(): # if not check.has_allowed_length(): # errors.append(forms.ValidationError(ugettext_lazy("Die Domain darf maximal 255 Zeichen lang sein"))) # if not check.has_only_allowed_chars(): # errors.append(forms.ValidationError(ugettext_lazy("Die Domain darf lediglich Buchstaben, Ziffern, Punkte und Minusse enthalten"))) # if not errors: # errors.append(forms.ValidationError(ugettext_lazy("Die Domain ist nicht gültig"))) # # raise forms.ValidationError(errors) # # return check.get_match() #dyndomain # # Path: upribox_interface/vpn/models.py # class VpnProfile(models.Model): # profilename = models.CharField(max_length=32) # config = models.TextField() # creation_date = models.DateField(auto_now_add=True) # # first slug - this field is used to reference the object, e.g. when creating a download link or when deleting # slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id) # # second slug - this field is used for the download link # download_slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id, always_update=True, null=True) # download_valid_until = models.DateTimeField(null=True) # dyndomain = models.CharField(max_length=256) # # class Meta: # ordering = ["creation_date"] . Output only the next line.
if request.method != 'POST':
Here is a snippet: <|code_start|> days.append({ 'date': date.strftime('%Y-%m-%d'), 'traffic': traffic, 'text': texts }) total += sum(traffic.values()) total_protocols.update(traffic) protocols_sorted = sorted(total_protocols, key=total_protocols.get, reverse=True) if len(protocols_sorted) > 0: colors = list(Color('#47ADC0').range_to(Color('black'), len(protocols_sorted))) return days, total, colors, texts, protocols_sorted def get_protocols_by_volume(days, protocols_sorted, colors): protocols = list() for protocol in protocols_sorted: dates = list() amounts = list() texts = list() for day in days: dates.append(day['date']) if protocol in day['traffic']: amounts.append(day['traffic'][protocol]) texts.append(day['text'][protocol]) <|code_end|> . Write the next line using the current file imports: import re from .ntopng import Metric, device_day_stats from lib.stats import get_week_days from colour import Color from collections import Counter and context from other files: # Path: upribox_interface/traffic/ntopng.py # class Metric(Enum): # PROTOCOLS = 'allprotocols_bps' # CATEGORIES = 'allcategories_bps' # TRAFFIC_PACKETS_PER_SECOND = 'traffic_pps' # TRAFFIC_BITS_PER_SECOND = 'traffic_bps' # TOTAL_BYTES = 'traffic_total_bytes' # TOTAL_PACKETS = 'traffic_total_packets' # # def device_day_stats(date, host, sent_recv=True, metric=Metric.PROTOCOLS): # if not check_ip(host): # raise ValueError("host is not a valid IP address") # # if metric not in Metric: # raise ValueError("not a supported metric") # # res = {} # byte = 8.0 # bits # time_factor = 300 * 12 # seconds of one rrd interval (1 h) for intervals older than 24 hours # if datetime.date.today() == date: # time_factor = 300 # seconds of one rrd interval (5 min) for values of the last 24 hours # # data = _device_day_data(date, host, metric) # # for proto in data: # if sent_recv and metric == Metric.PROTOCOLS: # # separate values for sent and received of one protocol # key = " ".join(proto['target'].split(" ")[:2]) # else: # # sum up values for send and received of one protocol # key = proto['target'].split(" ")[0] # # res.setdefault(key, 0) # # calculates bytes from given bps values # res[key] += sum((point[0] / byte) * time_factor for point in proto['datapoints']) # # final_result = {protocol: convert_to_megabytes(byte_count) for protocol, byte_count in res.items()} # # return final_result , which may include functions, classes, or code. Output only the next line.
else:
Continue the code snippet: <|code_start|># coding: utf-8 def get_protocol_sums(traffic): protocols = parse_traffic_dict(traffic) amounts = dict() texts = dict() for protocol in protocols.keys(): text = list() amount = 0.0 text.append(protocol.encode('utf-8')) if 'sent' in protocols[protocol] and float(protocols[protocol]['sent']) > 0: value = protocols[protocol]['sent'] text.append('▲ {}'.format(value)) amount += value if 'rcvd' in protocols[protocol] and float(protocols[protocol]['rcvd']) > 0: value = protocols[protocol]['rcvd'] text.append('▼ {}'.format(value)) amount += value amounts[protocol] = round(amount, 2) texts[protocol] = ' '.join(text) return amounts, texts <|code_end|> . Use current file imports: import re from .ntopng import Metric, device_day_stats from lib.stats import get_week_days from colour import Color from collections import Counter and context (classes, functions, or code) from other files: # Path: upribox_interface/traffic/ntopng.py # class Metric(Enum): # PROTOCOLS = 'allprotocols_bps' # CATEGORIES = 'allcategories_bps' # TRAFFIC_PACKETS_PER_SECOND = 'traffic_pps' # TRAFFIC_BITS_PER_SECOND = 'traffic_bps' # TOTAL_BYTES = 'traffic_total_bytes' # TOTAL_PACKETS = 'traffic_total_packets' # # def device_day_stats(date, host, sent_recv=True, metric=Metric.PROTOCOLS): # if not check_ip(host): # raise ValueError("host is not a valid IP address") # # if metric not in Metric: # raise ValueError("not a supported metric") # # res = {} # byte = 8.0 # bits # time_factor = 300 * 12 # seconds of one rrd interval (1 h) for intervals older than 24 hours # if datetime.date.today() == date: # time_factor = 300 # seconds of one rrd interval (5 min) for values of the last 24 hours # # data = _device_day_data(date, host, metric) # # for proto in data: # if sent_recv and metric == Metric.PROTOCOLS: # # separate values for sent and received of one protocol # key = " ".join(proto['target'].split(" ")[:2]) # else: # # sum up values for send and received of one protocol # key = proto['target'].split(" ")[0] # # res.setdefault(key, 0) # # calculates bytes from given bps values # res[key] += sum((point[0] / byte) * time_factor for point in proto['datapoints']) # # final_result = {protocol: convert_to_megabytes(byte_count) for protocol, byte_count in res.items()} # # return final_result . Output only the next line.
def parse_traffic_dict(traffic):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals # Get an instance of a logger logger = logging.getLogger('uprilogger') @require_http_methods(["GET", "POST"]) @login_required def silent(request): context = {} if request.method == 'POST': form = WlanForm(utils.get_fact('wlan', 'upri', 'ssid'), request.POST) if form.is_valid(): password = form.cleaned_data['password2'] ssid = form.cleaned_data['ssid'] jobs.queue_job(wlanjobs.reconfigure_wlan, (ssid, password)) context.update({'message': True, 'upri_ssid': ssid}) else: <|code_end|> using the current file's imports: import logging from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import Http404 from django.shortcuts import render from django.views.decorators.http import require_http_methods, require_POST from lib import jobs, utils from lib.info import ModelInfo from wlan import jobs as wlanjobs from .forms import WlanForm and any relevant context from other files: # Path: upribox_interface/wlan/forms.py # class WlanForm(forms.Form): # ssid = forms.CharField( # required=False, # label=ugettext_lazy("SSID:"), # max_length=100, # ) # password1 = forms.CharField( # required=False, # label=ugettext_lazy("Neues Passwort:"), # widget=forms.PasswordInput(attrs={'placeholder': '*' * 10}), # ) # password2 = forms.CharField( # required=False, # label=ugettext_lazy("Passwort bestätigen:"), # widget=forms.PasswordInput(attrs={'placeholder': '*' * 10}), # ) # # def __init__(self, ssid, *args, **kwargs): # super(WlanForm, self).__init__(*args, **kwargs) # self.fields['ssid'].widget.attrs['value'] = ssid # # def clean_password2(self): # password1 = self.cleaned_data.get('password1') # password2 = self.cleaned_data.get('password2') # # return utils.check_passwords(password1, password2) # # def clean_ssid(self): # ssid_str = self.cleaned_data.get('ssid') # # errors = [] # check = ssid.SSID(ssid_str) # # if not check.is_valid(): # if not check.has_allowed_length(): # errors.append(forms.ValidationError(ugettext_lazy("Die SSID muss zwischen 1 und 32 Zeichen lang sein"))) # if not check.has_only_allowed_chars(): # errors.append( # forms.ValidationError(ugettext_lazy("Die SSID darf lediglich die Sonderzeichen %s enthalten" % check.get_allowed_chars())) # ) # # raise forms.ValidationError(errors) # # return ssid_str . Output only the next line.
logger.error("form validation failed for %s" % request.path)
Predict the next line for this snippet: <|code_start|> logger.debug("configuring device modes") utils.exec_upri_config('configure_devices') except utils.AnsibleError as e: logger.error("ansible failed with error %d: %s" % (e.rc, e.message)) raise try: with sqlite3.connect(dbfile) as conn: c = conn.cursor() c.execute("Update devices_deviceentry set mode=?, changing=? where id=?;", (mode, False, device.id)) conn.commit() except sqlite3.Error as dbe: # logger.exception(dbe) raise jobs.job_message(_("Gerätemodus erfolgreich geändert.")) else: logger.error("device id unknown") raise jobs.JobFailedError() else: logger.error("something unexpected happened") # jobs.job_message(_("Es ist ein unbekannter Fehler aufgetreten.")) raise jobs.JobFailedError() except Exception as e: logger.exception(e) # jobs.job_clear_messages() jobs.job_error(_("Ändern des Gerätemodus fehlgeschlagen.")) try: <|code_end|> with the help of current file imports: import json import logging import sqlite3 import lib.jobs as jobs import lib.utils as utils from django.utils.translation import ugettext as _ from .models import DeviceEntry and context from other files: # Path: upribox_interface/devices/models.py # class DeviceEntry(models.Model): # ip = models.CharField(max_length=20, unique=False) # mac = models.CharField(max_length=20, null=False, unique=True) # dhcp_fingerprint = models.CharField(max_length=256, null=True) # dhcp_vendor = models.CharField(max_length=256, null=True) # user_agent = models.ManyToManyField(UserAgent) # hostname = models.CharField(max_length=256, null=True) # MODES = ( # ('SL', "Silent"), # ('NJ', "Ninja"), # ('NO', "No Mode") # ) # mode = models.CharField(max_length=2, choices=MODES, default='SL') # chosen_name = models.CharField(max_length=256, null=True) # slug = autoslug.AutoSlugField(unique=True, populate_from=utils.secure_random_id, always_update=False, null=True) # changing = models.NullBooleanField(null=True, default=False) # last_seen = models.DateTimeField(default=timezone.now) # # objects = DeviceManager() , which may contain function names, class names, or code. Output only the next line.
with sqlite3.connect(dbfile) as conn:
Given snippet: <|code_start|> downlink_format = common.df(m) crc = common.crc(m) icao = adsb.icao(m) tc = adsb.typecode(m) if 1 <= tc <= 4: category = adsb.category(m) callsign = adsb.callsign(m) if tc == 19: velocity = adsb.velocity(m) if 5 <= tc <= 8: if adsb.oe_flag(m): m_surf_1 = m t1 = ts else: m_surf_0 = m t0 = ts if m_surf_0 and m_surf_1: position = adsb.surface_position( m_surf_0, m_surf_1, t0, t1, 50.01, 4.35 ) altitude = adsb.altitude(m) if 9 <= tc <= 18: if adsb.oe_flag(m): m_air_1 = m t1 = ts <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import time import pandas as pd from tqdm import tqdm from pyModeS.decoder import adsb from pyModeS.decoder import common from pyModeS.decoder import c_common as common and context: # Path: pyModeS/decoder/adsb.py # def df(msg): # def icao(msg): # def typecode(msg): # def position(msg0, msg1, t0, t1, lat_ref=None, lon_ref=None): # def position_with_ref(msg, lat_ref, lon_ref): # def altitude(msg): # def velocity(msg, source=False): # def speed_heading(msg): # def oe_flag(msg): # def version(msg): # def nuc_p(msg): # def nuc_v(msg): # def nic_v1(msg, NICs): # def nic_v2(msg, NICa, NICbc): # def nic_s(msg): # def nic_a_c(msg): # def nic_b(msg): # def nac_p(msg): # def nac_v(msg): # def sil(msg, version): # HPL = uncertainty.NUCp[NUCp]["HPL"] # HVE = uncertainty.NUCv[NUCv]["HVE"] # VVE = uncertainty.NUCv[NUCv]["VVE"] # HVE, VVE = uncertainty.NA, uncertainty.NA # NIC = uncertainty.TC_NICv1_lookup[tc] # NIC = NIC[NICs] # VPL = uncertainty.NICv1[NIC][NICs]["VPL"] # NIC = uncertainty.TC_NICv2_lookup[tc] # NIC = NIC[NICs] # EPU = uncertainty.NACp[NACp]["EPU"] # VEPU = uncertainty.NACp[NACp]["VEPU"] # EPU, VEPU = uncertainty.NA, uncertainty.NA # SIL = common.bin2int(msgbin[76:78]) # SIL = common.bin2int(msgbin[82:84]) # PE_VPL = uncertainty.SIL[SIL]["PE_VPL"] # SIL_SUP = common.bin2int(msgbin[39]) # SIL_SUP = common.bin2int(msgbin[86]) which might include code, classes, or functions. Output only the next line.
else:
Continue the code snippet: <|code_start|> print_name() tret = jsocket.gethostname() ret = socket.gethostname() assert(ret == tret) # @check_stop def test_gethostbyaddr(): print_name() tret = jsocket.gethostbyaddr(HOST) ret = socket.gethostbyaddr(HOST) print(tret) print(ret) assert(tret[0] in HOSTS) # @check_stop def test_gethostbyaddr2(): print_name() tret = jsocket.gethostbyaddr(HOST_IP) ret = socket.gethostbyaddr(HOST_IP) print(tret) print(ret) assert(ret == tret) # @check_stop def test_gethostbyaddr3(): print_name() with raises(jsocket.gaierror): tret = jsocket.gethostbyaddr(FAIL_HOST) # @check_stop <|code_end|> . Use current file imports: from pytest import * from jega import loop from jega.ext import jsocket from util import * import socket and context (classes, functions, or code) from other files: # Path: jega/loop.py # _MAX_WORKERS = 5 # def _raise_stop_error(*args): # def __init__(self): # def reset(self): # def add_signal_handler(self, sig, callback, *args): # def _handle_signal(self, sig, arg): # def remove_signal_handler(self, sig): # def _check_signal(self, sig): # def _socketpair(self): # def _close_self_pipe(self): # def _make_self_pipe(self): # def _read_from_self(self): # def _write_to_self(self): # def destroy(self): # def wrap_future(self, future): # def run(self): # def run_once(self): # def run_forever(self): # def run_until_complete(self, future, timeout=None): # def stop(self): # def call_soon_threadsafe(self, callback, *args): # def run_in_executor(self, executor, callback, *args): # def set_default_executor(self, executor): # def getaddrinfo(self, host, port, family=0, type=0, proto=0, flags=0): # def getnameinfo(self, sockaddr, flags=0): # def _add_callback_signalsafe(self, handle): # def set_socket_acceptor(self, sock, acceptor): # def internal_acceptor(accept, acceptor): # def get_event_loop(): # def spawn(cb, *args): # class JegaEventLoop(jega.AbstractEventLoop): # # Path: jega/ext/jsocket.py # EBADF = 9 # SOCKETMETHODS = ('setblocking', 'bind', 'fileno', 'listen', 'getpeername', 'getsockname', 'getsockopt', 'setsockopt') # _GLOBAL_DEFAULT_TIMEOUT = __socket__._GLOBAL_DEFAULT_TIMEOUT # _GLOBAL_DEFAULT_TIMEOUT = object() # class _realsocket(_socket.socket): # class _fileobject: # class _closedsocket(object): # class socket(object): # class socket(object): # def __init__(self, sock, mode='rwb', bufsize=-1, close=False): # def closed(self): # def __del__(self): # def close(self): # def inet_ntop(address_family, packed_ip): # def wait_read(fileno, timeout=None, timeout_exc=timeout): # def wait_write(fileno, timeout=None, timeout_exc=timeout): # def wait_readwrite(fileno, timeout=None, timeout_exc=timeout): # def _get_memory(string, offset): # def _dummy(*args): # def internal_accept(s): # def internal_close(s): # def internal_connect(s, address): # def internal_connect_ex(s, address): # def internal_recv(s, *args): # def internal_recvfrom(s, *args): # def internal_recvfrom_into(s, *args): # def internal_recv_into(s, *args): # def internal_send(s, *args): # def internal_sendall(s, data, flags=0): # def internal_sendall(s, data, flags=0): # def internal_sendto(s, *args): # def internal_settimeout(s, howlong): # def internal_gettimeout(s): # def internal_shutdown(s, how): # def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): # def __enter__(self): # def __exit__(self, *args): # def dup(self): # def _decref_socketios(self): # def _real_close(self, _ss=_socket.socket): # def close(self): # def detach(self): # def accept_block(self): # def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): # def __repr__(self): # def __str__(self): # def _formatinfo(self): # def __enter__(self): # def __exit__(self, *args): # def dup(self): # def makefile(self, mode='r', bufsize=-1): # def accept_block(self): # def socketpair(*args): # def fromfd(fd, family, type, proto=0): # def fromfd(*args): # def getfqdn(name=''): # def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): # def ssl(sock, certificate=None, private_key=None): . Output only the next line.
def test_getnameinfo():
Continue the code snippet: <|code_start|> # @check_stop def test_gethostbyname_ex_fail(): print_name() with raises(jsocket.gaierror): ret = jsocket.gethostbyname_ex(FAIL_HOST) # @check_stop def test_gethostname(): print_name() tret = jsocket.gethostname() ret = socket.gethostname() assert(ret == tret) # @check_stop def test_gethostbyaddr(): print_name() tret = jsocket.gethostbyaddr(HOST) ret = socket.gethostbyaddr(HOST) print(tret) print(ret) assert(tret[0] in HOSTS) # @check_stop def test_gethostbyaddr2(): print_name() tret = jsocket.gethostbyaddr(HOST_IP) ret = socket.gethostbyaddr(HOST_IP) print(tret) <|code_end|> . Use current file imports: from pytest import * from jega import loop from jega.ext import jsocket from util import * import socket and context (classes, functions, or code) from other files: # Path: jega/loop.py # _MAX_WORKERS = 5 # def _raise_stop_error(*args): # def __init__(self): # def reset(self): # def add_signal_handler(self, sig, callback, *args): # def _handle_signal(self, sig, arg): # def remove_signal_handler(self, sig): # def _check_signal(self, sig): # def _socketpair(self): # def _close_self_pipe(self): # def _make_self_pipe(self): # def _read_from_self(self): # def _write_to_self(self): # def destroy(self): # def wrap_future(self, future): # def run(self): # def run_once(self): # def run_forever(self): # def run_until_complete(self, future, timeout=None): # def stop(self): # def call_soon_threadsafe(self, callback, *args): # def run_in_executor(self, executor, callback, *args): # def set_default_executor(self, executor): # def getaddrinfo(self, host, port, family=0, type=0, proto=0, flags=0): # def getnameinfo(self, sockaddr, flags=0): # def _add_callback_signalsafe(self, handle): # def set_socket_acceptor(self, sock, acceptor): # def internal_acceptor(accept, acceptor): # def get_event_loop(): # def spawn(cb, *args): # class JegaEventLoop(jega.AbstractEventLoop): # # Path: jega/ext/jsocket.py # EBADF = 9 # SOCKETMETHODS = ('setblocking', 'bind', 'fileno', 'listen', 'getpeername', 'getsockname', 'getsockopt', 'setsockopt') # _GLOBAL_DEFAULT_TIMEOUT = __socket__._GLOBAL_DEFAULT_TIMEOUT # _GLOBAL_DEFAULT_TIMEOUT = object() # class _realsocket(_socket.socket): # class _fileobject: # class _closedsocket(object): # class socket(object): # class socket(object): # def __init__(self, sock, mode='rwb', bufsize=-1, close=False): # def closed(self): # def __del__(self): # def close(self): # def inet_ntop(address_family, packed_ip): # def wait_read(fileno, timeout=None, timeout_exc=timeout): # def wait_write(fileno, timeout=None, timeout_exc=timeout): # def wait_readwrite(fileno, timeout=None, timeout_exc=timeout): # def _get_memory(string, offset): # def _dummy(*args): # def internal_accept(s): # def internal_close(s): # def internal_connect(s, address): # def internal_connect_ex(s, address): # def internal_recv(s, *args): # def internal_recvfrom(s, *args): # def internal_recvfrom_into(s, *args): # def internal_recv_into(s, *args): # def internal_send(s, *args): # def internal_sendall(s, data, flags=0): # def internal_sendall(s, data, flags=0): # def internal_sendto(s, *args): # def internal_settimeout(s, howlong): # def internal_gettimeout(s): # def internal_shutdown(s, how): # def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): # def __enter__(self): # def __exit__(self, *args): # def dup(self): # def _decref_socketios(self): # def _real_close(self, _ss=_socket.socket): # def close(self): # def detach(self): # def accept_block(self): # def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): # def __repr__(self): # def __str__(self): # def _formatinfo(self): # def __enter__(self): # def __exit__(self, *args): # def dup(self): # def makefile(self, mode='r', bufsize=-1): # def accept_block(self): # def socketpair(*args): # def fromfd(fd, family, type, proto=0): # def fromfd(*args): # def getfqdn(name=''): # def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): # def ssl(sock, certificate=None, private_key=None): . Output only the next line.
print(ret)
Next line prediction: <|code_start|> def _accept(): s = jsocket.socket(jsocket.AF_INET, jsocket.SOCK_STREAM) s.setsockopt(jsocket.SOL_SOCKET, jsocket.SO_REUSEADDR, 1) s.bind(("", 8080)) s.listen(1) c, a = s.accept() assert(a[0] == "127.0.0.1") f = c.makefile(mode="rw") assert(f) assert(f.read(10) == "A" * 10) f.write("B" * 10) return "_accept" def _conn(): s = jsocket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("", 8080)) s.sendall(b"A" * 10) assert(s.recv(10) == b"B" * 10) return "_conn" f1 = executor.submit(_accept) f2 = executor.submit(_conn) r = event_loop.run_until_complete(f1) assert(r == "_accept") r = event_loop.run_until_complete(f2) assert(r == "_conn") event_loop.stop() # @check_stop <|code_end|> . Use current file imports: (from pytest import * from jega.ext import jsocket from jega import loop from util import * import socket import jega) and context including class names, function names, or small code snippets from other files: # Path: jega/ext/jsocket.py # EBADF = 9 # SOCKETMETHODS = ('setblocking', 'bind', 'fileno', 'listen', 'getpeername', 'getsockname', 'getsockopt', 'setsockopt') # _GLOBAL_DEFAULT_TIMEOUT = __socket__._GLOBAL_DEFAULT_TIMEOUT # _GLOBAL_DEFAULT_TIMEOUT = object() # class _realsocket(_socket.socket): # class _fileobject: # class _closedsocket(object): # class socket(object): # class socket(object): # def __init__(self, sock, mode='rwb', bufsize=-1, close=False): # def closed(self): # def __del__(self): # def close(self): # def inet_ntop(address_family, packed_ip): # def wait_read(fileno, timeout=None, timeout_exc=timeout): # def wait_write(fileno, timeout=None, timeout_exc=timeout): # def wait_readwrite(fileno, timeout=None, timeout_exc=timeout): # def _get_memory(string, offset): # def _dummy(*args): # def internal_accept(s): # def internal_close(s): # def internal_connect(s, address): # def internal_connect_ex(s, address): # def internal_recv(s, *args): # def internal_recvfrom(s, *args): # def internal_recvfrom_into(s, *args): # def internal_recv_into(s, *args): # def internal_send(s, *args): # def internal_sendall(s, data, flags=0): # def internal_sendall(s, data, flags=0): # def internal_sendto(s, *args): # def internal_settimeout(s, howlong): # def internal_gettimeout(s): # def internal_shutdown(s, how): # def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): # def __enter__(self): # def __exit__(self, *args): # def dup(self): # def _decref_socketios(self): # def _real_close(self, _ss=_socket.socket): # def close(self): # def detach(self): # def accept_block(self): # def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): # def __repr__(self): # def __str__(self): # def _formatinfo(self): # def __enter__(self): # def __exit__(self, *args): # def dup(self): # def makefile(self, mode='r', bufsize=-1): # def accept_block(self): # def socketpair(*args): # def fromfd(fd, family, type, proto=0): # def fromfd(*args): # def getfqdn(name=''): # def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): # def ssl(sock, certificate=None, private_key=None): # # Path: jega/loop.py # _MAX_WORKERS = 5 # def _raise_stop_error(*args): # def __init__(self): # def reset(self): # def add_signal_handler(self, sig, callback, *args): # def _handle_signal(self, sig, arg): # def remove_signal_handler(self, sig): # def _check_signal(self, sig): # def _socketpair(self): # def _close_self_pipe(self): # def _make_self_pipe(self): # def _read_from_self(self): # def _write_to_self(self): # def destroy(self): # def wrap_future(self, future): # def run(self): # def run_once(self): # def run_forever(self): # def run_until_complete(self, future, timeout=None): # def stop(self): # def call_soon_threadsafe(self, callback, *args): # def run_in_executor(self, executor, callback, *args): # def set_default_executor(self, executor): # def getaddrinfo(self, host, port, family=0, type=0, proto=0, flags=0): # def getnameinfo(self, sockaddr, flags=0): # def _add_callback_signalsafe(self, handle): # def set_socket_acceptor(self, sock, acceptor): # def internal_acceptor(accept, acceptor): # def get_event_loop(): # def spawn(cb, *args): # class JegaEventLoop(jega.AbstractEventLoop): . Output only the next line.
def test_recv():
Next line prediction: <|code_start|> def _conn(): s = jsocket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("", 8080)) s.send(b"A" * 10) return "_conn" f1 = executor.submit(_accept) f2 = executor.submit(_conn) r = event_loop.run_until_complete(f1) assert(r == "_accept") r = event_loop.run_until_complete(f2) assert(r == "_conn") # @check_stop def test_recvfrom_into(): print_name() event_loop = loop.get_event_loop() executor = jega.TaskExecutor(event_loop) def _accept(): s = jsocket.socket(jsocket.AF_INET, jsocket.SOCK_STREAM) s.setsockopt(jsocket.SOL_SOCKET, jsocket.SO_REUSEADDR, 1) s.bind(("", 8080)) s.listen(1) c, a = s.accept() assert(a[0] == "127.0.0.1") buf = bytearray(1024) nbytes, addr = c.recvfrom_into(buf) assert(nbytes == 10) assert(buf[:10] == b"A" * 10) <|code_end|> . Use current file imports: (from pytest import * from jega.ext import jsocket from jega import loop from util import * import socket import jega) and context including class names, function names, or small code snippets from other files: # Path: jega/ext/jsocket.py # EBADF = 9 # SOCKETMETHODS = ('setblocking', 'bind', 'fileno', 'listen', 'getpeername', 'getsockname', 'getsockopt', 'setsockopt') # _GLOBAL_DEFAULT_TIMEOUT = __socket__._GLOBAL_DEFAULT_TIMEOUT # _GLOBAL_DEFAULT_TIMEOUT = object() # class _realsocket(_socket.socket): # class _fileobject: # class _closedsocket(object): # class socket(object): # class socket(object): # def __init__(self, sock, mode='rwb', bufsize=-1, close=False): # def closed(self): # def __del__(self): # def close(self): # def inet_ntop(address_family, packed_ip): # def wait_read(fileno, timeout=None, timeout_exc=timeout): # def wait_write(fileno, timeout=None, timeout_exc=timeout): # def wait_readwrite(fileno, timeout=None, timeout_exc=timeout): # def _get_memory(string, offset): # def _dummy(*args): # def internal_accept(s): # def internal_close(s): # def internal_connect(s, address): # def internal_connect_ex(s, address): # def internal_recv(s, *args): # def internal_recvfrom(s, *args): # def internal_recvfrom_into(s, *args): # def internal_recv_into(s, *args): # def internal_send(s, *args): # def internal_sendall(s, data, flags=0): # def internal_sendall(s, data, flags=0): # def internal_sendto(s, *args): # def internal_settimeout(s, howlong): # def internal_gettimeout(s): # def internal_shutdown(s, how): # def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None): # def __enter__(self): # def __exit__(self, *args): # def dup(self): # def _decref_socketios(self): # def _real_close(self, _ss=_socket.socket): # def close(self): # def detach(self): # def accept_block(self): # def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): # def __repr__(self): # def __str__(self): # def _formatinfo(self): # def __enter__(self): # def __exit__(self, *args): # def dup(self): # def makefile(self, mode='r', bufsize=-1): # def accept_block(self): # def socketpair(*args): # def fromfd(fd, family, type, proto=0): # def fromfd(*args): # def getfqdn(name=''): # def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): # def ssl(sock, certificate=None, private_key=None): # # Path: jega/loop.py # _MAX_WORKERS = 5 # def _raise_stop_error(*args): # def __init__(self): # def reset(self): # def add_signal_handler(self, sig, callback, *args): # def _handle_signal(self, sig, arg): # def remove_signal_handler(self, sig): # def _check_signal(self, sig): # def _socketpair(self): # def _close_self_pipe(self): # def _make_self_pipe(self): # def _read_from_self(self): # def _write_to_self(self): # def destroy(self): # def wrap_future(self, future): # def run(self): # def run_once(self): # def run_forever(self): # def run_until_complete(self, future, timeout=None): # def stop(self): # def call_soon_threadsafe(self, callback, *args): # def run_in_executor(self, executor, callback, *args): # def set_default_executor(self, executor): # def getaddrinfo(self, host, port, family=0, type=0, proto=0, flags=0): # def getnameinfo(self, sockaddr, flags=0): # def _add_callback_signalsafe(self, handle): # def set_socket_acceptor(self, sock, acceptor): # def internal_acceptor(accept, acceptor): # def get_event_loop(): # def spawn(cb, *args): # class JegaEventLoop(jega.AbstractEventLoop): . Output only the next line.
return "_accept"
Using the snippet: <|code_start|>patch.patch_socket() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) s.setsockopt(socket.IPPROTO_TCP, socket.TCP_DEFER_ACCEPT, 1) s.bind(("", 5000)) s.listen(1024) loop = jega.get_event_loop() def echo(sock, addr): try: recv = sock.recv send = sock.send while 1: buf = recv(4096) <|code_end|> , determine the next line of code. You have imports: import jega import socket from jega import patch and context (class names, function names, or code) available: # Path: jega/patch.py # def patch_socket(aggressive=False): # def patch_item(module, attr, newitem): # def patch_module(name, items=None): # def slurp_properties(source, destination, ignore=[], srckeys=None): # NONE = object() . Output only the next line.
if not buf:
Based on the snippet: <|code_start|>def test_executor_submit(): print_name() event_loop = loop.get_event_loop() executor = jega.TaskExecutor(event_loop) def _call(a, b): return a + b f = executor.submit(_call, 1, 2) assert(3 == f.result()) def test_executor_until_complete(): print_name() event_loop = loop.get_event_loop() executor = jega.TaskExecutor(event_loop) def _call(a, b): return a + b f = executor.submit(_call, 1, 2) r = event_loop.run_until_complete(f) assert(3 == r) def test_executor_until_complete_exc(): print_name() event_loop = loop.get_event_loop() executor = jega.TaskExecutor(event_loop) def _call(a, b): <|code_end|> , predict the immediate next line with the help of imports: from pytest import * from jega import loop from util import * import socket import jega import functools import functools and context (classes, functions, sometimes code) from other files: # Path: jega/loop.py # _MAX_WORKERS = 5 # def _raise_stop_error(*args): # def __init__(self): # def reset(self): # def add_signal_handler(self, sig, callback, *args): # def _handle_signal(self, sig, arg): # def remove_signal_handler(self, sig): # def _check_signal(self, sig): # def _socketpair(self): # def _close_self_pipe(self): # def _make_self_pipe(self): # def _read_from_self(self): # def _write_to_self(self): # def destroy(self): # def wrap_future(self, future): # def run(self): # def run_once(self): # def run_forever(self): # def run_until_complete(self, future, timeout=None): # def stop(self): # def call_soon_threadsafe(self, callback, *args): # def run_in_executor(self, executor, callback, *args): # def set_default_executor(self, executor): # def getaddrinfo(self, host, port, family=0, type=0, proto=0, flags=0): # def getnameinfo(self, sockaddr, flags=0): # def _add_callback_signalsafe(self, handle): # def set_socket_acceptor(self, sock, acceptor): # def internal_acceptor(accept, acceptor): # def get_event_loop(): # def spawn(cb, *args): # class JegaEventLoop(jega.AbstractEventLoop): . Output only the next line.
return a / b
Given the code snippet: <|code_start|> def test_event_simple(): print_name() ev = Event() def waiter(): r = ev.wait() return r f1 = jega.spawn(waiter) f2 = jega.spawn(ev.set) r = f1.result() <|code_end|> , generate the next line using the imports in this file: from jega.event import * from pytest import * from jega import loop from util import * import jega and context (functions, classes, or occasionally code) from other files: # Path: jega/loop.py # _MAX_WORKERS = 5 # def _raise_stop_error(*args): # def __init__(self): # def reset(self): # def add_signal_handler(self, sig, callback, *args): # def _handle_signal(self, sig, arg): # def remove_signal_handler(self, sig): # def _check_signal(self, sig): # def _socketpair(self): # def _close_self_pipe(self): # def _make_self_pipe(self): # def _read_from_self(self): # def _write_to_self(self): # def destroy(self): # def wrap_future(self, future): # def run(self): # def run_once(self): # def run_forever(self): # def run_until_complete(self, future, timeout=None): # def stop(self): # def call_soon_threadsafe(self, callback, *args): # def run_in_executor(self, executor, callback, *args): # def set_default_executor(self, executor): # def getaddrinfo(self, host, port, family=0, type=0, proto=0, flags=0): # def getnameinfo(self, sockaddr, flags=0): # def _add_callback_signalsafe(self, handle): # def set_socket_acceptor(self, sock, acceptor): # def internal_acceptor(accept, acceptor): # def get_event_loop(): # def spawn(cb, *args): # class JegaEventLoop(jega.AbstractEventLoop): . Output only the next line.
assert(True == r)
Predict the next line for this snippet: <|code_start|> class Packet15Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet byte item_id = streamer.next_short() position = (streamer.next_float(), streamer.next_float()) velocity = (streamer.next_float(), streamer.next_float()) stacks = streamer.next_short() prefix = streamer.next_byte() no_delay = streamer.next_byte() net_id = streamer.next_short() item_object = Item(item_id, net_id, position, velocity, prefix, stacks) if item_id in world.items: ev_man.raise_event(Events.ItemDropUpdate, item_object) else: world.items[item_id] = item_object <|code_end|> with the help of current file imports: from terrabot.util.streamer import Streamer from terrabot.events.events import Events from terrabot.data.item import Item and context from other files: # Path: terrabot/util/streamer.py # class Streamer(object): # """A class for streaming data from a databuffer.""" # # def __init__(self, data): # self.data = data # self.index = 0 # # def next_short(self): # result = struct.unpack("<h", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_u_short(self): # result = struct.unpack("<H", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_int32(self): # result = struct.unpack("<i", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def next_byte(self): # result = self.data[self.index] # self.index += 1 # return result # # def next_float(self): # result = struct.unpack("<f", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def remainder(self): # return self.data[self.index:] # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 # # Path: terrabot/data/item.py , which may contain function names, class names, or code. Output only the next line.
if not item_id in world.item_owner_index:
Using the snippet: <|code_start|> class Packet15Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet byte <|code_end|> , determine the next line of code. You have imports: from terrabot.util.streamer import Streamer from terrabot.events.events import Events from terrabot.data.item import Item and context (class names, function names, or code) available: # Path: terrabot/util/streamer.py # class Streamer(object): # """A class for streaming data from a databuffer.""" # # def __init__(self, data): # self.data = data # self.index = 0 # # def next_short(self): # result = struct.unpack("<h", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_u_short(self): # result = struct.unpack("<H", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_int32(self): # result = struct.unpack("<i", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def next_byte(self): # result = self.data[self.index] # self.index += 1 # return result # # def next_float(self): # result = struct.unpack("<f", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def remainder(self): # return self.data[self.index:] # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 # # Path: terrabot/data/item.py . Output only the next line.
item_id = streamer.next_short()
Based on the snippet: <|code_start|> class Packet15Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet byte item_id = streamer.next_short() position = (streamer.next_float(), streamer.next_float()) velocity = (streamer.next_float(), streamer.next_float()) stacks = streamer.next_short() <|code_end|> , predict the immediate next line with the help of imports: from terrabot.util.streamer import Streamer from terrabot.events.events import Events from terrabot.data.item import Item and context (classes, functions, sometimes code) from other files: # Path: terrabot/util/streamer.py # class Streamer(object): # """A class for streaming data from a databuffer.""" # # def __init__(self, data): # self.data = data # self.index = 0 # # def next_short(self): # result = struct.unpack("<h", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_u_short(self): # result = struct.unpack("<H", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_int32(self): # result = struct.unpack("<i", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def next_byte(self): # result = self.data[self.index] # self.index += 1 # return result # # def next_float(self): # result = struct.unpack("<f", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def remainder(self): # return self.data[self.index:] # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 # # Path: terrabot/data/item.py . Output only the next line.
prefix = streamer.next_byte()
Given the following code snippet before the placeholder: <|code_start|> for y in range(height): for x in range(width): if repeat_count > 0: repeat_count -= 1 world.tiles[starty + y][startx + x] = last_tile else: flag = streamer.next_byte() flag2 = 0 flag3 = 0 if flag & 1: flag2 = streamer.next_byte() if flag2 & 1: flag3 = streamer.next_byte() active = flag & 2 > 0 has_wall = flag & 4 > 0 liquid = flag & 8 > 0 is_short = flag & 32 > 0 repeat_value_present = flag & 64 > 0 extra_repeat_value = flag & 128 > 0 wire = flag2 & 2 > 0 wire2 = flag2 & 4 > 0 wire3 = flag2 & 8 > 0 has_color = flag3 & 8 > 0 has_wall_color = flag3 & 16 > 0 frame_y = 0 <|code_end|> , predict the next line using imports from the current file: import zlib from terrabot.data.tile import Tile from terrabot.util.tileutil import * from terrabot.util.streamer import Streamer from terrabot.events.events import Events and context including class names, function names, and sometimes code from other files: # Path: terrabot/data/tile.py # # Path: terrabot/util/streamer.py # class Streamer(object): # """A class for streaming data from a databuffer.""" # # def __init__(self, data): # self.data = data # self.index = 0 # # def next_short(self): # result = struct.unpack("<h", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_u_short(self): # result = struct.unpack("<H", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_int32(self): # result = struct.unpack("<i", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def next_byte(self): # result = self.data[self.index] # self.index += 1 # return result # # def next_float(self): # result = struct.unpack("<f", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def remainder(self): # return self.data[self.index:] # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 . Output only the next line.
frame_x = 0
Using the snippet: <|code_start|> class PacketAParser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet number byte compressed = streamer.next_byte() if compressed: compressed_data = streamer.remainder() data = zlib.decompress(compressed_data, -zlib.MAX_WBITS) streamer = Streamer(data) startx = streamer.next_int32() starty = streamer.next_int32() width = streamer.next_short() height = streamer.next_short() repeat_count = 0 last_tile = None for y in range(height): for x in range(width): if repeat_count > 0: repeat_count -= 1 world.tiles[starty + y][startx + x] = last_tile else: flag = streamer.next_byte() flag2 = 0 flag3 = 0 if flag & 1: <|code_end|> , determine the next line of code. You have imports: import zlib from terrabot.data.tile import Tile from terrabot.util.tileutil import * from terrabot.util.streamer import Streamer from terrabot.events.events import Events and context (class names, function names, or code) available: # Path: terrabot/data/tile.py # # Path: terrabot/util/streamer.py # class Streamer(object): # """A class for streaming data from a databuffer.""" # # def __init__(self, data): # self.data = data # self.index = 0 # # def next_short(self): # result = struct.unpack("<h", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_u_short(self): # result = struct.unpack("<H", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_int32(self): # result = struct.unpack("<i", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def next_byte(self): # result = self.data[self.index] # self.index += 1 # return result # # def next_float(self): # result = struct.unpack("<f", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def remainder(self): # return self.data[self.index:] # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 . Output only the next line.
flag2 = streamer.next_byte()
Based on the snippet: <|code_start|> starty = streamer.next_int32() width = streamer.next_short() height = streamer.next_short() repeat_count = 0 last_tile = None for y in range(height): for x in range(width): if repeat_count > 0: repeat_count -= 1 world.tiles[starty + y][startx + x] = last_tile else: flag = streamer.next_byte() flag2 = 0 flag3 = 0 if flag & 1: flag2 = streamer.next_byte() if flag2 & 1: flag3 = streamer.next_byte() active = flag & 2 > 0 has_wall = flag & 4 > 0 liquid = flag & 8 > 0 is_short = flag & 32 > 0 repeat_value_present = flag & 64 > 0 extra_repeat_value = flag & 128 > 0 wire = flag2 & 2 > 0 wire2 = flag2 & 4 > 0 <|code_end|> , predict the immediate next line with the help of imports: import zlib from terrabot.data.tile import Tile from terrabot.util.tileutil import * from terrabot.util.streamer import Streamer from terrabot.events.events import Events and context (classes, functions, sometimes code) from other files: # Path: terrabot/data/tile.py # # Path: terrabot/util/streamer.py # class Streamer(object): # """A class for streaming data from a databuffer.""" # # def __init__(self, data): # self.data = data # self.index = 0 # # def next_short(self): # result = struct.unpack("<h", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_u_short(self): # result = struct.unpack("<H", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_int32(self): # result = struct.unpack("<i", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def next_byte(self): # result = self.data[self.index] # self.index += 1 # return result # # def next_float(self): # result = struct.unpack("<f", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def remainder(self): # return self.data[self.index:] # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 . Output only the next line.
wire3 = flag2 & 8 > 0
Continue the code snippet: <|code_start|> class Packet7Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Ignore packet ID byte world.time = streamer.next_int32() world.daynight = streamer.next_byte() <|code_end|> . Use current file imports: from terrabot.util.streamer import Streamer from terrabot.events.events import Events and context (classes, functions, or code) from other files: # Path: terrabot/util/streamer.py # class Streamer(object): # """A class for streaming data from a databuffer.""" # # def __init__(self, data): # self.data = data # self.index = 0 # # def next_short(self): # result = struct.unpack("<h", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_u_short(self): # result = struct.unpack("<H", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_int32(self): # result = struct.unpack("<i", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def next_byte(self): # result = self.data[self.index] # self.index += 1 # return result # # def next_float(self): # result = struct.unpack("<f", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def remainder(self): # return self.data[self.index:] # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 . Output only the next line.
world.moonphase = streamer.next_byte()
Next line prediction: <|code_start|> bot = TerraBot('127.0.0.1') event = bot.get_event_manager() @event.on_event(Events.ItemOwnerChanged) def logged_in(event_id, data): print(data) @event.on_event(Events.ItemDropped) def drop_update(event_id, data): print("New item dropped") @event.on_event(Events.ItemDropUpdate) def drop_update(event_id, data): print("Update on item") print("X: " + str(data.x) + " Y: " + str(data.y)) <|code_end|> . Use current file imports: (from terrabot import TerraBot from terrabot.events import Events) and context including class names, function names, or small code snippets from other files: # Path: terrabot/bot.py # class TerraBot(object): # """A class that handles basic functions of a terraria bot like movement and login""" # # # Defaults to 7777, because that is the default port for the server # def __init__(self, ip, port=7777, protocol=188, name="Terrabot"): # super(TerraBot, self).__init__() # # self.protocol = protocol # # self.world = World() # self.player = Player(name) # # self.evman = EventManager() # # self.client = client.Client(ip, port, self.player, self.world, self.evman) # # self.evman.method_on_event(Events.PlayerID, self.received_player_id) # self.evman.method_on_event(Events.Initialized, self.initialized) # self.evman.method_on_event(Events.Login, self.logged_in) # self.evman.method_on_event(Events.ItemOwnerChanged, self.item_owner_changed) # # self.event_manager.method_on_event(events.Events.) # # def start(self): # self.client.start() # self.client.add_packet(packets.Packet1(self.protocol)) # # def item_owner_changed(self, id, data): # if self.player.logged_in: # self.add_packet(packets.Packet16(data[0], data[1])) # # def received_player_id(self, event_id, data): # self.client.add_packet(packets.Packet4(self.player)) # self.client.add_packet(packets.Packet10(self.player)) # self.client.add_packet(packets.Packet2A(self.player)) # self.client.add_packet(packets.Packet32(self.player)) # for i in range(0, 83): # self.client.add_packet(packets.Packet5(self.player, i)) # self.client.add_packet(packets.Packet6()) # # def initialized(self, event, data): # self.client.add_packet(packets.Packet8(self.player, self.world)) # # def logged_in(self, event, data): # self.client.add_packet(packets.PacketC(self.player, self.world)) # # def message(self, msg, color=None): # if self.player.logged_in: # if color: # hex_code = '%02x%02x%02x' % color # msg = "[c/" + hex_code + ":" + msg + "]" # self.client.add_packet(packets.Packet19(self.player, msg)) # # def get_event_manager(self): # return self.evman # # def stop(self): # self.client.stop() # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 . Output only the next line.
bot.start()
Based on the snippet: <|code_start|> bot = TerraBot('127.0.0.1') event = bot.get_event_manager() @event.on_event(Events.ItemOwnerChanged) def logged_in(event_id, data): print(data) @event.on_event(Events.ItemDropped) <|code_end|> , predict the immediate next line with the help of imports: from terrabot import TerraBot from terrabot.events import Events and context (classes, functions, sometimes code) from other files: # Path: terrabot/bot.py # class TerraBot(object): # """A class that handles basic functions of a terraria bot like movement and login""" # # # Defaults to 7777, because that is the default port for the server # def __init__(self, ip, port=7777, protocol=188, name="Terrabot"): # super(TerraBot, self).__init__() # # self.protocol = protocol # # self.world = World() # self.player = Player(name) # # self.evman = EventManager() # # self.client = client.Client(ip, port, self.player, self.world, self.evman) # # self.evman.method_on_event(Events.PlayerID, self.received_player_id) # self.evman.method_on_event(Events.Initialized, self.initialized) # self.evman.method_on_event(Events.Login, self.logged_in) # self.evman.method_on_event(Events.ItemOwnerChanged, self.item_owner_changed) # # self.event_manager.method_on_event(events.Events.) # # def start(self): # self.client.start() # self.client.add_packet(packets.Packet1(self.protocol)) # # def item_owner_changed(self, id, data): # if self.player.logged_in: # self.add_packet(packets.Packet16(data[0], data[1])) # # def received_player_id(self, event_id, data): # self.client.add_packet(packets.Packet4(self.player)) # self.client.add_packet(packets.Packet10(self.player)) # self.client.add_packet(packets.Packet2A(self.player)) # self.client.add_packet(packets.Packet32(self.player)) # for i in range(0, 83): # self.client.add_packet(packets.Packet5(self.player, i)) # self.client.add_packet(packets.Packet6()) # # def initialized(self, event, data): # self.client.add_packet(packets.Packet8(self.player, self.world)) # # def logged_in(self, event, data): # self.client.add_packet(packets.PacketC(self.player, self.world)) # # def message(self, msg, color=None): # if self.player.logged_in: # if color: # hex_code = '%02x%02x%02x' % color # msg = "[c/" + hex_code + ":" + msg + "]" # self.client.add_packet(packets.Packet19(self.player, msg)) # # def get_event_manager(self): # return self.evman # # def stop(self): # self.client.stop() # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 . Output only the next line.
def drop_update(event_id, data):
Given the following code snippet before the placeholder: <|code_start|> # Create a TerraBot object bot = TerraBot('127.0.0.1') event = bot.get_event_manager() # Connect a function to an event using a decorator @event.on_event(Events.Chat) def chat(event_id, msg): # Do something with the message # In this case, stop the bot if the word "Stop" occurs print(msg) if "stop" in msg: bot.stop() # Start the bot bot.start() # And wait <|code_end|> , predict the next line using imports from the current file: from terrabot import TerraBot from terrabot.events import Events and context including class names, function names, and sometimes code from other files: # Path: terrabot/bot.py # class TerraBot(object): # """A class that handles basic functions of a terraria bot like movement and login""" # # # Defaults to 7777, because that is the default port for the server # def __init__(self, ip, port=7777, protocol=188, name="Terrabot"): # super(TerraBot, self).__init__() # # self.protocol = protocol # # self.world = World() # self.player = Player(name) # # self.evman = EventManager() # # self.client = client.Client(ip, port, self.player, self.world, self.evman) # # self.evman.method_on_event(Events.PlayerID, self.received_player_id) # self.evman.method_on_event(Events.Initialized, self.initialized) # self.evman.method_on_event(Events.Login, self.logged_in) # self.evman.method_on_event(Events.ItemOwnerChanged, self.item_owner_changed) # # self.event_manager.method_on_event(events.Events.) # # def start(self): # self.client.start() # self.client.add_packet(packets.Packet1(self.protocol)) # # def item_owner_changed(self, id, data): # if self.player.logged_in: # self.add_packet(packets.Packet16(data[0], data[1])) # # def received_player_id(self, event_id, data): # self.client.add_packet(packets.Packet4(self.player)) # self.client.add_packet(packets.Packet10(self.player)) # self.client.add_packet(packets.Packet2A(self.player)) # self.client.add_packet(packets.Packet32(self.player)) # for i in range(0, 83): # self.client.add_packet(packets.Packet5(self.player, i)) # self.client.add_packet(packets.Packet6()) # # def initialized(self, event, data): # self.client.add_packet(packets.Packet8(self.player, self.world)) # # def logged_in(self, event, data): # self.client.add_packet(packets.PacketC(self.player, self.world)) # # def message(self, msg, color=None): # if self.player.logged_in: # if color: # hex_code = '%02x%02x%02x' % color # msg = "[c/" + hex_code + ":" + msg + "]" # self.client.add_packet(packets.Packet19(self.player, msg)) # # def get_event_manager(self): # return self.evman # # def stop(self): # self.client.stop() # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 . Output only the next line.
while bot.client.running:
Given the code snippet: <|code_start|> # Create a TerraBot object bot = TerraBot('127.0.0.1') event = bot.get_event_manager() # Connect a function to an event using a decorator @event.on_event(Events.Chat) def chat(event_id, msg): # Do something with the message # In this case, stop the bot if the word "Stop" occurs print(msg) <|code_end|> , generate the next line using the imports in this file: from terrabot import TerraBot from terrabot.events import Events and context (functions, classes, or occasionally code) from other files: # Path: terrabot/bot.py # class TerraBot(object): # """A class that handles basic functions of a terraria bot like movement and login""" # # # Defaults to 7777, because that is the default port for the server # def __init__(self, ip, port=7777, protocol=188, name="Terrabot"): # super(TerraBot, self).__init__() # # self.protocol = protocol # # self.world = World() # self.player = Player(name) # # self.evman = EventManager() # # self.client = client.Client(ip, port, self.player, self.world, self.evman) # # self.evman.method_on_event(Events.PlayerID, self.received_player_id) # self.evman.method_on_event(Events.Initialized, self.initialized) # self.evman.method_on_event(Events.Login, self.logged_in) # self.evman.method_on_event(Events.ItemOwnerChanged, self.item_owner_changed) # # self.event_manager.method_on_event(events.Events.) # # def start(self): # self.client.start() # self.client.add_packet(packets.Packet1(self.protocol)) # # def item_owner_changed(self, id, data): # if self.player.logged_in: # self.add_packet(packets.Packet16(data[0], data[1])) # # def received_player_id(self, event_id, data): # self.client.add_packet(packets.Packet4(self.player)) # self.client.add_packet(packets.Packet10(self.player)) # self.client.add_packet(packets.Packet2A(self.player)) # self.client.add_packet(packets.Packet32(self.player)) # for i in range(0, 83): # self.client.add_packet(packets.Packet5(self.player, i)) # self.client.add_packet(packets.Packet6()) # # def initialized(self, event, data): # self.client.add_packet(packets.Packet8(self.player, self.world)) # # def logged_in(self, event, data): # self.client.add_packet(packets.PacketC(self.player, self.world)) # # def message(self, msg, color=None): # if self.player.logged_in: # if color: # hex_code = '%02x%02x%02x' % color # msg = "[c/" + hex_code + ":" + msg + "]" # self.client.add_packet(packets.Packet19(self.player, msg)) # # def get_event_manager(self): # return self.evman # # def stop(self): # self.client.stop() # # Path: terrabot/events/events.py # class Events(enum.Enum): # # Trigger: chat message # # Data: message as string # Chat = 0 # # # Trigger: Tile information # # Data: 2D array of Tiles # TileUpdate = 1 # # # Trigger: Login # # Data: null # Login = 2 # # # Trigger: PlayerID packet comes in # # Data: PlayerID as int # PlayerID = 3 # # # Trigger: Access blocked # # Data: reason-message as string # Blocked = 4 # # # Trigger: Initialization on the server # # Data: null # Initialized = 5 # # # Trigger: Item owner changes # # Data: Tuple: (item_id, owner_id) # ItemOwnerChanged = 6 # # # Trigger: A new item drops # # Data: Item object # ItemDropped = 7 # # # Trigger: Server sends update on an item # # Data: Item object # ItemDropUpdate = 8 # # # Trigger: A new player joins # # Data: PlayerID # NewPlayer = 9 . Output only the next line.
if "stop" in msg:
Next line prediction: <|code_start|> class Packet39Parser(object): def parse(self, world, player, data, ev_man): streamer = Streamer(data) streamer.next_byte() # Skip packet number item_index = streamer.next_short() <|code_end|> . Use current file imports: (from terrabot.util.streamer import Streamer) and context including class names, function names, or small code snippets from other files: # Path: terrabot/util/streamer.py # class Streamer(object): # """A class for streaming data from a databuffer.""" # # def __init__(self, data): # self.data = data # self.index = 0 # # def next_short(self): # result = struct.unpack("<h", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_u_short(self): # result = struct.unpack("<H", self.data[self.index: self.index + 2])[0] # self.index += 2 # return result # # def next_int32(self): # result = struct.unpack("<i", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def next_byte(self): # result = self.data[self.index] # self.index += 1 # return result # # def next_float(self): # result = struct.unpack("<f", self.data[self.index: self.index + 4])[0] # self.index += 4 # return result # # def remainder(self): # return self.data[self.index:] . Output only the next line.
world.item_owner_index[item_index] = 255
Continue the code snippet: <|code_start|> @staticmethod def convert(value, unit, axis): 'convert value to a scalar or array' return dates.date2num(value) @staticmethod def axisinfo(unit, axis): 'return major and minor tick locators and formatters' if unit!='date': return None majloc = dates.AutoDateLocator() majfmt = dates.AutoDateFormatter(majloc) return AxisInfo(majloc=majloc, majfmt=majfmt, label='date') @staticmethod def default_units(x, axis): 'return the default unit for x or None' return 'date' # finally we register our object type with a converter units.registry[datetime.date] = DateConverter() """ from __future__ import print_function class AxisInfo: """information to support default axis labeling and tick labeling, and default limits""" <|code_end|> . Use current file imports: from matplotlib.cbook import iterable, is_numlike import numpy as np and context (classes, functions, or code) from other files: # Path: matplotlib/cbook.py # def iterable(obj): # 'return true if *obj* is iterable' # try: # iter(obj) # except TypeError: # return False # return True # # def is_numlike(obj): # 'return true if *obj* looks like a number' # try: # obj + 1 # except: # return False # else: # return True . Output only the next line.
def __init__(self, majloc=None, minloc=None,
Using the snippet: <|code_start|> 'convert value to a scalar or array' return dates.date2num(value) @staticmethod def axisinfo(unit, axis): 'return major and minor tick locators and formatters' if unit!='date': return None majloc = dates.AutoDateLocator() majfmt = dates.AutoDateFormatter(majloc) return AxisInfo(majloc=majloc, majfmt=majfmt, label='date') @staticmethod def default_units(x, axis): 'return the default unit for x or None' return 'date' # finally we register our object type with a converter units.registry[datetime.date] = DateConverter() """ from __future__ import print_function class AxisInfo: """information to support default axis labeling and tick labeling, and default limits""" def __init__(self, majloc=None, minloc=None, majfmt=None, minfmt=None, label=None, <|code_end|> , determine the next line of code. You have imports: from matplotlib.cbook import iterable, is_numlike import numpy as np and context (class names, function names, or code) available: # Path: matplotlib/cbook.py # def iterable(obj): # 'return true if *obj* is iterable' # try: # iter(obj) # except TypeError: # return False # return True # # def is_numlike(obj): # 'return true if *obj* looks like a number' # try: # obj + 1 # except: # return False # else: # return True . Output only the next line.
default_limits=None):
Given the following code snippet before the placeholder: <|code_start|> log = core.log class CassandraMigrations(core.MigrationsExecutor): engine = 'cassandra' filename_extensions = ['cql'] TABLE = 'migration' def __init__(self, db_config, repository): core.MigrationsExecutor.__init__(self, db_config, repository) core._assert_values_exist(db_config, 'cqlsh_path', 'pylib_path', 'keyspace', 'cluster_kwargs') <|code_end|> , predict the next line using imports from the current file: import os.path import sys import imp import datetime import cassandra.cluster import cassandra.protocol import click import cqlsh import cqlsh from mschematool import core from cqlshlib import cql3handling and context including class names, function names, and sometimes code from other files: # Path: mschematool/core.py # DEFAULT_CONFIG_MODULE_NAME = 'mschematool_config' # ENGINE_TO_IMPL = { # 'postgres': 'mschematool.executors.postgres.PostgresMigrations', # 'cassandra': 'mschematool.executors.cassandradb.CassandraMigrations', # 'sqlite3': 'mschematool.executors.sqlite3db.Sqlite3Migrations', # } # def _simplify_whitespace(s): # def _assert_values_exist(d, *keys): # def _import_class(cls_path): # def __init__(self, verbose, config_path): # def _setup_logging(self): # def _load_config(self): # def module(self): # def _sqlfile_to_statements(sql): # def get_migrations(self, exclude=None): # def generate_migration_name(self, name, suffix): # def migration_type(self, migration): # def __init__(self, dir, migration_patterns): # def _get_all_filenames(self): # def get_migrations(self, exclude=None): # def __init__(self, db_config, repository): # def supported_filename_globs(cls): # def glob_from_ext(ext): # def initialize(self): # def fetch_executed_migrations(self): # def execute_python_migration(self, migration, module): # def execute_native_migration(self, migration): # def _call_migrate(self, module, connection_param): # def execute_migration(self, migration_file_relative): # def __init__(self, config, dbnick): # def not_executed_migration_files(self): # def execute_after_sync(self): # class Config(object): # class MigrationsRepository(object): # class DirRepository(MigrationsRepository): # class MigrationsExecutor(object): # class MSchemaTool(object): . Output only the next line.
if db_config['pylib_path'] not in sys.path:
Given the code snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals def make_venv(): enable_coverage() venv = Path('venv') run('virtualenv', venv.strpath) install_coverage(venv.strpath) pip = venv.join('bin/pip').strpath run(pip, 'install', 'venv-update==' + __version__) return venv @pytest.mark.usefixtures('pypi_server', 'tmpdir') def test_circular_dependencies(): """pip-faster should be able to install packages with circular dependencies.""" <|code_end|> , generate the next line using the imports in this file: import sys import pytest from testing import cached_wheels from testing import enable_coverage from testing import install_coverage from testing import Path from testing import pip_freeze from testing import run from testing import strip_pip_warnings from testing import uncolor from venv_update import __version__ from os import environ and context (functions, classes, or occasionally code) from other files: # Path: venv_update.py # DEFAULT_VIRTUALENV_PATH = 'venv' # DEFAULT_OPTION_VALUES = { # 'venv=': (DEFAULT_VIRTUALENV_PATH,), # 'install=': ('-r', 'requirements.txt',), # 'pip-command=': ('pip-faster', 'install', '--upgrade', '--prune'), # 'bootstrap-deps=': ('venv-update==' + __version__,), # } # def parseargs(argv): # def timid_relpath(arg): # def shellescape(args): # def colorize(cmd): # def run(cmd): # def info(msg): # def check_output(cmd): # def samefile(file1, file2): # def exec_(argv): # never returns # def __init__(self): # def exec_scratch_virtualenv(args): # def get_original_path(venv_path): # TODO-TEST: a unit test # def get_python_version(interpreter): # def invalid_virtualenv_reason(venv_path, source_python, destination_python, virtualenv_system_site_packages): # def ensure_virtualenv(args, return_values): # def wait_for_all_subprocesses(): # def touch(filename, timestamp): # def mark_venv_valid(venv_path): # def mark_venv_invalid(venv_path): # def dotpy(filename): # def venv_executable(venv_path, executable): # def venv_python(venv_path): # def user_cache_dir(): # def venv_update( # venv=DEFAULT_OPTION_VALUES['venv='], # install=DEFAULT_OPTION_VALUES['install='], # pip_command=DEFAULT_OPTION_VALUES['pip-command='], # bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps='], # ): # def execfile_(filename): # def pip_faster(venv_path, pip_command, install, bootstrap_deps): # def raise_on_failure(mainfunc, ignore_return=False): # def main(): # class Scratch(object): # class return_values(object): . Output only the next line.
venv = make_venv()
Next line prediction: <|code_start|>from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals def assert_c_extension_runs(): out, err = run('venv/bin/c-extension-script') assert err == '' assert out == 'hello world\n' <|code_end|> . Use current file imports: (import fileinput import pytest from testing import enable_coverage from testing import OtherPython from testing import Path from testing import pip_freeze from testing import requirements from testing import run from testing import strip_pip_warnings from testing import TOP from testing import uncolor from testing import venv_update from testing import venv_update_symlink_pwd from venv_update import __version__ from sys import executable as python from sys import version from sys import executable as python) and context including class names, function names, or small code snippets from other files: # Path: venv_update.py # DEFAULT_VIRTUALENV_PATH = 'venv' # DEFAULT_OPTION_VALUES = { # 'venv=': (DEFAULT_VIRTUALENV_PATH,), # 'install=': ('-r', 'requirements.txt',), # 'pip-command=': ('pip-faster', 'install', '--upgrade', '--prune'), # 'bootstrap-deps=': ('venv-update==' + __version__,), # } # def parseargs(argv): # def timid_relpath(arg): # def shellescape(args): # def colorize(cmd): # def run(cmd): # def info(msg): # def check_output(cmd): # def samefile(file1, file2): # def exec_(argv): # never returns # def __init__(self): # def exec_scratch_virtualenv(args): # def get_original_path(venv_path): # TODO-TEST: a unit test # def get_python_version(interpreter): # def invalid_virtualenv_reason(venv_path, source_python, destination_python, virtualenv_system_site_packages): # def ensure_virtualenv(args, return_values): # def wait_for_all_subprocesses(): # def touch(filename, timestamp): # def mark_venv_valid(venv_path): # def mark_venv_invalid(venv_path): # def dotpy(filename): # def venv_executable(venv_path, executable): # def venv_python(venv_path): # def user_cache_dir(): # def venv_update( # venv=DEFAULT_OPTION_VALUES['venv='], # install=DEFAULT_OPTION_VALUES['install='], # pip_command=DEFAULT_OPTION_VALUES['pip-command='], # bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps='], # ): # def execfile_(filename): # def pip_faster(venv_path, pip_command, install, bootstrap_deps): # def raise_on_failure(mainfunc, ignore_return=False): # def main(): # class Scratch(object): # class return_values(object): . Output only the next line.
out, err = run('sh', '-c', '. venv/bin/activate && c-extension-script')
Here is a snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals ENV_WHITELIST = ( # allows coverage of subprocesses 'COVERAGE_PROCESS_START', # used in the configuration of coverage 'TOP', # let's not fill up the root partition, please 'TMPDIR', # these help my debugger not freak out 'HOME', <|code_end|> . Write the next line using the current file imports: import os import socket import subprocess import sys import time import pytest import six from contextlib import contextmanager from errno import ECONNREFUSED from ephemeral_port_reserve import reserve from testing import run from testing import TOP from venv_update import colorize from sys import executable from os import defpath from os.path import dirname from _pytest.assertion.util import assertrepr_compare and context from other files: # Path: venv_update.py # def colorize(cmd): # from os import isatty # # if isatty(1): # template = '\033[36m>\033[m \033[32m{0}\033[m' # else: # template = '> {0}' # # return template.format(shellescape(cmd)) , which may include functions, classes, or code. Output only the next line.
'TERM',
Given the code snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals @pytest.mark.usefixtures('pypi_server') def test_trivial(tmpdir): tmpdir.chdir() <|code_end|> , generate the next line using the imports in this file: import re import sys import pytest import virtualenv import virtualenv from subprocess import CalledProcessError from py._path.local import LocalPath as Path from testing import cached_wheels from testing import enable_coverage from testing import install_coverage from testing import OtherPython from testing import pip_freeze from testing import requirements from testing import run from testing import strip_coverage_warnings from testing import strip_pip_warnings from testing import TOP from testing import uncolor from testing import venv_update from venv_update import __version__ from os import environ from subprocess import Popen from os import close from testing.capture_subprocess import read_all from os import openpty from testing.capture_subprocess import pty_normalize_newlines from os import pipe and context (functions, classes, or occasionally code) from other files: # Path: venv_update.py # DEFAULT_VIRTUALENV_PATH = 'venv' # DEFAULT_OPTION_VALUES = { # 'venv=': (DEFAULT_VIRTUALENV_PATH,), # 'install=': ('-r', 'requirements.txt',), # 'pip-command=': ('pip-faster', 'install', '--upgrade', '--prune'), # 'bootstrap-deps=': ('venv-update==' + __version__,), # } # def parseargs(argv): # def timid_relpath(arg): # def shellescape(args): # def colorize(cmd): # def run(cmd): # def info(msg): # def check_output(cmd): # def samefile(file1, file2): # def exec_(argv): # never returns # def __init__(self): # def exec_scratch_virtualenv(args): # def get_original_path(venv_path): # TODO-TEST: a unit test # def get_python_version(interpreter): # def invalid_virtualenv_reason(venv_path, source_python, destination_python, virtualenv_system_site_packages): # def ensure_virtualenv(args, return_values): # def wait_for_all_subprocesses(): # def touch(filename, timestamp): # def mark_venv_valid(venv_path): # def mark_venv_invalid(venv_path): # def dotpy(filename): # def venv_executable(venv_path, executable): # def venv_python(venv_path): # def user_cache_dir(): # def venv_update( # venv=DEFAULT_OPTION_VALUES['venv='], # install=DEFAULT_OPTION_VALUES['install='], # pip_command=DEFAULT_OPTION_VALUES['pip-command='], # bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps='], # ): # def execfile_(filename): # def pip_faster(venv_path, pip_command, install, bootstrap_deps): # def raise_on_failure(mainfunc, ignore_return=False): # def main(): # class Scratch(object): # class return_values(object): . Output only the next line.
requirements('')
Predict the next line for this snippet: <|code_start|>from __future__ import print_function from __future__ import unicode_literals ALWAYS = {'pip', 'setuptools', 'venv-update', 'wheel'} def get_installed(): out, err = run('myvenv/bin/python', '-c', '''\ import pip_faster as p for p in sorted(p.reqnames(p.pip_get_installed())): print(p)''') assert err == '' out = set(out.split()) # Most python distributions which have argparse in the stdlib fail to # expose it to setuptools as an installed package (it seems all but ubuntu # do this). This results in argparse sometimes being installed locally, # sometimes not, even for a specific version of python. # We normalize by never looking at argparse =/ out -= {'argparse'} # these will always be present assert ALWAYS.issubset(out) return sorted(out - ALWAYS) @pytest.mark.usefixtures('pypi_server_with_fallback') <|code_end|> with the help of current file imports: import pytest from pip_faster import PY2 from testing import run from venv_update import __version__ and context from other files: # Path: pip_faster.py # PY2 = str is bytes # # Path: venv_update.py # DEFAULT_VIRTUALENV_PATH = 'venv' # DEFAULT_OPTION_VALUES = { # 'venv=': (DEFAULT_VIRTUALENV_PATH,), # 'install=': ('-r', 'requirements.txt',), # 'pip-command=': ('pip-faster', 'install', '--upgrade', '--prune'), # 'bootstrap-deps=': ('venv-update==' + __version__,), # } # def parseargs(argv): # def timid_relpath(arg): # def shellescape(args): # def colorize(cmd): # def run(cmd): # def info(msg): # def check_output(cmd): # def samefile(file1, file2): # def exec_(argv): # never returns # def __init__(self): # def exec_scratch_virtualenv(args): # def get_original_path(venv_path): # TODO-TEST: a unit test # def get_python_version(interpreter): # def invalid_virtualenv_reason(venv_path, source_python, destination_python, virtualenv_system_site_packages): # def ensure_virtualenv(args, return_values): # def wait_for_all_subprocesses(): # def touch(filename, timestamp): # def mark_venv_valid(venv_path): # def mark_venv_invalid(venv_path): # def dotpy(filename): # def venv_executable(venv_path, executable): # def venv_python(venv_path): # def user_cache_dir(): # def venv_update( # venv=DEFAULT_OPTION_VALUES['venv='], # install=DEFAULT_OPTION_VALUES['install='], # pip_command=DEFAULT_OPTION_VALUES['pip-command='], # bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps='], # ): # def execfile_(filename): # def pip_faster(venv_path, pip_command, install, bootstrap_deps): # def raise_on_failure(mainfunc, ignore_return=False): # def main(): # class Scratch(object): # class return_values(object): , which may contain function names, class names, or code. Output only the next line.
def test_pip_get_installed(tmpdir):
Given the code snippet: <|code_start|>for p in sorted(p.reqnames(p.pip_get_installed())): print(p)''') assert err == '' out = set(out.split()) # Most python distributions which have argparse in the stdlib fail to # expose it to setuptools as an installed package (it seems all but ubuntu # do this). This results in argparse sometimes being installed locally, # sometimes not, even for a specific version of python. # We normalize by never looking at argparse =/ out -= {'argparse'} # these will always be present assert ALWAYS.issubset(out) return sorted(out - ALWAYS) @pytest.mark.usefixtures('pypi_server_with_fallback') def test_pip_get_installed(tmpdir): tmpdir.chdir() run('virtualenv', 'myvenv') run('rm', '-rf', 'myvenv/local') run('myvenv/bin/pip', 'install', 'venv-update==' + __version__) assert get_installed() == [] run( 'myvenv/bin/pip', 'install', <|code_end|> , generate the next line using the imports in this file: import pytest from pip_faster import PY2 from testing import run from venv_update import __version__ and context (functions, classes, or occasionally code) from other files: # Path: pip_faster.py # PY2 = str is bytes # # Path: venv_update.py # DEFAULT_VIRTUALENV_PATH = 'venv' # DEFAULT_OPTION_VALUES = { # 'venv=': (DEFAULT_VIRTUALENV_PATH,), # 'install=': ('-r', 'requirements.txt',), # 'pip-command=': ('pip-faster', 'install', '--upgrade', '--prune'), # 'bootstrap-deps=': ('venv-update==' + __version__,), # } # def parseargs(argv): # def timid_relpath(arg): # def shellescape(args): # def colorize(cmd): # def run(cmd): # def info(msg): # def check_output(cmd): # def samefile(file1, file2): # def exec_(argv): # never returns # def __init__(self): # def exec_scratch_virtualenv(args): # def get_original_path(venv_path): # TODO-TEST: a unit test # def get_python_version(interpreter): # def invalid_virtualenv_reason(venv_path, source_python, destination_python, virtualenv_system_site_packages): # def ensure_virtualenv(args, return_values): # def wait_for_all_subprocesses(): # def touch(filename, timestamp): # def mark_venv_valid(venv_path): # def mark_venv_invalid(venv_path): # def dotpy(filename): # def venv_executable(venv_path, executable): # def venv_python(venv_path): # def user_cache_dir(): # def venv_update( # venv=DEFAULT_OPTION_VALUES['venv='], # install=DEFAULT_OPTION_VALUES['install='], # pip_command=DEFAULT_OPTION_VALUES['pip-command='], # bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps='], # ): # def execfile_(filename): # def pip_faster(venv_path, pip_command, install, bootstrap_deps): # def raise_on_failure(mainfunc, ignore_return=False): # def main(): # class Scratch(object): # class return_values(object): . Output only the next line.
'pytest',
Next line prediction: <|code_start|> last_line = HELP_OUTPUT.rsplit('\n', 2)[-2].strip() assert last_line.startswith('Please send issues to: https://') out, err = venv_update('--help') assert strip_coverage_warnings(err) == '' assert out == HELP_OUTPUT out, err = venv_update('-h') assert strip_coverage_warnings(err) == '' assert out == HELP_OUTPUT def test_version(): assert VERSION out, err = venv_update('--version') assert strip_coverage_warnings(err) == '' assert out == VERSION + '\n' out, err = venv_update('-V') assert strip_coverage_warnings(err) == '' assert out == VERSION + '\n' def test_bad_option(): with pytest.raises(CalledProcessError) as excinfo: venv_update('venv') out, err = excinfo.value.result assert strip_coverage_warnings(err) == '''\ <|code_end|> . Use current file imports: (from testing import strip_coverage_warnings from testing import venv_update from venv_update import __doc__ as HELP_OUTPUT from venv_update import __version__ as VERSION from subprocess import CalledProcessError import pytest) and context including class names, function names, or small code snippets from other files: # Path: venv_update.py # DEFAULT_VIRTUALENV_PATH = 'venv' # DEFAULT_OPTION_VALUES = { # 'venv=': (DEFAULT_VIRTUALENV_PATH,), # 'install=': ('-r', 'requirements.txt',), # 'pip-command=': ('pip-faster', 'install', '--upgrade', '--prune'), # 'bootstrap-deps=': ('venv-update==' + __version__,), # } # def parseargs(argv): # def timid_relpath(arg): # def shellescape(args): # def colorize(cmd): # def run(cmd): # def info(msg): # def check_output(cmd): # def samefile(file1, file2): # def exec_(argv): # never returns # def __init__(self): # def exec_scratch_virtualenv(args): # def get_original_path(venv_path): # TODO-TEST: a unit test # def get_python_version(interpreter): # def invalid_virtualenv_reason(venv_path, source_python, destination_python, virtualenv_system_site_packages): # def ensure_virtualenv(args, return_values): # def wait_for_all_subprocesses(): # def touch(filename, timestamp): # def mark_venv_valid(venv_path): # def mark_venv_invalid(venv_path): # def dotpy(filename): # def venv_executable(venv_path, executable): # def venv_python(venv_path): # def user_cache_dir(): # def venv_update( # venv=DEFAULT_OPTION_VALUES['venv='], # install=DEFAULT_OPTION_VALUES['install='], # pip_command=DEFAULT_OPTION_VALUES['pip-command='], # bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps='], # ): # def execfile_(filename): # def pip_faster(venv_path, pip_command, install, bootstrap_deps): # def raise_on_failure(mainfunc, ignore_return=False): # def main(): # class Scratch(object): # class return_values(object): # # Path: venv_update.py # DEFAULT_VIRTUALENV_PATH = 'venv' # DEFAULT_OPTION_VALUES = { # 'venv=': (DEFAULT_VIRTUALENV_PATH,), # 'install=': ('-r', 'requirements.txt',), # 'pip-command=': ('pip-faster', 'install', '--upgrade', '--prune'), # 'bootstrap-deps=': ('venv-update==' + __version__,), # } # def parseargs(argv): # def timid_relpath(arg): # def shellescape(args): # def colorize(cmd): # def run(cmd): # def info(msg): # def check_output(cmd): # def samefile(file1, file2): # def exec_(argv): # never returns # def __init__(self): # def exec_scratch_virtualenv(args): # def get_original_path(venv_path): # TODO-TEST: a unit test # def get_python_version(interpreter): # def invalid_virtualenv_reason(venv_path, source_python, destination_python, virtualenv_system_site_packages): # def ensure_virtualenv(args, return_values): # def wait_for_all_subprocesses(): # def touch(filename, timestamp): # def mark_venv_valid(venv_path): # def mark_venv_invalid(venv_path): # def dotpy(filename): # def venv_executable(venv_path, executable): # def venv_python(venv_path): # def user_cache_dir(): # def venv_update( # venv=DEFAULT_OPTION_VALUES['venv='], # install=DEFAULT_OPTION_VALUES['install='], # pip_command=DEFAULT_OPTION_VALUES['pip-command='], # bootstrap_deps=DEFAULT_OPTION_VALUES['bootstrap-deps='], # ): # def execfile_(filename): # def pip_faster(venv_path, pip_command, install, bootstrap_deps): # def raise_on_failure(mainfunc, ignore_return=False): # def main(): # class Scratch(object): # class return_values(object): . Output only the next line.
invalid option: venv
Given the code snippet: <|code_start|> class ChatRecord(Record): record_type = None database_id = '_public' def save(self): database = self._get_database() database.save([self]) def delete(self): <|code_end|> , generate the next line using the imports in this file: from skygear.models import Record, RecordID, Reference from .database import Database from .predicate import Predicate from .query import Query from .utils import _get_container and context (functions, classes, or occasionally code) from other files: # Path: chat/database.py # class Database(object): # def __init__(self, container, database_id): # self.container = container # self.database_id = database_id # # def save(self, arg, atomic=False): # if not isinstance(arg, list): # arg = [arg] # # if len(arg) == 0: # return {'result': []} # # records = [serialize_record(item) # if isinstance(item, Record) else item # for item in arg] # return self.container.send_action('record:save', { # 'database_id': self.database_id, # 'records': records, # 'atomic': atomic # }) # # @staticmethod # def _encode_id(record_id): # return record_id.type + "/" + record_id.key # # def delete(self, arg): # if not isinstance(arg, list): # arg = [arg] # ids = [Database._encode_id(item.id) # if isinstance(item, Record) # else item # for item in arg] # return self.container.send_action('record:delete', { # 'database_id': self.database_id, # 'ids': ids # }) # # def query(self, query): # include = {v: {"$type": "keypath", "$val": v} # for v in list(set(query.include))} # # payload = {'database_id': self.database_id, # 'record_type': query.record_type, # 'predicate': query.predicate.to_dict(), # 'count': query.count, # 'sort': query.sort, # 'include': include} # # if query.offset is not None: # payload['offset'] = query.offset # if query.limit is not None: # payload['limit'] = query.limit # result = self.container.send_action('record:query', payload) # if 'error' in result: # raise SkygearChatException(result['error']['message']) # result = result['result'] # output = [] # for r in result: # record = deserialize_record(r) # if '_transient' in r: # t = r['_transient'] # record['_transient'] = {k: deserialize_record(t[k]) # for k in t.keys()} # if 'attachment' in r: # record['attachment'] = r['attachment'].copy() # record['attachment']['$url'] =\ # sign_asset_url(r['attachment']['$name']) # output.append(record) # return output # # Path: chat/predicate.py # class Predicate(object): # AND = 'and' # OR = 'or' # NOT = 'not' # # def __init__(self, **kwargs): # self.op = kwargs.pop('op', Predicate.AND) # # Need to use ordered dict in order to pass unit test in python 3.5. # # See https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep468 # od = collections.OrderedDict(sorted(kwargs.items())) # self.conditions = [(key, kwargs[key]) for key in od.keys()] # # def __and__(self, other): # new_instance = Predicate() # if self.op == Predicate.AND: # new_instance.conditions = copy.copy(self.conditions) # if other.op == self.op: # new_instance.conditions += other.conditions # else: # new_instance.conditions.append(other) # else: # new_instance.conditions = [self, other] # return new_instance # # def __or__(self, other): # new_instance = Predicate(op=Predicate.OR) # if self.op == Predicate.OR: # new_instance.conditions = copy.copy(self.conditions) # if other.op == self.op: # new_instance.conditions += other.conditions # else: # new_instance.conditions.append(other) # else: # new_instance.conditions = [self, other] # return new_instance # # def __invert__(self): # new_instance = Predicate(op=Predicate.NOT) # new_instance.conditions = [self] # return new_instance # # @classmethod # def condition_to_dict(cls, t): # field, op = t[0].split("__") # return [op, {"$type": "keypath", "$val": field}, t[1]] # # def to_dict(self, root=None): # if root is None: # root = self # if root is None: # return [] # if isinstance(root, Predicate): # num_conditions = len(root.conditions) # if num_conditions == 0: # return [] # elif num_conditions == 1: # result = self.to_dict(root.conditions[0]) # if root.op != Predicate.NOT: # return result # return [root.op, result] # else: # return [root.op] + [self.to_dict(d) for d in root.conditions] # elif type(root) == tuple: # return Predicate.condition_to_dict(root) # else: # return [] # # Path: chat/query.py # class Query: # def __init__(self, record_type, # predicate=None, count=False, # limit=50, offset=None, include=[]): # self.record_type = record_type # if predicate is None: # predicate = Predicate() # self.predicate = predicate # self.count = count # self.sort = [] # self.limit = limit # self.offset = offset # self.include = include # # def add_order(self, key, order): # self.sort.append([{'$type': 'keypath', '$val': key}, order]) # return self # # Path: chat/utils.py # def _get_container(): # return SkygearContainer(api_key=skyoptions.masterkey, # user_id=current_user_id()) . Output only the next line.
database = self._get_database()
Continue the code snippet: <|code_start|> ["in", {"$type": "keypath", "$val": "type"}, ["cat", "dog"]]] self.assertListEqual(expected, p.to_dict()) def test_compound_statement_1(self): p = Predicate(_id__eq="chima", gender__eq="M", type__eq="dog") p2 = Predicate(_id__eq="fatseng", gender__eq="F", type__eq="cat") p3 = Predicate(_id__eq="milktea", gender__eq="NA", type__eq="frog") p4 = p & p2 & p3 expected = ["and", ["eq", {"$type": "keypath", "$val": "_id"}, "chima"], ["eq", {"$type": "keypath", "$val": "gender"}, "M"], ["eq", {"$type": "keypath", "$val": "type"}, "dog"], ["eq", {"$type": "keypath", "$val": "_id"}, "fatseng"], ["eq", {"$type": "keypath", "$val": "gender"}, "F"], ["eq", {"$type": "keypath", "$val": "type"}, "cat"], ["eq", {"$type": "keypath", "$val": "_id"}, "milktea"], ["eq", {"$type": "keypath", "$val": "gender"}, "NA"], ["eq", {"$type": "keypath", "$val": "type"}, "frog"]] self.assertListEqual(expected, p4.to_dict()) def test_compound_statement_2(self): p = Predicate(_id__eq="chima", gender__eq="M", type__eq="dog") p2 = Predicate(_id__eq="fatseng", gender__eq="F", type__eq="cat") p3 = ~Predicate(_id__eq="milktea", gender__eq="NA", type__eq="frog") p4 = p | p2 | p3 expected = ["or", ["and",["eq", {"$type": "keypath", "$val": "_id"}, "chima"], ["eq", {"$type": "keypath", "$val": "gender"}, "M"], ["eq", {"$type": "keypath", "$val": "type"}, "dog"]], ["and",["eq", {"$type": "keypath", "$val": "_id"}, "fatseng"], ["eq", {"$type": "keypath", "$val": "gender"}, "F"], ["eq", {"$type": "keypath", "$val": "type"}, "cat"]], <|code_end|> . Use current file imports: import unittest from ..query import Predicate and context (classes, functions, or code) from other files: # Path: chat/query.py # class Query: # def __init__(self, record_type, # predicate=None, count=False, # limit=50, offset=None, include=[]): # def add_order(self, key, order): . Output only the next line.
["not", ["and", ["eq", {"$type": "keypath", "$val": "_id"}, "milktea"],
Given the following code snippet before the placeholder: <|code_start|> @staticmethod def _encode_id(record_id): return record_id.type + "/" + record_id.key def delete(self, arg): if not isinstance(arg, list): arg = [arg] ids = [Database._encode_id(item.id) if isinstance(item, Record) else item for item in arg] return self.container.send_action('record:delete', { 'database_id': self.database_id, 'ids': ids }) def query(self, query): include = {v: {"$type": "keypath", "$val": v} for v in list(set(query.include))} payload = {'database_id': self.database_id, 'record_type': query.record_type, 'predicate': query.predicate.to_dict(), 'count': query.count, 'sort': query.sort, 'include': include} if query.offset is not None: payload['offset'] = query.offset <|code_end|> , predict the next line using imports from the current file: from skygear.encoding import deserialize_record, serialize_record from skygear.models import Record from .asset import sign_asset_url from .exc import SkygearChatException and context including class names, function names, and sometimes code from other files: # Path: chat/asset.py # def sign_asset_url(name): # signer = get_signer() # return signer.sign(name) # # Path: chat/exc.py # class SkygearChatException(SkygearException): # pass . Output only the next line.
if query.limit is not None:
Given snippet: <|code_start|># You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Database(object): def __init__(self, container, database_id): self.container = container self.database_id = database_id def save(self, arg, atomic=False): if not isinstance(arg, list): arg = [arg] if len(arg) == 0: return {'result': []} records = [serialize_record(item) if isinstance(item, Record) else item for item in arg] return self.container.send_action('record:save', { <|code_end|> , continue by predicting the next line. Consider current file imports: from skygear.encoding import deserialize_record, serialize_record from skygear.models import Record from .asset import sign_asset_url from .exc import SkygearChatException and context: # Path: chat/asset.py # def sign_asset_url(name): # signer = get_signer() # return signer.sign(name) # # Path: chat/exc.py # class SkygearChatException(SkygearException): # pass which might include code, classes, or functions. Output only the next line.
'database_id': self.database_id,
Based on the snippet: <|code_start|> class TestPublishEvent(unittest.TestCase): def record(self): return deserialize_record({ '_id': 'message/1', '_access': None, '_ownerID': 'user1', 'conversation': 'conversation1', 'body': 'hihi' }) @patch('chat.pubsub.Hub', autospec=True) @patch('chat.pubsub._get_channels_by_user_ids', Mock(return_value=['channel1'])) @patch('chat.pubsub.skyoptions', Mock(return_value={'apikey': 'changeme'})) def test_pubsub_publish_called(self, mock_hub): _publish_record_event('user1', 'message', 'create', self.record()) self.assertEqual(len(mock_hub.method_calls), 1) self.assertEqual(mock_hub.method_calls[0][0], '().publish') self.assertEqual(mock_hub.method_calls[0][1][0], ['channel1']) self.assertEqual(mock_hub.method_calls[0][1][1], { 'event': 'create', 'data': { 'event_type': 'create', 'type': 'record', 'record_type': 'message', 'record': { '_id': 'message/1', <|code_end|> , predict the immediate next line with the help of imports: import unittest from unittest.mock import Mock, patch from skygear.encoding import deserialize_record from ..pubsub import _publish_record_event and context (classes, functions, sometimes code) from other files: # Path: chat/pubsub.py # def _publish_record_event(user_ids: [], # record_type: str, # event: str, # record: Record) -> None: # if len(user_ids) == 0: # return # _publish_event(user_ids, event, { # 'event_type': event, # 'type': 'record', # 'record_type': record_type, # 'record': serialize_record(record) # }) . Output only the next line.
'_access': None,
Predict the next line after this snippet: <|code_start|> class MessageHistory(ChatRecord): record_type = 'message_history' def __init__(self, message): super().__init__(RecordID(self.record_type, str(uuid.uuid4())), current_user_id(), message.acl) for key in ['attachment', 'body', 'metadata', 'conversation', 'message_status', 'edited_by', 'edited_at']: <|code_end|> using the current file's imports: import uuid from skygear.models import RecordID, Reference from skygear.utils.context import current_user_id from .record import ChatRecord and any relevant context from other files: # Path: chat/record.py # class ChatRecord(Record): # record_type = None # database_id = '_public' # # def save(self): # database = self._get_database() # database.save([self]) # # def delete(self): # database = self._get_database() # database.delete([self]) # # def to_record(self, record): # record._id = self._id # record._owner_id = self._owner_id # record._acl = self._acl # record._created_at = self._created_at # record._created_by = self._created_by # record._updated_at = self._updated_at # record._updated_by = self._updated_by # record._data = self._data # # @classmethod # def delete_all(self, records): # database = self._get_database() # database.delete(records) # # @classmethod # def save_all(self, records, atomic=True): # database = self._get_database() # database.save(records, atomic) # # @classmethod # def _get_database(cls): # return Database(_get_container(), cls.database_id) # # @classmethod # def fetch_one(cls, key): # result = cls.fetch_all([key]) # if len(result) == 0: # return None # return result[0] # # @classmethod # def fetch_all(cls, keys): # keys = [cls.__key_from_obj(key) for key in keys] # database = cls._get_database() # result = database.query(Query(cls.record_type, # predicate=Predicate(_id__in=keys), # limit=len(keys))) # result = [cls.from_record(record) for record in result] # return result # # @classmethod # def exists(cls, record): # return cls.fetch_one(record.id.key) is not None # # @classmethod # def __key_from_obj(cls, obj): # if isinstance(obj, Reference): # obj = obj.recordID.key # if isinstance(obj, RecordID): # obj = obj.key # return obj # # @classmethod # def from_record(cls, record): # record = cls(record.id, # record.owner_id, # record.acl, # created_at=record.created_at, # created_by=record.created_by, # updated_at=record.updated_at, # updated_by=record.updated_by, # data=record.data) # return record . Output only the next line.
if key in message:
Using the snippet: <|code_start|> None, data={ 'user': Reference(RecordID('user', user_id)), 'message': Reference(RecordID('message', message_id)) } ) @classmethod def consistent_id(cls, user_id: str, message_id: str) -> str: seed = message_id + user_id sha = hashlib.sha256(bytes(seed, 'utf8')) return str(uuid.UUID(bytes=sha.digest()[0:16])) def mark_as_delivered(self) -> None: self[Receipt.DELIVERED_AT] = datetime.utcnow() def mark_as_read(self) -> None: self[Receipt.READ_AT] = datetime.utcnow() def is_delivered(self): return self.get(Receipt.DELIVERED_AT, None) is not None def is_read(self): return self.get(Receipt.READ_AT, None) is not None @classmethod def fetch_all_by_messages_and_user_id(cls, messages, user_id): receipt_ids = [Receipt.consistent_id(user_id, message.id.key) for message in messages] <|code_end|> , determine the next line of code. You have imports: import hashlib import uuid from datetime import datetime from skygear.models import RecordID, Reference from .record import ChatRecord and context (class names, function names, or code) available: # Path: chat/record.py # class ChatRecord(Record): # record_type = None # database_id = '_public' # # def save(self): # database = self._get_database() # database.save([self]) # # def delete(self): # database = self._get_database() # database.delete([self]) # # def to_record(self, record): # record._id = self._id # record._owner_id = self._owner_id # record._acl = self._acl # record._created_at = self._created_at # record._created_by = self._created_by # record._updated_at = self._updated_at # record._updated_by = self._updated_by # record._data = self._data # # @classmethod # def delete_all(self, records): # database = self._get_database() # database.delete(records) # # @classmethod # def save_all(self, records, atomic=True): # database = self._get_database() # database.save(records, atomic) # # @classmethod # def _get_database(cls): # return Database(_get_container(), cls.database_id) # # @classmethod # def fetch_one(cls, key): # result = cls.fetch_all([key]) # if len(result) == 0: # return None # return result[0] # # @classmethod # def fetch_all(cls, keys): # keys = [cls.__key_from_obj(key) for key in keys] # database = cls._get_database() # result = database.query(Query(cls.record_type, # predicate=Predicate(_id__in=keys), # limit=len(keys))) # result = [cls.from_record(record) for record in result] # return result # # @classmethod # def exists(cls, record): # return cls.fetch_one(record.id.key) is not None # # @classmethod # def __key_from_obj(cls, obj): # if isinstance(obj, Reference): # obj = obj.recordID.key # if isinstance(obj, RecordID): # obj = obj.key # return obj # # @classmethod # def from_record(cls, record): # record = cls(record.id, # record.owner_id, # record.acl, # created_at=record.created_at, # created_by=record.created_by, # updated_at=record.updated_at, # updated_by=record.updated_by, # data=record.data) # return record . Output only the next line.
return cls.fetch_all(receipt_ids)
Here is a snippet: <|code_start|> class TestHandleMessageBeforeSave(unittest.TestCase): def setUp(self): self.conn = None self.patchers = [ patch('chat.utils.skyoptions', Mock(return_value={'masterkey': 'secret'})) <|code_end|> . Write the next line using the current file imports: import unittest from unittest.mock import Mock, patch from skygear.encoding import deserialize_record from ..exc import SkygearChatException from ..message_handlers import handle_message_before_save from ..message_history import MessageHistory and context from other files: # Path: chat/exc.py # class SkygearChatException(SkygearException): # pass # # Path: chat/message_handlers.py # def handle_message_before_save(record, original_record, conn): # message = Message.from_record(record) # # if original_record is not None and original_record['deleted']: # raise AlreadyDeletedException() # # if UserConversation.fetch_one(message.conversation_id) is None: # raise NotInConversationException() # # if original_record is None: # message['deleted'] = False # message['revision'] = 1 # else: # message_history = MessageHistory(Message.from_record(original_record)) # message_history.save() # message['edited_at'] = datetime.utcnow() # message['edited_by'] = Reference(RecordID('user', current_user_id())) # # if message.get('message_status', None) is None: # message['message_status'] = 'delivered' # # # TODO use proper ACL setter # message._acl = Conversation.get_message_acl(message.conversation_id) # # # py-skygear save hook use the original record refs # # so we need to apply all the changes from message object to record # message.to_record(record) # return record # # Path: chat/message_history.py # class MessageHistory(ChatRecord): # record_type = 'message_history' # # def __init__(self, message): # super().__init__(RecordID(self.record_type, str(uuid.uuid4())), # current_user_id(), # message.acl) # for key in ['attachment', 'body', 'metadata', # 'conversation', 'message_status', # 'edited_by', 'edited_at']: # if key in message: # self[key] = message.get(key, None) # self['parent'] = Reference(message.id) , which may include functions, classes, or code. Output only the next line.
]
Here is a snippet: <|code_start|> class TestHandleMessageBeforeSave(unittest.TestCase): def setUp(self): self.conn = None self.patchers = [ patch('chat.utils.skyoptions', Mock(return_value={'masterkey': 'secret'})) ] for each_patcher in self.patchers: each_patcher.start() def tearDown(self): for each_patcher in self.patchers: each_patcher.stop() <|code_end|> . Write the next line using the current file imports: import unittest from unittest.mock import Mock, patch from skygear.encoding import deserialize_record from ..exc import SkygearChatException from ..message_handlers import handle_message_before_save from ..message_history import MessageHistory and context from other files: # Path: chat/exc.py # class SkygearChatException(SkygearException): # pass # # Path: chat/message_handlers.py # def handle_message_before_save(record, original_record, conn): # message = Message.from_record(record) # # if original_record is not None and original_record['deleted']: # raise AlreadyDeletedException() # # if UserConversation.fetch_one(message.conversation_id) is None: # raise NotInConversationException() # # if original_record is None: # message['deleted'] = False # message['revision'] = 1 # else: # message_history = MessageHistory(Message.from_record(original_record)) # message_history.save() # message['edited_at'] = datetime.utcnow() # message['edited_by'] = Reference(RecordID('user', current_user_id())) # # if message.get('message_status', None) is None: # message['message_status'] = 'delivered' # # # TODO use proper ACL setter # message._acl = Conversation.get_message_acl(message.conversation_id) # # # py-skygear save hook use the original record refs # # so we need to apply all the changes from message object to record # message.to_record(record) # return record # # Path: chat/message_history.py # class MessageHistory(ChatRecord): # record_type = 'message_history' # # def __init__(self, message): # super().__init__(RecordID(self.record_type, str(uuid.uuid4())), # current_user_id(), # message.acl) # for key in ['attachment', 'body', 'metadata', # 'conversation', 'message_status', # 'edited_by', 'edited_at']: # if key in message: # self[key] = message.get(key, None) # self['parent'] = Reference(message.id) , which may include functions, classes, or code. Output only the next line.
def record(self):
Given the following code snippet before the placeholder: <|code_start|> def _publish_event(user_ids: [], event: str, data: dict = None) -> None: if not isinstance(user_ids, list): user_ids = user_ids if len(user_ids) == 0: return channel_names = _get_channels_by_user_ids(user_ids) if channel_names: hub = Hub(api_key=skyoptions.apikey) hub.publish(channel_names, { 'event': event, 'data': data }) <|code_end|> , predict the next line using imports from the current file: from skygear.models import Record from skygear.options import options as skyoptions from .encoding import serialize_record from .hub import Hub from .utils import _get_channels_by_user_ids and context including class names, function names, and sometimes code from other files: # Path: chat/encoding.py # def serialize_record(record): # r = skyserialize(record) # if 'attachment' in r: # r['attachment']['$url'] = sign_asset_url(r['attachment']['$name']) # return r # # Path: chat/hub.py # class Hub: # # def __init__(self, end_point=None, api_key=None): # self.transport = 'websocket' # self.end_point = end_point or _get_default_pubsub_url() # self.api_key = api_key or options.apikey # # def publish(self, channels, data): # wsopts = {} # if self.api_key: # wsopts['header'] = [ # 'X-Skygear-API-Key: {0}'.format(self.api_key) # ] # conn = create_connection(self.end_point, **wsopts) # if isinstance(channels, str): # channels = [channels] # for channel in channels: # _data = encoder({ # 'action': 'pub', # 'channel': channel, # 'data': data, # }) # conn.send(_data) # conn.close() # # Path: chat/utils.py # def _get_channels_by_user_ids(user_ids): # # TODO: use database.query instead of raw SQL # with db.conn() as conn: # cur = conn.execute(''' # SELECT name # FROM %(schema_name)s.user_channel # WHERE _owner_id in %(user_ids)s # LIMIT %(len)s; # ''', { # 'schema_name': AsIs(_get_schema_name()), # 'user_ids': tuple(user_ids), # 'len': len(user_ids), # } # ) # # results = [] # for row in cur: # results.append(row[0]) # # return results . Output only the next line.
def _publish_record_event(user_ids: [],
Given the code snippet: <|code_start|> def _publish_event(user_ids: [], event: str, data: dict = None) -> None: if not isinstance(user_ids, list): user_ids = user_ids if len(user_ids) == 0: return channel_names = _get_channels_by_user_ids(user_ids) if channel_names: hub = Hub(api_key=skyoptions.apikey) hub.publish(channel_names, { <|code_end|> , generate the next line using the imports in this file: from skygear.models import Record from skygear.options import options as skyoptions from .encoding import serialize_record from .hub import Hub from .utils import _get_channels_by_user_ids and context (functions, classes, or occasionally code) from other files: # Path: chat/encoding.py # def serialize_record(record): # r = skyserialize(record) # if 'attachment' in r: # r['attachment']['$url'] = sign_asset_url(r['attachment']['$name']) # return r # # Path: chat/hub.py # class Hub: # # def __init__(self, end_point=None, api_key=None): # self.transport = 'websocket' # self.end_point = end_point or _get_default_pubsub_url() # self.api_key = api_key or options.apikey # # def publish(self, channels, data): # wsopts = {} # if self.api_key: # wsopts['header'] = [ # 'X-Skygear-API-Key: {0}'.format(self.api_key) # ] # conn = create_connection(self.end_point, **wsopts) # if isinstance(channels, str): # channels = [channels] # for channel in channels: # _data = encoder({ # 'action': 'pub', # 'channel': channel, # 'data': data, # }) # conn.send(_data) # conn.close() # # Path: chat/utils.py # def _get_channels_by_user_ids(user_ids): # # TODO: use database.query instead of raw SQL # with db.conn() as conn: # cur = conn.execute(''' # SELECT name # FROM %(schema_name)s.user_channel # WHERE _owner_id in %(user_ids)s # LIMIT %(len)s; # ''', { # 'schema_name': AsIs(_get_schema_name()), # 'user_ids': tuple(user_ids), # 'len': len(user_ids), # } # ) # # results = [] # for row in cur: # results.append(row[0]) # # return results . Output only the next line.
'event': event,
Here is a snippet: <|code_start|> def _publish_event(user_ids: [], event: str, data: dict = None) -> None: if not isinstance(user_ids, list): user_ids = user_ids if len(user_ids) == 0: return channel_names = _get_channels_by_user_ids(user_ids) if channel_names: hub = Hub(api_key=skyoptions.apikey) hub.publish(channel_names, { <|code_end|> . Write the next line using the current file imports: from skygear.models import Record from skygear.options import options as skyoptions from .encoding import serialize_record from .hub import Hub from .utils import _get_channels_by_user_ids and context from other files: # Path: chat/encoding.py # def serialize_record(record): # r = skyserialize(record) # if 'attachment' in r: # r['attachment']['$url'] = sign_asset_url(r['attachment']['$name']) # return r # # Path: chat/hub.py # class Hub: # # def __init__(self, end_point=None, api_key=None): # self.transport = 'websocket' # self.end_point = end_point or _get_default_pubsub_url() # self.api_key = api_key or options.apikey # # def publish(self, channels, data): # wsopts = {} # if self.api_key: # wsopts['header'] = [ # 'X-Skygear-API-Key: {0}'.format(self.api_key) # ] # conn = create_connection(self.end_point, **wsopts) # if isinstance(channels, str): # channels = [channels] # for channel in channels: # _data = encoder({ # 'action': 'pub', # 'channel': channel, # 'data': data, # }) # conn.send(_data) # conn.close() # # Path: chat/utils.py # def _get_channels_by_user_ids(user_ids): # # TODO: use database.query instead of raw SQL # with db.conn() as conn: # cur = conn.execute(''' # SELECT name # FROM %(schema_name)s.user_channel # WHERE _owner_id in %(user_ids)s # LIMIT %(len)s; # ''', { # 'schema_name': AsIs(_get_schema_name()), # 'user_ids': tuple(user_ids), # 'len': len(user_ids), # } # ) # # results = [] # for row in cur: # results.append(row[0]) # # return results , which may include functions, classes, or code. Output only the next line.
'event': event,
Continue the code snippet: <|code_start|> def serialize_record(record): r = skyserialize(record) if 'attachment' in r: r['attachment']['$url'] = sign_asset_url(r['attachment']['$name']) <|code_end|> . Use current file imports: from skygear.encoding import serialize_record as skyserialize from .asset import sign_asset_url and context (classes, functions, or code) from other files: # Path: chat/asset.py # def sign_asset_url(name): # signer = get_signer() # return signer.sign(name) . Output only the next line.
return r
Given snippet: <|code_start|> message_history_schema = _message_history_schema() schema_helper.create([user_schema, user_conversation_schema, conversation_schema, message_schema, message_history_schema, receipt_schema, user_channel_schema], plugin_request=True) # Create unique constraint to _database_id in user_channel table # to ensure there is only one user_channel for each user with db.conn() as conn: result = conn.execute(""" select 1 FROM information_schema.constraint_column_usage WHERE table_schema = '%(schema_name)s' AND table_name = 'user_channel' AND constraint_name = 'user_channel_database_id_key' """, { 'schema_name': AsIs(_get_schema_name()) }) first_row = result.first() if first_row is None: conn.execute(""" DELETE FROM %(schema_name)s.user_channel WHERE _id IN ( SELECT _id FROM ( <|code_end|> , continue by predicting the next line. Consider current file imports: from psycopg2.extensions import AsIs from skygear.container import SkygearContainer from skygear.options import options as skyoptions from skygear.utils import db from .field import Field from .schema import Schema, SchemaHelper from .utils import _get_schema_name import skygear and context: # Path: chat/field.py # class Field(object): # def __init__(self, name, field_type): # self.name = name # self.field_type = field_type # # def to_dict(self): # return {'name': self.name, # 'type': self.field_type} # # Path: chat/schema.py # class Schema(object): # def __init__(self, record_type, fields): # self.record_type = record_type # self.fields = fields # # def to_dict(self): # return {self.record_type: # {'fields': [field.to_dict() for field in self.fields]}} # # class SchemaHelper(object): # def __init__(self, container): # self.container = container # # def create(self, schemas, plugin_request=False): # record_types = {} # for schema in schemas: # record_types.update(schema.to_dict()) # payload = {'record_types': record_types} # return self.container.send_action('schema:create', # payload, # plugin_request=plugin_request) # # Path: chat/utils.py # def _get_schema_name(): # return "app_%s" % skyoptions.appname which might include code, classes, or functions. Output only the next line.
SELECT
Predict the next line after this snippet: <|code_start|> def register_initialization_event_handlers(settings): def _base_message_fields(): return [Field('attachment', 'asset'), Field('body', 'string'), Field('metadata', 'json'), Field('conversation', 'ref(conversation)'), Field('message_status', 'string'), Field('seq', 'sequence'), Field('revision', 'number'), Field('edited_by', 'ref(user)'), Field('edited_at', 'datetime')] <|code_end|> using the current file's imports: from psycopg2.extensions import AsIs from skygear.container import SkygearContainer from skygear.options import options as skyoptions from skygear.utils import db from .field import Field from .schema import Schema, SchemaHelper from .utils import _get_schema_name import skygear and any relevant context from other files: # Path: chat/field.py # class Field(object): # def __init__(self, name, field_type): # self.name = name # self.field_type = field_type # # def to_dict(self): # return {'name': self.name, # 'type': self.field_type} # # Path: chat/schema.py # class Schema(object): # def __init__(self, record_type, fields): # self.record_type = record_type # self.fields = fields # # def to_dict(self): # return {self.record_type: # {'fields': [field.to_dict() for field in self.fields]}} # # class SchemaHelper(object): # def __init__(self, container): # self.container = container # # def create(self, schemas, plugin_request=False): # record_types = {} # for schema in schemas: # record_types.update(schema.to_dict()) # payload = {'record_types': record_types} # return self.container.send_action('schema:create', # payload, # plugin_request=plugin_request) # # Path: chat/utils.py # def _get_schema_name(): # return "app_%s" % skyoptions.appname . Output only the next line.
def _message_schema():
Next line prediction: <|code_start|> fields = _base_message_fields() + [Field('parent', 'ref(message)')] return Schema('message_history', fields) @skygear.event("before-plugins-ready") def chat_plugin_init(config): container = SkygearContainer(api_key=skyoptions.masterkey) schema_helper = SchemaHelper(container) # We need this to provision the record type. Otherwise, make the follow # up `ref` type will fails. schema_helper.create([ Schema('user', []), Schema('message', []), Schema('conversation', []) ], plugin_request=True) conversation_schema = Schema('conversation', [Field('title', 'string'), Field('metadata', 'json'), Field('deleted', 'boolean'), Field('distinct_by_participants', 'boolean'), Field('last_message', 'ref(message)')]) user_schema = Schema('user', [Field('name', 'string')]) user_conversation_schema = Schema('user_conversation', [Field('user', 'ref(user)'), Field('conversation', 'ref(conversation)'), Field('unread_count', 'number'), Field('last_read_message', <|code_end|> . Use current file imports: (from psycopg2.extensions import AsIs from skygear.container import SkygearContainer from skygear.options import options as skyoptions from skygear.utils import db from .field import Field from .schema import Schema, SchemaHelper from .utils import _get_schema_name import skygear) and context including class names, function names, or small code snippets from other files: # Path: chat/field.py # class Field(object): # def __init__(self, name, field_type): # self.name = name # self.field_type = field_type # # def to_dict(self): # return {'name': self.name, # 'type': self.field_type} # # Path: chat/schema.py # class Schema(object): # def __init__(self, record_type, fields): # self.record_type = record_type # self.fields = fields # # def to_dict(self): # return {self.record_type: # {'fields': [field.to_dict() for field in self.fields]}} # # class SchemaHelper(object): # def __init__(self, container): # self.container = container # # def create(self, schemas, plugin_request=False): # record_types = {} # for schema in schemas: # record_types.update(schema.to_dict()) # payload = {'record_types': record_types} # return self.container.send_action('schema:create', # payload, # plugin_request=plugin_request) # # Path: chat/utils.py # def _get_schema_name(): # return "app_%s" % skyoptions.appname . Output only the next line.
'ref(message)'),
Predict the next line for this snippet: <|code_start|> FROM information_schema.constraint_column_usage WHERE table_schema = '%(schema_name)s' AND table_name = 'user_channel' AND constraint_name = 'user_channel_database_id_key' """, { 'schema_name': AsIs(_get_schema_name()) }) first_row = result.first() if first_row is None: conn.execute(""" DELETE FROM %(schema_name)s.user_channel WHERE _id IN ( SELECT _id FROM ( SELECT _id, ROW_NUMBER() OVER( PARTITION BY _database_id ORDER BY _created_at ) AS row_num FROM %(schema_name)s.user_channel ) u2 WHERE u2.row_num > 1 ) """, { 'schema_name': AsIs(_get_schema_name()) }) conn.execute(""" ALTER TABLE %(schema_name)s.user_channel ADD CONSTRAINT user_channel_database_id_key <|code_end|> with the help of current file imports: from psycopg2.extensions import AsIs from skygear.container import SkygearContainer from skygear.options import options as skyoptions from skygear.utils import db from .field import Field from .schema import Schema, SchemaHelper from .utils import _get_schema_name import skygear and context from other files: # Path: chat/field.py # class Field(object): # def __init__(self, name, field_type): # self.name = name # self.field_type = field_type # # def to_dict(self): # return {'name': self.name, # 'type': self.field_type} # # Path: chat/schema.py # class Schema(object): # def __init__(self, record_type, fields): # self.record_type = record_type # self.fields = fields # # def to_dict(self): # return {self.record_type: # {'fields': [field.to_dict() for field in self.fields]}} # # class SchemaHelper(object): # def __init__(self, container): # self.container = container # # def create(self, schemas, plugin_request=False): # record_types = {} # for schema in schemas: # record_types.update(schema.to_dict()) # payload = {'record_types': record_types} # return self.container.send_action('schema:create', # payload, # plugin_request=plugin_request) # # Path: chat/utils.py # def _get_schema_name(): # return "app_%s" % skyoptions.appname , which may contain function names, class names, or code. Output only the next line.
UNIQUE (_database_id);
Predict the next line after this snippet: <|code_start|># Copyright 2017 Oursky Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Query: def __init__(self, record_type, predicate=None, count=False, limit=50, offset=None, include=[]): self.record_type = record_type if predicate is None: predicate = Predicate() self.predicate = predicate self.count = count <|code_end|> using the current file's imports: from .predicate import Predicate and any relevant context from other files: # Path: chat/predicate.py # class Predicate(object): # AND = 'and' # OR = 'or' # NOT = 'not' # # def __init__(self, **kwargs): # self.op = kwargs.pop('op', Predicate.AND) # # Need to use ordered dict in order to pass unit test in python 3.5. # # See https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep468 # od = collections.OrderedDict(sorted(kwargs.items())) # self.conditions = [(key, kwargs[key]) for key in od.keys()] # # def __and__(self, other): # new_instance = Predicate() # if self.op == Predicate.AND: # new_instance.conditions = copy.copy(self.conditions) # if other.op == self.op: # new_instance.conditions += other.conditions # else: # new_instance.conditions.append(other) # else: # new_instance.conditions = [self, other] # return new_instance # # def __or__(self, other): # new_instance = Predicate(op=Predicate.OR) # if self.op == Predicate.OR: # new_instance.conditions = copy.copy(self.conditions) # if other.op == self.op: # new_instance.conditions += other.conditions # else: # new_instance.conditions.append(other) # else: # new_instance.conditions = [self, other] # return new_instance # # def __invert__(self): # new_instance = Predicate(op=Predicate.NOT) # new_instance.conditions = [self] # return new_instance # # @classmethod # def condition_to_dict(cls, t): # field, op = t[0].split("__") # return [op, {"$type": "keypath", "$val": field}, t[1]] # # def to_dict(self, root=None): # if root is None: # root = self # if root is None: # return [] # if isinstance(root, Predicate): # num_conditions = len(root.conditions) # if num_conditions == 0: # return [] # elif num_conditions == 1: # result = self.to_dict(root.conditions[0]) # if root.op != Predicate.NOT: # return result # return [root.op, result] # else: # return [root.op] + [self.to_dict(d) for d in root.conditions] # elif type(root) == tuple: # return Predicate.condition_to_dict(root) # else: # return [] . Output only the next line.
self.sort = []
Using the snippet: <|code_start|> # one_term() class OneTermMatchRule(SubtreeMatchRule): def __str__(self) -> str: return str(categorization.Category('one_term', self._positive_properties, self._negative_properties)) def __call__(self, category_list: Sequence[Category], head_index: int) -> bool: found = False <|code_end|> , determine the next line of code. You have imports: from typing import Sequence from pyramids import categorization from pyramids.categorization import Category from pyramids.rules.subtree_match import SubtreeMatchRule and context (class names, function names, or code) available: # Path: pyramids/categorization.py # CATEGORY_WILDCARD = _CATEGORY_WILDCARD # # Path: pyramids/categorization.py # CATEGORY_WILDCARD = _CATEGORY_WILDCARD # # Path: pyramids/rules/subtree_match.py # class SubtreeMatchRule: # # def __init__(self, positive_properties: Iterable[Property], # negative_properties: Iterable[Property]): # self._positive_properties = make_property_set(positive_properties) # self._negative_properties = make_property_set(negative_properties) # # @property # def positive_properties(self) -> FrozenSet[Property]: # return self._positive_properties # # @property # def negative_properties(self) -> FrozenSet[Property]: # return self._negative_properties # # def __str__(self) -> str: # raise NotImplementedError() # # def __repr__(self) -> str: # return (type(self).__name__ + "(" + repr(self._positive_properties) + ", " + # repr(self._negative_properties) + ")") # # # def __eq__(self, other): # # raise NotImplementedError() # # # # def __ne__(self, other): # # raise NotImplementedError() # # # # def __le__(self, other): # # raise NotImplementedError() # # # # def __ge__(self, other): # # raise NotImplementedError() # # # # def __lt__(self, other): # # raise NotImplementedError() # # # # def __gt__(self, other): # # raise NotImplementedError() # # def __call__(self, category_list: Sequence[Category], head_index: int) -> bool: # raise NotImplementedError() . Output only the next line.
for index in range(len(category_list)):
Predict the next line after this snippet: <|code_start|> self._counter += 1 else: assert index not in self._index_map assert not self._counter self._index_map[index] = len(self._tokens) self._tokens.append(Token(index, spelling, span, category)) self._links.append({}) self._phrases.append([(category, frozenset())]) # For convenience, return the id of the token so users can know # which index to use for links. return len(self._tokens) - 1 def handle_root(self) -> None: """Called to indicate that the next token is the root.""" assert self._root is None self._root = len(self._tokens) def handle_link(self, source_index: int, sink_index: int, label: str) -> None: """Called to indicate the occurrence of a link between two tokens. Note that this will not be called until handle_token() has been called for both the source and sink.""" assert source_index in self._index_map assert sink_index in self._index_map assert self._phrase_stack source_id = self._index_map[source_index] sink_id = self._index_map[sink_index] if sink_id in self._links[source_id]: <|code_end|> using the current file's imports: from typing import List, Tuple from pyramids.categorization import Category from pyramids.graphs import ParseGraph, Token from pyramids.traversal import LanguageContentHandler and any relevant context from other files: # Path: pyramids/categorization.py # CATEGORY_WILDCARD = _CATEGORY_WILDCARD # # Path: pyramids/graphs.py # class ParseGraph: # class BuildGraph: # def from_json(cls, json_data: Dict[str, List]) -> 'ParseGraph': # def __init__(self, root: int, tokens: Sequence[Token], links: List[Dict[int, Set[str]]], # phrases: List[List[Tuple[Category, List[Tuple[int, int]]]]]): # def root_index(self) -> int: # def root_category(self) -> Category: # def tokens(self) -> Tuple[Token, ...]: # def __str__(self) -> str: # def __getitem__(self, index: int) -> Token: # def __len__(self) -> int: # def to_json(self) -> Dict[str, List]: # def get_phrase_category(self, head: int) -> Category: # def get_phrase_stack(self, head: int) -> Category: # def get_sinks(self, source: int) -> Set[int]: # def get_sources(self, sink: int) -> Set[int]: # def get_labels(self, source: int, sink: int) -> FrozenSet[str]: # def _get_phrase_tokens(self, head: int, indices: Set[int]) -> None: # def get_phrase_tokens(self, head: int = None) -> List[Token]: # def get_phrase_text(self, head: int = None) -> str: # def visualize(self, gv_graph: Digraph) -> None: # def from_parse_graphs(cls, graphs: Sequence[Union[ParseGraph, 'BuildGraph']]) -> 'BuildGraph': # def from_json(cls, json_data: Dict[str, List]) -> 'BuildGraph': # def __init__(self): # def tokens(self) -> Tuple[Token, ...]: # def get_annotations(self) -> List[str]: # def find_roots(self) -> Set[int]: # def find_leaves(self) -> Set[int]: # def _is_forest(self, roots: Set[int]) -> bool: # def is_tree(self) -> bool: # def is_forest(self) -> bool: # def set_phrase_category(self, index: int, category: Category) -> None: # def append_token(self, spelling: str, category: Category = None, # span: Tuple[int, int] = None) -> int: # def clear_token_category(self, index: int) -> None: # def add_link(self, source: int, label: str, sink: int) -> None: # def discard_link(self, source: int, label: str, sink: int) -> None: # def remove_link(self, source: int, label: str, sink: int) -> None: # def has_link(self, source: int, label: str, sink: int) -> bool: # def iter_links(self, source: int = None, label: str = None, sink: int = None) \ # def sink_iterator_func(sinks): # def sink_iterator_func(sinks): # def label_iterator_func(labels): # def label_iterator_func(labels): # def __getitem__(self, index: int) -> Token: # def __len__(self) -> int: # def to_json(self) -> Dict[str, List]: # def get_phrase_category(self, head: int) -> Category: # def get_sinks(self, source: int) -> Set[int]: # def get_sources(self, sink: int) -> Set[int]: # def get_labels(self, source: int, sink: int) -> FrozenSet[LinkLabel]: # def _get_phrase_tokens(self, head: int, indices: Set[int]) -> None: # def get_phrase_tokens(self, head: int = None) -> List[Token]: # def visualize(self, gv_graph: Digraph) -> None: # # Path: pyramids/traversal.py # class LanguageContentHandler: # """A content handler for natural language, in the style of the # ContentHandler class of the xml.sax module.""" # # def handle_tree_end(self) -> None: # """Called to indicate the token_end_index of a tree.""" # # def handle_token(self, spelling: str, category: Category, index: int = None, # span: Tuple[int, int] = None) -> None: # """Called to indicate the occurrence of a token.""" # # def handle_root(self) -> None: # """Called to indicate that the next token is the root.""" # # def handle_link(self, source_start_index: int, sink_start_index: int, label: str) -> None: # """Called to indicate the occurrence of a link between two tokens. # Note that this will not be called until handle_token() has been # called for both the source and sink.""" # # def handle_phrase_start(self, category: Category, head_start_index: int = None) -> None: # """Called to indicate the token_start_index of a phrase.""" # # def handle_phrase_end(self) -> None: # """Called to indicate the token_end_index of a phrase.""" . Output only the next line.
self._links[source_id][sink_id].add(label)
Predict the next line after this snippet: <|code_start|> span: Tuple[int, int] = None) -> int: """Called to indicate the occurrence of a token.""" if index is None: index = self._counter self._counter += 1 else: assert index not in self._index_map assert not self._counter self._index_map[index] = len(self._tokens) self._tokens.append(Token(index, spelling, span, category)) self._links.append({}) self._phrases.append([(category, frozenset())]) # For convenience, return the id of the token so users can know # which index to use for links. return len(self._tokens) - 1 def handle_root(self) -> None: """Called to indicate that the next token is the root.""" assert self._root is None self._root = len(self._tokens) def handle_link(self, source_index: int, sink_index: int, label: str) -> None: """Called to indicate the occurrence of a link between two tokens. Note that this will not be called until handle_token() has been called for both the source and sink.""" assert source_index in self._index_map assert sink_index in self._index_map assert self._phrase_stack <|code_end|> using the current file's imports: from typing import List, Tuple from pyramids.categorization import Category from pyramids.graphs import ParseGraph, Token from pyramids.traversal import LanguageContentHandler and any relevant context from other files: # Path: pyramids/categorization.py # CATEGORY_WILDCARD = _CATEGORY_WILDCARD # # Path: pyramids/graphs.py # class ParseGraph: # class BuildGraph: # def from_json(cls, json_data: Dict[str, List]) -> 'ParseGraph': # def __init__(self, root: int, tokens: Sequence[Token], links: List[Dict[int, Set[str]]], # phrases: List[List[Tuple[Category, List[Tuple[int, int]]]]]): # def root_index(self) -> int: # def root_category(self) -> Category: # def tokens(self) -> Tuple[Token, ...]: # def __str__(self) -> str: # def __getitem__(self, index: int) -> Token: # def __len__(self) -> int: # def to_json(self) -> Dict[str, List]: # def get_phrase_category(self, head: int) -> Category: # def get_phrase_stack(self, head: int) -> Category: # def get_sinks(self, source: int) -> Set[int]: # def get_sources(self, sink: int) -> Set[int]: # def get_labels(self, source: int, sink: int) -> FrozenSet[str]: # def _get_phrase_tokens(self, head: int, indices: Set[int]) -> None: # def get_phrase_tokens(self, head: int = None) -> List[Token]: # def get_phrase_text(self, head: int = None) -> str: # def visualize(self, gv_graph: Digraph) -> None: # def from_parse_graphs(cls, graphs: Sequence[Union[ParseGraph, 'BuildGraph']]) -> 'BuildGraph': # def from_json(cls, json_data: Dict[str, List]) -> 'BuildGraph': # def __init__(self): # def tokens(self) -> Tuple[Token, ...]: # def get_annotations(self) -> List[str]: # def find_roots(self) -> Set[int]: # def find_leaves(self) -> Set[int]: # def _is_forest(self, roots: Set[int]) -> bool: # def is_tree(self) -> bool: # def is_forest(self) -> bool: # def set_phrase_category(self, index: int, category: Category) -> None: # def append_token(self, spelling: str, category: Category = None, # span: Tuple[int, int] = None) -> int: # def clear_token_category(self, index: int) -> None: # def add_link(self, source: int, label: str, sink: int) -> None: # def discard_link(self, source: int, label: str, sink: int) -> None: # def remove_link(self, source: int, label: str, sink: int) -> None: # def has_link(self, source: int, label: str, sink: int) -> bool: # def iter_links(self, source: int = None, label: str = None, sink: int = None) \ # def sink_iterator_func(sinks): # def sink_iterator_func(sinks): # def label_iterator_func(labels): # def label_iterator_func(labels): # def __getitem__(self, index: int) -> Token: # def __len__(self) -> int: # def to_json(self) -> Dict[str, List]: # def get_phrase_category(self, head: int) -> Category: # def get_sinks(self, source: int) -> Set[int]: # def get_sources(self, sink: int) -> Set[int]: # def get_labels(self, source: int, sink: int) -> FrozenSet[LinkLabel]: # def _get_phrase_tokens(self, head: int, indices: Set[int]) -> None: # def get_phrase_tokens(self, head: int = None) -> List[Token]: # def visualize(self, gv_graph: Digraph) -> None: # # Path: pyramids/traversal.py # class LanguageContentHandler: # """A content handler for natural language, in the style of the # ContentHandler class of the xml.sax module.""" # # def handle_tree_end(self) -> None: # """Called to indicate the token_end_index of a tree.""" # # def handle_token(self, spelling: str, category: Category, index: int = None, # span: Tuple[int, int] = None) -> None: # """Called to indicate the occurrence of a token.""" # # def handle_root(self) -> None: # """Called to indicate that the next token is the root.""" # # def handle_link(self, source_start_index: int, sink_start_index: int, label: str) -> None: # """Called to indicate the occurrence of a link between two tokens. # Note that this will not be called until handle_token() has been # called for both the source and sink.""" # # def handle_phrase_start(self, category: Category, head_start_index: int = None) -> None: # """Called to indicate the token_start_index of a phrase.""" # # def handle_phrase_end(self) -> None: # """Called to indicate the token_end_index of a phrase.""" . Output only the next line.
source_id = self._index_map[source_index]
Predict the next line after this snippet: <|code_start|> """Called to indicate the occurrence of a token.""" if index is None: index = self._counter self._counter += 1 else: assert index not in self._index_map assert not self._counter self._index_map[index] = len(self._tokens) self._tokens.append(Token(index, spelling, span, category)) self._links.append({}) self._phrases.append([(category, frozenset())]) # For convenience, return the id of the token so users can know # which index to use for links. return len(self._tokens) - 1 def handle_root(self) -> None: """Called to indicate that the next token is the root.""" assert self._root is None self._root = len(self._tokens) def handle_link(self, source_index: int, sink_index: int, label: str) -> None: """Called to indicate the occurrence of a link between two tokens. Note that this will not be called until handle_token() has been called for both the source and sink.""" assert source_index in self._index_map assert sink_index in self._index_map assert self._phrase_stack source_id = self._index_map[source_index] <|code_end|> using the current file's imports: from typing import List, Tuple from pyramids.categorization import Category from pyramids.graphs import ParseGraph, Token from pyramids.traversal import LanguageContentHandler and any relevant context from other files: # Path: pyramids/categorization.py # CATEGORY_WILDCARD = _CATEGORY_WILDCARD # # Path: pyramids/graphs.py # class ParseGraph: # class BuildGraph: # def from_json(cls, json_data: Dict[str, List]) -> 'ParseGraph': # def __init__(self, root: int, tokens: Sequence[Token], links: List[Dict[int, Set[str]]], # phrases: List[List[Tuple[Category, List[Tuple[int, int]]]]]): # def root_index(self) -> int: # def root_category(self) -> Category: # def tokens(self) -> Tuple[Token, ...]: # def __str__(self) -> str: # def __getitem__(self, index: int) -> Token: # def __len__(self) -> int: # def to_json(self) -> Dict[str, List]: # def get_phrase_category(self, head: int) -> Category: # def get_phrase_stack(self, head: int) -> Category: # def get_sinks(self, source: int) -> Set[int]: # def get_sources(self, sink: int) -> Set[int]: # def get_labels(self, source: int, sink: int) -> FrozenSet[str]: # def _get_phrase_tokens(self, head: int, indices: Set[int]) -> None: # def get_phrase_tokens(self, head: int = None) -> List[Token]: # def get_phrase_text(self, head: int = None) -> str: # def visualize(self, gv_graph: Digraph) -> None: # def from_parse_graphs(cls, graphs: Sequence[Union[ParseGraph, 'BuildGraph']]) -> 'BuildGraph': # def from_json(cls, json_data: Dict[str, List]) -> 'BuildGraph': # def __init__(self): # def tokens(self) -> Tuple[Token, ...]: # def get_annotations(self) -> List[str]: # def find_roots(self) -> Set[int]: # def find_leaves(self) -> Set[int]: # def _is_forest(self, roots: Set[int]) -> bool: # def is_tree(self) -> bool: # def is_forest(self) -> bool: # def set_phrase_category(self, index: int, category: Category) -> None: # def append_token(self, spelling: str, category: Category = None, # span: Tuple[int, int] = None) -> int: # def clear_token_category(self, index: int) -> None: # def add_link(self, source: int, label: str, sink: int) -> None: # def discard_link(self, source: int, label: str, sink: int) -> None: # def remove_link(self, source: int, label: str, sink: int) -> None: # def has_link(self, source: int, label: str, sink: int) -> bool: # def iter_links(self, source: int = None, label: str = None, sink: int = None) \ # def sink_iterator_func(sinks): # def sink_iterator_func(sinks): # def label_iterator_func(labels): # def label_iterator_func(labels): # def __getitem__(self, index: int) -> Token: # def __len__(self) -> int: # def to_json(self) -> Dict[str, List]: # def get_phrase_category(self, head: int) -> Category: # def get_sinks(self, source: int) -> Set[int]: # def get_sources(self, sink: int) -> Set[int]: # def get_labels(self, source: int, sink: int) -> FrozenSet[LinkLabel]: # def _get_phrase_tokens(self, head: int, indices: Set[int]) -> None: # def get_phrase_tokens(self, head: int = None) -> List[Token]: # def visualize(self, gv_graph: Digraph) -> None: # # Path: pyramids/traversal.py # class LanguageContentHandler: # """A content handler for natural language, in the style of the # ContentHandler class of the xml.sax module.""" # # def handle_tree_end(self) -> None: # """Called to indicate the token_end_index of a tree.""" # # def handle_token(self, spelling: str, category: Category, index: int = None, # span: Tuple[int, int] = None) -> None: # """Called to indicate the occurrence of a token.""" # # def handle_root(self) -> None: # """Called to indicate that the next token is the root.""" # # def handle_link(self, source_start_index: int, sink_start_index: int, label: str) -> None: # """Called to indicate the occurrence of a link between two tokens. # Note that this will not be called until handle_token() has been # called for both the source and sink.""" # # def handle_phrase_start(self, category: Category, head_start_index: int = None) -> None: # """Called to indicate the token_start_index of a phrase.""" # # def handle_phrase_end(self) -> None: # """Called to indicate the token_end_index of a phrase.""" . Output only the next line.
sink_id = self._index_map[sink_index]
Using the snippet: <|code_start|> self._index_map[index] = len(self._tokens) self._tokens.append(Token(index, spelling, span, category)) self._links.append({}) self._phrases.append([(category, frozenset())]) # For convenience, return the id of the token so users can know # which index to use for links. return len(self._tokens) - 1 def handle_root(self) -> None: """Called to indicate that the next token is the root.""" assert self._root is None self._root = len(self._tokens) def handle_link(self, source_index: int, sink_index: int, label: str) -> None: """Called to indicate the occurrence of a link between two tokens. Note that this will not be called until handle_token() has been called for both the source and sink.""" assert source_index in self._index_map assert sink_index in self._index_map assert self._phrase_stack source_id = self._index_map[source_index] sink_id = self._index_map[sink_index] if sink_id in self._links[source_id]: self._links[source_id][sink_id].add(label) else: self._links[source_id][sink_id] = {label} <|code_end|> , determine the next line of code. You have imports: from typing import List, Tuple from pyramids.categorization import Category from pyramids.graphs import ParseGraph, Token from pyramids.traversal import LanguageContentHandler and context (class names, function names, or code) available: # Path: pyramids/categorization.py # CATEGORY_WILDCARD = _CATEGORY_WILDCARD # # Path: pyramids/graphs.py # class ParseGraph: # class BuildGraph: # def from_json(cls, json_data: Dict[str, List]) -> 'ParseGraph': # def __init__(self, root: int, tokens: Sequence[Token], links: List[Dict[int, Set[str]]], # phrases: List[List[Tuple[Category, List[Tuple[int, int]]]]]): # def root_index(self) -> int: # def root_category(self) -> Category: # def tokens(self) -> Tuple[Token, ...]: # def __str__(self) -> str: # def __getitem__(self, index: int) -> Token: # def __len__(self) -> int: # def to_json(self) -> Dict[str, List]: # def get_phrase_category(self, head: int) -> Category: # def get_phrase_stack(self, head: int) -> Category: # def get_sinks(self, source: int) -> Set[int]: # def get_sources(self, sink: int) -> Set[int]: # def get_labels(self, source: int, sink: int) -> FrozenSet[str]: # def _get_phrase_tokens(self, head: int, indices: Set[int]) -> None: # def get_phrase_tokens(self, head: int = None) -> List[Token]: # def get_phrase_text(self, head: int = None) -> str: # def visualize(self, gv_graph: Digraph) -> None: # def from_parse_graphs(cls, graphs: Sequence[Union[ParseGraph, 'BuildGraph']]) -> 'BuildGraph': # def from_json(cls, json_data: Dict[str, List]) -> 'BuildGraph': # def __init__(self): # def tokens(self) -> Tuple[Token, ...]: # def get_annotations(self) -> List[str]: # def find_roots(self) -> Set[int]: # def find_leaves(self) -> Set[int]: # def _is_forest(self, roots: Set[int]) -> bool: # def is_tree(self) -> bool: # def is_forest(self) -> bool: # def set_phrase_category(self, index: int, category: Category) -> None: # def append_token(self, spelling: str, category: Category = None, # span: Tuple[int, int] = None) -> int: # def clear_token_category(self, index: int) -> None: # def add_link(self, source: int, label: str, sink: int) -> None: # def discard_link(self, source: int, label: str, sink: int) -> None: # def remove_link(self, source: int, label: str, sink: int) -> None: # def has_link(self, source: int, label: str, sink: int) -> bool: # def iter_links(self, source: int = None, label: str = None, sink: int = None) \ # def sink_iterator_func(sinks): # def sink_iterator_func(sinks): # def label_iterator_func(labels): # def label_iterator_func(labels): # def __getitem__(self, index: int) -> Token: # def __len__(self) -> int: # def to_json(self) -> Dict[str, List]: # def get_phrase_category(self, head: int) -> Category: # def get_sinks(self, source: int) -> Set[int]: # def get_sources(self, sink: int) -> Set[int]: # def get_labels(self, source: int, sink: int) -> FrozenSet[LinkLabel]: # def _get_phrase_tokens(self, head: int, indices: Set[int]) -> None: # def get_phrase_tokens(self, head: int = None) -> List[Token]: # def visualize(self, gv_graph: Digraph) -> None: # # Path: pyramids/traversal.py # class LanguageContentHandler: # """A content handler for natural language, in the style of the # ContentHandler class of the xml.sax module.""" # # def handle_tree_end(self) -> None: # """Called to indicate the token_end_index of a tree.""" # # def handle_token(self, spelling: str, category: Category, index: int = None, # span: Tuple[int, int] = None) -> None: # """Called to indicate the occurrence of a token.""" # # def handle_root(self) -> None: # """Called to indicate that the next token is the root.""" # # def handle_link(self, source_start_index: int, sink_start_index: int, label: str) -> None: # """Called to indicate the occurrence of a link between two tokens. # Note that this will not be called until handle_token() has been # called for both the source and sink.""" # # def handle_phrase_start(self, category: Category, head_start_index: int = None) -> None: # """Called to indicate the token_start_index of a phrase.""" # # def handle_phrase_end(self) -> None: # """Called to indicate the token_end_index of a phrase.""" . Output only the next line.
self._phrase_stack[-1][-1].append((source_id, sink_id))