Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|>
def test_concept_eq(lattice):
assert lattice[5]._eq(lattice[5])
assert not lattice[1]._eq(lattice[7])
def test_concept_eq_neighors(lattice):
c = lattice[7]
mock_concept = functools.partial(lattices.Concept, c.lattice, c._extent, c._intent)
assert not c._eq(mock_concept(c.upper_neighbors[1:], c.lower_neighbors))
assert not c._eq(mock_concept(c.upper_neighbors, c.lower_neighbors[1:]))
assert not c._eq(mock_concept(tuple(reversed(c.upper_neighbors)),
c.lower_neighbors))
assert not c._eq(mock_concept(c.upper_neighbors,
tuple(reversed(c.lower_neighbors))))
def test_pickling(lattice):
result = pickle.loads(pickle.dumps(lattice))
assert result._context, lattice._context
assert [tuple(c) for c in result._concepts] == \
[tuple(c) for c in lattice._concepts]
def test_len(lattice):
assert len(lattice) == 22
@pytest.mark.parametrize(
<|code_end|>
, generate the next line using the imports in this file:
import functools
import pickle
import pytest
import concepts
from concepts import lattices
and context (functions, classes, or occasionally code) from other files:
# Path: concepts/lattices.py
# class Data:
# class FormattingMixin:
# class CollectionMixin:
# class AggregagtionMixin:
# class NavigateableMixin:
# class VisualizableMixin:
# class Lattice(VisualizableMixin, NavigateableMixin, AggregagtionMixin,
# CollectionMixin, FormattingMixin, Data):
# def _longlex(concept):
# def _shortlex(concept):
# def _fromlist(cls, context, lattice, unordered) -> 'Lattice':
# def __init__(self, context: 'contexts.Context', infimum=()) -> None:
# def _make_mapping(concepts):
# def _init(inst,
# context: 'contexts.Context',
# concepts,
# mapping=None, unpickle=False) -> None:
# def _annotate(context, mapping):
# def __getstate__(self):
# def __setstate__(self, state):
# def _tolist(self):
# def _eq(self, other) -> typing.Union[type(NotImplemented), bool]:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __call__(self, properties: typing.Tuple[str]) -> Concept:
# def __getitem__(self, key: typing.Union[int, typing.Tuple[str, ...]]
# ) -> Concept:
# def __iter__(self) -> typing.Iterator[Concept]:
# def __len__(self) -> int:
# def join(self, concepts: typing.Iterable[Concept]) -> Concept:
# def meet(self, concepts: typing.Iterable[Concept]) -> Concept:
# def upset_union(self, concepts: typing.Iterable[Concept],
# _sortkey=operator.attrgetter('index'),
# _next_concepts=operator.attrgetter('upper_neighbors')
# ) -> typing.Iterator[Concept]:
# def downset_union(self, concepts: typing.Iterable[Concept],
# _sortkey=operator.attrgetter('dindex'),
# _next_concepts=operator.attrgetter('lower_neighbors')
# ) -> typing.Iterator[Concept]:
# def upset_generalization(self, concepts: typing.Iterable[Concept]
# ) -> typing.Iterator[Concept]:
# def graphviz(self, filename=None, directory=None,
# render: bool = False,
# view: bool = False,
# make_object_label=' '.join,
# make_property_label=' '.join,
# **kwargs) -> graphviz.Digraph:
# def infimum(self) -> Infimum:
# def supremum(self) -> Supremum:
# def atoms(self) -> typing.Tuple[Atom, ...]:
. Output only the next line. | 'concepts, expected', |
Predict the next line for this snippet: <|code_start|>
__all__ = ['PythonLiteral']
def load_file(file) -> SerializedArgs:
python_source = file.read()
args = ast.literal_eval(python_source)
assert args is not None
assert isinstance(args, dict)
objects = args['objects']
properties = args['properties']
bools = [[False for _ in args['properties']]
for _ in args['objects']]
for row, true_indexes in zip(bools, args['context']):
for i in true_indexes:
row[i] = True
bools = [tuple(row) for row in bools]
return SerializedArgs(objects, properties, bools, serialized=args)
def dump_file(file, objects, properties, bools, *, _serialized=None) -> None:
<|code_end|>
with the help of current file imports:
import ast
import functools
from .base import SerializedArgs, Format
and context from other files:
# Path: concepts/formats/base.py
# class SerializedArgs(ContextArgs):
#
# lattice: typing.Optional[LatticeType] = None
#
# class Format(metaclass=FormatMeta):
# """Parse and serialize formal contexts in a specific string format."""
#
# __abstract__ = True
#
# encoding = None
#
# newline = None
#
# dumps_rstrip = None
#
# @classmethod
# def load(cls, filename, encoding, **kwargs) -> ContextArgs:
# """Load and parse serialized objects, properties, bools from file."""
# if encoding is None:
# encoding = cls.encoding
#
# with open(filename, encoding=encoding, newline=cls.newline) as f:
# return cls.loadf(f, **kwargs)
#
# @classmethod
# def loads(cls, source, **kwargs) -> ContextArgs:
# """Parse source string and return ``ContextArgs``."""
# with io.StringIO(source) as buf:
# return cls.loadf(buf, **kwargs)
#
# @classmethod
# def dump(cls, filename, objects, properties, bools,
# *, encoding: typing.Optional[str], _serialized=None, **kwargs):
# """Write serialized objects, properties, bools to file."""
# if encoding is None:
# encoding = cls.encoding
#
# with open(filename, 'w', encoding=encoding, newline=cls.newline) as f:
# cls.dumpf(f, objects, properties, bools, _serialized=_serialized,
# **kwargs)
#
# @classmethod
# def dumps(cls, objects, properties, bools, _serialized=None, **kwargs):
# with io.StringIO(newline=cls.newline) as buf:
# cls.dumpf(buf, objects, properties, bools, _serialized=_serialized,
# **kwargs)
# source = buf.getvalue()
# if cls.dumps_rstrip:
# source = source.rstrip()
# return source
#
# @staticmethod
# def loadf(file, **kwargs) -> ContextArgs:
# """Parse file-like object and return ``ContextArgs``."""
# raise NotImplementedError # pragma: no cover
#
# @staticmethod
# def dumpf(file, objects, properties, bools, *, _serialized=None, **kwargs):
# """Serialize ``(objects, properties, bools)`` into file-like object."""
# raise NotImplementedError # pragma: no cover
, which may contain function names, class names, or code. Output only the next line. | if _serialized is None: |
Given the following code snippet before the placeholder: <|code_start|>
__all__ = ['PythonLiteral']
def load_file(file) -> SerializedArgs:
python_source = file.read()
args = ast.literal_eval(python_source)
assert args is not None
<|code_end|>
, predict the next line using imports from the current file:
import ast
import functools
from .base import SerializedArgs, Format
and context including class names, function names, and sometimes code from other files:
# Path: concepts/formats/base.py
# class SerializedArgs(ContextArgs):
#
# lattice: typing.Optional[LatticeType] = None
#
# class Format(metaclass=FormatMeta):
# """Parse and serialize formal contexts in a specific string format."""
#
# __abstract__ = True
#
# encoding = None
#
# newline = None
#
# dumps_rstrip = None
#
# @classmethod
# def load(cls, filename, encoding, **kwargs) -> ContextArgs:
# """Load and parse serialized objects, properties, bools from file."""
# if encoding is None:
# encoding = cls.encoding
#
# with open(filename, encoding=encoding, newline=cls.newline) as f:
# return cls.loadf(f, **kwargs)
#
# @classmethod
# def loads(cls, source, **kwargs) -> ContextArgs:
# """Parse source string and return ``ContextArgs``."""
# with io.StringIO(source) as buf:
# return cls.loadf(buf, **kwargs)
#
# @classmethod
# def dump(cls, filename, objects, properties, bools,
# *, encoding: typing.Optional[str], _serialized=None, **kwargs):
# """Write serialized objects, properties, bools to file."""
# if encoding is None:
# encoding = cls.encoding
#
# with open(filename, 'w', encoding=encoding, newline=cls.newline) as f:
# cls.dumpf(f, objects, properties, bools, _serialized=_serialized,
# **kwargs)
#
# @classmethod
# def dumps(cls, objects, properties, bools, _serialized=None, **kwargs):
# with io.StringIO(newline=cls.newline) as buf:
# cls.dumpf(buf, objects, properties, bools, _serialized=_serialized,
# **kwargs)
# source = buf.getvalue()
# if cls.dumps_rstrip:
# source = source.rstrip()
# return source
#
# @staticmethod
# def loadf(file, **kwargs) -> ContextArgs:
# """Parse file-like object and return ``ContextArgs``."""
# raise NotImplementedError # pragma: no cover
#
# @staticmethod
# def dumpf(file, objects, properties, bools, *, _serialized=None, **kwargs):
# """Serialize ``(objects, properties, bools)`` into file-like object."""
# raise NotImplementedError # pragma: no cover
. Output only the next line. | assert isinstance(args, dict) |
Given the code snippet: <|code_start|>
__all__ = ['WikiTable']
def dump_file(file, objects, properties, bools, *, _serialized=None):
write = functools.partial(print, file=file)
write('{| class="featuresystem"')
write('!')
write('!{}'.format('!!'.join(properties)))
wp = list(map(len, properties))
for o, intent in zip(objects, bools):
bcells = (('X' if b else '').ljust(w) for w, b in zip(wp, intent))
<|code_end|>
, generate the next line using the imports in this file:
import functools
from .base import Format
and context (functions, classes, or occasionally code) from other files:
# Path: concepts/formats/base.py
# class Format(metaclass=FormatMeta):
# """Parse and serialize formal contexts in a specific string format."""
#
# __abstract__ = True
#
# encoding = None
#
# newline = None
#
# dumps_rstrip = None
#
# @classmethod
# def load(cls, filename, encoding, **kwargs) -> ContextArgs:
# """Load and parse serialized objects, properties, bools from file."""
# if encoding is None:
# encoding = cls.encoding
#
# with open(filename, encoding=encoding, newline=cls.newline) as f:
# return cls.loadf(f, **kwargs)
#
# @classmethod
# def loads(cls, source, **kwargs) -> ContextArgs:
# """Parse source string and return ``ContextArgs``."""
# with io.StringIO(source) as buf:
# return cls.loadf(buf, **kwargs)
#
# @classmethod
# def dump(cls, filename, objects, properties, bools,
# *, encoding: typing.Optional[str], _serialized=None, **kwargs):
# """Write serialized objects, properties, bools to file."""
# if encoding is None:
# encoding = cls.encoding
#
# with open(filename, 'w', encoding=encoding, newline=cls.newline) as f:
# cls.dumpf(f, objects, properties, bools, _serialized=_serialized,
# **kwargs)
#
# @classmethod
# def dumps(cls, objects, properties, bools, _serialized=None, **kwargs):
# with io.StringIO(newline=cls.newline) as buf:
# cls.dumpf(buf, objects, properties, bools, _serialized=_serialized,
# **kwargs)
# source = buf.getvalue()
# if cls.dumps_rstrip:
# source = source.rstrip()
# return source
#
# @staticmethod
# def loadf(file, **kwargs) -> ContextArgs:
# """Parse file-like object and return ``ContextArgs``."""
# raise NotImplementedError # pragma: no cover
#
# @staticmethod
# def dumpf(file, objects, properties, bools, *, _serialized=None, **kwargs):
# """Serialize ``(objects, properties, bools)`` into file-like object."""
# raise NotImplementedError # pragma: no cover
. Output only the next line. | write('|-') |
Predict the next line after this snippet: <|code_start|>
__all__ = ['iter_cxt_lines', 'Cxt']
SYMBOLS = {False: '.', True: 'X'}
def iter_cxt_lines(objects, properties, bools,
*, symbols: typing.Mapping[bool, str] = SYMBOLS):
assert len(objects) == len(bools)
assert {len(properties)} == set(map(len, bools))
yield 'B'
yield ''
yield f'{len(objects):d}'
<|code_end|>
using the current file's imports:
import functools
import typing
from .base import ContextArgs, Format
and any relevant context from other files:
# Path: concepts/formats/base.py
# class ContextArgs(typing.NamedTuple):
# """Return value of ``.loads()`` and ``.load()``."""
#
# objects: typing.List[str]
#
# properties: typing.List[str]
#
# bools: typing.List[typing.Tuple[bool, ...]]
#
# serialized: typing.Optional['SerializedArgs'] = None
#
# class Format(metaclass=FormatMeta):
# """Parse and serialize formal contexts in a specific string format."""
#
# __abstract__ = True
#
# encoding = None
#
# newline = None
#
# dumps_rstrip = None
#
# @classmethod
# def load(cls, filename, encoding, **kwargs) -> ContextArgs:
# """Load and parse serialized objects, properties, bools from file."""
# if encoding is None:
# encoding = cls.encoding
#
# with open(filename, encoding=encoding, newline=cls.newline) as f:
# return cls.loadf(f, **kwargs)
#
# @classmethod
# def loads(cls, source, **kwargs) -> ContextArgs:
# """Parse source string and return ``ContextArgs``."""
# with io.StringIO(source) as buf:
# return cls.loadf(buf, **kwargs)
#
# @classmethod
# def dump(cls, filename, objects, properties, bools,
# *, encoding: typing.Optional[str], _serialized=None, **kwargs):
# """Write serialized objects, properties, bools to file."""
# if encoding is None:
# encoding = cls.encoding
#
# with open(filename, 'w', encoding=encoding, newline=cls.newline) as f:
# cls.dumpf(f, objects, properties, bools, _serialized=_serialized,
# **kwargs)
#
# @classmethod
# def dumps(cls, objects, properties, bools, _serialized=None, **kwargs):
# with io.StringIO(newline=cls.newline) as buf:
# cls.dumpf(buf, objects, properties, bools, _serialized=_serialized,
# **kwargs)
# source = buf.getvalue()
# if cls.dumps_rstrip:
# source = source.rstrip()
# return source
#
# @staticmethod
# def loadf(file, **kwargs) -> ContextArgs:
# """Parse file-like object and return ``ContextArgs``."""
# raise NotImplementedError # pragma: no cover
#
# @staticmethod
# def dumpf(file, objects, properties, bools, *, _serialized=None, **kwargs):
# """Serialize ``(objects, properties, bools)`` into file-like object."""
# raise NotImplementedError # pragma: no cover
. Output only the next line. | yield f'{len(properties):d}' |
Continue the code snippet: <|code_start|>
@pytest.fixture(scope='module')
def relation():
xname = 'Condition'
yname = 'Symbol'
xmembers = 'TT', 'TF', 'FT', 'FF'
ymembers = '->', '<-'
xbools = [(True, False, True, True), (True, True, False, True)]
return matrices.Relation(xname, yname, xmembers, ymembers, xbools)
def test_pair_with(relation):
vx, vy = relation
with pytest.raises(RuntimeError, match=r'attempt _pair_with'):
vx._pair_with(relation, 1, vy)
<|code_end|>
. Use current file imports:
import pytest
from concepts import matrices
and context (classes, functions, or code) from other files:
# Path: concepts/matrices.py
# class Vectors(bitsets.series.Tuple):
# class Relation(tuple):
# def _pair_with(self, relation, index, other):
# def prime(bitset):
# def double(bitset):
# def doubleprime(bitset):
# def __reduce__(self):
# def __new__(cls, xname, yname, xmembers, ymembers, xbools, _ids=None):
# def __repr__(self):
# def __reduce__(self):
# X = bitsets.meta.bitset(xname, xmembers, xid, Vector, None, Vectors) # noqa: N806
# Y = bitsets.meta.bitset(yname, ymembers, yid, Vector, None, Vectors) # noqa: N806
# X = bitsets.bitset(xname, xmembers, Vector, tuple=Vectors) # noqa: N806
# Y = bitsets.bitset(yname, ymembers, Vector, tuple=Vectors) # noqa: N806
# X, Y = (v.BitSet for v in self) # noqa: N806
. Output only the next line. | def test_prime_infimum(relation): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
class TestPhonecallsSuperBackup(unittest.TestCase):
def setUp(self):
self._test_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data',
'calls_superbackup.xml')
argv = "-s -f " + self._test_file
memacs = PhonecallsSuperBackupMemacs(argv=argv.split())
self.data = memacs.test_get_entries()
def test_all(self):
self.assertEqual(
self.data[0],
"** <2018-09-17 Mon 19:58>-<2018-09-17 Mon 20:02> Phonecall from [[contact:TestPerson1][TestPerson1]]"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import unittest
from memacs.phonecalls_superbackup import PhonecallsSuperBackupMemacs
and context:
# Path: memacs/phonecalls_superbackup.py
# class PhonecallsSuperBackupMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="smsxmlfile",
# action="store", required=True,
# help="path to sms xml backup file")
#
# self._parser.add_argument(
# "--ignore-incoming", dest="ignore_incoming",
# action="store_true",
# help="ignore incoming phonecalls")
#
# self._parser.add_argument(
# "--ignore-outgoing", dest="ignore_outgoing",
# action="store_true",
# help="ignore outgoing phonecalls")
#
# self._parser.add_argument(
# "--ignore-missed", dest="ignore_missed",
# action="store_true",
# help="ignore outgoing phonecalls")
#
# self._parser.add_argument(
# "--ignore-voicemail", dest="ignore_voicemail",
# action="store_true",
# help="ignore voicemail phonecalls")
#
# self._parser.add_argument(
# "--ignore-rejected", dest="ignore_rejected",
# action="store_true",
# help="ignore rejected phonecalls")
#
# self._parser.add_argument(
# "--ignore-refused", dest="ignore_refused",
# action="store_true",
# help="ignore refused phonecalls")
#
# self._parser.add_argument(
# "--minimum-duration", dest="minimum_duration",
# action="store", type=int,
# help="[sec] show only calls with duration >= this argument")
#
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if not (os.path.exists(self._args.smsxmlfile) or \
# os.access(self._args.smsxmlfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
#
# def _main(self):
# """
# gets called automatically from Memacs class.
# read the lines from phonecalls backup xml file,
# parse and write them to org file
# """
#
# data = CommonReader.get_data_from_file(self._args.smsxmlfile)
#
# try:
# xml.sax.parseString(data.encode('utf-8'),
# PhonecallsSaxHandler(self._writer,
# self._args.ignore_incoming,
# self._args.ignore_outgoing,
# self._args.ignore_missed,
# self._args.ignore_voicemail,
# self._args.ignore_rejected,
# self._args.ignore_refused,
# self._args.minimum_duration or 0,
# ))
# except SAXParseException:
# logging.error("No correct XML given")
# sys.exit(1)
which might include code, classes, or functions. Output only the next line. | ) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class TestGPX(unittest.TestCase):
def test_google(self):
sample = os.path.join(
<|code_end|>
with the help of current file imports:
import os
import unittest
from memacs.gpx import GPX
and context from other files:
# Path: memacs/gpx.py
# class GPX(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--folder", dest="source",
# action="store", required=True,
# help="path to gpx file or folder")
#
# self._parser.add_argument(
# "-p", "--provider", dest="provider",
# action="store", default="google",
# help="geocode provider, default google")
#
# self._parser.add_argument(
# "-u", "--url", dest="url",
# action="store", help="url to nominatim server (osm only)")
#
# self._parser.add_argument(
# "--output-format", dest="output_format",
# action="store", default="{address}",
# help="format string to use for the headline")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
#
# if not os.path.exists(self._args.source):
# self._parser.error("source file or folder does not exist")
#
# if self._args.url and not self._args.url.startswith("http"):
# self._parser.error("invalid url given")
#
# def reverse_geocode(self, lat, lng):
# """get address for latitude/longitude"""
#
# if 'google' in self._args.provider:
# geocode = geocoder.google([lat, lng], method='reverse')
#
# elif 'osm' in self._args.provider:
# if not self._args.url:
# geocode = geocoder.osm([lat, lng], method='reverse')
# time.sleep(1) # Nominatim Usage Policy
# else:
# if 'localhost' in self._args.url:
# geocode = geocoder.osm([lat, lng], method='reverse', url='http://localhost/nominatim/search')
# else:
# geocode = geocoder.osm([lat, lng], method='reverse', url=self._args.url)
#
# else:
# self._parser.error("invalid provider given")
# raise ValueError('invalid provider given')
#
# if not geocode.ok:
# logging.error("geocoding failed or api limit exceeded")
# raise RuntimeError('geocoding failed or api limit exceeded')
# else:
# logging.debug(geocode.json)
# return geocode.json
#
# def write_point(self, p):
# """write a point (including geocoding)"""
#
# timestamp = OrgFormat.date(p.time, show_time=True)
# geocode = self.reverse_geocode(p.latitude, p.longitude)
# output = self._args.output_format.format(**geocode)
#
# tags = []
#
# properties = OrgProperties(data_for_hashing=timestamp)
#
# if p.latitude:
# properties.add('LATITUDE', p.latitude)
#
# if p.longitude:
# properties.add('LONGITUDE', p.longitude)
#
# if p.source:
# tags.append(p.source.lower())
#
# if timestamp:
# self._writer.write_org_subitem(timestamp=timestamp,
# output=output,
# properties=properties,
# tags=tags)
#
# def handle_file(self, f):
# """iterate through a file"""
#
# data = open(f)
# gpx = gpxpy.parse(data)
#
# for track in gpx.tracks:
# for segment in track.segments:
# for point in segment.points:
# self.write_point(point)
# logging.debug(point)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
#
# if os.path.isfile(self._args.source):
# self.handle_file(self._args.source)
#
# else:
# for root, dirs, files in os.walk(self._args.source):
# for f in files:
# if f.endswith('.gpx'):
# self.handle_file(os.path.join(root, f))
, which may contain function names, class names, or code. Output only the next line. | os.path.dirname(os.path.abspath(__file__)), 'data', 'sample.gpx' |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# Time-stamp: <2012-09-06 22:02:48 armin>
class TestPhonecallsMemacs(unittest.TestCase):
def setUp(self):
self._test_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data', 'calls.xml'
<|code_end|>
. Use current file imports:
import os
import re
import time
import unittest
import xml.etree.ElementTree as ET
from memacs.phonecalls import PhonecallsMemacs
and context (classes, functions, or code) from other files:
# Path: memacs/phonecalls.py
# class PhonecallsMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="smsxmlfile",
# action="store", required=True,
# help="path to sms xml backup file")
#
# self._parser.add_argument(
# "--ignore-incoming", dest="ignore_incoming",
# action="store_true",
# help="ignore incoming phonecalls")
#
# self._parser.add_argument(
# "--ignore-outgoing", dest="ignore_outgoing",
# action="store_true",
# help="ignore outgoing phonecalls")
#
# self._parser.add_argument(
# "--ignore-missed", dest="ignore_missed",
# action="store_true",
# help="ignore outgoing phonecalls")
#
# self._parser.add_argument(
# "--ignore-cancelled", dest="ignore_cancelled",
# action="store_true",
# help="ignore cancelled phonecalls")
#
# self._parser.add_argument(
# "--minimum-duration", dest="minimum_duration",
# action="store", type=int,
# help="[sec] show only calls with duration >= this argument")
#
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if not (os.path.exists(self._args.smsxmlfile) or \
# os.access(self._args.smsxmlfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
#
# def _main(self):
# """
# gets called automatically from Memacs class.
# read the lines from phonecalls backup xml file,
# parse and write them to org file
# """
#
# data = CommonReader.get_data_from_file(self._args.smsxmlfile)
#
# try:
# xml.sax.parseString(data.encode('utf-8'),
# PhonecallsSaxHandler(self._writer,
# self._args.ignore_incoming,
# self._args.ignore_outgoing,
# self._args.ignore_missed,
# self._args.ignore_cancelled,
# self._args.minimum_duration or 0,
# ))
# except SAXParseException:
# logging.error("No correct XML given")
# sys.exit(1)
. Output only the next line. | ) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# Time-stamp: <2013-04-04 16:18:07 vk>
PROG_VERSION_NUMBER = "0.0"
PROG_VERSION_DATE = "2018-07-14"
PROG_SHORT_DESCRIPTION = "Memacs for firefox url history "
PROG_TAG = "firefox"
PROG_DESCRIPTION = """
This class will parse firefox history file (places.sqlite) and
produce an org file with all your visited sites
"""
# set CONFIG_PARSER_NAME only, when you want to have a config file
# otherwise you can comment it out
# CONFIG_PARSER_NAME="memacs-example"
COPYRIGHT_YEAR = "2018"
COPYRIGHT_AUTHORS = """Raimon Grau <raimonster@gmail.com>"""
def main():
global memacs
memacs = Firefox(
prog_version=PROG_VERSION_NUMBER,
prog_version_date=PROG_VERSION_DATE,
prog_description=PROG_DESCRIPTION,
prog_short_description=PROG_SHORT_DESCRIPTION,
prog_tag=PROG_TAG,
copyright_year=COPYRIGHT_YEAR,
copyright_authors=COPYRIGHT_AUTHORS
# use_config_parser_name=CONFIG_PARSER_NAME
<|code_end|>
. Use current file imports:
from memacs.firefox import Firefox
and context (classes, functions, or code) from other files:
# Path: memacs/firefox.py
# class Firefox(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="historystore",
# action="store", type=open , required=True,
# help="""path to places.sqlite file. usually in
# /home/rgrau/.mozilla/firefox/__SOMETHING__.default/places.sqlite """)
#
# self._parser.add_argument(
# "--output-format", dest="output_format",
# action="store", default="[[{url}][{title}]]",
# help="format string to use for the headline")
#
# self._parser.add_argument(
# "--omit-drawer", dest="omit_drawer",
# action="store_true", required=False,
# help="""Use a minimal output format that omits the PROPERTIES drawer.""")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
#
# def _handle_url(self, params):
# timestamp = datetime.datetime.fromtimestamp(int(params['timestamp']/1000000))
#
# if not self._args.omit_drawer:
# properties = OrgProperties()
# if (params['title'] == "") :
# params['title'] = params['url']
# properties.add('URL', params['url'])
# properties.add('VISIT_COUNT', params['visit_count'])
#
# output = OrgFormat.link(params['url'], params['title'])
#
# try:
# output = self._args.output_format.decode('utf-8').format(**params)
# except Exception:
# pass
#
# if self._args.omit_drawer:
# self._writer.write_org_subitem(
# timestamp=OrgFormat.date(timestamp, show_time=True),
# output=output, properties=None)
# else:
# self._writer.write_org_subitem(
# timestamp=OrgFormat.date(timestamp, show_time=True),
# output=output, properties=properties)
#
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
# conn = sqlite3.connect(os.path.abspath(self._args.historystore.name))
# query = conn.execute("""
# select url, title, visit_count,
# -- datetime(last_visit_date/1000000, 'unixepoch')
# last_visit_date
# from moz_places
# where last_visit_date IS NOT NULL
# order by last_visit_date """)
#
# for row in query:
# self._handle_url({
# 'url' : row[0],
# 'title' : row[1],
# 'visit_count' : row[2],
# 'timestamp' : row[3],
# })
. Output only the next line. | ) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
# Time-stamp: <2018-08-25 14:16:04 vk>
class TestFoo(unittest.TestCase):
def setUp(self):
pass
def test_all(self):
argv = "-s"
memacs = Foo(argv=argv.split())
# or when in append mode:
# memacs = Foo(argv=argv.split(), append=True)
data = memacs.test_get_entries()
# generate assertEquals :)
#for d in range(len(data)):
# print "self.assertEqual(\n\tdata[%d],\n\t\"%s\")" % \
# (d, data[d])
self.assertEqual(
data[0],
"** <1970-01-01 Thu 00:00> foo")
self.assertEqual(
<|code_end|>
. Use current file imports:
(import unittest
from memacs.example import Foo)
and context including class names, function names, or small code snippets from other files:
# Path: memacs/example.py
# class Foo(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# #self._parser.add_argument(
# # "-e", "--example", dest="example",
# # action="store_true",
# # help="path to a folder to search for filenametimestamps, " +
# # "multiple folders can be specified: -f /path1 -f /path2")
#
# #self._parser.add_argument(
# # "-i", "--int", dest="example_int",
# # action="store_true",
# # help="example2",
# # type=int)
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# # if self._args.example == ...:
# # self._parser.error("could not parse foo")
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
# # do all the stuff
#
# # if you need something from config:
# # attention: foo will be unicode
# # foo = self._get_config_option("foo")
#
# logging.info("foo started")
#
# # how to handle config files ?
# # sample config file:
# # ---------8<-----------
# # [memacs-example]
# # foo = 0
# # bar = 1
# # --------->8-----------
# # to read it out, just do following:
# # foo = self._get_config_option("foo")
# # bar = self._get_config_option("bar")
#
# # use logging.debug() for debug messages
# # use logging.error() for error messages
# # use logging.info() instead of print for informing user
# #
# # on an fatal error:
# # use logging.error() and sys.exit(1)
#
# timestamp = OrgFormat.date(time.gmtime(0), show_time=True)
# # note: timestamp has to be a struct_time object
#
# # Orgproperties
# # Option 1: no properties given, specify argument for hashing data
# properties = OrgProperties("hashing data :ALKJ!@# should be unique")
# # Option 2: add properties which are all-together unique
# # properties.add("Category","fun")
# # properties.add("from","me@example.com")
# # properties.add("body","foo")
#
# self._writer.write_org_subitem(timestamp=timestamp,
# output="foo",
# properties=properties)
#
# # writes following:
# #** <1970-01-01 Thu 00:00> foo
# # :PROPERTIES:
# # :ID: da39a3ee5e6b4b0d3255bfef95601890afd80709
# # :END:
#
# notes = "bar notes\nfoo notes"
#
# p = OrgProperties(data_for_hashing="read comment below")
# # if a hash is not unique only with its :PROPERTIES: , then
# # set data_for_hasing string additional information i.e. the output
# # , which then makes the hash really unique
# #
# # if you *really*, *really* have already a unique id,
# # then you can call following method:
# # p.set_id("unique id here")
#
# p.add("DESCRIPTION", "foooo")
# p.add("foo-property", "asdf")
#
# tags = ["tag1", "tag2"]
#
# self._writer.write_org_subitem(timestamp=timestamp,
# output="bar",
# note=notes,
# properties=p,
# tags=tags)
# # writes following:
# #** <1970-01-01 Thu 00:00> bar :tag1:tag2:
# # bar notes
# # foo notes
# # :PROPERTIES:
# # :DESCRIPTION: foooo
# # :FOO-PROPERTY: asdf
# # :ID: 97521347348df02dab8bf86fbb6817c0af333a3f
# # :END:
. Output only the next line. | data[1], |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2013-04-04 16:19:39 vk>
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2012-03-10"
PROG_SHORT_DESCRIPTION = "Memacs for photos (exif)"
PROG_TAG = "photos"
PROG_DESCRIPTION = """
This memacs module will walk through a given folder looking for photos.
<|code_end|>
. Use current file imports:
from memacs.photos import PhotosMemacs
and context (classes, functions, or code) from other files:
# Path: memacs/photos.py
# class PhotosMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--folder", dest="photo_folder",
# action="store", required=True,
# help="path to search for photos")
#
# self._parser.add_argument("-l", "--follow-links",
# dest="follow_links", action="store_true",
# help="follow symbolics links," + \
# " default False")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if not os.path.exists(self._args.photo_folder):
# self._parser.error("photo folder does not exist")
#
# def __handle_file(self, photo_file, filename):
# """
# checks if file is an image, try to get exif data and
# write to org file
# """
#
# logging.debug("handling file %s", filename)
#
# # check if file is an image:
# if imghdr.what(filename) != None:
# datetime = get_exif_datetime(filename)
# if datetime == None:
# logging.debug("skipping: %s has no EXIF information", filename)
# else:
# try:
# datetime = time.strptime(datetime, "%Y:%m:%d %H:%M:%S")
# timestamp = OrgFormat.date(datetime, show_time=True)
# output = OrgFormat.link(filename, photo_file)
# properties = OrgProperties(photo_file + timestamp)
#
# self._writer.write_org_subitem(timestamp=timestamp,
# output=output,
# properties=properties)
# except ValueError as e:
# logging.warning("skipping: Could not parse " + \
# "timestamp for %s : %s", filename, e)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# walk through given folder and handle each file
# """
#
# for rootdir, dirs, files in os.walk(self._args.photo_folder,
# followlinks=self._args.follow_links):
# for photo_file in files:
# filename = rootdir + os.sep + photo_file
# self.__handle_file(photo_file, filename)
. Output only the next line. | If a photo is found, it will get a timestamp from the exif information. |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2017-02-24"
PROG_SHORT_DESCRIPTION = "Memacs for battery"
PROG_TAG = "battery"
COPYRIGHT_YEAR = "2017"
COPYRIGHT_AUTHORS = """Manuel Koell <mankoell@gmail.com>"""
def main():
memacs = Battery(
prog_version=PROG_VERSION_NUMBER,
prog_version_date=PROG_VERSION_DATE,
prog_short_description=PROG_SHORT_DESCRIPTION,
prog_tag=PROG_TAG,
copyright_year=COPYRIGHT_YEAR,
<|code_end|>
. Write the next line using the current file imports:
from memacs.battery import Battery
and context from other files:
# Path: memacs/battery.py
# class Battery(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-b", "--battery", dest="name",
# action="store", default="BAT0",
# help="select battery to read stats from")
#
# self._parser.add_argument(
# "-p", "--path", dest="path",
# action="store", default=ROOT,
# help=argparse.SUPPRESS)
#
# self._parser.add_argument(
# "--output-format", dest="output_format",
# action="store", default="{battery.name}",
# help="format string to use for the output"
# )
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
#
# def _handle_battery(self, bat):
# """
# handle single battery, e.g. BAT0
# """
#
# # calculate watt usage
# consumption = float(bat.current_now / 1000000.0 *
# bat.voltage_now / 1000000.0)
#
# timestamp = OrgFormat.date(datetime.datetime.now(), show_time=True)
# output = self._args.output_format.format(battery=bat)
#
# properties = OrgProperties(data_for_hashing=timestamp)
# properties.add("CYCLE_COUNT", bat.cycle_count)
# properties.add("CAPACITY", '%s%%' % bat.capacity)
# properties.add("STATUS", bat.status.lower())
#
# if consumption:
# properties.add("CONSUMPTION", '%.1f W' % consumption)
#
# self._writer.write_org_subitem(timestamp=timestamp,
# output=output,
# properties=properties)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
#
# try:
# batteries = batinfo.Batteries(self._args.path)
#
# for bat in batteries.stat:
# if self._args.name in bat.name:
# self._handle_battery(bat)
#
# except OSError as e:
# logging.error("no battery present")
# sys.exit(1)
, which may include functions, classes, or code. Output only the next line. | copyright_authors=COPYRIGHT_AUTHORS |
Given snippet: <|code_start|>
sample config:
[memacs-example] <-- "memacs-example" has to be CONFIG_PARSER_NAME
foo = 0
bar = 1
"""
# set CONFIG_PARSER_NAME only, when you want to have a config file
# otherwise you can comment it out
# CONFIG_PARSER_NAME="memacs-example"
COPYRIGHT_YEAR = "2011-2013"
COPYRIGHT_AUTHORS = """Karl Voit <tools@Karl-Voit.at>,
Armin Wieser <armin.wieser@gmail.com>"""
def main():
global memacs
memacs = Foo(
prog_version=PROG_VERSION_NUMBER,
prog_version_date=PROG_VERSION_DATE,
prog_description=PROG_DESCRIPTION,
prog_short_description=PROG_SHORT_DESCRIPTION,
prog_tag=PROG_TAG,
copyright_year=COPYRIGHT_YEAR,
copyright_authors=COPYRIGHT_AUTHORS
# use_config_parser_name=CONFIG_PARSER_NAME
)
memacs.handle_main()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from memacs.example import Foo
and context:
# Path: memacs/example.py
# class Foo(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# #self._parser.add_argument(
# # "-e", "--example", dest="example",
# # action="store_true",
# # help="path to a folder to search for filenametimestamps, " +
# # "multiple folders can be specified: -f /path1 -f /path2")
#
# #self._parser.add_argument(
# # "-i", "--int", dest="example_int",
# # action="store_true",
# # help="example2",
# # type=int)
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# # if self._args.example == ...:
# # self._parser.error("could not parse foo")
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
# # do all the stuff
#
# # if you need something from config:
# # attention: foo will be unicode
# # foo = self._get_config_option("foo")
#
# logging.info("foo started")
#
# # how to handle config files ?
# # sample config file:
# # ---------8<-----------
# # [memacs-example]
# # foo = 0
# # bar = 1
# # --------->8-----------
# # to read it out, just do following:
# # foo = self._get_config_option("foo")
# # bar = self._get_config_option("bar")
#
# # use logging.debug() for debug messages
# # use logging.error() for error messages
# # use logging.info() instead of print for informing user
# #
# # on an fatal error:
# # use logging.error() and sys.exit(1)
#
# timestamp = OrgFormat.date(time.gmtime(0), show_time=True)
# # note: timestamp has to be a struct_time object
#
# # Orgproperties
# # Option 1: no properties given, specify argument for hashing data
# properties = OrgProperties("hashing data :ALKJ!@# should be unique")
# # Option 2: add properties which are all-together unique
# # properties.add("Category","fun")
# # properties.add("from","me@example.com")
# # properties.add("body","foo")
#
# self._writer.write_org_subitem(timestamp=timestamp,
# output="foo",
# properties=properties)
#
# # writes following:
# #** <1970-01-01 Thu 00:00> foo
# # :PROPERTIES:
# # :ID: da39a3ee5e6b4b0d3255bfef95601890afd80709
# # :END:
#
# notes = "bar notes\nfoo notes"
#
# p = OrgProperties(data_for_hashing="read comment below")
# # if a hash is not unique only with its :PROPERTIES: , then
# # set data_for_hasing string additional information i.e. the output
# # , which then makes the hash really unique
# #
# # if you *really*, *really* have already a unique id,
# # then you can call following method:
# # p.set_id("unique id here")
#
# p.add("DESCRIPTION", "foooo")
# p.add("foo-property", "asdf")
#
# tags = ["tag1", "tag2"]
#
# self._writer.write_org_subitem(timestamp=timestamp,
# output="bar",
# note=notes,
# properties=p,
# tags=tags)
# # writes following:
# #** <1970-01-01 Thu 00:00> bar :tag1:tag2:
# # bar notes
# # foo notes
# # :PROPERTIES:
# # :DESCRIPTION: foooo
# # :FOO-PROPERTY: asdf
# # :ID: 97521347348df02dab8bf86fbb6817c0af333a3f
# # :END:
which might include code, classes, or functions. Output only the next line. | if __name__ == "__main__": |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2013-04-04 16:18:07 vk>
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2013-09-01"
PROG_SHORT_DESCRIPTION = "Memacs for Twitter "
PROG_TAG = "mytag"
PROG_DESCRIPTION = """
This Memacs module will process your Twitter timeline ....
sample config:
[memacs-twitter] <-- "memacs-example" has to be CONFIG_PARSER_NAME
APP_KEY =
APP_SECRET =
<|code_end|>
. Use current file imports:
(from memacs.twitter import Twitter)
and context including class names, function names, or small code snippets from other files:
# Path: memacs/twitter.py
# class Twitter(Memacs):
# def _main(self):
# APP_KEY = self._get_config_option("APP_KEY")
#
# APP_SECRET = self._get_config_option("APP_SECRET")
#
# OAUTH_TOKEN = self._get_config_option("OAUTH_TOKEN")
#
# OAUTH_TOKEN_SECRET = self._get_config_option("OAUTH_TOKEN_SECRET")
#
# screen_name = self._get_config_option("screen_name")
#
# count = self._get_config_option("count")
#
# twitter = Twython(
# APP_KEY,
# APP_SECRET,
# OAUTH_TOKEN,
# OAUTH_TOKEN_SECRET
# )
# try:
# home_timeline = twitter.get_home_timeline(screenname=screen_name, count=count)
#
# except TwythonError as e:
# logging.error(e)
# sys.exit(1)
#
# for tweet in home_timeline:
# # strptime doesn't support timezone info, so we are using dateutils.
# date_object = parser.parse(tweet['created_at'])
#
# timestamp = OrgFormat.date(date_object, show_time=True)
# try:
# # Data is already Unicode, so don't try to re-encode it.
# output = tweet['text']
# except:
# logging.error(sys.exc_info()[0])
# print("Error: ", sys.exc_info()[0])
#
# data_for_hashing = output + timestamp + output
# properties = OrgProperties(data_for_hashing=data_for_hashing)
#
# properties.add("name", tweet['user']['name'])
# properties.add("twitter_id", tweet['id'])
# properties.add("contributors", tweet['contributors'])
# properties.add("truncated", tweet['truncated'])
# properties.add("in_reply_to_status_id", tweet['in_reply_to_status_id'])
# properties.add("favorite_count", tweet['favorite_count'])
# properties.add("source", tweet['source'])
# properties.add("retweeted", tweet['retweeted'])
# properties.add("coordinates", tweet['coordinates'])
# properties.add("entities", tweet['entities'])
#
# self._writer.write_org_subitem(timestamp=timestamp,
# output = output,
# properties = properties)
. Output only the next line. | OAUTH_TOKEN = |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2013-04-04 16:18:40 vk>
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2011-12-20"
PROG_SHORT_DESCRIPTION = "Memacs for git files "
PROG_TAG = "git"
PROG_DESCRIPTION = """
This class will parse files from git rev-parse output
use following command to generate input file
<|code_end|>
. Use current file imports:
(from memacs.git import GitMemacs)
and context including class names, function names, or small code snippets from other files:
# Path: memacs/git.py
# class GitMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="gitrevfile",
# action="store",
# help="path to a an file which contains output from " + \
# " following git command: git rev-list --all --pretty=raw")
#
# self._parser.add_argument(
# "-g", "--grep-user", dest="grepuser",
# action="store",
# help="if you wanna parse only commit from a specific person. " + \
# "format:<Forname Lastname> of user to grep")
#
# self._parser.add_argument(
# "-e", "--encoding", dest="encoding",
# action="store",
# help="default encoding utf-8, see " + \
# "http://docs.python.org/library/codecs.html#standard-encodings" + \
# "for possible encodings")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if self._args.gitrevfile and not \
# (os.path.exists(self._args.gitrevfile) or \
# os.access(self._args.gitrevfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
# if not self._args.encoding:
# self._args.encoding = "utf-8"
#
# def get_line_from_stream(self, input_stream):
# try:
# return input_stream.readline()
# except UnicodeError as e:
# logging.error("Can't decode to encoding %s, " + \
# "use argument -e or --encoding see help",
# self._args.encoding)
# sys.exit(1)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# read the lines from git-rev-list file,parse and write them to org file
# """
#
# # read file
# if self._args.gitrevfile:
# logging.debug("using as %s input_stream",
# self._args.gitrevfile)
# input_stream = open(self._args.gitrevfile)
# else:
# logging.debug("using sys.stdin as input_stream")
# input_stream = sys.stdin
#
# # now go through the file
# # Logic (see example commit below)
# # first we are in an header and not in an body
# # every newline toggles output
# # if we are in body then add the body to commit class
# # if we are in header then add the header to commit class
# #
# # commit 6fb35035c5fa7ead66901073413a42742a323e89
# # tree 7027c628031b3ad07ad5401991f5a12aead8237a
# # parent 05ba138e6aa1481db2c815ddd2acb52d3597852f
# # author Armin Wieser <armin.wieser@example.com> 1324422878 +0100
# # committer Armin Wieser <armin.wieser@example.com> 1324422878 +0100
# #
# # PEP8
# # Signed-off-by: Armin Wieser <armin.wieser@gmail.com>
#
# was_in_body = False
# commit = Commit()
# commits = []
#
# line = self.get_line_from_stream(input_stream)
#
# while line:
# line = line.rstrip() # removing \n
# logging.debug("got line: %s", line)
# if line.strip() == "" or len(line) != len(line.lstrip()):
# commit.add_body(line)
# was_in_body = True
# else:
# if was_in_body:
# commits.append(commit)
# commit = Commit()
# commit.add_header(line)
# was_in_body = False
#
# line = self.get_line_from_stream(input_stream)
#
# # adding last commit
# if not commit.is_empty():
# commits.append(commit)
#
# logging.debug("got %d commits", len(commits))
# if len(commits) == 0:
# logging.error("Is there an error? Because i found no commits.")
#
# # time to write all commits to org-file
# for commit in commits:
# output, properties, note, author, timestamp = commit.get_output()
#
# if not(self._args.grepuser) or \
# (self._args.grepuser and self._args.grepuser == author):
# # only write to stream if
# # * grepuser is not set or
# # * grepuser is set and we got an entry with the right author
# self._writer.write_org_subitem(output=output,
# timestamp=timestamp,
# properties=properties,
# note=note)
#
# if self._args.gitrevfile:
# input_stream.close()
. Output only the next line. | $ git rev-list --all --pretty=raw > /path/to/input file |
Given snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2014-12-13 13:39:15 vk>
PROG_VERSION_NUMBER = "0.2"
PROG_VERSION_DATE = "2014-12-13"
PROG_SHORT_DESCRIPTION = "Memacs for sms"
PROG_TAG = "sms"
PROG_DESCRIPTION = """
This Memacs module will parse output of sms xml backup files
> A sample xml file you find in the documentation file memacs_sms.org.
Then an Org-mode file is generated.
"""
COPYRIGHT_YEAR = "2011-2014"
COPYRIGHT_AUTHORS = """Karl Voit <tools@Karl-Voit.at>,
Armin Wieser <armin.wieser@gmail.com>"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from memacs.sms import SmsMemacs
and context:
# Path: memacs/sms.py
# class SmsMemacs(Memacs):
#
# _numberdict = False
#
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="smsxmlfile",
# action="store", required=True,
# help="path to sms xml backup file")
#
# self._parser.add_argument(
# "--ignore-incoming", dest="ignore_incoming",
# action="store_true",
# help="ignore incoming smses")
#
# self._parser.add_argument(
# "--ignore-outgoing", dest="ignore_outgoing",
# action="store_true",
# help="ignore outgoing smses")
#
# self._parser.add_argument(
# "--orgcontactsfile", dest="orgcontactsfile",
# action="store", required=False,
# help="path to Org-contacts file for phone number lookup. Phone numbers have to match.")
#
#
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if not (os.path.exists(self._args.smsxmlfile) or \
# os.access(self._args.smsxmlfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
# if self._args.orgcontactsfile:
# if not (os.path.exists(self._args.orgcontactsfile) or \
# os.access(self._args.orgcontactsfile, os.R_OK)):
# self._parser.error("Org-contacts file not found or not readable")
# self._numberdict = parse_org_contact_file(self._args.orgcontactsfile)
#
#
# def _main(self):
# """
# get's automatically called from Memacs class
# read the lines from sms backup xml file,
# parse and write them to org file
# """
#
# ## replace HTML entities "&#" in original file to prevent XML parser from worrying:
# temp_xml_file = tempfile.mkstemp()[1]
# line_number = 0
# logging.debug("tempfile [%s]", str(temp_xml_file))
# with codecs.open(temp_xml_file, 'w', encoding='utf-8') as outputhandle:
# for line in codecs.open(self._args.smsxmlfile, 'r', encoding='utf-8'):
# try:
# ## NOTE: this is a dirty hack to prevent te XML parser from complainaing about
# ## encoding issues of UTF-8 encoded emojis. Will be reverted when parsing sms_body
# outputhandle.write(line.replace('&#', 'EnCoDiNgHaCk42') + '\n')
# except IOError as e:
# print("tempfile line " + str(line_number) + " [" + str(temp_xml_file) + "]")
# print("I/O error({0}): {1}".format(e.errno, e.strerror))
# except ValueError as e:
# print("tempfile line " + str(line_number) + " [" + str(temp_xml_file) + "]")
# print("Value error: {0}".format(e))
# #print "line [%s]" % str(line)
# except:
# print("tempfile line " + str(line_number) + " [" + str(temp_xml_file) + "]")
# print("Unexpected error:", sys.exc_info()[0])
# raise
#
# data = CommonReader.get_data_from_file(temp_xml_file)
#
# try:
# xml.sax.parseString(data.encode('utf-8'),
# SmsSaxHandler(self._writer,
# self._args.ignore_incoming,
# self._args.ignore_outgoing,
# self._numberdict))
# except SAXParseException:
# logging.error("No correct XML given")
# sys.exit(1)
# else:
# os.remove(temp_xml_file)
which might include code, classes, or functions. Output only the next line. | def main(): |
Based on the snippet: <|code_start|> argv.append("-f")
argv.append(example1)
argv.append("--fieldnames")
argv.append("date,text,value,currency,")
argv.append("--timestamp-field")
argv.append("date")
argv.append("--timestamp-format")
argv.append("%d.%m.%Y")
argv.append("--output-format")
argv.append("{text}")
argv.append("--properties")
argv.append("currency,value")
memacs = Csv(argv=argv)
data = memacs.test_get_entries()
self.assertEqual(data[0], "** <2012-02-23 Thu> Amazon")
self.assertEqual(data[1], " :PROPERTIES:")
self.assertEqual(data[2], " :CURRENCY: EUR")
self.assertEqual(data[3], " :VALUE: 100,00")
self.assertEqual(data[4], " :ID: a9cfa86bd9d89b72f35bfca0bb75131be0ca86b1")
self.assertEqual(data[5], " :END:")
def test_example2(self):
example1 = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data', 'example2.csv'
)
argv = []
argv.append("--delimiter")
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import unittest
from memacs.csv import Csv
and context (classes, functions, sometimes code) from other files:
# Path: memacs/csv.py
# class Csv(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="csvfile", required=True,
# action="store", help="input csv file", type=argparse.FileType('rb'))
#
# self._parser.add_argument(
# "-d", "--delimiter", dest="delimiter", default=";",
# action="store", help='delimiter, default ";"')
#
# self._parser.add_argument(
# "-e", "--encoding", dest="encoding",
# action="store", default="utf-8", help="default encoding utf-8, " +
# "see http://docs.python.org/library/codecs.html#standard-encodings" +
# "for possible encodings")
#
# self._parser.add_argument(
# "-n", "--fieldnames", dest="fieldnames", default=None,
# action="store", help="header field names of the columns",
# type=str.lower)
#
# self._parser.add_argument(
# "-p", "--properties", dest="properties", default='',
# action="store", help="fields to use for properties",
# type=str.lower)
#
# self._parser.add_argument(
# "--timestamp-field", dest="timestamp_field", required=True,
# action="store", help="field name of the timestamp",
# type=str.lower)
#
# self._parser.add_argument(
# "--timestamp-format", dest="timestamp_format",
# action="store", help='format of the timestamp, i.e. ' +
# '"%d.%m.%Y %H:%M:%S" for "14.02.2012 10:22:37" ' +
# 'see http://docs.python.org/library/time.html#time.strftime' +
# 'for possible formats, default unix timestamp')
#
# self._parser.add_argument(
# "--output-format", dest="output_format", required=True,
# action="store", help="format string to use for the output")
#
# self._parser.add_argument(
# "--skip-header", dest="skip_header",
# action="store_true", help="skip first line of the csv file")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
#
# if self._args.fieldnames:
# self._args.fieldnames = [name.strip() for name in self._args.fieldnames.split(',')]
#
# def _handle_row(self, row):
# """
# handle a single row
# """
#
# try:
# # assume unix timestamp
# if not self._args.timestamp_format:
# timestamp = datetime.datetime.fromtimestamp(int(row[self._args.timestamp_field]))
# else:
# timestamp = time.strptime(row[self._args.timestamp_field], self._args.timestamp_format)
#
# # show time with the timestamp format, but only
# # if it contains at least hours and minutes
# if not self._args.timestamp_format or \
# any(x in self._args.timestamp_format for x in ['%H', '%M']):
# timestamp = OrgFormat.date(timestamp, show_time=True)
# else:
# timestamp = OrgFormat.date(timestamp)
#
# except ValueError as e:
# logging.error("timestamp-format does not match: %s", e)
# sys.exit(1)
#
# except IndexError as e:
# logging.error("did you specify the right delimiter?", e)
# sys.exit(1)
#
# properties = OrgProperties(data_for_hashing=json.dumps(row))
# output = self._args.output_format.format(**row)
#
# if self._args.properties:
# for prop in self._args.properties.split(','):
# properties.add(prop.upper().strip(), row[prop])
#
# self._writer.write_org_subitem(timestamp=timestamp,
# output=output,
# properties=properties)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
#
# with self._args.csvfile as f:
#
# try:
# reader = UnicodeDictReader(f,
# self._args.delimiter,
# self._args.encoding,
# self._args.fieldnames)
#
# if self._args.skip_header:
# next(reader)
#
# for row in reader:
# self._handle_row(row)
# logging.debug(row)
#
# except TypeError as e:
# logging.error("not enough fieldnames or wrong delimiter given")
# logging.debug("Error: %s" % e)
# sys.exit(1)
#
# except UnicodeDecodeError as e:
# logging.error("could not decode file in utf-8, please specify input encoding")
# sys.exit(1)
. Output only the next line. | argv.append("|") |
Continue the code snippet: <|code_start|>
def test_false_appending(self):
try:
memacs = RssMemacs(argv=self.argv.split())
memacs.test_get_entries()
except Exception:
pass
def test_all(self):
memacs = RssMemacs(argv=self.argv.split())
data = memacs.test_get_entries()
# omit the hour from the result because this depends on the current locals:
self.assertTrue(data[0].startswith('** <2009-09-06 Sun '))
self.assertTrue(data[0].endswith(':45> [[http://www.wikipedia.org/][Example entry]]'))
self.assertEqual(
data[2],
" :GUID: unique string per item")
self.assertEqual(
data[3],
' :PUBLISHED: Mon, 06 Sep 2009 16:45:00 +0000'
)
self.assertEqual(
data[4],
" :ID: a0df7d405a7e9822fdd86af04e162663f1dccf11"
)
self.assertEqual(
data[6],
" Here is some text containing an interesting description."
<|code_end|>
. Use current file imports:
import os
import unittest
from memacs.rss import RssMemacs
and context (classes, functions, or code) from other files:
# Path: memacs/rss.py
# class RssMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-u", "--url", dest="url",
# action="store",
# help="url to a rss file")
#
# self._parser.add_argument(
# "-f", "--file", dest="file",
# action="store",
# help="path to rss file")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if self._args.url and self._args.file:
# self._parser.error("you cannot set both url and file")
#
# if not self._args.url and not self._args.file:
# self._parser.error("please specify a file or url")
#
# if self._args.file:
# if not os.path.exists(self._args.file):
# self._parser.error("file %s not readable", self._args.file)
# if not os.access(self._args.file, os.R_OK):
# self._parser.error("file %s not readable", self._args.file)
#
# def __get_item_data(self, item):
# """
# gets information out of <item>..</item>
#
# @return: output, note, properties, tags
# variables for orgwriter.append_org_subitem
# """
# try:
# # logging.debug(item)
# properties = OrgProperties()
# guid = item['id']
# if not guid:
# logging.error("got no id")
#
# unformatted_link = item['link']
# short_link = OrgFormat.link(unformatted_link, "link")
#
# # if we found a url in title
# # then append the url in front of subject
# if re.search("http[s]?://", item['title']) is not None:
# output = short_link + ": " + item['title']
# else:
# output = OrgFormat.link(unformatted_link, item['title'])
#
# note = item['description']
#
# # converting updated_parsed UTC --> LOCALTIME
# # Karl 2018-09-22 this might be changed due to:
# # DeprecationWarning: To avoid breaking existing software
# # while fixing issue 310, a temporary mapping has been
# # created from `updated_parsed` to `published_parsed` if
# # `updated_parsed` doesn't exist. This fallback will be
# # removed in a future version of feedparser.
# timestamp = OrgFormat.date(
# time.localtime(calendar.timegm(item['updated_parsed'])), show_time=True)
#
# properties.add("guid", guid)
#
# except KeyError:
# logging.error("input is not a RSS 2.0")
# sys.exit(1)
#
# tags = []
# # Karl 2018-09-22 this might be changed due to:
# # DeprecationWarning: To avoid breaking existing software
# # while fixing issue 310, a temporary mapping has been created
# # from `updated_parsed` to `published_parsed` if
# # `updated_parsed` doesn't exist. This fallback will be
# # removed in a future version of feedparser.
# dont_parse = ['title', 'description', 'updated', 'summary',
# 'updated_parsed', 'link', 'links']
# for i in item:
# logging.debug(i)
# if i not in dont_parse:
# if (type(i) == str or type(i) == str) and \
# type(item[i]) == str and item[i] != "":
# if i == "id":
# i = "guid"
# properties.add(i, item[i])
# else:
# if i == "tags":
# for tag in item[i]:
# logging.debug("found tag: %s", tag['term'])
# tags.append(tag['term'])
#
# return output, note, properties, tags, timestamp
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
# # getting data
# if self._args.file:
# data = CommonReader.get_data_from_file(self._args.file)
# elif self._args.url:
# data = CommonReader.get_data_from_url(self._args.url)
#
# rss = feedparser.parse(data)
# logging.info("title: %s", rss['feed']['title'])
# logging.info("there are: %d entries", len(rss.entries))
#
# for item in rss.entries:
# logging.debug(item)
# output, note, properties, tags, timestamp = \
# self.__get_item_data(item)
# self._writer.write_org_subitem(output=output,
# timestamp=timestamp,
# note=note,
# properties=properties,
# tags=tags)
. Output only the next line. | ) |
Next line prediction: <|code_start|>This Memacs module will parse output of phonecalls xml backup files
sample xml file:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<calls count="8">
<call number="+43691234123" duration="59" date="1312563906092" type="1" />
<call number="06612341234" duration="22" date="1312541215834" type="2" />
<call number="-1" duration="382" date="1312530691081" type="1" />
<call number="+4312341234" duration="289" date="1312482327195" type="1" />
<call number="+4366412341234" duration="70" date="1312476334059" type="1" />
<call number="+4366234123" duration="0" date="1312473751975" type="2" />
<call number="+436612341234" duration="0" date="1312471300072" type="3" />
<call number="+433123412" duration="60" date="1312468562489" type="2" />
</calls>
Then an Org-mode file is generated.
"""
COPYRIGHT_YEAR = "2011-2013"
COPYRIGHT_AUTHORS = """Karl Voit <tools@Karl-Voit.at>,
Armin Wieser <armin.wieser@gmail.com>"""
def main():
global memacs
memacs = PhonecallsMemacs(
prog_version=PROG_VERSION_NUMBER,
prog_version_date=PROG_VERSION_DATE,
prog_description=PROG_DESCRIPTION,
prog_short_description=PROG_SHORT_DESCRIPTION,
prog_tag=PROG_TAG,
<|code_end|>
. Use current file imports:
(from memacs.phonecalls import PhonecallsMemacs)
and context including class names, function names, or small code snippets from other files:
# Path: memacs/phonecalls.py
# class PhonecallsMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="smsxmlfile",
# action="store", required=True,
# help="path to sms xml backup file")
#
# self._parser.add_argument(
# "--ignore-incoming", dest="ignore_incoming",
# action="store_true",
# help="ignore incoming phonecalls")
#
# self._parser.add_argument(
# "--ignore-outgoing", dest="ignore_outgoing",
# action="store_true",
# help="ignore outgoing phonecalls")
#
# self._parser.add_argument(
# "--ignore-missed", dest="ignore_missed",
# action="store_true",
# help="ignore outgoing phonecalls")
#
# self._parser.add_argument(
# "--ignore-cancelled", dest="ignore_cancelled",
# action="store_true",
# help="ignore cancelled phonecalls")
#
# self._parser.add_argument(
# "--minimum-duration", dest="minimum_duration",
# action="store", type=int,
# help="[sec] show only calls with duration >= this argument")
#
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if not (os.path.exists(self._args.smsxmlfile) or \
# os.access(self._args.smsxmlfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
#
# def _main(self):
# """
# gets called automatically from Memacs class.
# read the lines from phonecalls backup xml file,
# parse and write them to org file
# """
#
# data = CommonReader.get_data_from_file(self._args.smsxmlfile)
#
# try:
# xml.sax.parseString(data.encode('utf-8'),
# PhonecallsSaxHandler(self._writer,
# self._args.ignore_incoming,
# self._args.ignore_outgoing,
# self._args.ignore_missed,
# self._args.ignore_cancelled,
# self._args.minimum_duration or 0,
# ))
# except SAXParseException:
# logging.error("No correct XML given")
# sys.exit(1)
. Output only the next line. | copyright_year=COPYRIGHT_YEAR, |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2013-04-04 16:20:01 vk>
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2011-12-27"
PROG_SHORT_DESCRIPTION = "Memacs for svn"
PROG_TAG = "svn"
PROG_DESCRIPTION = """
This Memacs module will parse output of svn log --xml
sample xml:
<?xml version="1.0"?>
<log>
<logentry
revision="13">
<author>bob</author>
<date>2011-11-05T18:18:22.936127Z</date>
<msg>Bugfix.</msg>
</logentry>
<|code_end|>
. Write the next line using the current file imports:
from memacs.svn import SvnMemacs
and context from other files:
# Path: memacs/svn.py
# class SvnMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="svnlogxmlfile",
# action="store",
# help="path to a an file which contains output from " + \
# " following svn command: svn log --xml")
#
# self._parser.add_argument(
# "-g", "--grep-author", dest="grepauthor",
# action="store",
# help="if you wanna parse only messages from a specific person. " + \
# "format:<author> of author to grep")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if self._args.svnlogxmlfile and not \
# (os.path.exists(self._args.svnlogxmlfile) or \
# os.access(self._args.svnlogxmlfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
# def _main(self):
# """
# get's automatically called from Memacs class
# read the lines from svn xml file, parse and write them to org file
# """
#
# # read file
# if self._args.svnlogxmlfile:
# logging.debug("using as %s input_stream", self._args.svnlogxmlfile)
# data = CommonReader.get_data_from_file(self._args.svnlogxmlfile)
# else:
# logging.info("Using stdin as input_stream")
# data = CommonReader.get_data_from_stdin()
#
# try:
# xml.sax.parseString(data.encode('utf-8'),
# SvnSaxHandler(self._writer,
# self._args.grepauthor))
# except SAXParseException:
# logging.error("No correct XML given")
# sys.exit(1)
, which may include functions, classes, or code. Output only the next line. | </log> |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
CONFIG_PARSER_NAME="memacs-lastfm"
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2017-02-24"
PROG_SHORT_DESCRIPTION = "Memacs for lastfm"
PROG_TAG = "lastfm"
COPYRIGHT_YEAR = "2017"
COPYRIGHT_AUTHORS = """Manuel Koell <mankoell@gmail.com>"""
def main():
global memacs
memacs = LastFM(
prog_version=PROG_VERSION_NUMBER,
prog_version_date=PROG_VERSION_DATE,
prog_short_description=PROG_SHORT_DESCRIPTION,
prog_tag=PROG_TAG,
copyright_year=COPYRIGHT_YEAR,
copyright_authors=COPYRIGHT_AUTHORS,
<|code_end|>
. Write the next line using the current file imports:
from memacs.lastfm import LastFM
and context from other files:
# Path: memacs/lastfm.py
# class LastFM(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# '--output-format', dest='output_format',
# action='store', default='{title}',
# help='formt string to use for the output'
# )
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
#
# if self._args.output_format:
# self._args.output_format = self._args.output_format
#
# def _handle_recent_tracks(self, tracks):
# """parse recent tracks"""
# logging.debug(tracks)
#
# for t in tracks:
# timestamp = datetime.datetime.fromtimestamp(int(t.timestamp))
#
# output = self._args.output_format.format(title=t.track.title,
# artist=t.track.artist,
# album=t.album)
#
# properties = OrgProperties(data_for_hashing=t.timestamp)
# properties.add('ARTIST', t.track.artist)
# properties.add('ALBUM', t.album)
#
# self._writer.write_org_subitem(timestamp=OrgFormat.date(timestamp, show_time=True),
# output=output,
# properties=properties)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
#
# options = {
# 'api_secret': self._get_config_option('api_secret'),
# 'api_key': self._get_config_option('api_key'),
# 'password_hash': pylast.md5(self._get_config_option('password')),
# 'username': self._get_config_option('username')
# }
#
# try:
#
# if 'lastfm' in self._get_config_option('network'):
# network = pylast.LastFMNetwork(**options)
#
# if 'librefm' in self._get_config_option('network'):
# network = pylast.LibreFMNetwork(**options)
#
# user = network.get_user(options['username'])
#
# self._handle_recent_tracks(user.get_recent_tracks(limit=100))
#
# except pylast.WSError as e:
# logging.error('an issue with the network web service occured: %s' % e)
# sys.exit(1)
, which may include functions, classes, or code. Output only the next line. | use_config_parser_name=CONFIG_PARSER_NAME |
Using the snippet: <|code_start|>sample xml file:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<calls count="8">
<call number="+43691234123" duration="59" date="1312563906092" type="1" />
<call number="06612341234" duration="22" date="1312541215834" type="2" />
<call number="-1" duration="382" date="1312530691081" type="1" />
<call number="+4312341234" duration="289" date="1312482327195" type="1" />
<call number="+4366412341234" duration="70" date="1312476334059" type="1" />
<call number="+4366234123" duration="0" date="1312473751975" type="2" />
<call number="+436612341234" duration="0" date="1312471300072" type="3" />
<call number="+433123412" duration="60" date="1312468562489" type="2" />
</calls>
Then an Org-mode file is generated.
"""
COPYRIGHT_YEAR = "2011-2013"
COPYRIGHT_AUTHORS = """Karl Voit <tools@Karl-Voit.at>,
Armin Wieser <armin.wieser@gmail.com>
Ian Barton <ian@manor-farm.org>"""
def main():
global memacs
memacs = PhonecallsSuperBackupMemacs(
prog_version=PROG_VERSION_NUMBER,
prog_version_date=PROG_VERSION_DATE,
prog_description=PROG_DESCRIPTION,
prog_short_description=PROG_SHORT_DESCRIPTION,
prog_tag=PROG_TAG,
copyright_year=COPYRIGHT_YEAR,
<|code_end|>
, determine the next line of code. You have imports:
from memacs.phonecalls_superbackup import PhonecallsSuperBackupMemacs
and context (class names, function names, or code) available:
# Path: memacs/phonecalls_superbackup.py
# class PhonecallsSuperBackupMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="smsxmlfile",
# action="store", required=True,
# help="path to sms xml backup file")
#
# self._parser.add_argument(
# "--ignore-incoming", dest="ignore_incoming",
# action="store_true",
# help="ignore incoming phonecalls")
#
# self._parser.add_argument(
# "--ignore-outgoing", dest="ignore_outgoing",
# action="store_true",
# help="ignore outgoing phonecalls")
#
# self._parser.add_argument(
# "--ignore-missed", dest="ignore_missed",
# action="store_true",
# help="ignore outgoing phonecalls")
#
# self._parser.add_argument(
# "--ignore-voicemail", dest="ignore_voicemail",
# action="store_true",
# help="ignore voicemail phonecalls")
#
# self._parser.add_argument(
# "--ignore-rejected", dest="ignore_rejected",
# action="store_true",
# help="ignore rejected phonecalls")
#
# self._parser.add_argument(
# "--ignore-refused", dest="ignore_refused",
# action="store_true",
# help="ignore refused phonecalls")
#
# self._parser.add_argument(
# "--minimum-duration", dest="minimum_duration",
# action="store", type=int,
# help="[sec] show only calls with duration >= this argument")
#
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if not (os.path.exists(self._args.smsxmlfile) or \
# os.access(self._args.smsxmlfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
#
# def _main(self):
# """
# gets called automatically from Memacs class.
# read the lines from phonecalls backup xml file,
# parse and write them to org file
# """
#
# data = CommonReader.get_data_from_file(self._args.smsxmlfile)
#
# try:
# xml.sax.parseString(data.encode('utf-8'),
# PhonecallsSaxHandler(self._writer,
# self._args.ignore_incoming,
# self._args.ignore_outgoing,
# self._args.ignore_missed,
# self._args.ignore_voicemail,
# self._args.ignore_rejected,
# self._args.ignore_refused,
# self._args.minimum_duration or 0,
# ))
# except SAXParseException:
# logging.error("No correct XML given")
# sys.exit(1)
. Output only the next line. | copyright_authors=COPYRIGHT_AUTHORS |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2017-03-02"
PROG_SHORT_DESCRIPTION = "Memacs for GPX files"
PROG_TAG = "gps"
COPYRIGHT_YEAR = "2017"
<|code_end|>
, generate the next line using the imports in this file:
from memacs.gpx import GPX
and context (functions, classes, or occasionally code) from other files:
# Path: memacs/gpx.py
# class GPX(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--folder", dest="source",
# action="store", required=True,
# help="path to gpx file or folder")
#
# self._parser.add_argument(
# "-p", "--provider", dest="provider",
# action="store", default="google",
# help="geocode provider, default google")
#
# self._parser.add_argument(
# "-u", "--url", dest="url",
# action="store", help="url to nominatim server (osm only)")
#
# self._parser.add_argument(
# "--output-format", dest="output_format",
# action="store", default="{address}",
# help="format string to use for the headline")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
#
# if not os.path.exists(self._args.source):
# self._parser.error("source file or folder does not exist")
#
# if self._args.url and not self._args.url.startswith("http"):
# self._parser.error("invalid url given")
#
# def reverse_geocode(self, lat, lng):
# """get address for latitude/longitude"""
#
# if 'google' in self._args.provider:
# geocode = geocoder.google([lat, lng], method='reverse')
#
# elif 'osm' in self._args.provider:
# if not self._args.url:
# geocode = geocoder.osm([lat, lng], method='reverse')
# time.sleep(1) # Nominatim Usage Policy
# else:
# if 'localhost' in self._args.url:
# geocode = geocoder.osm([lat, lng], method='reverse', url='http://localhost/nominatim/search')
# else:
# geocode = geocoder.osm([lat, lng], method='reverse', url=self._args.url)
#
# else:
# self._parser.error("invalid provider given")
# raise ValueError('invalid provider given')
#
# if not geocode.ok:
# logging.error("geocoding failed or api limit exceeded")
# raise RuntimeError('geocoding failed or api limit exceeded')
# else:
# logging.debug(geocode.json)
# return geocode.json
#
# def write_point(self, p):
# """write a point (including geocoding)"""
#
# timestamp = OrgFormat.date(p.time, show_time=True)
# geocode = self.reverse_geocode(p.latitude, p.longitude)
# output = self._args.output_format.format(**geocode)
#
# tags = []
#
# properties = OrgProperties(data_for_hashing=timestamp)
#
# if p.latitude:
# properties.add('LATITUDE', p.latitude)
#
# if p.longitude:
# properties.add('LONGITUDE', p.longitude)
#
# if p.source:
# tags.append(p.source.lower())
#
# if timestamp:
# self._writer.write_org_subitem(timestamp=timestamp,
# output=output,
# properties=properties,
# tags=tags)
#
# def handle_file(self, f):
# """iterate through a file"""
#
# data = open(f)
# gpx = gpxpy.parse(data)
#
# for track in gpx.tracks:
# for segment in track.segments:
# for point in segment.points:
# self.write_point(point)
# logging.debug(point)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
#
# if os.path.isfile(self._args.source):
# self.handle_file(self._args.source)
#
# else:
# for root, dirs, files in os.walk(self._args.source):
# for f in files:
# if f.endswith('.gpx'):
# self.handle_file(os.path.join(root, f))
. Output only the next line. | COPYRIGHT_AUTHORS = """Manuel Koell <mankoell@gmail.com>""" |
Continue the code snippet: <|code_start|> self.assertTrue(
data[16].endswith(':41> group-5 (r2): 5.tex')
)
self.assertEqual(
data[17],
" :PROPERTIES:")
self.assertEqual(
data[18],
" :REVISION: 2")
self.assertEqual(
data[19],
" :ID: f45be418de175ccf56e960a6941c9973094ab9e3")
self.assertEqual(
data[20],
" :END:")
# omit the hours when comparing the results since this is depending on the locales:
self.assertTrue(
data[21].startswith('** <2011-10-27 Thu ')
)
self.assertTrue(
data[21].endswith(':44> group-5 (r1): initial files')
)
self.assertEqual(
data[22],
" :PROPERTIES:")
self.assertEqual(
data[23],
" :REVISION: 1")
self.assertEqual(
data[24],
<|code_end|>
. Use current file imports:
import os
import unittest
from memacs.svn import SvnMemacs
and context (classes, functions, or code) from other files:
# Path: memacs/svn.py
# class SvnMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="svnlogxmlfile",
# action="store",
# help="path to a an file which contains output from " + \
# " following svn command: svn log --xml")
#
# self._parser.add_argument(
# "-g", "--grep-author", dest="grepauthor",
# action="store",
# help="if you wanna parse only messages from a specific person. " + \
# "format:<author> of author to grep")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if self._args.svnlogxmlfile and not \
# (os.path.exists(self._args.svnlogxmlfile) or \
# os.access(self._args.svnlogxmlfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
# def _main(self):
# """
# get's automatically called from Memacs class
# read the lines from svn xml file, parse and write them to org file
# """
#
# # read file
# if self._args.svnlogxmlfile:
# logging.debug("using as %s input_stream", self._args.svnlogxmlfile)
# data = CommonReader.get_data_from_file(self._args.svnlogxmlfile)
# else:
# logging.info("Using stdin as input_stream")
# data = CommonReader.get_data_from_stdin()
#
# try:
# xml.sax.parseString(data.encode('utf-8'),
# SvnSaxHandler(self._writer,
# self._args.grepauthor))
# except SAXParseException:
# logging.error("No correct XML given")
# sys.exit(1)
. Output only the next line. | " :ID: 9b7d570e2dc4fb3a009461714358c35cbe24a8fd") |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2015-04-30 17:12:02 vs>
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2015-03-08"
PROG_SHORT_DESCRIPTION = "Memacs for Mu Mails"
PROG_TAG = "emails:mumail"
PROG_DESCRIPTION = """This memacs module will connect mu mail database,
fetch all mails and writes them to an orgfile.
"""
CONFIG_PARSER_NAME = ""
COPYRIGHT_YEAR = "2011-2015"
COPYRIGHT_AUTHORS = """Karl Voit <tools@Karl-Voit.at>,
Stephanus Volke <post@stephanus-volke.de>"""
def main():
global memacs
memacs = MuMail(
prog_version=PROG_VERSION_NUMBER,
prog_version_date=PROG_VERSION_DATE,
prog_description=PROG_DESCRIPTION,
prog_short_description=PROG_SHORT_DESCRIPTION,
prog_tag=PROG_TAG,
copyright_year=COPYRIGHT_YEAR,
<|code_end|>
, generate the next line using the imports in this file:
from memacs.mu import MuMail
and context (functions, classes, or occasionally code) from other files:
# Path: memacs/mu.py
# class MuMail(Memacs):
#
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-q", "--query",
# dest="query",
# help="mu search query")
#
# self._parser.add_argument(
# "-m", "--me",
# dest="sender",
# help="space seperated list of mail addresses that belongs to you")
#
# self._parser.add_argument(
# "-d", "--delegation",
# dest="todo",
# action='store_true',
# help="adds NEXT or WAITING state to flagged messages")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
#
# self._query = []
#
# if self._args.sender:
# self._args.sendern = self._args.sender.strip()
# self._sender = list(self._args.sender.split(" "))
# else:
# raise ValueError('You have to specify at least one e mail adress')
#
# if self._args.query:
# self._query = self._args.query
#
# if self._args.todo:
# self._todo = True
# else:
# self._todo = False
#
# def __parse_Plain(self,plain_mails):
# messages = plain_mails.decode('utf-8')
# return messages.splitlines()
#
# def __getTimestamp(self, time, onlyDate=False):
# """
# converts xml timestamp into org readable timestamp
# Do 6 Nov 21:22:17 2014
# """
# time = time.strip()
#
# mail_date = datetime.strptime(time,"%c")
# if onlyDate is False:
# return OrgFormat.date(mail_date, show_time=True)
# return OrgFormat.date(mail_date)
#
# def __create_mail_link(self, sender):
# """
# creates well formated org mail link from message 'from' field.
# """
# rex = re.compile('([\w\s.,-]*?)[\s<"]*([\w.-]+@[\w.-]+)',re.UNICODE)
# m = rex.search(sender)
# if m:
# name = m.group(1).strip()
# mail = m.group(2).strip()
# if name is not "":
# return ("[[mailto:" + mail + "][" + name + "]]",name,mail)
# else:
# return ("[[mailto:" + mail + "][" + mail + "]]",name,mail)
# return ("Unknown","Unknown","Unknown")
#
#
# def _main(self):
# """
# get's automatically called from Memacs class
# fetches all mails out of mu database
# """
# command = self._query
# # command.extend(self._query)
# command = command+" --fields=t:#:d:#:f:#:g:#:s:#:i --format=plain"
# try:
# xml_mails = subprocess.check_output(command, shell=True)
# except:
# print("something goes wrong")
# exit()
# messages = self.__parse_Plain(xml_mails)
#
# properties = OrgProperties()
# for message in messages:
# (an,datum,von,flags,betreff,msgid) = message.split(":#:")
# betreff = betreff.replace("[","<")
# betreff = betreff.replace("]",">")
# properties.add('TO',an)
# if von != "":
# (sender,vname,vmail) = self.__create_mail_link(von)
# (an,aname,amail) = self.__create_mail_link(an)
# timestamp = self.__getTimestamp(datum)
# properties.add_data_for_hashing(timestamp + "_" + msgid)
# properties.add("FROM",sender)
# notes = ""
# if any(match in vmail for match in self._sender):
# output = output = "".join(["T: ",an,": [[mu4e:msgid:",msgid,"][",betreff,"]]"])
# pre = 'WAITING '
# else:
# output = "".join(["F: ",sender,": [[mu4e:msgid:",msgid,"][",betreff,"]]"])
# pre = 'NEXT '
# if (flags.find('F') >= 0 and self._todo):
# date = self.__getTimestamp(datum,True)
# notes = "SCHEDULED: "+date
# timestamp = ""
# output = pre+output
# self._writer.write_org_subitem(timestamp, output, notes, properties)
. Output only the next line. | copyright_authors=COPYRIGHT_AUTHORS, |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
# Time-stamp: <2013-10-03 15:18:07 br>
PROG_VERSION_NUMBER = "0.0"
PROG_VERSION_DATE = "2018-10-02"
PROG_SHORT_DESCRIPTION = "Memacs for chrome url history "
PROG_TAG = "chrome"
PROG_DESCRIPTION = """
This class will parse chrome history file (History) and
produce an org file with all your visited sites
"""
# set CONFIG_PARSER_NAME only, when you want to have a config file
# otherwise you can comment it out
# CONFIG_PARSER_NAME="memacs-example"
COPYRIGHT_YEAR = "2018"
COPYRIGHT_AUTHORS = """Bala Ramadurai <bala@balaramadurai.net>"""
def main():
global memacs
memacs = Chrome(
prog_version=PROG_VERSION_NUMBER,
prog_version_date=PROG_VERSION_DATE,
prog_description=PROG_DESCRIPTION,
prog_short_description=PROG_SHORT_DESCRIPTION,
prog_tag=PROG_TAG,
copyright_year=COPYRIGHT_YEAR,
copyright_authors=COPYRIGHT_AUTHORS
)
<|code_end|>
, predict the next line using imports from the current file:
from memacs.chrome import Chrome
and context including class names, function names, and sometimes code from other files:
# Path: memacs/chrome.py
# class Chrome(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="historystore",
# action="store", type=open, required=True,
# help="""path to Google Chrome History sqlite file. usually in
# /home/bala/.config/google-chrome/Default/History """)
#
# self._parser.add_argument(
# "--output-format", dest="output_format",
# action="store", default="[[{url}][{title}]]",
# help="format string to use for the headline")
#
# self._parser.add_argument(
# "--omit-drawer", dest="omit_drawer",
# action="store_true", required=False,
# help="""Use a minimal output format that omits the PROPERTIES drawer.""")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
#
# def _handle_url(self, params):
# epoch = datetime.datetime(1970, 1, 1)-datetime.datetime(1601, 1, 1)
# url_time = params['timestamp']/1000000-epoch.total_seconds()
#
# if (url_time > 0) :
# timestamp = datetime.datetime.fromtimestamp(int(url_time))
# else:
# timestamp = datetime.datetime(1970, 1, 1)
#
# if not self._args.omit_drawer:
# properties = OrgProperties()
# if (params['title'] == "") :
# params['title'] = params['url']
# properties.add('URL', params['url'])
# properties.add('VISIT_COUNT', params['visit_count'])
#
# output = OrgFormat.link(params['url'], params['title'])
# try:
# output = self._args.output_format.decode('utf-8').format(**params)
# except Exception:
# pass
#
# if self._args.omit_drawer:
# self._writer.write_org_subitem(
# timestamp=OrgFormat.date(timestamp, show_time=True),
# output=output, properties=None)
# else:
# self._writer.write_org_subitem(
# timestamp=OrgFormat.date(timestamp, show_time=True),
# output=output, properties=properties)
#
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
# conn = sqlite3.connect(os.path.abspath(self._args.historystore.name))
# query = conn.execute("""
# select url, title, visit_count,
# last_visit_time
# from urls
# where last_visit_time IS NOT NULL
# order by last_visit_time """)
#
# for row in query:
# self._handle_url({
# 'url' : row[0],
# 'title' : row[1],
# 'visit_count' : row[2],
# 'timestamp' : row[3],
# })
. Output only the next line. | memacs.handle_main() |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2017-02-28"
PROG_SHORT_DESCRIPTION = "Memacs for whatsapp"
PROG_TAG = "whatsapp"
COPYRIGHT_YEAR = "2017"
COPYRIGHT_AUTHORS = """Manuel Koell <mankoell@gmail.com>"""
def main():
memacs = WhatsApp(
prog_version=PROG_VERSION_NUMBER,
prog_version_date=PROG_VERSION_DATE,
prog_short_description=PROG_SHORT_DESCRIPTION,
prog_tag=PROG_TAG,
copyright_year=COPYRIGHT_YEAR,
copyright_authors=COPYRIGHT_AUTHORS
<|code_end|>
. Write the next line using the current file imports:
from memacs.whatsapp import WhatsApp
and context from other files:
# Path: memacs/whatsapp.py
# class WhatsApp(Memacs):
#
#
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="msgstore",
# action="store", type=open, required=True,
# help="path to decrypted msgstore.db file")
#
# self._parser.add_argument(
# "--ignore-incoming", dest="ignore_incoming",
# action="store_true", help="ignore received messages")
#
# self._parser.add_argument(
# "--ignore-outgoing", dest="ignore_outgoing",
# action="store_true", help="ignore sent messages")
#
# self._parser.add_argument(
# "--ignore-groups", dest="ignore_groups",
# action="store_true",help="ignore group messages")
#
# self._parser.add_argument(
# "--output-format", dest="output_format",
# action="store", default="{verb} [[{handler}:{name}][{name}]]: {text}",
# help="format string to use for the headline")
#
# self._parser.add_argument(
# "--set-handler", dest="handler",
# action="store", default="tel",
# help="set link handler")
#
# self._parser.add_argument(
# "--demojize", dest="demojize",
# action="store_true", help="replace emoji with the appropriate :shortcode:")
#
# self._parser.add_argument(
# "--skip-emoji", dest="skip_emoji",
# action="store_true", help="skip all emoji")
#
# self._parser.add_argument(
# "--orgcontactsfile", dest="orgcontactsfile",
# action="store", required=False,
# help="path to Org-contacts file for phone number lookup. Phone numbers have to match.")
#
#
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if self._args.orgcontactsfile:
# if not (os.path.exists(self._args.orgcontactsfile) or \
# os.access(self._args.orgcontactsfile, os.R_OK)):
# self._parser.error("Org-contacts file not found or not readable")
# self._numberdict = parse_org_contact_file(self._args.orgcontactsfile)
# else:
# self._numberdict = {}
#
# def _is_ignored(self, msg):
# """check for ignored message type"""
#
# if msg['type'] is 'INCOMING' and self._args.ignore_incoming:
# return True
#
# if msg['type'] is 'OUTGOING' and self._args.ignore_outgoing:
# return True
#
# group_message_regex = r'-[0-9]{10}'
# if self._args.ignore_groups and re.findall(group_message_regex, msg['number']):
# return True
#
# def _handle_message(self, msg):
# """parse a single message row"""
#
# msg['number'] = '00' + msg['number'].split('@')[0]
# msg['name'] = self._numberdict.get(msg['number'],msg['number'])
# msg['verb'] = 'to' if msg['type'] else 'from'
# msg['type'] = 'OUTGOING' if msg['type'] else 'INCOMING'
# msg['handler'] = self._args.handler
#
# if msg['text']:
# if self._args.demojize:
# msg['text'] = emoji.demojize(msg['text'])
#
# if self._args.skip_emoji:
# msg['text'] = re.sub(emoji.get_emoji_regexp(), '', msg['text'])
#
# timestamp = datetime.datetime.fromtimestamp(msg['timestamp'] / 1000)
#
# properties = OrgProperties(data_for_hashing=json.dumps(msg))
# properties.add('NUMBER', msg['number'])
# properties.add('TYPE', msg['type'])
#
# output = self._args.output_format.format(**msg)
#
# if msg['text'] and not self._is_ignored(msg):
# self._writer.write_org_subitem(timestamp=OrgFormat.date(timestamp, show_time=True),
# output=output, properties=properties)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
#
# conn = sqlite3.connect(os.path.abspath(self._args.msgstore.name))
# query = conn.execute('SELECT * FROM messages')
#
# for row in query:
# self._handle_message({
# 'timestamp': row[7],
# 'number': row[1],
# 'type': row[2],
# 'text': row[6]
# })
#
# logging.debug(row)
, which may include functions, classes, or code. Output only the next line. | ) |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2013-04-04 16:19:47 vk>
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2011-12-27"
PROG_SHORT_DESCRIPTION = "Memacs for rss feeds"
PROG_TAG = "rss"
PROG_DESCRIPTION = """
This Memacs module will parse rss files.
rss can be read from file (-f FILE) or url (-u URL)
The items are automatically be appended to the org file.
Attention: RSS2.0 is required
Sample Org-entries
: ** <2009-09-06 Sun 18:45> [[http://www.wikipedia.org/][link]]: Example entry
: Here is some text containing an interesting description.
<|code_end|>
, generate the next line using the imports in this file:
from memacs.rss import RssMemacs
and context (functions, classes, or occasionally code) from other files:
# Path: memacs/rss.py
# class RssMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-u", "--url", dest="url",
# action="store",
# help="url to a rss file")
#
# self._parser.add_argument(
# "-f", "--file", dest="file",
# action="store",
# help="path to rss file")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if self._args.url and self._args.file:
# self._parser.error("you cannot set both url and file")
#
# if not self._args.url and not self._args.file:
# self._parser.error("please specify a file or url")
#
# if self._args.file:
# if not os.path.exists(self._args.file):
# self._parser.error("file %s not readable", self._args.file)
# if not os.access(self._args.file, os.R_OK):
# self._parser.error("file %s not readable", self._args.file)
#
# def __get_item_data(self, item):
# """
# gets information out of <item>..</item>
#
# @return: output, note, properties, tags
# variables for orgwriter.append_org_subitem
# """
# try:
# # logging.debug(item)
# properties = OrgProperties()
# guid = item['id']
# if not guid:
# logging.error("got no id")
#
# unformatted_link = item['link']
# short_link = OrgFormat.link(unformatted_link, "link")
#
# # if we found a url in title
# # then append the url in front of subject
# if re.search("http[s]?://", item['title']) is not None:
# output = short_link + ": " + item['title']
# else:
# output = OrgFormat.link(unformatted_link, item['title'])
#
# note = item['description']
#
# # converting updated_parsed UTC --> LOCALTIME
# # Karl 2018-09-22 this might be changed due to:
# # DeprecationWarning: To avoid breaking existing software
# # while fixing issue 310, a temporary mapping has been
# # created from `updated_parsed` to `published_parsed` if
# # `updated_parsed` doesn't exist. This fallback will be
# # removed in a future version of feedparser.
# timestamp = OrgFormat.date(
# time.localtime(calendar.timegm(item['updated_parsed'])), show_time=True)
#
# properties.add("guid", guid)
#
# except KeyError:
# logging.error("input is not a RSS 2.0")
# sys.exit(1)
#
# tags = []
# # Karl 2018-09-22 this might be changed due to:
# # DeprecationWarning: To avoid breaking existing software
# # while fixing issue 310, a temporary mapping has been created
# # from `updated_parsed` to `published_parsed` if
# # `updated_parsed` doesn't exist. This fallback will be
# # removed in a future version of feedparser.
# dont_parse = ['title', 'description', 'updated', 'summary',
# 'updated_parsed', 'link', 'links']
# for i in item:
# logging.debug(i)
# if i not in dont_parse:
# if (type(i) == str or type(i) == str) and \
# type(item[i]) == str and item[i] != "":
# if i == "id":
# i = "guid"
# properties.add(i, item[i])
# else:
# if i == "tags":
# for tag in item[i]:
# logging.debug("found tag: %s", tag['term'])
# tags.append(tag['term'])
#
# return output, note, properties, tags, timestamp
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
# # getting data
# if self._args.file:
# data = CommonReader.get_data_from_file(self._args.file)
# elif self._args.url:
# data = CommonReader.get_data_from_url(self._args.url)
#
# rss = feedparser.parse(data)
# logging.info("title: %s", rss['feed']['title'])
# logging.info("there are: %d entries", len(rss.entries))
#
# for item in rss.entries:
# logging.debug(item)
# output, note, properties, tags, timestamp = \
# self.__get_item_data(item)
# self._writer.write_org_subitem(output=output,
# timestamp=timestamp,
# note=note,
# properties=properties,
# tags=tags)
. Output only the next line. | : :PROPERTIES: |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
# Time-stamp: <2019-11-06 15:24:56 vk>
class TestOrgProperties(unittest.TestCase):
def test_properties_default_ctor(self):
p = OrgProperties("hashing data 1235")
properties = str(p).splitlines()
self.assertEqual(properties[0], " :PROPERTIES:")
self.assertEqual(properties[1],
" :ID: 063fad7f77461ed6a818b6b79306d641e9c90a83")
self.assertEqual(properties[2], " :END:")
def test_properties_with_own_created(self):
p = OrgProperties()
p.add("CREATED",
OrgFormat.date(time.gmtime(0), show_time=True))
properties = str(p).splitlines()
self.assertEqual(properties[0], " :PROPERTIES:")
<|code_end|>
, generate the next line using the imports in this file:
import time
import unittest
from orgformat import OrgFormat
from memacs.lib.orgproperty import OrgProperties
and context (functions, classes, or occasionally code) from other files:
# Path: memacs/lib/orgproperty.py
# class OrgProperties(object):
# """
# Class for handling Memacs's org-drawer:
#
# :PROPERTIES:
# ...
# :<tag>: value
# ...
# :ID: - id is generated from all above tags/values
# :END:
# """
#
# def __init__(self, data_for_hashing=""):
# """
# Ctor
# @param data_for_hashing: if no special properties are set,
# you can add here data only for hash generation
# """
# self.__properties = OrderedDict()
# self.__properties_multiline = {}
# self.__data_for_hashing = data_for_hashing
# self.__id = None
#
# def add(self, tag, value):
# """
# Add an OrgProperty(tag,value) to the properties
# @param tag: property tag
# @param value: property value
# """
# tag = str(tag).strip().upper()
# value = str(value).strip()
#
# if tag == "ID":
# raise Exception("you should not specify an :ID: property " + \
# "it will be generated automatically")
#
# value_multiline = value.splitlines()
#
# if len(value_multiline) > 1:
# # we do have multiline value
# multiline_value = [" " + v for v in value_multiline]
# self.__properties_multiline[tag] = multiline_value
#
# value = " ".join(value_multiline)
#
# self.__properties[tag] = str(value)
#
# def set_id(self, value):
# """
# set id here, then its not generated / hashed
# """
# self.__id = value
#
# def delete(self, key):
# """
# delete a pair out of properties
# @param key index
# """
# try:
# del self.__properties[key]
# del self.__properties_multiline[key]
# except Keyerror as e:
# pass
#
# def __get_property_max_tag_width(self):
# width = 10 # :PROPERTIES: has width 10
# for key in list(self.__properties.keys()):
# if width < len(key):
# width = len(key)
# return width
#
# def __format_tag(self, tag):
# num_whitespaces = self.__get_property_max_tag_width() - len(tag)
# whitespaces = ""
# for w in range(num_whitespaces):
# whitespaces += " "
# return " :" + tag + ": " + whitespaces
#
# def __str__(self):
# """
# for representig properties in unicode with org formatting
# """
#
# if self.__properties == {} and \
# self.__data_for_hashing == "" and \
# self.__id == None:
# raise Exception("No data for hashing specified, and no " + \
# "property was given. Cannot generate unique ID.")
#
# ret = " :PROPERTIES:\n"
#
# for tag, value in self.__properties.items():
# ret += self.__format_tag(tag) + value + "\n"
#
# ret += self.__format_tag("ID") + self.get_id() + "\n"
# ret += " :END:"
# return ret
#
# def get_id(self):
# """
# generates the hash string for all properties
# @return: sha1(properties)
# """
# if self.__id != None:
# return self.__id
# to_hash = "".join(map(str, list(self.__properties.values())))
# to_hash += "".join(map(str, list(self.__properties.keys())))
# to_hash += self.__data_for_hashing
# return hashlib.sha1(to_hash.encode('utf-8')).hexdigest()
#
# def get_value(self, key):
# """
# @param: key of property
# @return: returns the value of a given key
# """
# return self.__properties[key]
#
# def add_data_for_hashing(self, data_for_hashing):
# """
# add additional data for hashing
# useful when no possibility to set in Ctor
# """
# self.__data_for_hashing += data_for_hashing
#
# def get_value_delete_but_add_for_hashing(self, key):
# """
# see method name ;)
# """
# ret = self.get_value(key)
# self.delete(key)
# self.add_data_for_hashing(ret)
# return ret
#
# def get_multiline_properties(self):
# ret = ""
# for key in list(self.__properties_multiline.keys()):
# ret += "\n " + key + ":\n"
# ret += "\n".join(self.__properties_multiline[key])
# ret += "\n"
#
# return ret
. Output only the next line. | self.assertEqual(properties[1], " :CREATED: <1970-01-0" + \ |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2013-09-12 09:11 igb>
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2012-03-07"
PROG_SHORT_DESCRIPTION = "Memacs for sms"
<|code_end|>
. Use current file imports:
(from memacs.sms_superbackup import SmsSuperBackupMemacs)
and context including class names, function names, or small code snippets from other files:
# Path: memacs/sms_superbackup.py
# class SmsSuperBackupMemacs(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="smsxmlfile",
# action="store", required=True,
# help="path to sms xml backup file")
#
# self._parser.add_argument(
# "--ignore-incoming", dest="ignore_incoming",
# action="store_true",
# help="ignore incoming smses")
#
# self._parser.add_argument(
# "--ignore-outgoing", dest="ignore_outgoing",
# action="store_true",
# help="ignore outgoing smses")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if not (os.path.exists(self._args.smsxmlfile) or \
# os.access(self._args.smsxmlfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
# def _main(self):
# """
# get's automatically called from Memacs class
# read the lines from sms backup xml file,
# parse and write them to org file
# """
#
# data = CommonReader.get_data_from_file(self._args.smsxmlfile)
#
# try:
# xml.sax.parseString(data.encode('utf-8'),
# SmsSaxHandler(self._writer,
# self._args.ignore_incoming,
# self._args.ignore_outgoing))
# except SAXParseException:
# logging.error("No correct XML given")
# sys.exit(1)
. Output only the next line. | PROG_TAG = "sms" |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
# Time-stamp: <2018-09-22 13:57:41 vk>
class TestWhatsApp(unittest.TestCase):
def setUp(self):
msgstore = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data', 'msgstore.db'
)
self.argv = []
self.argv.append('-f')
self.argv.append(msgstore)
def test_whatsapp(self):
self.argv.append('--output-format')
<|code_end|>
. Write the next line using the current file imports:
import os
import unittest
from memacs.whatsapp import WhatsApp
and context from other files:
# Path: memacs/whatsapp.py
# class WhatsApp(Memacs):
#
#
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="msgstore",
# action="store", type=open, required=True,
# help="path to decrypted msgstore.db file")
#
# self._parser.add_argument(
# "--ignore-incoming", dest="ignore_incoming",
# action="store_true", help="ignore received messages")
#
# self._parser.add_argument(
# "--ignore-outgoing", dest="ignore_outgoing",
# action="store_true", help="ignore sent messages")
#
# self._parser.add_argument(
# "--ignore-groups", dest="ignore_groups",
# action="store_true",help="ignore group messages")
#
# self._parser.add_argument(
# "--output-format", dest="output_format",
# action="store", default="{verb} [[{handler}:{name}][{name}]]: {text}",
# help="format string to use for the headline")
#
# self._parser.add_argument(
# "--set-handler", dest="handler",
# action="store", default="tel",
# help="set link handler")
#
# self._parser.add_argument(
# "--demojize", dest="demojize",
# action="store_true", help="replace emoji with the appropriate :shortcode:")
#
# self._parser.add_argument(
# "--skip-emoji", dest="skip_emoji",
# action="store_true", help="skip all emoji")
#
# self._parser.add_argument(
# "--orgcontactsfile", dest="orgcontactsfile",
# action="store", required=False,
# help="path to Org-contacts file for phone number lookup. Phone numbers have to match.")
#
#
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if self._args.orgcontactsfile:
# if not (os.path.exists(self._args.orgcontactsfile) or \
# os.access(self._args.orgcontactsfile, os.R_OK)):
# self._parser.error("Org-contacts file not found or not readable")
# self._numberdict = parse_org_contact_file(self._args.orgcontactsfile)
# else:
# self._numberdict = {}
#
# def _is_ignored(self, msg):
# """check for ignored message type"""
#
# if msg['type'] is 'INCOMING' and self._args.ignore_incoming:
# return True
#
# if msg['type'] is 'OUTGOING' and self._args.ignore_outgoing:
# return True
#
# group_message_regex = r'-[0-9]{10}'
# if self._args.ignore_groups and re.findall(group_message_regex, msg['number']):
# return True
#
# def _handle_message(self, msg):
# """parse a single message row"""
#
# msg['number'] = '00' + msg['number'].split('@')[0]
# msg['name'] = self._numberdict.get(msg['number'],msg['number'])
# msg['verb'] = 'to' if msg['type'] else 'from'
# msg['type'] = 'OUTGOING' if msg['type'] else 'INCOMING'
# msg['handler'] = self._args.handler
#
# if msg['text']:
# if self._args.demojize:
# msg['text'] = emoji.demojize(msg['text'])
#
# if self._args.skip_emoji:
# msg['text'] = re.sub(emoji.get_emoji_regexp(), '', msg['text'])
#
# timestamp = datetime.datetime.fromtimestamp(msg['timestamp'] / 1000)
#
# properties = OrgProperties(data_for_hashing=json.dumps(msg))
# properties.add('NUMBER', msg['number'])
# properties.add('TYPE', msg['type'])
#
# output = self._args.output_format.format(**msg)
#
# if msg['text'] and not self._is_ignored(msg):
# self._writer.write_org_subitem(timestamp=OrgFormat.date(timestamp, show_time=True),
# output=output, properties=properties)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
#
# conn = sqlite3.connect(os.path.abspath(self._args.msgstore.name))
# query = conn.execute('SELECT * FROM messages')
#
# for row in query:
# self._handle_message({
# 'timestamp': row[7],
# 'number': row[1],
# 'type': row[2],
# 'text': row[6]
# })
#
# logging.debug(row)
, which may include functions, classes, or code. Output only the next line. | self.argv.append('{text}') |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2013-04-04 16:18:15 vk>
PROG_VERSION_NUMBER = "0.1"
PROG_VERSION_DATE = "2012-02-24"
PROG_SHORT_DESCRIPTION = "Memacs for csv files"
PROG_TAG = "csv"
PROG_DESCRIPTION = """
This Memacs module will parse csv files
"""
# set CONFIG_PARSER_NAME only, when you want to have a config file
# otherwise you can comment it out
# CONFIG_PARSER_NAME="memacs-example"
COPYRIGHT_YEAR = "2012-2013"
COPYRIGHT_AUTHORS = """Karl Voit <tools@Karl-Voit.at>,
Armin Wieser <armin.wieser@gmail.com>"""
def main():
global memacs
memacs = Csv(
<|code_end|>
, predict the next line using imports from the current file:
from memacs.csv import Csv
and context including class names, function names, and sometimes code from other files:
# Path: memacs/csv.py
# class Csv(Memacs):
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="csvfile", required=True,
# action="store", help="input csv file", type=argparse.FileType('rb'))
#
# self._parser.add_argument(
# "-d", "--delimiter", dest="delimiter", default=";",
# action="store", help='delimiter, default ";"')
#
# self._parser.add_argument(
# "-e", "--encoding", dest="encoding",
# action="store", default="utf-8", help="default encoding utf-8, " +
# "see http://docs.python.org/library/codecs.html#standard-encodings" +
# "for possible encodings")
#
# self._parser.add_argument(
# "-n", "--fieldnames", dest="fieldnames", default=None,
# action="store", help="header field names of the columns",
# type=str.lower)
#
# self._parser.add_argument(
# "-p", "--properties", dest="properties", default='',
# action="store", help="fields to use for properties",
# type=str.lower)
#
# self._parser.add_argument(
# "--timestamp-field", dest="timestamp_field", required=True,
# action="store", help="field name of the timestamp",
# type=str.lower)
#
# self._parser.add_argument(
# "--timestamp-format", dest="timestamp_format",
# action="store", help='format of the timestamp, i.e. ' +
# '"%d.%m.%Y %H:%M:%S" for "14.02.2012 10:22:37" ' +
# 'see http://docs.python.org/library/time.html#time.strftime' +
# 'for possible formats, default unix timestamp')
#
# self._parser.add_argument(
# "--output-format", dest="output_format", required=True,
# action="store", help="format string to use for the output")
#
# self._parser.add_argument(
# "--skip-header", dest="skip_header",
# action="store_true", help="skip first line of the csv file")
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
#
# if self._args.fieldnames:
# self._args.fieldnames = [name.strip() for name in self._args.fieldnames.split(',')]
#
# def _handle_row(self, row):
# """
# handle a single row
# """
#
# try:
# # assume unix timestamp
# if not self._args.timestamp_format:
# timestamp = datetime.datetime.fromtimestamp(int(row[self._args.timestamp_field]))
# else:
# timestamp = time.strptime(row[self._args.timestamp_field], self._args.timestamp_format)
#
# # show time with the timestamp format, but only
# # if it contains at least hours and minutes
# if not self._args.timestamp_format or \
# any(x in self._args.timestamp_format for x in ['%H', '%M']):
# timestamp = OrgFormat.date(timestamp, show_time=True)
# else:
# timestamp = OrgFormat.date(timestamp)
#
# except ValueError as e:
# logging.error("timestamp-format does not match: %s", e)
# sys.exit(1)
#
# except IndexError as e:
# logging.error("did you specify the right delimiter?", e)
# sys.exit(1)
#
# properties = OrgProperties(data_for_hashing=json.dumps(row))
# output = self._args.output_format.format(**row)
#
# if self._args.properties:
# for prop in self._args.properties.split(','):
# properties.add(prop.upper().strip(), row[prop])
#
# self._writer.write_org_subitem(timestamp=timestamp,
# output=output,
# properties=properties)
#
# def _main(self):
# """
# get's automatically called from Memacs class
# """
#
# with self._args.csvfile as f:
#
# try:
# reader = UnicodeDictReader(f,
# self._args.delimiter,
# self._args.encoding,
# self._args.fieldnames)
#
# if self._args.skip_header:
# next(reader)
#
# for row in reader:
# self._handle_row(row)
# logging.debug(row)
#
# except TypeError as e:
# logging.error("not enough fieldnames or wrong delimiter given")
# logging.debug("Error: %s" % e)
# sys.exit(1)
#
# except UnicodeDecodeError as e:
# logging.error("could not decode file in utf-8, please specify input encoding")
# sys.exit(1)
. Output only the next line. | prog_version=PROG_VERSION_NUMBER, |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
# Time-stamp: <2012-03-09 15:36:52 armin>
class TestSmsMemacs(unittest.TestCase):
def setUp(self):
self._test_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'data', 'smsxml.txt'
)
argv = "-s -f " + self._test_file
memacs = SmsMemacs(argv=argv.split())
self.data = memacs.test_get_entries()
self._smses = ET.parse(self._test_file)
def test_from_file(self):
data = self.data
for i in range(4):
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import time
import unittest
import xml.etree.ElementTree as ET
from memacs.sms import SmsMemacs
and context (class names, function names, or code) available:
# Path: memacs/sms.py
# class SmsMemacs(Memacs):
#
# _numberdict = False
#
# def _parser_add_arguments(self):
# """
# overwritten method of class Memacs
#
# add additional arguments
# """
# Memacs._parser_add_arguments(self)
#
# self._parser.add_argument(
# "-f", "--file", dest="smsxmlfile",
# action="store", required=True,
# help="path to sms xml backup file")
#
# self._parser.add_argument(
# "--ignore-incoming", dest="ignore_incoming",
# action="store_true",
# help="ignore incoming smses")
#
# self._parser.add_argument(
# "--ignore-outgoing", dest="ignore_outgoing",
# action="store_true",
# help="ignore outgoing smses")
#
# self._parser.add_argument(
# "--orgcontactsfile", dest="orgcontactsfile",
# action="store", required=False,
# help="path to Org-contacts file for phone number lookup. Phone numbers have to match.")
#
#
#
# def _parser_parse_args(self):
# """
# overwritten method of class Memacs
#
# all additional arguments are parsed in here
# """
# Memacs._parser_parse_args(self)
# if not (os.path.exists(self._args.smsxmlfile) or \
# os.access(self._args.smsxmlfile, os.R_OK)):
# self._parser.error("input file not found or not readable")
#
# if self._args.orgcontactsfile:
# if not (os.path.exists(self._args.orgcontactsfile) or \
# os.access(self._args.orgcontactsfile, os.R_OK)):
# self._parser.error("Org-contacts file not found or not readable")
# self._numberdict = parse_org_contact_file(self._args.orgcontactsfile)
#
#
# def _main(self):
# """
# get's automatically called from Memacs class
# read the lines from sms backup xml file,
# parse and write them to org file
# """
#
# ## replace HTML entities "&#" in original file to prevent XML parser from worrying:
# temp_xml_file = tempfile.mkstemp()[1]
# line_number = 0
# logging.debug("tempfile [%s]", str(temp_xml_file))
# with codecs.open(temp_xml_file, 'w', encoding='utf-8') as outputhandle:
# for line in codecs.open(self._args.smsxmlfile, 'r', encoding='utf-8'):
# try:
# ## NOTE: this is a dirty hack to prevent te XML parser from complainaing about
# ## encoding issues of UTF-8 encoded emojis. Will be reverted when parsing sms_body
# outputhandle.write(line.replace('&#', 'EnCoDiNgHaCk42') + '\n')
# except IOError as e:
# print("tempfile line " + str(line_number) + " [" + str(temp_xml_file) + "]")
# print("I/O error({0}): {1}".format(e.errno, e.strerror))
# except ValueError as e:
# print("tempfile line " + str(line_number) + " [" + str(temp_xml_file) + "]")
# print("Value error: {0}".format(e))
# #print "line [%s]" % str(line)
# except:
# print("tempfile line " + str(line_number) + " [" + str(temp_xml_file) + "]")
# print("Unexpected error:", sys.exc_info()[0])
# raise
#
# data = CommonReader.get_data_from_file(temp_xml_file)
#
# try:
# xml.sax.parseString(data.encode('utf-8'),
# SmsSaxHandler(self._writer,
# self._args.ignore_incoming,
# self._args.ignore_outgoing,
# self._numberdict))
# except SAXParseException:
# logging.error("No correct XML given")
# sys.exit(1)
# else:
# os.remove(temp_xml_file)
. Output only the next line. | self._assertSMSLog(i, data[i*6:(i+1)*6]) |
Using the snippet: <|code_start|> names = map(lambda model: model.name, models)
assert names == [
"CodeISO", "chGeoId10", "MultilingualText09", "OeREBKRM09", "OeREBKRM09vs", "OeREBKRM09trsfr"]
assert models[0].version == "20060808"
assert models[0].uri == "http://www.kogis.ch"
def test_detect_models_none():
loader = ModelLoader("./tests/data/osm/railway.shp")
assert loader.detect_models() is None
def manualtest_model_conversion():
loader = ModelLoader("")
outfile = os.path.join(TEMPDIR, "tmpogrtools")
loader.convert_model(["./tests/data/ili/Beispiel.ili"], outfile)
with open(outfile) as file:
imd = file.read()
assert 'IlisMeta07.ModelData.EnumNode TID="Beispiel.Bodenbedeckung.BoFlaechen.Art.TYPE.TOP"' in imd
loader.convert_model(["./tests/data/ili/Test23_erweitert.ili"], outfile)
with open(outfile) as file:
imd = file.read()
assert 'IlisMeta07.ModelData.Class TID="Test23_erweitert.FixpunkteKategorie1.LFP1"' in imd
# Does include Test23.ili as well:
assert 'IlisMeta07.ModelData.NumType TID="Test23.Genauigkeit"' in imd
def test_lookup_ili():
loader = ModelLoader("./tests/data/ili/roads23.xtf")
<|code_end|>
, determine the next line of code. You have imports:
import os
import tempfile
from ogrtools.interlis.model_loader import ModelLoader
and context (class names, function names, or code) available:
# Path: ogrtools/interlis/model_loader.py
# class ModelLoader:
#
# """Load models of Interlis transfer files"""
#
# def __init__(self, fn):
# self._fn = fn
# self._fmt = None
# self.models = None
#
# def detect_format(self):
# """Detect Interlis transfer file type"""
# # Detection as in OGR lib
# f = open(self._fn, "rb")
# header = f.read(1000)
# f.close()
#
# if "interlis.ch/INTERLIS2" in header:
# return 'Interlis 2'
# elif "SCNT" in header:
# return 'Interlis 1'
# else:
# return None
#
# def detect_models(self):
# """Find models in itf/xtf file"""
# self.models = None
# self._fmt = self.detect_format()
# f = open(self._fn, "r")
# if self._fmt == 'Interlis 1':
# # Search for MODL xxx
# regex = re.compile(r'^MODL\s+(\w+)')
# for line in f:
# m = regex.search(line)
# if m:
# self.models = [IliModel(m.group(1))]
# break
# elif self._fmt == 'Interlis 2':
# # Search for <MODEL NAME="xxx"
# size = os.stat(self._fn).st_size
# data = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
# self.models = []
# m = re.search(r'<MODELS>.+?</MODELS>', data, re.DOTALL)
# if m:
# tree = ElementTree.fromstring(m.group())
# for elem in tree.iterfind('MODEL'):
# model = IliModel(
# elem.get("NAME"), elem.get("VERSION"), elem.get("URI"))
# self.models.append(model)
# f.close()
# return self.models
#
# def ilidirs(self):
# return "%ILI_DIR;http://models.interlis.ch/"
#
# def ili2c(self):
# return os.getenv("ILI2C", "ili2c.jar")
#
# def gen_lookup_ili(self):
# self.detect_models()
# # if self._fmt == "Interlis 2":
# ili = 'INTERLIS 2.3;\nMODEL Lookup AT "http://interlis.sourcepole.ch/" VERSION "" =\n'
# for model in self.models:
# ili += " IMPORTS %s;\n" % model.name
# ili += "END Lookup."
# return ili
#
# def create_ilismeta_model(self):
# ili = self.gen_lookup_ili()
# fh, ilifn = tempfile.mkstemp(suffix='.ili')
# os.write(fh, ili)
# os.close(fh)
# imd = self._fn + '.imd' # TODO: use main model as prefix
# print self.convert_model([ilifn], imd)
# os.remove(ilifn)
# return imd
#
# def convert_model(self, ilifiles, outfile):
# """Convert ili model to ilismeta model."""
#
# # ili2c USAGE
# # ili2c [Options] file1.ili file2.ili ...
# #
# # OPTIONS
# #
# #--no-auto don't look automatically after required models.
# #-o0 Generate no output (default).
# #-o1 Generate INTERLIS-1 output.
# #-o2 Generate INTERLIS-2 output.
# #-oXSD Generate an XML-Schema.
# #-oFMT Generate an INTERLIS-1 Format.
# #-oIMD Generate Model as IlisMeta INTERLIS-Transfer (XTF).
# #-oIOM (deprecated) Generate Model as INTERLIS-Transfer (XTF).
# #--out file/dir file or folder for output.
# #--ilidirs %ILI_DIR;http://models.interlis.ch/;%JAR_DIR list of directories with ili-files.
# #--proxy host proxy server to access model repositories.
# #--proxyPort port proxy port to access model repositories.
# #--with-predefined Include the predefined MODEL INTERLIS in
# # the output. Usually, this is omitted.
# #--without-warnings Report only errors, no warnings. Usually,
# # warnings are generated as well.
# #--trace Display detailed trace messages.
# #--quiet Suppress info messages.
# #-h|--help Display this help text.
# #-u|--usage Display short information about usage.
# #-v|--version Display the version of ili2c.
# return run_java(self.ili2c(),
# ["-oIMD", "--ilidirs", "'" +
# self.ilidirs() + "'", "--out", outfile]
# + ilifiles)
. Output only the next line. | assert "IMPORTS RoadsExdm2ben" in loader.gen_lookup_ili() |
Predict the next line for this snippet: <|code_start|> ic, iy, ix = brain.outshape[-3:]
if any((iy % self.fdim, ix % self.fdim)):
raise RuntimeError(
"Incompatible shapes: {} % {}".format((ix, iy), self.fdim)
)
LayerBase.connect(self, brain)
self.output = zX(ic, iy // self.fdim, ix // self.fdim)
def feedforward(self, questions):
self.output, self.filter = self.op.forward(questions, self.fdim)
return self.output
def backpropagate(self, delta):
return self.op.backward(delta, self.filter)
@property
def outshape(self):
return self.output.shape[-3:]
def __str__(self):
return "Pool-{}x{}".format(self.fdim, self.fdim)
class ConvLayer(LayerBase):
def __init__(self, nfilters, filterx=3, filtery=3, compiled=True, **kw):
super().__init__(compiled=compiled, **kw)
self.nfilters = nfilters
self.fx = filterx
self.fy = filtery
<|code_end|>
with the help of current file imports:
import numpy as np
from .abstract_layer import LayerBase, NoParamMixin
from ..util import zX, zX_like, white, scalX
from ..llatomic.lltensor_op import MaxPoolOp
from ..atomic import MaxPoolOp
from ..llatomic import ConvolutionOp
from ..atomic import ConvolutionOp
and context from other files:
# Path: brainforge/layers/abstract_layer.py
# class LayerBase(abc.ABC):
#
# trainable = True
#
# def __init__(self, activation="linear", **kw):
#
# self.brain = None
# self.inputs = None
# self.output = None
# self.inshape = None
# self.op = None
# self.opb = None
#
# self.weights = None
# self.biases = None
# self.nabla_w = None
# self.nabla_b = None
#
# self.compiled = kw.get("compiled", config.compiled)
# self.trainable = kw.get("trainable", self.trainable)
#
# self.activation = atomic.activations[activation]() \
# if isinstance(activation, str) else activation
#
# def connect(self, brain):
# self.brain = brain
# self.inshape = brain.outshape
#
# def shuffle(self) -> None:
# self.weights = white_like(self.weights)
# self.biases = zX_like(self.biases)
#
# def get_weights(self, unfold=True):
# if unfold:
# return np.concatenate((self.weights.ravel(), self.biases.ravel()))
# return [self.weights, self.biases]
#
# def set_weights(self, w, fold=True):
# if fold:
# W = self.weights
# self.weights = w[:W.size].reshape(W.shape)
# self.biases = w[W.size:].reshape(self.biases.shape)
# else:
# self.weights, self.biases = w
#
# def get_gradients(self, unfold=True):
# nabla = [self.nabla_w, self.nabla_b]
# return nabla if not unfold else np.concatenate([grad.ravel() for grad in nabla])
#
# def set_gradients(self, nabla, fold=True):
# if fold:
# self.nabla_w = nabla[:self.nabla_w.size].reshape(self.nabla_w.shape)
# self.nabla_b = nabla[self.nabla_w.size:].reshape(self.nabla_b.shape)
# else:
# self.nabla_w, self.nabla_b = nabla
#
# @property
# def gradients(self):
# return self.get_gradients(unfold=True)
#
# @property
# def num_params(self):
# return self.weights.size + self.biases.size
#
# @abc.abstractmethod
# def feedforward(self, X): raise NotImplementedError
#
# @abc.abstractmethod
# def backpropagate(self, delta): raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self): raise NotImplementedError
#
# def __str__(self):
# return self.__class__.__name__
#
# class NoParamMixin(abc.ABC):
#
# trainable = False
#
# def shuffle(self): pass
#
# def get_weights(self, unfold=True): pass
#
# def set_weights(self, w, fold=True): pass
#
# def get_gradients(self): pass
#
# def set_gradients(self): pass
#
# @property
# def nparams(self):
# return None
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
#
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def white(*dims, dtype=floatX) -> np.ndarray:
# """Returns a white noise tensor"""
# tensor = _densewhite(*dims) if len(dims) == 2 else _convwhite(*dims)
# return tensor.astype(dtype)
, which may contain function names, class names, or code. Output only the next line. | self.depth = 0 |
Given the following code snippet before the placeholder: <|code_start|> return self.output
def backpropagate(self, delta):
return self.op.backward(delta, self.filter)
@property
def outshape(self):
return self.output.shape[-3:]
def __str__(self):
return "Pool-{}x{}".format(self.fdim, self.fdim)
class ConvLayer(LayerBase):
def __init__(self, nfilters, filterx=3, filtery=3, compiled=True, **kw):
super().__init__(compiled=compiled, **kw)
self.nfilters = nfilters
self.fx = filterx
self.fy = filtery
self.depth = 0
self.stride = 1
self.inshape = None
self.op = None
def connect(self, brain):
if self.compiled:
else:
depth, iy, ix = brain.outshape[-3:]
if any((iy < self.fy, ix < self.fx)):
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
from .abstract_layer import LayerBase, NoParamMixin
from ..util import zX, zX_like, white, scalX
from ..llatomic.lltensor_op import MaxPoolOp
from ..atomic import MaxPoolOp
from ..llatomic import ConvolutionOp
from ..atomic import ConvolutionOp
and context including class names, function names, and sometimes code from other files:
# Path: brainforge/layers/abstract_layer.py
# class LayerBase(abc.ABC):
#
# trainable = True
#
# def __init__(self, activation="linear", **kw):
#
# self.brain = None
# self.inputs = None
# self.output = None
# self.inshape = None
# self.op = None
# self.opb = None
#
# self.weights = None
# self.biases = None
# self.nabla_w = None
# self.nabla_b = None
#
# self.compiled = kw.get("compiled", config.compiled)
# self.trainable = kw.get("trainable", self.trainable)
#
# self.activation = atomic.activations[activation]() \
# if isinstance(activation, str) else activation
#
# def connect(self, brain):
# self.brain = brain
# self.inshape = brain.outshape
#
# def shuffle(self) -> None:
# self.weights = white_like(self.weights)
# self.biases = zX_like(self.biases)
#
# def get_weights(self, unfold=True):
# if unfold:
# return np.concatenate((self.weights.ravel(), self.biases.ravel()))
# return [self.weights, self.biases]
#
# def set_weights(self, w, fold=True):
# if fold:
# W = self.weights
# self.weights = w[:W.size].reshape(W.shape)
# self.biases = w[W.size:].reshape(self.biases.shape)
# else:
# self.weights, self.biases = w
#
# def get_gradients(self, unfold=True):
# nabla = [self.nabla_w, self.nabla_b]
# return nabla if not unfold else np.concatenate([grad.ravel() for grad in nabla])
#
# def set_gradients(self, nabla, fold=True):
# if fold:
# self.nabla_w = nabla[:self.nabla_w.size].reshape(self.nabla_w.shape)
# self.nabla_b = nabla[self.nabla_w.size:].reshape(self.nabla_b.shape)
# else:
# self.nabla_w, self.nabla_b = nabla
#
# @property
# def gradients(self):
# return self.get_gradients(unfold=True)
#
# @property
# def num_params(self):
# return self.weights.size + self.biases.size
#
# @abc.abstractmethod
# def feedforward(self, X): raise NotImplementedError
#
# @abc.abstractmethod
# def backpropagate(self, delta): raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self): raise NotImplementedError
#
# def __str__(self):
# return self.__class__.__name__
#
# class NoParamMixin(abc.ABC):
#
# trainable = False
#
# def shuffle(self): pass
#
# def get_weights(self, unfold=True): pass
#
# def set_weights(self, w, fold=True): pass
#
# def get_gradients(self): pass
#
# def set_gradients(self): pass
#
# @property
# def nparams(self):
# return None
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
#
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def white(*dims, dtype=floatX) -> np.ndarray:
# """Returns a white noise tensor"""
# tensor = _densewhite(*dims) if len(dims) == 2 else _convwhite(*dims)
# return tensor.astype(dtype)
. Output only the next line. | raise RuntimeError( |
Predict the next line for this snippet: <|code_start|> raise RuntimeError(
"Incompatible shapes: {} % {}".format((ix, iy), self.fdim)
)
LayerBase.connect(self, brain)
self.output = zX(ic, iy // self.fdim, ix // self.fdim)
def feedforward(self, questions):
self.output, self.filter = self.op.forward(questions, self.fdim)
return self.output
def backpropagate(self, delta):
return self.op.backward(delta, self.filter)
@property
def outshape(self):
return self.output.shape[-3:]
def __str__(self):
return "Pool-{}x{}".format(self.fdim, self.fdim)
class ConvLayer(LayerBase):
def __init__(self, nfilters, filterx=3, filtery=3, compiled=True, **kw):
super().__init__(compiled=compiled, **kw)
self.nfilters = nfilters
self.fx = filterx
self.fy = filtery
self.depth = 0
self.stride = 1
<|code_end|>
with the help of current file imports:
import numpy as np
from .abstract_layer import LayerBase, NoParamMixin
from ..util import zX, zX_like, white, scalX
from ..llatomic.lltensor_op import MaxPoolOp
from ..atomic import MaxPoolOp
from ..llatomic import ConvolutionOp
from ..atomic import ConvolutionOp
and context from other files:
# Path: brainforge/layers/abstract_layer.py
# class LayerBase(abc.ABC):
#
# trainable = True
#
# def __init__(self, activation="linear", **kw):
#
# self.brain = None
# self.inputs = None
# self.output = None
# self.inshape = None
# self.op = None
# self.opb = None
#
# self.weights = None
# self.biases = None
# self.nabla_w = None
# self.nabla_b = None
#
# self.compiled = kw.get("compiled", config.compiled)
# self.trainable = kw.get("trainable", self.trainable)
#
# self.activation = atomic.activations[activation]() \
# if isinstance(activation, str) else activation
#
# def connect(self, brain):
# self.brain = brain
# self.inshape = brain.outshape
#
# def shuffle(self) -> None:
# self.weights = white_like(self.weights)
# self.biases = zX_like(self.biases)
#
# def get_weights(self, unfold=True):
# if unfold:
# return np.concatenate((self.weights.ravel(), self.biases.ravel()))
# return [self.weights, self.biases]
#
# def set_weights(self, w, fold=True):
# if fold:
# W = self.weights
# self.weights = w[:W.size].reshape(W.shape)
# self.biases = w[W.size:].reshape(self.biases.shape)
# else:
# self.weights, self.biases = w
#
# def get_gradients(self, unfold=True):
# nabla = [self.nabla_w, self.nabla_b]
# return nabla if not unfold else np.concatenate([grad.ravel() for grad in nabla])
#
# def set_gradients(self, nabla, fold=True):
# if fold:
# self.nabla_w = nabla[:self.nabla_w.size].reshape(self.nabla_w.shape)
# self.nabla_b = nabla[self.nabla_w.size:].reshape(self.nabla_b.shape)
# else:
# self.nabla_w, self.nabla_b = nabla
#
# @property
# def gradients(self):
# return self.get_gradients(unfold=True)
#
# @property
# def num_params(self):
# return self.weights.size + self.biases.size
#
# @abc.abstractmethod
# def feedforward(self, X): raise NotImplementedError
#
# @abc.abstractmethod
# def backpropagate(self, delta): raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self): raise NotImplementedError
#
# def __str__(self):
# return self.__class__.__name__
#
# class NoParamMixin(abc.ABC):
#
# trainable = False
#
# def shuffle(self): pass
#
# def get_weights(self, unfold=True): pass
#
# def set_weights(self, w, fold=True): pass
#
# def get_gradients(self): pass
#
# def set_gradients(self): pass
#
# @property
# def nparams(self):
# return None
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
#
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def white(*dims, dtype=floatX) -> np.ndarray:
# """Returns a white noise tensor"""
# tensor = _densewhite(*dims) if len(dims) == 2 else _convwhite(*dims)
# return tensor.astype(dtype)
, which may contain function names, class names, or code. Output only the next line. | self.inshape = None |
Next line prediction: <|code_start|> def __init__(self, nfilters, filterx=3, filtery=3, compiled=True, **kw):
super().__init__(compiled=compiled, **kw)
self.nfilters = nfilters
self.fx = filterx
self.fy = filtery
self.depth = 0
self.stride = 1
self.inshape = None
self.op = None
def connect(self, brain):
if self.compiled:
else:
depth, iy, ix = brain.outshape[-3:]
if any((iy < self.fy, ix < self.fx)):
raise RuntimeError(
"Incompatible shapes: iy ({}) < fy ({}) OR ix ({}) < fx ({})"
.format(iy, self.fy, ix, self.fx)
)
super().connect(brain)
self.op = ConvolutionOp()
self.inshape = brain.outshape
self.depth = depth
self.weights = white(self.nfilters, self.depth, self.fx, self.fy)
self.biases = zX(self.nfilters)[None, :, None, None]
self.nabla_b = zX_like(self.biases)
self.nabla_w = zX_like(self.weights)
def feedforward(self, X):
self.inputs = X
<|code_end|>
. Use current file imports:
(import numpy as np
from .abstract_layer import LayerBase, NoParamMixin
from ..util import zX, zX_like, white, scalX
from ..llatomic.lltensor_op import MaxPoolOp
from ..atomic import MaxPoolOp
from ..llatomic import ConvolutionOp
from ..atomic import ConvolutionOp)
and context including class names, function names, or small code snippets from other files:
# Path: brainforge/layers/abstract_layer.py
# class LayerBase(abc.ABC):
#
# trainable = True
#
# def __init__(self, activation="linear", **kw):
#
# self.brain = None
# self.inputs = None
# self.output = None
# self.inshape = None
# self.op = None
# self.opb = None
#
# self.weights = None
# self.biases = None
# self.nabla_w = None
# self.nabla_b = None
#
# self.compiled = kw.get("compiled", config.compiled)
# self.trainable = kw.get("trainable", self.trainable)
#
# self.activation = atomic.activations[activation]() \
# if isinstance(activation, str) else activation
#
# def connect(self, brain):
# self.brain = brain
# self.inshape = brain.outshape
#
# def shuffle(self) -> None:
# self.weights = white_like(self.weights)
# self.biases = zX_like(self.biases)
#
# def get_weights(self, unfold=True):
# if unfold:
# return np.concatenate((self.weights.ravel(), self.biases.ravel()))
# return [self.weights, self.biases]
#
# def set_weights(self, w, fold=True):
# if fold:
# W = self.weights
# self.weights = w[:W.size].reshape(W.shape)
# self.biases = w[W.size:].reshape(self.biases.shape)
# else:
# self.weights, self.biases = w
#
# def get_gradients(self, unfold=True):
# nabla = [self.nabla_w, self.nabla_b]
# return nabla if not unfold else np.concatenate([grad.ravel() for grad in nabla])
#
# def set_gradients(self, nabla, fold=True):
# if fold:
# self.nabla_w = nabla[:self.nabla_w.size].reshape(self.nabla_w.shape)
# self.nabla_b = nabla[self.nabla_w.size:].reshape(self.nabla_b.shape)
# else:
# self.nabla_w, self.nabla_b = nabla
#
# @property
# def gradients(self):
# return self.get_gradients(unfold=True)
#
# @property
# def num_params(self):
# return self.weights.size + self.biases.size
#
# @abc.abstractmethod
# def feedforward(self, X): raise NotImplementedError
#
# @abc.abstractmethod
# def backpropagate(self, delta): raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self): raise NotImplementedError
#
# def __str__(self):
# return self.__class__.__name__
#
# class NoParamMixin(abc.ABC):
#
# trainable = False
#
# def shuffle(self): pass
#
# def get_weights(self, unfold=True): pass
#
# def set_weights(self, w, fold=True): pass
#
# def get_gradients(self): pass
#
# def set_gradients(self): pass
#
# @property
# def nparams(self):
# return None
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
#
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def white(*dims, dtype=floatX) -> np.ndarray:
# """Returns a white noise tensor"""
# tensor = _densewhite(*dims) if len(dims) == 2 else _convwhite(*dims)
# return tensor.astype(dtype)
. Output only the next line. | self.output = self.activation.forward(self.op.forward(X, self.weights, "valid")) |
Next line prediction: <|code_start|>
class PoolLayer(NoParamMixin, LayerBase):
def __init__(self, filter_size, compiled=True):
LayerBase.__init__(self, activation="linear", trainable=False)
if compiled:
else:
self.fdim = filter_size
self.filter = None
self.op = MaxPoolOp()
def connect(self, brain):
ic, iy, ix = brain.outshape[-3:]
if any((iy % self.fdim, ix % self.fdim)):
raise RuntimeError(
"Incompatible shapes: {} % {}".format((ix, iy), self.fdim)
<|code_end|>
. Use current file imports:
(import numpy as np
from .abstract_layer import LayerBase, NoParamMixin
from ..util import zX, zX_like, white, scalX
from ..llatomic.lltensor_op import MaxPoolOp
from ..atomic import MaxPoolOp
from ..llatomic import ConvolutionOp
from ..atomic import ConvolutionOp)
and context including class names, function names, or small code snippets from other files:
# Path: brainforge/layers/abstract_layer.py
# class LayerBase(abc.ABC):
#
# trainable = True
#
# def __init__(self, activation="linear", **kw):
#
# self.brain = None
# self.inputs = None
# self.output = None
# self.inshape = None
# self.op = None
# self.opb = None
#
# self.weights = None
# self.biases = None
# self.nabla_w = None
# self.nabla_b = None
#
# self.compiled = kw.get("compiled", config.compiled)
# self.trainable = kw.get("trainable", self.trainable)
#
# self.activation = atomic.activations[activation]() \
# if isinstance(activation, str) else activation
#
# def connect(self, brain):
# self.brain = brain
# self.inshape = brain.outshape
#
# def shuffle(self) -> None:
# self.weights = white_like(self.weights)
# self.biases = zX_like(self.biases)
#
# def get_weights(self, unfold=True):
# if unfold:
# return np.concatenate((self.weights.ravel(), self.biases.ravel()))
# return [self.weights, self.biases]
#
# def set_weights(self, w, fold=True):
# if fold:
# W = self.weights
# self.weights = w[:W.size].reshape(W.shape)
# self.biases = w[W.size:].reshape(self.biases.shape)
# else:
# self.weights, self.biases = w
#
# def get_gradients(self, unfold=True):
# nabla = [self.nabla_w, self.nabla_b]
# return nabla if not unfold else np.concatenate([grad.ravel() for grad in nabla])
#
# def set_gradients(self, nabla, fold=True):
# if fold:
# self.nabla_w = nabla[:self.nabla_w.size].reshape(self.nabla_w.shape)
# self.nabla_b = nabla[self.nabla_w.size:].reshape(self.nabla_b.shape)
# else:
# self.nabla_w, self.nabla_b = nabla
#
# @property
# def gradients(self):
# return self.get_gradients(unfold=True)
#
# @property
# def num_params(self):
# return self.weights.size + self.biases.size
#
# @abc.abstractmethod
# def feedforward(self, X): raise NotImplementedError
#
# @abc.abstractmethod
# def backpropagate(self, delta): raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self): raise NotImplementedError
#
# def __str__(self):
# return self.__class__.__name__
#
# class NoParamMixin(abc.ABC):
#
# trainable = False
#
# def shuffle(self): pass
#
# def get_weights(self, unfold=True): pass
#
# def set_weights(self, w, fold=True): pass
#
# def get_gradients(self): pass
#
# def set_gradients(self): pass
#
# @property
# def nparams(self):
# return None
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
#
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def white(*dims, dtype=floatX) -> np.ndarray:
# """Returns a white noise tensor"""
# tensor = _densewhite(*dims) if len(dims) == 2 else _convwhite(*dims)
# return tensor.astype(dtype)
. Output only the next line. | ) |
Predict the next line after this snippet: <|code_start|>
class PoolLayer(NoParamMixin, LayerBase):
def __init__(self, filter_size, compiled=True):
LayerBase.__init__(self, activation="linear", trainable=False)
if compiled:
<|code_end|>
using the current file's imports:
import numpy as np
from .abstract_layer import LayerBase, NoParamMixin
from ..util import zX, zX_like, white, scalX
from ..llatomic.lltensor_op import MaxPoolOp
from ..atomic import MaxPoolOp
from ..llatomic import ConvolutionOp
from ..atomic import ConvolutionOp
and any relevant context from other files:
# Path: brainforge/layers/abstract_layer.py
# class LayerBase(abc.ABC):
#
# trainable = True
#
# def __init__(self, activation="linear", **kw):
#
# self.brain = None
# self.inputs = None
# self.output = None
# self.inshape = None
# self.op = None
# self.opb = None
#
# self.weights = None
# self.biases = None
# self.nabla_w = None
# self.nabla_b = None
#
# self.compiled = kw.get("compiled", config.compiled)
# self.trainable = kw.get("trainable", self.trainable)
#
# self.activation = atomic.activations[activation]() \
# if isinstance(activation, str) else activation
#
# def connect(self, brain):
# self.brain = brain
# self.inshape = brain.outshape
#
# def shuffle(self) -> None:
# self.weights = white_like(self.weights)
# self.biases = zX_like(self.biases)
#
# def get_weights(self, unfold=True):
# if unfold:
# return np.concatenate((self.weights.ravel(), self.biases.ravel()))
# return [self.weights, self.biases]
#
# def set_weights(self, w, fold=True):
# if fold:
# W = self.weights
# self.weights = w[:W.size].reshape(W.shape)
# self.biases = w[W.size:].reshape(self.biases.shape)
# else:
# self.weights, self.biases = w
#
# def get_gradients(self, unfold=True):
# nabla = [self.nabla_w, self.nabla_b]
# return nabla if not unfold else np.concatenate([grad.ravel() for grad in nabla])
#
# def set_gradients(self, nabla, fold=True):
# if fold:
# self.nabla_w = nabla[:self.nabla_w.size].reshape(self.nabla_w.shape)
# self.nabla_b = nabla[self.nabla_w.size:].reshape(self.nabla_b.shape)
# else:
# self.nabla_w, self.nabla_b = nabla
#
# @property
# def gradients(self):
# return self.get_gradients(unfold=True)
#
# @property
# def num_params(self):
# return self.weights.size + self.biases.size
#
# @abc.abstractmethod
# def feedforward(self, X): raise NotImplementedError
#
# @abc.abstractmethod
# def backpropagate(self, delta): raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self): raise NotImplementedError
#
# def __str__(self):
# return self.__class__.__name__
#
# class NoParamMixin(abc.ABC):
#
# trainable = False
#
# def shuffle(self): pass
#
# def get_weights(self, unfold=True): pass
#
# def set_weights(self, w, fold=True): pass
#
# def get_gradients(self): pass
#
# def set_gradients(self): pass
#
# @property
# def nparams(self):
# return None
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
#
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def white(*dims, dtype=floatX) -> np.ndarray:
# """Returns a white noise tensor"""
# tensor = _densewhite(*dims) if len(dims) == 2 else _convwhite(*dims)
# return tensor.astype(dtype)
. Output only the next line. | else: |
Using the snippet: <|code_start|>
class DirectFeedbackAlignment(Backpropagation):
def __init__(self, layerstack, cost, optimizer, name="", **kw):
super().__init__(layerstack, cost, optimizer, name, **kw)
self.backwards_weights = np.concatenate(
[white(self.outshape[0], np.prod(layer.outshape))
for layer in self.trainable_layers[:-1]]
)
def backpropagate(self, error):
m = len(error)
self.layers[-1].backpropagate(error)
all_deltas = error @ self.backwards_weights # [m x net_out] [net_out x [layer_outs]] = [m x [layer_outs]]
start = 0
for layer in self.trainable_layers[1:-1]:
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
from .backpropagation import Backpropagation
from ..util.typing import white
and context (class names, function names, or code) available:
# Path: brainforge/learner/backpropagation.py
# class Backpropagation(Learner):
#
# def __init__(self, layerstack, cost="mse", optimizer="sgd", name="", **kw):
# super().__init__(layerstack, cost, name, **kw)
# self.optimizer = (
# optimizer if isinstance(optimizer, GradientDescent) else optimizers[optimizer]()
# )
# self.optimizer.initialize(nparams=self.layers.num_params)
#
# def learn_batch(self, X, Y, w=None, metrics=(), update=True):
# m = len(X)
# preds = self.predict(X)
# delta = self.cost.derivative(preds, Y)
# if w is not None:
# delta *= w[:, None]
# self.backpropagate(delta)
# if update:
# self.update(m)
#
# train_metrics = {"cost": self.cost(self.output, Y) / m}
# if metrics:
# for metric in metrics:
# train_metrics[str(metric).lower()] = metric(preds, Y) / m
# return train_metrics
#
# def backpropagate(self, error):
# for layer in self.layers[-1:0:-1]:
# error = layer.backpropagate(error)
# return error
#
# def update(self, m):
# W = self.layers.get_weights(unfold=True)
# gW = self.get_gradients(unfold=True)
# oW = self.optimizer.optimize(W, gW, m)
# self.layers.set_weights(oW, fold=True)
# self.zero_gradients()
#
# def get_weights(self, unfold=True):
# return self.layers.get_weights(unfold=unfold)
#
# def set_weigts(self, ws, fold=True):
# self.layers.set_weights(ws=ws, fold=fold)
#
# def get_gradients(self, unfold=True):
# grads = [l.gradients for l in self.layers if l.trainable]
# if unfold:
# grads = np.concatenate(grads)
# return grads
#
# def set_gradients(self, gradients, fold=True):
# trl = (l for l in self.layers if l.trainable)
# if fold:
# start = 0
# for layer in trl:
# end = start + layer.num_params
# layer.set_weights(gradients[start:end])
# start = end
# else:
# for w, layer in zip(gradients, trl):
# layer.set_weights(w)
#
# def zero_gradients(self):
# for layer in self.layers:
# if not layer.trainable:
# continue
# layer.nabla_w *= 0
# layer.nabla_b *= 0
#
# @property
# def num_params(self):
# return self.layers.num_params
#
# @property
# def output_shape(self):
# return self.layers.output_shape
#
# @property
# def input_shape(self):
# return self.layers.input_shape
#
# Path: brainforge/util/typing.py
# def white(*dims, dtype=floatX) -> np.ndarray:
# """Returns a white noise tensor"""
# tensor = _densewhite(*dims) if len(dims) == 2 else _convwhite(*dims)
# return tensor.astype(dtype)
. Output only the next line. | num_deltas = np.prod(layer.outshape) |
Given the code snippet: <|code_start|>
class DirectFeedbackAlignment(Backpropagation):
def __init__(self, layerstack, cost, optimizer, name="", **kw):
super().__init__(layerstack, cost, optimizer, name, **kw)
self.backwards_weights = np.concatenate(
[white(self.outshape[0], np.prod(layer.outshape))
for layer in self.trainable_layers[:-1]]
)
def backpropagate(self, error):
m = len(error)
self.layers[-1].backpropagate(error)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from .backpropagation import Backpropagation
from ..util.typing import white
and context (functions, classes, or occasionally code) from other files:
# Path: brainforge/learner/backpropagation.py
# class Backpropagation(Learner):
#
# def __init__(self, layerstack, cost="mse", optimizer="sgd", name="", **kw):
# super().__init__(layerstack, cost, name, **kw)
# self.optimizer = (
# optimizer if isinstance(optimizer, GradientDescent) else optimizers[optimizer]()
# )
# self.optimizer.initialize(nparams=self.layers.num_params)
#
# def learn_batch(self, X, Y, w=None, metrics=(), update=True):
# m = len(X)
# preds = self.predict(X)
# delta = self.cost.derivative(preds, Y)
# if w is not None:
# delta *= w[:, None]
# self.backpropagate(delta)
# if update:
# self.update(m)
#
# train_metrics = {"cost": self.cost(self.output, Y) / m}
# if metrics:
# for metric in metrics:
# train_metrics[str(metric).lower()] = metric(preds, Y) / m
# return train_metrics
#
# def backpropagate(self, error):
# for layer in self.layers[-1:0:-1]:
# error = layer.backpropagate(error)
# return error
#
# def update(self, m):
# W = self.layers.get_weights(unfold=True)
# gW = self.get_gradients(unfold=True)
# oW = self.optimizer.optimize(W, gW, m)
# self.layers.set_weights(oW, fold=True)
# self.zero_gradients()
#
# def get_weights(self, unfold=True):
# return self.layers.get_weights(unfold=unfold)
#
# def set_weigts(self, ws, fold=True):
# self.layers.set_weights(ws=ws, fold=fold)
#
# def get_gradients(self, unfold=True):
# grads = [l.gradients for l in self.layers if l.trainable]
# if unfold:
# grads = np.concatenate(grads)
# return grads
#
# def set_gradients(self, gradients, fold=True):
# trl = (l for l in self.layers if l.trainable)
# if fold:
# start = 0
# for layer in trl:
# end = start + layer.num_params
# layer.set_weights(gradients[start:end])
# start = end
# else:
# for w, layer in zip(gradients, trl):
# layer.set_weights(w)
#
# def zero_gradients(self):
# for layer in self.layers:
# if not layer.trainable:
# continue
# layer.nabla_w *= 0
# layer.nabla_b *= 0
#
# @property
# def num_params(self):
# return self.layers.num_params
#
# @property
# def output_shape(self):
# return self.layers.output_shape
#
# @property
# def input_shape(self):
# return self.layers.input_shape
#
# Path: brainforge/util/typing.py
# def white(*dims, dtype=floatX) -> np.ndarray:
# """Returns a white noise tensor"""
# tensor = _densewhite(*dims) if len(dims) == 2 else _convwhite(*dims)
# return tensor.astype(dtype)
. Output only the next line. | all_deltas = error @ self.backwards_weights # [m x net_out] [net_out x [layer_outs]] = [m x [layer_outs]] |
Predict the next line for this snippet: <|code_start|>
class DenseOp:
@staticmethod
def forward(X, W, b=None):
<|code_end|>
with the help of current file imports:
from ._llops import dense_forward
from brainforge.util.typing import zX
and context from other files:
# Path: brainforge/llatomic/_llops.py
# @nb.jit("{f2}({f2},{f2},{f1})".format(f1=Xd(1), f2=Xd(2)), nopython=True)
# def dense_forward(X, W, b):
# return np.dot(X, W) + b
#
# Path: brainforge/util/typing.py
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
, which may contain function names, class names, or code. Output only the next line. | if b is None: |
Here is a snippet: <|code_start|> time, batch, indim = X.shape
Z = np.zeros((time, batch, indim+outdim))
O = np.zeros((time, batch, outdim))
T = np.zeros((time, 6, batch, outdim)) # C[0], Ca[1], cand[2], f[3], i[4], o[5]
for t in range(time):
Z[t] = np.concatenate((X[t], O[t-1]), axis=-1)
p = np.dot(Z[t], W) + b
p[:, :outdim] = activation(p[:, :outdim]) # nonlin to candidate
p[:, outdim:] = sigmoid(p[:, outdim:]) # sigmoid to gates
T[t, 2] = p[:, :outdim] # candidate
T[t, 3] = p[:, outdim:2*outdim] # forget
T[t, 4] = p[:, 2*outdim:3*outdim] # input
T[t, 5] = p[:, 3*outdim:] # output
T[t, 0] = T[t-1, 0] * T[t, 3] + T[t, 2] * T[t, 4] # Ct = Ct-1 * f + cand * i
T[t, 1] = activation(T[t, 0]) # nonlin to state
O[t] = T[t, 1] * T[t, 5] # O = f(C) * o
return np.concatenate((O.ravel(), Z.ravel(), T.ravel()))
@nb.jit(nopython=True)
def lstm_backward(Z, bwO, E, W, cache, bwcache):
# bwcache: bwCa, bwcand, bwf, bwi, bwo
dimo = W.shape[-1] // 4
time, batch, zdim = Z.shape
indim = zdim - dimo
<|code_end|>
. Write the next line using the current file imports:
import numba as nb
import numpy as np
from ._llactivation import sigmoid, tanh, relu
and context from other files:
# Path: brainforge/llatomic/_llactivation.py
# @nb.vectorize(finfout, nopython=True)
# def sigmoid(Z):
# return s1 / (s1 + np.exp(-Z))
#
# @nb.jit(nopython=True)
# def tanh(Z):
# return np.tanh(Z)
#
# @nb.vectorize(finfout, nopython=True)
# def relu(Z):
# return s0 if s0 >= Z else Z
, which may include functions, classes, or code. Output only the next line. | C, Ca, cand, f, i, o = cache[0], cache[1], cache[2], cache[3], cache[4], cache[5] |
Here is a snippet: <|code_start|>s1 = scalX(1.)
s2 = scalX(2.)
class CostFunction:
def __call__(self, outputs, targets):
raise NotImplementedError
def __str__(self):
return self.__class__.__name__
@staticmethod
def derivative(outputs, targets):
return outputs - targets
class _MeanSquaredError(CostFunction):
def __call__(self, outputs, targets):
return s05 * np.linalg.norm(outputs - targets) ** s2
@staticmethod
def true_derivative(outputs, targets):
return outputs - targets
class _CategoricalCrossEntropy(CostFunction):
def __call__(self, outputs: np.ndarray, targets: np.ndarray):
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from ..util.typing import scalX
and context from other files:
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
, which may include functions, classes, or code. Output only the next line. | return -(targets * np.log(outputs)).sum() |
Given the code snippet: <|code_start|>arg = np.arange(len(rX))
np.random.shuffle(arg)
targ, varg = arg[:100], arg[100:]
targ.sort()
varg.sort()
tX, tY = rX[targ], rY[targ]
vX, vY = rX[varg], rY[varg]
tX += np.random.randn(*tX.shape) / np.sqrt(tX.size*0.25)
net = Backpropagation([Dense(120, activation="tanh"),
Dense(120, activation="tanh"),
Dense(1, activation="linear")],
input_shape=1, optimizer="adam")
tpred = net.predict(tX)
vpred = net.predict(vX)
plt.ion()
plt.plot(tX, tY, "b--", alpha=0.5, label="Training data (noisy)")
plt.plot(rX, rY, "r--", alpha=0.5, label="Validation data (clean)")
plt.ylim(-2, 2)
plt.plot(rX, np.ones_like(rX), c="black", linestyle="--")
plt.plot(rX, -np.ones_like(rX), c="black", linestyle="--")
plt.plot(rX, np.zeros_like(rX), c="grey", linestyle="--")
tobj, = plt.plot(tX, tpred, "bo", markersize=3, alpha=0.5, label="Training pred")
vobj, = plt.plot(vX, vpred, "ro", markersize=3, alpha=0.5, label="Validation pred")
templ = "Batch: {:>5}, tMSE: {:>.4f}, vMSE: {:>.4f}"
t = plt.title(templ.format(0, 0., 0.))
plt.legend()
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from matplotlib import pyplot as plt
from brainforge.learner import Backpropagation
from brainforge.layers import Dense
and context (functions, classes, or occasionally code) from other files:
# Path: brainforge/learner/backpropagation.py
# class Backpropagation(Learner):
#
# def __init__(self, layerstack, cost="mse", optimizer="sgd", name="", **kw):
# super().__init__(layerstack, cost, name, **kw)
# self.optimizer = (
# optimizer if isinstance(optimizer, GradientDescent) else optimizers[optimizer]()
# )
# self.optimizer.initialize(nparams=self.layers.num_params)
#
# def learn_batch(self, X, Y, w=None, metrics=(), update=True):
# m = len(X)
# preds = self.predict(X)
# delta = self.cost.derivative(preds, Y)
# if w is not None:
# delta *= w[:, None]
# self.backpropagate(delta)
# if update:
# self.update(m)
#
# train_metrics = {"cost": self.cost(self.output, Y) / m}
# if metrics:
# for metric in metrics:
# train_metrics[str(metric).lower()] = metric(preds, Y) / m
# return train_metrics
#
# def backpropagate(self, error):
# for layer in self.layers[-1:0:-1]:
# error = layer.backpropagate(error)
# return error
#
# def update(self, m):
# W = self.layers.get_weights(unfold=True)
# gW = self.get_gradients(unfold=True)
# oW = self.optimizer.optimize(W, gW, m)
# self.layers.set_weights(oW, fold=True)
# self.zero_gradients()
#
# def get_weights(self, unfold=True):
# return self.layers.get_weights(unfold=unfold)
#
# def set_weigts(self, ws, fold=True):
# self.layers.set_weights(ws=ws, fold=fold)
#
# def get_gradients(self, unfold=True):
# grads = [l.gradients for l in self.layers if l.trainable]
# if unfold:
# grads = np.concatenate(grads)
# return grads
#
# def set_gradients(self, gradients, fold=True):
# trl = (l for l in self.layers if l.trainable)
# if fold:
# start = 0
# for layer in trl:
# end = start + layer.num_params
# layer.set_weights(gradients[start:end])
# start = end
# else:
# for w, layer in zip(gradients, trl):
# layer.set_weights(w)
#
# def zero_gradients(self):
# for layer in self.layers:
# if not layer.trainable:
# continue
# layer.nabla_w *= 0
# layer.nabla_b *= 0
#
# @property
# def num_params(self):
# return self.layers.num_params
#
# @property
# def output_shape(self):
# return self.layers.output_shape
#
# @property
# def input_shape(self):
# return self.layers.input_shape
#
# Path: brainforge/layers/core.py
# class Dense(FFBase):
#
# def connect(self, brain):
# inshape = brain.outshape
# if len(inshape) != 1:
# err = "Dense only accepts input shapes with 1 dimension!\n"
# err += "Maybe you should consider placing <Flatten> before <Dense>?"
# raise RuntimeError(err)
# self.weights = white(inshape[0], self.neurons)
# self.biases = zX(self.neurons)
# super().connect(brain)
# if self.compiled:
# from .. import llatomic
# print("Compiling DenseLayer...")
# self.op = llatomic.DenseOp()
# else:
# self.op = atomic.DenseOp()
#
# def feedforward(self, X):
# self.inputs = X
# self.output = self.activation.forward(self.op.forward(
# X, self.weights, self.biases
# ))
# return self.output
#
# def backpropagate(self, delta):
# delta *= self.activation.backward(self.output)
# nabla_w, nabla_b, dX = self.op.backward(self.inputs, delta, self.weights)
# self.nabla_w += nabla_w
# self.nabla_b += nabla_b
# return dX
#
# def __str__(self):
# return "Dense-{}-{}".format(self.neurons, str(self.activation)[:5])
. Output only the next line. | batchno = 1 |
Predict the next line for this snippet: <|code_start|>
rX = np.linspace(-6., 6., 200)[:, None]
rY = np.sin(rX)
arg = np.arange(len(rX))
np.random.shuffle(arg)
targ, varg = arg[:100], arg[100:]
targ.sort()
varg.sort()
tX, tY = rX[targ], rY[targ]
vX, vY = rX[varg], rY[varg]
tX += np.random.randn(*tX.shape) / np.sqrt(tX.size*0.25)
net = Backpropagation([Dense(120, activation="tanh"),
Dense(120, activation="tanh"),
Dense(1, activation="linear")],
input_shape=1, optimizer="adam")
tpred = net.predict(tX)
vpred = net.predict(vX)
plt.ion()
plt.plot(tX, tY, "b--", alpha=0.5, label="Training data (noisy)")
plt.plot(rX, rY, "r--", alpha=0.5, label="Validation data (clean)")
plt.ylim(-2, 2)
plt.plot(rX, np.ones_like(rX), c="black", linestyle="--")
plt.plot(rX, -np.ones_like(rX), c="black", linestyle="--")
plt.plot(rX, np.zeros_like(rX), c="grey", linestyle="--")
tobj, = plt.plot(tX, tpred, "bo", markersize=3, alpha=0.5, label="Training pred")
<|code_end|>
with the help of current file imports:
import numpy as np
from matplotlib import pyplot as plt
from brainforge.learner import Backpropagation
from brainforge.layers import Dense
and context from other files:
# Path: brainforge/learner/backpropagation.py
# class Backpropagation(Learner):
#
# def __init__(self, layerstack, cost="mse", optimizer="sgd", name="", **kw):
# super().__init__(layerstack, cost, name, **kw)
# self.optimizer = (
# optimizer if isinstance(optimizer, GradientDescent) else optimizers[optimizer]()
# )
# self.optimizer.initialize(nparams=self.layers.num_params)
#
# def learn_batch(self, X, Y, w=None, metrics=(), update=True):
# m = len(X)
# preds = self.predict(X)
# delta = self.cost.derivative(preds, Y)
# if w is not None:
# delta *= w[:, None]
# self.backpropagate(delta)
# if update:
# self.update(m)
#
# train_metrics = {"cost": self.cost(self.output, Y) / m}
# if metrics:
# for metric in metrics:
# train_metrics[str(metric).lower()] = metric(preds, Y) / m
# return train_metrics
#
# def backpropagate(self, error):
# for layer in self.layers[-1:0:-1]:
# error = layer.backpropagate(error)
# return error
#
# def update(self, m):
# W = self.layers.get_weights(unfold=True)
# gW = self.get_gradients(unfold=True)
# oW = self.optimizer.optimize(W, gW, m)
# self.layers.set_weights(oW, fold=True)
# self.zero_gradients()
#
# def get_weights(self, unfold=True):
# return self.layers.get_weights(unfold=unfold)
#
# def set_weigts(self, ws, fold=True):
# self.layers.set_weights(ws=ws, fold=fold)
#
# def get_gradients(self, unfold=True):
# grads = [l.gradients for l in self.layers if l.trainable]
# if unfold:
# grads = np.concatenate(grads)
# return grads
#
# def set_gradients(self, gradients, fold=True):
# trl = (l for l in self.layers if l.trainable)
# if fold:
# start = 0
# for layer in trl:
# end = start + layer.num_params
# layer.set_weights(gradients[start:end])
# start = end
# else:
# for w, layer in zip(gradients, trl):
# layer.set_weights(w)
#
# def zero_gradients(self):
# for layer in self.layers:
# if not layer.trainable:
# continue
# layer.nabla_w *= 0
# layer.nabla_b *= 0
#
# @property
# def num_params(self):
# return self.layers.num_params
#
# @property
# def output_shape(self):
# return self.layers.output_shape
#
# @property
# def input_shape(self):
# return self.layers.input_shape
#
# Path: brainforge/layers/core.py
# class Dense(FFBase):
#
# def connect(self, brain):
# inshape = brain.outshape
# if len(inshape) != 1:
# err = "Dense only accepts input shapes with 1 dimension!\n"
# err += "Maybe you should consider placing <Flatten> before <Dense>?"
# raise RuntimeError(err)
# self.weights = white(inshape[0], self.neurons)
# self.biases = zX(self.neurons)
# super().connect(brain)
# if self.compiled:
# from .. import llatomic
# print("Compiling DenseLayer...")
# self.op = llatomic.DenseOp()
# else:
# self.op = atomic.DenseOp()
#
# def feedforward(self, X):
# self.inputs = X
# self.output = self.activation.forward(self.op.forward(
# X, self.weights, self.biases
# ))
# return self.output
#
# def backpropagate(self, delta):
# delta *= self.activation.backward(self.output)
# nabla_w, nabla_b, dX = self.op.backward(self.inputs, delta, self.weights)
# self.nabla_w += nabla_w
# self.nabla_b += nabla_b
# return dX
#
# def __str__(self):
# return "Dense-{}-{}".format(self.neurons, str(self.activation)[:5])
, which may contain function names, class names, or code. Output only the next line. | vobj, = plt.plot(vX, vpred, "ro", markersize=3, alpha=0.5, label="Validation pred") |
Next line prediction: <|code_start|> deltaC *= f[t]
deltaZ[t] = np.dot(dgates[t], W.T)
E[t-1] += deltaZ[t, :, indim:] if t else s0
nablaW = np.matmul(Z.transpose(0, 2, 1), dgates).sum(axis=0)
nablab = np.sum(dgates, axis=(0, 1))
deltaX = deltaZ[:, :, :indim]
return deltaX, nablaW, nablab
def backward_o(self, Z, O, E, W, cache):
C, f, i, o, cand, Ca = cache
outdim = W.shape[-1] // 4
time, batch, zdim = Z.shape
indim = zdim - outdim
bwgates = np.concatenate((f, i, o, cand), axis=-1)
bwgates[:, :, :-outdim] = sigmoid.backward(bwgates[:, :, :-outdim])
bwgates[:, :, -outdim:] = self.actfn.backward(bwgates[:, :, -outdim:])
bwCa = self.actfn.backward(Ca)
nablaW = zX_like(W)
nablab = zX(outdim*4)
delta = zX_like(O[-1])
deltaC = zX_like(O[-1])
deltaX = zX(time, batch, indim)
dgates = zX(time, batch, outdim*4)
for t in range(time-1, -1, -1):
<|code_end|>
. Use current file imports:
(import numpy as np
from .activation_op import activations
from ..util.typing import zX, zX_like, scalX)
and context including class names, function names, or small code snippets from other files:
# Path: brainforge/atomic/activation_op.py
# class ActivationFunction:
# class Sigmoid(ActivationFunction):
# class HardSigmoid(ActivationFunction):
# class Tanh(ActivationFunction):
# class Sqrt(ActivationFunction):
# class Linear(ActivationFunction):
# class ReLU(ActivationFunction):
# class LeakyReLU(ActivationFunction):
# class SoftMax(ActivationFunction):
# class OnePlus(ActivationFunction):
# def forward(self, Z: np.ndarray) -> np.ndarray:
# def __str__(self):
# def backward(self, Z: np.ndarray) -> np.ndarray:
# def forward(self, Z: np.ndarray):
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z: np.ndarray):
# def backward(self, A: np.ndarray):
# def forward(self, Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, Z) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, A) -> np.ndarray:
# def __init__(self, alpha=0.3):
# def forward(self, Z: np.ndarray) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def __init__(self, temperature=1.):
# def tn(self, Z):
# def t1(Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def true_backward(A: np.ndarray):
# def forward(self, Z):
# def backward(self, Z: np.ndarray):
# J = np.ones_like(A)
# J[A <= 0.] = self.alpha
# I = np.eye(A.shape[1], dtype=floatX)
#
# Path: brainforge/util/typing.py
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
. Output only the next line. | E[t] += delta |
Predict the next line for this snippet: <|code_start|> bwCa = np.atleast_2d(self.actfn.backward(Ca))
deltaC = zX_like(O[-1])
deltaZ = zX_like(Z)
dgates = zX(time, batch, outdim*4)
for t in range(time-1, -1, -1):
deltaC += E[t] * o[t] * bwCa[t]
dcand = deltaC * i[t]
df = deltaC * (C[t-1] if t else s0)
di = deltaC * cand[t]
do = Ca[t] * E[t]
dgates[t] = np.concatenate((dcand, df, di, do), axis=-1) * bwgates[t]
deltaC *= f[t]
deltaZ[t] = np.dot(dgates[t], W.T)
E[t-1] += deltaZ[t, :, indim:] if t else s0
nablaW = np.matmul(Z.transpose(0, 2, 1), dgates).sum(axis=0)
nablab = np.sum(dgates, axis=(0, 1))
deltaX = deltaZ[:, :, :indim]
return deltaX, nablaW, nablab
def backward_o(self, Z, O, E, W, cache):
C, f, i, o, cand, Ca = cache
outdim = W.shape[-1] // 4
time, batch, zdim = Z.shape
<|code_end|>
with the help of current file imports:
import numpy as np
from .activation_op import activations
from ..util.typing import zX, zX_like, scalX
and context from other files:
# Path: brainforge/atomic/activation_op.py
# class ActivationFunction:
# class Sigmoid(ActivationFunction):
# class HardSigmoid(ActivationFunction):
# class Tanh(ActivationFunction):
# class Sqrt(ActivationFunction):
# class Linear(ActivationFunction):
# class ReLU(ActivationFunction):
# class LeakyReLU(ActivationFunction):
# class SoftMax(ActivationFunction):
# class OnePlus(ActivationFunction):
# def forward(self, Z: np.ndarray) -> np.ndarray:
# def __str__(self):
# def backward(self, Z: np.ndarray) -> np.ndarray:
# def forward(self, Z: np.ndarray):
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z: np.ndarray):
# def backward(self, A: np.ndarray):
# def forward(self, Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, Z) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, A) -> np.ndarray:
# def __init__(self, alpha=0.3):
# def forward(self, Z: np.ndarray) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def __init__(self, temperature=1.):
# def tn(self, Z):
# def t1(Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def true_backward(A: np.ndarray):
# def forward(self, Z):
# def backward(self, Z: np.ndarray):
# J = np.ones_like(A)
# J[A <= 0.] = self.alpha
# I = np.eye(A.shape[1], dtype=floatX)
#
# Path: brainforge/util/typing.py
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
, which may contain function names, class names, or code. Output only the next line. | indim = zdim - outdim |
Here is a snippet: <|code_start|> dgates = zX(time, batch, outdim*4)
for t in range(time-1, -1, -1):
deltaC += E[t] * o[t] * bwCa[t]
dcand = deltaC * i[t]
df = deltaC * (C[t-1] if t else s0)
di = deltaC * cand[t]
do = Ca[t] * E[t]
dgates[t] = np.concatenate((dcand, df, di, do), axis=-1) * bwgates[t]
deltaC *= f[t]
deltaZ[t] = np.dot(dgates[t], W.T)
E[t-1] += deltaZ[t, :, indim:] if t else s0
nablaW = np.matmul(Z.transpose(0, 2, 1), dgates).sum(axis=0)
nablab = np.sum(dgates, axis=(0, 1))
deltaX = deltaZ[:, :, :indim]
return deltaX, nablaW, nablab
def backward_o(self, Z, O, E, W, cache):
C, f, i, o, cand, Ca = cache
outdim = W.shape[-1] // 4
time, batch, zdim = Z.shape
indim = zdim - outdim
bwgates = np.concatenate((f, i, o, cand), axis=-1)
bwgates[:, :, :-outdim] = sigmoid.backward(bwgates[:, :, :-outdim])
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from .activation_op import activations
from ..util.typing import zX, zX_like, scalX
and context from other files:
# Path: brainforge/atomic/activation_op.py
# class ActivationFunction:
# class Sigmoid(ActivationFunction):
# class HardSigmoid(ActivationFunction):
# class Tanh(ActivationFunction):
# class Sqrt(ActivationFunction):
# class Linear(ActivationFunction):
# class ReLU(ActivationFunction):
# class LeakyReLU(ActivationFunction):
# class SoftMax(ActivationFunction):
# class OnePlus(ActivationFunction):
# def forward(self, Z: np.ndarray) -> np.ndarray:
# def __str__(self):
# def backward(self, Z: np.ndarray) -> np.ndarray:
# def forward(self, Z: np.ndarray):
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z: np.ndarray):
# def backward(self, A: np.ndarray):
# def forward(self, Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, Z) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, A) -> np.ndarray:
# def __init__(self, alpha=0.3):
# def forward(self, Z: np.ndarray) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def __init__(self, temperature=1.):
# def tn(self, Z):
# def t1(Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def true_backward(A: np.ndarray):
# def forward(self, Z):
# def backward(self, Z: np.ndarray):
# J = np.ones_like(A)
# J[A <= 0.] = self.alpha
# I = np.eye(A.shape[1], dtype=floatX)
#
# Path: brainforge/util/typing.py
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
, which may include functions, classes, or code. Output only the next line. | bwgates[:, :, -outdim:] = self.actfn.backward(bwgates[:, :, -outdim:]) |
Continue the code snippet: <|code_start|>
cand[t] = p[:, :outdim]
f[t] = p[:, outdim:2*outdim]
i[t] = p[:, 2*outdim:3*outdim]
o[t] = p[:, 3*outdim:]
# cand[t], f[t], i[t], o[t] = np.split(p, 4, axis=1)
C[t] = C[t-1] * f[t] + cand[t] * i[t]
Ca[t] = self.actfn.forward(C[t])
O[t] = Ca[t] * o[t]
return O, Z, np.stack((C, Ca, cand, f, i, o))
def backward(self, Z, O, E, W, cache):
outdim = W.shape[-1] // 4
time, batch, zdim = Z.shape
indim = zdim - outdim
C, Ca, cand, f, i, o = cache
bwgates = np.concatenate(cache[2:], axis=-1)
bwgates[..., outdim:] = sigmoid.backward(bwgates[..., outdim:])
bwgates[..., :outdim] = self.actfn.backward(bwgates[..., :outdim])
bwCa = np.atleast_2d(self.actfn.backward(Ca))
deltaC = zX_like(O[-1])
deltaZ = zX_like(Z)
dgates = zX(time, batch, outdim*4)
for t in range(time-1, -1, -1):
<|code_end|>
. Use current file imports:
import numpy as np
from .activation_op import activations
from ..util.typing import zX, zX_like, scalX
and context (classes, functions, or code) from other files:
# Path: brainforge/atomic/activation_op.py
# class ActivationFunction:
# class Sigmoid(ActivationFunction):
# class HardSigmoid(ActivationFunction):
# class Tanh(ActivationFunction):
# class Sqrt(ActivationFunction):
# class Linear(ActivationFunction):
# class ReLU(ActivationFunction):
# class LeakyReLU(ActivationFunction):
# class SoftMax(ActivationFunction):
# class OnePlus(ActivationFunction):
# def forward(self, Z: np.ndarray) -> np.ndarray:
# def __str__(self):
# def backward(self, Z: np.ndarray) -> np.ndarray:
# def forward(self, Z: np.ndarray):
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z: np.ndarray):
# def backward(self, A: np.ndarray):
# def forward(self, Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, Z) -> np.ndarray:
# def forward(self, Z) -> np.ndarray:
# def backward(self, A) -> np.ndarray:
# def __init__(self, alpha=0.3):
# def forward(self, Z: np.ndarray) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def __init__(self, temperature=1.):
# def tn(self, Z):
# def t1(Z) -> np.ndarray:
# def backward(self, A: np.ndarray) -> np.ndarray:
# def true_backward(A: np.ndarray):
# def forward(self, Z):
# def backward(self, Z: np.ndarray):
# J = np.ones_like(A)
# J[A <= 0.] = self.alpha
# I = np.eye(A.shape[1], dtype=floatX)
#
# Path: brainforge/util/typing.py
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
. Output only the next line. | deltaC += E[t] * o[t] * bwCa[t] |
Given snippet: <|code_start|> return J
class SoftMax(ActivationFunction):
type = "softmax"
def __init__(self, temperature=1.):
if temperature != 1.:
self.temperature = scalX(temperature)
self.__call__ = self.tn
def tn(self, Z):
return self.t1(Z / self.temperature)
@staticmethod
def t1(Z) -> np.ndarray:
eZ = np.exp(Z - Z.max(axis=1, keepdims=True))
return eZ / np.sum(eZ, axis=1, keepdims=True)
forward = t1
def backward(self, A: np.ndarray) -> np.ndarray:
return s1
@staticmethod
def true_backward(A: np.ndarray):
# TODO: test this with numerical gradient testing!
I = np.eye(A.shape[1], dtype=floatX)
idx, idy = np.diag_indices(I)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from ..util.typing import scalX, zX_like
from ..config import floatX
and context:
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# Path: brainforge/config/numeric.py
which might include code, classes, or functions. Output only the next line. | return A * (A[..., None] - I[None, ...])[:, idx, idy] |
Predict the next line for this snippet: <|code_start|> return J
class SoftMax(ActivationFunction):
type = "softmax"
def __init__(self, temperature=1.):
if temperature != 1.:
self.temperature = scalX(temperature)
self.__call__ = self.tn
def tn(self, Z):
return self.t1(Z / self.temperature)
@staticmethod
def t1(Z) -> np.ndarray:
eZ = np.exp(Z - Z.max(axis=1, keepdims=True))
return eZ / np.sum(eZ, axis=1, keepdims=True)
forward = t1
def backward(self, A: np.ndarray) -> np.ndarray:
return s1
@staticmethod
def true_backward(A: np.ndarray):
# TODO: test this with numerical gradient testing!
I = np.eye(A.shape[1], dtype=floatX)
idx, idy = np.diag_indices(I)
<|code_end|>
with the help of current file imports:
import numpy as np
from ..util.typing import scalX, zX_like
from ..config import floatX
and context from other files:
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# Path: brainforge/config/numeric.py
, which may contain function names, class names, or code. Output only the next line. | return A * (A[..., None] - I[None, ...])[:, idx, idy] |
Here is a snippet: <|code_start|>
class Linear(ActivationFunction):
type = "linear"
def forward(self, Z) -> np.ndarray:
return Z
def backward(self, Z) -> np.ndarray:
return s1
class ReLU(ActivationFunction):
type = "relu"
def forward(self, Z) -> np.ndarray:
return np.maximum(s0, Z)
def backward(self, A) -> np.ndarray:
return (A > 0.).astype(A.dtype)
class LeakyReLU(ActivationFunction):
type = "leakyrelu"
def __init__(self, alpha=0.3):
self.alpha = alpha
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from ..util.typing import scalX, zX_like
from ..config import floatX
and context from other files:
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
#
# Path: brainforge/config/numeric.py
, which may include functions, classes, or code. Output only the next line. | def forward(self, Z: np.ndarray) -> np.ndarray: |
Continue the code snippet: <|code_start|>
class HillClimbing(AgentBase):
def __init__(self, network, nactions, agentconfig=None, **kw):
super().__init__(network, agentconfig, **kw)
self.rewards = 0
self.bestreward = 0
def reset(self):
self.rewards = 0
def sample(self, state, reward):
self.rewards += reward if reward is not None else 0
pred = self.net.feedforward(state[None, :])[0]
return pred.argmax()
def accumulate(self, state, reward):
W = self.net.layers.get_weights(unfold=True)
<|code_end|>
. Use current file imports:
import numpy as np
from .abstract_agent import AgentBase
and context (classes, functions, or code) from other files:
# Path: brainforge/reinforcement/abstract_agent.py
# class AgentBase(abc.ABC):
#
# type = ""
#
# def __init__(self, network, agentconfig: AgentConfig, **kw):
# if agentconfig is None:
# agentconfig = AgentConfig(**kw)
# self.net = network
# # self.shadow_net = network.layers.get_weights()
# self.xp = agentconfig.replay_memory
# self.cfg = agentconfig # type: AgentConfig
# self.shadow_net = None
#
# @abc.abstractmethod
# def reset(self):
# raise NotImplementedError
#
# @abc.abstractmethod
# def sample(self, state, reward):
# raise NotImplementedError
#
# @abc.abstractmethod
# def accumulate(self, state, reward):
# raise NotImplementedError
#
# def learn_batch(self, batch_size=None, callbacks=None):
# X, Y = self.xp.replay(batch_size or self.cfg.bsize)
# N = len(X)
# if N < self.cfg.batch_size:
# return 0.
# cost = self.net.fit(X, Y, batch_size=32, verbose=0, epochs=1, callbacks=callbacks)
# return np.mean(cost.history["loss"])
# # return np.mean(costs)
#
# def push_weights(self):
# W = self.net.layers.get_weights(unfold=True)
# D = np.linalg.norm(self.shadow_net - W)
# self.shadow_net *= (1. - self.cfg.tau)
# self.shadow_net += self.cfg.tau * self.net.layers.get_weights(unfold=True)
# return D / len(W)
#
# def pull_weights(self):
# self.net.layers.set_weights(self.shadow_net, fold=True)
. Output only the next line. | if self.rewards > self.bestreward: |
Given the code snippet: <|code_start|> self.decay = decay
def optimize(self, W, gW, m):
nabla = gW / m
self.memory *= self.decay
self.memory += (1. - self.decay) * (nabla ** 2.)
updates = (self.eta * nabla) / np.sqrt(self.memory + self.epsilon)
return W - updates
def __str__(self):
return "RMSprop"
class Adam(_SGD):
def __init__(self, eta=0.001, decay_memory=0.999, decay_velocity=0.9, epsilon=1e-5):
super().__init__(eta)
self.decay_velocity = decay_velocity
self.decay_memory = decay_memory
self.epsilon = epsilon
self.velocity, self.memory = None, None
def initialize(self, nparams, velocity=None, memory=None):
self.velocity = np.zeros((nparams,)) if velocity is None else velocity
self.memory = np.zeros((nparams,)) if memory is None else memory
def optimize(self, W, gW, m):
eta = self.eta / m
self.velocity = self.decay_velocity * self.velocity + (1. - self.decay_velocity) * gW
self.memory = (self.decay_memory * self.memory + (1. - self.decay_memory) * (gW ** 2))
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from .gradient_descent import SGD as _SGD
and context (functions, classes, or occasionally code) from other files:
# Path: brainforge/optimizers/gradient_descent.py
# class SGD(GradientDescent):
#
# def optimize(self, W, gW, m):
# return W - gW * (self.eta / m)
#
# def __str__(self):
# return "SGD"
. Output only the next line. | update = (eta * self.velocity) / np.sqrt(self.memory + self.epsilon) |
Here is a snippet: <|code_start|>
def ctx1(*arrays):
return np.concatenate(arrays, axis=1)
def scalX(scalar, dtype=floatX):
return np.asscalar(np.array([scalar], dtype=dtype))
def zX(*dims, dtype=floatX):
return np.zeros(dims, dtype=dtype)
def zX_like(array, dtype=floatX):
return zX(*array.shape, dtype=dtype)
def _densewhite(fanin, fanout):
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from ..config import floatX
and context from other files:
# Path: brainforge/config/numeric.py
, which may include functions, classes, or code. Output only the next line. | return np.random.randn(fanin, fanout) * np.sqrt(2. / float(fanin + fanout)) |
Continue the code snippet: <|code_start|>
class LocalCorrelationAligment(Backpropagation):
def backpropagate(self, error):
m = len(error)
self.layers[-1].backpropagate(error)
all_deltas = error @ self.backwards_weights # [m x net_out] [net_out x [layer_outs]] = [m x [layer_outs]]
start = 0
<|code_end|>
. Use current file imports:
import numpy as np
from .backpropagation import Backpropagation
from ..metrics import mse
and context (classes, functions, or code) from other files:
# Path: brainforge/learner/backpropagation.py
# class Backpropagation(Learner):
#
# def __init__(self, layerstack, cost="mse", optimizer="sgd", name="", **kw):
# super().__init__(layerstack, cost, name, **kw)
# self.optimizer = (
# optimizer if isinstance(optimizer, GradientDescent) else optimizers[optimizer]()
# )
# self.optimizer.initialize(nparams=self.layers.num_params)
#
# def learn_batch(self, X, Y, w=None, metrics=(), update=True):
# m = len(X)
# preds = self.predict(X)
# delta = self.cost.derivative(preds, Y)
# if w is not None:
# delta *= w[:, None]
# self.backpropagate(delta)
# if update:
# self.update(m)
#
# train_metrics = {"cost": self.cost(self.output, Y) / m}
# if metrics:
# for metric in metrics:
# train_metrics[str(metric).lower()] = metric(preds, Y) / m
# return train_metrics
#
# def backpropagate(self, error):
# for layer in self.layers[-1:0:-1]:
# error = layer.backpropagate(error)
# return error
#
# def update(self, m):
# W = self.layers.get_weights(unfold=True)
# gW = self.get_gradients(unfold=True)
# oW = self.optimizer.optimize(W, gW, m)
# self.layers.set_weights(oW, fold=True)
# self.zero_gradients()
#
# def get_weights(self, unfold=True):
# return self.layers.get_weights(unfold=unfold)
#
# def set_weigts(self, ws, fold=True):
# self.layers.set_weights(ws=ws, fold=fold)
#
# def get_gradients(self, unfold=True):
# grads = [l.gradients for l in self.layers if l.trainable]
# if unfold:
# grads = np.concatenate(grads)
# return grads
#
# def set_gradients(self, gradients, fold=True):
# trl = (l for l in self.layers if l.trainable)
# if fold:
# start = 0
# for layer in trl:
# end = start + layer.num_params
# layer.set_weights(gradients[start:end])
# start = end
# else:
# for w, layer in zip(gradients, trl):
# layer.set_weights(w)
#
# def zero_gradients(self):
# for layer in self.layers:
# if not layer.trainable:
# continue
# layer.nabla_w *= 0
# layer.nabla_b *= 0
#
# @property
# def num_params(self):
# return self.layers.num_params
#
# @property
# def output_shape(self):
# return self.layers.output_shape
#
# @property
# def input_shape(self):
# return self.layers.input_shape
#
# Path: brainforge/metrics/costs.py
# class CostFunction:
# class _MeanSquaredError(CostFunction):
# class _CategoricalCrossEntropy(CostFunction):
# class _BinaryCrossEntropy(CostFunction):
# class _Hinge(CostFunction):
# def __call__(self, outputs, targets):
# def __str__(self):
# def derivative(outputs, targets):
# def __call__(self, outputs, targets):
# def true_derivative(outputs, targets):
# def __call__(self, outputs: np.ndarray, targets: np.ndarray):
# def true_derivative(outputs, targets):
# def __call__(self, outputs: np.ndarray, targets: np.ndarray):
# def true_derivative(outputs, targets):
# def __call__(self, outputs, targets):
# def derivative(outputs, targets):
# def get(cost_function):
. Output only the next line. | for layer in self.trainable_layers[1:-1]: |
Given snippet: <|code_start|>
def _sanitize_configpath():
cfgpath = "~/.brainforgerc"
if not exists(cfgpath):
cfgpath = "~/.brainforgerc.txt"
if not exists(cfgpath):
cfgpath = None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
from os.path import expanduser, exists
from configparser import ConfigParser
from brainforge.config import numeric
and context:
# Path: brainforge/config/numeric.py
which might include code, classes, or functions. Output only the next line. | return cfgpath |
Given snippet: <|code_start|>
np.random.seed(1337)
ops = {
"sigmoid": (NpSigm(), NbSigm()),
"tanh": (NpTanh(), NbTanh()),
"relu": (NpReLU(), NbReLU())
}
class TestActivationFunctions(unittest.TestCase):
def _run_function_test(self, func):
npop, nbop = ops[func]
npO = npop.forward(self.X)
nbO = nbop.forward(self.X)
self.assertTrue(np.allclose(npO, nbO))
def setUp(self):
self.X = np.random.randn(100)
def test_sigmoid(self):
self._run_function_test("sigmoid")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
import numpy as np
from brainforge.atomic.activation_op import (
Sigmoid as NpSigm, Tanh as NpTanh, ReLU as NpReLU
)
from brainforge.llatomic.llactivation_op import (
Sigmoid as NbSigm, Tanh as NbTanh, ReLU as NbReLU
)
and context:
# Path: brainforge/atomic/activation_op.py
# class Sigmoid(ActivationFunction):
#
# type = "sigmoid"
#
# def forward(self, Z: np.ndarray):
# return s1 / (s1 + np.exp(-Z))
#
# def backward(self, A: np.ndarray) -> np.ndarray:
# return A * (s1 - A)
#
# class Tanh(ActivationFunction):
#
# type = "tanh"
#
# def forward(self, Z) -> np.ndarray:
# return np.tanh(Z)
#
# def backward(self, A: np.ndarray) -> np.ndarray:
# return s1 - A**2
#
# class ReLU(ActivationFunction):
#
# type = "relu"
#
# def forward(self, Z) -> np.ndarray:
# return np.maximum(s0, Z)
#
# def backward(self, A) -> np.ndarray:
# return (A > 0.).astype(A.dtype)
#
# Path: brainforge/llatomic/llactivation_op.py
# class Sigmoid(LLActivation):
# type = "sigmoid"
#
# class Tanh(LLActivation):
# type = "tanh"
#
# class ReLU(LLActivation):
# type = "relu"
which might include code, classes, or functions. Output only the next line. | def test_tanh(self): |
Given snippet: <|code_start|>
@nb.jit(nopython=True)
def recurrent_forward_relu(X, W, b):
outdim = W.shape[-1]
time, batch, indim = X.shape
O = np.zeros((time, batch, outdim))
for t in range(time):
Z = np.concatenate((X[t], O[t-1]), axis=-1)
preact = np.dot(Z, W) + b
O[t] = relu(preact.ravel()).reshape(*preact.shape)
return O
@nb.jit(nopython=True)
def recurrent_forward_tanh(X, W, b):
outdim = W.shape[-1]
time, batch, indim = X.shape
O = np.zeros((time, batch, outdim))
Z = np.zeros((time, batch, indim+outdim))
for t in range(time):
Z[t] = np.concatenate((X[t], O[t-1]), axis=-1)
preact = np.dot(Z[t], W) + b
O[t] = tanh(preact.ravel()).reshape(*preact.shape)
return np.concatenate((O.ravel(), Z.ravel()))
@nb.jit(nopython=True)
def recurrent_backward(Z, bwO, E, W):
indim = Z.shape[-1] - bwO.shape[-1]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numba as nb
import numpy as np
from ._llactivation import relu, tanh
and context:
# Path: brainforge/llatomic/_llactivation.py
# @nb.vectorize(finfout, nopython=True)
# def relu(Z):
# return s0 if s0 >= Z else Z
#
# @nb.jit(nopython=True)
# def tanh(Z):
# return np.tanh(Z)
which might include code, classes, or functions. Output only the next line. | nablaW = np.zeros_like(W) |
Continue the code snippet: <|code_start|>
@nb.jit(nopython=True)
def recurrent_forward_relu(X, W, b):
outdim = W.shape[-1]
time, batch, indim = X.shape
O = np.zeros((time, batch, outdim))
for t in range(time):
Z = np.concatenate((X[t], O[t-1]), axis=-1)
preact = np.dot(Z, W) + b
O[t] = relu(preact.ravel()).reshape(*preact.shape)
return O
@nb.jit(nopython=True)
def recurrent_forward_tanh(X, W, b):
outdim = W.shape[-1]
time, batch, indim = X.shape
O = np.zeros((time, batch, outdim))
Z = np.zeros((time, batch, indim+outdim))
for t in range(time):
Z[t] = np.concatenate((X[t], O[t-1]), axis=-1)
preact = np.dot(Z[t], W) + b
O[t] = tanh(preact.ravel()).reshape(*preact.shape)
return np.concatenate((O.ravel(), Z.ravel()))
@nb.jit(nopython=True)
def recurrent_backward(Z, bwO, E, W):
indim = Z.shape[-1] - bwO.shape[-1]
<|code_end|>
. Use current file imports:
import numba as nb
import numpy as np
from ._llactivation import relu, tanh
and context (classes, functions, or code) from other files:
# Path: brainforge/llatomic/_llactivation.py
# @nb.vectorize(finfout, nopython=True)
# def relu(Z):
# return s0 if s0 >= Z else Z
#
# @nb.jit(nopython=True)
# def tanh(Z):
# return np.tanh(Z)
. Output only the next line. | nablaW = np.zeros_like(W) |
Predict the next line for this snippet: <|code_start|> def __call__(self):
raise NotImplementedError
@abc.abstractmethod
def derivative(self, eta, m):
raise NotImplementedError
@abc.abstractmethod
def __str__(self):
raise NotImplementedError
class L1Norm(Regularizer):
def __call__(self):
return self.lmbd * np.abs(self.layer.get_weights()).sum()
def derivative(self, eta, m):
return ((eta * self.lmbd) / m) * np.sign(self.layer.get_weights())
def __str__(self):
return "L1-{}".format(self.lmbd)
class L2Norm(Regularizer):
def __call__(self):
return s05 * self.lmbd * np.linalg.norm(self.layer.get_weights() ** s2)
def derivative(self, eta, m):
<|code_end|>
with the help of current file imports:
import abc
import numpy as np
from ..util.typing import scalX
and context from other files:
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
, which may contain function names, class names, or code. Output only the next line. | return (s1 - ((eta * self.lmbd) / m)) * self.layer.get_weights().sum() |
Next line prediction: <|code_start|> im, ic, iy, ix = A.shape
nf, fc, fy, fx = F.shape
# fx, fy, fc, nf = F.shape
oy, ox = iy - fy + 1, ix - fx + 1
rfields = _reshape_receptive_fields(A, F)
# output = np.zeros((im, oy*ox, nf), dtype=nbfloatX)
Frsh = F.reshape(nf, fx * fy * fc)
output = np.empty((im, oy*ox, nf))
for m in range(im):
output[m] = np.dot(rfields[m], Frsh.T)
return output
@nb.jit("{f1}({f4},{i})".format(f1=Xd(1), f4=Xd(4), i=intX),
nopython=True)
def maxpool(A, fdim):
im, ic, iy, ix = A.shape
oy, ox = iy // fdim, ix // fdim
output = np.empty((im, ic, oy, ox), dtype=nbfloatX)
filt = np.zeros_like(A, dtype=nbfloatX)
for m in range(im):
for c in range(ic):
for y, sy in enumerate(range(0, iy, fdim)):
for x, sx in enumerate(range(0, ix, fdim)):
recfield = A[m, c, sy:sy + fdim, sx:sx + fdim]
value = recfield.max()
output[m, c, y, x] = value
filterfield = np.equal(recfield, value)
<|code_end|>
. Use current file imports:
(import numpy as np
import numba as nb
from ._llutil import nbfloatX, Xd)
and context including class names, function names, or small code snippets from other files:
# Path: brainforge/llatomic/_llutil.py
# def Xd(X, t=nbfloatX):
. Output only the next line. | filt[m, c, sy:sy + fdim, sx:sx + fdim] += filterfield |
Given the code snippet: <|code_start|> @staticmethod
def full(A, F):
nf, fc, fy, fx = F.shape
py, px = fy - 1, fx - 1
pA = np.pad(A, pad_width=((0, 0), (0, 0), (py, py), (px, px)),
mode="constant", constant_values=0.)
return ConvolutionOp.valid(pA, F)
@staticmethod
def forward(A, F, mode="valid"):
if mode == "valid":
return ConvolutionOp.valid(A, F)
return ConvolutionOp.full(A, F)
@staticmethod
def backward(X, E, F):
dF = ConvolutionOp.forward(
A=X.transpose(1, 0, 2, 3),
F=E.transpose(1, 0, 2, 3),
mode="valid"
).transpose(1, 0, 2, 3)
db = E.sum(axis=(0, 2, 3), keepdims=True)
dX = ConvolutionOp.forward(
A=E,
F=F[:, :, ::-1, ::-1].transpose(1, 0, 2, 3),
mode="full"
)
return dF, db, dX
@staticmethod
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from ..util.typing import zX, zX_like
and context (functions, classes, or occasionally code) from other files:
# Path: brainforge/util/typing.py
# def zX(*dims, dtype=floatX):
# return np.zeros(dims, dtype=dtype)
#
# def zX_like(array, dtype=floatX):
# return zX(*array.shape, dtype=dtype)
. Output only the next line. | def outshape(inshape, fshape, mode="valid"): |
Given the following code snippet before the placeholder: <|code_start|>
s0 = scalX(0., floatX)
s1 = scalX(1., floatX)
s2 = scalX(2., floatX)
finfout = "{t}({t})".format(t=nbfloatX)
jitsig = "{t}({t})".format(t=Xd(1))
@nb.vectorize(finfout, nopython=True)
def sigmoid(Z):
return s1 / (s1 + np.exp(-Z))
@nb.vectorize(finfout, nopython=True)
def sigmoid_p(A):
return A * (s1 - A)
@nb.jit(nopython=True)
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import numba as nb
from ._llutil import floatX, Xd, nbfloatX
from brainforge.util.typing import scalX
and context including class names, function names, and sometimes code from other files:
# Path: brainforge/llatomic/_llutil.py
# def Xd(X, t=nbfloatX):
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
. Output only the next line. | def tanh(Z): |
Next line prediction: <|code_start|>
s0 = scalX(0., floatX)
s1 = scalX(1., floatX)
s2 = scalX(2., floatX)
finfout = "{t}({t})".format(t=nbfloatX)
jitsig = "{t}({t})".format(t=Xd(1))
@nb.vectorize(finfout, nopython=True)
def sigmoid(Z):
<|code_end|>
. Use current file imports:
(import numpy as np
import numba as nb
from ._llutil import floatX, Xd, nbfloatX
from brainforge.util.typing import scalX)
and context including class names, function names, or small code snippets from other files:
# Path: brainforge/llatomic/_llutil.py
# def Xd(X, t=nbfloatX):
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
. Output only the next line. | return s1 / (s1 + np.exp(-Z)) |
Here is a snippet: <|code_start|>
s0 = scalX(0., floatX)
s1 = scalX(1., floatX)
s2 = scalX(2., floatX)
finfout = "{t}({t})".format(t=nbfloatX)
jitsig = "{t}({t})".format(t=Xd(1))
@nb.vectorize(finfout, nopython=True)
def sigmoid(Z):
return s1 / (s1 + np.exp(-Z))
@nb.vectorize(finfout, nopython=True)
def sigmoid_p(A):
return A * (s1 - A)
@nb.jit(nopython=True)
def tanh(Z):
return np.tanh(Z)
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import numba as nb
from ._llutil import floatX, Xd, nbfloatX
from brainforge.util.typing import scalX
and context from other files:
# Path: brainforge/llatomic/_llutil.py
# def Xd(X, t=nbfloatX):
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
, which may include functions, classes, or code. Output only the next line. | @nb.vectorize(finfout, nopython=True) |
Next line prediction: <|code_start|>
s0 = scalX(0., floatX)
s1 = scalX(1., floatX)
s2 = scalX(2., floatX)
finfout = "{t}({t})".format(t=nbfloatX)
jitsig = "{t}({t})".format(t=Xd(1))
<|code_end|>
. Use current file imports:
(import numpy as np
import numba as nb
from ._llutil import floatX, Xd, nbfloatX
from brainforge.util.typing import scalX)
and context including class names, function names, or small code snippets from other files:
# Path: brainforge/llatomic/_llutil.py
# def Xd(X, t=nbfloatX):
#
# Path: brainforge/util/typing.py
# def scalX(scalar, dtype=floatX):
# return np.asscalar(np.array([scalar], dtype=dtype))
. Output only the next line. | @nb.vectorize(finfout, nopython=True) |
Based on the snippet: <|code_start|>
class AgentConfig:
def __init__(self, batch_size=128,
discount_factor=0.99,
knowledge_transfer_rate=0.1,
epsilon_greedy_rate=0.9,
epsilon_decay=1.0,
epsilon_min=0.01,
replay_memory=None,
timestep=1):
self.batch_size = batch_size
self.gamma = discount_factor
self.tau = knowledge_transfer_rate
self.epsilon = epsilon_greedy_rate
self.epsilon_decay = epsilon_decay
self.epsilon_min = epsilon_min
self.replay_memory = (replay_memory if isinstance(replay_memory, Experience)
else replay_memory_factory(replay_memory, mode="drop", time=timestep))
self.time = timestep
<|code_end|>
, predict the immediate next line with the help of imports:
from .experience import replay_memory_factory, Experience
and context (classes, functions, sometimes code) from other files:
# Path: brainforge/reinforcement/experience.py
# def replay_memory_factory(limit, mode, time, downsample=0):
# if time > 1:
# return TimeExperience(time, limit, downsample)
# else:
# return Experience(limit, mode, downsample)
#
# class Experience:
#
# def __init__(self, limit=40000, mode="drop", downsample=0):
# self.limit = limit
# self.X = []
# self.Y = []
# self._adder = {"drop": self._add_drop, "mix in": self._mix_in}[mode]
# self.downsample = downsample
#
# @property
# def N(self):
# return len(self.X)
#
# def initialize(self, X, Y):
# self.X = X
# self.Y = Y
#
# def _mix_in(self, X, Y):
# m = len(X)
# N = self.N
# narg = np.arange(N)
# np.random.shuffle(narg)
# marg = narg[:m]
# self.X[marg] = X
# self.Y[marg] = Y
#
# def _add_drop(self, X, Y):
# m = len(X)
# self.X = np.concatenate((self.X[m:], X))
# self.Y = np.concatenate((self.Y[m:], Y))
#
# def _add(self, X, Y):
# self.X = np.concatenate((self.X, X))
# self.Y = np.concatenate((self.Y, Y))
# self.X = self.X[-self.limit:]
# self.Y = self.Y[-self.limit:]
#
# def _incorporate(self, X, Y):
# if self.N < self.limit:
# self._add(X, Y)
# self._adder(X, Y)
#
# def remember(self, X, Y):
# if self.downsample > 1:
# X, Y = X[::self.downsample], Y[::self.downsample]
# assert len(X) == len(Y)
# if len(self.X) < 1:
# self.initialize(X, Y)
# else:
# self._incorporate(X, Y)
#
# def replay(self, batch_size):
# narg = np.arange(self.N)
# np.random.shuffle(narg)
# batch_args = narg[:batch_size]
# if len(batch_args) == 0:
# return [], []
# return self.X[batch_args], self.Y[batch_args]
. Output only the next line. | @property |
Given the following code snippet before the placeholder: <|code_start|>
class AgentConfig:
def __init__(self, batch_size=128,
discount_factor=0.99,
knowledge_transfer_rate=0.1,
epsilon_greedy_rate=0.9,
epsilon_decay=1.0,
epsilon_min=0.01,
replay_memory=None,
timestep=1):
self.batch_size = batch_size
self.gamma = discount_factor
self.tau = knowledge_transfer_rate
self.epsilon = epsilon_greedy_rate
self.epsilon_decay = epsilon_decay
self.epsilon_min = epsilon_min
self.replay_memory = (replay_memory if isinstance(replay_memory, Experience)
else replay_memory_factory(replay_memory, mode="drop", time=timestep))
self.time = timestep
@property
def decaying_epsilon(self):
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
return self.epsilon
<|code_end|>
, predict the next line using imports from the current file:
from .experience import replay_memory_factory, Experience
and context including class names, function names, and sometimes code from other files:
# Path: brainforge/reinforcement/experience.py
# def replay_memory_factory(limit, mode, time, downsample=0):
# if time > 1:
# return TimeExperience(time, limit, downsample)
# else:
# return Experience(limit, mode, downsample)
#
# class Experience:
#
# def __init__(self, limit=40000, mode="drop", downsample=0):
# self.limit = limit
# self.X = []
# self.Y = []
# self._adder = {"drop": self._add_drop, "mix in": self._mix_in}[mode]
# self.downsample = downsample
#
# @property
# def N(self):
# return len(self.X)
#
# def initialize(self, X, Y):
# self.X = X
# self.Y = Y
#
# def _mix_in(self, X, Y):
# m = len(X)
# N = self.N
# narg = np.arange(N)
# np.random.shuffle(narg)
# marg = narg[:m]
# self.X[marg] = X
# self.Y[marg] = Y
#
# def _add_drop(self, X, Y):
# m = len(X)
# self.X = np.concatenate((self.X[m:], X))
# self.Y = np.concatenate((self.Y[m:], Y))
#
# def _add(self, X, Y):
# self.X = np.concatenate((self.X, X))
# self.Y = np.concatenate((self.Y, Y))
# self.X = self.X[-self.limit:]
# self.Y = self.Y[-self.limit:]
#
# def _incorporate(self, X, Y):
# if self.N < self.limit:
# self._add(X, Y)
# self._adder(X, Y)
#
# def remember(self, X, Y):
# if self.downsample > 1:
# X, Y = X[::self.downsample], Y[::self.downsample]
# assert len(X) == len(Y)
# if len(self.X) < 1:
# self.initialize(X, Y)
# else:
# self._incorporate(X, Y)
#
# def replay(self, batch_size):
# narg = np.arange(self.N)
# np.random.shuffle(narg)
# batch_args = narg[:batch_size]
# if len(batch_args) == 0:
# return [], []
# return self.X[batch_args], self.Y[batch_args]
. Output only the next line. | self.epsilon = self.epsilon_min |
Given snippet: <|code_start|>
class LLActivation(abc.ABC):
type = ""
def __init__(self):
self.llact, self.llactp = {
"sigmoid": (sigmoid, sigmoid_p),
"tanh": (tanh, tanh_p),
"relu": (relu, relu_p)
}[self.type]
def forward(self, X):
return self.llact(X.ravel()).reshape(X.shape)
def backward(self, A):
return self.llactp(A.ravel()).reshape(A.shape)
class Sigmoid(LLActivation):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import abc
from ._llactivation import (
sigmoid, sigmoid_p,
tanh, tanh_p,
relu, relu_p,
# softmax, softmax_p,
)
and context:
# Path: brainforge/llatomic/_llactivation.py
# @nb.vectorize(finfout, nopython=True)
# def sigmoid(Z):
# return s1 / (s1 + np.exp(-Z))
#
# @nb.vectorize(finfout, nopython=True)
# def sigmoid_p(A):
# return A * (s1 - A)
#
# @nb.jit(nopython=True)
# def tanh(Z):
# return np.tanh(Z)
#
# @nb.vectorize(finfout, nopython=True)
# def tanh_p(A):
# return s1 - A ** s2
#
# @nb.vectorize(finfout, nopython=True)
# def relu(Z):
# return s0 if s0 >= Z else Z
#
# @nb.vectorize(finfout, nopython=True)
# def relu_p(A):
# return s0 if A < s0 else s1
which might include code, classes, or functions. Output only the next line. | type = "sigmoid" |
Given the code snippet: <|code_start|>
class LLActivation(abc.ABC):
type = ""
def __init__(self):
self.llact, self.llactp = {
"sigmoid": (sigmoid, sigmoid_p),
"tanh": (tanh, tanh_p),
"relu": (relu, relu_p)
}[self.type]
def forward(self, X):
return self.llact(X.ravel()).reshape(X.shape)
def backward(self, A):
return self.llactp(A.ravel()).reshape(A.shape)
class Sigmoid(LLActivation):
type = "sigmoid"
class Tanh(LLActivation):
type = "tanh"
class Sqrt(LLActivation):
<|code_end|>
, generate the next line using the imports in this file:
import abc
from ._llactivation import (
sigmoid, sigmoid_p,
tanh, tanh_p,
relu, relu_p,
# softmax, softmax_p,
)
and context (functions, classes, or occasionally code) from other files:
# Path: brainforge/llatomic/_llactivation.py
# @nb.vectorize(finfout, nopython=True)
# def sigmoid(Z):
# return s1 / (s1 + np.exp(-Z))
#
# @nb.vectorize(finfout, nopython=True)
# def sigmoid_p(A):
# return A * (s1 - A)
#
# @nb.jit(nopython=True)
# def tanh(Z):
# return np.tanh(Z)
#
# @nb.vectorize(finfout, nopython=True)
# def tanh_p(A):
# return s1 - A ** s2
#
# @nb.vectorize(finfout, nopython=True)
# def relu(Z):
# return s0 if s0 >= Z else Z
#
# @nb.vectorize(finfout, nopython=True)
# def relu_p(A):
# return s0 if A < s0 else s1
. Output only the next line. | type = "sqrt" |
Given the code snippet: <|code_start|>
class LLActivation(abc.ABC):
type = ""
def __init__(self):
<|code_end|>
, generate the next line using the imports in this file:
import abc
from ._llactivation import (
sigmoid, sigmoid_p,
tanh, tanh_p,
relu, relu_p,
# softmax, softmax_p,
)
and context (functions, classes, or occasionally code) from other files:
# Path: brainforge/llatomic/_llactivation.py
# @nb.vectorize(finfout, nopython=True)
# def sigmoid(Z):
# return s1 / (s1 + np.exp(-Z))
#
# @nb.vectorize(finfout, nopython=True)
# def sigmoid_p(A):
# return A * (s1 - A)
#
# @nb.jit(nopython=True)
# def tanh(Z):
# return np.tanh(Z)
#
# @nb.vectorize(finfout, nopython=True)
# def tanh_p(A):
# return s1 - A ** s2
#
# @nb.vectorize(finfout, nopython=True)
# def relu(Z):
# return s0 if s0 >= Z else Z
#
# @nb.vectorize(finfout, nopython=True)
# def relu_p(A):
# return s0 if A < s0 else s1
. Output only the next line. | self.llact, self.llactp = { |
Continue the code snippet: <|code_start|>
class LLActivation(abc.ABC):
type = ""
def __init__(self):
self.llact, self.llactp = {
"sigmoid": (sigmoid, sigmoid_p),
"tanh": (tanh, tanh_p),
"relu": (relu, relu_p)
}[self.type]
def forward(self, X):
return self.llact(X.ravel()).reshape(X.shape)
def backward(self, A):
return self.llactp(A.ravel()).reshape(A.shape)
class Sigmoid(LLActivation):
type = "sigmoid"
class Tanh(LLActivation):
type = "tanh"
class Sqrt(LLActivation):
<|code_end|>
. Use current file imports:
import abc
from ._llactivation import (
sigmoid, sigmoid_p,
tanh, tanh_p,
relu, relu_p,
# softmax, softmax_p,
)
and context (classes, functions, or code) from other files:
# Path: brainforge/llatomic/_llactivation.py
# @nb.vectorize(finfout, nopython=True)
# def sigmoid(Z):
# return s1 / (s1 + np.exp(-Z))
#
# @nb.vectorize(finfout, nopython=True)
# def sigmoid_p(A):
# return A * (s1 - A)
#
# @nb.jit(nopython=True)
# def tanh(Z):
# return np.tanh(Z)
#
# @nb.vectorize(finfout, nopython=True)
# def tanh_p(A):
# return s1 - A ** s2
#
# @nb.vectorize(finfout, nopython=True)
# def relu(Z):
# return s0 if s0 >= Z else Z
#
# @nb.vectorize(finfout, nopython=True)
# def relu_p(A):
# return s0 if A < s0 else s1
. Output only the next line. | type = "sqrt" |
Using the snippet: <|code_start|>
class LLActivation(abc.ABC):
type = ""
def __init__(self):
self.llact, self.llactp = {
"sigmoid": (sigmoid, sigmoid_p),
"tanh": (tanh, tanh_p),
"relu": (relu, relu_p)
<|code_end|>
, determine the next line of code. You have imports:
import abc
from ._llactivation import (
sigmoid, sigmoid_p,
tanh, tanh_p,
relu, relu_p,
# softmax, softmax_p,
)
and context (class names, function names, or code) available:
# Path: brainforge/llatomic/_llactivation.py
# @nb.vectorize(finfout, nopython=True)
# def sigmoid(Z):
# return s1 / (s1 + np.exp(-Z))
#
# @nb.vectorize(finfout, nopython=True)
# def sigmoid_p(A):
# return A * (s1 - A)
#
# @nb.jit(nopython=True)
# def tanh(Z):
# return np.tanh(Z)
#
# @nb.vectorize(finfout, nopython=True)
# def tanh_p(A):
# return s1 - A ** s2
#
# @nb.vectorize(finfout, nopython=True)
# def relu(Z):
# return s0 if s0 >= Z else Z
#
# @nb.vectorize(finfout, nopython=True)
# def relu_p(A):
# return s0 if A < s0 else s1
. Output only the next line. | }[self.type] |
Next line prediction: <|code_start|>
class LayerStack(Model):
def __init__(self, input_shape, layers=()):
super().__init__(input_shape)
self.layers = []
self.architecture = []
self.learning = False
self._iterme = None
self._add_input_layer(input_shape)
for layer in layers:
self.add(layer)
def _add_input_layer(self, input_shape):
if isinstance(input_shape, int) or isinstance(input_shape, np.int64):
<|code_end|>
. Use current file imports:
(import numpy as np
from .abstract_model import Model
from ..layers.abstract_layer import LayerBase
from ..layers.core import InputLayer)
and context including class names, function names, or small code snippets from other files:
# Path: brainforge/model/abstract_model.py
# class Model(abc.ABC):
#
# def __init__(self, input_shape, **kw):
# self.input_shape = input_shape
# self.floatX = kw.get("floatX", "float64")
# self.compiled = kw.get("compiled", False)
#
# @abc.abstractmethod
# def feedforward(self, X):
# raise NotImplementedError
#
# @abc.abstractmethod
# def get_weights(self, unfold):
# raise NotImplementedError
#
# @abc.abstractmethod
# def set_weights(self, fold):
# raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def num_params(self):
# raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self):
# raise NotImplementedError
#
# Path: brainforge/layers/abstract_layer.py
# class LayerBase(abc.ABC):
#
# trainable = True
#
# def __init__(self, activation="linear", **kw):
#
# self.brain = None
# self.inputs = None
# self.output = None
# self.inshape = None
# self.op = None
# self.opb = None
#
# self.weights = None
# self.biases = None
# self.nabla_w = None
# self.nabla_b = None
#
# self.compiled = kw.get("compiled", config.compiled)
# self.trainable = kw.get("trainable", self.trainable)
#
# self.activation = atomic.activations[activation]() \
# if isinstance(activation, str) else activation
#
# def connect(self, brain):
# self.brain = brain
# self.inshape = brain.outshape
#
# def shuffle(self) -> None:
# self.weights = white_like(self.weights)
# self.biases = zX_like(self.biases)
#
# def get_weights(self, unfold=True):
# if unfold:
# return np.concatenate((self.weights.ravel(), self.biases.ravel()))
# return [self.weights, self.biases]
#
# def set_weights(self, w, fold=True):
# if fold:
# W = self.weights
# self.weights = w[:W.size].reshape(W.shape)
# self.biases = w[W.size:].reshape(self.biases.shape)
# else:
# self.weights, self.biases = w
#
# def get_gradients(self, unfold=True):
# nabla = [self.nabla_w, self.nabla_b]
# return nabla if not unfold else np.concatenate([grad.ravel() for grad in nabla])
#
# def set_gradients(self, nabla, fold=True):
# if fold:
# self.nabla_w = nabla[:self.nabla_w.size].reshape(self.nabla_w.shape)
# self.nabla_b = nabla[self.nabla_w.size:].reshape(self.nabla_b.shape)
# else:
# self.nabla_w, self.nabla_b = nabla
#
# @property
# def gradients(self):
# return self.get_gradients(unfold=True)
#
# @property
# def num_params(self):
# return self.weights.size + self.biases.size
#
# @abc.abstractmethod
# def feedforward(self, X): raise NotImplementedError
#
# @abc.abstractmethod
# def backpropagate(self, delta): raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self): raise NotImplementedError
#
# def __str__(self):
# return self.__class__.__name__
. Output only the next line. | input_shape = (input_shape,) |
Continue the code snippet: <|code_start|>
class LayerStack(Model):
def __init__(self, input_shape, layers=()):
super().__init__(input_shape)
self.layers = []
self.architecture = []
self.learning = False
self._iterme = None
<|code_end|>
. Use current file imports:
import numpy as np
from .abstract_model import Model
from ..layers.abstract_layer import LayerBase
from ..layers.core import InputLayer
and context (classes, functions, or code) from other files:
# Path: brainforge/model/abstract_model.py
# class Model(abc.ABC):
#
# def __init__(self, input_shape, **kw):
# self.input_shape = input_shape
# self.floatX = kw.get("floatX", "float64")
# self.compiled = kw.get("compiled", False)
#
# @abc.abstractmethod
# def feedforward(self, X):
# raise NotImplementedError
#
# @abc.abstractmethod
# def get_weights(self, unfold):
# raise NotImplementedError
#
# @abc.abstractmethod
# def set_weights(self, fold):
# raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def num_params(self):
# raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self):
# raise NotImplementedError
#
# Path: brainforge/layers/abstract_layer.py
# class LayerBase(abc.ABC):
#
# trainable = True
#
# def __init__(self, activation="linear", **kw):
#
# self.brain = None
# self.inputs = None
# self.output = None
# self.inshape = None
# self.op = None
# self.opb = None
#
# self.weights = None
# self.biases = None
# self.nabla_w = None
# self.nabla_b = None
#
# self.compiled = kw.get("compiled", config.compiled)
# self.trainable = kw.get("trainable", self.trainable)
#
# self.activation = atomic.activations[activation]() \
# if isinstance(activation, str) else activation
#
# def connect(self, brain):
# self.brain = brain
# self.inshape = brain.outshape
#
# def shuffle(self) -> None:
# self.weights = white_like(self.weights)
# self.biases = zX_like(self.biases)
#
# def get_weights(self, unfold=True):
# if unfold:
# return np.concatenate((self.weights.ravel(), self.biases.ravel()))
# return [self.weights, self.biases]
#
# def set_weights(self, w, fold=True):
# if fold:
# W = self.weights
# self.weights = w[:W.size].reshape(W.shape)
# self.biases = w[W.size:].reshape(self.biases.shape)
# else:
# self.weights, self.biases = w
#
# def get_gradients(self, unfold=True):
# nabla = [self.nabla_w, self.nabla_b]
# return nabla if not unfold else np.concatenate([grad.ravel() for grad in nabla])
#
# def set_gradients(self, nabla, fold=True):
# if fold:
# self.nabla_w = nabla[:self.nabla_w.size].reshape(self.nabla_w.shape)
# self.nabla_b = nabla[self.nabla_w.size:].reshape(self.nabla_b.shape)
# else:
# self.nabla_w, self.nabla_b = nabla
#
# @property
# def gradients(self):
# return self.get_gradients(unfold=True)
#
# @property
# def num_params(self):
# return self.weights.size + self.biases.size
#
# @abc.abstractmethod
# def feedforward(self, X): raise NotImplementedError
#
# @abc.abstractmethod
# def backpropagate(self, delta): raise NotImplementedError
#
# @property
# @abc.abstractmethod
# def outshape(self): raise NotImplementedError
#
# def __str__(self):
# return self.__class__.__name__
. Output only the next line. | self._add_input_layer(input_shape) |
Given snippet: <|code_start|>
class DNI:
def __init__(self, bpropnet, synth):
self.bpropnet = bpropnet
self.synth = synth
self._predictor = None
def predictor_coro(self):
prediction = None
delta_backwards = None
while 1:
inputs = yield prediction, delta_backwards
prediction = self.bpropnet.predict(inputs)
synthesized_delta = self.synth.predict(prediction)
self.bpropnet.update(len(inputs))
delta_backwards = self.bpropnet.backpropagate(synthesized_delta)
def predict(self, X):
if self._predictor is None:
self._predictor = self.predictor_coro()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from brainforge.learner import Backpropagation
from brainforge.layers import Dense
from brainforge.optimizers import Momentum
from brainforge.util import etalon
and context:
# Path: brainforge/learner/backpropagation.py
# class Backpropagation(Learner):
#
# def __init__(self, layerstack, cost="mse", optimizer="sgd", name="", **kw):
# super().__init__(layerstack, cost, name, **kw)
# self.optimizer = (
# optimizer if isinstance(optimizer, GradientDescent) else optimizers[optimizer]()
# )
# self.optimizer.initialize(nparams=self.layers.num_params)
#
# def learn_batch(self, X, Y, w=None, metrics=(), update=True):
# m = len(X)
# preds = self.predict(X)
# delta = self.cost.derivative(preds, Y)
# if w is not None:
# delta *= w[:, None]
# self.backpropagate(delta)
# if update:
# self.update(m)
#
# train_metrics = {"cost": self.cost(self.output, Y) / m}
# if metrics:
# for metric in metrics:
# train_metrics[str(metric).lower()] = metric(preds, Y) / m
# return train_metrics
#
# def backpropagate(self, error):
# for layer in self.layers[-1:0:-1]:
# error = layer.backpropagate(error)
# return error
#
# def update(self, m):
# W = self.layers.get_weights(unfold=True)
# gW = self.get_gradients(unfold=True)
# oW = self.optimizer.optimize(W, gW, m)
# self.layers.set_weights(oW, fold=True)
# self.zero_gradients()
#
# def get_weights(self, unfold=True):
# return self.layers.get_weights(unfold=unfold)
#
# def set_weigts(self, ws, fold=True):
# self.layers.set_weights(ws=ws, fold=fold)
#
# def get_gradients(self, unfold=True):
# grads = [l.gradients for l in self.layers if l.trainable]
# if unfold:
# grads = np.concatenate(grads)
# return grads
#
# def set_gradients(self, gradients, fold=True):
# trl = (l for l in self.layers if l.trainable)
# if fold:
# start = 0
# for layer in trl:
# end = start + layer.num_params
# layer.set_weights(gradients[start:end])
# start = end
# else:
# for w, layer in zip(gradients, trl):
# layer.set_weights(w)
#
# def zero_gradients(self):
# for layer in self.layers:
# if not layer.trainable:
# continue
# layer.nabla_w *= 0
# layer.nabla_b *= 0
#
# @property
# def num_params(self):
# return self.layers.num_params
#
# @property
# def output_shape(self):
# return self.layers.output_shape
#
# @property
# def input_shape(self):
# return self.layers.input_shape
#
# Path: brainforge/layers/core.py
# class Dense(FFBase):
#
# def connect(self, brain):
# inshape = brain.outshape
# if len(inshape) != 1:
# err = "Dense only accepts input shapes with 1 dimension!\n"
# err += "Maybe you should consider placing <Flatten> before <Dense>?"
# raise RuntimeError(err)
# self.weights = white(inshape[0], self.neurons)
# self.biases = zX(self.neurons)
# super().connect(brain)
# if self.compiled:
# from .. import llatomic
# print("Compiling DenseLayer...")
# self.op = llatomic.DenseOp()
# else:
# self.op = atomic.DenseOp()
#
# def feedforward(self, X):
# self.inputs = X
# self.output = self.activation.forward(self.op.forward(
# X, self.weights, self.biases
# ))
# return self.output
#
# def backpropagate(self, delta):
# delta *= self.activation.backward(self.output)
# nabla_w, nabla_b, dX = self.op.backward(self.inputs, delta, self.weights)
# self.nabla_w += nabla_w
# self.nabla_b += nabla_b
# return dX
#
# def __str__(self):
# return "Dense-{}-{}".format(self.neurons, str(self.activation)[:5])
#
# Path: brainforge/optimizers/gradient_descent.py
# class Momentum(SGD):
#
# def __init__(self, eta=0.1, mu=0.9):
# super().__init__(eta)
# self.mu = mu
# self.velocity = None
#
# def initialize(self, nparams, velocity=None):
# self.velocity = np.zeros((nparams,)) if velocity is None else velocity
#
# def optimize(self, W, gW, m):
# eta = self.eta / m
# self.velocity = self.velocity * self.mu + gW * eta
# return W - self.velocity
#
# def __str__(self):
# return "Momentum"
#
# Path: brainforge/util/_etalon.py
# X, Y = _data[:, :4].astype(float), _data[:, 4:].astype(float)
which might include code, classes, or functions. Output only the next line. | next(self._predictor) |
Using the snippet: <|code_start|>
class DNI:
def __init__(self, bpropnet, synth):
self.bpropnet = bpropnet
self.synth = synth
self._predictor = None
<|code_end|>
, determine the next line of code. You have imports:
from brainforge.learner import Backpropagation
from brainforge.layers import Dense
from brainforge.optimizers import Momentum
from brainforge.util import etalon
and context (class names, function names, or code) available:
# Path: brainforge/learner/backpropagation.py
# class Backpropagation(Learner):
#
# def __init__(self, layerstack, cost="mse", optimizer="sgd", name="", **kw):
# super().__init__(layerstack, cost, name, **kw)
# self.optimizer = (
# optimizer if isinstance(optimizer, GradientDescent) else optimizers[optimizer]()
# )
# self.optimizer.initialize(nparams=self.layers.num_params)
#
# def learn_batch(self, X, Y, w=None, metrics=(), update=True):
# m = len(X)
# preds = self.predict(X)
# delta = self.cost.derivative(preds, Y)
# if w is not None:
# delta *= w[:, None]
# self.backpropagate(delta)
# if update:
# self.update(m)
#
# train_metrics = {"cost": self.cost(self.output, Y) / m}
# if metrics:
# for metric in metrics:
# train_metrics[str(metric).lower()] = metric(preds, Y) / m
# return train_metrics
#
# def backpropagate(self, error):
# for layer in self.layers[-1:0:-1]:
# error = layer.backpropagate(error)
# return error
#
# def update(self, m):
# W = self.layers.get_weights(unfold=True)
# gW = self.get_gradients(unfold=True)
# oW = self.optimizer.optimize(W, gW, m)
# self.layers.set_weights(oW, fold=True)
# self.zero_gradients()
#
# def get_weights(self, unfold=True):
# return self.layers.get_weights(unfold=unfold)
#
# def set_weigts(self, ws, fold=True):
# self.layers.set_weights(ws=ws, fold=fold)
#
# def get_gradients(self, unfold=True):
# grads = [l.gradients for l in self.layers if l.trainable]
# if unfold:
# grads = np.concatenate(grads)
# return grads
#
# def set_gradients(self, gradients, fold=True):
# trl = (l for l in self.layers if l.trainable)
# if fold:
# start = 0
# for layer in trl:
# end = start + layer.num_params
# layer.set_weights(gradients[start:end])
# start = end
# else:
# for w, layer in zip(gradients, trl):
# layer.set_weights(w)
#
# def zero_gradients(self):
# for layer in self.layers:
# if not layer.trainable:
# continue
# layer.nabla_w *= 0
# layer.nabla_b *= 0
#
# @property
# def num_params(self):
# return self.layers.num_params
#
# @property
# def output_shape(self):
# return self.layers.output_shape
#
# @property
# def input_shape(self):
# return self.layers.input_shape
#
# Path: brainforge/layers/core.py
# class Dense(FFBase):
#
# def connect(self, brain):
# inshape = brain.outshape
# if len(inshape) != 1:
# err = "Dense only accepts input shapes with 1 dimension!\n"
# err += "Maybe you should consider placing <Flatten> before <Dense>?"
# raise RuntimeError(err)
# self.weights = white(inshape[0], self.neurons)
# self.biases = zX(self.neurons)
# super().connect(brain)
# if self.compiled:
# from .. import llatomic
# print("Compiling DenseLayer...")
# self.op = llatomic.DenseOp()
# else:
# self.op = atomic.DenseOp()
#
# def feedforward(self, X):
# self.inputs = X
# self.output = self.activation.forward(self.op.forward(
# X, self.weights, self.biases
# ))
# return self.output
#
# def backpropagate(self, delta):
# delta *= self.activation.backward(self.output)
# nabla_w, nabla_b, dX = self.op.backward(self.inputs, delta, self.weights)
# self.nabla_w += nabla_w
# self.nabla_b += nabla_b
# return dX
#
# def __str__(self):
# return "Dense-{}-{}".format(self.neurons, str(self.activation)[:5])
#
# Path: brainforge/optimizers/gradient_descent.py
# class Momentum(SGD):
#
# def __init__(self, eta=0.1, mu=0.9):
# super().__init__(eta)
# self.mu = mu
# self.velocity = None
#
# def initialize(self, nparams, velocity=None):
# self.velocity = np.zeros((nparams,)) if velocity is None else velocity
#
# def optimize(self, W, gW, m):
# eta = self.eta / m
# self.velocity = self.velocity * self.mu + gW * eta
# return W - self.velocity
#
# def __str__(self):
# return "Momentum"
#
# Path: brainforge/util/_etalon.py
# X, Y = _data[:, :4].astype(float), _data[:, 4:].astype(float)
. Output only the next line. | def predictor_coro(self): |
Given the code snippet: <|code_start|>
class DNI:
def __init__(self, bpropnet, synth):
self.bpropnet = bpropnet
self.synth = synth
self._predictor = None
def predictor_coro(self):
prediction = None
delta_backwards = None
<|code_end|>
, generate the next line using the imports in this file:
from brainforge.learner import Backpropagation
from brainforge.layers import Dense
from brainforge.optimizers import Momentum
from brainforge.util import etalon
and context (functions, classes, or occasionally code) from other files:
# Path: brainforge/learner/backpropagation.py
# class Backpropagation(Learner):
#
# def __init__(self, layerstack, cost="mse", optimizer="sgd", name="", **kw):
# super().__init__(layerstack, cost, name, **kw)
# self.optimizer = (
# optimizer if isinstance(optimizer, GradientDescent) else optimizers[optimizer]()
# )
# self.optimizer.initialize(nparams=self.layers.num_params)
#
# def learn_batch(self, X, Y, w=None, metrics=(), update=True):
# m = len(X)
# preds = self.predict(X)
# delta = self.cost.derivative(preds, Y)
# if w is not None:
# delta *= w[:, None]
# self.backpropagate(delta)
# if update:
# self.update(m)
#
# train_metrics = {"cost": self.cost(self.output, Y) / m}
# if metrics:
# for metric in metrics:
# train_metrics[str(metric).lower()] = metric(preds, Y) / m
# return train_metrics
#
# def backpropagate(self, error):
# for layer in self.layers[-1:0:-1]:
# error = layer.backpropagate(error)
# return error
#
# def update(self, m):
# W = self.layers.get_weights(unfold=True)
# gW = self.get_gradients(unfold=True)
# oW = self.optimizer.optimize(W, gW, m)
# self.layers.set_weights(oW, fold=True)
# self.zero_gradients()
#
# def get_weights(self, unfold=True):
# return self.layers.get_weights(unfold=unfold)
#
# def set_weigts(self, ws, fold=True):
# self.layers.set_weights(ws=ws, fold=fold)
#
# def get_gradients(self, unfold=True):
# grads = [l.gradients for l in self.layers if l.trainable]
# if unfold:
# grads = np.concatenate(grads)
# return grads
#
# def set_gradients(self, gradients, fold=True):
# trl = (l for l in self.layers if l.trainable)
# if fold:
# start = 0
# for layer in trl:
# end = start + layer.num_params
# layer.set_weights(gradients[start:end])
# start = end
# else:
# for w, layer in zip(gradients, trl):
# layer.set_weights(w)
#
# def zero_gradients(self):
# for layer in self.layers:
# if not layer.trainable:
# continue
# layer.nabla_w *= 0
# layer.nabla_b *= 0
#
# @property
# def num_params(self):
# return self.layers.num_params
#
# @property
# def output_shape(self):
# return self.layers.output_shape
#
# @property
# def input_shape(self):
# return self.layers.input_shape
#
# Path: brainforge/layers/core.py
# class Dense(FFBase):
#
# def connect(self, brain):
# inshape = brain.outshape
# if len(inshape) != 1:
# err = "Dense only accepts input shapes with 1 dimension!\n"
# err += "Maybe you should consider placing <Flatten> before <Dense>?"
# raise RuntimeError(err)
# self.weights = white(inshape[0], self.neurons)
# self.biases = zX(self.neurons)
# super().connect(brain)
# if self.compiled:
# from .. import llatomic
# print("Compiling DenseLayer...")
# self.op = llatomic.DenseOp()
# else:
# self.op = atomic.DenseOp()
#
# def feedforward(self, X):
# self.inputs = X
# self.output = self.activation.forward(self.op.forward(
# X, self.weights, self.biases
# ))
# return self.output
#
# def backpropagate(self, delta):
# delta *= self.activation.backward(self.output)
# nabla_w, nabla_b, dX = self.op.backward(self.inputs, delta, self.weights)
# self.nabla_w += nabla_w
# self.nabla_b += nabla_b
# return dX
#
# def __str__(self):
# return "Dense-{}-{}".format(self.neurons, str(self.activation)[:5])
#
# Path: brainforge/optimizers/gradient_descent.py
# class Momentum(SGD):
#
# def __init__(self, eta=0.1, mu=0.9):
# super().__init__(eta)
# self.mu = mu
# self.velocity = None
#
# def initialize(self, nparams, velocity=None):
# self.velocity = np.zeros((nparams,)) if velocity is None else velocity
#
# def optimize(self, W, gW, m):
# eta = self.eta / m
# self.velocity = self.velocity * self.mu + gW * eta
# return W - self.velocity
#
# def __str__(self):
# return "Momentum"
#
# Path: brainforge/util/_etalon.py
# X, Y = _data[:, :4].astype(float), _data[:, 4:].astype(float)
. Output only the next line. | while 1: |
Based on the snippet: <|code_start|>
class DNI:
def __init__(self, bpropnet, synth):
self.bpropnet = bpropnet
self.synth = synth
self._predictor = None
def predictor_coro(self):
prediction = None
delta_backwards = None
while 1:
inputs = yield prediction, delta_backwards
prediction = self.bpropnet.predict(inputs)
synthesized_delta = self.synth.predict(prediction)
self.bpropnet.update(len(inputs))
delta_backwards = self.bpropnet.backpropagate(synthesized_delta)
def predict(self, X):
if self._predictor is None:
self._predictor = self.predictor_coro()
next(self._predictor)
return self._predictor.send(X)
def udpate(self, true_delta):
<|code_end|>
, predict the immediate next line with the help of imports:
from brainforge.learner import Backpropagation
from brainforge.layers import Dense
from brainforge.optimizers import Momentum
from brainforge.util import etalon
and context (classes, functions, sometimes code) from other files:
# Path: brainforge/learner/backpropagation.py
# class Backpropagation(Learner):
#
# def __init__(self, layerstack, cost="mse", optimizer="sgd", name="", **kw):
# super().__init__(layerstack, cost, name, **kw)
# self.optimizer = (
# optimizer if isinstance(optimizer, GradientDescent) else optimizers[optimizer]()
# )
# self.optimizer.initialize(nparams=self.layers.num_params)
#
# def learn_batch(self, X, Y, w=None, metrics=(), update=True):
# m = len(X)
# preds = self.predict(X)
# delta = self.cost.derivative(preds, Y)
# if w is not None:
# delta *= w[:, None]
# self.backpropagate(delta)
# if update:
# self.update(m)
#
# train_metrics = {"cost": self.cost(self.output, Y) / m}
# if metrics:
# for metric in metrics:
# train_metrics[str(metric).lower()] = metric(preds, Y) / m
# return train_metrics
#
# def backpropagate(self, error):
# for layer in self.layers[-1:0:-1]:
# error = layer.backpropagate(error)
# return error
#
# def update(self, m):
# W = self.layers.get_weights(unfold=True)
# gW = self.get_gradients(unfold=True)
# oW = self.optimizer.optimize(W, gW, m)
# self.layers.set_weights(oW, fold=True)
# self.zero_gradients()
#
# def get_weights(self, unfold=True):
# return self.layers.get_weights(unfold=unfold)
#
# def set_weigts(self, ws, fold=True):
# self.layers.set_weights(ws=ws, fold=fold)
#
# def get_gradients(self, unfold=True):
# grads = [l.gradients for l in self.layers if l.trainable]
# if unfold:
# grads = np.concatenate(grads)
# return grads
#
# def set_gradients(self, gradients, fold=True):
# trl = (l for l in self.layers if l.trainable)
# if fold:
# start = 0
# for layer in trl:
# end = start + layer.num_params
# layer.set_weights(gradients[start:end])
# start = end
# else:
# for w, layer in zip(gradients, trl):
# layer.set_weights(w)
#
# def zero_gradients(self):
# for layer in self.layers:
# if not layer.trainable:
# continue
# layer.nabla_w *= 0
# layer.nabla_b *= 0
#
# @property
# def num_params(self):
# return self.layers.num_params
#
# @property
# def output_shape(self):
# return self.layers.output_shape
#
# @property
# def input_shape(self):
# return self.layers.input_shape
#
# Path: brainforge/layers/core.py
# class Dense(FFBase):
#
# def connect(self, brain):
# inshape = brain.outshape
# if len(inshape) != 1:
# err = "Dense only accepts input shapes with 1 dimension!\n"
# err += "Maybe you should consider placing <Flatten> before <Dense>?"
# raise RuntimeError(err)
# self.weights = white(inshape[0], self.neurons)
# self.biases = zX(self.neurons)
# super().connect(brain)
# if self.compiled:
# from .. import llatomic
# print("Compiling DenseLayer...")
# self.op = llatomic.DenseOp()
# else:
# self.op = atomic.DenseOp()
#
# def feedforward(self, X):
# self.inputs = X
# self.output = self.activation.forward(self.op.forward(
# X, self.weights, self.biases
# ))
# return self.output
#
# def backpropagate(self, delta):
# delta *= self.activation.backward(self.output)
# nabla_w, nabla_b, dX = self.op.backward(self.inputs, delta, self.weights)
# self.nabla_w += nabla_w
# self.nabla_b += nabla_b
# return dX
#
# def __str__(self):
# return "Dense-{}-{}".format(self.neurons, str(self.activation)[:5])
#
# Path: brainforge/optimizers/gradient_descent.py
# class Momentum(SGD):
#
# def __init__(self, eta=0.1, mu=0.9):
# super().__init__(eta)
# self.mu = mu
# self.velocity = None
#
# def initialize(self, nparams, velocity=None):
# self.velocity = np.zeros((nparams,)) if velocity is None else velocity
#
# def optimize(self, W, gW, m):
# eta = self.eta / m
# self.velocity = self.velocity * self.mu + gW * eta
# return W - self.velocity
#
# def __str__(self):
# return "Momentum"
#
# Path: brainforge/util/_etalon.py
# X, Y = _data[:, :4].astype(float), _data[:, 4:].astype(float)
. Output only the next line. | synthesizer_delta = self.synth.cost.derivative( |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
DEFAULT_DELIMITER = ','
@python_2_unicode_compatible
class SelectMultipleField(six.with_metaclass(models.SubfieldBase,
<|code_end|>
. Use current file imports:
from django.core import exceptions, validators
from django.db import models
from django.utils import six
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from .codecs import decode_csv_to_list, encode_list_to_csv
from .validators import MaxChoicesValidator, MaxLengthValidator
from south.modelsinspector import introspector
import select_multiple_field.forms as forms
and context (classes, functions, or code) from other files:
# Path: select_multiple_field/codecs.py
# def decode_csv_to_list(encoded):
# """
# Decodes a delimiter separated string to a Python list
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# if encoded == '':
# return []
#
# decoded = sorted(set(encoded.split(delimiter)))
# return decoded
#
# def encode_list_to_csv(decoded):
# """
# Encodes a Python list to a delimiter separated string
#
# Note: This sorts the list lexicographically
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# decoded = sorted(set(decoded))
# return delimiter.join(decoded)
#
# Path: select_multiple_field/validators.py
# class MaxChoicesValidator(validators.BaseValidator):
#
# message = ungettext_lazy(
# 'Ensure this value has at most %(limit_value)d choice (it has %(show_value)d).', # NOQA
# 'Ensure this value has at most %(limit_value)d choices (it has %(show_value)d).', # NOQA
# 'limit_value')
# code = 'max_choices'
#
# def compare(self, a, b):
# return a > b
#
# def clean(self, x):
# return len(x)
#
# class MaxLengthValidator(validators.BaseValidator):
#
# message = ungettext_lazy(
# 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).', # NOQA
# 'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).', # NOQA
# 'limit_value')
# code = 'max_length'
#
# def compare(self, a, b):
# return a > b
#
# def clean(self, value):
# return len(force_text(encode_list_to_csv(value)))
. Output only the next line. | models.Field)): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
DEFAULT_DELIMITER = ','
@python_2_unicode_compatible
<|code_end|>
with the help of current file imports:
from django.core import exceptions, validators
from django.db import models
from django.utils import six
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from .codecs import decode_csv_to_list, encode_list_to_csv
from .validators import MaxChoicesValidator, MaxLengthValidator
from south.modelsinspector import introspector
import select_multiple_field.forms as forms
and context from other files:
# Path: select_multiple_field/codecs.py
# def decode_csv_to_list(encoded):
# """
# Decodes a delimiter separated string to a Python list
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# if encoded == '':
# return []
#
# decoded = sorted(set(encoded.split(delimiter)))
# return decoded
#
# def encode_list_to_csv(decoded):
# """
# Encodes a Python list to a delimiter separated string
#
# Note: This sorts the list lexicographically
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# decoded = sorted(set(decoded))
# return delimiter.join(decoded)
#
# Path: select_multiple_field/validators.py
# class MaxChoicesValidator(validators.BaseValidator):
#
# message = ungettext_lazy(
# 'Ensure this value has at most %(limit_value)d choice (it has %(show_value)d).', # NOQA
# 'Ensure this value has at most %(limit_value)d choices (it has %(show_value)d).', # NOQA
# 'limit_value')
# code = 'max_choices'
#
# def compare(self, a, b):
# return a > b
#
# def clean(self, x):
# return len(x)
#
# class MaxLengthValidator(validators.BaseValidator):
#
# message = ungettext_lazy(
# 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).', # NOQA
# 'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).', # NOQA
# 'limit_value')
# code = 'max_length'
#
# def compare(self, a, b):
# return a > b
#
# def clean(self, value):
# return len(force_text(encode_list_to_csv(value)))
, which may contain function names, class names, or code. Output only the next line. | class SelectMultipleField(six.with_metaclass(models.SubfieldBase, |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
DEFAULT_DELIMITER = ','
@python_2_unicode_compatible
<|code_end|>
. Write the next line using the current file imports:
from django.core import exceptions, validators
from django.db import models
from django.utils import six
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from .codecs import decode_csv_to_list, encode_list_to_csv
from .validators import MaxChoicesValidator, MaxLengthValidator
from south.modelsinspector import introspector
import select_multiple_field.forms as forms
and context from other files:
# Path: select_multiple_field/codecs.py
# def decode_csv_to_list(encoded):
# """
# Decodes a delimiter separated string to a Python list
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# if encoded == '':
# return []
#
# decoded = sorted(set(encoded.split(delimiter)))
# return decoded
#
# def encode_list_to_csv(decoded):
# """
# Encodes a Python list to a delimiter separated string
#
# Note: This sorts the list lexicographically
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# decoded = sorted(set(decoded))
# return delimiter.join(decoded)
#
# Path: select_multiple_field/validators.py
# class MaxChoicesValidator(validators.BaseValidator):
#
# message = ungettext_lazy(
# 'Ensure this value has at most %(limit_value)d choice (it has %(show_value)d).', # NOQA
# 'Ensure this value has at most %(limit_value)d choices (it has %(show_value)d).', # NOQA
# 'limit_value')
# code = 'max_choices'
#
# def compare(self, a, b):
# return a > b
#
# def clean(self, x):
# return len(x)
#
# class MaxLengthValidator(validators.BaseValidator):
#
# message = ungettext_lazy(
# 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).', # NOQA
# 'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).', # NOQA
# 'limit_value')
# code = 'max_length'
#
# def compare(self, a, b):
# return a > b
#
# def clean(self, value):
# return len(force_text(encode_list_to_csv(value)))
, which may include functions, classes, or code. Output only the next line. | class SelectMultipleField(six.with_metaclass(models.SubfieldBase, |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class SelectMultipleFieldTestCase(SimpleTestCase):
def setUp(self):
self.choices = (
('a', 'Alpha'),
('b', 'Bravo'),
('c', 'Charlie'),
)
def test_instantiation(self):
w = SelectMultipleField()
self.assertIsInstance(w, widgets.SelectMultiple)
<|code_end|>
, generate the next line using the imports in this file:
from django.forms import widgets
from django.test import SimpleTestCase
from django.utils.datastructures import MultiValueDict
from select_multiple_field.widgets import (
HTML_ATTR_CLASS, SelectMultipleField)
and context (functions, classes, or occasionally code) from other files:
# Path: select_multiple_field/widgets.py
# HTML_ATTR_CLASS = 'select-multiple-field'
#
# class SelectMultipleField(widgets.SelectMultiple):
# """Multiple select widget ready for jQuery multiselect.js"""
#
# allow_multiple_selected = True
#
# def render(self, name, value, attrs={}, choices=()):
# rendered_attrs = {'class': HTML_ATTR_CLASS}
# rendered_attrs.update(attrs)
# if value is None:
# value = []
#
# final_attrs = self.build_attrs(rendered_attrs, name=name)
# # output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)]
# output = [format_html('<select multiple="multiple"{0}>',
# flatatt(final_attrs))]
# options = self.render_options(choices, value)
# if options:
# output.append(options)
#
# output.append('</select>')
# return mark_safe('\n'.join(output))
#
# def value_from_datadict(self, data, files, name):
# """
# SelectMultipleField widget delegates processing of raw user data to
# Django's SelectMultiple widget
#
# Returns list or None
# """
# return super(SelectMultipleField, self).value_from_datadict(
# data, files, name)
. Output only the next line. | def test_has_select_multiple_class(self): |
Using the snippet: <|code_start|>
class PizzaListView(ListView):
queryset = Pizza.objects.order_by('-id')
context_object_name = 'pizzas'
paginate_by = 10
class PizzaCreateView(CreateView):
model = Pizza
fields = ['toppings']
success_url = reverse_lazy('pizza:created')
class PizzaDetailView(DetailView):
model = Pizza
class PizzaUpdateView(UpdateView):
model = Pizza
fields = ['toppings']
success_url = reverse_lazy('pizza:updated')
<|code_end|>
, determine the next line of code. You have imports:
from django.core.urlresolvers import reverse_lazy
from django.views.generic import (
CreateView, DetailView, DeleteView, ListView, UpdateView)
from django.utils.encoding import force_text
from .models import Pizza
and context (class names, function names, or code) available:
# Path: test_projects/django18/pizzagigi/models.py
# class Pizza(models.Model):
# """Pizza demonstrates minimal use-case"""
#
# ANCHOVIES = 'a'
# BLACK_OLIVES = 'b'
# CHEDDAR_CHEESE = 'c'
# EGG = 'e'
# PANCETTA = 'pk'
# PEPPERONI = 'p'
# PROSCIUTTO_CRUDO = 'P'
# MOZZARELLA = 'm'
# MUSHROOMS = 'M'
# TOMATO = 't'
# TOPPING_CHOICES = (
# (ANCHOVIES, _('Anchovies')),
# (BLACK_OLIVES, _('Black olives')),
# (CHEDDAR_CHEESE, _('Cheddar cheese')),
# (EGG, _('Eggs')),
# (PANCETTA, _('Pancetta')),
# (PEPPERONI, _('Pepperoni')),
# (PROSCIUTTO_CRUDO, _('Prosciutto crudo')),
# (MOZZARELLA, _('Mozzarella')),
# (MUSHROOMS, _('Mushrooms')),
# (TOMATO, _('Tomato')),
# )
#
# toppings = SelectMultipleField(
# max_length=10,
# choices=TOPPING_CHOICES
# )
#
# def get_toppings(self):
# if self.toppings:
# keys_choices = self.toppings
# return '%s' % (', '.join(filter(bool, keys_choices)))
# get_toppings.short_description = _('Toppings')
#
# def __str__(self):
# return "pk=%s" % force_text(self.pk)
#
# def get_absolute_url(self):
# return reverse('pizza:detail', args=[self.pk])
. Output only the next line. | class PizzaDeleteView(DeleteView): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class SelectMultipleFormFieldTestCase(SimpleTestCase):
def setUp(self):
self.choices = tuple([(c, c) for c in string.ascii_letters])
<|code_end|>
with the help of current file imports:
import string
from django.forms import fields
from django.test import SimpleTestCase
from select_multiple_field.codecs import encode_list_to_csv
from select_multiple_field.forms import (
DEFAULT_MAX_CHOICES_ATTR, SelectMultipleFormField)
from select_multiple_field.widgets import SelectMultipleField
and context from other files:
# Path: select_multiple_field/codecs.py
# def encode_list_to_csv(decoded):
# """
# Encodes a Python list to a delimiter separated string
#
# Note: This sorts the list lexicographically
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# decoded = sorted(set(decoded))
# return delimiter.join(decoded)
#
# Path: select_multiple_field/forms.py
# DEFAULT_MAX_CHOICES_ATTR = 'data-max-choices'
#
# class SelectMultipleFormField(fields.MultipleChoiceField):
#
# widget = SelectMultipleField
#
# def __init__(
# self, max_length=None, size=4, max_choices=None,
# max_choices_attr=DEFAULT_MAX_CHOICES_ATTR,
# *args, **kwargs):
# """
# max_length refers to number of characters used to store the encoded
# list of choices (est. 2n - 1)
#
# size is the HTML element size attribute passed to the widget
#
# max_choices is the maximum number of choices allowed by the field
#
# max_choices_attr is a string used as an attribute name in the widget
# representation of max_choices (currently a data attribute)
#
# coerce is bound to ModelField.to_python method when using
# ModelViewMixin, otherwise it returns what is passed (the identity
# function)
#
# empty_value is the value used to represent an empty field
# """
# self.max_length, self.max_choices = max_length, max_choices
# self.size, self.max_choices_attr = size, max_choices_attr
# self.coerce = kwargs.pop('coerce', lambda val: val)
# self.empty_value = kwargs.pop('empty_value', [])
# if not hasattr(self, 'empty_values'):
# self.empty_values = list(validators.EMPTY_VALUES)
# super(SelectMultipleFormField, self).__init__(*args, **kwargs)
#
# def to_python(self, value):
# """
# Takes processed widget data as value, possibly a char string, and
# makes it into a Python list
#
# Returns a Python list
#
# Method also handles lists and strings
# """
# if (value == self.empty_value) or (value in self.empty_values):
# return self.empty_value
#
# if isinstance(value, six.string_types):
# if len(value) == 0:
# return []
#
# native = decode_csv_to_list(value)
# return native
#
# return list(value)
#
# def _coerce(self, value):
# return value
#
# def get_prep_value(self, value):
# """
# Prepares a string for use in serializer
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# if isinstance(value, (list, tuple)):
# if len(value) == 0:
# return ''
# else:
# return delimiter.join(value)
#
# return ''
#
# # def validate(self, value):
# # checked_out = True
# # for val in value:
# # if not self.valid_value(val):
# # checked_out = False
# #
# # return super(SelectMultipleFormField, self).validate(value)
#
# def widget_attrs(self, widget):
# """
# Given a Widget instance (*not* a Widget class), returns a dictionary of
# any HTML attributes that should be added to the Widget, based on this
# Field.
# """
# attrs = super(SelectMultipleFormField, self).widget_attrs(widget)
# if self.size != 4:
# attrs.update({'size': str(self.size)})
#
# if self.max_choices:
# attrs.update({self.max_choices_attr: str(self.max_choices)})
#
# return attrs
#
# Path: select_multiple_field/widgets.py
# class SelectMultipleField(widgets.SelectMultiple):
# """Multiple select widget ready for jQuery multiselect.js"""
#
# allow_multiple_selected = True
#
# def render(self, name, value, attrs={}, choices=()):
# rendered_attrs = {'class': HTML_ATTR_CLASS}
# rendered_attrs.update(attrs)
# if value is None:
# value = []
#
# final_attrs = self.build_attrs(rendered_attrs, name=name)
# # output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)]
# output = [format_html('<select multiple="multiple"{0}>',
# flatatt(final_attrs))]
# options = self.render_options(choices, value)
# if options:
# output.append(options)
#
# output.append('</select>')
# return mark_safe('\n'.join(output))
#
# def value_from_datadict(self, data, files, name):
# """
# SelectMultipleField widget delegates processing of raw user data to
# Django's SelectMultiple widget
#
# Returns list or None
# """
# return super(SelectMultipleField, self).value_from_datadict(
# data, files, name)
, which may contain function names, class names, or code. Output only the next line. | self.choices_list = [c[0] for c in self.choices[0:len(self.choices)]] |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class SelectMultipleFormFieldTestCase(SimpleTestCase):
def setUp(self):
self.choices = tuple([(c, c) for c in string.ascii_letters])
self.choices_list = [c[0] for c in self.choices[0:len(self.choices)]]
def test_instantiation(self):
ff = SelectMultipleFormField()
self.assertIsInstance(ff, fields.Field)
self.assertIsInstance(ff, fields.MultipleChoiceField)
<|code_end|>
, predict the immediate next line with the help of imports:
import string
from django.forms import fields
from django.test import SimpleTestCase
from select_multiple_field.codecs import encode_list_to_csv
from select_multiple_field.forms import (
DEFAULT_MAX_CHOICES_ATTR, SelectMultipleFormField)
from select_multiple_field.widgets import SelectMultipleField
and context (classes, functions, sometimes code) from other files:
# Path: select_multiple_field/codecs.py
# def encode_list_to_csv(decoded):
# """
# Encodes a Python list to a delimiter separated string
#
# Note: This sorts the list lexicographically
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# decoded = sorted(set(decoded))
# return delimiter.join(decoded)
#
# Path: select_multiple_field/forms.py
# DEFAULT_MAX_CHOICES_ATTR = 'data-max-choices'
#
# class SelectMultipleFormField(fields.MultipleChoiceField):
#
# widget = SelectMultipleField
#
# def __init__(
# self, max_length=None, size=4, max_choices=None,
# max_choices_attr=DEFAULT_MAX_CHOICES_ATTR,
# *args, **kwargs):
# """
# max_length refers to number of characters used to store the encoded
# list of choices (est. 2n - 1)
#
# size is the HTML element size attribute passed to the widget
#
# max_choices is the maximum number of choices allowed by the field
#
# max_choices_attr is a string used as an attribute name in the widget
# representation of max_choices (currently a data attribute)
#
# coerce is bound to ModelField.to_python method when using
# ModelViewMixin, otherwise it returns what is passed (the identity
# function)
#
# empty_value is the value used to represent an empty field
# """
# self.max_length, self.max_choices = max_length, max_choices
# self.size, self.max_choices_attr = size, max_choices_attr
# self.coerce = kwargs.pop('coerce', lambda val: val)
# self.empty_value = kwargs.pop('empty_value', [])
# if not hasattr(self, 'empty_values'):
# self.empty_values = list(validators.EMPTY_VALUES)
# super(SelectMultipleFormField, self).__init__(*args, **kwargs)
#
# def to_python(self, value):
# """
# Takes processed widget data as value, possibly a char string, and
# makes it into a Python list
#
# Returns a Python list
#
# Method also handles lists and strings
# """
# if (value == self.empty_value) or (value in self.empty_values):
# return self.empty_value
#
# if isinstance(value, six.string_types):
# if len(value) == 0:
# return []
#
# native = decode_csv_to_list(value)
# return native
#
# return list(value)
#
# def _coerce(self, value):
# return value
#
# def get_prep_value(self, value):
# """
# Prepares a string for use in serializer
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# if isinstance(value, (list, tuple)):
# if len(value) == 0:
# return ''
# else:
# return delimiter.join(value)
#
# return ''
#
# # def validate(self, value):
# # checked_out = True
# # for val in value:
# # if not self.valid_value(val):
# # checked_out = False
# #
# # return super(SelectMultipleFormField, self).validate(value)
#
# def widget_attrs(self, widget):
# """
# Given a Widget instance (*not* a Widget class), returns a dictionary of
# any HTML attributes that should be added to the Widget, based on this
# Field.
# """
# attrs = super(SelectMultipleFormField, self).widget_attrs(widget)
# if self.size != 4:
# attrs.update({'size': str(self.size)})
#
# if self.max_choices:
# attrs.update({self.max_choices_attr: str(self.max_choices)})
#
# return attrs
#
# Path: select_multiple_field/widgets.py
# class SelectMultipleField(widgets.SelectMultiple):
# """Multiple select widget ready for jQuery multiselect.js"""
#
# allow_multiple_selected = True
#
# def render(self, name, value, attrs={}, choices=()):
# rendered_attrs = {'class': HTML_ATTR_CLASS}
# rendered_attrs.update(attrs)
# if value is None:
# value = []
#
# final_attrs = self.build_attrs(rendered_attrs, name=name)
# # output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)]
# output = [format_html('<select multiple="multiple"{0}>',
# flatatt(final_attrs))]
# options = self.render_options(choices, value)
# if options:
# output.append(options)
#
# output.append('</select>')
# return mark_safe('\n'.join(output))
#
# def value_from_datadict(self, data, files, name):
# """
# SelectMultipleField widget delegates processing of raw user data to
# Django's SelectMultiple widget
#
# Returns list or None
# """
# return super(SelectMultipleField, self).value_from_datadict(
# data, files, name)
. Output only the next line. | def test_widget_class(self): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class SelectMultipleFormFieldTestCase(SimpleTestCase):
def setUp(self):
self.choices = tuple([(c, c) for c in string.ascii_letters])
self.choices_list = [c[0] for c in self.choices[0:len(self.choices)]]
<|code_end|>
. Use current file imports:
(import string
from django.forms import fields
from django.test import SimpleTestCase
from select_multiple_field.codecs import encode_list_to_csv
from select_multiple_field.forms import (
DEFAULT_MAX_CHOICES_ATTR, SelectMultipleFormField)
from select_multiple_field.widgets import SelectMultipleField)
and context including class names, function names, or small code snippets from other files:
# Path: select_multiple_field/codecs.py
# def encode_list_to_csv(decoded):
# """
# Encodes a Python list to a delimiter separated string
#
# Note: This sorts the list lexicographically
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# decoded = sorted(set(decoded))
# return delimiter.join(decoded)
#
# Path: select_multiple_field/forms.py
# DEFAULT_MAX_CHOICES_ATTR = 'data-max-choices'
#
# class SelectMultipleFormField(fields.MultipleChoiceField):
#
# widget = SelectMultipleField
#
# def __init__(
# self, max_length=None, size=4, max_choices=None,
# max_choices_attr=DEFAULT_MAX_CHOICES_ATTR,
# *args, **kwargs):
# """
# max_length refers to number of characters used to store the encoded
# list of choices (est. 2n - 1)
#
# size is the HTML element size attribute passed to the widget
#
# max_choices is the maximum number of choices allowed by the field
#
# max_choices_attr is a string used as an attribute name in the widget
# representation of max_choices (currently a data attribute)
#
# coerce is bound to ModelField.to_python method when using
# ModelViewMixin, otherwise it returns what is passed (the identity
# function)
#
# empty_value is the value used to represent an empty field
# """
# self.max_length, self.max_choices = max_length, max_choices
# self.size, self.max_choices_attr = size, max_choices_attr
# self.coerce = kwargs.pop('coerce', lambda val: val)
# self.empty_value = kwargs.pop('empty_value', [])
# if not hasattr(self, 'empty_values'):
# self.empty_values = list(validators.EMPTY_VALUES)
# super(SelectMultipleFormField, self).__init__(*args, **kwargs)
#
# def to_python(self, value):
# """
# Takes processed widget data as value, possibly a char string, and
# makes it into a Python list
#
# Returns a Python list
#
# Method also handles lists and strings
# """
# if (value == self.empty_value) or (value in self.empty_values):
# return self.empty_value
#
# if isinstance(value, six.string_types):
# if len(value) == 0:
# return []
#
# native = decode_csv_to_list(value)
# return native
#
# return list(value)
#
# def _coerce(self, value):
# return value
#
# def get_prep_value(self, value):
# """
# Prepares a string for use in serializer
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# if isinstance(value, (list, tuple)):
# if len(value) == 0:
# return ''
# else:
# return delimiter.join(value)
#
# return ''
#
# # def validate(self, value):
# # checked_out = True
# # for val in value:
# # if not self.valid_value(val):
# # checked_out = False
# #
# # return super(SelectMultipleFormField, self).validate(value)
#
# def widget_attrs(self, widget):
# """
# Given a Widget instance (*not* a Widget class), returns a dictionary of
# any HTML attributes that should be added to the Widget, based on this
# Field.
# """
# attrs = super(SelectMultipleFormField, self).widget_attrs(widget)
# if self.size != 4:
# attrs.update({'size': str(self.size)})
#
# if self.max_choices:
# attrs.update({self.max_choices_attr: str(self.max_choices)})
#
# return attrs
#
# Path: select_multiple_field/widgets.py
# class SelectMultipleField(widgets.SelectMultiple):
# """Multiple select widget ready for jQuery multiselect.js"""
#
# allow_multiple_selected = True
#
# def render(self, name, value, attrs={}, choices=()):
# rendered_attrs = {'class': HTML_ATTR_CLASS}
# rendered_attrs.update(attrs)
# if value is None:
# value = []
#
# final_attrs = self.build_attrs(rendered_attrs, name=name)
# # output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)]
# output = [format_html('<select multiple="multiple"{0}>',
# flatatt(final_attrs))]
# options = self.render_options(choices, value)
# if options:
# output.append(options)
#
# output.append('</select>')
# return mark_safe('\n'.join(output))
#
# def value_from_datadict(self, data, files, name):
# """
# SelectMultipleField widget delegates processing of raw user data to
# Django's SelectMultiple widget
#
# Returns list or None
# """
# return super(SelectMultipleField, self).value_from_datadict(
# data, files, name)
. Output only the next line. | def test_instantiation(self): |
Next line prediction: <|code_start|>
urlpatterns = patterns('', # NOQA
url(r'^$', ChickenWingsListView.as_view(), name='list'),
url(r'^create/$', ChickenWingsCreateView.as_view(), name='create'),
url(r'^created/$', TemplateView.as_view(
template_name='forthewing/chickenwings_created.html'), name='created'),
url(r'^detail/(?P<pk>[0-9]*)$',
ChickenWingsDetailView.as_view(), name='detail'),
<|code_end|>
. Use current file imports:
(from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from .views import (
ChickenWingsCreateView, ChickenWingsDeleteView, ChickenWingsDetailView,
ChickenWingsListView, ChickenWingsUpdateView
))
and context including class names, function names, or small code snippets from other files:
# Path: test_projects/django18/forthewing/views.py
# class ChickenWingsCreateView(CreateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:created')
# context_object_name = 'wings'
#
# class ChickenWingsDeleteView(DeleteView):
#
# model = ChickenWings
# success_url = reverse_lazy('ftw:deleted')
#
# def get_success_url(self):
# return force_text(self.success_url)
#
# class ChickenWingsDetailView(DetailView):
#
# model = ChickenWings
#
# class ChickenWingsListView(ListView):
#
# queryset = ChickenWings.objects.order_by('-id')
# context_object_name = 'chickenwings'
# paginate_by = 10
#
# class ChickenWingsUpdateView(UpdateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:updated')
. Output only the next line. | url(r'^update/(?P<pk>[0-9]*)$', |
Continue the code snippet: <|code_start|>
urlpatterns = patterns('', # NOQA
url(r'^$', ChickenWingsListView.as_view(), name='list'),
url(r'^create/$', ChickenWingsCreateView.as_view(), name='create'),
url(r'^created/$', TemplateView.as_view(
template_name='forthewing/chickenwings_created.html'), name='created'),
<|code_end|>
. Use current file imports:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from .views import (
ChickenWingsCreateView, ChickenWingsDeleteView, ChickenWingsDetailView,
ChickenWingsListView, ChickenWingsUpdateView
)
and context (classes, functions, or code) from other files:
# Path: test_projects/django18/forthewing/views.py
# class ChickenWingsCreateView(CreateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:created')
# context_object_name = 'wings'
#
# class ChickenWingsDeleteView(DeleteView):
#
# model = ChickenWings
# success_url = reverse_lazy('ftw:deleted')
#
# def get_success_url(self):
# return force_text(self.success_url)
#
# class ChickenWingsDetailView(DetailView):
#
# model = ChickenWings
#
# class ChickenWingsListView(ListView):
#
# queryset = ChickenWings.objects.order_by('-id')
# context_object_name = 'chickenwings'
# paginate_by = 10
#
# class ChickenWingsUpdateView(UpdateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:updated')
. Output only the next line. | url(r'^detail/(?P<pk>[0-9]*)$', |
Using the snippet: <|code_start|>
urlpatterns = patterns('', # NOQA
url(r'^$', ChickenWingsListView.as_view(), name='list'),
url(r'^create/$', ChickenWingsCreateView.as_view(), name='create'),
url(r'^created/$', TemplateView.as_view(
template_name='forthewing/chickenwings_created.html'), name='created'),
url(r'^detail/(?P<pk>[0-9]*)$',
ChickenWingsDetailView.as_view(), name='detail'),
url(r'^update/(?P<pk>[0-9]*)$',
ChickenWingsUpdateView.as_view(), name='update'),
url(r'^updated/$', TemplateView.as_view(
template_name='forthewing/chickenwings_updated.html'), name='updated'),
url(r'^delete/(?P<pk>[0-9]*)$',
ChickenWingsDeleteView.as_view(), name='delete'),
url(r'^deleted/$', TemplateView.as_view(
<|code_end|>
, determine the next line of code. You have imports:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from .views import (
ChickenWingsCreateView, ChickenWingsDeleteView, ChickenWingsDetailView,
ChickenWingsListView, ChickenWingsUpdateView
)
and context (class names, function names, or code) available:
# Path: test_projects/django18/forthewing/views.py
# class ChickenWingsCreateView(CreateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:created')
# context_object_name = 'wings'
#
# class ChickenWingsDeleteView(DeleteView):
#
# model = ChickenWings
# success_url = reverse_lazy('ftw:deleted')
#
# def get_success_url(self):
# return force_text(self.success_url)
#
# class ChickenWingsDetailView(DetailView):
#
# model = ChickenWings
#
# class ChickenWingsListView(ListView):
#
# queryset = ChickenWings.objects.order_by('-id')
# context_object_name = 'chickenwings'
# paginate_by = 10
#
# class ChickenWingsUpdateView(UpdateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:updated')
. Output only the next line. | template_name='forthewing/chickenwings_deleted.html'), name='deleted'), |
Here is a snippet: <|code_start|>
urlpatterns = patterns('', # NOQA
url(r'^$', ChickenWingsListView.as_view(), name='list'),
url(r'^create/$', ChickenWingsCreateView.as_view(), name='create'),
url(r'^created/$', TemplateView.as_view(
template_name='forthewing/chickenwings_created.html'), name='created'),
url(r'^detail/(?P<pk>[0-9]*)$',
ChickenWingsDetailView.as_view(), name='detail'),
url(r'^update/(?P<pk>[0-9]*)$',
ChickenWingsUpdateView.as_view(), name='update'),
url(r'^updated/$', TemplateView.as_view(
template_name='forthewing/chickenwings_updated.html'), name='updated'),
url(r'^delete/(?P<pk>[0-9]*)$',
ChickenWingsDeleteView.as_view(), name='delete'),
url(r'^deleted/$', TemplateView.as_view(
template_name='forthewing/chickenwings_deleted.html'), name='deleted'),
<|code_end|>
. Write the next line using the current file imports:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from .views import (
ChickenWingsCreateView, ChickenWingsDeleteView, ChickenWingsDetailView,
ChickenWingsListView, ChickenWingsUpdateView
)
and context from other files:
# Path: test_projects/django18/forthewing/views.py
# class ChickenWingsCreateView(CreateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:created')
# context_object_name = 'wings'
#
# class ChickenWingsDeleteView(DeleteView):
#
# model = ChickenWings
# success_url = reverse_lazy('ftw:deleted')
#
# def get_success_url(self):
# return force_text(self.success_url)
#
# class ChickenWingsDetailView(DetailView):
#
# model = ChickenWings
#
# class ChickenWingsListView(ListView):
#
# queryset = ChickenWings.objects.order_by('-id')
# context_object_name = 'chickenwings'
# paginate_by = 10
#
# class ChickenWingsUpdateView(UpdateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:updated')
, which may include functions, classes, or code. Output only the next line. | ) |
Given snippet: <|code_start|>
urlpatterns = patterns('', # NOQA
url(r'^$', ChickenWingsListView.as_view(), name='list'),
url(r'^create/$', ChickenWingsCreateView.as_view(), name='create'),
url(r'^created/$', TemplateView.as_view(
template_name='forthewing/chickenwings_created.html'), name='created'),
url(r'^detail/(?P<pk>[0-9]*)$',
ChickenWingsDetailView.as_view(), name='detail'),
url(r'^update/(?P<pk>[0-9]*)$',
ChickenWingsUpdateView.as_view(), name='update'),
url(r'^updated/$', TemplateView.as_view(
template_name='forthewing/chickenwings_updated.html'), name='updated'),
url(r'^delete/(?P<pk>[0-9]*)$',
ChickenWingsDeleteView.as_view(), name='delete'),
url(r'^deleted/$', TemplateView.as_view(
template_name='forthewing/chickenwings_deleted.html'), name='deleted'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from .views import (
ChickenWingsCreateView, ChickenWingsDeleteView, ChickenWingsDetailView,
ChickenWingsListView, ChickenWingsUpdateView
)
and context:
# Path: test_projects/django18/forthewing/views.py
# class ChickenWingsCreateView(CreateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:created')
# context_object_name = 'wings'
#
# class ChickenWingsDeleteView(DeleteView):
#
# model = ChickenWings
# success_url = reverse_lazy('ftw:deleted')
#
# def get_success_url(self):
# return force_text(self.success_url)
#
# class ChickenWingsDetailView(DetailView):
#
# model = ChickenWings
#
# class ChickenWingsListView(ListView):
#
# queryset = ChickenWings.objects.order_by('-id')
# context_object_name = 'chickenwings'
# paginate_by = 10
#
# class ChickenWingsUpdateView(UpdateView):
#
# model = ChickenWings
# fields = ['flavour']
# success_url = reverse_lazy('ftw:updated')
which might include code, classes, or functions. Output only the next line. | ) |
Continue the code snippet: <|code_start|> )
self.test_list = ['a', 'b', 'c']
self.test_encoded = 'a,b,c'
self.wild_delimiter = 'シ'
self.test_encoded_alt = 'aシbシc'
def test_decoder(self):
decoded = decode_csv_to_list(self.test_encoded)
self.assertEqual(decoded, self.test_list)
decoded = decode_csv_to_list(self.test_encoded[0:1])
self.assertEqual(decoded, self.test_list[0:1])
def test_decoder_on_empty_string(self):
decoded = decode_csv_to_list('')
self.assertEqual(decoded, [])
def test_decoder_on_single_encoded_character(self):
single_encoded = self.choices[1][0]
decoded = decode_csv_to_list(single_encoded)
self.assertEqual(decoded, [single_encoded])
def test_decoder_deduplicates(self):
decoded = decode_csv_to_list(self.test_encoded + ',b,c,c')
self.assertEqual(decoded, self.test_list)
def test_decoder_delimiter(self):
with self.settings(SELECTMULTIPLEFIELD_DELIMITER=self.wild_delimiter):
decoded = decode_csv_to_list(self.test_encoded_alt)
self.assertEqual(decoded, self.test_list)
<|code_end|>
. Use current file imports:
from django.test import SimpleTestCase
from select_multiple_field.codecs import (
decode_csv_to_list, encode_list_to_csv)
and context (classes, functions, or code) from other files:
# Path: select_multiple_field/codecs.py
# def decode_csv_to_list(encoded):
# """
# Decodes a delimiter separated string to a Python list
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# if encoded == '':
# return []
#
# decoded = sorted(set(encoded.split(delimiter)))
# return decoded
#
# def encode_list_to_csv(decoded):
# """
# Encodes a Python list to a delimiter separated string
#
# Note: This sorts the list lexicographically
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# decoded = sorted(set(decoded))
# return delimiter.join(decoded)
. Output only the next line. | def test_encoder(self): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class CodecTestCase(SimpleTestCase):
def setUp(self):
self.choices = (
<|code_end|>
with the help of current file imports:
from django.test import SimpleTestCase
from select_multiple_field.codecs import (
decode_csv_to_list, encode_list_to_csv)
and context from other files:
# Path: select_multiple_field/codecs.py
# def decode_csv_to_list(encoded):
# """
# Decodes a delimiter separated string to a Python list
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# if encoded == '':
# return []
#
# decoded = sorted(set(encoded.split(delimiter)))
# return decoded
#
# def encode_list_to_csv(decoded):
# """
# Encodes a Python list to a delimiter separated string
#
# Note: This sorts the list lexicographically
# """
# delimiter = getattr(
# settings, 'SELECTMULTIPLEFIELD_DELIMITER', DEFAULT_DELIMITER)
# decoded = sorted(set(decoded))
# return delimiter.join(decoded)
, which may contain function names, class names, or code. Output only the next line. | ('a', 'Alpha'), |
Given the code snippet: <|code_start|> queryset = ChickenWings.objects.order_by('-id')
context_object_name = 'chickenwings'
paginate_by = 10
class ChickenWingsCreateView(CreateView):
model = ChickenWings
fields = ['flavour']
success_url = reverse_lazy('ftw:created')
context_object_name = 'wings'
class ChickenWingsDetailView(DetailView):
model = ChickenWings
class ChickenWingsUpdateView(UpdateView):
model = ChickenWings
fields = ['flavour']
success_url = reverse_lazy('ftw:updated')
class ChickenWingsDeleteView(DeleteView):
model = ChickenWings
success_url = reverse_lazy('ftw:deleted')
<|code_end|>
, generate the next line using the imports in this file:
from django.core.urlresolvers import reverse_lazy
from django.views.generic import (
CreateView, DetailView, DeleteView, ListView, UpdateView)
from django.utils.encoding import force_text
from .models import ChickenWings
and context (functions, classes, or occasionally code) from other files:
# Path: test_projects/django18/forthewing/models.py
# class ChickenWings(models.Model):
# """ChickenWings demonstrates optgroup usage and max_choices"""
#
# SUICIDE = 's'
# HOT = 'h'
# MEDIUM = 'm'
# MILD = 'M'
# CAJUN = 'c'
# JERK = 'j'
# HONEY_GARLIC = 'g'
# HONEY_BBQ = 'H'
# THAI = 't'
# BACON = 'b'
# BOURBON = 'B'
# FLAVOUR_CHOICES = (
# (_('Hot & Spicy'), (
# (SUICIDE, _('Suicide hot')),
# (HOT, _('Hot hot sauce')),
# (MEDIUM, _('Medium hot sauce')),
# (MILD, _('Mild hot sauce')),
# (CAJUN, _('Cajun sauce')),
# (JERK, _('Jerk sauce')))),
# (_('Sweets'), (
# (HONEY_GARLIC, _('Honey garlic')),
# (HONEY_BBQ, _('Honey barbeque')),
# (THAI, _('Thai sweet sauce')),
# (BACON, _('Messy bacon sauce')),
# (BOURBON, _('Bourbon whiskey barbeque')))),
# )
# flavour = SelectMultipleField(
# blank=True,
# include_blank=False,
# max_length=5,
# max_choices=2,
# choices=FLAVOUR_CHOICES
# )
#
# def __str__(self):
# return "pk=%s" % force_text(self.pk)
#
# def get_absolute_url(self):
# return reverse('ftw:detail', args=[self.pk])
. Output only the next line. | def get_success_url(self): |
Predict the next line after this snippet: <|code_start|>
urlpatterns = patterns('', # NOQA
url(r'^$', PizzaListView.as_view(), name='list'),
url(r'^create/$', PizzaCreateView.as_view(), name='create'),
url(r'^created/$', TemplateView.as_view(
template_name='pizzagigi/pizza_created.html'), name='created'),
url(r'^detail/(?P<pk>[0-9]*)$', PizzaDetailView.as_view(), name='detail'),
url(r'^update/(?P<pk>[0-9]*)$', PizzaUpdateView.as_view(), name='update'),
url(r'^updated/$', TemplateView.as_view(
template_name='pizzagigi/pizza_updated.html'), name='updated'),
url(r'^delete/(?P<pk>[0-9]*)$', PizzaDeleteView.as_view(), name='delete'),
url(r'^deleted/$', TemplateView.as_view(
template_name='pizzagigi/pizza_deleted.html'), name='deleted'),
<|code_end|>
using the current file's imports:
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from .views import (
PizzaCreateView, PizzaDeleteView, PizzaDetailView, PizzaListView,
PizzaUpdateView
)
and any relevant context from other files:
# Path: test_projects/django18/pizzagigi/views.py
# class PizzaCreateView(CreateView):
#
# model = Pizza
# fields = ['toppings']
# success_url = reverse_lazy('pizza:created')
#
# class PizzaDeleteView(DeleteView):
#
# model = Pizza
# success_url = reverse_lazy('pizza:deleted')
#
# def get_success_url(self):
# return force_text(self.success_url)
#
# class PizzaDetailView(DetailView):
#
# model = Pizza
#
# class PizzaListView(ListView):
#
# queryset = Pizza.objects.order_by('-id')
# context_object_name = 'pizzas'
# paginate_by = 10
#
# class PizzaUpdateView(UpdateView):
#
# model = Pizza
# fields = ['toppings']
# success_url = reverse_lazy('pizza:updated')
. Output only the next line. | ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.