Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|> 'list_campaigns',
'list_experiments',
'list_wsn_gen_algorithms',
'render_campaign',
'render_templates',
'validated_parameters',
]
# *********************************************** GET FUNCTIONS ************************************************
def get_available_platforms():
"""
This function retrieves the list of available platforms from the Contiki directory.
:return: List of strings representing the available platforms
"""
platforms = []
for item in listdir(join(CONTIKI_FOLDER, 'platform')):
if isdir(join(CONTIKI_FOLDER, 'platform', item)):
platforms.append(item)
return platforms
def get_building_blocks():
"""
This function retrieves the list of available building blocks for the malicious mote.
:return: List of strings representing the available building blocks
"""
return is_valid_commented_json(join(TEMPLATES_FOLDER, 'building-blocks.json'),
<|code_end|>
, predict the next line using imports from the current file:
from copy import deepcopy
from jinja2 import Environment, FileSystemLoader
from math import sqrt
from os import listdir, makedirs, rename
from os.path import basename, dirname, exists, expanduser, isdir, isfile, join, split, splitext
from re import findall, finditer, search, sub, DOTALL, MULTILINE
from six import string_types
from core.common.helpers import *
from core.common.wsngenerator import *
from core.conf.constants import *
from core.conf.logconfig import logger
from core.common.wsngenerator import __all__
from core.common.wsngenerator import __all__ as wsn_algos
and context including class names, function names, and sometimes code from other files:
# Path: core/conf/logconfig.py
# LOG_FORMAT = '%(asctime)s %(name)s[%(process)d] %(levelname)s %(message)s'
# LOG_LEVELS = {
# 'info': logging.INFO,
# 'warning': logging.WARNING,
# 'error': logging.ERROR,
# 'debug': logging.DEBUG,
# }
# HIDDEN_ALL = ['warnings', 'stdout', 'stderr', 'running']
# HIDDEN_KEEP_STDERR = ['warnings', 'stdout', 'running']
# def set_logging(lvl='info'):
. Output only the next line. | return_json=True, logger=logger) or {} |
Continue the code snippet: <|code_start|> return self.command(*args, **kwargs)
class MultiprocessedCommand(DefaultCommand):
"""
This class handles command multi-processing and is to be attached to a console through its constructor's
arguments.
"""
is_multiprocessed = True
def __init__(self, console, command, name, path):
super(MultiprocessedCommand, self).__init__(console, command, name, path)
self.pool = console.pool
self.task = None
self.tasklist[self] = {
'name': name,
'command': self.command.__name__,
'status': 'INIT',
'expires': None,
'result': 'Not defined yet',
}
def __str__(self):
return '{}[{}]'.format(self.name, self.command.__name__.lstrip('_'))
def __set_info(self, status, result=None, expires=True):
if status != 'PENDING':
logger.debug(' > Process {} is over.'.format(self))
self.tasklist[self].update({'status': status, 'result': result or self.tasklist[self]['result']})
if expires:
<|code_end|>
. Use current file imports:
import dill
import os
import signal
import time
from datetime import datetime, timedelta
from multiprocessing import TimeoutError
from core.conf.constants import TASK_EXPIRATION
from core.conf.logconfig import logger
and context (classes, functions, or code) from other files:
# Path: core/conf/constants.py
# TASK_EXPIRATION = 60 # seconds
#
# Path: core/conf/logconfig.py
# LOG_FORMAT = '%(asctime)s %(name)s[%(process)d] %(levelname)s %(message)s'
# LOG_LEVELS = {
# 'info': logging.INFO,
# 'warning': logging.WARNING,
# 'error': logging.ERROR,
# 'debug': logging.DEBUG,
# }
# HIDDEN_ALL = ['warnings', 'stdout', 'stderr', 'running']
# HIDDEN_KEEP_STDERR = ['warnings', 'stdout', 'running']
# def set_logging(lvl='info'):
. Output only the next line. | self.tasklist[self]['expires'] = datetime.now() + timedelta(seconds=TASK_EXPIRATION) |
Given the code snippet: <|code_start|> if path is not None else []
def run(self, *args, **kwargs):
return self.command(*args, **kwargs)
class MultiprocessedCommand(DefaultCommand):
"""
This class handles command multi-processing and is to be attached to a console through its constructor's
arguments.
"""
is_multiprocessed = True
def __init__(self, console, command, name, path):
super(MultiprocessedCommand, self).__init__(console, command, name, path)
self.pool = console.pool
self.task = None
self.tasklist[self] = {
'name': name,
'command': self.command.__name__,
'status': 'INIT',
'expires': None,
'result': 'Not defined yet',
}
def __str__(self):
return '{}[{}]'.format(self.name, self.command.__name__.lstrip('_'))
def __set_info(self, status, result=None, expires=True):
if status != 'PENDING':
<|code_end|>
, generate the next line using the imports in this file:
import dill
import os
import signal
import time
from datetime import datetime, timedelta
from multiprocessing import TimeoutError
from core.conf.constants import TASK_EXPIRATION
from core.conf.logconfig import logger
and context (functions, classes, or occasionally code) from other files:
# Path: core/conf/constants.py
# TASK_EXPIRATION = 60 # seconds
#
# Path: core/conf/logconfig.py
# LOG_FORMAT = '%(asctime)s %(name)s[%(process)d] %(levelname)s %(message)s'
# LOG_LEVELS = {
# 'info': logging.INFO,
# 'warning': logging.WARNING,
# 'error': logging.ERROR,
# 'debug': logging.DEBUG,
# }
# HIDDEN_ALL = ['warnings', 'stdout', 'stderr', 'running']
# HIDDEN_KEEP_STDERR = ['warnings', 'stdout', 'running']
# def set_logging(lvl='info'):
. Output only the next line. | logger.debug(' > Process {} is over.'.format(self)) |
Using the snippet: <|code_start|> make(SIM, ask=False, silent=True)
def test1_experiment_structure(self):
""" > Is the new experiment correctly structured ? """
self.assertTrue(check_structure(self.path))
class Test4Remake(ExperimentTestCase):
""" 4. Remake the same example experiment """
@classmethod
def setUpClass(cls):
cls.t1 = getmtime(join(cls.path, 'with-malicious', 'motes', 'malicious.z1'))
remake(SIM, silent=True)
cls.t2 = getmtime(join(cls.path, 'with-malicious', 'motes', 'malicious.z1'))
def test1_experiment_structure_unchanged(self):
""" > Is the new experiment still correctly structured ? """
self.assertTrue(check_structure(self.path))
def test2_malicious_mote_recompiled(self):
""" > Is the malicious mote well recompiled ? """
self.assertNotEqual(self.t1, self.t2)
class Test5Clean(ExperimentTestCase):
""" 5. Clean the same example experiment """
@classmethod
def setUpClass(cls):
<|code_end|>
, determine the next line of code. You have imports:
import sh
import unittest
from os.path import exists, expanduser, getmtime, join
from core.commands import clean, make, remake
from core.conf.constants import EXPERIMENT_FOLDER
from core.utils.rpla import check_structure
and context (class names, function names, or code) available:
# Path: core/commands.py
# def get_commands(include=None, exclude=None):
# def build(name, ask=True, **kwargs):
# def is_device_present():
# def clean(name, ask=True, **kwargs):
# def cooja(name, with_malicious=True, **kwargs):
# def __make(name, ask=True, **kwargs):
# def __remake(name, build=False, **kwargs):
# def report(name, theme=REPORT_THEME, silent=False, **kwargs):
# def __run(name, **kwargs):
# def clean_all(exp_file, **kwargs):
# def drop(exp_file, ask=True, **kwargs):
# def make_all(exp_file, **kwargs):
# def prepare(exp_file, ask=True, **kwargs):
# def remake_all(exp_file, **kwargs):
# def run_all(exp_file, **kwargs):
# def list(item_type, **kwargs):
# def config(contiki_folder='~/contiki', experiments_folder='~/Experiments', silent=False, **kwargs):
# def test(**kwargs):
# def setup(silent=False, **kwargs):
# def update(silent=False, **kwargs):
# def versions(**kwargs):
# def demo(**kwargs):
#
# Path: core/conf/constants.py
# EXPERIMENT_FOLDER = abspath(expanduser(confparser.get("RPL Attacks Framework Configuration", "experiments_folder")))
#
# Path: core/utils/rpla.py
# def check_structure(path, files=None, create=False, remove=False):
# """
# This function checks if the file structure given by the dictionary files exists at the input path.
#
# :param path: path to be checked for the file structure
# :param files: file structure as a dictionary
# :param create: create subfolders if they do not exist
# :param remove: if this flag is True, non-matching files are removed
# :return: True if the file structure is respected, otherwise False
# """
# if create and not exists(path):
# makedirs(path)
# files = deepcopy(EXPERIMENT_STRUCTURE) if files is None else files
# if files.get('*'):
# return True
# items = listdir(path)
# if create:
# items = [i for i, f in files.items() if not isinstance(f, bool)] + items
# for item in items:
# wildcard = '{}.*'.format(splitext(item)[0])
# match = item if item in files.keys() else (wildcard if wildcard in files.keys() else None)
# if match is None:
# if remove:
# remove_files(path, item)
# continue
# files[match] = True if isinstance(files[match], bool) else \
# check_structure(join(path, match), deepcopy(files[match]), create, remove)
# return all(files.values())
. Output only the next line. | clean(SIM, ask=False, silent=True) |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
SIM = 'test-simulation'
class ExperimentTestCase(unittest.TestCase):
path = expanduser(join(EXPERIMENT_FOLDER, SIM))
backup = path + '.backup'
class Test3Make(ExperimentTestCase):
""" 3. Make an example experiment """
@classmethod
def setUpClass(cls):
if exists(cls.path):
sh.mv(cls.path, cls.backup)
<|code_end|>
, generate the next line using the imports in this file:
import sh
import unittest
from os.path import exists, expanduser, getmtime, join
from core.commands import clean, make, remake
from core.conf.constants import EXPERIMENT_FOLDER
from core.utils.rpla import check_structure
and context (functions, classes, or occasionally code) from other files:
# Path: core/commands.py
# def get_commands(include=None, exclude=None):
# def build(name, ask=True, **kwargs):
# def is_device_present():
# def clean(name, ask=True, **kwargs):
# def cooja(name, with_malicious=True, **kwargs):
# def __make(name, ask=True, **kwargs):
# def __remake(name, build=False, **kwargs):
# def report(name, theme=REPORT_THEME, silent=False, **kwargs):
# def __run(name, **kwargs):
# def clean_all(exp_file, **kwargs):
# def drop(exp_file, ask=True, **kwargs):
# def make_all(exp_file, **kwargs):
# def prepare(exp_file, ask=True, **kwargs):
# def remake_all(exp_file, **kwargs):
# def run_all(exp_file, **kwargs):
# def list(item_type, **kwargs):
# def config(contiki_folder='~/contiki', experiments_folder='~/Experiments', silent=False, **kwargs):
# def test(**kwargs):
# def setup(silent=False, **kwargs):
# def update(silent=False, **kwargs):
# def versions(**kwargs):
# def demo(**kwargs):
#
# Path: core/conf/constants.py
# EXPERIMENT_FOLDER = abspath(expanduser(confparser.get("RPL Attacks Framework Configuration", "experiments_folder")))
#
# Path: core/utils/rpla.py
# def check_structure(path, files=None, create=False, remove=False):
# """
# This function checks if the file structure given by the dictionary files exists at the input path.
#
# :param path: path to be checked for the file structure
# :param files: file structure as a dictionary
# :param create: create subfolders if they do not exist
# :param remove: if this flag is True, non-matching files are removed
# :return: True if the file structure is respected, otherwise False
# """
# if create and not exists(path):
# makedirs(path)
# files = deepcopy(EXPERIMENT_STRUCTURE) if files is None else files
# if files.get('*'):
# return True
# items = listdir(path)
# if create:
# items = [i for i, f in files.items() if not isinstance(f, bool)] + items
# for item in items:
# wildcard = '{}.*'.format(splitext(item)[0])
# match = item if item in files.keys() else (wildcard if wildcard in files.keys() else None)
# if match is None:
# if remove:
# remove_files(path, item)
# continue
# files[match] = True if isinstance(files[match], bool) else \
# check_structure(join(path, match), deepcopy(files[match]), create, remove)
# return all(files.values())
. Output only the next line. | make(SIM, ask=False, silent=True) |
Given the code snippet: <|code_start|>
SIM = 'test-simulation'
class ExperimentTestCase(unittest.TestCase):
path = expanduser(join(EXPERIMENT_FOLDER, SIM))
backup = path + '.backup'
class Test3Make(ExperimentTestCase):
""" 3. Make an example experiment """
@classmethod
def setUpClass(cls):
if exists(cls.path):
sh.mv(cls.path, cls.backup)
make(SIM, ask=False, silent=True)
def test1_experiment_structure(self):
""" > Is the new experiment correctly structured ? """
self.assertTrue(check_structure(self.path))
class Test4Remake(ExperimentTestCase):
""" 4. Remake the same example experiment """
@classmethod
def setUpClass(cls):
cls.t1 = getmtime(join(cls.path, 'with-malicious', 'motes', 'malicious.z1'))
<|code_end|>
, generate the next line using the imports in this file:
import sh
import unittest
from os.path import exists, expanduser, getmtime, join
from core.commands import clean, make, remake
from core.conf.constants import EXPERIMENT_FOLDER
from core.utils.rpla import check_structure
and context (functions, classes, or occasionally code) from other files:
# Path: core/commands.py
# def get_commands(include=None, exclude=None):
# def build(name, ask=True, **kwargs):
# def is_device_present():
# def clean(name, ask=True, **kwargs):
# def cooja(name, with_malicious=True, **kwargs):
# def __make(name, ask=True, **kwargs):
# def __remake(name, build=False, **kwargs):
# def report(name, theme=REPORT_THEME, silent=False, **kwargs):
# def __run(name, **kwargs):
# def clean_all(exp_file, **kwargs):
# def drop(exp_file, ask=True, **kwargs):
# def make_all(exp_file, **kwargs):
# def prepare(exp_file, ask=True, **kwargs):
# def remake_all(exp_file, **kwargs):
# def run_all(exp_file, **kwargs):
# def list(item_type, **kwargs):
# def config(contiki_folder='~/contiki', experiments_folder='~/Experiments', silent=False, **kwargs):
# def test(**kwargs):
# def setup(silent=False, **kwargs):
# def update(silent=False, **kwargs):
# def versions(**kwargs):
# def demo(**kwargs):
#
# Path: core/conf/constants.py
# EXPERIMENT_FOLDER = abspath(expanduser(confparser.get("RPL Attacks Framework Configuration", "experiments_folder")))
#
# Path: core/utils/rpla.py
# def check_structure(path, files=None, create=False, remove=False):
# """
# This function checks if the file structure given by the dictionary files exists at the input path.
#
# :param path: path to be checked for the file structure
# :param files: file structure as a dictionary
# :param create: create subfolders if they do not exist
# :param remove: if this flag is True, non-matching files are removed
# :return: True if the file structure is respected, otherwise False
# """
# if create and not exists(path):
# makedirs(path)
# files = deepcopy(EXPERIMENT_STRUCTURE) if files is None else files
# if files.get('*'):
# return True
# items = listdir(path)
# if create:
# items = [i for i, f in files.items() if not isinstance(f, bool)] + items
# for item in items:
# wildcard = '{}.*'.format(splitext(item)[0])
# match = item if item in files.keys() else (wildcard if wildcard in files.keys() else None)
# if match is None:
# if remove:
# remove_files(path, item)
# continue
# files[match] = True if isinstance(files[match], bool) else \
# check_structure(join(path, match), deepcopy(files[match]), create, remove)
# return all(files.values())
. Output only the next line. | remake(SIM, silent=True) |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
SIM = 'test-simulation'
class ExperimentTestCase(unittest.TestCase):
path = expanduser(join(EXPERIMENT_FOLDER, SIM))
backup = path + '.backup'
class Test3Make(ExperimentTestCase):
""" 3. Make an example experiment """
@classmethod
def setUpClass(cls):
if exists(cls.path):
sh.mv(cls.path, cls.backup)
make(SIM, ask=False, silent=True)
def test1_experiment_structure(self):
""" > Is the new experiment correctly structured ? """
<|code_end|>
. Use current file imports:
(import sh
import unittest
from os.path import exists, expanduser, getmtime, join
from core.commands import clean, make, remake
from core.conf.constants import EXPERIMENT_FOLDER
from core.utils.rpla import check_structure)
and context including class names, function names, or small code snippets from other files:
# Path: core/commands.py
# def get_commands(include=None, exclude=None):
# def build(name, ask=True, **kwargs):
# def is_device_present():
# def clean(name, ask=True, **kwargs):
# def cooja(name, with_malicious=True, **kwargs):
# def __make(name, ask=True, **kwargs):
# def __remake(name, build=False, **kwargs):
# def report(name, theme=REPORT_THEME, silent=False, **kwargs):
# def __run(name, **kwargs):
# def clean_all(exp_file, **kwargs):
# def drop(exp_file, ask=True, **kwargs):
# def make_all(exp_file, **kwargs):
# def prepare(exp_file, ask=True, **kwargs):
# def remake_all(exp_file, **kwargs):
# def run_all(exp_file, **kwargs):
# def list(item_type, **kwargs):
# def config(contiki_folder='~/contiki', experiments_folder='~/Experiments', silent=False, **kwargs):
# def test(**kwargs):
# def setup(silent=False, **kwargs):
# def update(silent=False, **kwargs):
# def versions(**kwargs):
# def demo(**kwargs):
#
# Path: core/conf/constants.py
# EXPERIMENT_FOLDER = abspath(expanduser(confparser.get("RPL Attacks Framework Configuration", "experiments_folder")))
#
# Path: core/utils/rpla.py
# def check_structure(path, files=None, create=False, remove=False):
# """
# This function checks if the file structure given by the dictionary files exists at the input path.
#
# :param path: path to be checked for the file structure
# :param files: file structure as a dictionary
# :param create: create subfolders if they do not exist
# :param remove: if this flag is True, non-matching files are removed
# :return: True if the file structure is respected, otherwise False
# """
# if create and not exists(path):
# makedirs(path)
# files = deepcopy(EXPERIMENT_STRUCTURE) if files is None else files
# if files.get('*'):
# return True
# items = listdir(path)
# if create:
# items = [i for i, f in files.items() if not isinstance(f, bool)] + items
# for item in items:
# wildcard = '{}.*'.format(splitext(item)[0])
# match = item if item in files.keys() else (wildcard if wildcard in files.keys() else None)
# if match is None:
# if remove:
# remove_files(path, item)
# continue
# files[match] = True if isinstance(files[match], bool) else \
# check_structure(join(path, match), deepcopy(files[match]), create, remove)
# return all(files.values())
. Output only the next line. | self.assertTrue(check_structure(self.path)) |
Given the following code snippet before the placeholder: <|code_start|> '-e', 'wpan.dst64',
'-e', 'icmpv6.type',
'-e', 'ipv6.src',
'-e', 'ipv6.dst',
'-e', 'icmpv6.code',
'-e', 'data.data',
'-r', join(data, 'output.pcap')], stdout=PIPE)
out, _ = p.communicate()
except OSError:
out = b"Tshark is not installed !"
if logger:
logger.warn(out)
with open(join(results, 'pcap.csv'), 'wb') as f:
f.write(out)
PT_ITEMS = ['monitored', 'on', 'tx', 'rx', 'int']
PT_REGEX = r'^({})_(?P<mote_id>\d+) {} (?P<{}>\d+)'
def __convert_powertracker_log_to_csv(path, logger=None):
"""
This function creates a CSV file (to ./results) from a PowerTracker log file (from ./data).
This is inspired from https://github.com/sieben/makesense/blob/master/makesense/parser.py.
:param path: path to the experiment (including [with-|without-malicious])
:param logger: logging.Logger instance
"""
if logger:
logger.debug(" > Converting power tracking log to CSV...")
<|code_end|>
, predict the next line using imports from the current file:
import networkx
import numpy
from csv import DictReader, DictWriter
from matplotlib import pyplot
from matplotlib.patches import FancyArrowPatch
from os.path import basename, isdir, join, normpath
from re import finditer, match, MULTILINE
from subprocess import Popen, PIPE
from core.utils.rpla import get_available_platforms, get_motes_from_simulation
and context including class names, function names, and sometimes code from other files:
# Path: core/utils/rpla.py
# def get_available_platforms():
# """
# This function retrieves the list of available platforms from the Contiki directory.
#
# :return: List of strings representing the available platforms
# """
# platforms = []
# for item in listdir(join(CONTIKI_FOLDER, 'platform')):
# if isdir(join(CONTIKI_FOLDER, 'platform', item)):
# platforms.append(item)
# return platforms
#
# def get_motes_from_simulation(simfile, as_dictionary=True):
# """
# This function retrieves motes data from a simulation file (.csc).
#
# :param simfile: path to the simulation file
# :param as_dictionary: flag to indicate that the output has to be formatted as a dictionary
# :return: the list of motes formatted as dictionaries with 'id', 'x', 'y' and 'motetype_identifier' keys if
# short is False or a dictionary with each mote id as the key and its tuple (x, y) as the value
# """
# motes = []
# with open(simfile) as f:
# content = f.read()
# iterables, fields = [], ['mote_id']
# for it in ['id', 'x', 'y', 'motetype_identifier']:
# iterables.append(finditer(r'^\s*<{0}>(?P<{0}>.*)</{0}>\s*$'.format(it), content, MULTILINE))
# for matches in zip(*iterables):
# mote = {}
# for m in matches:
# mote.update(m.groupdict())
# motes.append(mote)
# if as_dictionary:
# motes = {int(m['id']): (float(m['x']), float(m['y'])) for m in motes}
# return motes
. Output only the next line. | platforms = [p.capitalize() for p in get_available_platforms()] |
Given snippet: <|code_start|> time_field = '{}_time'.format(it)
row[time_field] = float(row[time_field] / 10 ** 6)
writer.writerow(row)
RELATIONSHIP_REGEX = r'^\d+\s+ID\:(?P<mote_id>\d+)\s+#L\s+(?P<parent_id>\d+)\s+(?P<flag>\d+)$'
def __draw_dodag(path, logger=None):
"""
This function draws the DODAG (to ./results) from the list of motes (from ./simulation.csc) and the list of
edges (from ./data/relationships.log).
:param path: path to the experiment (including [with-|without-malicious])
:param logger: logging.Logger instance
"""
if logger:
logger.debug(" > Drawing DODAG to PNG...")
pyplot.clf()
with_malicious = (basename(normpath(path)) == 'with-malicious')
data, results = join(path, 'data'), join(path, 'results')
with open(join(data, 'relationships.log')) as f:
relationships = f.read()
# first, check if the mote relationships were recorded
if len(relationships.strip()) == 0:
if logger:
logger.warn("Relationships log file is empty !")
return
# retrieve motes and their colors
dodag = networkx.DiGraph()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import networkx
import numpy
from csv import DictReader, DictWriter
from matplotlib import pyplot
from matplotlib.patches import FancyArrowPatch
from os.path import basename, isdir, join, normpath
from re import finditer, match, MULTILINE
from subprocess import Popen, PIPE
from core.utils.rpla import get_available_platforms, get_motes_from_simulation
and context:
# Path: core/utils/rpla.py
# def get_available_platforms():
# """
# This function retrieves the list of available platforms from the Contiki directory.
#
# :return: List of strings representing the available platforms
# """
# platforms = []
# for item in listdir(join(CONTIKI_FOLDER, 'platform')):
# if isdir(join(CONTIKI_FOLDER, 'platform', item)):
# platforms.append(item)
# return platforms
#
# def get_motes_from_simulation(simfile, as_dictionary=True):
# """
# This function retrieves motes data from a simulation file (.csc).
#
# :param simfile: path to the simulation file
# :param as_dictionary: flag to indicate that the output has to be formatted as a dictionary
# :return: the list of motes formatted as dictionaries with 'id', 'x', 'y' and 'motetype_identifier' keys if
# short is False or a dictionary with each mote id as the key and its tuple (x, y) as the value
# """
# motes = []
# with open(simfile) as f:
# content = f.read()
# iterables, fields = [], ['mote_id']
# for it in ['id', 'x', 'y', 'motetype_identifier']:
# iterables.append(finditer(r'^\s*<{0}>(?P<{0}>.*)</{0}>\s*$'.format(it), content, MULTILINE))
# for matches in zip(*iterables):
# mote = {}
# for m in matches:
# mote.update(m.groupdict())
# motes.append(mote)
# if as_dictionary:
# motes = {int(m['id']): (float(m['x']), float(m['y'])) for m in motes}
# return motes
which might include code, classes, or functions. Output only the next line. | motes = get_motes_from_simulation(join(path, 'simulation.csc')) |
Predict the next line for this snippet: <|code_start|> k = 'web-port'
else:
k = '%s-port' % mon_method
params['monitor']['method'][mon_method][k] = int(port)
params['monitor']['override-port'] = int(port)
# handle POST case for HTTP/HTTPS hm
if ('url-type' in params['monitor']['method'][mon_method] and
'url-path' in params['monitor']['method'][mon_method] and
params['monitor']['method'][mon_method]['url-type'] == "POST"):
if post_data:
params['monitor']['method'][mon_method]['post-type'] = "postdata"
if mon_method == self.HTTPS:
params['monitor']['method'][mon_method]['https-postdata'] = str(post_data)
else:
params['monitor']['method'][mon_method]['http-postdata'] = str(post_data)
postpath = params['monitor']['method'][mon_method]['url-path']
params['monitor']['method'][mon_method]['post-path'] = postpath
params['monitor']['method'][mon_method].pop('url-path', None)
else:
params['monitor']['method'][mon_method].pop('post-type', None)
params['monitor']['method'][mon_method].pop('http-postdata', None)
params['monitor']['method'][mon_method].pop('post-path', None)
return params
def create(self, name, mon_type, hm_interval, hm_timeout, hm_max_retries,
method=None, url=None, expect_code=None, port=None, ipv4=None, post_data=None,
max_retries=None, timeout=None, **kwargs):
try:
self.get(name)
<|code_end|>
with the help of current file imports:
from acos_client import errors as acos_errors
from acos_client.v30 import base
and context from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
, which may contain function names, class names, or code. Output only the next line. | except acos_errors.NotFound: |
Here is a snippet: <|code_start|>#
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
class BasePersistence(base.BaseV30):
def __init__(self, client):
super(BasePersistence, self).__init__(client)
self.prefix = "/slb/template/persist/%s/" % self.pers_type
def get(self, name, **kwargs):
return self._get(self.prefix + name, **kwargs)
def exists(self, name):
try:
self.get(name)
return True
<|code_end|>
. Write the next line using the current file imports:
from acos_client import errors as acos_errors
from acos_client.v30 import base
and context from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
, which may include functions, classes, or code. Output only the next line. | except acos_errors.NotFound: |
Predict the next line for this snippet: <|code_start|># Copyright (C) 2016, A10 Networks Inc. All rights reserved.
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
class TestVRID(unittest.TestCase):
def setUp(self):
self.client = mock.MagicMock()
<|code_end|>
with the help of current file imports:
import unittest
import mock
import unittest2 as unittest
from unittest import mock
from acos_client.v30.vrrpa import vrid
and context from other files:
# Path: acos_client/v30/vrrpa/vrid.py
# class VRID(base.BaseV30):
# def __init__(self, client):
# def blade(self):
# def get(self, vrid_val):
# def exists(self, vrid_val):
# def _build_params(self, vrid_val, threshold=None, disable=None, floating_ips=[],
# is_partition=False):
# def create(self, vrid_val, threshold=None, disable=None, floating_ips=[], is_partition=False):
# def update(self, vrid_val, threshold=None, disable=None, floating_ips=[], is_partition=False):
# def delete(self, vrid_val):
, which may contain function names, class names, or code. Output only the next line. | self.target = vrid.VRID(self.client) |
Predict the next line after this snippet: <|code_start|>#
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
HOSTNAME = 'fake_a10'
BASE_URL = "https://{}:443/axapi/v3/".format(HOSTNAME)
AUTH_URL = "{}auth".format(BASE_URL)
SLB_URL = '{}slb/template/persist/cookie/'.format(BASE_URL)
class TestSLBTemplateCookiePersistence(unittest.TestCase):
def setUp(self):
<|code_end|>
using the current file's imports:
import unittest2 as unittest
import unittest
import acos_client.errors as acos_errors
import responses
from acos_client import client
and any relevant context from other files:
# Path: acos_client/client.py
# VERSION_IMPORTS = {
# '21': {
# 'DNS': v21_DNS,
# 'http': v21_http,
# 'HA': v21_HA,
# 'Interface': v21_Interface,
# 'LicenseManager': v21_LicenseManager,
# 'Nat': v21_Nat,
# 'Network': v21_Network,
# 'Session': v21_Session,
# 'SFlow': v21_SFlow,
# 'SLB': v21_SLB,
# 'System': v21_System,
# 'Vlan': None,
# 'VRRPA': v21_VRRPA
# },
# '30': {
# 'DNS': v30_DNS,
# 'http': v30_http,
# 'Interface': v30_Interface,
# 'HA': v30_HA,
# 'LicenseManager': v30_LicenseManager,
# 'Nat': v30_Nat,
# 'Network': v30_Network,
# 'Overlay': v30_Overlay,
# 'RIB': v30_RIB,
# 'Session': v30_Session,
# 'SFlow': v30_SFlow,
# 'SLB': v30_SLB,
# 'System': v30_System,
# 'File': v30_File,
# 'Vlan': v30_Vlan,
# 'VRRPA': v30_VRRPA,
# 'DeviceContext': v30_DeviceContext,
# 'Flexpool': Flexpool,
# 'Delete': Delete,
# },
# }
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(
# self,
# host, # ip address or name of the A10 device
# version, # either 21 or 30
# username, # username to use for authenticating to the A10 device
# password, # password to use for authenticating to the A10 device
# max_retries=3, # number of times to retry a connection before giving up
# port=None, # TCP port to use for connecting to the A10 device
# protocol="https", # transport protocol - http or https, encryption recommended
# timeout=5 # seconds to wait for return data before giving up
# ):
# def _just_digits(self, s):
# def dns(self):
# def ha(self):
# def interface(self):
# def system(self):
# def slb(self):
# def network(self):
# def nat(self):
# def file(self):
# def sflow(self):
# def license_manager(self):
# def glm(self):
# def overlay(self):
# def vlan(self):
# def route(self):
# def vrrpa(self):
# def device_context(self):
# def delete(self):
# def wait_for_connect(self, max_timeout=60):
. Output only the next line. | self.client = client.Client(HOSTNAME, '30', 'fake_username', 'fake_password') |
Continue the code snippet: <|code_start|>#
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
HOSTNAME = 'fake_a10'
BASE_URL = 'https://{}:443/axapi/v3'.format(HOSTNAME)
AUTH_URL = '{}/auth'.format(BASE_URL)
VSERVER_NAME = 'test'
CREATE_URL = '{}/slb/virtual-server/'.format(BASE_URL)
OBJECT_URL = '{}/slb/virtual-server/{}'.format(BASE_URL, VSERVER_NAME)
STATS_URL = '{}/slb/virtual-server/{}/port/stats'.format(BASE_URL, VSERVER_NAME)
OPER_URL = '{}/slb/virtual-server/{}/oper'.format(BASE_URL, VSERVER_NAME)
class TestVirtualServer(unittest.TestCase):
def setUp(self):
<|code_end|>
. Use current file imports:
import json
import responses
import unittest
import unittest2 as unittest
import acos_client.errors as acos_errors
from acos_client import client
and context (classes, functions, or code) from other files:
# Path: acos_client/client.py
# VERSION_IMPORTS = {
# '21': {
# 'DNS': v21_DNS,
# 'http': v21_http,
# 'HA': v21_HA,
# 'Interface': v21_Interface,
# 'LicenseManager': v21_LicenseManager,
# 'Nat': v21_Nat,
# 'Network': v21_Network,
# 'Session': v21_Session,
# 'SFlow': v21_SFlow,
# 'SLB': v21_SLB,
# 'System': v21_System,
# 'Vlan': None,
# 'VRRPA': v21_VRRPA
# },
# '30': {
# 'DNS': v30_DNS,
# 'http': v30_http,
# 'Interface': v30_Interface,
# 'HA': v30_HA,
# 'LicenseManager': v30_LicenseManager,
# 'Nat': v30_Nat,
# 'Network': v30_Network,
# 'Overlay': v30_Overlay,
# 'RIB': v30_RIB,
# 'Session': v30_Session,
# 'SFlow': v30_SFlow,
# 'SLB': v30_SLB,
# 'System': v30_System,
# 'File': v30_File,
# 'Vlan': v30_Vlan,
# 'VRRPA': v30_VRRPA,
# 'DeviceContext': v30_DeviceContext,
# 'Flexpool': Flexpool,
# 'Delete': Delete,
# },
# }
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(
# self,
# host, # ip address or name of the A10 device
# version, # either 21 or 30
# username, # username to use for authenticating to the A10 device
# password, # password to use for authenticating to the A10 device
# max_retries=3, # number of times to retry a connection before giving up
# port=None, # TCP port to use for connecting to the A10 device
# protocol="https", # transport protocol - http or https, encryption recommended
# timeout=5 # seconds to wait for return data before giving up
# ):
# def _just_digits(self, s):
# def dns(self):
# def ha(self):
# def interface(self):
# def system(self):
# def slb(self):
# def network(self):
# def nat(self):
# def file(self):
# def sflow(self):
# def license_manager(self):
# def glm(self):
# def overlay(self):
# def vlan(self):
# def route(self):
# def vrrpa(self):
# def device_context(self):
# def delete(self):
# def wait_for_connect(self, max_timeout=60):
. Output only the next line. | self.client = client.Client(HOSTNAME, '30', 'fake_username', 'fake_password') |
Given the code snippet: <|code_start|> conn_resume=None, conn_limit=None, health_check=None, **kwargs):
params = self._set(name, ip_address, status=status, port_list=port_list,
conn_resume=conn_resume, conn_limit=conn_limit, health_check=health_check,
server_templates=server_templates, **kwargs)
return self._post(self.url_prefix, params, max_retries=max_retries, timeout=timeout,
axapi_args=kwargs)
def update(self, name, ip_address, status=1, server_templates=None,
port_list=None, max_retries=None, timeout=None,
conn_resume=None, conn_limit=None, health_check=None, **kwargs):
params = self._set(name, ip_address, status=status, port_list=port_list,
conn_resume=conn_resume, conn_limit=conn_limit, health_check=health_check,
server_templates=server_templates, **kwargs)
return self._post(self.url_prefix + name, params, max_retries=max_retries, timeout=timeout,
axapi_args=kwargs)
def replace(self, name, ip_address, status=1, server_templates=None,
port_list=None, max_retries=None, timeout=None,
conn_resume=None, conn_limit=None, health_check=None, **kwargs):
params = self._set(name, ip_address, status=status, port_list=port_list,
conn_resume=conn_resume, conn_limit=conn_limit, health_check=health_check,
server_templates=server_templates, **kwargs)
return self._put(self.url_prefix + name, params, max_retries=max_retries, timeout=timeout,
axapi_args=kwargs)
def delete(self, name):
return self._delete(self.url_prefix + name)
@property
def port(self):
<|code_end|>
, generate the next line using the imports in this file:
from acos_client.v30 import base
from acos_client.v30.slb.port import Port
and context (functions, classes, or occasionally code) from other files:
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
#
# Path: acos_client/v30/slb/port.py
# class Port(base.BaseV30):
#
# url_base_tmpl = "/slb/server/{server}/port/"
# url_port_tmpl = "{port}+{protocol}/"
#
# def create(self, server_name, port, protocol, max_retries=None, timeout=None,
# conn_resume=None, conn_limit=None, stats_data_action="stats-data-enable",
# weight=1, range=0, action="enable", **kwargs):
# url = self.url_base_tmpl.format(server=server_name)
# params = self._set(server_name, port, protocol, conn_resume=conn_resume, conn_limit=conn_limit,
# stats_data_action=stats_data_action, weight=weight, range=range, action=action)
# return self._post(url, params, max_retries=max_retries, timeout=timeout, axapi_args=kwargs)
#
# def update(self, server_name, port, protocol, max_retries=None, timeout=None,
# conn_resume=None, conn_limit=None, stats_data_action="stats-data-enable",
# weight=1, range=0, action="enable", **kwargs):
# url = self.url_base_tmpl.format(server=server_name)
# url += self.url_port_tmpl.format(port=port, protocol=protocol)
# params = self._set(server_name, port, protocol, conn_resume=conn_resume, conn_limit=conn_limit,
# stats_data_action=stats_data_action, weight=weight, range=range, action=action)
# return self._put(url, params, max_retries=max_retries, timeout=timeout, axapi_args=kwargs)
#
# def delete(self, server_name, port, protocol, **kwargs):
# url = (self.url_base_tmpl + self.url_port_tmpl).format(server=server_name,
# port=port,
# protocol=protocol)
#
# return self._delete(url)
#
# def _set(self, server_name, port, protocol, conn_resume=None, conn_limit=None,
# stats_data_action="stats-data-enable", weight=1, range=0, action="enable"):
# params = {
# "port": {
# "stats-data-action": stats_data_action,
# "weight": weight,
# "port-number": port,
# "range": range,
# "action": action,
# "protocol": protocol
# }
# }
#
# if conn_resume:
# params['port']['conn-resume'] = conn_resume
#
# if conn_limit:
# params['port']['conn-limit'] = conn_limit
#
# return params
. Output only the next line. | return Port(self.client) |
Predict the next line after this snippet: <|code_start|># 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
HOSTNAME = 'fake_a10'
BASE_URL = 'https://{}:443/axapi/v3'.format(HOSTNAME)
AUTH_URL = '{}/auth'.format(BASE_URL)
SERVICE_GROUP_NAME = 'test1'
CREATE_URL = '{}/slb/service-group/'.format(BASE_URL)
OBJECT_URL = '{}/slb/service-group/{}'.format(BASE_URL, SERVICE_GROUP_NAME)
class TestVirtualServer(unittest.TestCase):
def setUp(self):
<|code_end|>
using the current file's imports:
import unittest
import unittest2 as unittest
import acos_client.errors as acos_errors
import json
import responses
from acos_client import client
and any relevant context from other files:
# Path: acos_client/client.py
# VERSION_IMPORTS = {
# '21': {
# 'DNS': v21_DNS,
# 'http': v21_http,
# 'HA': v21_HA,
# 'Interface': v21_Interface,
# 'LicenseManager': v21_LicenseManager,
# 'Nat': v21_Nat,
# 'Network': v21_Network,
# 'Session': v21_Session,
# 'SFlow': v21_SFlow,
# 'SLB': v21_SLB,
# 'System': v21_System,
# 'Vlan': None,
# 'VRRPA': v21_VRRPA
# },
# '30': {
# 'DNS': v30_DNS,
# 'http': v30_http,
# 'Interface': v30_Interface,
# 'HA': v30_HA,
# 'LicenseManager': v30_LicenseManager,
# 'Nat': v30_Nat,
# 'Network': v30_Network,
# 'Overlay': v30_Overlay,
# 'RIB': v30_RIB,
# 'Session': v30_Session,
# 'SFlow': v30_SFlow,
# 'SLB': v30_SLB,
# 'System': v30_System,
# 'File': v30_File,
# 'Vlan': v30_Vlan,
# 'VRRPA': v30_VRRPA,
# 'DeviceContext': v30_DeviceContext,
# 'Flexpool': Flexpool,
# 'Delete': Delete,
# },
# }
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(
# self,
# host, # ip address or name of the A10 device
# version, # either 21 or 30
# username, # username to use for authenticating to the A10 device
# password, # password to use for authenticating to the A10 device
# max_retries=3, # number of times to retry a connection before giving up
# port=None, # TCP port to use for connecting to the A10 device
# protocol="https", # transport protocol - http or https, encryption recommended
# timeout=5 # seconds to wait for return data before giving up
# ):
# def _just_digits(self, s):
# def dns(self):
# def ha(self):
# def interface(self):
# def system(self):
# def slb(self):
# def network(self):
# def nat(self):
# def file(self):
# def sflow(self):
# def license_manager(self):
# def glm(self):
# def overlay(self):
# def vlan(self):
# def route(self):
# def vrrpa(self):
# def device_context(self):
# def delete(self):
# def wait_for_connect(self, max_timeout=60):
. Output only the next line. | self.client = client.Client(HOSTNAME, '30', 'fake_username', 'fake_password') |
Predict the next line for this snippet: <|code_start|># 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 VRID(base.BaseV30):
def __init__(self, client):
super(VRID, self).__init__(client)
self.client = client
self.base_url = "/vrrp-a/vrid/"
@property
def blade(self):
return BladeParameters(self.client)
def get(self, vrid_val):
return self._get(self.base_url + str(vrid_val))
def exists(self, vrid_val):
try:
self.get(vrid_val)
return True
<|code_end|>
with the help of current file imports:
from acos_client import errors as acos_errors
from acos_client.v30 import base
from acos_client.v30.vrrpa.blade_params import BladeParameters
and context from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
, which may contain function names, class names, or code. Output only the next line. | except acos_errors.NotFound: |
Based on the snippet: <|code_start|># 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
HOSTNAME = 'fake_a10'
BASE_URL = 'https://{}:443/axapi/v3'.format(HOSTNAME)
AUTH_URL = '{}/auth'.format(BASE_URL)
MEM_NAME = 'fake-server'
SG_NAME = 'fake-sg'
CREATE_URL = '{}/slb/service-group/{}/member/'.format(BASE_URL, SG_NAME)
OBJECT_URL = '{}/slb/service-group/{}/member/{}+{}/'
OK_RESP = {'response': {'status': 'OK'}}
class TestMember(unittest.TestCase):
def setUp(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import responses
import unittest
import unittest2 as unittest
from acos_client import client
and context (classes, functions, sometimes code) from other files:
# Path: acos_client/client.py
# VERSION_IMPORTS = {
# '21': {
# 'DNS': v21_DNS,
# 'http': v21_http,
# 'HA': v21_HA,
# 'Interface': v21_Interface,
# 'LicenseManager': v21_LicenseManager,
# 'Nat': v21_Nat,
# 'Network': v21_Network,
# 'Session': v21_Session,
# 'SFlow': v21_SFlow,
# 'SLB': v21_SLB,
# 'System': v21_System,
# 'Vlan': None,
# 'VRRPA': v21_VRRPA
# },
# '30': {
# 'DNS': v30_DNS,
# 'http': v30_http,
# 'Interface': v30_Interface,
# 'HA': v30_HA,
# 'LicenseManager': v30_LicenseManager,
# 'Nat': v30_Nat,
# 'Network': v30_Network,
# 'Overlay': v30_Overlay,
# 'RIB': v30_RIB,
# 'Session': v30_Session,
# 'SFlow': v30_SFlow,
# 'SLB': v30_SLB,
# 'System': v30_System,
# 'File': v30_File,
# 'Vlan': v30_Vlan,
# 'VRRPA': v30_VRRPA,
# 'DeviceContext': v30_DeviceContext,
# 'Flexpool': Flexpool,
# 'Delete': Delete,
# },
# }
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(
# self,
# host, # ip address or name of the A10 device
# version, # either 21 or 30
# username, # username to use for authenticating to the A10 device
# password, # password to use for authenticating to the A10 device
# max_retries=3, # number of times to retry a connection before giving up
# port=None, # TCP port to use for connecting to the A10 device
# protocol="https", # transport protocol - http or https, encryption recommended
# timeout=5 # seconds to wait for return data before giving up
# ):
# def _just_digits(self, s):
# def dns(self):
# def ha(self):
# def interface(self):
# def system(self):
# def slb(self):
# def network(self):
# def nat(self):
# def file(self):
# def sflow(self):
# def license_manager(self):
# def glm(self):
# def overlay(self):
# def vlan(self):
# def route(self):
# def vrrpa(self):
# def device_context(self):
# def delete(self):
# def wait_for_connect(self, max_timeout=60):
. Output only the next line. | self.client = client.Client(HOSTNAME, '30', 'fake_username', 'fake_password') |
Given snippet: <|code_start|># Copyright (C) 2021, A10 Networks Inc. All rights reserved.
# 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 Flexpool(base.BaseV30):
url_prefix = '/glm'
@property
def proxy_server(self):
return proxy.ProxyServer(self.client)
@property
def create_license_request(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from acos_client.v30 import base
from acos_client.v30.glm import license
from acos_client.v30.glm import proxy
and context:
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
#
# Path: acos_client/v30/glm/license.py
# class LicenseRequest(base.BaseV30):
# class MultiLicenseException(Exception):
# class NewLicense(base.BaseV30):
# def _set(self, create_license_request):
# def create(self, create_license_request=None, **kwargs):
# def update(self, create_license_request=None, **kwargs):
# def put(self, create_license_request=None, **kwargs):
# def delete(self):
# def __init__(self):
# def create(self, account_name=None, country=None, existing_org=None,
# glm_password=None, last_name=None, name=None, new_email=None,
# new_password=None, new_user=None, org_id=None, phone=None,
# license_type=None, existing_user=None, first_name=None,
# glm_email=None):
#
# Path: acos_client/v30/glm/proxy.py
# class SecretStringUndefinedException(Exception):
# class ProxyServer(base.BaseV30):
# def __init__(self):
# def _set(self, host=None, port=None, username=None,
# password=None, secret_string=None):
# def create(self, host=None, port=None, username=None,
# password=None, secret_string=None, **kwargs):
# def update(self, host=None, port=None, username=None,
# password=None, secret_string=None, **kwargs):
# def put(self, host=None, port=None, username=None,
# password=None, secret_string=None, **kwargs):
# def delete(self):
which might include code, classes, or functions. Output only the next line. | return license.LicenseRequest(self.client) |
Predict the next line after this snippet: <|code_start|># Copyright (C) 2021, A10 Networks Inc. All rights reserved.
# 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 Flexpool(base.BaseV30):
url_prefix = '/glm'
@property
def proxy_server(self):
<|code_end|>
using the current file's imports:
from acos_client.v30 import base
from acos_client.v30.glm import license
from acos_client.v30.glm import proxy
and any relevant context from other files:
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
#
# Path: acos_client/v30/glm/license.py
# class LicenseRequest(base.BaseV30):
# class MultiLicenseException(Exception):
# class NewLicense(base.BaseV30):
# def _set(self, create_license_request):
# def create(self, create_license_request=None, **kwargs):
# def update(self, create_license_request=None, **kwargs):
# def put(self, create_license_request=None, **kwargs):
# def delete(self):
# def __init__(self):
# def create(self, account_name=None, country=None, existing_org=None,
# glm_password=None, last_name=None, name=None, new_email=None,
# new_password=None, new_user=None, org_id=None, phone=None,
# license_type=None, existing_user=None, first_name=None,
# glm_email=None):
#
# Path: acos_client/v30/glm/proxy.py
# class SecretStringUndefinedException(Exception):
# class ProxyServer(base.BaseV30):
# def __init__(self):
# def _set(self, host=None, port=None, username=None,
# password=None, secret_string=None):
# def create(self, host=None, port=None, username=None,
# password=None, secret_string=None, **kwargs):
# def update(self, host=None, port=None, username=None,
# password=None, secret_string=None, **kwargs):
# def put(self, host=None, port=None, username=None,
# password=None, secret_string=None, **kwargs):
# def delete(self):
. Output only the next line. | return proxy.ProxyServer(self.client) |
Based on the snippet: <|code_start|># 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
HOSTNAME = 'fake_a10'
BASE_URL = "https://{}:443/axapi/v3".format(HOSTNAME)
AUTH_URL = "{}/auth".format(BASE_URL)
VSERVER_NAME = 'test'
CREATE_URL = '{}/slb/server/'.format(BASE_URL)
OBJECT_URL = '{}/slb/server/{}'.format(BASE_URL, VSERVER_NAME)
class TestServer(unittest.TestCase):
def setUp(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
import unittest2 as unittest
import acos_client.errors as acos_errors
import json
import responses
from acos_client import client
and context (classes, functions, sometimes code) from other files:
# Path: acos_client/client.py
# VERSION_IMPORTS = {
# '21': {
# 'DNS': v21_DNS,
# 'http': v21_http,
# 'HA': v21_HA,
# 'Interface': v21_Interface,
# 'LicenseManager': v21_LicenseManager,
# 'Nat': v21_Nat,
# 'Network': v21_Network,
# 'Session': v21_Session,
# 'SFlow': v21_SFlow,
# 'SLB': v21_SLB,
# 'System': v21_System,
# 'Vlan': None,
# 'VRRPA': v21_VRRPA
# },
# '30': {
# 'DNS': v30_DNS,
# 'http': v30_http,
# 'Interface': v30_Interface,
# 'HA': v30_HA,
# 'LicenseManager': v30_LicenseManager,
# 'Nat': v30_Nat,
# 'Network': v30_Network,
# 'Overlay': v30_Overlay,
# 'RIB': v30_RIB,
# 'Session': v30_Session,
# 'SFlow': v30_SFlow,
# 'SLB': v30_SLB,
# 'System': v30_System,
# 'File': v30_File,
# 'Vlan': v30_Vlan,
# 'VRRPA': v30_VRRPA,
# 'DeviceContext': v30_DeviceContext,
# 'Flexpool': Flexpool,
# 'Delete': Delete,
# },
# }
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(
# self,
# host, # ip address or name of the A10 device
# version, # either 21 or 30
# username, # username to use for authenticating to the A10 device
# password, # password to use for authenticating to the A10 device
# max_retries=3, # number of times to retry a connection before giving up
# port=None, # TCP port to use for connecting to the A10 device
# protocol="https", # transport protocol - http or https, encryption recommended
# timeout=5 # seconds to wait for return data before giving up
# ):
# def _just_digits(self, s):
# def dns(self):
# def ha(self):
# def interface(self):
# def system(self):
# def slb(self):
# def network(self):
# def nat(self):
# def file(self):
# def sflow(self):
# def license_manager(self):
# def glm(self):
# def overlay(self):
# def vlan(self):
# def route(self):
# def vrrpa(self):
# def device_context(self):
# def delete(self):
# def wait_for_connect(self, max_timeout=60):
. Output only the next line. | self.client = client.Client(HOSTNAME, '30', 'fake_username', 'fake_password') |
Predict the next line after this snippet: <|code_start|># Copyright 2014, Jeff Buttars, A10 Networks.
#
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
class ServiceGroup(base.BaseV30):
url_prefix = '/slb/service-group/'
@property
def member(self):
<|code_end|>
using the current file's imports:
from acos_client.v30 import base
from acos_client.v30.slb.member import Member
and any relevant context from other files:
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
#
# Path: acos_client/v30/slb/member.py
# class Member(base.BaseV30):
#
# url_base_tmpl = '/slb/service-group/{gname}/member/'
# url_mbr_tmpl = '{name}+{port}/'
#
# STATUS_ENABLE = 0
# STATUS_DISABLE = 1
#
# def get(self, service_group_name, server_name, server_port, **kwargs):
# url = self.url_base_tmpl.format(gname=service_group_name)
# url += self.url_mbr_tmpl.format(
# name=server_name,
# port=server_port
# )
#
# return self._get(url, **kwargs)
#
# def get_oper(self, service_group_name, server_name, server_port, **kwargs):
# url = self.url_base_tmpl.format(gname=service_group_name)
# url += self.url_mbr_tmpl.format(
# name=server_name,
# port=server_port
# )
# return self._get(url + 'oper', **kwargs)
#
# def _set(self,
# service_group_name,
# server_name,
# server_port,
# status=STATUS_ENABLE,
# member_state=True, **kwargs):
# params = {
# "member": self.minimal_dict({
# "name": server_name,
# "port": int(server_port),
# # flip status code, becuase it's a disable flag in v30
# "member-stats-data-disable": status,
# "member-state": member_state and 'enable' or 'disable',
# })
# }
#
# config_defaults = kwargs.get("config_defaults")
#
# if config_defaults:
# for k, v in six.iteritems(config_defaults):
# params['member'][k] = v
#
# return params
#
# def create(self,
# service_group_name,
# server_name,
# server_port,
# status=STATUS_ENABLE,
# member_state=True, **kwargs):
# url = self.url_base_tmpl.format(gname=service_group_name)
# params = self._set(service_group_name,
# server_name, server_port, status, member_state, **kwargs)
# return self._post(url, params, **kwargs)
#
# def update(self,
# service_group_name,
# server_name,
# server_port,
# status=STATUS_ENABLE,
# member_state=True, **kwargs):
# url = self.url_base_tmpl.format(gname=service_group_name)
# url += self.url_mbr_tmpl.format(
# name=server_name,
# port=server_port
# )
# params = self._set(service_group_name,
# server_name, server_port, status, member_state, **kwargs)
# return self._post(url, params, **kwargs)
#
# def replace(self,
# service_group_name,
# server_name,
# server_port,
# status=STATUS_ENABLE,
# member_state=True, **kwargs):
# url = self.url_base_tmpl.format(gname=service_group_name)
# url += self.url_mbr_tmpl.format(name=server_name,
# port=server_port)
# params = self._set(service_group_name,
# server_name, server_port, status, member_state, **kwargs)
# return self._put(url, params, **kwargs)
#
# def delete(self, service_group_name, server_name, server_port):
# url = self.url_base_tmpl.format(gname=service_group_name)
# url += self.url_mbr_tmpl.format(
# name=server_name,
# port=server_port
# )
# self._delete(url)
. Output only the next line. | return Member(self.client) |
Predict the next line after this snippet: <|code_start|> "used to define a new license: existing_org, "
"existing_user, new_user, or name. These cannot "
"be used in conjuction.")
super(MultiLicenseException, self).__init__()
class NewLicense(base.BaseV30):
url_prefix = '/glm/new-license'
def create(self, account_name=None, country=None, existing_org=None,
glm_password=None, last_name=None, name=None, new_email=None,
new_password=None, new_user=None, org_id=None, phone=None,
license_type=None, existing_user=None, first_name=None,
glm_email=None):
params = {
"new-license": {}
}
xor = bool(existing_org) + bool(existing_user) + bool(new_user) + bool(name)
if xor > 1:
raise MultiLicenseException()
if existing_org:
params['new-license'] = self.minimal_dict({
'existing-org': existing_org,
'org-id': org_id
})
elif existing_user:
if not glm_email:
<|code_end|>
using the current file's imports:
from acos_client import errors as acos_errors
from acos_client.v30 import base
and any relevant context from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
. Output only the next line. | raise acos_errors.RequiredAttributeNotSpecified( |
Continue the code snippet: <|code_start|># Copyright (C) 2016, A10 Networks Inc. All rights reserved.
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
class TestDns(unittest.TestCase):
def setUp(self):
self.client = mock.MagicMock()
<|code_end|>
. Use current file imports:
import unittest
import mock
import unittest2 as unittest
from unittest import mock
from acos_client.v30 import dns
and context (classes, functions, or code) from other files:
# Path: acos_client/v30/dns.py
# class DNS(base.BaseV30):
# def _set_dns(self, precedence, addr):
# def _set_suffix(self, suffix):
# def set(self, primary=None, secondary=None, suffix=None):
# def delete(self, primary=None, secondary=None, suffix=None):
. Output only the next line. | self.target = dns.DNS(self.client) |
Continue the code snippet: <|code_start|># 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.
from __future__ import absolute_import
from __future__ import unicode_literals
class BaseV30(object):
def __init__(self, client):
self.client = client
self.http = client.http
self.auth_header = {}
def minimal_dict(self, my_dict, exclude=[]):
return dict((k, v) for k, v in my_dict.items() if v is not None or k in exclude)
def url(self, action):
self.auth_header['Authorization'] = "A10 %s" % self.client.session.id
return ("/axapi/v3" + action)
def _request(self, method, action, params, retry_count=0, max_retries=None,
timeout=None, axapi_args=None, **kwargs):
if retry_count > 24:
<|code_end|>
. Use current file imports:
import ipaddress
import six
import time
from acos_client import errors as ae
and context (classes, functions, or code) from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
. Output only the next line. | raise ae.ACOSUnknownError() |
Predict the next line after this snippet: <|code_start|># Copyright 2014, Doug Wiegley, A10 Networks.
#
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
RESPONSE_CODES = {
33619969: {
'*': {
<|code_end|>
using the current file's imports:
import re
from acos_client import errors as ae
from requests import exceptions as req_ex
and any relevant context from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
. Output only the next line. | '*': ae.InUse |
Using the snippet: <|code_start|># 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.
from __future__ import absolute_import
from __future__ import unicode_literals
class Action(base.BaseV30):
def write_memory(self, partition="all", destination=None, specified_partition=None, **kwargs):
payload = {
"memory": {
"destination": destination,
"partition": partition
}
}
if specified_partition:
del payload["memory"]["destination"]
payload["memory"]["specified-partition"] = specified_partition
try:
try:
self._post("/write/memory/", payload, **kwargs)
<|code_end|>
, determine the next line of code. You have imports:
from acos_client import errors as ae
from acos_client.v30 import base
import acos_client.utils as utils
and context (class names, function names, or code) available:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
. Output only the next line. | except ae.AxapiJsonFormatError: |
Given the following code snippet before the placeholder: <|code_start|>
def _set(self, name, start_ip, end_ip, mask, ip_rr=None, vrid=None, gateway=None):
params = {
"pool": self.minimal_dict(
{
'pool-name': name,
'start-address': start_ip,
'end-address': end_ip,
'netmask': mask,
}
),
}
if ip_rr:
params["pool"]["ip-rr"] = ip_rr
if vrid:
params["pool"]["vrid"] = vrid
if gateway:
params["pool"]['gateway'] = gateway
return params
def get(self, name):
return self._get(self.url_prefix + name)
def try_get(self, name):
try:
return self.get(name)
<|code_end|>
, predict the next line using imports from the current file:
from acos_client import errors as acos_errors
from acos_client.v30 import base
and context including class names, function names, and sometimes code from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
. Output only the next line. | except acos_errors.NotFound: |
Here is a snippet: <|code_start|># Copyright (C) 2021, A10 Networks Inc. All rights reserved.
# 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 SecretStringUndefinedException(Exception):
def __init__(self):
self.message = ("The secret_string argument must "
"be defined if password is specified.")
super(SecretStringUndefinedException, self).__init__(self.message)
<|code_end|>
. Write the next line using the current file imports:
from acos_client.v30 import base
and context from other files:
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
, which may include functions, classes, or code. Output only the next line. | class ProxyServer(base.BaseV30): |
Given the code snippet: <|code_start|># Copyright 2015, Tobit Raff, A10 Networks.
#
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
class SSLKey(base.BaseV30):
url_prefix = '/file/ssl-key/'
def get(self, file):
return self._get(self.url_prefix + file)
def exists(self, file):
try:
self.get(file)
return True
<|code_end|>
, generate the next line using the imports in this file:
import six
from acos_client import errors as acos_errors
from acos_client.v30 import base
and context (functions, classes, or occasionally code) from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
. Output only the next line. | except acos_errors.NotFound: |
Given the code snippet: <|code_start|># Copyright (C) 2021, A10 Networks Inc. All rights reserved.
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
class Delete(base.BaseV30):
@property
<|code_end|>
, generate the next line using the imports in this file:
from acos_client.v30 import base
from acos_client.v30.delete import glm_license
and context (functions, classes, or occasionally code) from other files:
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
#
# Path: acos_client/v30/delete/glm_license.py
# class DeleteGLMLicense(base.BaseV30):
# def post(self, a10_ti=None, ipsec_vpn=None, qosmos=None,
# threatstop=None, webroot=None, webroot_ti=None,
# max_retries=None, timeout=None, **kwargs):
. Output only the next line. | def glm_license(self): |
Here is a snippet: <|code_start|># 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
HOSTNAME = 'fake_a10'
BASE_URL = 'https://{}:443/axapi/v3'.format(HOSTNAME)
AUTH_URL = '{}/auth'.format(BASE_URL)
VSERVER_NAME = 'test'
CREATE_URL = '{}/slb/virtual-server/{}/port/'.format(BASE_URL, VSERVER_NAME)
OBJECT_URL = '{}/slb/virtual-server/{}/port/80+http'.format(BASE_URL, VSERVER_NAME)
OBJECT_TCP_URL = '{}/slb/virtual-server/{}/port/80+tcp'.format(BASE_URL, VSERVER_NAME)
ALL_URL = '{}/slb/virtual-server/{}/port/'.format(BASE_URL, VSERVER_NAME)
OK_RESP = {'response': {'status': 'OK'}}
class TestVirtualPort(unittest.TestCase):
def setUp(self):
<|code_end|>
. Write the next line using the current file imports:
import unittest
import mock
import unittest2 as unittest
import acos_client.errors as acos_errors
import json
import responses
from unittest import mock
from acos_client import client
and context from other files:
# Path: acos_client/client.py
# VERSION_IMPORTS = {
# '21': {
# 'DNS': v21_DNS,
# 'http': v21_http,
# 'HA': v21_HA,
# 'Interface': v21_Interface,
# 'LicenseManager': v21_LicenseManager,
# 'Nat': v21_Nat,
# 'Network': v21_Network,
# 'Session': v21_Session,
# 'SFlow': v21_SFlow,
# 'SLB': v21_SLB,
# 'System': v21_System,
# 'Vlan': None,
# 'VRRPA': v21_VRRPA
# },
# '30': {
# 'DNS': v30_DNS,
# 'http': v30_http,
# 'Interface': v30_Interface,
# 'HA': v30_HA,
# 'LicenseManager': v30_LicenseManager,
# 'Nat': v30_Nat,
# 'Network': v30_Network,
# 'Overlay': v30_Overlay,
# 'RIB': v30_RIB,
# 'Session': v30_Session,
# 'SFlow': v30_SFlow,
# 'SLB': v30_SLB,
# 'System': v30_System,
# 'File': v30_File,
# 'Vlan': v30_Vlan,
# 'VRRPA': v30_VRRPA,
# 'DeviceContext': v30_DeviceContext,
# 'Flexpool': Flexpool,
# 'Delete': Delete,
# },
# }
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(
# self,
# host, # ip address or name of the A10 device
# version, # either 21 or 30
# username, # username to use for authenticating to the A10 device
# password, # password to use for authenticating to the A10 device
# max_retries=3, # number of times to retry a connection before giving up
# port=None, # TCP port to use for connecting to the A10 device
# protocol="https", # transport protocol - http or https, encryption recommended
# timeout=5 # seconds to wait for return data before giving up
# ):
# def _just_digits(self, s):
# def dns(self):
# def ha(self):
# def interface(self):
# def system(self):
# def slb(self):
# def network(self):
# def nat(self):
# def file(self):
# def sflow(self):
# def license_manager(self):
# def glm(self):
# def overlay(self):
# def vlan(self):
# def route(self):
# def vrrpa(self):
# def device_context(self):
# def delete(self):
# def wait_for_connect(self, max_timeout=60):
, which may include functions, classes, or code. Output only the next line. | self.client = client.Client(HOSTNAME, '30', 'fake_username', 'fake_password') |
Next line prediction: <|code_start|> commands = []
if use_mgmt_port:
commands += ["license-manager use-mgmt-port"]
for host in llp_hosts:
commands += ["license-manager host %s" % host]
commands += [
"license-manager sn %s" % sn,
"license-manager interval %s" % interval,
"license-manager instance-name %s" % instance_name,
"license-manager bandwidth-base %s" % bandwidth_base,
]
payload = {
"commandlist": commands
}
self._post(url, payload)
def _paygo_connect(self):
url = "/clideploy/"
payload = {
"commandlist": [
"license-manager connect"
]
}
# There is some lag between the setup call above and being able
# to successfully retrieve a license.
for i in six.moves.range(0, 60):
try:
return self._post(url, payload)
<|code_end|>
. Use current file imports:
(import six
import time
from acos_client import errors as acos_errors
from acos_client.v30 import base)
and context including class names, function names, or small code snippets from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
. Output only the next line. | except acos_errors.ACOSException as e: |
Given the code snippet: <|code_start|># Copyright (C) 2016, A10 Networks Inc. All rights reserved.
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
INTERVAL_MONTHLY = 1
INTERVAL_DAILY = 2
INTERVAL_HOURLY = 3
DEFAULT_LICENSE_PORT = 443
<|code_end|>
, generate the next line using the imports in this file:
import six
import time
from acos_client import errors as acos_errors
from acos_client.v30 import base
and context (functions, classes, or occasionally code) from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
. Output only the next line. | class LicenseManager(base.BaseV30): |
Using the snippet: <|code_start|>
def _update(
self,
virtual_server_name,
name,
protocol,
protocol_port,
service_group_name,
s_pers_name=None,
c_pers_name=None,
status=1,
autosnat=None,
ipinip=None,
no_dest_nat=None,
source_nat_pool=None,
ha_conn_mirror=None,
use_rcv_hop=None,
conn_limit=None,
virtual_port_templates=None,
tcp_template=None,
udp_template=None,
template_server_ssl=None,
template_client_ssl=None,
sampling_enable=None,
aflex_scripts=None,
**kwargs
):
vp = self.get(virtual_server_name, name, protocol, protocol_port)
if vp is None:
<|code_end|>
, determine the next line of code. You have imports:
from acos_client import errors as ae
from acos_client.v30 import base
and context (class names, function names, or code) available:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
. Output only the next line. | raise ae.NotFound() |
Here is a snippet: <|code_start|># 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
HOSTNAME = 'fake_a10'
BASE_URL = 'https://{}:443/axapi/v3'.format(HOSTNAME)
AUTH_URL = '{}/auth'.format(BASE_URL)
AFLEX_NAME = 'test1'
CREATE_URL = '{}/file/aflex/'.format(BASE_URL)
OBJECT_URL = '{}/file/aflex/{}'.format(BASE_URL, AFLEX_NAME)
class TestAFlex(unittest.TestCase):
def setUp(self):
<|code_end|>
. Write the next line using the current file imports:
import unittest
import mock
import unittest2 as unittest
import acos_client.errors as acos_errors
import responses
from unittest import mock
from acos_client import client
and context from other files:
# Path: acos_client/client.py
# VERSION_IMPORTS = {
# '21': {
# 'DNS': v21_DNS,
# 'http': v21_http,
# 'HA': v21_HA,
# 'Interface': v21_Interface,
# 'LicenseManager': v21_LicenseManager,
# 'Nat': v21_Nat,
# 'Network': v21_Network,
# 'Session': v21_Session,
# 'SFlow': v21_SFlow,
# 'SLB': v21_SLB,
# 'System': v21_System,
# 'Vlan': None,
# 'VRRPA': v21_VRRPA
# },
# '30': {
# 'DNS': v30_DNS,
# 'http': v30_http,
# 'Interface': v30_Interface,
# 'HA': v30_HA,
# 'LicenseManager': v30_LicenseManager,
# 'Nat': v30_Nat,
# 'Network': v30_Network,
# 'Overlay': v30_Overlay,
# 'RIB': v30_RIB,
# 'Session': v30_Session,
# 'SFlow': v30_SFlow,
# 'SLB': v30_SLB,
# 'System': v30_System,
# 'File': v30_File,
# 'Vlan': v30_Vlan,
# 'VRRPA': v30_VRRPA,
# 'DeviceContext': v30_DeviceContext,
# 'Flexpool': Flexpool,
# 'Delete': Delete,
# },
# }
# LOG = logging.getLogger(__name__)
# class Client(object):
# def __init__(
# self,
# host, # ip address or name of the A10 device
# version, # either 21 or 30
# username, # username to use for authenticating to the A10 device
# password, # password to use for authenticating to the A10 device
# max_retries=3, # number of times to retry a connection before giving up
# port=None, # TCP port to use for connecting to the A10 device
# protocol="https", # transport protocol - http or https, encryption recommended
# timeout=5 # seconds to wait for return data before giving up
# ):
# def _just_digits(self, s):
# def dns(self):
# def ha(self):
# def interface(self):
# def system(self):
# def slb(self):
# def network(self):
# def nat(self):
# def file(self):
# def sflow(self):
# def license_manager(self):
# def glm(self):
# def overlay(self):
# def vlan(self):
# def route(self):
# def vrrpa(self):
# def device_context(self):
# def delete(self):
# def wait_for_connect(self, max_timeout=60):
, which may include functions, classes, or code. Output only the next line. | self.client = client.Client(HOSTNAME, '30', 'fake_username', 'fake_password') |
Continue the code snippet: <|code_start|># Copyright 2015, Tobit Raff, A10 Networks.
#
# 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.
from __future__ import absolute_import
from __future__ import unicode_literals
class SSLCert(base.BaseV30):
url_prefix = '/file/ssl-cert/'
def get(self, file, **kwargs):
return self._get(self.url_prefix + file, **kwargs)
def exists(self, file):
try:
self.get(file)
return True
<|code_end|>
. Use current file imports:
import six
from acos_client import errors as acos_errors
from acos_client.v30 import base
and context (classes, functions, or code) from other files:
# Path: acos_client/errors.py
# class RequiredAttributeNotSpecified(Exception):
# class ACOSException(Exception):
# class ACOSUnsupportedVersion(ACOSException):
# class ACOSUnknownError(ACOSException):
# class AddressSpecifiedIsInUse(ACOSException):
# class AuthenticationFailure(ACOSException):
# class InvalidSessionID(ACOSException):
# class Exists(ACOSException):
# class NotFound(ACOSException):
# class NoSuchServiceGroup(ACOSException):
# class NotImplemented(ACOSException):
# class InUse(ACOSException):
# class InvalidPartitionParameter(ACOSException):
# class MemoryFault(ACOSException):
# class InvalidParameter(ACOSException):
# class OutOfPartitions(ACOSException):
# class PartitionIdExists(ACOSException):
# class HMMissingHttpPassive(ACOSException):
# class AxapiJsonFormatError(ACOSException):
# class ConfigManagerNotReady(ACOSException):
# class DhcpAcquireFailed(ACOSException):
# class InvalidInteger(ACOSException):
# class CertificateParsingFailed(ACOSException):
# class KeyParsingFailed(ACOSException):
# class FeatureNotSupported(ACOSException):
# class ACOSSystemNotReady(ACOSException):
# class ACOSSystemIsBusy(ACOSException):
# class LicenseOptionNotAllowed(ACOSException):
# def __init__(self, url, attribute, requires=[]):
# def __init__(self, code=1, msg=''):
# def __str__(self):
#
# Path: acos_client/v30/base.py
# class BaseV30(object):
# def __init__(self, client):
# def minimal_dict(self, my_dict, exclude=[]):
# def url(self, action):
# def _request(self, method, action, params, retry_count=0, max_retries=None,
# timeout=None, axapi_args=None, **kwargs):
# def _get(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _post(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _put(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _delete(self, action, params={}, max_retries=None, timeout=None, axapi_args=None, **kwargs):
# def _is_ipv6(self, ip_address):
. Output only the next line. | except acos_errors.NotFound: |
Continue the code snippet: <|code_start|># 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.
from __future__ import absolute_import
from __future__ import unicode_literals
try:
except ImportError:
class TestPort(unittest.TestCase):
def setUp(self):
self.client = mock.MagicMock()
<|code_end|>
. Use current file imports:
import unittest
import mock
import unittest2 as unittest
from unittest import mock
from acos_client.v30.slb import port
and context (classes, functions, or code) from other files:
# Path: acos_client/v30/slb/port.py
# class Port(base.BaseV30):
# def create(self, server_name, port, protocol, max_retries=None, timeout=None,
# conn_resume=None, conn_limit=None, stats_data_action="stats-data-enable",
# weight=1, range=0, action="enable", **kwargs):
# def update(self, server_name, port, protocol, max_retries=None, timeout=None,
# conn_resume=None, conn_limit=None, stats_data_action="stats-data-enable",
# weight=1, range=0, action="enable", **kwargs):
# def delete(self, server_name, port, protocol, **kwargs):
# def _set(self, server_name, port, protocol, conn_resume=None, conn_limit=None,
# stats_data_action="stats-data-enable", weight=1, range=0, action="enable"):
. Output only the next line. | self.port = port.Port(self.client) |
Predict the next line for this snippet: <|code_start|>
@click.command(short_help='Creates and opens file with template code.')
@click.argument('code_file',
type=click.Path(writable=True, dir_okay=False),
required=False)
@click.option('--editor',
help="Specify the editor to launch the file with.",
default=config.read('settings.yml', 'editor'))
<|code_end|>
with the help of current file imports:
import click
import os
from ..utils.exceptions import handle_exceptions
from ..utils import config
from ..utils.logging import logger
from ..utils.launch import launch, substitute
from ..utils.load import get_default_code_name
and context from other files:
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/launch.py
# def launch(app_args, url):
# logger.debug(app_args)
# if(app_args is None):
# logger.warn('Preferred application is not set,'
# 'launching %s in default application' % url)
# click.launch(url)
# else:
# args = app_args[:]
# if(not isinstance(app_args, list)):
# args = [app_args]
# if(isinstance(args[0], list) and args[0] != []):
# launch(args[0], '')
# if(len(args) > 1):
# logger.debug("len>1")
# launch(args[1:], url)
# return
# logger.info('launching command with following params')
# logger.info(args)
# if url not in [None, '']:
# args.append(url)
# logger.debug(args)
# subprocess.run(args, check=True)
#
# def substitute(args, keymap):
# logger.debug('in substitute args')
# logger.debug(args)
# logger.debug(keymap)
# if args not in [None, '', []]:
# if(not (isinstance(args, list))):
# logger.debug('executed base')
# final_args = args[:]
# for key in keymap:
# value = keymap[key]
# final_args = final_args.replace("{{%s}}" % key, str(value))
# logger.debug('final_args')
# logger.debug(final_args)
# status = final_args != args
# else:
# status1, temp_arg = substitute(args[0], keymap)
# status2, temp_arg1 = substitute(args[1:], keymap)
# if(temp_arg1 not in [None, '', []]):
# final_args = [temp_arg]
# final_args.extend(temp_arg1)
# else:
# final_args = [temp_arg]
# status = status1 or status2
# logger.debug('ran for')
# logger.debug(args[0])
# logger.debug(args[1:])
# logger.debug("got back")
# logger.debug(temp_arg)
# logger.debug(temp_arg1)
#
# logger.debug(keymap)
# logger.debug("args")
# logger.debug(final_args)
# return (status, final_args)
# else:
# return (False, None)
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
, which may contain function names, class names, or code. Output only the next line. | @handle_exceptions(BaseException) |
Here is a snippet: <|code_start|>
@click.command(short_help='Creates and opens file with template code.')
@click.argument('code_file',
type=click.Path(writable=True, dir_okay=False),
required=False)
@click.option('--editor',
help="Specify the editor to launch the file with.",
<|code_end|>
. Write the next line using the current file imports:
import click
import os
from ..utils.exceptions import handle_exceptions
from ..utils import config
from ..utils.logging import logger
from ..utils.launch import launch, substitute
from ..utils.load import get_default_code_name
and context from other files:
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/launch.py
# def launch(app_args, url):
# logger.debug(app_args)
# if(app_args is None):
# logger.warn('Preferred application is not set,'
# 'launching %s in default application' % url)
# click.launch(url)
# else:
# args = app_args[:]
# if(not isinstance(app_args, list)):
# args = [app_args]
# if(isinstance(args[0], list) and args[0] != []):
# launch(args[0], '')
# if(len(args) > 1):
# logger.debug("len>1")
# launch(args[1:], url)
# return
# logger.info('launching command with following params')
# logger.info(args)
# if url not in [None, '']:
# args.append(url)
# logger.debug(args)
# subprocess.run(args, check=True)
#
# def substitute(args, keymap):
# logger.debug('in substitute args')
# logger.debug(args)
# logger.debug(keymap)
# if args not in [None, '', []]:
# if(not (isinstance(args, list))):
# logger.debug('executed base')
# final_args = args[:]
# for key in keymap:
# value = keymap[key]
# final_args = final_args.replace("{{%s}}" % key, str(value))
# logger.debug('final_args')
# logger.debug(final_args)
# status = final_args != args
# else:
# status1, temp_arg = substitute(args[0], keymap)
# status2, temp_arg1 = substitute(args[1:], keymap)
# if(temp_arg1 not in [None, '', []]):
# final_args = [temp_arg]
# final_args.extend(temp_arg1)
# else:
# final_args = [temp_arg]
# status = status1 or status2
# logger.debug('ran for')
# logger.debug(args[0])
# logger.debug(args[1:])
# logger.debug("got back")
# logger.debug(temp_arg)
# logger.debug(temp_arg1)
#
# logger.debug(keymap)
# logger.debug("args")
# logger.debug(final_args)
# return (status, final_args)
# else:
# return (False, None)
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
, which may include functions, classes, or code. Output only the next line. | default=config.read('settings.yml', 'editor')) |
Given the code snippet: <|code_start|>
TODO [WIP]:
If other code file(s) exist, it should suggests to open the most
recently edited one.
Template for the code is loaded based upon extension.
See 'termicoder config' for editing default templates,
editor, and language preferences.
'''
if code_file is None:
default_name = get_default_code_name()
code_file = click.prompt(
"Please enter a file name", default=default_name,
type=click.Path(writable=True, dir_okay=False))
extension = code_file.split('.')[-1]
template = config.read('lang/%s/template.yml' % extension)
if(template is not None):
try:
code_to_write = template['code']
# allow jinja style template substitution in command
# example {{row_no}} and {{col_no}}
# see settings.yml for info on usage
status, editor = substitute(editor, template)
# useful for sublime's go to line functionality
# see settings.yml for info on usage
status, editor = substitute(editor, {
r"CODE_FILE": code_file
})
<|code_end|>
, generate the next line using the imports in this file:
import click
import os
from ..utils.exceptions import handle_exceptions
from ..utils import config
from ..utils.logging import logger
from ..utils.launch import launch, substitute
from ..utils.load import get_default_code_name
and context (functions, classes, or occasionally code) from other files:
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/launch.py
# def launch(app_args, url):
# logger.debug(app_args)
# if(app_args is None):
# logger.warn('Preferred application is not set,'
# 'launching %s in default application' % url)
# click.launch(url)
# else:
# args = app_args[:]
# if(not isinstance(app_args, list)):
# args = [app_args]
# if(isinstance(args[0], list) and args[0] != []):
# launch(args[0], '')
# if(len(args) > 1):
# logger.debug("len>1")
# launch(args[1:], url)
# return
# logger.info('launching command with following params')
# logger.info(args)
# if url not in [None, '']:
# args.append(url)
# logger.debug(args)
# subprocess.run(args, check=True)
#
# def substitute(args, keymap):
# logger.debug('in substitute args')
# logger.debug(args)
# logger.debug(keymap)
# if args not in [None, '', []]:
# if(not (isinstance(args, list))):
# logger.debug('executed base')
# final_args = args[:]
# for key in keymap:
# value = keymap[key]
# final_args = final_args.replace("{{%s}}" % key, str(value))
# logger.debug('final_args')
# logger.debug(final_args)
# status = final_args != args
# else:
# status1, temp_arg = substitute(args[0], keymap)
# status2, temp_arg1 = substitute(args[1:], keymap)
# if(temp_arg1 not in [None, '', []]):
# final_args = [temp_arg]
# final_args.extend(temp_arg1)
# else:
# final_args = [temp_arg]
# status = status1 or status2
# logger.debug('ran for')
# logger.debug(args[0])
# logger.debug(args[1:])
# logger.debug("got back")
# logger.debug(temp_arg)
# logger.debug(temp_arg1)
#
# logger.debug(keymap)
# logger.debug("args")
# logger.debug(final_args)
# return (status, final_args)
# else:
# return (False, None)
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
. Output only the next line. | logger.debug(code_to_write) |
Predict the next line for this snippet: <|code_start|> code_file = click.prompt(
"Please enter a file name", default=default_name,
type=click.Path(writable=True, dir_okay=False))
extension = code_file.split('.')[-1]
template = config.read('lang/%s/template.yml' % extension)
if(template is not None):
try:
code_to_write = template['code']
# allow jinja style template substitution in command
# example {{row_no}} and {{col_no}}
# see settings.yml for info on usage
status, editor = substitute(editor, template)
# useful for sublime's go to line functionality
# see settings.yml for info on usage
status, editor = substitute(editor, {
r"CODE_FILE": code_file
})
logger.debug(code_to_write)
except (AttributeError, KeyError):
logger.error("Probelm with template file")
else:
logger.warn("You don't have templates setup for extension %s."
"Launching empty file " % extension)
if(not os.path.exists(code_file)):
code = click.open_file(code_file, 'w')
if(template is not None):
code.write(code_to_write)
if status:
code_file = ''
<|code_end|>
with the help of current file imports:
import click
import os
from ..utils.exceptions import handle_exceptions
from ..utils import config
from ..utils.logging import logger
from ..utils.launch import launch, substitute
from ..utils.load import get_default_code_name
and context from other files:
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/launch.py
# def launch(app_args, url):
# logger.debug(app_args)
# if(app_args is None):
# logger.warn('Preferred application is not set,'
# 'launching %s in default application' % url)
# click.launch(url)
# else:
# args = app_args[:]
# if(not isinstance(app_args, list)):
# args = [app_args]
# if(isinstance(args[0], list) and args[0] != []):
# launch(args[0], '')
# if(len(args) > 1):
# logger.debug("len>1")
# launch(args[1:], url)
# return
# logger.info('launching command with following params')
# logger.info(args)
# if url not in [None, '']:
# args.append(url)
# logger.debug(args)
# subprocess.run(args, check=True)
#
# def substitute(args, keymap):
# logger.debug('in substitute args')
# logger.debug(args)
# logger.debug(keymap)
# if args not in [None, '', []]:
# if(not (isinstance(args, list))):
# logger.debug('executed base')
# final_args = args[:]
# for key in keymap:
# value = keymap[key]
# final_args = final_args.replace("{{%s}}" % key, str(value))
# logger.debug('final_args')
# logger.debug(final_args)
# status = final_args != args
# else:
# status1, temp_arg = substitute(args[0], keymap)
# status2, temp_arg1 = substitute(args[1:], keymap)
# if(temp_arg1 not in [None, '', []]):
# final_args = [temp_arg]
# final_args.extend(temp_arg1)
# else:
# final_args = [temp_arg]
# status = status1 or status2
# logger.debug('ran for')
# logger.debug(args[0])
# logger.debug(args[1:])
# logger.debug("got back")
# logger.debug(temp_arg)
# logger.debug(temp_arg1)
#
# logger.debug(keymap)
# logger.debug("args")
# logger.debug(final_args)
# return (status, final_args)
# else:
# return (False, None)
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
, which may contain function names, class names, or code. Output only the next line. | launch(editor, code_file) |
Predict the next line for this snippet: <|code_start|> If CODE_FILE is not passed, a default name of file is suggested
based on current directory, language preferences and existing
files in directory.
Default CODE_FILE is <PROBLEM_NAME>.<DEFAULT_EXTENSION> if user is
in a problem folder and no other supported code file exists.
TODO [WIP]:
If other code file(s) exist, it should suggests to open the most
recently edited one.
Template for the code is loaded based upon extension.
See 'termicoder config' for editing default templates,
editor, and language preferences.
'''
if code_file is None:
default_name = get_default_code_name()
code_file = click.prompt(
"Please enter a file name", default=default_name,
type=click.Path(writable=True, dir_okay=False))
extension = code_file.split('.')[-1]
template = config.read('lang/%s/template.yml' % extension)
if(template is not None):
try:
code_to_write = template['code']
# allow jinja style template substitution in command
# example {{row_no}} and {{col_no}}
# see settings.yml for info on usage
<|code_end|>
with the help of current file imports:
import click
import os
from ..utils.exceptions import handle_exceptions
from ..utils import config
from ..utils.logging import logger
from ..utils.launch import launch, substitute
from ..utils.load import get_default_code_name
and context from other files:
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/launch.py
# def launch(app_args, url):
# logger.debug(app_args)
# if(app_args is None):
# logger.warn('Preferred application is not set,'
# 'launching %s in default application' % url)
# click.launch(url)
# else:
# args = app_args[:]
# if(not isinstance(app_args, list)):
# args = [app_args]
# if(isinstance(args[0], list) and args[0] != []):
# launch(args[0], '')
# if(len(args) > 1):
# logger.debug("len>1")
# launch(args[1:], url)
# return
# logger.info('launching command with following params')
# logger.info(args)
# if url not in [None, '']:
# args.append(url)
# logger.debug(args)
# subprocess.run(args, check=True)
#
# def substitute(args, keymap):
# logger.debug('in substitute args')
# logger.debug(args)
# logger.debug(keymap)
# if args not in [None, '', []]:
# if(not (isinstance(args, list))):
# logger.debug('executed base')
# final_args = args[:]
# for key in keymap:
# value = keymap[key]
# final_args = final_args.replace("{{%s}}" % key, str(value))
# logger.debug('final_args')
# logger.debug(final_args)
# status = final_args != args
# else:
# status1, temp_arg = substitute(args[0], keymap)
# status2, temp_arg1 = substitute(args[1:], keymap)
# if(temp_arg1 not in [None, '', []]):
# final_args = [temp_arg]
# final_args.extend(temp_arg1)
# else:
# final_args = [temp_arg]
# status = status1 or status2
# logger.debug('ran for')
# logger.debug(args[0])
# logger.debug(args[1:])
# logger.debug("got back")
# logger.debug(temp_arg)
# logger.debug(temp_arg1)
#
# logger.debug(keymap)
# logger.debug("args")
# logger.debug(final_args)
# return (status, final_args)
# else:
# return (False, None)
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
, which may contain function names, class names, or code. Output only the next line. | status, editor = substitute(editor, template) |
Based on the snippet: <|code_start|> type=click.Path(writable=True, dir_okay=False),
required=False)
@click.option('--editor',
help="Specify the editor to launch the file with.",
default=config.read('settings.yml', 'editor'))
@handle_exceptions(BaseException)
def main(code_file, editor):
'''
Creates and opens CODE_FILE with template code.
If CODE_FILE already exists, 'code' just opens it in the default/
supplied editor without any change.
If CODE_FILE is not passed, a default name of file is suggested
based on current directory, language preferences and existing
files in directory.
Default CODE_FILE is <PROBLEM_NAME>.<DEFAULT_EXTENSION> if user is
in a problem folder and no other supported code file exists.
TODO [WIP]:
If other code file(s) exist, it should suggests to open the most
recently edited one.
Template for the code is loaded based upon extension.
See 'termicoder config' for editing default templates,
editor, and language preferences.
'''
if code_file is None:
<|code_end|>
, predict the immediate next line with the help of imports:
import click
import os
from ..utils.exceptions import handle_exceptions
from ..utils import config
from ..utils.logging import logger
from ..utils.launch import launch, substitute
from ..utils.load import get_default_code_name
and context (classes, functions, sometimes code) from other files:
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/launch.py
# def launch(app_args, url):
# logger.debug(app_args)
# if(app_args is None):
# logger.warn('Preferred application is not set,'
# 'launching %s in default application' % url)
# click.launch(url)
# else:
# args = app_args[:]
# if(not isinstance(app_args, list)):
# args = [app_args]
# if(isinstance(args[0], list) and args[0] != []):
# launch(args[0], '')
# if(len(args) > 1):
# logger.debug("len>1")
# launch(args[1:], url)
# return
# logger.info('launching command with following params')
# logger.info(args)
# if url not in [None, '']:
# args.append(url)
# logger.debug(args)
# subprocess.run(args, check=True)
#
# def substitute(args, keymap):
# logger.debug('in substitute args')
# logger.debug(args)
# logger.debug(keymap)
# if args not in [None, '', []]:
# if(not (isinstance(args, list))):
# logger.debug('executed base')
# final_args = args[:]
# for key in keymap:
# value = keymap[key]
# final_args = final_args.replace("{{%s}}" % key, str(value))
# logger.debug('final_args')
# logger.debug(final_args)
# status = final_args != args
# else:
# status1, temp_arg = substitute(args[0], keymap)
# status2, temp_arg1 = substitute(args[1:], keymap)
# if(temp_arg1 not in [None, '', []]):
# final_args = [temp_arg]
# final_args.extend(temp_arg1)
# else:
# final_args = [temp_arg]
# status = status1 or status2
# logger.debug('ran for')
# logger.debug(args[0])
# logger.debug(args[1:])
# logger.debug("got back")
# logger.debug(temp_arg)
# logger.debug(temp_arg1)
#
# logger.debug(keymap)
# logger.debug("args")
# logger.debug(final_args)
# return (status, final_args)
# else:
# return (False, None)
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
. Output only the next line. | default_name = get_default_code_name() |
Here is a snippet: <|code_start|>
@click.command()
def main():
"""
Remove the configuration directory.
"""
if(check_config_path()):
<|code_end|>
. Write the next line using the current file imports:
import click
import shutil
from ...utils.config import get_config_path, check_config_path
from ...utils.logging import logger
and context from other files:
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# config_path = click.get_app_dir('termicoder')
# if(ensure_exists is True and not os.path.exists(config_path)):
# logger.error(
# "Termicoder config not initialized\n"
# "Requested operation requires configuration files to proceed\n"
# "Run `termicoder config init` and try executing this command again"
# )
# raise click.Abort("Config not initialized")
# return config_path
#
# def check_config_path():
# config_path = get_config_path()
# return os.path.exists(config_path)
#
# Path: termicoder/utils/logging.py
, which may include functions, classes, or code. Output only the next line. | config_path = get_config_path() |
Using the snippet: <|code_start|>
@click.command()
def main():
"""
Remove the configuration directory.
"""
<|code_end|>
, determine the next line of code. You have imports:
import click
import shutil
from ...utils.config import get_config_path, check_config_path
from ...utils.logging import logger
and context (class names, function names, or code) available:
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# config_path = click.get_app_dir('termicoder')
# if(ensure_exists is True and not os.path.exists(config_path)):
# logger.error(
# "Termicoder config not initialized\n"
# "Requested operation requires configuration files to proceed\n"
# "Run `termicoder config init` and try executing this command again"
# )
# raise click.Abort("Config not initialized")
# return config_path
#
# def check_config_path():
# config_path = get_config_path()
# return os.path.exists(config_path)
#
# Path: termicoder/utils/logging.py
. Output only the next line. | if(check_config_path()): |
Predict the next line for this snippet: <|code_start|>
@click.command()
def main():
"""
Remove the configuration directory.
"""
if(check_config_path()):
config_path = get_config_path()
<|code_end|>
with the help of current file imports:
import click
import shutil
from ...utils.config import get_config_path, check_config_path
from ...utils.logging import logger
and context from other files:
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# config_path = click.get_app_dir('termicoder')
# if(ensure_exists is True and not os.path.exists(config_path)):
# logger.error(
# "Termicoder config not initialized\n"
# "Requested operation requires configuration files to proceed\n"
# "Run `termicoder config init` and try executing this command again"
# )
# raise click.Abort("Config not initialized")
# return config_path
#
# def check_config_path():
# config_path = get_config_path()
# return os.path.exists(config_path)
#
# Path: termicoder/utils/logging.py
, which may contain function names, class names, or code. Output only the next line. | logger.warn("This will completely erase %s" % config_path) |
Using the snippet: <|code_start|> self.status = None
self.submission_count = 0
self.testcases = None
self.judge_name = "codechef"
self.timelimit = float(3.0)
if(data is not None):
self._initialize()
def _initialize(self):
concerned_data = self.data['result']['data']['content']
problem_content = namedtuple(
"problem", concerned_data.keys())(*concerned_data.values())
self.name = problem_content.problemName
self.submissions_count = problem_content.successfulSubmissions
self.code = problem_content.problemCode
self.text = problem_content.body
self.html = self._get_html(problem_content.body)
self.testcases = self._extract_testcases(self.html)
self.timelimit = float(problem_content.maxTimeLimit)
if(self.timelimit == 0):
self.timelimit = 3.0
def _get_html(self, body):
newbody = body.replace('<br>', '\n')
newbody = newbody.replace('<br />', '\n')
self.text = newbody
mdProcessor = markdown.Markdown()
myHtmlFragment = str(mdProcessor.convert(newbody))
myHtmlFragment = myHtmlFragment.replace('<code>', '<pre>')
myHtmlFragment = myHtmlFragment.replace('</code>', '</pre>')
<|code_end|>
, determine the next line of code. You have imports:
from termicoder.models import Problem
from termicoder.utils.logging import logger
from collections import namedtuple
from ..utils.testcases import extract
from tomd import Tomd
import markdown
import os
import mdv
and context (class names, function names, or code) available:
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/judges/codechef/utils/testcases.py
# def extract(html):
# logger.debug("extract is being called")
# soup = BeautifulSoup(html, "html.parser")
# testcases = []
# pre_tag_elements = soup.find_all('pre')
# try:
# io = _extract_io(pre_tag_elements)
# logger.debug(io)
# except BaseException:
# logger.error("Extraction of testcase for the problem failed")
# return []
#
# if(len(pre_tag_elements) >= 1):
# for i in range(len(io[0])):
# inp = io[0][i]
# ans = io[1][i]
# testcases.append(Testcase(inp=inp, ans=ans, code=i))
# logger.debug("inp\n" + inp + "\n\n")
# logger.debug("ans\n" + ans + "\n\n")
# return testcases
# else:
# logger.error("Extraction of testcase for the problem failed")
. Output only the next line. | logger.debug(myHtmlFragment) |
Next line prediction: <|code_start|> self._initialize()
def _initialize(self):
concerned_data = self.data['result']['data']['content']
problem_content = namedtuple(
"problem", concerned_data.keys())(*concerned_data.values())
self.name = problem_content.problemName
self.submissions_count = problem_content.successfulSubmissions
self.code = problem_content.problemCode
self.text = problem_content.body
self.html = self._get_html(problem_content.body)
self.testcases = self._extract_testcases(self.html)
self.timelimit = float(problem_content.maxTimeLimit)
if(self.timelimit == 0):
self.timelimit = 3.0
def _get_html(self, body):
newbody = body.replace('<br>', '\n')
newbody = newbody.replace('<br />', '\n')
self.text = newbody
mdProcessor = markdown.Markdown()
myHtmlFragment = str(mdProcessor.convert(newbody))
myHtmlFragment = myHtmlFragment.replace('<code>', '<pre>')
myHtmlFragment = myHtmlFragment.replace('</code>', '</pre>')
logger.debug(myHtmlFragment)
javascript = open(
os.path.join((os.path.dirname(__file__)), "script.js")).read()
return ("<script>%s</script>" % javascript) + myHtmlFragment
def _extract_testcases(self, html):
<|code_end|>
. Use current file imports:
(from termicoder.models import Problem
from termicoder.utils.logging import logger
from collections import namedtuple
from ..utils.testcases import extract
from tomd import Tomd
import markdown
import os
import mdv)
and context including class names, function names, or small code snippets from other files:
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/judges/codechef/utils/testcases.py
# def extract(html):
# logger.debug("extract is being called")
# soup = BeautifulSoup(html, "html.parser")
# testcases = []
# pre_tag_elements = soup.find_all('pre')
# try:
# io = _extract_io(pre_tag_elements)
# logger.debug(io)
# except BaseException:
# logger.error("Extraction of testcase for the problem failed")
# return []
#
# if(len(pre_tag_elements) >= 1):
# for i in range(len(io[0])):
# inp = io[0][i]
# ans = io[1][i]
# testcases.append(Testcase(inp=inp, ans=ans, code=i))
# logger.debug("inp\n" + inp + "\n\n")
# logger.debug("ans\n" + ans + "\n\n")
# return testcases
# else:
# logger.error("Extraction of testcase for the problem failed")
. Output only the next line. | testcases = extract(html) |
Predict the next line for this snippet: <|code_start|>
@click.command(short_help='Copies code from file to clipboard.')
@click.argument('code_file',
type=click.Path(exists=True, dir_okay=False),
required=False)
@handle_exceptions(BaseException)
def main(code_file):
'''
Copies code from CODE_FILE to the clipboard.
If CODE_FILE is not passed, a default file is suggested based
on current directory.
The suggested file is the most recently edited code file
recognized by termicoder.
'''
if(code_file is None):
default_file = get_default_code_name()
if (not os.path.exists(default_file)):
default_file = None
code_file = click.prompt(
"Please enter the file to copy",
default=default_file,
type=click.Path(readable=True, exists=True)
)
pyperclip.copy(open(code_file, 'r').read())
<|code_end|>
with the help of current file imports:
import click
import pyperclip
import os
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
from ..utils.load import get_default_code_name
and context from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
, which may contain function names, class names, or code. Output only the next line. | logger.info("copied %s to clipboard" % code_file) |
Given snippet: <|code_start|>
@click.command(short_help='Copies code from file to clipboard.')
@click.argument('code_file',
type=click.Path(exists=True, dir_okay=False),
required=False)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import pyperclip
import os
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
from ..utils.load import get_default_code_name
and context:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
which might include code, classes, or functions. Output only the next line. | @handle_exceptions(BaseException) |
Predict the next line after this snippet: <|code_start|>
@click.command(short_help='Copies code from file to clipboard.')
@click.argument('code_file',
type=click.Path(exists=True, dir_okay=False),
required=False)
@handle_exceptions(BaseException)
def main(code_file):
'''
Copies code from CODE_FILE to the clipboard.
If CODE_FILE is not passed, a default file is suggested based
on current directory.
The suggested file is the most recently edited code file
recognized by termicoder.
'''
if(code_file is None):
<|code_end|>
using the current file's imports:
import click
import pyperclip
import os
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
from ..utils.load import get_default_code_name
and any relevant context from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
. Output only the next line. | default_file = get_default_code_name() |
Continue the code snippet: <|code_start|>
judge_factory = JudgeFactory()
@click.command()
@click.argument('code_file', type=click.Path(exists=True, dir_okay=False),
required=False)
@handle_exceptions(BaseException)
def main(code_file):
'''
Submit a solution.
You should be in a problem directory to submit
\b
Script will prompt you to login into the judge(if not already).
'''
if '.problem.yml' not in os.listdir():
<|code_end|>
. Use current file imports:
import click
import os
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
from ..models import JudgeFactory
from ..utils import yaml
from ..utils.load import get_default_code_name
and context (classes, functions, or code) from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/models/JudgeFactory.py
# class JudgeFactory:
# def __init__(self):
# self.available_judges = []
# self._judge_classes = {}
# self._load_judges()
#
# def _load_judges(self):
# judges = iter_entry_points('termicoder.judge_plugins')
# for judge in judges:
# try:
# judge_class = judge.load()
# assert(issubclass(judge_class, Judge))
# # Try instantiating judge to check if abstract methods
# # are implemented
# # TODO: see for a better alternative instead of instantiating
# self.available_judges.append(judge.name)
# judge_class()
#
# # decorate login and logout with _write_session_data
# judge_class.login = self._write_session_data(
# judge.name)(judge_class.login)
# judge_class.logout = self._write_session_data(
# judge.name)(judge_class.logout)
# judge_class.refresh_login = self._write_session_data(
# judge.name)(judge_class.refresh_login)
#
# self._judge_classes[judge.name] = judge_class
#
# # TODO log about 'why could not load judge'
# # also pass the exception instead of raising
# except AssertionError as e:
# logger.error("%s is not a subclass of Judge" % judge_class)
# except TypeError as e:
# # Abstract methods are not implemented
# logger.error(
# "%s \ndoes not implement required "
# "abstract methods of class Judge" % judge_class)
# except BaseException as e:
# logger.error(e)
# # think about something using click.abort without
# # printing traceback
# sys.exit(1)
#
# # sorting judges for statefulness
# self.available_judges.sort()
#
# def get_judge(self, judge_name):
# if(judge_name not in self.available_judges):
# raise JudgeNotFoundError
# else:
# # Return an instance of the judge
# # TODO load session data if available
# session_data = config.read('judges/sessions.yml', judge_name)
# return self._judge_classes[judge_name](session_data=session_data)
#
# def _write_session_data(self, judge_name):
# def decorator(function):
# def decorated_function(self_, *args, **kwargs):
# function(self_, *args, **kwargs)
# # TODO save to the appropriate location
# logger.debug("_write_session_data for %s" % judge_name)
# logger.debug(self_.session_data)
# config.write(
# 'judges/sessions.yml', judge_name, self_.session_data)
# return decorated_function
# return decorator
#
# Path: termicoder/utils/yaml.py
# def read(file_path, key=None, safe=False):
# def write(file_path, key, value):
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
. Output only the next line. | logger.error("You should be in a problem directory to submit") |
Given the code snippet: <|code_start|>
judge_factory = JudgeFactory()
@click.command()
@click.argument('code_file', type=click.Path(exists=True, dir_okay=False),
required=False)
<|code_end|>
, generate the next line using the imports in this file:
import click
import os
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
from ..models import JudgeFactory
from ..utils import yaml
from ..utils.load import get_default_code_name
and context (functions, classes, or occasionally code) from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/models/JudgeFactory.py
# class JudgeFactory:
# def __init__(self):
# self.available_judges = []
# self._judge_classes = {}
# self._load_judges()
#
# def _load_judges(self):
# judges = iter_entry_points('termicoder.judge_plugins')
# for judge in judges:
# try:
# judge_class = judge.load()
# assert(issubclass(judge_class, Judge))
# # Try instantiating judge to check if abstract methods
# # are implemented
# # TODO: see for a better alternative instead of instantiating
# self.available_judges.append(judge.name)
# judge_class()
#
# # decorate login and logout with _write_session_data
# judge_class.login = self._write_session_data(
# judge.name)(judge_class.login)
# judge_class.logout = self._write_session_data(
# judge.name)(judge_class.logout)
# judge_class.refresh_login = self._write_session_data(
# judge.name)(judge_class.refresh_login)
#
# self._judge_classes[judge.name] = judge_class
#
# # TODO log about 'why could not load judge'
# # also pass the exception instead of raising
# except AssertionError as e:
# logger.error("%s is not a subclass of Judge" % judge_class)
# except TypeError as e:
# # Abstract methods are not implemented
# logger.error(
# "%s \ndoes not implement required "
# "abstract methods of class Judge" % judge_class)
# except BaseException as e:
# logger.error(e)
# # think about something using click.abort without
# # printing traceback
# sys.exit(1)
#
# # sorting judges for statefulness
# self.available_judges.sort()
#
# def get_judge(self, judge_name):
# if(judge_name not in self.available_judges):
# raise JudgeNotFoundError
# else:
# # Return an instance of the judge
# # TODO load session data if available
# session_data = config.read('judges/sessions.yml', judge_name)
# return self._judge_classes[judge_name](session_data=session_data)
#
# def _write_session_data(self, judge_name):
# def decorator(function):
# def decorated_function(self_, *args, **kwargs):
# function(self_, *args, **kwargs)
# # TODO save to the appropriate location
# logger.debug("_write_session_data for %s" % judge_name)
# logger.debug(self_.session_data)
# config.write(
# 'judges/sessions.yml', judge_name, self_.session_data)
# return decorated_function
# return decorator
#
# Path: termicoder/utils/yaml.py
# def read(file_path, key=None, safe=False):
# def write(file_path, key, value):
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
. Output only the next line. | @handle_exceptions(BaseException) |
Next line prediction: <|code_start|>
@click.command()
@click.argument('code_file', type=click.Path(exists=True, dir_okay=False),
required=False)
@handle_exceptions(BaseException)
def main(code_file):
'''
Submit a solution.
You should be in a problem directory to submit
\b
Script will prompt you to login into the judge(if not already).
'''
if '.problem.yml' not in os.listdir():
logger.error("You should be in a problem directory to submit")
return
if(code_file is None):
default_file = get_default_code_name()
if (not os.path.exists(default_file)):
default_file = None
code_file = click.prompt(
"Please a code file to submit",
default=default_file,
type=click.Path(readable=True, exists=True)
)
code = click.open_file(code_file).read()
extension = code_file.split(".")[-1]
<|code_end|>
. Use current file imports:
(import click
import os
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
from ..models import JudgeFactory
from ..utils import yaml
from ..utils.load import get_default_code_name)
and context including class names, function names, or small code snippets from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/models/JudgeFactory.py
# class JudgeFactory:
# def __init__(self):
# self.available_judges = []
# self._judge_classes = {}
# self._load_judges()
#
# def _load_judges(self):
# judges = iter_entry_points('termicoder.judge_plugins')
# for judge in judges:
# try:
# judge_class = judge.load()
# assert(issubclass(judge_class, Judge))
# # Try instantiating judge to check if abstract methods
# # are implemented
# # TODO: see for a better alternative instead of instantiating
# self.available_judges.append(judge.name)
# judge_class()
#
# # decorate login and logout with _write_session_data
# judge_class.login = self._write_session_data(
# judge.name)(judge_class.login)
# judge_class.logout = self._write_session_data(
# judge.name)(judge_class.logout)
# judge_class.refresh_login = self._write_session_data(
# judge.name)(judge_class.refresh_login)
#
# self._judge_classes[judge.name] = judge_class
#
# # TODO log about 'why could not load judge'
# # also pass the exception instead of raising
# except AssertionError as e:
# logger.error("%s is not a subclass of Judge" % judge_class)
# except TypeError as e:
# # Abstract methods are not implemented
# logger.error(
# "%s \ndoes not implement required "
# "abstract methods of class Judge" % judge_class)
# except BaseException as e:
# logger.error(e)
# # think about something using click.abort without
# # printing traceback
# sys.exit(1)
#
# # sorting judges for statefulness
# self.available_judges.sort()
#
# def get_judge(self, judge_name):
# if(judge_name not in self.available_judges):
# raise JudgeNotFoundError
# else:
# # Return an instance of the judge
# # TODO load session data if available
# session_data = config.read('judges/sessions.yml', judge_name)
# return self._judge_classes[judge_name](session_data=session_data)
#
# def _write_session_data(self, judge_name):
# def decorator(function):
# def decorated_function(self_, *args, **kwargs):
# function(self_, *args, **kwargs)
# # TODO save to the appropriate location
# logger.debug("_write_session_data for %s" % judge_name)
# logger.debug(self_.session_data)
# config.write(
# 'judges/sessions.yml', judge_name, self_.session_data)
# return decorated_function
# return decorator
#
# Path: termicoder/utils/yaml.py
# def read(file_path, key=None, safe=False):
# def write(file_path, key, value):
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
. Output only the next line. | problem = yaml.read('.problem.yml') |
Using the snippet: <|code_start|>
judge_factory = JudgeFactory()
@click.command()
@click.argument('code_file', type=click.Path(exists=True, dir_okay=False),
required=False)
@handle_exceptions(BaseException)
def main(code_file):
'''
Submit a solution.
You should be in a problem directory to submit
\b
Script will prompt you to login into the judge(if not already).
'''
if '.problem.yml' not in os.listdir():
logger.error("You should be in a problem directory to submit")
return
if(code_file is None):
<|code_end|>
, determine the next line of code. You have imports:
import click
import os
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
from ..models import JudgeFactory
from ..utils import yaml
from ..utils.load import get_default_code_name
and context (class names, function names, or code) available:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/models/JudgeFactory.py
# class JudgeFactory:
# def __init__(self):
# self.available_judges = []
# self._judge_classes = {}
# self._load_judges()
#
# def _load_judges(self):
# judges = iter_entry_points('termicoder.judge_plugins')
# for judge in judges:
# try:
# judge_class = judge.load()
# assert(issubclass(judge_class, Judge))
# # Try instantiating judge to check if abstract methods
# # are implemented
# # TODO: see for a better alternative instead of instantiating
# self.available_judges.append(judge.name)
# judge_class()
#
# # decorate login and logout with _write_session_data
# judge_class.login = self._write_session_data(
# judge.name)(judge_class.login)
# judge_class.logout = self._write_session_data(
# judge.name)(judge_class.logout)
# judge_class.refresh_login = self._write_session_data(
# judge.name)(judge_class.refresh_login)
#
# self._judge_classes[judge.name] = judge_class
#
# # TODO log about 'why could not load judge'
# # also pass the exception instead of raising
# except AssertionError as e:
# logger.error("%s is not a subclass of Judge" % judge_class)
# except TypeError as e:
# # Abstract methods are not implemented
# logger.error(
# "%s \ndoes not implement required "
# "abstract methods of class Judge" % judge_class)
# except BaseException as e:
# logger.error(e)
# # think about something using click.abort without
# # printing traceback
# sys.exit(1)
#
# # sorting judges for statefulness
# self.available_judges.sort()
#
# def get_judge(self, judge_name):
# if(judge_name not in self.available_judges):
# raise JudgeNotFoundError
# else:
# # Return an instance of the judge
# # TODO load session data if available
# session_data = config.read('judges/sessions.yml', judge_name)
# return self._judge_classes[judge_name](session_data=session_data)
#
# def _write_session_data(self, judge_name):
# def decorator(function):
# def decorated_function(self_, *args, **kwargs):
# function(self_, *args, **kwargs)
# # TODO save to the appropriate location
# logger.debug("_write_session_data for %s" % judge_name)
# logger.debug(self_.session_data)
# config.write(
# 'judges/sessions.yml', judge_name, self_.session_data)
# return decorated_function
# return decorator
#
# Path: termicoder/utils/yaml.py
# def read(file_path, key=None, safe=False):
# def write(file_path, key, value):
#
# Path: termicoder/utils/load.py
# def get_default_code_name():
# default_name = config.read('settings.yml', 'default_code_file')
# if ".problem.yml" in os.listdir():
# problem = yaml.read('.problem.yml')
# default_name = problem.code + "." + config.read(
# 'settings.yml', 'default_extension')
# return default_name
. Output only the next line. | default_file = get_default_code_name() |
Given the following code snippet before the placeholder: <|code_start|>
judge_factory = JudgeFactory()
OJs = judge_factory.available_judges
if default_judge is None:
try:
default_judge = OJs[0]
except IndexError:
pass
@click.command(short_help="List a particular contest.")
@click.option('-j', '--judge', type=click.Choice(OJs),
# prompt="Please provide a judge("+'|'.join(OJs)+")",
default=default_judge)
@handle_exceptions(BaseException)
def main(judge):
'''
List problems from a particular contest with their status.
depending on judge it may give a list of categories also
such as PRACTICE etc.
'''
<|code_end|>
, predict the next line using imports from the current file:
import click
from ...models import JudgeFactory
from ...utils.constants import default_judge
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
and context including class names, function names, and sometimes code from other files:
# Path: termicoder/models/JudgeFactory.py
# class JudgeFactory:
# def __init__(self):
# self.available_judges = []
# self._judge_classes = {}
# self._load_judges()
#
# def _load_judges(self):
# judges = iter_entry_points('termicoder.judge_plugins')
# for judge in judges:
# try:
# judge_class = judge.load()
# assert(issubclass(judge_class, Judge))
# # Try instantiating judge to check if abstract methods
# # are implemented
# # TODO: see for a better alternative instead of instantiating
# self.available_judges.append(judge.name)
# judge_class()
#
# # decorate login and logout with _write_session_data
# judge_class.login = self._write_session_data(
# judge.name)(judge_class.login)
# judge_class.logout = self._write_session_data(
# judge.name)(judge_class.logout)
# judge_class.refresh_login = self._write_session_data(
# judge.name)(judge_class.refresh_login)
#
# self._judge_classes[judge.name] = judge_class
#
# # TODO log about 'why could not load judge'
# # also pass the exception instead of raising
# except AssertionError as e:
# logger.error("%s is not a subclass of Judge" % judge_class)
# except TypeError as e:
# # Abstract methods are not implemented
# logger.error(
# "%s \ndoes not implement required "
# "abstract methods of class Judge" % judge_class)
# except BaseException as e:
# logger.error(e)
# # think about something using click.abort without
# # printing traceback
# sys.exit(1)
#
# # sorting judges for statefulness
# self.available_judges.sort()
#
# def get_judge(self, judge_name):
# if(judge_name not in self.available_judges):
# raise JudgeNotFoundError
# else:
# # Return an instance of the judge
# # TODO load session data if available
# session_data = config.read('judges/sessions.yml', judge_name)
# return self._judge_classes[judge_name](session_data=session_data)
#
# def _write_session_data(self, judge_name):
# def decorator(function):
# def decorated_function(self_, *args, **kwargs):
# function(self_, *args, **kwargs)
# # TODO save to the appropriate location
# logger.debug("_write_session_data for %s" % judge_name)
# logger.debug(self_.session_data)
# config.write(
# 'judges/sessions.yml', judge_name, self_.session_data)
# return decorated_function
# return decorator
#
# Path: termicoder/utils/constants.py
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
. Output only the next line. | logger.error('Not implemented list contest in this version') |
Continue the code snippet: <|code_start|>
judge_factory = JudgeFactory()
OJs = judge_factory.available_judges
if default_judge is None:
try:
default_judge = OJs[0]
except IndexError:
pass
@click.command(short_help="List a particular contest.")
@click.option('-j', '--judge', type=click.Choice(OJs),
# prompt="Please provide a judge("+'|'.join(OJs)+")",
default=default_judge)
<|code_end|>
. Use current file imports:
import click
from ...models import JudgeFactory
from ...utils.constants import default_judge
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
and context (classes, functions, or code) from other files:
# Path: termicoder/models/JudgeFactory.py
# class JudgeFactory:
# def __init__(self):
# self.available_judges = []
# self._judge_classes = {}
# self._load_judges()
#
# def _load_judges(self):
# judges = iter_entry_points('termicoder.judge_plugins')
# for judge in judges:
# try:
# judge_class = judge.load()
# assert(issubclass(judge_class, Judge))
# # Try instantiating judge to check if abstract methods
# # are implemented
# # TODO: see for a better alternative instead of instantiating
# self.available_judges.append(judge.name)
# judge_class()
#
# # decorate login and logout with _write_session_data
# judge_class.login = self._write_session_data(
# judge.name)(judge_class.login)
# judge_class.logout = self._write_session_data(
# judge.name)(judge_class.logout)
# judge_class.refresh_login = self._write_session_data(
# judge.name)(judge_class.refresh_login)
#
# self._judge_classes[judge.name] = judge_class
#
# # TODO log about 'why could not load judge'
# # also pass the exception instead of raising
# except AssertionError as e:
# logger.error("%s is not a subclass of Judge" % judge_class)
# except TypeError as e:
# # Abstract methods are not implemented
# logger.error(
# "%s \ndoes not implement required "
# "abstract methods of class Judge" % judge_class)
# except BaseException as e:
# logger.error(e)
# # think about something using click.abort without
# # printing traceback
# sys.exit(1)
#
# # sorting judges for statefulness
# self.available_judges.sort()
#
# def get_judge(self, judge_name):
# if(judge_name not in self.available_judges):
# raise JudgeNotFoundError
# else:
# # Return an instance of the judge
# # TODO load session data if available
# session_data = config.read('judges/sessions.yml', judge_name)
# return self._judge_classes[judge_name](session_data=session_data)
#
# def _write_session_data(self, judge_name):
# def decorator(function):
# def decorated_function(self_, *args, **kwargs):
# function(self_, *args, **kwargs)
# # TODO save to the appropriate location
# logger.debug("_write_session_data for %s" % judge_name)
# logger.debug(self_.session_data)
# config.write(
# 'judges/sessions.yml', judge_name, self_.session_data)
# return decorated_function
# return decorator
#
# Path: termicoder/utils/constants.py
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
. Output only the next line. | @handle_exceptions(BaseException) |
Given the following code snippet before the placeholder: <|code_start|>
@click.command()
@handle_exceptions(BaseException)
def main():
'''
Launches custom debug interface.
Here you can use testcase generator,
launch debugger for the particular language
and visualize the output.
NOTE:
This functionality is not implemented in this version.
This option is only included for compatibility purposes.
If you want to contribute to its development visit:
https://github.com/termicoder/termicoder
'''
<|code_end|>
, predict the next line using imports from the current file:
import click
from ..utils.logging import logger
from ..utils.exceptions import handle_exceptions
and context including class names, function names, and sometimes code from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
. Output only the next line. | logger.info( |
Continue the code snippet: <|code_start|>
def transpose_running_oauth(x):
return {
'code': x['code'],
'endDate': datetime.strptime(x['endDate'], '%Y-%m-%d %H:%M:%S'),
'startDate': datetime.strptime(x['endDate'], '%Y-%m-%d %H:%M:%S'),
'name': x['name']
}
def running_contests(self):
path = 'contests'
url = self._make_url(self.api_url, path)
r = self._request_api(url)
data = r['result']['data']['content']
contest_list = map(transpose_running_oauth, data['contestList'])
current_time = datetime.fromtimestamp(data['currentTime'])
def check_current(contest):
contest_time = contest['endDate']
return contest_time >= current_time
running = list(filter(check_current, contest_list))
<|code_end|>
. Use current file imports:
from datetime import datetime
from ....utils.logging import logger
and context (classes, functions, or code) from other files:
# Path: termicoder/utils/logging.py
. Output only the next line. | logger.debug("got running") |
Given the code snippet: <|code_start|>
@click.command()
def main():
"""
Initialize the config directory.
"""
config_path = get_config_path()
<|code_end|>
, generate the next line using the imports in this file:
import click
import os
import termicoder.data.config as config_data
import shutil
from ...utils.logging import logger
from ...utils.config import get_config_path
and context (functions, classes, or occasionally code) from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# config_path = click.get_app_dir('termicoder')
# if(ensure_exists is True and not os.path.exists(config_path)):
# logger.error(
# "Termicoder config not initialized\n"
# "Requested operation requires configuration files to proceed\n"
# "Run `termicoder config init` and try executing this command again"
# )
# raise click.Abort("Config not initialized")
# return config_path
. Output only the next line. | logger.info("Setting up configuration at '{config_dest}'".format( |
Using the snippet: <|code_start|>
@click.command()
def main():
"""
Initialize the config directory.
"""
<|code_end|>
, determine the next line of code. You have imports:
import click
import os
import termicoder.data.config as config_data
import shutil
from ...utils.logging import logger
from ...utils.config import get_config_path
and context (class names, function names, or code) available:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# config_path = click.get_app_dir('termicoder')
# if(ensure_exists is True and not os.path.exists(config_path)):
# logger.error(
# "Termicoder config not initialized\n"
# "Requested operation requires configuration files to proceed\n"
# "Run `termicoder config init` and try executing this command again"
# )
# raise click.Abort("Config not initialized")
# return config_path
. Output only the next line. | config_path = get_config_path() |
Given the code snippet: <|code_start|> directory_path = testcase_dir
inp_path = os.path.join(
directory_path, '%s.in' % testcase.code)
ans_path = os.path.join(
directory_path, '%s.ans' % testcase.code)
logger.debug(inp_path)
logger.debug(ans_path)
os.makedirs(directory_path)
except FileExistsError:
pass
except AssertionError:
logger.debug(type(testcase))
raise
except BaseException:
raise
inp_file = click.open_file(inp_path, 'w')
ans_file = click.open_file(ans_path, 'w')
logger.debug('writing testcase %s for problem' % (testcase.code))
inp_file.write(testcase.inp)
ans_file.write(testcase.ans)
inp_file.close()
ans_file.close()
# judge_name is required for instantiating it back from file
def output_problem(problem, problem_dir):
# TODO output
# .problem(problem_data, problem_name, contest_name, judge_name)
# output testcases
try:
<|code_end|>
, generate the next line using the imports in this file:
from ..models import Problem
from ..models import Contest
from ..models import Testcase
from .logging import logger
from ..utils.yaml import write
from builtins import FileExistsError
import click
import os
and context (functions, classes, or occasionally code) from other files:
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Contest.py
# class Contest(ABC):
# @abstractmethod
# def __init__(self, data=None):
# # If contest_data, problems is passed, it should take priority
# self.code = None
# self.problems = None
# self.judge_name = None
# self.data = data
#
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Testcase.py
# class Testcase(ABC):
# @abstractmethod
# def __init__(self, ans, inp, code):
# self.ans = ans
# self.inp = inp
# self.code = code
#
# # judges can override this if they want
# # this is used to produce diff on termicoder test
# def diff(self, out):
# ans_file_name = self.code + ".ans"
# out_file_name = self.code + ".out"
# ans_list = [x+'\n' for x in self.ans.split('\n')]
# out_list = [x+'\n' for x in out.split('\n')]
# diffobj = icdiff.ConsoleDiff(line_numbers=True, show_all_spaces=True)
#
# if(ans_list == out_list):
# return None
# else:
# return '\n'.join(diffobj.make_table(
# out_list, ans_list, fromdesc=out_file_name,
# todesc=ans_file_name, context=False, numlines=10))
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/yaml.py
# def write(file_path, key, value):
# existing_data = read(file_path, None)
# if existing_data is None:
# existing_data = {}
#
# if key is not None:
# existing_data[key] = value
# else:
# existing_data = value
# data_file = click.open_file(file_path, 'w')
# try:
# logger.debug("writing data to file %s" % file_path)
# logger.debug(existing_data)
# yaml.dump(data=existing_data, stream=data_file, Dumper=Dumper)
# except yaml.YAMLError:
# raise
. Output only the next line. | assert isinstance(problem, Problem) |
Based on the snippet: <|code_start|> # output testcases
try:
assert isinstance(problem, Problem)
directory_path = os.path.join(problem_dir, problem.code)
problem_path = os.path.join(directory_path, '.problem.yml')
logger.debug(problem_path)
os.makedirs(directory_path)
except FileExistsError:
pass
except AssertionError:
logger.debug(type(problem))
raise
except BaseException:
raise
write(problem_path, None, problem)
html_path = os.path.join(directory_path, problem.code + '.html')
html_file = click.open_file(html_path, 'w')
logger.debug('writing html for %s' % problem.code)
html_file.write(problem.html)
html_file.close()
testcase_path = os.path.join(directory_path, 'testcases')
for testcase in problem.testcases:
output_testcase(testcase, testcase_path)
def output_contest(contest, contest_dir):
# TODO output .contest(contest_data, contest_name, judge_name)
# for each problem:
# output problem_data
# output testcases
<|code_end|>
, predict the immediate next line with the help of imports:
from ..models import Problem
from ..models import Contest
from ..models import Testcase
from .logging import logger
from ..utils.yaml import write
from builtins import FileExistsError
import click
import os
and context (classes, functions, sometimes code) from other files:
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Contest.py
# class Contest(ABC):
# @abstractmethod
# def __init__(self, data=None):
# # If contest_data, problems is passed, it should take priority
# self.code = None
# self.problems = None
# self.judge_name = None
# self.data = data
#
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Testcase.py
# class Testcase(ABC):
# @abstractmethod
# def __init__(self, ans, inp, code):
# self.ans = ans
# self.inp = inp
# self.code = code
#
# # judges can override this if they want
# # this is used to produce diff on termicoder test
# def diff(self, out):
# ans_file_name = self.code + ".ans"
# out_file_name = self.code + ".out"
# ans_list = [x+'\n' for x in self.ans.split('\n')]
# out_list = [x+'\n' for x in out.split('\n')]
# diffobj = icdiff.ConsoleDiff(line_numbers=True, show_all_spaces=True)
#
# if(ans_list == out_list):
# return None
# else:
# return '\n'.join(diffobj.make_table(
# out_list, ans_list, fromdesc=out_file_name,
# todesc=ans_file_name, context=False, numlines=10))
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/yaml.py
# def write(file_path, key, value):
# existing_data = read(file_path, None)
# if existing_data is None:
# existing_data = {}
#
# if key is not None:
# existing_data[key] = value
# else:
# existing_data = value
# data_file = click.open_file(file_path, 'w')
# try:
# logger.debug("writing data to file %s" % file_path)
# logger.debug(existing_data)
# yaml.dump(data=existing_data, stream=data_file, Dumper=Dumper)
# except yaml.YAMLError:
# raise
. Output only the next line. | assert isinstance(contest, Contest) |
Using the snippet: <|code_start|>
def output_testcase(testcase, testcase_dir):
try:
assert isinstance(testcase, Testcase)
directory_path = testcase_dir
inp_path = os.path.join(
directory_path, '%s.in' % testcase.code)
ans_path = os.path.join(
directory_path, '%s.ans' % testcase.code)
<|code_end|>
, determine the next line of code. You have imports:
from ..models import Problem
from ..models import Contest
from ..models import Testcase
from .logging import logger
from ..utils.yaml import write
from builtins import FileExistsError
import click
import os
and context (class names, function names, or code) available:
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Contest.py
# class Contest(ABC):
# @abstractmethod
# def __init__(self, data=None):
# # If contest_data, problems is passed, it should take priority
# self.code = None
# self.problems = None
# self.judge_name = None
# self.data = data
#
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Testcase.py
# class Testcase(ABC):
# @abstractmethod
# def __init__(self, ans, inp, code):
# self.ans = ans
# self.inp = inp
# self.code = code
#
# # judges can override this if they want
# # this is used to produce diff on termicoder test
# def diff(self, out):
# ans_file_name = self.code + ".ans"
# out_file_name = self.code + ".out"
# ans_list = [x+'\n' for x in self.ans.split('\n')]
# out_list = [x+'\n' for x in out.split('\n')]
# diffobj = icdiff.ConsoleDiff(line_numbers=True, show_all_spaces=True)
#
# if(ans_list == out_list):
# return None
# else:
# return '\n'.join(diffobj.make_table(
# out_list, ans_list, fromdesc=out_file_name,
# todesc=ans_file_name, context=False, numlines=10))
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/yaml.py
# def write(file_path, key, value):
# existing_data = read(file_path, None)
# if existing_data is None:
# existing_data = {}
#
# if key is not None:
# existing_data[key] = value
# else:
# existing_data = value
# data_file = click.open_file(file_path, 'w')
# try:
# logger.debug("writing data to file %s" % file_path)
# logger.debug(existing_data)
# yaml.dump(data=existing_data, stream=data_file, Dumper=Dumper)
# except yaml.YAMLError:
# raise
. Output only the next line. | logger.debug(inp_path) |
Predict the next line after this snippet: <|code_start|>
def output_testcase(testcase, testcase_dir):
try:
assert isinstance(testcase, Testcase)
directory_path = testcase_dir
inp_path = os.path.join(
directory_path, '%s.in' % testcase.code)
ans_path = os.path.join(
directory_path, '%s.ans' % testcase.code)
logger.debug(inp_path)
logger.debug(ans_path)
os.makedirs(directory_path)
except FileExistsError:
pass
except AssertionError:
logger.debug(type(testcase))
raise
except BaseException:
raise
inp_file = click.open_file(inp_path, 'w')
ans_file = click.open_file(ans_path, 'w')
logger.debug('writing testcase %s for problem' % (testcase.code))
<|code_end|>
using the current file's imports:
from ..models import Problem
from ..models import Contest
from ..models import Testcase
from .logging import logger
from ..utils.yaml import write
from builtins import FileExistsError
import click
import os
and any relevant context from other files:
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Contest.py
# class Contest(ABC):
# @abstractmethod
# def __init__(self, data=None):
# # If contest_data, problems is passed, it should take priority
# self.code = None
# self.problems = None
# self.judge_name = None
# self.data = data
#
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Testcase.py
# class Testcase(ABC):
# @abstractmethod
# def __init__(self, ans, inp, code):
# self.ans = ans
# self.inp = inp
# self.code = code
#
# # judges can override this if they want
# # this is used to produce diff on termicoder test
# def diff(self, out):
# ans_file_name = self.code + ".ans"
# out_file_name = self.code + ".out"
# ans_list = [x+'\n' for x in self.ans.split('\n')]
# out_list = [x+'\n' for x in out.split('\n')]
# diffobj = icdiff.ConsoleDiff(line_numbers=True, show_all_spaces=True)
#
# if(ans_list == out_list):
# return None
# else:
# return '\n'.join(diffobj.make_table(
# out_list, ans_list, fromdesc=out_file_name,
# todesc=ans_file_name, context=False, numlines=10))
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/yaml.py
# def write(file_path, key, value):
# existing_data = read(file_path, None)
# if existing_data is None:
# existing_data = {}
#
# if key is not None:
# existing_data[key] = value
# else:
# existing_data = value
# data_file = click.open_file(file_path, 'w')
# try:
# logger.debug("writing data to file %s" % file_path)
# logger.debug(existing_data)
# yaml.dump(data=existing_data, stream=data_file, Dumper=Dumper)
# except yaml.YAMLError:
# raise
. Output only the next line. | inp_file.write(testcase.inp) |
Given the following code snippet before the placeholder: <|code_start|>
def handle_exceptions(*exceptions):
"""
Used as a decorator.
Takes exceptions and a function,
returns function warpped with try except and debug functionality
"""
# TODO correct the line number
def wrapper(function):
def customized_function(*args, **kwargs):
<|code_end|>
, predict the next line using imports from the current file:
import click
import sys
from .logging import logger
and context including class names, function names, and sometimes code from other files:
# Path: termicoder/utils/logging.py
. Output only the next line. | logger.debug( |
Predict the next line for this snippet: <|code_start|>try:
except ImportError:
def read(file_path, key=None, safe=False):
if(not os.path.exists(file_path)):
return None
data_file = click.open_file(file_path)
value = None
try:
data = yaml.load(data_file, Loader=Loader)
data_file.close()
<|code_end|>
with the help of current file imports:
import click
import os
import yaml
from yaml import CLoader as Loader, CDumper as Dumper
from yaml import Loader, Dumper
from .logging import logger
and context from other files:
# Path: termicoder/utils/logging.py
, which may contain function names, class names, or code. Output only the next line. | logger.debug("read data from file %s" % file_path) |
Using the snippet: <|code_start|>
@click.command(short_help="View contents of folder.")
@click.argument("FOLDER", type=click.Path(
exists=True, file_okay=False, dir_okay=True), default='.')
@handle_exceptions(BaseException)
def main(folder):
'''
Display the termicoder contents in current/passed folder.
Current folder is the default.
\b
If it is a contest folder it displays the list of problems in the browser.
If its a problem folder, displays the problem in a browser.
'''
<|code_end|>
, determine the next line of code. You have imports:
import click
import subprocess
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
from ...utils.load import get_problem_or_contest
from ...models import Problem, Contest
and context (class names, function names, or code) available:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/load.py
# def get_problem_or_contest(folder):
# if ".contest.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.contest.yml'))
# elif ".problem.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.problem.yml'))
#
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Contest.py
# class Contest(ABC):
# @abstractmethod
# def __init__(self, data=None):
# # If contest_data, problems is passed, it should take priority
# self.code = None
# self.problems = None
# self.judge_name = None
# self.data = data
#
# @abstractmethod
# def __str__(self):
# pass
. Output only the next line. | logger.warn('list is not colored in this version') |
Given snippet: <|code_start|>
@click.command(short_help="View contents of folder.")
@click.argument("FOLDER", type=click.Path(
exists=True, file_okay=False, dir_okay=True), default='.')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import subprocess
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
from ...utils.load import get_problem_or_contest
from ...models import Problem, Contest
and context:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/load.py
# def get_problem_or_contest(folder):
# if ".contest.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.contest.yml'))
# elif ".problem.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.problem.yml'))
#
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Contest.py
# class Contest(ABC):
# @abstractmethod
# def __init__(self, data=None):
# # If contest_data, problems is passed, it should take priority
# self.code = None
# self.problems = None
# self.judge_name = None
# self.data = data
#
# @abstractmethod
# def __str__(self):
# pass
which might include code, classes, or functions. Output only the next line. | @handle_exceptions(BaseException) |
Here is a snippet: <|code_start|>
@click.command(short_help="View contents of folder.")
@click.argument("FOLDER", type=click.Path(
exists=True, file_okay=False, dir_okay=True), default='.')
@handle_exceptions(BaseException)
def main(folder):
'''
Display the termicoder contents in current/passed folder.
Current folder is the default.
\b
If it is a contest folder it displays the list of problems in the browser.
If its a problem folder, displays the problem in a browser.
'''
logger.warn('list is not colored in this version')
<|code_end|>
. Write the next line using the current file imports:
import click
import subprocess
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
from ...utils.load import get_problem_or_contest
from ...models import Problem, Contest
and context from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/load.py
# def get_problem_or_contest(folder):
# if ".contest.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.contest.yml'))
# elif ".problem.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.problem.yml'))
#
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Contest.py
# class Contest(ABC):
# @abstractmethod
# def __init__(self, data=None):
# # If contest_data, problems is passed, it should take priority
# self.code = None
# self.problems = None
# self.judge_name = None
# self.data = data
#
# @abstractmethod
# def __str__(self):
# pass
, which may include functions, classes, or code. Output only the next line. | p_or_c = get_problem_or_contest(folder) |
Next line prediction: <|code_start|>
@click.command(short_help="View contents of folder.")
@click.argument("FOLDER", type=click.Path(
exists=True, file_okay=False, dir_okay=True), default='.')
@handle_exceptions(BaseException)
def main(folder):
'''
Display the termicoder contents in current/passed folder.
Current folder is the default.
\b
If it is a contest folder it displays the list of problems in the browser.
If its a problem folder, displays the problem in a browser.
'''
logger.warn('list is not colored in this version')
p_or_c = get_problem_or_contest(folder)
<|code_end|>
. Use current file imports:
(import click
import subprocess
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
from ...utils.load import get_problem_or_contest
from ...models import Problem, Contest)
and context including class names, function names, or small code snippets from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/load.py
# def get_problem_or_contest(folder):
# if ".contest.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.contest.yml'))
# elif ".problem.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.problem.yml'))
#
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Contest.py
# class Contest(ABC):
# @abstractmethod
# def __init__(self, data=None):
# # If contest_data, problems is passed, it should take priority
# self.code = None
# self.problems = None
# self.judge_name = None
# self.data = data
#
# @abstractmethod
# def __str__(self):
# pass
. Output only the next line. | assert(isinstance(p_or_c, Problem) or isinstance(p_or_c, Contest)) |
Predict the next line after this snippet: <|code_start|>
@click.command(short_help="View contents of folder.")
@click.argument("FOLDER", type=click.Path(
exists=True, file_okay=False, dir_okay=True), default='.')
@handle_exceptions(BaseException)
def main(folder):
'''
Display the termicoder contents in current/passed folder.
Current folder is the default.
\b
If it is a contest folder it displays the list of problems in the browser.
If its a problem folder, displays the problem in a browser.
'''
logger.warn('list is not colored in this version')
p_or_c = get_problem_or_contest(folder)
<|code_end|>
using the current file's imports:
import click
import subprocess
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
from ...utils.load import get_problem_or_contest
from ...models import Problem, Contest
and any relevant context from other files:
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/load.py
# def get_problem_or_contest(folder):
# if ".contest.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.contest.yml'))
# elif ".problem.yml" in os.listdir(folder):
# return yaml.read(os.path.join(folder, '.problem.yml'))
#
# Path: termicoder/models/Problem.py
# class Problem(ABC):
# @abstractmethod
# def __init__(self, data):
# self.name = None
# self.status = None
# self.submissions_count = 0
# self.data = data
# self.code = None
# self.html = None
# self.testcases = None
# self.contest_code = None
# self.judge_name = None
# self.timelimit = 3.0 # in seconds
#
# # used by list
# @abstractmethod
# def __str__(self):
# pass
#
# Path: termicoder/models/Contest.py
# class Contest(ABC):
# @abstractmethod
# def __init__(self, data=None):
# # If contest_data, problems is passed, it should take priority
# self.code = None
# self.problems = None
# self.judge_name = None
# self.data = data
#
# @abstractmethod
# def __str__(self):
# pass
. Output only the next line. | assert(isinstance(p_or_c, Problem) or isinstance(p_or_c, Contest)) |
Using the snippet: <|code_start|>
@click.command()
def main():
"""
Edit the configuration.
Launches the config folder for modifying settings.
"""
<|code_end|>
, determine the next line of code. You have imports:
import click
from ...utils.config import get_config_path
and context (class names, function names, or code) available:
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# config_path = click.get_app_dir('termicoder')
# if(ensure_exists is True and not os.path.exists(config_path)):
# logger.error(
# "Termicoder config not initialized\n"
# "Requested operation requires configuration files to proceed\n"
# "Run `termicoder config init` and try executing this command again"
# )
# raise click.Abort("Config not initialized")
# return config_path
. Output only the next line. | config_path = get_config_path(ensure_exists=True) |
Given snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# ABC is the AbstractBaseClass in python
class Testcase(ABC):
@abstractmethod
def __init__(self, ans, inp, code):
self.ans = ans
self.inp = inp
self.code = code
# judges can override this if they want
# this is used to produce diff on termicoder test
def diff(self, out):
ans_file_name = self.code + ".ans"
out_file_name = self.code + ".out"
ans_list = [x+'\n' for x in self.ans.split('\n')]
out_list = [x+'\n' for x in out.split('\n')]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from abc import ABC, abstractmethod
from ..utils import icdiff
and context:
# Path: termicoder/utils/icdiff.py
# class ConsoleDiff(object):
# class MultipleOption(Option):
# def __init__(self, tabsize=8, wrapcolumn=None, linejunk=None,
# charjunk=difflib.IS_CHARACTER_JUNK, cols=80,
# line_numbers=False,
# show_all_spaces=False,
# highlight=False,
# no_bold=False,
# strip_trailing_cr=False):
# def _tab_newline_replace(self, fromlines, tolines):
# def expand_tabs(line):
# def _strip_trailing_cr(self, lines):
# def _all_cr_nl(self, lines):
# def _display_len(self, s):
# def width(c):
# def _split_line(self, data_list, line_num, text):
# def _line_wrapper(self, diffs):
# def _collect_lines(self, diffs):
# def _format_line(self, linenum, text):
# def _add_line_numbers(self, linenum, text):
# def _real_len(self, s):
# def _rpad(self, s, field_width):
# def _pad(self, s, field_width):
# def _lpad(self, s, field_width):
# def make_table(self, fromlines, tolines, fromdesc='', todesc='',
# context=False, numlines=5):
# def _generate_table(self, fromdesc, todesc, diffs):
# def colorize(self, s):
# def background(color):
# def will_see_coloredspace(i, s):
# def simple_colorize(s, chosen_color):
# def replace_all(replacements, string):
# def take_action(self, action, dest, opt, value, values, parser):
# def create_option_parser():
# def set_cols_option(options):
# def ioctl_GWINSZ(fd):
# def validate_has_two_arguments(parser, args):
# def start():
# def codec_print(s, options):
# def diff(options, a, b):
# def print_meta(s):
# def read_file(fname, options):
# def diff_files(options, a, b):
# C_ADD = color_codes["green"]
# C_SUB = color_codes["red"]
# C_CHG = color_codes["yellow"]
# C_ADD = color_codes["green_bold"]
# C_SUB = color_codes["red_bold"]
# C_CHG = color_codes["yellow_bold"]
# C_ADD, C_SUB, C_CHG = (background(C_ADD),
# background(C_SUB),
# background(C_CHG))
# C_NONE = color_codes["none"]
# ACTIONS = Option.ACTIONS + ("extend",)
# STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
# TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
# ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
which might include code, classes, or functions. Output only the next line. | diffobj = icdiff.ConsoleDiff(line_numbers=True, show_all_spaces=True) |
Given snippet: <|code_start|>
@click.command(short_help="View contents of folder.")
@click.argument("dir_name", type=click.Path(
exists=True, file_okay=False, dir_okay=True), default='.')
@click.option("--browser", help='Browser to launch',
default=config.read('settings.yml', 'browser_local'))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
from ...utils.exceptions import handle_exceptions
from ...utils import view
from ...utils import config
and context:
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/view.py
# def folder(directory, browser_local):
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
which might include code, classes, or functions. Output only the next line. | @handle_exceptions(BaseException) |
Next line prediction: <|code_start|>
@click.command(short_help="View contents of folder.")
@click.argument("dir_name", type=click.Path(
exists=True, file_okay=False, dir_okay=True), default='.')
@click.option("--browser", help='Browser to launch',
default=config.read('settings.yml', 'browser_local'))
@handle_exceptions(BaseException)
def main(dir_name, browser):
'''
display the termicoder contents in current/passed folder
\b
if it is a contest folder it displays the list of problems.
if its a problem folder, displays the problem in a browser.
'''
<|code_end|>
. Use current file imports:
(import click
from ...utils.exceptions import handle_exceptions
from ...utils import view
from ...utils import config)
and context including class names, function names, or small code snippets from other files:
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/view.py
# def folder(directory, browser_local):
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
. Output only the next line. | view.folder(dir_name, browser) |
Given the following code snippet before the placeholder: <|code_start|>
@click.command(short_help="View contents of folder.")
@click.argument("dir_name", type=click.Path(
exists=True, file_okay=False, dir_okay=True), default='.')
@click.option("--browser", help='Browser to launch',
<|code_end|>
, predict the next line using imports from the current file:
import click
from ...utils.exceptions import handle_exceptions
from ...utils import view
from ...utils import config
and context including class names, function names, and sometimes code from other files:
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
#
# Path: termicoder/utils/view.py
# def folder(directory, browser_local):
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
. Output only the next line. | default=config.read('settings.yml', 'browser_local')) |
Using the snippet: <|code_start|>
judge_factory = JudgeFactory()
OJs = judge_factory.available_judges
@click.command()
@click.option('-j', '--judge', 'judge_name', type=click.Choice(OJs),
prompt="Please provide a judge ("+'|'.join(OJs)+")",
<|code_end|>
, determine the next line of code. You have imports:
import click
from ...models import JudgeFactory
from ...utils.constants import default_judge
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
and context (class names, function names, or code) available:
# Path: termicoder/models/JudgeFactory.py
# class JudgeFactory:
# def __init__(self):
# self.available_judges = []
# self._judge_classes = {}
# self._load_judges()
#
# def _load_judges(self):
# judges = iter_entry_points('termicoder.judge_plugins')
# for judge in judges:
# try:
# judge_class = judge.load()
# assert(issubclass(judge_class, Judge))
# # Try instantiating judge to check if abstract methods
# # are implemented
# # TODO: see for a better alternative instead of instantiating
# self.available_judges.append(judge.name)
# judge_class()
#
# # decorate login and logout with _write_session_data
# judge_class.login = self._write_session_data(
# judge.name)(judge_class.login)
# judge_class.logout = self._write_session_data(
# judge.name)(judge_class.logout)
# judge_class.refresh_login = self._write_session_data(
# judge.name)(judge_class.refresh_login)
#
# self._judge_classes[judge.name] = judge_class
#
# # TODO log about 'why could not load judge'
# # also pass the exception instead of raising
# except AssertionError as e:
# logger.error("%s is not a subclass of Judge" % judge_class)
# except TypeError as e:
# # Abstract methods are not implemented
# logger.error(
# "%s \ndoes not implement required "
# "abstract methods of class Judge" % judge_class)
# except BaseException as e:
# logger.error(e)
# # think about something using click.abort without
# # printing traceback
# sys.exit(1)
#
# # sorting judges for statefulness
# self.available_judges.sort()
#
# def get_judge(self, judge_name):
# if(judge_name not in self.available_judges):
# raise JudgeNotFoundError
# else:
# # Return an instance of the judge
# # TODO load session data if available
# session_data = config.read('judges/sessions.yml', judge_name)
# return self._judge_classes[judge_name](session_data=session_data)
#
# def _write_session_data(self, judge_name):
# def decorator(function):
# def decorated_function(self_, *args, **kwargs):
# function(self_, *args, **kwargs)
# # TODO save to the appropriate location
# logger.debug("_write_session_data for %s" % judge_name)
# logger.debug(self_.session_data)
# config.write(
# 'judges/sessions.yml', judge_name, self_.session_data)
# return decorated_function
# return decorator
#
# Path: termicoder/utils/constants.py
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
. Output only the next line. | default=default_judge, show_default=True) |
Given the following code snippet before the placeholder: <|code_start|>
judge_factory = JudgeFactory()
OJs = judge_factory.available_judges
@click.command()
@click.option('-j', '--judge', 'judge_name', type=click.Choice(OJs),
prompt="Please provide a judge ("+'|'.join(OJs)+")",
default=default_judge, show_default=True)
<|code_end|>
, predict the next line using imports from the current file:
import click
from ...models import JudgeFactory
from ...utils.constants import default_judge
from ...utils.logging import logger
from ...utils.exceptions import handle_exceptions
and context including class names, function names, and sometimes code from other files:
# Path: termicoder/models/JudgeFactory.py
# class JudgeFactory:
# def __init__(self):
# self.available_judges = []
# self._judge_classes = {}
# self._load_judges()
#
# def _load_judges(self):
# judges = iter_entry_points('termicoder.judge_plugins')
# for judge in judges:
# try:
# judge_class = judge.load()
# assert(issubclass(judge_class, Judge))
# # Try instantiating judge to check if abstract methods
# # are implemented
# # TODO: see for a better alternative instead of instantiating
# self.available_judges.append(judge.name)
# judge_class()
#
# # decorate login and logout with _write_session_data
# judge_class.login = self._write_session_data(
# judge.name)(judge_class.login)
# judge_class.logout = self._write_session_data(
# judge.name)(judge_class.logout)
# judge_class.refresh_login = self._write_session_data(
# judge.name)(judge_class.refresh_login)
#
# self._judge_classes[judge.name] = judge_class
#
# # TODO log about 'why could not load judge'
# # also pass the exception instead of raising
# except AssertionError as e:
# logger.error("%s is not a subclass of Judge" % judge_class)
# except TypeError as e:
# # Abstract methods are not implemented
# logger.error(
# "%s \ndoes not implement required "
# "abstract methods of class Judge" % judge_class)
# except BaseException as e:
# logger.error(e)
# # think about something using click.abort without
# # printing traceback
# sys.exit(1)
#
# # sorting judges for statefulness
# self.available_judges.sort()
#
# def get_judge(self, judge_name):
# if(judge_name not in self.available_judges):
# raise JudgeNotFoundError
# else:
# # Return an instance of the judge
# # TODO load session data if available
# session_data = config.read('judges/sessions.yml', judge_name)
# return self._judge_classes[judge_name](session_data=session_data)
#
# def _write_session_data(self, judge_name):
# def decorator(function):
# def decorated_function(self_, *args, **kwargs):
# function(self_, *args, **kwargs)
# # TODO save to the appropriate location
# logger.debug("_write_session_data for %s" % judge_name)
# logger.debug(self_.session_data)
# config.write(
# 'judges/sessions.yml', judge_name, self_.session_data)
# return decorated_function
# return decorator
#
# Path: termicoder/utils/constants.py
#
# Path: termicoder/utils/logging.py
#
# Path: termicoder/utils/exceptions.py
# def handle_exceptions(*exceptions):
# """
# Used as a decorator.
# Takes exceptions and a function,
# returns function warpped with try except and debug functionality
# """
# # TODO correct the line number
# def wrapper(function):
# def customized_function(*args, **kwargs):
# logger.debug(
# "calling function %s" % sys.modules[function.__module__])
# try:
# function(*args, **kwargs)
# except (exceptions) as e:
# if(logger.level == 10 or isinstance(e, click.Abort)):
# raise
# else:
# logger.error("in module %s:function %s:line %s" % (
# sys.modules[function.__module__].__file__,
# function.__name__, e.__traceback__.tb_lineno))
# logger.error("%s %s" % (e.__class__.__name__, e))
# raise click.Abort
# customized_function.__wrapped__ = True
# customized_function.__doc__ = function.__doc__
# return customized_function
# return wrapper
. Output only the next line. | @handle_exceptions(BaseException) |
Given the code snippet: <|code_start|># for loading judge plugins
# Takes care of instantiating judges and keeping their session_data
# Decorates login logout methods of the judges to write session data
class JudgeFactory:
def __init__(self):
self.available_judges = []
self._judge_classes = {}
self._load_judges()
def _load_judges(self):
judges = iter_entry_points('termicoder.judge_plugins')
for judge in judges:
try:
judge_class = judge.load()
<|code_end|>
, generate the next line using the imports in this file:
from pkg_resources import iter_entry_points
from . import Judge
from ..utils.Errors import JudgeNotFoundError
from ..utils import config
from ..utils.logging import logger
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: termicoder/models/Judge.py
# class Judge(ABC):
# @abstractmethod
# def __init__(self, session_data=None):
# # Init should not have any network requests
# # do them in login, logout, check_running_contest
# self.session_data = session_data
#
# @abstractmethod
# def check_login(self):
# pass
#
# @abstractmethod
# def login(self):
# # login also controls all the messages being displayed to the user
# pass
#
# @abstractmethod
# def refresh_login(self):
# pass
#
# @abstractmethod
# def logout(self):
# # logout also controls all the messages displayed to the user
# pass
#
# @abstractmethod
# def get_running_contests(self):
# # return a string of running contest, do it in form of a table.
# pass
#
# # This method serves both as a problem getter as well as kind of factory
# # for problem
# @abstractmethod
# def get_problem(self, problem_code, contest_code):
# # Method should call the respective Problem.__init__ method to create a
# # problem instance and return it
# pass
#
# @abstractmethod
# def get_contest(self, contest_code):
# # Method should call the respective Problem.__init__ method to create a
# # contest instance with all its problems and return it
# pass
#
# @abstractmethod
# def get_problem_url(self, problem_code, contest_code):
# # Method should return the url used by judge for a particular problem
# pass
#
# @abstractmethod
# def get_contest_url(self, contest_code):
# # Method should return the url used by judge for a particular contest
# pass
#
# @abstractmethod
# def get_contests_list_url(self):
# # Method should return the url used by judge for listing contest
# pass
#
# @abstractmethod
# def submit(self, problem, code_text, extension):
# # problem is an instance of judge's problem class
# # code test is the code to be submitted
# # extension is the extension of the code file to determine
# # language of submission
# pass
#
# @abstractmethod
# def get_testcase(self, inp, ans, code):
# # returns the testcase with inp, ans and code
# # used by termicoder test to output diff
# pass
#
# Path: termicoder/utils/Errors/JudgeNotFoundError.py
# class JudgeNotFoundError(Exception):
# pass
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
. Output only the next line. | assert(issubclass(judge_class, Judge)) |
Based on the snippet: <|code_start|> # decorate login and logout with _write_session_data
judge_class.login = self._write_session_data(
judge.name)(judge_class.login)
judge_class.logout = self._write_session_data(
judge.name)(judge_class.logout)
judge_class.refresh_login = self._write_session_data(
judge.name)(judge_class.refresh_login)
self._judge_classes[judge.name] = judge_class
# TODO log about 'why could not load judge'
# also pass the exception instead of raising
except AssertionError as e:
logger.error("%s is not a subclass of Judge" % judge_class)
except TypeError as e:
# Abstract methods are not implemented
logger.error(
"%s \ndoes not implement required "
"abstract methods of class Judge" % judge_class)
except BaseException as e:
logger.error(e)
# think about something using click.abort without
# printing traceback
sys.exit(1)
# sorting judges for statefulness
self.available_judges.sort()
def get_judge(self, judge_name):
if(judge_name not in self.available_judges):
<|code_end|>
, predict the immediate next line with the help of imports:
from pkg_resources import iter_entry_points
from . import Judge
from ..utils.Errors import JudgeNotFoundError
from ..utils import config
from ..utils.logging import logger
import sys
and context (classes, functions, sometimes code) from other files:
# Path: termicoder/models/Judge.py
# class Judge(ABC):
# @abstractmethod
# def __init__(self, session_data=None):
# # Init should not have any network requests
# # do them in login, logout, check_running_contest
# self.session_data = session_data
#
# @abstractmethod
# def check_login(self):
# pass
#
# @abstractmethod
# def login(self):
# # login also controls all the messages being displayed to the user
# pass
#
# @abstractmethod
# def refresh_login(self):
# pass
#
# @abstractmethod
# def logout(self):
# # logout also controls all the messages displayed to the user
# pass
#
# @abstractmethod
# def get_running_contests(self):
# # return a string of running contest, do it in form of a table.
# pass
#
# # This method serves both as a problem getter as well as kind of factory
# # for problem
# @abstractmethod
# def get_problem(self, problem_code, contest_code):
# # Method should call the respective Problem.__init__ method to create a
# # problem instance and return it
# pass
#
# @abstractmethod
# def get_contest(self, contest_code):
# # Method should call the respective Problem.__init__ method to create a
# # contest instance with all its problems and return it
# pass
#
# @abstractmethod
# def get_problem_url(self, problem_code, contest_code):
# # Method should return the url used by judge for a particular problem
# pass
#
# @abstractmethod
# def get_contest_url(self, contest_code):
# # Method should return the url used by judge for a particular contest
# pass
#
# @abstractmethod
# def get_contests_list_url(self):
# # Method should return the url used by judge for listing contest
# pass
#
# @abstractmethod
# def submit(self, problem, code_text, extension):
# # problem is an instance of judge's problem class
# # code test is the code to be submitted
# # extension is the extension of the code file to determine
# # language of submission
# pass
#
# @abstractmethod
# def get_testcase(self, inp, ans, code):
# # returns the testcase with inp, ans and code
# # used by termicoder test to output diff
# pass
#
# Path: termicoder/utils/Errors/JudgeNotFoundError.py
# class JudgeNotFoundError(Exception):
# pass
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
. Output only the next line. | raise JudgeNotFoundError |
Using the snippet: <|code_start|> judge.name)(judge_class.logout)
judge_class.refresh_login = self._write_session_data(
judge.name)(judge_class.refresh_login)
self._judge_classes[judge.name] = judge_class
# TODO log about 'why could not load judge'
# also pass the exception instead of raising
except AssertionError as e:
logger.error("%s is not a subclass of Judge" % judge_class)
except TypeError as e:
# Abstract methods are not implemented
logger.error(
"%s \ndoes not implement required "
"abstract methods of class Judge" % judge_class)
except BaseException as e:
logger.error(e)
# think about something using click.abort without
# printing traceback
sys.exit(1)
# sorting judges for statefulness
self.available_judges.sort()
def get_judge(self, judge_name):
if(judge_name not in self.available_judges):
raise JudgeNotFoundError
else:
# Return an instance of the judge
# TODO load session data if available
<|code_end|>
, determine the next line of code. You have imports:
from pkg_resources import iter_entry_points
from . import Judge
from ..utils.Errors import JudgeNotFoundError
from ..utils import config
from ..utils.logging import logger
import sys
and context (class names, function names, or code) available:
# Path: termicoder/models/Judge.py
# class Judge(ABC):
# @abstractmethod
# def __init__(self, session_data=None):
# # Init should not have any network requests
# # do them in login, logout, check_running_contest
# self.session_data = session_data
#
# @abstractmethod
# def check_login(self):
# pass
#
# @abstractmethod
# def login(self):
# # login also controls all the messages being displayed to the user
# pass
#
# @abstractmethod
# def refresh_login(self):
# pass
#
# @abstractmethod
# def logout(self):
# # logout also controls all the messages displayed to the user
# pass
#
# @abstractmethod
# def get_running_contests(self):
# # return a string of running contest, do it in form of a table.
# pass
#
# # This method serves both as a problem getter as well as kind of factory
# # for problem
# @abstractmethod
# def get_problem(self, problem_code, contest_code):
# # Method should call the respective Problem.__init__ method to create a
# # problem instance and return it
# pass
#
# @abstractmethod
# def get_contest(self, contest_code):
# # Method should call the respective Problem.__init__ method to create a
# # contest instance with all its problems and return it
# pass
#
# @abstractmethod
# def get_problem_url(self, problem_code, contest_code):
# # Method should return the url used by judge for a particular problem
# pass
#
# @abstractmethod
# def get_contest_url(self, contest_code):
# # Method should return the url used by judge for a particular contest
# pass
#
# @abstractmethod
# def get_contests_list_url(self):
# # Method should return the url used by judge for listing contest
# pass
#
# @abstractmethod
# def submit(self, problem, code_text, extension):
# # problem is an instance of judge's problem class
# # code test is the code to be submitted
# # extension is the extension of the code file to determine
# # language of submission
# pass
#
# @abstractmethod
# def get_testcase(self, inp, ans, code):
# # returns the testcase with inp, ans and code
# # used by termicoder test to output diff
# pass
#
# Path: termicoder/utils/Errors/JudgeNotFoundError.py
# class JudgeNotFoundError(Exception):
# pass
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
. Output only the next line. | session_data = config.read('judges/sessions.yml', judge_name) |
Predict the next line for this snippet: <|code_start|> def __init__(self):
self.available_judges = []
self._judge_classes = {}
self._load_judges()
def _load_judges(self):
judges = iter_entry_points('termicoder.judge_plugins')
for judge in judges:
try:
judge_class = judge.load()
assert(issubclass(judge_class, Judge))
# Try instantiating judge to check if abstract methods
# are implemented
# TODO: see for a better alternative instead of instantiating
self.available_judges.append(judge.name)
judge_class()
# decorate login and logout with _write_session_data
judge_class.login = self._write_session_data(
judge.name)(judge_class.login)
judge_class.logout = self._write_session_data(
judge.name)(judge_class.logout)
judge_class.refresh_login = self._write_session_data(
judge.name)(judge_class.refresh_login)
self._judge_classes[judge.name] = judge_class
# TODO log about 'why could not load judge'
# also pass the exception instead of raising
except AssertionError as e:
<|code_end|>
with the help of current file imports:
from pkg_resources import iter_entry_points
from . import Judge
from ..utils.Errors import JudgeNotFoundError
from ..utils import config
from ..utils.logging import logger
import sys
and context from other files:
# Path: termicoder/models/Judge.py
# class Judge(ABC):
# @abstractmethod
# def __init__(self, session_data=None):
# # Init should not have any network requests
# # do them in login, logout, check_running_contest
# self.session_data = session_data
#
# @abstractmethod
# def check_login(self):
# pass
#
# @abstractmethod
# def login(self):
# # login also controls all the messages being displayed to the user
# pass
#
# @abstractmethod
# def refresh_login(self):
# pass
#
# @abstractmethod
# def logout(self):
# # logout also controls all the messages displayed to the user
# pass
#
# @abstractmethod
# def get_running_contests(self):
# # return a string of running contest, do it in form of a table.
# pass
#
# # This method serves both as a problem getter as well as kind of factory
# # for problem
# @abstractmethod
# def get_problem(self, problem_code, contest_code):
# # Method should call the respective Problem.__init__ method to create a
# # problem instance and return it
# pass
#
# @abstractmethod
# def get_contest(self, contest_code):
# # Method should call the respective Problem.__init__ method to create a
# # contest instance with all its problems and return it
# pass
#
# @abstractmethod
# def get_problem_url(self, problem_code, contest_code):
# # Method should return the url used by judge for a particular problem
# pass
#
# @abstractmethod
# def get_contest_url(self, contest_code):
# # Method should return the url used by judge for a particular contest
# pass
#
# @abstractmethod
# def get_contests_list_url(self):
# # Method should return the url used by judge for listing contest
# pass
#
# @abstractmethod
# def submit(self, problem, code_text, extension):
# # problem is an instance of judge's problem class
# # code test is the code to be submitted
# # extension is the extension of the code file to determine
# # language of submission
# pass
#
# @abstractmethod
# def get_testcase(self, inp, ans, code):
# # returns the testcase with inp, ans and code
# # used by termicoder test to output diff
# pass
#
# Path: termicoder/utils/Errors/JudgeNotFoundError.py
# class JudgeNotFoundError(Exception):
# pass
#
# Path: termicoder/utils/config.py
# def get_config_path(ensure_exists=False):
# def check_config_path():
# def read(rel_path, key=None, safe=False):
# def write(rel_path, key, value):
#
# Path: termicoder/utils/logging.py
, which may contain function names, class names, or code. Output only the next line. | logger.error("%s is not a subclass of Judge" % judge_class) |
Predict the next line after this snippet: <|code_start|>"""PyTypes wrappers."""
c_backend = get_rs_lib()
class MissingTypeHint(TypeError):
pass
@unique
class PyEquivType(Enum):
String = 1
Bool = 2
Int = 3
Double = 4
<|code_end|>
using the current file's imports:
import abc
from collections import deque
from enum import Enum, unique
from collections import abc as abc_coll
from rustypy.type_checkers import prev_to_37
from .ffi_defs import *
from .rswrapper import Float, Double, UnsignedLongLong, Tuple
and any relevant context from other files:
# Path: src/rustypy/rswrapper/rswrapper.py
# FIND_TYPE = re.compile("type\((.*)\)")
# class TupleMeta(type):
# class Tuple(metaclass=TupleMeta):
# class OpaquePtr(object):
# class KrateData(object):
# class RustBinds(object):
# class FnCall(object):
# def __new__(mcs, name, bases, namespace, parameters=None):
# def check_type(arg_t, **checkers):
# def __init__(cls, *args, **kwds):
# def __len__(self):
# def __getitem__(self, parameters):
# def __repr__(self):
# def element_type(self, pos):
# def __subclasscheck__(self, cls):
# def __iter__(self):
# def __next__(self):
# def __new__(cls, *args, **kwds):
# def _get_signature_types(params):
# def inner_types(t):
# def non_empty(param):
# def _get_ptr_to_C_obj(obj, sig=None):
# def _extract_pytypes(ref, sig=False, call_fn=None, depth=0):
# def get_crate_entry(mod):
# def bind_rs_crate_funcs(mod, lib, prefixes=None):
# def __init__(self, prefixes):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __iter__(self):
# def __next__(self):
# def __init__(self, entry_point, compiled_lib, prefixes=None):
# def __init__(self, name, argtypes, lib):
# def __call__(self, *args, **kwargs):
# def real_restype(self):
# def restype(self):
# def restype(self, annotation):
# def argtypes(self):
# def argtypes(self):
# def add_argtype(self, position, hint):
# def get_argtype(self, position):
# def decl_C_args(FFI, params):
. Output only the next line. | Float = 5 |
Predict the next line for this snippet: <|code_start|>"""PyTypes wrappers."""
c_backend = get_rs_lib()
class MissingTypeHint(TypeError):
pass
@unique
class PyEquivType(Enum):
String = 1
Bool = 2
Int = 3
<|code_end|>
with the help of current file imports:
import abc
from collections import deque
from enum import Enum, unique
from collections import abc as abc_coll
from rustypy.type_checkers import prev_to_37
from .ffi_defs import *
from .rswrapper import Float, Double, UnsignedLongLong, Tuple
and context from other files:
# Path: src/rustypy/rswrapper/rswrapper.py
# FIND_TYPE = re.compile("type\((.*)\)")
# class TupleMeta(type):
# class Tuple(metaclass=TupleMeta):
# class OpaquePtr(object):
# class KrateData(object):
# class RustBinds(object):
# class FnCall(object):
# def __new__(mcs, name, bases, namespace, parameters=None):
# def check_type(arg_t, **checkers):
# def __init__(cls, *args, **kwds):
# def __len__(self):
# def __getitem__(self, parameters):
# def __repr__(self):
# def element_type(self, pos):
# def __subclasscheck__(self, cls):
# def __iter__(self):
# def __next__(self):
# def __new__(cls, *args, **kwds):
# def _get_signature_types(params):
# def inner_types(t):
# def non_empty(param):
# def _get_ptr_to_C_obj(obj, sig=None):
# def _extract_pytypes(ref, sig=False, call_fn=None, depth=0):
# def get_crate_entry(mod):
# def bind_rs_crate_funcs(mod, lib, prefixes=None):
# def __init__(self, prefixes):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __iter__(self):
# def __next__(self):
# def __init__(self, entry_point, compiled_lib, prefixes=None):
# def __init__(self, name, argtypes, lib):
# def __call__(self, *args, **kwargs):
# def real_restype(self):
# def restype(self):
# def restype(self, annotation):
# def argtypes(self):
# def argtypes(self):
# def add_argtype(self, position, hint):
# def get_argtype(self, position):
# def decl_C_args(FFI, params):
, which may contain function names, class names, or code. Output only the next line. | Double = 4 |
Here is a snippet: <|code_start|>
def _to_pytuple(signature):
def dec(arg):
return c_backend.pyarg_from_pytuple(PyTuple.from_tuple(arg, signature))
return dec
def _to_pylist(signature):
def dec(arg):
return c_backend.pyarg_from_pylist(PyList.from_list(arg, signature))
return dec
def _to_pydict(signature):
def dec(arg):
d = PyDict.from_dict(arg, signature)
return c_backend.pyarg_from_pydict(d)
return dec
def _extract_value(pyarg, sig, depth=0):
arg_t = PythonObject.type_checking(sig)
if arg_t == PyEquivType.String:
content = c_backend.pyarg_extract_owned_str(pyarg)
pytype = c_backend.pystring_get_str(content).decode("utf-8")
elif arg_t == PyEquivType.Bool:
b = PyBool(c_backend.pyarg_extract_owned_bool(pyarg))
pytype = b.to_bool()
elif arg_t == PyEquivType.Int:
pytype = c_backend.pyarg_extract_owned_int(pyarg)
<|code_end|>
. Write the next line using the current file imports:
import abc
from collections import deque
from enum import Enum, unique
from collections import abc as abc_coll
from rustypy.type_checkers import prev_to_37
from .ffi_defs import *
from .rswrapper import Float, Double, UnsignedLongLong, Tuple
and context from other files:
# Path: src/rustypy/rswrapper/rswrapper.py
# FIND_TYPE = re.compile("type\((.*)\)")
# class TupleMeta(type):
# class Tuple(metaclass=TupleMeta):
# class OpaquePtr(object):
# class KrateData(object):
# class RustBinds(object):
# class FnCall(object):
# def __new__(mcs, name, bases, namespace, parameters=None):
# def check_type(arg_t, **checkers):
# def __init__(cls, *args, **kwds):
# def __len__(self):
# def __getitem__(self, parameters):
# def __repr__(self):
# def element_type(self, pos):
# def __subclasscheck__(self, cls):
# def __iter__(self):
# def __next__(self):
# def __new__(cls, *args, **kwds):
# def _get_signature_types(params):
# def inner_types(t):
# def non_empty(param):
# def _get_ptr_to_C_obj(obj, sig=None):
# def _extract_pytypes(ref, sig=False, call_fn=None, depth=0):
# def get_crate_entry(mod):
# def bind_rs_crate_funcs(mod, lib, prefixes=None):
# def __init__(self, prefixes):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __iter__(self):
# def __next__(self):
# def __init__(self, entry_point, compiled_lib, prefixes=None):
# def __init__(self, name, argtypes, lib):
# def __call__(self, *args, **kwargs):
# def real_restype(self):
# def restype(self):
# def restype(self, annotation):
# def argtypes(self):
# def argtypes(self):
# def add_argtype(self, position, hint):
# def get_argtype(self, position):
# def decl_C_args(FFI, params):
, which may include functions, classes, or code. Output only the next line. | elif arg_t is UnsignedLongLong: |
Using the snippet: <|code_start|>"""PyTypes wrappers."""
c_backend = get_rs_lib()
class MissingTypeHint(TypeError):
pass
@unique
class PyEquivType(Enum):
String = 1
Bool = 2
Int = 3
Double = 4
Float = 5
<|code_end|>
, determine the next line of code. You have imports:
import abc
from collections import deque
from enum import Enum, unique
from collections import abc as abc_coll
from rustypy.type_checkers import prev_to_37
from .ffi_defs import *
from .rswrapper import Float, Double, UnsignedLongLong, Tuple
and context (class names, function names, or code) available:
# Path: src/rustypy/rswrapper/rswrapper.py
# FIND_TYPE = re.compile("type\((.*)\)")
# class TupleMeta(type):
# class Tuple(metaclass=TupleMeta):
# class OpaquePtr(object):
# class KrateData(object):
# class RustBinds(object):
# class FnCall(object):
# def __new__(mcs, name, bases, namespace, parameters=None):
# def check_type(arg_t, **checkers):
# def __init__(cls, *args, **kwds):
# def __len__(self):
# def __getitem__(self, parameters):
# def __repr__(self):
# def element_type(self, pos):
# def __subclasscheck__(self, cls):
# def __iter__(self):
# def __next__(self):
# def __new__(cls, *args, **kwds):
# def _get_signature_types(params):
# def inner_types(t):
# def non_empty(param):
# def _get_ptr_to_C_obj(obj, sig=None):
# def _extract_pytypes(ref, sig=False, call_fn=None, depth=0):
# def get_crate_entry(mod):
# def bind_rs_crate_funcs(mod, lib, prefixes=None):
# def __init__(self, prefixes):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __iter__(self):
# def __next__(self):
# def __init__(self, entry_point, compiled_lib, prefixes=None):
# def __init__(self, name, argtypes, lib):
# def __call__(self, *args, **kwargs):
# def real_restype(self):
# def restype(self):
# def restype(self, annotation):
# def argtypes(self):
# def argtypes(self):
# def add_argtype(self, position, hint):
# def get_argtype(self, position):
# def decl_C_args(FFI, params):
. Output only the next line. | Tuple = 6 |
Based on the snippet: <|code_start|> path, filename = os.path.split(f)
rel_imp = [libname, None]
while True:
path, tail = os.path.split(path)
if path == root or path == os.path.abspath(os.sep):
break
rel_imp.insert(1, tail)
rel_imp = [s + '.' for s in rel_imp[:-1]]
rel_imp.append(filename[:-3])
imp_statement = "".join(rel_imp)
module_objs = m_dict[imp_statement] = []
module = import_module(imp_statement).__dict__
inspect_parameters()
sys.path.pop()
def parse_parameter(self, p, pytypes=False):
@type_checkers
def check_type(arg_t, curr, **checkers):
is_map_like = checkers["map_like"]
is_seq_like = checkers["seq_like"]
is_generic = checkers["generic"]
add = []
param = False
if arg_t is int:
if pytypes:
param = "PyLong"
else:
param = "c_long"
<|code_end|>
, predict the immediate next line with the help of imports:
import inspect
import os
import random
import sys
from collections import abc, namedtuple
from importlib import import_module, invalidate_caches
from io import StringIO
from string import Template, ascii_letters
from textwrap import dedent, indent
from types import FunctionType
from .rswrapper.rswrapper import Double, Float, Tuple
from .scripts import get_version
from .type_checkers import type_checkers
and context (classes, functions, sometimes code) from other files:
# Path: src/rustypy/rswrapper/rswrapper.py
# FIND_TYPE = re.compile("type\((.*)\)")
# class TupleMeta(type):
# class Tuple(metaclass=TupleMeta):
# class OpaquePtr(object):
# class KrateData(object):
# class RustBinds(object):
# class FnCall(object):
# def __new__(mcs, name, bases, namespace, parameters=None):
# def check_type(arg_t, **checkers):
# def __init__(cls, *args, **kwds):
# def __len__(self):
# def __getitem__(self, parameters):
# def __repr__(self):
# def element_type(self, pos):
# def __subclasscheck__(self, cls):
# def __iter__(self):
# def __next__(self):
# def __new__(cls, *args, **kwds):
# def _get_signature_types(params):
# def inner_types(t):
# def non_empty(param):
# def _get_ptr_to_C_obj(obj, sig=None):
# def _extract_pytypes(ref, sig=False, call_fn=None, depth=0):
# def get_crate_entry(mod):
# def bind_rs_crate_funcs(mod, lib, prefixes=None):
# def __init__(self, prefixes):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __iter__(self):
# def __next__(self):
# def __init__(self, entry_point, compiled_lib, prefixes=None):
# def __init__(self, name, argtypes, lib):
# def __call__(self, *args, **kwargs):
# def real_restype(self):
# def restype(self):
# def restype(self, annotation):
# def argtypes(self):
# def argtypes(self):
# def add_argtype(self, position, hint):
# def get_argtype(self, position):
# def decl_C_args(FFI, params):
#
# Path: src/rustypy/scripts.py
# def get_version():
# import pkg_resources
# try:
# rustypy_ver = pkg_resources.require("rustypy")[0].version
# except:
# import os
# import re
# p = os.path.join(os.path.dirname(__file__), '__init__.py')
# rustypy_ver = re.compile(r"^__version__ = '(.*)'")
# with open(p) as f:
# for l in f:
# ver = re.match(rustypy_ver, l)
# if ver:
# rustypy_ver = ver.group(1)
# break
# return rustypy_ver
#
# Path: src/rustypy/type_checkers.py
# def type_checkers(func):
# @functools.wraps(func)
# def checker(*args, **kwargs):
#
# checkers = {
# "map_like": is_map_like,
# "seq_like": is_seq_like,
# "generic": is_generic,
# }
#
# kwargs.update(checkers)
# return func(*args, **kwargs)
# return checker
. Output only the next line. | elif arg_t is float or arg_t is Double or arg_t is Float: |
Given the following code snippet before the placeholder: <|code_start|> path, filename = os.path.split(f)
rel_imp = [libname, None]
while True:
path, tail = os.path.split(path)
if path == root or path == os.path.abspath(os.sep):
break
rel_imp.insert(1, tail)
rel_imp = [s + '.' for s in rel_imp[:-1]]
rel_imp.append(filename[:-3])
imp_statement = "".join(rel_imp)
module_objs = m_dict[imp_statement] = []
module = import_module(imp_statement).__dict__
inspect_parameters()
sys.path.pop()
def parse_parameter(self, p, pytypes=False):
@type_checkers
def check_type(arg_t, curr, **checkers):
is_map_like = checkers["map_like"]
is_seq_like = checkers["seq_like"]
is_generic = checkers["generic"]
add = []
param = False
if arg_t is int:
if pytypes:
param = "PyLong"
else:
param = "c_long"
<|code_end|>
, predict the next line using imports from the current file:
import inspect
import os
import random
import sys
from collections import abc, namedtuple
from importlib import import_module, invalidate_caches
from io import StringIO
from string import Template, ascii_letters
from textwrap import dedent, indent
from types import FunctionType
from .rswrapper.rswrapper import Double, Float, Tuple
from .scripts import get_version
from .type_checkers import type_checkers
and context including class names, function names, and sometimes code from other files:
# Path: src/rustypy/rswrapper/rswrapper.py
# FIND_TYPE = re.compile("type\((.*)\)")
# class TupleMeta(type):
# class Tuple(metaclass=TupleMeta):
# class OpaquePtr(object):
# class KrateData(object):
# class RustBinds(object):
# class FnCall(object):
# def __new__(mcs, name, bases, namespace, parameters=None):
# def check_type(arg_t, **checkers):
# def __init__(cls, *args, **kwds):
# def __len__(self):
# def __getitem__(self, parameters):
# def __repr__(self):
# def element_type(self, pos):
# def __subclasscheck__(self, cls):
# def __iter__(self):
# def __next__(self):
# def __new__(cls, *args, **kwds):
# def _get_signature_types(params):
# def inner_types(t):
# def non_empty(param):
# def _get_ptr_to_C_obj(obj, sig=None):
# def _extract_pytypes(ref, sig=False, call_fn=None, depth=0):
# def get_crate_entry(mod):
# def bind_rs_crate_funcs(mod, lib, prefixes=None):
# def __init__(self, prefixes):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __iter__(self):
# def __next__(self):
# def __init__(self, entry_point, compiled_lib, prefixes=None):
# def __init__(self, name, argtypes, lib):
# def __call__(self, *args, **kwargs):
# def real_restype(self):
# def restype(self):
# def restype(self, annotation):
# def argtypes(self):
# def argtypes(self):
# def add_argtype(self, position, hint):
# def get_argtype(self, position):
# def decl_C_args(FFI, params):
#
# Path: src/rustypy/scripts.py
# def get_version():
# import pkg_resources
# try:
# rustypy_ver = pkg_resources.require("rustypy")[0].version
# except:
# import os
# import re
# p = os.path.join(os.path.dirname(__file__), '__init__.py')
# rustypy_ver = re.compile(r"^__version__ = '(.*)'")
# with open(p) as f:
# for l in f:
# ver = re.match(rustypy_ver, l)
# if ver:
# rustypy_ver = ver.group(1)
# break
# return rustypy_ver
#
# Path: src/rustypy/type_checkers.py
# def type_checkers(func):
# @functools.wraps(func)
# def checker(*args, **kwargs):
#
# checkers = {
# "map_like": is_map_like,
# "seq_like": is_seq_like,
# "generic": is_generic,
# }
#
# kwargs.update(checkers)
# return func(*args, **kwargs)
# return checker
. Output only the next line. | elif arg_t is float or arg_t is Double or arg_t is Float: |
Given snippet: <|code_start|> else:
param = "c_double"
elif arg_t is str:
if pytypes:
param = "PyString"
else:
param = "String"
elif arg_t is bool:
if pytypes:
param = "PyBool"
else:
param = "bool"
elif is_seq_like(arg_t):
if pytypes:
curr.append("PyList")
else:
curr.append("Vec")
for type_ in arg_t.__args__:
check_type(type_, add)
param = True
elif is_map_like(arg_t):
if pytypes:
curr.append("PyDict")
else:
curr.append("HashMap")
for type_ in arg_t.__args__:
check_type(type_, add)
param = True
elif is_generic(arg_t):
param = "PyObject"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import inspect
import os
import random
import sys
from collections import abc, namedtuple
from importlib import import_module, invalidate_caches
from io import StringIO
from string import Template, ascii_letters
from textwrap import dedent, indent
from types import FunctionType
from .rswrapper.rswrapper import Double, Float, Tuple
from .scripts import get_version
from .type_checkers import type_checkers
and context:
# Path: src/rustypy/rswrapper/rswrapper.py
# FIND_TYPE = re.compile("type\((.*)\)")
# class TupleMeta(type):
# class Tuple(metaclass=TupleMeta):
# class OpaquePtr(object):
# class KrateData(object):
# class RustBinds(object):
# class FnCall(object):
# def __new__(mcs, name, bases, namespace, parameters=None):
# def check_type(arg_t, **checkers):
# def __init__(cls, *args, **kwds):
# def __len__(self):
# def __getitem__(self, parameters):
# def __repr__(self):
# def element_type(self, pos):
# def __subclasscheck__(self, cls):
# def __iter__(self):
# def __next__(self):
# def __new__(cls, *args, **kwds):
# def _get_signature_types(params):
# def inner_types(t):
# def non_empty(param):
# def _get_ptr_to_C_obj(obj, sig=None):
# def _extract_pytypes(ref, sig=False, call_fn=None, depth=0):
# def get_crate_entry(mod):
# def bind_rs_crate_funcs(mod, lib, prefixes=None):
# def __init__(self, prefixes):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __iter__(self):
# def __next__(self):
# def __init__(self, entry_point, compiled_lib, prefixes=None):
# def __init__(self, name, argtypes, lib):
# def __call__(self, *args, **kwargs):
# def real_restype(self):
# def restype(self):
# def restype(self, annotation):
# def argtypes(self):
# def argtypes(self):
# def add_argtype(self, position, hint):
# def get_argtype(self, position):
# def decl_C_args(FFI, params):
#
# Path: src/rustypy/scripts.py
# def get_version():
# import pkg_resources
# try:
# rustypy_ver = pkg_resources.require("rustypy")[0].version
# except:
# import os
# import re
# p = os.path.join(os.path.dirname(__file__), '__init__.py')
# rustypy_ver = re.compile(r"^__version__ = '(.*)'")
# with open(p) as f:
# for l in f:
# ver = re.match(rustypy_ver, l)
# if ver:
# rustypy_ver = ver.group(1)
# break
# return rustypy_ver
#
# Path: src/rustypy/type_checkers.py
# def type_checkers(func):
# @functools.wraps(func)
# def checker(*args, **kwargs):
#
# checkers = {
# "map_like": is_map_like,
# "seq_like": is_seq_like,
# "generic": is_generic,
# }
#
# kwargs.update(checkers)
# return func(*args, **kwargs)
# return checker
which might include code, classes, or functions. Output only the next line. | elif issubclass(arg_t, Tuple): |
Next line prediction: <|code_start|>
self.m_dict = m_dict = {}
if inspect.ismodule(self.root):
module = self.root.__dict__
module_objs = m_dict[self.root.__name__] = []
imp_statement = module["__spec__"].name
inspect_parameters()
else:
root, libname = os.path.split(self.root)
sys.path.append(root)
invalidate_caches()
for f in self.pyfiles:
self.__no_funcs = True
# get the absolute import path and dynamically import it
path, filename = os.path.split(f)
rel_imp = [libname, None]
while True:
path, tail = os.path.split(path)
if path == root or path == os.path.abspath(os.sep):
break
rel_imp.insert(1, tail)
rel_imp = [s + '.' for s in rel_imp[:-1]]
rel_imp.append(filename[:-3])
imp_statement = "".join(rel_imp)
module_objs = m_dict[imp_statement] = []
module = import_module(imp_statement).__dict__
inspect_parameters()
sys.path.pop()
def parse_parameter(self, p, pytypes=False):
<|code_end|>
. Use current file imports:
(import inspect
import os
import random
import sys
from collections import abc, namedtuple
from importlib import import_module, invalidate_caches
from io import StringIO
from string import Template, ascii_letters
from textwrap import dedent, indent
from types import FunctionType
from .rswrapper.rswrapper import Double, Float, Tuple
from .scripts import get_version
from .type_checkers import type_checkers)
and context including class names, function names, or small code snippets from other files:
# Path: src/rustypy/rswrapper/rswrapper.py
# FIND_TYPE = re.compile("type\((.*)\)")
# class TupleMeta(type):
# class Tuple(metaclass=TupleMeta):
# class OpaquePtr(object):
# class KrateData(object):
# class RustBinds(object):
# class FnCall(object):
# def __new__(mcs, name, bases, namespace, parameters=None):
# def check_type(arg_t, **checkers):
# def __init__(cls, *args, **kwds):
# def __len__(self):
# def __getitem__(self, parameters):
# def __repr__(self):
# def element_type(self, pos):
# def __subclasscheck__(self, cls):
# def __iter__(self):
# def __next__(self):
# def __new__(cls, *args, **kwds):
# def _get_signature_types(params):
# def inner_types(t):
# def non_empty(param):
# def _get_ptr_to_C_obj(obj, sig=None):
# def _extract_pytypes(ref, sig=False, call_fn=None, depth=0):
# def get_crate_entry(mod):
# def bind_rs_crate_funcs(mod, lib, prefixes=None):
# def __init__(self, prefixes):
# def __enter__(self):
# def __exit__(self, exc_type, exc_value, traceback):
# def __iter__(self):
# def __next__(self):
# def __init__(self, entry_point, compiled_lib, prefixes=None):
# def __init__(self, name, argtypes, lib):
# def __call__(self, *args, **kwargs):
# def real_restype(self):
# def restype(self):
# def restype(self, annotation):
# def argtypes(self):
# def argtypes(self):
# def add_argtype(self, position, hint):
# def get_argtype(self, position):
# def decl_C_args(FFI, params):
#
# Path: src/rustypy/scripts.py
# def get_version():
# import pkg_resources
# try:
# rustypy_ver = pkg_resources.require("rustypy")[0].version
# except:
# import os
# import re
# p = os.path.join(os.path.dirname(__file__), '__init__.py')
# rustypy_ver = re.compile(r"^__version__ = '(.*)'")
# with open(p) as f:
# for l in f:
# ver = re.match(rustypy_ver, l)
# if ver:
# rustypy_ver = ver.group(1)
# break
# return rustypy_ver
#
# Path: src/rustypy/type_checkers.py
# def type_checkers(func):
# @functools.wraps(func)
# def checker(*args, **kwargs):
#
# checkers = {
# "map_like": is_map_like,
# "seq_like": is_seq_like,
# "generic": is_generic,
# }
#
# kwargs.update(checkers)
# return func(*args, **kwargs)
# return checker
. Output only the next line. | @type_checkers |
Given the code snippet: <|code_start|>
HTTP_METHOD_GET = 'GET'
HTTP_METHOD_POST = 'POST'
INDEX_PAGE = 'admin_ui/index'
LOGIN_PAGE = 'admin_ui/login'
DEBUG = True
SMART_SERVER_LOCATION = urlparse.urlparse(settings.SMART_API_SERVER_BASE)
SMART_SERVER_LOCATION = {
'host': SMART_SERVER_LOCATION.hostname,
'scheme': SMART_SERVER_LOCATION.scheme,
'port': SMART_SERVER_LOCATION.port or (
SMART_SERVER_LOCATION.scheme == 'http' and '80' or
SMART_SERVER_LOCATION.scheme == 'https' and '443'
)
}
def admin_login_url(request):
url = "%s?return_url=%s" % (reverse(login), urllib.quote(request.get_full_path()))
return url
def get_api(request=None):
<|code_end|>
, generate the next line using the imports in this file:
from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponseForbidden, HttpRequest
from django.core.exceptions import *
from django.core.urlresolvers import reverse
from django.conf import settings
from smart_ui_server import utils
from smart_ui_server.ui.views import login, logout
from indivo_client_py.lib.client import IndivoClient
import urllib
import urlparse
import json
and context (functions, classes, or occasionally code) from other files:
# Path: indivo_client_py/lib/client.py
# class IndivoClient(APIConnector):
# def create_account(self, user):
# USER_EMAIL = 'user_email'
# ACCOUNT_ID = 'account_id'
# if not (user.has_key(USER_EMAIL) or user.has_key(ACCOUNT_ID)):
# raise APIConnectorError("No user email or account id when posting account")
#
# account_id = None
# if user.has_key(USER_EMAIL):
# account_id = user[USER_EMAIL]
# elif user.has_key(ACCOUNT_ID):
# account_id = user[ACCOUNT_ID]
#
# if account_id:
# primary_secret = user.get('primary_secret_p', 0)
# secondary_secret = user.get('secondary_secret_p', 0)
# password = user.get('user_pass', '')
#
# # There is a difference between app_type chrome without auth and admin
# return self.api.call(self.ds.app_info, {'account_id': account_id,
# 'primary_secret_p': primary_secret,
# 'secondary_secret_p': secondary_secret,
# 'password': password})
# return False
#
# def set_record_id(self, id):
# self.record_id, self.ds.record_id = id, id
#
# def set_app_id(self, id):
# self.app_id, self.ds.app_id = id, id
#
# def create_session(self, user):
# if user.has_key('username') and user.has_key('user_pass'):
# chrome_auth = {'username' : user['username'], 'password' : user['user_pass']}
# chrome_token = self.api.call(self.ds.app_info, chrome_auth)['prd']
# if isinstance(chrome_token, dict):
# self.ds.app_info.update(chrome_token)
# return chrome_token
# return False
#
# def update_token(self, oauth_token={}):
# if oauth_token \
# and isinstance(oauth_token, dict) \
# and oauth_token.has_key(OAUTH_TOKEN) \
# and oauth_token.has_key(OAUTH_TOKEN_SECRET):
# self.ds.app_info[OAUTH_TOKEN] = oauth_token[OAUTH_TOKEN]
# self.ds.app_info[OAUTH_TOKEN_SECRET] = oauth_token[OAUTH_TOKEN_SECRET]
#
# def get_surl_credentials(self):
# """Requires there to be a token and secret set
#
# produces a token and secret dictionary for SURL (signing URLs).
# """
#
# if self.ds.app_info.has_key(OAUTH_TOKEN) and \
# self.ds.app_info.has_key(OAUTH_TOKEN_SECRET):
# token = self.ds.app_info[OAUTH_TOKEN]
# secret = base64.b64encode(hmac.new(self.ds.app_info[OAUTH_TOKEN_SECRET], "SURL-SECRET", hashlib.sha1).digest())
# return {'token' : token, 'secret' : secret}
# return False
. Output only the next line. | api = IndivoClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET, SMART_SERVER_LOCATION) |
Given snippet: <|code_start|>"""
Views for Indivo JS UI
"""
# todo: rm unused
HTTP_METHOD_GET = 'GET'
HTTP_METHOD_POST = 'POST'
LOGIN_PAGE = 'ui/login'
DEBUG = True
passthrough_server = "/smart_passthrough"
# init the IndivoClient python object
SMART_SERVER_LOCATION = urlparse.urlparse(settings.SMART_API_SERVER_BASE)
SMART_SERVER_LOCATION = {
'host': SMART_SERVER_LOCATION.hostname,
'scheme': SMART_SERVER_LOCATION.scheme,
'port': SMART_SERVER_LOCATION.port
or (
SMART_SERVER_LOCATION.scheme == 'http' and '80'
or SMART_SERVER_LOCATION.scheme == 'https' and '443'
)
}
def get_api(request=None):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponseForbidden, HttpRequest
from django.contrib.auth.models import User
from django.core.exceptions import *
from django.core.urlresolvers import reverse
from django.core import serializers
from django.db import transaction
from django.conf import settings
from django.utils import simplejson
from indivo_client_py.oauth import oauth
from django.db import transaction
from models import SmartConnectToken
from smart_ui_server import utils
from indivo_client_py.lib.client import IndivoClient
import xml.etree.ElementTree as ET
import urllib
import re
import httplib
import urllib
import urllib2
import urlparse
import time
import logging
and context:
# Path: indivo_client_py/lib/client.py
# class IndivoClient(APIConnector):
# def create_account(self, user):
# USER_EMAIL = 'user_email'
# ACCOUNT_ID = 'account_id'
# if not (user.has_key(USER_EMAIL) or user.has_key(ACCOUNT_ID)):
# raise APIConnectorError("No user email or account id when posting account")
#
# account_id = None
# if user.has_key(USER_EMAIL):
# account_id = user[USER_EMAIL]
# elif user.has_key(ACCOUNT_ID):
# account_id = user[ACCOUNT_ID]
#
# if account_id:
# primary_secret = user.get('primary_secret_p', 0)
# secondary_secret = user.get('secondary_secret_p', 0)
# password = user.get('user_pass', '')
#
# # There is a difference between app_type chrome without auth and admin
# return self.api.call(self.ds.app_info, {'account_id': account_id,
# 'primary_secret_p': primary_secret,
# 'secondary_secret_p': secondary_secret,
# 'password': password})
# return False
#
# def set_record_id(self, id):
# self.record_id, self.ds.record_id = id, id
#
# def set_app_id(self, id):
# self.app_id, self.ds.app_id = id, id
#
# def create_session(self, user):
# if user.has_key('username') and user.has_key('user_pass'):
# chrome_auth = {'username' : user['username'], 'password' : user['user_pass']}
# chrome_token = self.api.call(self.ds.app_info, chrome_auth)['prd']
# if isinstance(chrome_token, dict):
# self.ds.app_info.update(chrome_token)
# return chrome_token
# return False
#
# def update_token(self, oauth_token={}):
# if oauth_token \
# and isinstance(oauth_token, dict) \
# and oauth_token.has_key(OAUTH_TOKEN) \
# and oauth_token.has_key(OAUTH_TOKEN_SECRET):
# self.ds.app_info[OAUTH_TOKEN] = oauth_token[OAUTH_TOKEN]
# self.ds.app_info[OAUTH_TOKEN_SECRET] = oauth_token[OAUTH_TOKEN_SECRET]
#
# def get_surl_credentials(self):
# """Requires there to be a token and secret set
#
# produces a token and secret dictionary for SURL (signing URLs).
# """
#
# if self.ds.app_info.has_key(OAUTH_TOKEN) and \
# self.ds.app_info.has_key(OAUTH_TOKEN_SECRET):
# token = self.ds.app_info[OAUTH_TOKEN]
# secret = base64.b64encode(hmac.new(self.ds.app_info[OAUTH_TOKEN_SECRET], "SURL-SECRET", hashlib.sha1).digest())
# return {'token' : token, 'secret' : secret}
# return False
which might include code, classes, or functions. Output only the next line. | api = IndivoClient(settings.CONSUMER_KEY, settings.CONSUMER_SECRET, |
Next line prediction: <|code_start|> # perturbation of weight values
perturbations = np.linspace(-span, span, 200)
# Compute the loss when varying the study weight
parameters = deepcopy(model.parameters)
current_weight = float(get_parameter(parameters))
loss_range = []
old_parameters = list(model.parameters)
for perturbation in perturbations:
# Chage parameters
model.parameters = set_parameter(
parameters,
current_weight + perturbation
)
# Compute loss
perturbated_loss = model.cross_entropy_loss(
batch['input'],
batch['output']
)
loss_range.append(perturbated_loss)
# Return to old parameters
model.parameters = old_parameters
weight_range = current_weight + perturbations
return weight_range, loss_range
<|code_end|>
. Use current file imports:
(import os
import yaml
import numpy as np
import matplotlib.pyplot as plt
from six.moves import cPickle as pickle
from copy import deepcopy
from lxmls.deep_learning.utils import Model)
and context including class names, function names, or small code snippets from other files:
# Path: lxmls/deep_learning/utils.py
# class Model(object):
# def __init__(self, **config):
# self.initialized = False
#
# def initialize_features(self, *args):
# self.initialized = True
# raise NotImplementedError(
# "Need to implement initialize_features method"
# )
#
# def get_features(self, input=None, output=None):
# """
# Default feature extraction is do nothing
# """
# return {'input': input, 'output': output}
#
# def predict(self, *args):
# raise NotImplementedError("Need to implement predict method")
#
# def update(self, *args):
# # This needs to return at least {'cost' : 0}
# raise NotImplementedError("Need to implement update method")
# return {'cost': None}
#
# def set(self, **kwargs):
# raise NotImplementedError("Need to implement set method")
#
# def get(self, name):
# raise NotImplementedError("Need to implement get method")
#
# def save(self):
# raise NotImplementedError("Need to implement save method")
#
# def load(self, model_folder):
# raise NotImplementedError("Need to implement load method")
. Output only the next line. | class RNN(Model): |
Predict the next line after this snippet: <|code_start|>
MAX_SENT_SIZE = 1000
MAX_NR_SENTENCES = 100000
MODEL_DIR = "/Users/graca/Projects/swm_src/feeds/models/all_data_postag/"
def build_corpus_features():
corpus = pcc.PostagCorpus()
<|code_end|>
using the current file's imports:
import os
import sys
import codecs
import readers.pos_corpus as pcc
import readers.brown_pos_corpus as bpc
import sequences.extended_feature as exfc
import sequences.structured_perceptron as spc
import sequences.confusion_matrix as bcm
from lxmls import data
from sequences.sequence import *
from sequences.sequence_list import *
and any relevant context from other files:
# Path: lxmls/data.py
# def find(filename):
. Output only the next line. | train_seq = corpus.read_sequence_list_conll(data.find('train-02-21.conll'), |
Continue the code snippet: <|code_start|>from __future__ import division
# To sample from model
def cast_float(variable, grad=True):
return Variable(torch.from_numpy(variable).float(), requires_grad=grad)
def cast_int(variable, grad=True):
return Variable(torch.from_numpy(variable).long(), requires_grad=grad)
<|code_end|>
. Use current file imports:
import numpy as np
import scipy
import scipy.linalg
import torch
from torch.autograd import Variable
from torch.distributions import Categorical
from lxmls.deep_learning.rnn import RNN
from itertools import chain
and context (classes, functions, or code) from other files:
# Path: lxmls/deep_learning/rnn.py
# class RNN(Model):
# def __init__(self, **config):
#
# # CHECK THE PARAMETERS ARE VALID
# self.sanity_checks(config)
#
# # OPTIONAL MODEL LOADING
# model_folder = config.get('model_folder', None)
# if model_folder is not None:
# saved_config, loaded_parameters = self.load(model_folder)
# # Note that if a config is given this is used instead of the saved
# # one (must be consistent)
# if config is None:
# config = saved_config
# else:
# loaded_parameters = None
#
# # Class variables
# self.config = config
# self.parameters = initialize_rnn_parameters(
# config['input_size'],
# config['embedding_size'],
# config['hidden_size'],
# config['output_size'],
# loaded_parameters=loaded_parameters
# )
#
# def sanity_checks(self, config):
#
# model_folder = config.get('model_folder', None)
#
# assert bool(config is None) or bool(model_folder is None), \
# "Need to specify config, model_folder or both"
#
# if config is not None:
# pass
#
# if model_folder is not None:
# model_file = "%s/config.yml" % model_folder
# assert os.path.isfile(model_file), "Need to provide %s" % model_file
#
# def load(self, model_folder):
# """
# Load model
# """
#
# # Configuration un yaml format
# config_file = "%s/config.yml" % model_folder
# config = load_config(config_file)
#
# # Computation graph parameters as pickle file
# parameter_file = "%s/parameters.pkl" % model_folder
# loaded_parameters = load_parameters(parameter_file)
#
# return config, loaded_parameters
#
# def save(self, model_folder):
# """
# Save model
# """
#
# # Create folder if it does not exist
# if not os.path.isdir(model_folder):
# os.mkdir(model_folder)
#
# # Configuration un yaml format
# config_file = "%s/config.yml" % model_folder
# save_config(config_file, self.config)
#
# # Computation graph parameters as pickle file
# parameter_file = "%s/parameters.pkl" % model_folder
# with open(parameter_file, 'wb') as fid:
# pickle.dump(self.parameters, fid, pickle.HIGHEST_PROTOCOL)
#
# def plot_weights(self, show=True, aspect='auto'):
# """
# Plots the weights of the newtwork
#
# Use show = False to plot various models one after the other
# """
# import matplotlib.pyplot as plt
# plt.figure()
# for n in range(self.n_layers):
#
# # Get weights and bias
# weight, bias = self.parameters[n]
#
# # Plot them
# plt.subplot(2, self.n_layers, n+1)
# plt.imshow(weight, aspect=aspect, interpolation='nearest')
# plt.title('Layer %d Weight' % n)
# plt.colorbar()
# plt.subplot(2, self.n_layers, self.n_layers+(n+1))
# plt.plot(bias)
# plt.title('Layer %d Bias' % n)
# plt.colorbar()
#
# if show:
# plt.show()
. Output only the next line. | class PytorchRNN(RNN): |
Given the following code snippet before the placeholder: <|code_start|>
class NumpyLogLinear(Model):
def __init__(self, **config):
# Initialize parameters
weight_shape = (config['input_size'], config['num_classes'])
# after Xavier Glorot et al
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
from lxmls.deep_learning.utils import (
Model,
glorot_weight_init,
index2onehot,
logsumexp
)
and context including class names, function names, and sometimes code from other files:
# Path: lxmls/deep_learning/utils.py
# class Model(object):
# def __init__(self, **config):
# self.initialized = False
#
# def initialize_features(self, *args):
# self.initialized = True
# raise NotImplementedError(
# "Need to implement initialize_features method"
# )
#
# def get_features(self, input=None, output=None):
# """
# Default feature extraction is do nothing
# """
# return {'input': input, 'output': output}
#
# def predict(self, *args):
# raise NotImplementedError("Need to implement predict method")
#
# def update(self, *args):
# # This needs to return at least {'cost' : 0}
# raise NotImplementedError("Need to implement update method")
# return {'cost': None}
#
# def set(self, **kwargs):
# raise NotImplementedError("Need to implement set method")
#
# def get(self, name):
# raise NotImplementedError("Need to implement get method")
#
# def save(self):
# raise NotImplementedError("Need to implement save method")
#
# def load(self, model_folder):
# raise NotImplementedError("Need to implement load method")
#
# def glorot_weight_init(shape, activation_function, random_seed=None):
# """Layer weight initialization after Xavier Glorot et. al"""
#
# if random_seed is None:
# random_seed = np.random.RandomState(1234)
#
# # Weights are uniform distributed with span depending on input and output
# # sizes
# num_inputs, num_outputs = shape
# weight = random_seed.uniform(
# low=-np.sqrt(6. / (num_inputs + num_outputs)),
# high=np.sqrt(6. / (num_inputs + num_outputs)),
# size=(num_outputs, num_inputs)
# )
#
# # Scaling factor depending on non-linearity
# if activation_function == 'sigmoid':
# weight *= 4
# elif activation_function == 'softmax':
# weight *= 4
#
# return weight
#
# def index2onehot(index, N):
# """
# Transforms index to one-hot representation, for example
#
# Input: e.g. index = [1, 2, 0], N = 4
# Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]
# """
# L = index.shape[0]
# onehot = np.zeros((L, N))
# for l in np.arange(L):
# onehot[l, index[l]] = 1
# return onehot
#
# def logsumexp(a, axis=None, keepdims=False):
# """
# This is an improvement over the original logsumexp of
# scipy/maxentropy/maxentutils.py that allows specifying an axis to sum
# It also allows keepdims=True.
# """
# if axis is None:
# a = np.asarray(a)
# a_max = a.max()
# return a_max + np.log(np.exp(a-a_max).sum())
# else:
# a_max = np.amax(a, axis=axis, keepdims=keepdims)
# return a_max + np.log((np.exp(a-a_max)).sum(axis, keepdims=keepdims))
. Output only the next line. | self.weight = glorot_weight_init(weight_shape, 'softmax') |
Predict the next line for this snippet: <|code_start|> # Initialize parameters
weight_shape = (config['input_size'], config['num_classes'])
# after Xavier Glorot et al
self.weight = glorot_weight_init(weight_shape, 'softmax')
self.bias = np.zeros((1, config['num_classes']))
self.learning_rate = config['learning_rate']
def log_forward(self, input=None):
"""Forward pass of the computation graph"""
# Linear transformation
z = np.dot(input, self.weight.T) + self.bias
# Softmax implemented in log domain
log_tilde_z = z - logsumexp(z, axis=1, keepdims=True)
return log_tilde_z
def predict(self, input=None):
"""Most probable class index"""
return np.argmax(np.exp(self.log_forward(input)), axis=1)
def update(self, input=None, output=None):
"""Stochastic Gradient Descent update"""
# Probabilities of each class
class_probabilities = np.exp(self.log_forward(input))
batch_size, num_classes = class_probabilities.shape
# Error derivative at softmax layer
<|code_end|>
with the help of current file imports:
import numpy as np
from lxmls.deep_learning.utils import (
Model,
glorot_weight_init,
index2onehot,
logsumexp
)
and context from other files:
# Path: lxmls/deep_learning/utils.py
# class Model(object):
# def __init__(self, **config):
# self.initialized = False
#
# def initialize_features(self, *args):
# self.initialized = True
# raise NotImplementedError(
# "Need to implement initialize_features method"
# )
#
# def get_features(self, input=None, output=None):
# """
# Default feature extraction is do nothing
# """
# return {'input': input, 'output': output}
#
# def predict(self, *args):
# raise NotImplementedError("Need to implement predict method")
#
# def update(self, *args):
# # This needs to return at least {'cost' : 0}
# raise NotImplementedError("Need to implement update method")
# return {'cost': None}
#
# def set(self, **kwargs):
# raise NotImplementedError("Need to implement set method")
#
# def get(self, name):
# raise NotImplementedError("Need to implement get method")
#
# def save(self):
# raise NotImplementedError("Need to implement save method")
#
# def load(self, model_folder):
# raise NotImplementedError("Need to implement load method")
#
# def glorot_weight_init(shape, activation_function, random_seed=None):
# """Layer weight initialization after Xavier Glorot et. al"""
#
# if random_seed is None:
# random_seed = np.random.RandomState(1234)
#
# # Weights are uniform distributed with span depending on input and output
# # sizes
# num_inputs, num_outputs = shape
# weight = random_seed.uniform(
# low=-np.sqrt(6. / (num_inputs + num_outputs)),
# high=np.sqrt(6. / (num_inputs + num_outputs)),
# size=(num_outputs, num_inputs)
# )
#
# # Scaling factor depending on non-linearity
# if activation_function == 'sigmoid':
# weight *= 4
# elif activation_function == 'softmax':
# weight *= 4
#
# return weight
#
# def index2onehot(index, N):
# """
# Transforms index to one-hot representation, for example
#
# Input: e.g. index = [1, 2, 0], N = 4
# Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]
# """
# L = index.shape[0]
# onehot = np.zeros((L, N))
# for l in np.arange(L):
# onehot[l, index[l]] = 1
# return onehot
#
# def logsumexp(a, axis=None, keepdims=False):
# """
# This is an improvement over the original logsumexp of
# scipy/maxentropy/maxentutils.py that allows specifying an axis to sum
# It also allows keepdims=True.
# """
# if axis is None:
# a = np.asarray(a)
# a_max = a.max()
# return a_max + np.log(np.exp(a-a_max).sum())
# else:
# a_max = np.amax(a, axis=axis, keepdims=keepdims)
# return a_max + np.log((np.exp(a-a_max)).sum(axis, keepdims=keepdims))
, which may contain function names, class names, or code. Output only the next line. | I = index2onehot(output, num_classes) |
Given snippet: <|code_start|>
class NumpyLogLinear(Model):
def __init__(self, **config):
# Initialize parameters
weight_shape = (config['input_size'], config['num_classes'])
# after Xavier Glorot et al
self.weight = glorot_weight_init(weight_shape, 'softmax')
self.bias = np.zeros((1, config['num_classes']))
self.learning_rate = config['learning_rate']
def log_forward(self, input=None):
"""Forward pass of the computation graph"""
# Linear transformation
z = np.dot(input, self.weight.T) + self.bias
# Softmax implemented in log domain
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from lxmls.deep_learning.utils import (
Model,
glorot_weight_init,
index2onehot,
logsumexp
)
and context:
# Path: lxmls/deep_learning/utils.py
# class Model(object):
# def __init__(self, **config):
# self.initialized = False
#
# def initialize_features(self, *args):
# self.initialized = True
# raise NotImplementedError(
# "Need to implement initialize_features method"
# )
#
# def get_features(self, input=None, output=None):
# """
# Default feature extraction is do nothing
# """
# return {'input': input, 'output': output}
#
# def predict(self, *args):
# raise NotImplementedError("Need to implement predict method")
#
# def update(self, *args):
# # This needs to return at least {'cost' : 0}
# raise NotImplementedError("Need to implement update method")
# return {'cost': None}
#
# def set(self, **kwargs):
# raise NotImplementedError("Need to implement set method")
#
# def get(self, name):
# raise NotImplementedError("Need to implement get method")
#
# def save(self):
# raise NotImplementedError("Need to implement save method")
#
# def load(self, model_folder):
# raise NotImplementedError("Need to implement load method")
#
# def glorot_weight_init(shape, activation_function, random_seed=None):
# """Layer weight initialization after Xavier Glorot et. al"""
#
# if random_seed is None:
# random_seed = np.random.RandomState(1234)
#
# # Weights are uniform distributed with span depending on input and output
# # sizes
# num_inputs, num_outputs = shape
# weight = random_seed.uniform(
# low=-np.sqrt(6. / (num_inputs + num_outputs)),
# high=np.sqrt(6. / (num_inputs + num_outputs)),
# size=(num_outputs, num_inputs)
# )
#
# # Scaling factor depending on non-linearity
# if activation_function == 'sigmoid':
# weight *= 4
# elif activation_function == 'softmax':
# weight *= 4
#
# return weight
#
# def index2onehot(index, N):
# """
# Transforms index to one-hot representation, for example
#
# Input: e.g. index = [1, 2, 0], N = 4
# Output: [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]
# """
# L = index.shape[0]
# onehot = np.zeros((L, N))
# for l in np.arange(L):
# onehot[l, index[l]] = 1
# return onehot
#
# def logsumexp(a, axis=None, keepdims=False):
# """
# This is an improvement over the original logsumexp of
# scipy/maxentropy/maxentutils.py that allows specifying an axis to sum
# It also allows keepdims=True.
# """
# if axis is None:
# a = np.asarray(a)
# a_max = a.max()
# return a_max + np.log(np.exp(a-a_max).sum())
# else:
# a_max = np.amax(a, axis=axis, keepdims=keepdims)
# return a_max + np.log((np.exp(a-a_max)).sum(axis, keepdims=keepdims))
which might include code, classes, or functions. Output only the next line. | log_tilde_z = z - logsumexp(z, axis=1, keepdims=True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.