Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>"""
Base page renderer class
"""
#Nonsense to make PTVS happy
class PdfBaseRenderer(object):
"""PdfRenderer object. PdfOperations act on this to produce a
representation of the contents of the pdf document. This class primarily
serves to maintain the global state as the page is drawn.
Usage:
redered_page = PdfRenderer(page).render()
TODO: Vertical writing support
TODO: Figure out graphics stuff"""
def __init__(self, page):
self.ts = TextState() # Text state
self.gs = GraphicsState() # Graphics state
self._page = page
self._fonts = page.Fonts
self.in_text = False
<|code_end|>
using the current file's imports:
from .renderer_states import TextState, GraphicsState
from ..pdf_matrix import PdfMatrix
import copy
import io
and any relevant context from other files:
# Path: gymnast/renderer/renderer_states.py
# class TextState(object):
# """Renderer text state. Has all of the various text rendering parameters
# described on pp. 396-404 in the Reference (without the leading T).
#
# Attributes (all units are in text space units):
# m: The current text matrix
# lm: Text matrix at the start of the current line
# c: Charcter spacing - Amount of extra space between characters before
# scaling by T_h. Default 0.
# w: Word spacing - Extra space (pre-T_h) added on encountering a space.
# Default 0.
# h: Horizontal scaling - Scaling factor applied to character width and
# horizontal spacing (i.e., T_c and T_w). Default 1.
# N.B.: The associated Tz operator sets this to its operand divided by
# 100.
# l: Leading - Vertical distance between the baselines of adjacent text
# lines. Default 0.
# f: Text font - The name of the current font in the current resource
# dictionary. No default value.
# fs: Text font size - Scaling factor applied to the font in all
# directions. No default value.
# mode: Text rendering mode - Determines text shading, outlining, when
# rendering text. Default 0 (solid fill, no stroke).
# rise: Text rise - Vertical offset from the baseline at which to draw
# the text. Positive values result in superscript, negative in
# subsctipt. Default 0.
# k: Text knockout - Boolean used in drawing overlappign characters.
# Set through graphics state operators. Default True."""
# id_matrix = PdfMatrix(1, 0, 0, 1, 0, 0)
# def __init__(self):
# """Create a new TextState object with values initialed to their
# respective defaults"""
# self.c = 0.0 # Char space
# self.w = 0.0 # Word space
# self.h = 1.0 # Horizontal text scale
# self.l = 0.0 # Text leading
# self.f = None # Font
# self.fs = None # Font scaling
# self.mode = 0 # Text render mode
# self.rise = 0.0 # Text rise
# self.m = self.id_matrix # Text Matrix
# self.lm = self.id_matrix # Line Matrix
#
# def reset_m(self):
# """Reset the text matrix to the identity"""
# self.m = self.id_matrix
#
# def reset_lm(self):
# """Reset the line matrix to the general text matrix"""
# self.lm = copy.copy(self.m)
#
# class GraphicsState(RendererState):
# """Renderer graphics state. Has all of the various graphical state
# parameters, including the current transformation matrix."""
# def __init__(self):
# self.CTM = self.id_matrix # Current transformation matrix
# self.line_width = 1.0
# self.line_cap = 0
# self.line_join = 0
# self.miter_limit = 10.0
# self.dash_array = [] # See p. 217
# self.dash_phase = 0
# self.intent = None # See p. 260
# self.flatness = 0 # See S6.5.1 - p. 508
#
# Path: gymnast/pdf_matrix.py
# class PdfMatrix(object):
# """Very limited matrix class representing PDF transformations"""
# def __init__(self, a, b, c, d, e, f):
# """Create a new PdfMatrix object. Arguments real numbers and represent
# a matrix as described on p. 208 of the Reference:
# [ a b 0 ]
# PdfMatrix(a, b, c, d, e, f) = [ c d 0 ]
# [ e f 1 ]
# """
# self.a = float(a)
# self.b = float(b)
# self.c = float(c)
# self.d = float(d)
# self.e = float(e)
# self.f = float(f)
# def transform_coords(self, x, y):
# return (self.a*x+self.c*y+self.e,
# self.b*x+self.d*y+self.f)
# def __mul__(self, other):
# """Matrix multiplication.
# Given the type constraint below, this will be self*other"""
# if not isinstance(other, PdfMatrix):
# raise TypeError('Can only multiply PdfMatrices by PdfMatrice')
# return PdfMatrix(self.a*other.a+self.b*other.c,
# self.a*other.b+self.b*other.d,
# self.c*other.a+self.d*other.c,
# self.c*other.b+self.d*other.d,
# self.e*other.a+self.f*other.c+other.e,
# self.e*other.b+self.f*other.d+other.f)
# @property
# def current_coords(self):
# """Current x, y offset in whatever space this matrix represents"""
# return self.e, self.f
# def copy(self):
# """Return a copy of this matrix"""
# return PdfMatrix(self.a, self.b,
# self.c, self.d,
# self.e, self.f)
. Output only the next line. | self._state_stack = [] |
Next line prediction: <|code_start|>"""
PDF Operations base class
"""
__all__ =['PdfOperation']
@six.add_metaclass(MetaGettable)
class PdfOperation(object):
"""PDF content stream operations dispatcher. Content stream operations are
registered by calling PdfOperation.register(), passing the opcode, the type
of operation, and the function that does it."""
# Operation type constants (see Reference p. 196)
# These mostly exist to make things easier in PdfRenderer methods
NOP = 0
GENERAL_GRAPHICS_STATE = 1
SPECIAL_GRAPHICS_STATE = 2
PATH_CONSTRUCTION = 4
PATH_PAINTING = 8
CLIPPING_PATHS = 16
TEXT_OBJECTS = 32
TEXT_STATE = 64
TEXT_POSITIONING = 128
TEXT_SHOWING = 256
TYPE_3_FONTS = 512
COLOR = 1024
SHADING_PATTERNS = 2048
INLINE_IMAGES = 4096
XOBJECTS = 8192
<|code_end|>
. Use current file imports:
(import inspect
import six
import warnings
from ..exc import PdfOpWarning
from ..misc import ensure_str, MetaGettable)
and context including class names, function names, or small code snippets from other files:
# Path: gymnast/exc.py
# class PdfOpWarning(PdfWarning):
# """Invalid or non-implemented PDF content operation"""
# pass
#
# Path: gymnast/misc.py
# def ensure_str(val):
# """Converts the argument to a string if it isn't one already"""
# if isinstance(val, str):
# return val
# elif isinstance(val, (bytes, bytearray)):
# return val.decode()
# else:
# raise ValueError('Expected bytes or string')
#
# class MetaGettable(type):
# """Metaclass to allow classes to be treated as dictlikes with MyClass[key].
# Instance classes should implement a classmethod __getitem__(cls, key)."""
# def __getitem__(cls, key):
# return cls.__getitem__(key)
. Output only the next line. | MARKED_CONTENT = 16384 |
Predict the next line after this snippet: <|code_start|>"""
PDF Operations base class
"""
__all__ =['PdfOperation']
@six.add_metaclass(MetaGettable)
class PdfOperation(object):
"""PDF content stream operations dispatcher. Content stream operations are
registered by calling PdfOperation.register(), passing the opcode, the type
of operation, and the function that does it."""
# Operation type constants (see Reference p. 196)
# These mostly exist to make things easier in PdfRenderer methods
NOP = 0
GENERAL_GRAPHICS_STATE = 1
SPECIAL_GRAPHICS_STATE = 2
PATH_CONSTRUCTION = 4
PATH_PAINTING = 8
CLIPPING_PATHS = 16
TEXT_OBJECTS = 32
TEXT_STATE = 64
TEXT_POSITIONING = 128
TEXT_SHOWING = 256
TYPE_3_FONTS = 512
COLOR = 1024
SHADING_PATTERNS = 2048
INLINE_IMAGES = 4096
XOBJECTS = 8192
<|code_end|>
using the current file's imports:
import inspect
import six
import warnings
from ..exc import PdfOpWarning
from ..misc import ensure_str, MetaGettable
and any relevant context from other files:
# Path: gymnast/exc.py
# class PdfOpWarning(PdfWarning):
# """Invalid or non-implemented PDF content operation"""
# pass
#
# Path: gymnast/misc.py
# def ensure_str(val):
# """Converts the argument to a string if it isn't one already"""
# if isinstance(val, str):
# return val
# elif isinstance(val, (bytes, bytearray)):
# return val.decode()
# else:
# raise ValueError('Expected bytes or string')
#
# class MetaGettable(type):
# """Metaclass to allow classes to be treated as dictlikes with MyClass[key].
# Instance classes should implement a classmethod __getitem__(cls, key)."""
# def __getitem__(cls, key):
# return cls.__getitem__(key)
. Output only the next line. | MARKED_CONTENT = 16384 |
Next line prediction: <|code_start|>"""
PDF Operations base class
"""
__all__ =['PdfOperation']
@six.add_metaclass(MetaGettable)
class PdfOperation(object):
"""PDF content stream operations dispatcher. Content stream operations are
registered by calling PdfOperation.register(), passing the opcode, the type
of operation, and the function that does it."""
# Operation type constants (see Reference p. 196)
# These mostly exist to make things easier in PdfRenderer methods
NOP = 0
GENERAL_GRAPHICS_STATE = 1
SPECIAL_GRAPHICS_STATE = 2
PATH_CONSTRUCTION = 4
PATH_PAINTING = 8
<|code_end|>
. Use current file imports:
(import inspect
import six
import warnings
from ..exc import PdfOpWarning
from ..misc import ensure_str, MetaGettable)
and context including class names, function names, or small code snippets from other files:
# Path: gymnast/exc.py
# class PdfOpWarning(PdfWarning):
# """Invalid or non-implemented PDF content operation"""
# pass
#
# Path: gymnast/misc.py
# def ensure_str(val):
# """Converts the argument to a string if it isn't one already"""
# if isinstance(val, str):
# return val
# elif isinstance(val, (bytes, bytearray)):
# return val.decode()
# else:
# raise ValueError('Expected bytes or string')
#
# class MetaGettable(type):
# """Metaclass to allow classes to be treated as dictlikes with MyClass[key].
# Instance classes should implement a classmethod __getitem__(cls, key)."""
# def __getitem__(cls, key):
# return cls.__getitem__(key)
. Output only the next line. | CLIPPING_PATHS = 16 |
Predict the next line for this snippet: <|code_start|> # Also, for some reason, some header keys change when that happens.
try:
with open(header['F'], 'rb') as f:
data = f.read()
except KeyError:
self._data = data
self._filedata = False
else:
self._filedata = True
if self._filter_key in header:
self._decoded = False
else:
self._decoded = True
self._decoded_data = self._data
@property
def header(self):
"""Stream header"""
return self._header
@property
def _filter_key(self):
return 'FFilter' if self._filedata else 'Filter'
@property
def _params_key(self):
return 'FDecodeParms' if self._filedata else 'DecodeParms'
def decode(self):
"""Decode the data in the stream by sequentially applying the
filters with their parameters"""
if self._decoded:
<|code_end|>
with the help of current file imports:
from functools import partial, reduce
from .common import PdfType
from ..filters import StreamFilter
from ..misc import ensure_list
and context from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/filters/stream_filter.py
# class StreamFilter(object):
# """PDF stream filter stream dispatcher. Stream filters are registered by
# calling PdfOperation.register() and passing a subclass of StreamFilterBase.
#
# Information on filters at can be found at
# https://partners.adobe.com/public/developer/en/ps/sdk/TN5603.Filters.pdf"""
# # Nothing to see here. Pay no attention to that man behind the curtain.
# _filters = {}
# _nop_filter = StreamFilterBase('NOPFilter', lambda x: x)
#
# @classmethod
# def register(cls, filter_name, decoder, eod=None, encoder=None):
# """Register a new stream filter"""
# new_filt = StreamFilterBase(filter_name, decoder, eod, encoder)
# cls._filters[filter_name] = new_filt
#
# @classmethod
# def __getitem__(cls, filter_name):
# filter_name = ensure_str(filter_name)
# try:
# return cls._filters[filter_name]
# except KeyError:
# return cls._nop_filter
#
# Path: gymnast/misc.py
# def ensure_list(val):
# """Converts the argument to a list, wrapping in [] if needed"""
# return val if isinstance(val, list) else [val]
, which may contain function names, class names, or code. Output only the next line. | return self._decoded_data |
Here is a snippet: <|code_start|> # to specify another file with the data, ignoring the stream data.
# Also, for some reason, some header keys change when that happens.
try:
with open(header['F'], 'rb') as f:
data = f.read()
except KeyError:
self._data = data
self._filedata = False
else:
self._filedata = True
if self._filter_key in header:
self._decoded = False
else:
self._decoded = True
self._decoded_data = self._data
@property
def header(self):
"""Stream header"""
return self._header
@property
def _filter_key(self):
return 'FFilter' if self._filedata else 'Filter'
@property
def _params_key(self):
return 'FDecodeParms' if self._filedata else 'DecodeParms'
def decode(self):
"""Decode the data in the stream by sequentially applying the
filters with their parameters"""
<|code_end|>
. Write the next line using the current file imports:
from functools import partial, reduce
from .common import PdfType
from ..filters import StreamFilter
from ..misc import ensure_list
and context from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/filters/stream_filter.py
# class StreamFilter(object):
# """PDF stream filter stream dispatcher. Stream filters are registered by
# calling PdfOperation.register() and passing a subclass of StreamFilterBase.
#
# Information on filters at can be found at
# https://partners.adobe.com/public/developer/en/ps/sdk/TN5603.Filters.pdf"""
# # Nothing to see here. Pay no attention to that man behind the curtain.
# _filters = {}
# _nop_filter = StreamFilterBase('NOPFilter', lambda x: x)
#
# @classmethod
# def register(cls, filter_name, decoder, eod=None, encoder=None):
# """Register a new stream filter"""
# new_filt = StreamFilterBase(filter_name, decoder, eod, encoder)
# cls._filters[filter_name] = new_filt
#
# @classmethod
# def __getitem__(cls, filter_name):
# filter_name = ensure_str(filter_name)
# try:
# return cls._filters[filter_name]
# except KeyError:
# return cls._nop_filter
#
# Path: gymnast/misc.py
# def ensure_list(val):
# """Converts the argument to a list, wrapping in [] if needed"""
# return val if isinstance(val, list) else [val]
, which may include functions, classes, or code. Output only the next line. | if self._decoded: |
Given the code snippet: <|code_start|>
if self._filter_key in header:
self._decoded = False
else:
self._decoded = True
self._decoded_data = self._data
@property
def header(self):
"""Stream header"""
return self._header
@property
def _filter_key(self):
return 'FFilter' if self._filedata else 'Filter'
@property
def _params_key(self):
return 'FDecodeParms' if self._filedata else 'DecodeParms'
def decode(self):
"""Decode the data in the stream by sequentially applying the
filters with their parameters"""
if self._decoded:
return self._decoded_data
# Need to use self._filter_key because, for some reason beyond my
# grasp, the key changes when the stream data is external
# Also, since these may be lists, let's make that happen
filters = ensure_list(self._header.get(self._filter_key, []))
params = ensure_list(self._header.get(self._params_key, []))
if not params:
params = [{} for f in filters]
composed_filters = chain_funcs((partial(StreamFilter[f].decode, **p)
<|code_end|>
, generate the next line using the imports in this file:
from functools import partial, reduce
from .common import PdfType
from ..filters import StreamFilter
from ..misc import ensure_list
and context (functions, classes, or occasionally code) from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/filters/stream_filter.py
# class StreamFilter(object):
# """PDF stream filter stream dispatcher. Stream filters are registered by
# calling PdfOperation.register() and passing a subclass of StreamFilterBase.
#
# Information on filters at can be found at
# https://partners.adobe.com/public/developer/en/ps/sdk/TN5603.Filters.pdf"""
# # Nothing to see here. Pay no attention to that man behind the curtain.
# _filters = {}
# _nop_filter = StreamFilterBase('NOPFilter', lambda x: x)
#
# @classmethod
# def register(cls, filter_name, decoder, eod=None, encoder=None):
# """Register a new stream filter"""
# new_filt = StreamFilterBase(filter_name, decoder, eod, encoder)
# cls._filters[filter_name] = new_filt
#
# @classmethod
# def __getitem__(cls, filter_name):
# filter_name = ensure_str(filter_name)
# try:
# return cls._filters[filter_name]
# except KeyError:
# return cls._nop_filter
#
# Path: gymnast/misc.py
# def ensure_list(val):
# """Converts the argument to a list, wrapping in [] if needed"""
# return val if isinstance(val, list) else [val]
. Output only the next line. | for f, p in zip(filters, params))) |
Continue the code snippet: <|code_start|>"""
PdfTypes for indirect objects and references to them
"""
class PdfIndirectObject(PdfType):
"""PDF indirect object definition"""
def __init__(self, object_number, generation, obj, document):
super(PdfIndirectObject, self).__init__()
self._object_number = object_number
self._generation = generation
self._object = obj
self._document = document
self._parsed_obj = None
@property
def object_key(self):
return (self._object_number, self._generation)
@property
def value(self):
return self._object
@property
def parsed_object(self):
"""The PdfElement corresponding to the object
TODO: Move most of this somewhere more sane."""
<|code_end|>
. Use current file imports:
from .common import PdfType
from .compound_types import PdfDict
from ..exc import PdfError
from .. import pdf_elements
and context (classes, functions, or code) from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/pdf_types/compound_types.py
# class PdfDict(PdfType, UserDict):
# """PDF dict type"""
# def __init__(self, *args, **kwargs):
# PdfType.__init__(self)
# UserDict.__init__(self, *args, **kwargs)
#
# def __getattr__(self, name):
# try:
# return self[name].parsed_object
# except AttributeError:
# return self[name]
# except KeyError:
# raise AttributeError('Object has no attribute "{}"'.format(name))
# def pdf_encode(self):
# return b'<<'+b' '.join(k.pdf_encode()+b' '+v.pdf_encode()
# for k, v in six.iteritems(self))+b'>>'
#
# Path: gymnast/exc.py
# class PdfError(Exception):
# """Generic PDF exception"""
# pass
. Output only the next line. | obj_types = {'Page' : pdf_elements.PdfPage, |
Given snippet: <|code_start|>PdfTypes for indirect objects and references to them
"""
class PdfIndirectObject(PdfType):
"""PDF indirect object definition"""
def __init__(self, object_number, generation, obj, document):
super(PdfIndirectObject, self).__init__()
self._object_number = object_number
self._generation = generation
self._object = obj
self._document = document
self._parsed_obj = None
@property
def object_key(self):
return (self._object_number, self._generation)
@property
def value(self):
return self._object
@property
def parsed_object(self):
"""The PdfElement corresponding to the object
TODO: Move most of this somewhere more sane."""
obj_types = {'Page' : pdf_elements.PdfPage,
'Pages' : pdf_elements.PdfPageNode,
'Font' : pdf_elements.PdfFont,
#'XObject' : PdfXObject, #TODO
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .common import PdfType
from .compound_types import PdfDict
from ..exc import PdfError
from .. import pdf_elements
and context:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/pdf_types/compound_types.py
# class PdfDict(PdfType, UserDict):
# """PDF dict type"""
# def __init__(self, *args, **kwargs):
# PdfType.__init__(self)
# UserDict.__init__(self, *args, **kwargs)
#
# def __getattr__(self, name):
# try:
# return self[name].parsed_object
# except AttributeError:
# return self[name]
# except KeyError:
# raise AttributeError('Object has no attribute "{}"'.format(name))
# def pdf_encode(self):
# return b'<<'+b' '.join(k.pdf_encode()+b' '+v.pdf_encode()
# for k, v in six.iteritems(self))+b'>>'
#
# Path: gymnast/exc.py
# class PdfError(Exception):
# """Generic PDF exception"""
# pass
which might include code, classes, or functions. Output only the next line. | 'FontDescriptor': pdf_elements.FontDescriptor, |
Given the following code snippet before the placeholder: <|code_start|>"""
class PdfIndirectObject(PdfType):
"""PDF indirect object definition"""
def __init__(self, object_number, generation, obj, document):
super(PdfIndirectObject, self).__init__()
self._object_number = object_number
self._generation = generation
self._object = obj
self._document = document
self._parsed_obj = None
@property
def object_key(self):
return (self._object_number, self._generation)
@property
def value(self):
return self._object
@property
def parsed_object(self):
"""The PdfElement corresponding to the object
TODO: Move most of this somewhere more sane."""
obj_types = {'Page' : pdf_elements.PdfPage,
'Pages' : pdf_elements.PdfPageNode,
'Font' : pdf_elements.PdfFont,
#'XObject' : PdfXObject, #TODO
'FontDescriptor': pdf_elements.FontDescriptor,
<|code_end|>
, predict the next line using imports from the current file:
from .common import PdfType
from .compound_types import PdfDict
from ..exc import PdfError
from .. import pdf_elements
and context including class names, function names, and sometimes code from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/pdf_types/compound_types.py
# class PdfDict(PdfType, UserDict):
# """PDF dict type"""
# def __init__(self, *args, **kwargs):
# PdfType.__init__(self)
# UserDict.__init__(self, *args, **kwargs)
#
# def __getattr__(self, name):
# try:
# return self[name].parsed_object
# except AttributeError:
# return self[name]
# except KeyError:
# raise AttributeError('Object has no attribute "{}"'.format(name))
# def pdf_encode(self):
# return b'<<'+b' '.join(k.pdf_encode()+b' '+v.pdf_encode()
# for k, v in six.iteritems(self))+b'>>'
#
# Path: gymnast/exc.py
# class PdfError(Exception):
# """Generic PDF exception"""
# pass
. Output only the next line. | 'Encoding' : pdf_elements.FontEncoding, |
Based on the snippet: <|code_start|> elif isinstance(data.raw, io.BytesIO): return True
elif isinstance(data.raw, io.FileIO) and 'b' in data.mode: return True
return False
def read_until(data, char_set):
"""Reads buffered io object until an element of char_set is encountered,
returning the read data without the terminator."""
result = io.BytesIO()
char_set = set(char_set)
c = data.read(1)
while c and c not in char_set:
result.write(c)
c = data.read(1)
return result.getvalue()
def is_digit(val):
"""Returns True if chr(val) is a digit 0-9"""
return 48 <= val <= 57
def consume_whitespace(data, whitespace=WHITESPACE):
"""Reads buffered io object data until a non-whitespace byte is encountered
and leaves the file position at that character."""
whitespace = set(whitespace)
for c in whitespace:
break
while c and c in whitespace:
c = data.read(1)
if c and c not in whitespace:
data.seek(-1, 1) # Rewind 1 byte
<|code_end|>
, predict the immediate next line with the help of imports:
import io
import re
import struct
from functools import wraps
from .pdf_constants import WHITESPACE
and context (classes, functions, sometimes code) from other files:
# Path: gymnast/pdf_constants.py
# WHITESPACE = frozenset((b' ', b'\t', b'\r', b'\n', b'\f', b'\x00'))
. Output only the next line. | def force_decode(bstring): |
Here is a snippet: <|code_start|>
class TestStringTypes(ParserTestCase):
def test_literal_string(self):
func = self.parser._parse_literal_string
self.set_data(b'simple string)')
<|code_end|>
. Write the next line using the current file imports:
from .parser_test import ParserTestCase
from ..pdf_parser.pdf_types import PdfName
and context from other files:
# Path: tests/parser_test.py
# class ParserTestCase(unittest.TestCase):
# """Test the parser"""
# def setUp(self):
# self.parser = PdfParser()
, which may include functions, classes, or code. Output only the next line. | self.assertEqual(func(None)._parsed_bytes, b'simple string') |
Next line prediction: <|code_start|>"""
PDF objects that represent the low-level document structure
"""
class PdfXref(PdfType):
"""Cross reference objects. These forms the basic scaffolding of the PDF
file, indicating where in the file each object is located."""
<|code_end|>
. Use current file imports:
(import re
from decimal import Decimal
from .common import PdfType
from ..exc import PdfParseError)
and context including class names, function names, or small code snippets from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/exc.py
# class PdfParseError(PdfError):
# """Exception parsing PDF file"""
# pass
. Output only the next line. | LINE_PAT = re.compile(r'^(\d{10}) (\d{5}) (n|f)\s{0,2}$') |
Predict the next line for this snippet: <|code_start|>class PdfXref(PdfType):
"""Cross reference objects. These forms the basic scaffolding of the PDF
file, indicating where in the file each object is located."""
LINE_PAT = re.compile(r'^(\d{10}) (\d{5}) (n|f)\s{0,2}$')
def __init__(self, document, obj_no, offset, generation, in_use):
super(PdfXref, self).__init__()
self._obj_no = obj_no
self._offset = offset
self._generation = generation
self._in_use = in_use
self._document = document
@property
def key(self):
return (self._obj_no, self._generation)
@property
def value(self):
return self.get_object()
def get_object(self):
"""Return the object referenced by this Xref. If it's already parsed
in the document, great, otherwise parse it."""
if self._in_use:
objs = self._document.indirect_objects
try:
return objs[self.key]
except KeyError:
self._document.parse_object(self._offset)
return objs[self.key]
<|code_end|>
with the help of current file imports:
import re
from decimal import Decimal
from .common import PdfType
from ..exc import PdfParseError
and context from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/exc.py
# class PdfParseError(PdfError):
# """Exception parsing PDF file"""
# pass
, which may contain function names, class names, or code. Output only the next line. | else: |
Given the code snippet: <|code_start|>"""
Text positioning operations - Reference p. 406
"""
def opcode_Td(renderer, t_x, t_y):
"""Move to a new line, parallel to the current one, at text space
coordinates offset from the start of the current line by (t_x, t_y)"""
renderer.ts.m = PdfMatrix(1, 0, 0, 1, t_x, t_y)*renderer.ts.lm
renderer.ts.reset_lm()
<|code_end|>
, generate the next line using the imports in this file:
from ..pdf_operation import PdfOperation
from ...pdf_matrix import PdfMatrix
and context (functions, classes, or occasionally code) from other files:
# Path: gymnast/pdf_operation/pdf_operation.py
# class PdfOperation(object):
# """PDF content stream operations dispatcher. Content stream operations are
# registered by calling PdfOperation.register(), passing the opcode, the type
# of operation, and the function that does it."""
# # Operation type constants (see Reference p. 196)
# # These mostly exist to make things easier in PdfRenderer methods
# NOP = 0
# GENERAL_GRAPHICS_STATE = 1
# SPECIAL_GRAPHICS_STATE = 2
# PATH_CONSTRUCTION = 4
# PATH_PAINTING = 8
# CLIPPING_PATHS = 16
# TEXT_OBJECTS = 32
# TEXT_STATE = 64
# TEXT_POSITIONING = 128
# TEXT_SHOWING = 256
# TYPE_3_FONTS = 512
# COLOR = 1024
# SHADING_PATTERNS = 2048
# INLINE_IMAGES = 4096
# XOBJECTS = 8192
# MARKED_CONTENT = 16384
# COMPATIBILITY = 32768
#
# _opcodes = {}
# _nops = {} # As we spawn new NOP classes, we'll cache them here
# @classmethod
# def register(cls, opcode, optype, opfunc):
# """Register a new PDF operation. Arguments are the opcode, the type of
# operation, and the function that actually does the operation."""
# opcode = ensure_str(opcode)
# if not callable(opfunc):
# raise TypeError('opfunc must be callable')
# args = inspect.getfullargspec(opfunc)
# if not (args.varargs or args.args):
# raise ValueError('opfunc must take at least one positional argument')
# opcode = ensure_str(opcode)
# cls._opcodes[opcode] = new_opcode(opcode, optype, opfunc)
#
# @classmethod
# def __getitem__(cls, operator):
# operator = ensure_str(operator)
# try:
# return cls._opcodes[operator]
# except KeyError:
# return cls._nop(operator)
# @classmethod
# def _nop(cls, operator):
# """Get the corresponding NOP operation, creating it if necessary."""
# warnings.warn("Opcode '{}' not implemented. NOP".format(operator),
# PdfOpWarning)
# try:
# return cls._nops[operator]
# except KeyError:
# tpe = new_opcode(operator, 0, lambda *x: None)
# cls._nops[operator] = tpe
# return tpe
#
# Path: gymnast/pdf_matrix.py
# class PdfMatrix(object):
# """Very limited matrix class representing PDF transformations"""
# def __init__(self, a, b, c, d, e, f):
# """Create a new PdfMatrix object. Arguments real numbers and represent
# a matrix as described on p. 208 of the Reference:
# [ a b 0 ]
# PdfMatrix(a, b, c, d, e, f) = [ c d 0 ]
# [ e f 1 ]
# """
# self.a = float(a)
# self.b = float(b)
# self.c = float(c)
# self.d = float(d)
# self.e = float(e)
# self.f = float(f)
# def transform_coords(self, x, y):
# return (self.a*x+self.c*y+self.e,
# self.b*x+self.d*y+self.f)
# def __mul__(self, other):
# """Matrix multiplication.
# Given the type constraint below, this will be self*other"""
# if not isinstance(other, PdfMatrix):
# raise TypeError('Can only multiply PdfMatrices by PdfMatrice')
# return PdfMatrix(self.a*other.a+self.b*other.c,
# self.a*other.b+self.b*other.d,
# self.c*other.a+self.d*other.c,
# self.c*other.b+self.d*other.d,
# self.e*other.a+self.f*other.c+other.e,
# self.e*other.b+self.f*other.d+other.f)
# @property
# def current_coords(self):
# """Current x, y offset in whatever space this matrix represents"""
# return self.e, self.f
# def copy(self):
# """Return a copy of this matrix"""
# return PdfMatrix(self.a, self.b,
# self.c, self.d,
# self.e, self.f)
. Output only the next line. | def opcode_TD(renderer, t_x, t_y): |
Predict the next line after this snippet: <|code_start|>"""
Text positioning operations - Reference p. 406
"""
def opcode_Td(renderer, t_x, t_y):
"""Move to a new line, parallel to the current one, at text space
coordinates offset from the start of the current line by (t_x, t_y)"""
renderer.ts.m = PdfMatrix(1, 0, 0, 1, t_x, t_y)*renderer.ts.lm
renderer.ts.reset_lm()
<|code_end|>
using the current file's imports:
from ..pdf_operation import PdfOperation
from ...pdf_matrix import PdfMatrix
and any relevant context from other files:
# Path: gymnast/pdf_operation/pdf_operation.py
# class PdfOperation(object):
# """PDF content stream operations dispatcher. Content stream operations are
# registered by calling PdfOperation.register(), passing the opcode, the type
# of operation, and the function that does it."""
# # Operation type constants (see Reference p. 196)
# # These mostly exist to make things easier in PdfRenderer methods
# NOP = 0
# GENERAL_GRAPHICS_STATE = 1
# SPECIAL_GRAPHICS_STATE = 2
# PATH_CONSTRUCTION = 4
# PATH_PAINTING = 8
# CLIPPING_PATHS = 16
# TEXT_OBJECTS = 32
# TEXT_STATE = 64
# TEXT_POSITIONING = 128
# TEXT_SHOWING = 256
# TYPE_3_FONTS = 512
# COLOR = 1024
# SHADING_PATTERNS = 2048
# INLINE_IMAGES = 4096
# XOBJECTS = 8192
# MARKED_CONTENT = 16384
# COMPATIBILITY = 32768
#
# _opcodes = {}
# _nops = {} # As we spawn new NOP classes, we'll cache them here
# @classmethod
# def register(cls, opcode, optype, opfunc):
# """Register a new PDF operation. Arguments are the opcode, the type of
# operation, and the function that actually does the operation."""
# opcode = ensure_str(opcode)
# if not callable(opfunc):
# raise TypeError('opfunc must be callable')
# args = inspect.getfullargspec(opfunc)
# if not (args.varargs or args.args):
# raise ValueError('opfunc must take at least one positional argument')
# opcode = ensure_str(opcode)
# cls._opcodes[opcode] = new_opcode(opcode, optype, opfunc)
#
# @classmethod
# def __getitem__(cls, operator):
# operator = ensure_str(operator)
# try:
# return cls._opcodes[operator]
# except KeyError:
# return cls._nop(operator)
# @classmethod
# def _nop(cls, operator):
# """Get the corresponding NOP operation, creating it if necessary."""
# warnings.warn("Opcode '{}' not implemented. NOP".format(operator),
# PdfOpWarning)
# try:
# return cls._nops[operator]
# except KeyError:
# tpe = new_opcode(operator, 0, lambda *x: None)
# cls._nops[operator] = tpe
# return tpe
#
# Path: gymnast/pdf_matrix.py
# class PdfMatrix(object):
# """Very limited matrix class representing PDF transformations"""
# def __init__(self, a, b, c, d, e, f):
# """Create a new PdfMatrix object. Arguments real numbers and represent
# a matrix as described on p. 208 of the Reference:
# [ a b 0 ]
# PdfMatrix(a, b, c, d, e, f) = [ c d 0 ]
# [ e f 1 ]
# """
# self.a = float(a)
# self.b = float(b)
# self.c = float(c)
# self.d = float(d)
# self.e = float(e)
# self.f = float(f)
# def transform_coords(self, x, y):
# return (self.a*x+self.c*y+self.e,
# self.b*x+self.d*y+self.f)
# def __mul__(self, other):
# """Matrix multiplication.
# Given the type constraint below, this will be self*other"""
# if not isinstance(other, PdfMatrix):
# raise TypeError('Can only multiply PdfMatrices by PdfMatrice')
# return PdfMatrix(self.a*other.a+self.b*other.c,
# self.a*other.b+self.b*other.d,
# self.c*other.a+self.d*other.c,
# self.c*other.b+self.d*other.d,
# self.e*other.a+self.f*other.c+other.e,
# self.e*other.b+self.f*other.d+other.f)
# @property
# def current_coords(self):
# """Current x, y offset in whatever space this matrix represents"""
# return self.e, self.f
# def copy(self):
# """Return a copy of this matrix"""
# return PdfMatrix(self.a, self.b,
# self.c, self.d,
# self.e, self.f)
. Output only the next line. | def opcode_TD(renderer, t_x, t_y): |
Predict the next line for this snippet: <|code_start|> self.h = 1.0 # Horizontal text scale
self.l = 0.0 # Text leading
self.f = None # Font
self.fs = None # Font scaling
self.mode = 0 # Text render mode
self.rise = 0.0 # Text rise
self.m = self.id_matrix # Text Matrix
self.lm = self.id_matrix # Line Matrix
def reset_m(self):
"""Reset the text matrix to the identity"""
self.m = self.id_matrix
def reset_lm(self):
"""Reset the line matrix to the general text matrix"""
self.lm = copy.copy(self.m)
class GraphicsState(RendererState):
"""Renderer graphics state. Has all of the various graphical state
parameters, including the current transformation matrix."""
def __init__(self):
self.CTM = self.id_matrix # Current transformation matrix
self.line_width = 1.0
self.line_cap = 0
self.line_join = 0
self.miter_limit = 10.0
self.dash_array = [] # See p. 217
self.dash_phase = 0
self.intent = None # See p. 260
<|code_end|>
with the help of current file imports:
import copy
from ..pdf_matrix import PdfMatrix
and context from other files:
# Path: gymnast/pdf_matrix.py
# class PdfMatrix(object):
# """Very limited matrix class representing PDF transformations"""
# def __init__(self, a, b, c, d, e, f):
# """Create a new PdfMatrix object. Arguments real numbers and represent
# a matrix as described on p. 208 of the Reference:
# [ a b 0 ]
# PdfMatrix(a, b, c, d, e, f) = [ c d 0 ]
# [ e f 1 ]
# """
# self.a = float(a)
# self.b = float(b)
# self.c = float(c)
# self.d = float(d)
# self.e = float(e)
# self.f = float(f)
# def transform_coords(self, x, y):
# return (self.a*x+self.c*y+self.e,
# self.b*x+self.d*y+self.f)
# def __mul__(self, other):
# """Matrix multiplication.
# Given the type constraint below, this will be self*other"""
# if not isinstance(other, PdfMatrix):
# raise TypeError('Can only multiply PdfMatrices by PdfMatrice')
# return PdfMatrix(self.a*other.a+self.b*other.c,
# self.a*other.b+self.b*other.d,
# self.c*other.a+self.d*other.c,
# self.c*other.b+self.d*other.d,
# self.e*other.a+self.f*other.c+other.e,
# self.e*other.b+self.f*other.d+other.f)
# @property
# def current_coords(self):
# """Current x, y offset in whatever space this matrix represents"""
# return self.e, self.f
# def copy(self):
# """Return a copy of this matrix"""
# return PdfMatrix(self.a, self.b,
# self.c, self.d,
# self.e, self.f)
, which may contain function names, class names, or code. Output only the next line. | self.flatness = 0 # See S6.5.1 - p. 508 |
Here is a snippet: <|code_start|> def __iter__(self):
return self._object.__iter__()
# OO style access
def __getattr__(self, name):
try:
val = self.__dict__[name]
except KeyError:
try:
val = self._object[name]
except KeyError:
raise AttributeError('Object has no attribute "{}"'.format(name))
if isinstance(val, PdfType):
return val.parsed_object
else:
return val
def __repr__(self):
o = '\n'.join([' '+l for l in pformat(dict(self)).splitlines()])
txt = '{}(\n{}'.format(self.__class__.__name__, o)
if self._obj_key:
txt += ', '+pformat(self._obj_key)
return txt +'\n)'
def __dir__(self):
return set(super(PdfElement, self).__dir__()).union(set(self._object.keys()))
def __all_properties(self):
"""Get all properties defined on the object. Probably only going to
use this in __len__. We need to go up the mro because properties are
defined on the class, not the instance."""
return reduce(lambda x, y: x.union(y),
[{k for k,v in six.iteritems(b.__dict__)
<|code_end|>
. Write the next line using the current file imports:
import six
from pprint import pformat
from collections.abc import MutableMapping
from collections import MutableMapping
from functools import reduce
from ..pdf_types import PdfType, PdfName
and context from other files:
# Path: gymnast/pdf_types/string_types.py
# class PdfName(PdfType, str):
# """PDF name objects, mostly use for dict keys"""
# def __new__(cls, *args, **kwargs):
# return str.__new__(cls, *args, **kwargs)
# def __init__(self, *args, **kwargs):
# PdfType.__init__(self)
# str.__init__(self)
# @classmethod
# def from_token(cls, token):
# """Parse names by stripping the leading / and replacing instances of
# #YY with the character b'\\xYY' and decoding to unicode."""
# try:
# name = bytearray(token[token[0] == '/':].encode())
# except AttributeError:
# # Hopefully this means that it's bytes
# name = bytearray(token[token[:1] == b'/':])
# hash_pos = name.find(b'#')
# while hash_pos > 0:
# try:
# new_char = bytes((int(name[hash_pos+1:hash_pos+3], 16),))
# except ValueError:
# msg = 'Invalid hex code in name {} ({})'
# raise PdfError(msg.format(token, name[hash_pos:hash_pos+3]))
# name[hash_pos:hash_pos+3] = new_char
# hash_pos = name.find(b'#', hash_pos)
# return cls(bytes(name).decode())
#
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
, which may include functions, classes, or code. Output only the next line. | if isinstance(v, property) |
Next line prediction: <|code_start|> # OO style access
def __getattr__(self, name):
try:
val = self.__dict__[name]
except KeyError:
try:
val = self._object[name]
except KeyError:
raise AttributeError('Object has no attribute "{}"'.format(name))
if isinstance(val, PdfType):
return val.parsed_object
else:
return val
def __repr__(self):
o = '\n'.join([' '+l for l in pformat(dict(self)).splitlines()])
txt = '{}(\n{}'.format(self.__class__.__name__, o)
if self._obj_key:
txt += ', '+pformat(self._obj_key)
return txt +'\n)'
def __dir__(self):
return set(super(PdfElement, self).__dir__()).union(set(self._object.keys()))
def __all_properties(self):
"""Get all properties defined on the object. Probably only going to
use this in __len__. We need to go up the mro because properties are
defined on the class, not the instance."""
return reduce(lambda x, y: x.union(y),
[{k for k,v in six.iteritems(b.__dict__)
if isinstance(v, property)
} for b in self.__class__.__mro__
]
<|code_end|>
. Use current file imports:
(import six
from pprint import pformat
from collections.abc import MutableMapping
from collections import MutableMapping
from functools import reduce
from ..pdf_types import PdfType, PdfName)
and context including class names, function names, or small code snippets from other files:
# Path: gymnast/pdf_types/string_types.py
# class PdfName(PdfType, str):
# """PDF name objects, mostly use for dict keys"""
# def __new__(cls, *args, **kwargs):
# return str.__new__(cls, *args, **kwargs)
# def __init__(self, *args, **kwargs):
# PdfType.__init__(self)
# str.__init__(self)
# @classmethod
# def from_token(cls, token):
# """Parse names by stripping the leading / and replacing instances of
# #YY with the character b'\\xYY' and decoding to unicode."""
# try:
# name = bytearray(token[token[0] == '/':].encode())
# except AttributeError:
# # Hopefully this means that it's bytes
# name = bytearray(token[token[:1] == b'/':])
# hash_pos = name.find(b'#')
# while hash_pos > 0:
# try:
# new_char = bytes((int(name[hash_pos+1:hash_pos+3], 16),))
# except ValueError:
# msg = 'Invalid hex code in name {} ({})'
# raise PdfError(msg.format(token, name[hash_pos:hash_pos+3]))
# name[hash_pos:hash_pos+3] = new_char
# hash_pos = name.find(b'#', hash_pos)
# return cls(bytes(name).decode())
#
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
. Output only the next line. | ) |
Predict the next line for this snippet: <|code_start|>"""
Simple PDF types (numbers, nulls, and booleans). These mostly exist so that we
will be able to write PDFs by calling their .pdf_encode() methods
"""
@six.add_metaclass(MetaNonelike)
class PdfNull(PdfType):
"""None-like singleton representing PDF's equivalent of None."""
@classproperty
def value(cls):
return cls
def pdf_encode(self):
return b'null'
class PdfInt(PdfType, int):
"""Pdf int type"""
def __new__(cls, val):
return int.__new__(cls, val)
def __getattr__(self, name):
return int.__getattribute__(name)
def pdf_encode(self):
return bytes(str(self))
class PdfReal(PdfType, float):
"""PDF real type
TODO: Decide if this should be a Decimal instead"""
def __new__(cls, val):
return float.__new__(cls, val)
<|code_end|>
with the help of current file imports:
import six
from .common import PdfType
from ..misc import MetaNonelike, classproperty
and context from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/misc.py
# class MetaNonelike(type):
# """Metaclass to make a class as None-like as possible."""
# def __call__(cls):
# return cls
# def __str__(cls): return cls.__name__
# def __repr__(cls): return cls.__name__
# def __hash__(cls): return id(cls)
# def __bool__(cls): return False
# def __lt__(cls, other): return (None < other)
# def __le__(cls, other): return (None <= other)
# def __eq__(cls, other): return (None is other)
# def __ne__(cls, other): return (None is not other)
# def __gt__(cls, other): return (None > other)
# def __ge__(cls, other): return (None >= other)
#
# class classproperty(object):
# """Like the @property method, but for classes instead of instances"""
# def __init__(self, fget):
# self.fget = fget
# def __get__(self, owner_self, owner_cls):
# return self.fget(owner_cls)
, which may contain function names, class names, or code. Output only the next line. | def __getattr__(self, name): |
Predict the next line after this snippet: <|code_start|>Simple PDF types (numbers, nulls, and booleans). These mostly exist so that we
will be able to write PDFs by calling their .pdf_encode() methods
"""
@six.add_metaclass(MetaNonelike)
class PdfNull(PdfType):
"""None-like singleton representing PDF's equivalent of None."""
@classproperty
def value(cls):
return cls
def pdf_encode(self):
return b'null'
class PdfInt(PdfType, int):
"""Pdf int type"""
def __new__(cls, val):
return int.__new__(cls, val)
def __getattr__(self, name):
return int.__getattribute__(name)
def pdf_encode(self):
return bytes(str(self))
class PdfReal(PdfType, float):
"""PDF real type
TODO: Decide if this should be a Decimal instead"""
def __new__(cls, val):
return float.__new__(cls, val)
def __getattr__(self, name):
return float.__getattribute__(name)
<|code_end|>
using the current file's imports:
import six
from .common import PdfType
from ..misc import MetaNonelike, classproperty
and any relevant context from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/misc.py
# class MetaNonelike(type):
# """Metaclass to make a class as None-like as possible."""
# def __call__(cls):
# return cls
# def __str__(cls): return cls.__name__
# def __repr__(cls): return cls.__name__
# def __hash__(cls): return id(cls)
# def __bool__(cls): return False
# def __lt__(cls, other): return (None < other)
# def __le__(cls, other): return (None <= other)
# def __eq__(cls, other): return (None is other)
# def __ne__(cls, other): return (None is not other)
# def __gt__(cls, other): return (None > other)
# def __ge__(cls, other): return (None >= other)
#
# class classproperty(object):
# """Like the @property method, but for classes instead of instances"""
# def __init__(self, fget):
# self.fget = fget
# def __get__(self, owner_self, owner_cls):
# return self.fget(owner_cls)
. Output only the next line. | def pdf_encode(self): |
Given the code snippet: <|code_start|>"""
Simple PDF types (numbers, nulls, and booleans). These mostly exist so that we
will be able to write PDFs by calling their .pdf_encode() methods
"""
@six.add_metaclass(MetaNonelike)
class PdfNull(PdfType):
"""None-like singleton representing PDF's equivalent of None."""
@classproperty
def value(cls):
return cls
def pdf_encode(self):
return b'null'
class PdfInt(PdfType, int):
"""Pdf int type"""
def __new__(cls, val):
return int.__new__(cls, val)
def __getattr__(self, name):
return int.__getattribute__(name)
def pdf_encode(self):
return bytes(str(self))
class PdfReal(PdfType, float):
"""PDF real type
TODO: Decide if this should be a Decimal instead"""
def __new__(cls, val):
<|code_end|>
, generate the next line using the imports in this file:
import six
from .common import PdfType
from ..misc import MetaNonelike, classproperty
and context (functions, classes, or occasionally code) from other files:
# Path: gymnast/pdf_types/common.py
# class PdfType(object):
# """Abstract base class for PDF objects"""
# def pdf_encode(self):
# """Translate the object into bytes in PDF format"""
# raise NotImplementedError
# @property
# def value(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
# @property
# def parsed_object(self):
# """Objects, references, and such will override this in clever
# ways."""
# return self
#
# Path: gymnast/misc.py
# class MetaNonelike(type):
# """Metaclass to make a class as None-like as possible."""
# def __call__(cls):
# return cls
# def __str__(cls): return cls.__name__
# def __repr__(cls): return cls.__name__
# def __hash__(cls): return id(cls)
# def __bool__(cls): return False
# def __lt__(cls, other): return (None < other)
# def __le__(cls, other): return (None <= other)
# def __eq__(cls, other): return (None is other)
# def __ne__(cls, other): return (None is not other)
# def __gt__(cls, other): return (None > other)
# def __ge__(cls, other): return (None >= other)
#
# class classproperty(object):
# """Like the @property method, but for classes instead of instances"""
# def __init__(self, fget):
# self.fget = fget
# def __get__(self, owner_self, owner_cls):
# return self.fget(owner_cls)
. Output only the next line. | return float.__new__(cls, val) |
Here is a snippet: <|code_start|>"""
TrueType Fonts
"""
class TrueTypeFont(PdfBaseFont):
"""For our purposes, these are just a more restricted form of the Type 1
Fonts, so...we're done here."""
<|code_end|>
. Write the next line using the current file imports:
from .base_font import PdfBaseFont
and context from other files:
# Path: gymnast/pdf_elements/fonts/base_font.py
# class PdfBaseFont(PdfElement):
# """Base PDF Font. Right now this is exclusively Type 1."""
#
# def __init__(self, obj, obj_key=None, document=None):
# super(PdfBaseFont, self).__init__(obj, obj_key, document)
# self._encoding = None
# self._codec = None
# self._avg_width = None
#
# def text_space_coords(self, x, y):
# """Convert a vector in glyph space to text space"""
# raise NotImplementedError
#
# @property
# def Encoding(self):
# """The font's parsed Encoding object.
# Returns a null encoding if the attribute is missing."""
# if self._encoding:
# return self._encoding
# try:
# obj = self._object['Encoding'].parsed_object
# except KeyError:
# self._encoding = FontEncoding(PdfDict({}))
# else:
# if isinstance(obj, FontEncoding):
# self._encoding = obj
# else:
# self._encoding = FontEncoding.from_name(obj)
# return self._encoding
# @property
# def codec(self):
# """codecs.Codec object based on the font's Endcoding"""
# if not self._codec:
# self._codec = self._get_codec()
# return self._codec
#
# def to_text(self, string):
# """Convert the string to a unicode representation based on the font's
# encoding."""
# self.codec.decode(string.encode('utf-16-be'))
# def decode_char(self, char):
# """Translate a string based on the font's encoding. This is kind of
# twisted, so here's the basic explanation for Latin1 fonts:
#
# 1. First, try to use the font's ToUnicode CMap (not yet implemented)
# 2. If there's no ToUnicode, use the font's Encoding:
# a. Use the Encoding (including the Differences array, if defined)
# to map the character code to a name.
# b. Look up that name's UTF-16 value in the Adobe Glyph List
#
# TODO: CMap"""
# val = char.encode('utf-16-be')
# intval = struct.unpack(">Q", b'\x00'*(8-len(val))+val)[0]
# try:
# return GLYPH_LIST[self.get_glyph_name(intval)]
# except KeyError:
# return char
#
# def decode_string(self, string):
# """Convenience method to translate a string one character at a time."""
# return ''.join(self.decode_char(c) for c in string)
#
# def get_glyph_width(self, glyph, missing_width=0):
# """Return the width of the specified glyph in the current font.
# Note that these widths are in _glyph_ space, not _text_ space.
#
# Arguments:
# glyph - a one character string"""
# if not isinstance(glyph, int):
# glyph = self.Encoding.get_char_code(GLYPH_LIST[:glyph])
# if not (self.FirstChar <= glyph <= self.LastChar):
# return self.FontDescriptor.get('MissingWidth', missing_width)
# return self.Widths[glyph - self.FirstChar]
#
# def get_glyph_name(self, code):
# return self.Encoding.get_glyph_name(code)
#
# def get_char_code(self, name):
# return self.Encoding.get_char_code(name)
#
# @property
# def space_width(self):
# """Width of the space character in the current font"""
# return self.get_glyph_width(self.get_char_code('space'))
# @property
# def avg_width(self):
# """Approximate average character width. Currently only defined for
# latin fonts."""
# if self._avg_width is None:
# capwidths = [i for i in (self.get_glyph_width(i, None)
# for i in range(ord('A'), ord('Z')+1)) if i]
# lowwidths = [i for i in (self.get_glyph_width(i, None)
# for i in range(ord('a'), ord('z')+1)) if i]
# try:
# self._avg_width = float(4*sum(lowwidths)+sum(capwidths)) \
# /(4*len(lowwidths)+len(capwidths))
# except ZeroDivisionError:
# self._avg_width = float(sum(self.Widths))/len(self.Widths)
# return self._avg_width
, which may include functions, classes, or code. Output only the next line. | def text_space_coords(self, x, y): |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def main():
fh, tmp = tempfile.mkstemp()
config.setStatePath(tmp)
assert cloud.authenticate()
config.dump_state()
print(hub.tz())
os.remove(tmp)
if __name__ == "__main__":
<|code_end|>
, generate the next line using the imports in this file:
import tempfile, os
from cozify import config, cloud, hub
and context (functions, classes, or occasionally code) from other files:
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
. Output only the next line. | main() |
Using the snippet: <|code_start|>#!/usr/bin/env python3
def main(start=hub_api.apiPath):
hub_id = hub.default()
host = hub.host(hub_id)
token = hub.token(hub_id)
api_ver = start
base = hub_api._getBase(host)
print('Testing against {0}, starting from {1}{2}'.format(hub_id, base, start))
while True:
if not ping(base + api_ver, token):
print('Fail: {0}'.format(api_ver))
else:
<|code_end|>
, determine the next line of code. You have imports:
import sys
import requests
from cozify import hub, hub_api
from cozify.Error import APIError
and context (class names, function names, or code) available:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/hub_api.py
# def _getBase(host, port=8893, **kwargs):
# def get(call, hub_token_header=True, base=apiPath, **kwargs):
# def put(call, data, hub_token_header=True, base=apiPath, **kwargs):
# def _call(*, call, method, hub_token_header, data=None, **kwargs):
# def hub(**kwargs):
# def tz(**kwargs):
# def devices(**kwargs):
# def devices_command(command, **kwargs):
# def devices_command_generic(*, device_id, command=None, request_type, **kwargs):
# def devices_command_state(*, device_id, state, **kwargs):
# def devices_command_on(device_id, **kwargs):
# def devices_command_off(device_id, **kwargs):
#
# Path: cozify/Error.py
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
. Output only the next line. | print('Works: {0}'.format(api_ver)) |
Given snippet: <|code_start|>def main(start=hub_api.apiPath):
hub_id = hub.default()
host = hub.host(hub_id)
token = hub.token(hub_id)
api_ver = start
base = hub_api._getBase(host)
print('Testing against {0}, starting from {1}{2}'.format(hub_id, base, start))
while True:
if not ping(base + api_ver, token):
print('Fail: {0}'.format(api_ver))
else:
print('Works: {0}'.format(api_ver))
break
api_ver = increment(api_ver)
def increment(apipath):
base, section, version = apipath.split('/')
next_version = round(float(version) + 0.1, 10)
return '{0}/{1}/{2}'.format(base, section, next_version)
def ping(base, hub_token):
headers = {'Authorization': hub_token}
call = '/hub/tz'
response = requests.get(base + call, headers=headers, timeout=5)
if response.status_code == 200:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import requests
from cozify import hub, hub_api
from cozify.Error import APIError
and context:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/hub_api.py
# def _getBase(host, port=8893, **kwargs):
# def get(call, hub_token_header=True, base=apiPath, **kwargs):
# def put(call, data, hub_token_header=True, base=apiPath, **kwargs):
# def _call(*, call, method, hub_token_header, data=None, **kwargs):
# def hub(**kwargs):
# def tz(**kwargs):
# def devices(**kwargs):
# def devices_command(command, **kwargs):
# def devices_command_generic(*, device_id, command=None, request_type, **kwargs):
# def devices_command_state(*, device_id, state, **kwargs):
# def devices_command_on(device_id, **kwargs):
# def devices_command_off(device_id, **kwargs):
#
# Path: cozify/Error.py
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
which might include code, classes, or functions. Output only the next line. | return True |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
def main(statepath):
config.setStatePath(statepath)
cloud_token = cloud.token()
hub_id = hub.default()
hub_token = hub.token(hub_id)
pp = pprint.PrettyPrinter(indent=2)
for token in cloud_token, hub_token:
claims = jwt.decode(token, verify=False)
pp.pprint(claims)
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1])
else:
<|code_end|>
using the current file's imports:
import sys, pprint
import jwt
from cozify import hub, cloud, config
and any relevant context from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
. Output only the next line. | sys.exit(1) |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
def main(statepath):
config.setStatePath(statepath)
cloud_token = cloud.token()
hub_id = hub.default()
hub_token = hub.token(hub_id)
pp = pprint.PrettyPrinter(indent=2)
<|code_end|>
, predict the immediate next line with the help of imports:
import sys, pprint
import jwt
from cozify import hub, cloud, config
and context (classes, functions, sometimes code) from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
. Output only the next line. | for token in cloud_token, hub_token: |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def main(statepath):
config.setStatePath(statepath)
cloud_token = cloud.token()
hub_id = hub.default()
hub_token = hub.token(hub_id)
pp = pprint.PrettyPrinter(indent=2)
for token in cloud_token, hub_token:
claims = jwt.decode(token, verify=False)
pp.pprint(claims)
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1])
<|code_end|>
, generate the next line using the imports in this file:
import sys, pprint
import jwt
from cozify import hub, cloud, config
and context (functions, classes, or occasionally code) from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
. Output only the next line. | else: |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
FLAGS = flags.FLAGS
flags.DEFINE_string('device', None,
'Device ID of a controllable socket into which the Lightify device is plugged')
flags.DEFINE_float('ontime', 5, 'Time to keep the light on', lower_bound=0.0)
flags.DEFINE_float('offtime', 5, 'Time to keep the light off', lower_bound=0.0)
flags.DEFINE_integer('iterations', 5, 'Number of cycles to perform', lower_bound=1)
flags.DEFINE_integer('initial_delay', 5, 'Stablize time before starting cycles', lower_bound=1)
flags.mark_flag_as_required('device')
def init(device):
hub.ping()
hub.device_off(device)
time.sleep(FLAGS.initial_delay)
def cycle(device):
hub.device_on(device)
<|code_end|>
using the current file's imports:
import time
import pprint, sys
from absl import logging, app, flags
from cozify import hub
from cozify.test import debug
and any relevant context from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/test/debug.py
. Output only the next line. | time.sleep(FLAGS.ontime) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
@pytest.mark.live
def test_hub(live_cloud, live_hub):
assert live_hub.ping()
<|code_end|>
. Use current file imports:
import pytest
from cozify import cloud, hub, hub_api, config
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import AuthenticationError, APIError, ConnectionError
from mbtest.imposters import Imposter, Predicate, Stub, Response
and context (classes, functions, or code) from other files:
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/hub_api.py
# def _getBase(host, port=8893, **kwargs):
# def get(call, hub_token_header=True, base=apiPath, **kwargs):
# def put(call, data, hub_token_header=True, base=apiPath, **kwargs):
# def _call(*, call, method, hub_token_header, data=None, **kwargs):
# def hub(**kwargs):
# def tz(**kwargs):
# def devices(**kwargs):
# def devices_command(command, **kwargs):
# def devices_command_generic(*, device_id, command=None, request_type, **kwargs):
# def devices_command_state(*, device_id, state, **kwargs):
# def devices_command_on(device_id, **kwargs):
# def devices_command_off(device_id, **kwargs):
#
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class AuthenticationError(Exception):
# """Error raised for nonrecoverable authentication failures.
#
# Args:
# message(str): Human readable error description
#
# Attributes:
# message(str): Human readable error description
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Authentication error: {}'.format(self.message)
#
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
#
# class ConnectionError(ConnectionError):
# """Error raised for connection level failures,
# such as a lost internet connection.
#
# Args:
# message(str): Potential error message returned by the requests library
#
# Attributes:
# message(str): Potential error message returned by the requests library
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Connection error: {}'.format(self.message)
. Output only the next line. | hub_id = live_hub.default() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
@pytest.mark.live
def test_hub(live_cloud, live_hub):
assert live_hub.ping()
hub_id = live_hub.default()
assert hub_api.hub(
<|code_end|>
with the help of current file imports:
import pytest
from cozify import cloud, hub, hub_api, config
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import AuthenticationError, APIError, ConnectionError
from mbtest.imposters import Imposter, Predicate, Stub, Response
and context from other files:
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/hub_api.py
# def _getBase(host, port=8893, **kwargs):
# def get(call, hub_token_header=True, base=apiPath, **kwargs):
# def put(call, data, hub_token_header=True, base=apiPath, **kwargs):
# def _call(*, call, method, hub_token_header, data=None, **kwargs):
# def hub(**kwargs):
# def tz(**kwargs):
# def devices(**kwargs):
# def devices_command(command, **kwargs):
# def devices_command_generic(*, device_id, command=None, request_type, **kwargs):
# def devices_command_state(*, device_id, state, **kwargs):
# def devices_command_on(device_id, **kwargs):
# def devices_command_off(device_id, **kwargs):
#
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class AuthenticationError(Exception):
# """Error raised for nonrecoverable authentication failures.
#
# Args:
# message(str): Human readable error description
#
# Attributes:
# message(str): Human readable error description
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Authentication error: {}'.format(self.message)
#
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
#
# class ConnectionError(ConnectionError):
# """Error raised for connection level failures,
# such as a lost internet connection.
#
# Args:
# message(str): Potential error message returned by the requests library
#
# Attributes:
# message(str): Potential error message returned by the requests library
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Connection error: {}'.format(self.message)
, which may contain function names, class names, or code. Output only the next line. | hub_id=hub_id, |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
@pytest.mark.live
def test_hub(live_cloud, live_hub):
assert live_hub.ping()
hub_id = live_hub.default()
assert hub_api.hub(
hub_id=hub_id,
host=live_hub.host(hub_id),
remote=live_hub.remote(hub_id),
cloud_token=live_cloud.token(),
hub_token=live_hub.token(hub_id))
@pytest.mark.mbtest
def test_hub_api_timeout(mock_server, tmp_hub):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from cozify import cloud, hub, hub_api, config
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import AuthenticationError, APIError, ConnectionError
from mbtest.imposters import Imposter, Predicate, Stub, Response
and context including class names, function names, and sometimes code from other files:
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/hub_api.py
# def _getBase(host, port=8893, **kwargs):
# def get(call, hub_token_header=True, base=apiPath, **kwargs):
# def put(call, data, hub_token_header=True, base=apiPath, **kwargs):
# def _call(*, call, method, hub_token_header, data=None, **kwargs):
# def hub(**kwargs):
# def tz(**kwargs):
# def devices(**kwargs):
# def devices_command(command, **kwargs):
# def devices_command_generic(*, device_id, command=None, request_type, **kwargs):
# def devices_command_state(*, device_id, state, **kwargs):
# def devices_command_on(device_id, **kwargs):
# def devices_command_off(device_id, **kwargs):
#
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class AuthenticationError(Exception):
# """Error raised for nonrecoverable authentication failures.
#
# Args:
# message(str): Human readable error description
#
# Attributes:
# message(str): Human readable error description
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Authentication error: {}'.format(self.message)
#
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
#
# class ConnectionError(ConnectionError):
# """Error raised for connection level failures,
# such as a lost internet connection.
#
# Args:
# message(str): Potential error message returned by the requests library
#
# Attributes:
# message(str): Potential error message returned by the requests library
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Connection error: {}'.format(self.message)
. Output only the next line. | imposter = Imposter( |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
@pytest.mark.logic
def test_config_XDG(tmp_hub):
assert config._initXDG()
@pytest.mark.logic
def test_config_XDG_env(tmp_hub):
with tempfile.TemporaryDirectory() as td:
os.environ["XDG_CONFIG_HOME"] = td
config.setStatePath(config._initXDG())
assert td in config.state_file
<|code_end|>
. Use current file imports:
import pytest
import os, tempfile
from cozify import config
from cozify.test import debug
from cozify.test.fixtures import tmp_hub, tmp_cloud
and context (classes, functions, or code) from other files:
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/test/debug.py
#
# Path: cozify/test/fixtures.py
# @pytest.fixture
# def tmp_hub(tmp_cloud):
# with Tmp_hub(tmp_cloud) as hub_obj:
# print('Tmp hub state for testing:')
# config.dump_state()
# yield hub_obj
#
# @pytest.fixture
# def tmp_cloud():
# obj = lambda: 0
# obj.configfile, obj.configpath = tempfile.mkstemp(suffix='tmp_cloud')
# obj.section = 'Cloud'
# obj.email = 'example@example.com'
# obj.token = 'eyJkb20iOiJ1ayIsImFsZyI6IkhTNTEyIiwidHlwIjoiSldUIn0.eyJyb2xlIjo4LCJpYXQiOjE1MTI5ODg5NjksImV4cCI6MTUxNTQwODc2OSwidXNlcl9pZCI6ImRlYWRiZWVmLWFhYWEtYmJiYi1jY2NjLWRkZGRkZGRkZGRkZCIsImtpZCI6ImRlYWRiZWVmLWRkZGQtY2NjYy1iYmJiLWFhYWFhYWFhYWFhYSIsImlzcyI6IkNsb3VkIn0.QVKKYyfTJPks_BXeKs23uvslkcGGQnBTKodA-UGjgHg' # valid but useless jwt token.
# obj.expiry = datetime.timedelta(days=1)
# obj.now = datetime.datetime.now()
# obj.iso_now = obj.now.isoformat().split(".")[0]
# obj.yesterday = obj.now - datetime.timedelta(days=1)
# obj.iso_yesterday = obj.yesterday.isoformat().split(".")[0]
# config.setStatePath(obj.configpath)
# from cozify import cloud
# cloud._setAttr('email', obj.email)
# cloud._setAttr('remotetoken', obj.token)
# cloud._setAttr('last_refresh', obj.iso_yesterday)
# yield obj
# os.remove(obj.configpath)
# logging.error('exiting, tried to remove: {0}'.format(obj.configpath))
. Output only the next line. | @pytest.mark.logic |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
@pytest.mark.logic
def test_config_XDG(tmp_hub):
assert config._initXDG()
@pytest.mark.logic
def test_config_XDG_env(tmp_hub):
with tempfile.TemporaryDirectory() as td:
os.environ["XDG_CONFIG_HOME"] = td
config.setStatePath(config._initXDG())
assert td in config.state_file
@pytest.mark.logic
def test_config_XDG_basedir(tmp_hub):
# using mktemp deliberately to let _initXDG create it
<|code_end|>
using the current file's imports:
import pytest
import os, tempfile
from cozify import config
from cozify.test import debug
from cozify.test.fixtures import tmp_hub, tmp_cloud
and any relevant context from other files:
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/test/debug.py
#
# Path: cozify/test/fixtures.py
# @pytest.fixture
# def tmp_hub(tmp_cloud):
# with Tmp_hub(tmp_cloud) as hub_obj:
# print('Tmp hub state for testing:')
# config.dump_state()
# yield hub_obj
#
# @pytest.fixture
# def tmp_cloud():
# obj = lambda: 0
# obj.configfile, obj.configpath = tempfile.mkstemp(suffix='tmp_cloud')
# obj.section = 'Cloud'
# obj.email = 'example@example.com'
# obj.token = 'eyJkb20iOiJ1ayIsImFsZyI6IkhTNTEyIiwidHlwIjoiSldUIn0.eyJyb2xlIjo4LCJpYXQiOjE1MTI5ODg5NjksImV4cCI6MTUxNTQwODc2OSwidXNlcl9pZCI6ImRlYWRiZWVmLWFhYWEtYmJiYi1jY2NjLWRkZGRkZGRkZGRkZCIsImtpZCI6ImRlYWRiZWVmLWRkZGQtY2NjYy1iYmJiLWFhYWFhYWFhYWFhYSIsImlzcyI6IkNsb3VkIn0.QVKKYyfTJPks_BXeKs23uvslkcGGQnBTKodA-UGjgHg' # valid but useless jwt token.
# obj.expiry = datetime.timedelta(days=1)
# obj.now = datetime.datetime.now()
# obj.iso_now = obj.now.isoformat().split(".")[0]
# obj.yesterday = obj.now - datetime.timedelta(days=1)
# obj.iso_yesterday = obj.yesterday.isoformat().split(".")[0]
# config.setStatePath(obj.configpath)
# from cozify import cloud
# cloud._setAttr('email', obj.email)
# cloud._setAttr('remotetoken', obj.token)
# cloud._setAttr('last_refresh', obj.iso_yesterday)
# yield obj
# os.remove(obj.configpath)
# logging.error('exiting, tried to remove: {0}'.format(obj.configpath))
. Output only the next line. | td = tempfile.mktemp() |
Given snippet: <|code_start|>
@pytest.mark.logic
def test_hub_clean_state(tmp_hub):
states = tmp_hub.states()
assert states['clean'] == hub._clean_state(states['dirty'])
@pytest.mark.logic
def test_hub_in_range():
assert hub._in_range(0.5, low=0.0, high=1.0)
assert hub._in_range(0.0, low=0.0, high=1.0)
assert hub._in_range(1.0, low=0.0, high=1.0)
assert hub._in_range(None, low=0.0, high=1.0)
with pytest.raises(ValueError):
hub._in_range(1.5, low=0.0, high=1.0)
with pytest.raises(ValueError):
hub._in_range(-0.5, low=0.0, high=1.0)
@pytest.mark.destructive
@pytest.mark.remote
def test_hub_dirty_remote(live_hub):
# test if we are remote to get meaningful results
live_hub.ping(live_hub.default())
if not live_hub.remote(live_hub.default()):
pytest.xfail("Not remote, cannot run this test")
else:
# fuck up the state on purpose to say we're not remote
assert not live_hub.remote(live_hub.default(), False)
# attempt to repair the state
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from cozify import hub, multisensor
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import APIError, ConnectionError
and context:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/multisensor.py
# def getMultisensorData(data): # pragma: no cover
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
#
# class ConnectionError(ConnectionError):
# """Error raised for connection level failures,
# such as a lost internet connection.
#
# Args:
# message(str): Potential error message returned by the requests library
#
# Attributes:
# message(str): Potential error message returned by the requests library
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Connection error: {}'.format(self.message)
which might include code, classes, or functions. Output only the next line. | assert live_hub.ping() |
Using the snippet: <|code_start|> assert hub.autoremote(tmp_hub.id, False) == False
assert hub.autoremote(tmp_hub.id) == False
@pytest.mark.logic
def test_hub_id_to_name(tmp_hub):
assert hub.name(tmp_hub.id) == tmp_hub.name
@pytest.mark.logic
def test_hub_name_to_id(tmp_hub):
assert hub.hub_id(tmp_hub.name) == tmp_hub.id
@pytest.mark.logic
def test_hub_attr(tmp_hub):
with pytest.raises(AttributeError):
hub._setAttr('deadbeef', 'nop', 'deadbeef')
hub._setAttr(tmp_hub.id, 'testkey', 'deadbeef')
assert hub._getAttr(tmp_hub.id, 'testkey') == 'deadbeef'
@pytest.mark.live
def test_multisensor(live_hub):
assert hub.ping()
data = hub.devices()
print(multisensor.getMultisensorData(data))
@pytest.mark.logic
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from cozify import hub, multisensor
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import APIError, ConnectionError
and context (class names, function names, or code) available:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/multisensor.py
# def getMultisensorData(data): # pragma: no cover
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
#
# class ConnectionError(ConnectionError):
# """Error raised for connection level failures,
# such as a lost internet connection.
#
# Args:
# message(str): Potential error message returned by the requests library
#
# Attributes:
# message(str): Potential error message returned by the requests library
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Connection error: {}'.format(self.message)
. Output only the next line. | def test_hub_get_id(tmp_hub): |
Continue the code snippet: <|code_start|> assert hub._getAttr(tmp_hub.id, 'testkey') == 'deadbeef'
@pytest.mark.live
def test_multisensor(live_hub):
assert hub.ping()
data = hub.devices()
print(multisensor.getMultisensorData(data))
@pytest.mark.logic
def test_hub_get_id(tmp_hub):
assert hub._get_id(hub_id=tmp_hub.id) == tmp_hub.id
assert hub._get_id(hub_name=tmp_hub.name) == tmp_hub.id
assert hub._get_id(hub_name=tmp_hub.name, hub_id=tmp_hub.id) == tmp_hub.id
assert hub._get_id(hubName=tmp_hub.name) == tmp_hub.id
assert hub._get_id(hubId=tmp_hub.id) == tmp_hub.id
assert hub._get_id() == tmp_hub.id
assert not hub._get_id(hub_id='foo') == tmp_hub.id
@pytest.mark.destructive
def test_hub_ping_autorefresh(live_hub):
assert hub.ping()
hub_id = live_hub.default()
live_hub.token(hub_id=hub_id, new_token='destroyed-on-purpose-by-destructive-test')
assert not live_hub.ping(autorefresh=False)
with pytest.raises(APIError):
hub.tz()
<|code_end|>
. Use current file imports:
import pytest
from cozify import hub, multisensor
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import APIError, ConnectionError
and context (classes, functions, or code) from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/multisensor.py
# def getMultisensorData(data): # pragma: no cover
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
#
# class ConnectionError(ConnectionError):
# """Error raised for connection level failures,
# such as a lost internet connection.
#
# Args:
# message(str): Potential error message returned by the requests library
#
# Attributes:
# message(str): Potential error message returned by the requests library
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Connection error: {}'.format(self.message)
. Output only the next line. | assert live_hub.ping(autorefresh=True) |
Given the code snippet: <|code_start|> assert kwargs[key] is not None, 'key {0} was set to None'.format(key)
@pytest.mark.logic
def test_hub_clean_state(tmp_hub):
states = tmp_hub.states()
assert states['clean'] == hub._clean_state(states['dirty'])
@pytest.mark.logic
def test_hub_in_range():
assert hub._in_range(0.5, low=0.0, high=1.0)
assert hub._in_range(0.0, low=0.0, high=1.0)
assert hub._in_range(1.0, low=0.0, high=1.0)
assert hub._in_range(None, low=0.0, high=1.0)
with pytest.raises(ValueError):
hub._in_range(1.5, low=0.0, high=1.0)
with pytest.raises(ValueError):
hub._in_range(-0.5, low=0.0, high=1.0)
@pytest.mark.destructive
@pytest.mark.remote
def test_hub_dirty_remote(live_hub):
# test if we are remote to get meaningful results
live_hub.ping(live_hub.default())
if not live_hub.remote(live_hub.default()):
pytest.xfail("Not remote, cannot run this test")
else:
# fuck up the state on purpose to say we're not remote
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from cozify import hub, multisensor
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import APIError, ConnectionError
and context (functions, classes, or occasionally code) from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/multisensor.py
# def getMultisensorData(data): # pragma: no cover
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
#
# class ConnectionError(ConnectionError):
# """Error raised for connection level failures,
# such as a lost internet connection.
#
# Args:
# message(str): Potential error message returned by the requests library
#
# Attributes:
# message(str): Potential error message returned by the requests library
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Connection error: {}'.format(self.message)
. Output only the next line. | assert not live_hub.remote(live_hub.default(), False) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
def main():
hub_id = hub.default()
print(
hub_api.tz(
host=hub.host(hub_id),
cloud_token=cloud.token(),
hub_token=hub.token(hub_id),
<|code_end|>
with the help of current file imports:
from cozify import hub, cloud, hub_api
from cozify.test import debug
and context from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/hub_api.py
# def _getBase(host, port=8893, **kwargs):
# def get(call, hub_token_header=True, base=apiPath, **kwargs):
# def put(call, data, hub_token_header=True, base=apiPath, **kwargs):
# def _call(*, call, method, hub_token_header, data=None, **kwargs):
# def hub(**kwargs):
# def tz(**kwargs):
# def devices(**kwargs):
# def devices_command(command, **kwargs):
# def devices_command_generic(*, device_id, command=None, request_type, **kwargs):
# def devices_command_state(*, device_id, state, **kwargs):
# def devices_command_on(device_id, **kwargs):
# def devices_command_off(device_id, **kwargs):
#
# Path: cozify/test/debug.py
, which may contain function names, class names, or code. Output only the next line. | remote=True)) |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
def main():
hub_id = hub.default()
print(
hub_api.tz(
host=hub.host(hub_id),
cloud_token=cloud.token(),
hub_token=hub.token(hub_id),
remote=True))
if __name__ == "__main__":
<|code_end|>
, predict the immediate next line with the help of imports:
from cozify import hub, cloud, hub_api
from cozify.test import debug
and context (classes, functions, sometimes code) from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/hub_api.py
# def _getBase(host, port=8893, **kwargs):
# def get(call, hub_token_header=True, base=apiPath, **kwargs):
# def put(call, data, hub_token_header=True, base=apiPath, **kwargs):
# def _call(*, call, method, hub_token_header, data=None, **kwargs):
# def hub(**kwargs):
# def tz(**kwargs):
# def devices(**kwargs):
# def devices_command(command, **kwargs):
# def devices_command_generic(*, device_id, command=None, request_type, **kwargs):
# def devices_command_state(*, device_id, state, **kwargs):
# def devices_command_on(device_id, **kwargs):
# def devices_command_off(device_id, **kwargs):
#
# Path: cozify/test/debug.py
. Output only the next line. | main() |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def main():
hub_id = hub.default()
print(
hub_api.tz(
host=hub.host(hub_id),
cloud_token=cloud.token(),
hub_token=hub.token(hub_id),
remote=True))
<|code_end|>
, generate the next line using the imports in this file:
from cozify import hub, cloud, hub_api
from cozify.test import debug
and context (functions, classes, or occasionally code) from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/hub_api.py
# def _getBase(host, port=8893, **kwargs):
# def get(call, hub_token_header=True, base=apiPath, **kwargs):
# def put(call, data, hub_token_header=True, base=apiPath, **kwargs):
# def _call(*, call, method, hub_token_header, data=None, **kwargs):
# def hub(**kwargs):
# def tz(**kwargs):
# def devices(**kwargs):
# def devices_command(command, **kwargs):
# def devices_command_generic(*, device_id, command=None, request_type, **kwargs):
# def devices_command_state(*, device_id, state, **kwargs):
# def devices_command_on(device_id, **kwargs):
# def devices_command_off(device_id, **kwargs):
#
# Path: cozify/test/debug.py
. Output only the next line. | if __name__ == "__main__": |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
FLAGS = flags.FLAGS
flags.DEFINE_string('device', None, 'Device to operate on.')
def main(argv):
<|code_end|>
. Write the next line using the current file imports:
from cozify import hub
from absl import flags, app
from cozify.test import debug
import pprint, sys
and context from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/test/debug.py
, which may include functions, classes, or code. Output only the next line. | del argv |
Using the snippet: <|code_start|>#!/usr/bin/env python3
def dedup(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
def main():
capabilities = []
devs = hub.devices()
for id, dev in devs.items():
capabilities = capabilities + dev['capabilities']['values']
gathered = sorted(dedup(capabilities))
implemented = [e.name for e in hub.capability]
not_implemented = [item for item in gathered if item not in implemented]
composite = sorted(implemented + not_implemented)
print('Capabilities in python-cozify version {0}'.format(cozify.__version__))
print('implemented ({0}): {1}'.format(len(implemented), implemented))
print('gathered ({0}): {1}'.format(len(gathered), gathered))
<|code_end|>
, determine the next line of code. You have imports:
from cozify import hub
import cozify
and context (class names, function names, or code) available:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
. Output only the next line. | print('Not currently implemented ({0}): {1}'.format(len(not_implemented), not_implemented)) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
FLAGS = flags.FLAGS
flags.DEFINE_string('device', None, 'Device to operate on.')
flags.DEFINE_float('delay', 0.5, 'Step length in seconds.')
flags.DEFINE_float('steps', 20, 'Amount of steps to divide into.')
flags.DEFINE_bool('verify', False, 'Verify if value went through as-is.')
green = '\u001b[32m'
yellow = '\u001b[33m'
red = '\u001b[31m'
reset = '\u001b[0m'
def main(argv):
del argv
previous = None
for step in numpy.flipud(numpy.linspace(0.0, 1.0, num=FLAGS.steps)):
hub.light_brightness(FLAGS.device, step)
time.sleep(FLAGS.delay)
<|code_end|>
. Use current file imports:
from cozify import hub
from absl import flags, app
import numpy, time
and context (classes, functions, or code) from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
. Output only the next line. | read = 'N/A' |
Given the following code snippet before the placeholder: <|code_start|> obj = lambda: 0
obj.configfile, obj.configpath = tempfile.mkstemp(suffix='tmp_cloud')
obj.section = 'Cloud'
obj.email = 'example@example.com'
obj.token = 'eyJkb20iOiJ1ayIsImFsZyI6IkhTNTEyIiwidHlwIjoiSldUIn0.eyJyb2xlIjo4LCJpYXQiOjE1MTI5ODg5NjksImV4cCI6MTUxNTQwODc2OSwidXNlcl9pZCI6ImRlYWRiZWVmLWFhYWEtYmJiYi1jY2NjLWRkZGRkZGRkZGRkZCIsImtpZCI6ImRlYWRiZWVmLWRkZGQtY2NjYy1iYmJiLWFhYWFhYWFhYWFhYSIsImlzcyI6IkNsb3VkIn0.QVKKYyfTJPks_BXeKs23uvslkcGGQnBTKodA-UGjgHg' # valid but useless jwt token.
obj.expiry = datetime.timedelta(days=1)
obj.now = datetime.datetime.now()
obj.iso_now = obj.now.isoformat().split(".")[0]
obj.yesterday = obj.now - datetime.timedelta(days=1)
obj.iso_yesterday = obj.yesterday.isoformat().split(".")[0]
config.setStatePath(obj.configpath)
cloud._setAttr('email', obj.email)
cloud._setAttr('remotetoken', obj.token)
cloud._setAttr('last_refresh', obj.iso_yesterday)
yield obj
os.remove(obj.configpath)
logging.error('exiting, tried to remove: {0}'.format(obj.configpath))
@pytest.fixture
def live_cloud():
configfile, configpath = tempfile.mkstemp(suffix='live_cloud')
config.setStatePath() # assume default path will contain live config
config.setStatePath(configpath, copy_current=True)
yield cloud
config.setStatePath()
os.remove(configpath)
@pytest.fixture(scope="session")
<|code_end|>
, predict the next line using imports from the current file:
import os, pytest, tempfile, datetime
import hashlib, json
from absl import logging
from mbtest.server import MountebankServer
from cozify import config, hub
from . import fixtures_devices as dev
from cozify import cloud
from cozify import cloud
from cozify import hub
and context including class names, function names, and sometimes code from other files:
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
. Output only the next line. | def mock_server(): |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture(scope="module")
def vcr_config():
return {"filter_headers": ["authorization", "X-Hub-Key"], "record_mode": "rewrite"}
@pytest.fixture
def tmp_cloud():
obj = lambda: 0
obj.configfile, obj.configpath = tempfile.mkstemp(suffix='tmp_cloud')
obj.section = 'Cloud'
obj.email = 'example@example.com'
obj.token = 'eyJkb20iOiJ1ayIsImFsZyI6IkhTNTEyIiwidHlwIjoiSldUIn0.eyJyb2xlIjo4LCJpYXQiOjE1MTI5ODg5NjksImV4cCI6MTUxNTQwODc2OSwidXNlcl9pZCI6ImRlYWRiZWVmLWFhYWEtYmJiYi1jY2NjLWRkZGRkZGRkZGRkZCIsImtpZCI6ImRlYWRiZWVmLWRkZGQtY2NjYy1iYmJiLWFhYWFhYWFhYWFhYSIsImlzcyI6IkNsb3VkIn0.QVKKYyfTJPks_BXeKs23uvslkcGGQnBTKodA-UGjgHg' # valid but useless jwt token.
obj.expiry = datetime.timedelta(days=1)
obj.now = datetime.datetime.now()
obj.iso_now = obj.now.isoformat().split(".")[0]
obj.yesterday = obj.now - datetime.timedelta(days=1)
obj.iso_yesterday = obj.yesterday.isoformat().split(".")[0]
config.setStatePath(obj.configpath)
cloud._setAttr('email', obj.email)
cloud._setAttr('remotetoken', obj.token)
cloud._setAttr('last_refresh', obj.iso_yesterday)
yield obj
os.remove(obj.configpath)
logging.error('exiting, tried to remove: {0}'.format(obj.configpath))
@pytest.fixture
def live_cloud():
<|code_end|>
, predict the next line using imports from the current file:
import os, pytest, tempfile, datetime
import hashlib, json
from absl import logging
from mbtest.server import MountebankServer
from cozify import config, hub
from . import fixtures_devices as dev
from cozify import cloud
from cozify import cloud
from cozify import hub
and context including class names, function names, and sometimes code from other files:
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
. Output only the next line. | configfile, configpath = tempfile.mkstemp(suffix='live_cloud') |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
def main(capability=None):
devs = None
if capability:
devs = hub.devices(capabilities=hub.capability[capability])
else:
devs = hub.devices()
for key, dev in devs.items():
print('{0}: {1}'.format(key, dev['name']))
if __name__ == "__main__":
<|code_end|>
using the current file's imports:
from cozify import hub
import sys
and any relevant context from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
. Output only the next line. | if len(sys.argv) > 1: |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def main(device):
hub.device_on(device)
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1])
else:
<|code_end|>
, generate the next line using the imports in this file:
from cozify import hub
from cozify.test import debug
import pprint, sys
and context (functions, classes, or occasionally code) from other files:
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/test/debug.py
. Output only the next line. | sys.exit(1) |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
## basic cloud.authenticate() tests
@pytest.mark.live
def test_cloud_authenticate(live_cloud):
assert live_cloud.authenticate()
live_cloud.resetState()
<|code_end|>
. Write the next line using the current file imports:
import os, pytest, tempfile, datetime, time
from cozify import cloud, config, hub
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import AuthenticationError
and context from other files:
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class AuthenticationError(Exception):
# """Error raised for nonrecoverable authentication failures.
#
# Args:
# message(str): Human readable error description
#
# Attributes:
# message(str): Human readable error description
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Authentication error: {}'.format(self.message)
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(OSError): |
Using the snippet: <|code_start|> assert cloud._need_refresh(force=False, expiry=datetime.timedelta(days=365))
@pytest.mark.logic
def test_cloud_refresh_expiry_over(tmp_cloud):
config.dump_state()
assert cloud._need_refresh(force=False, expiry=datetime.timedelta(hours=1))
@pytest.mark.logic
def test_cloud_refresh_expiry_not_over(tmp_cloud):
config.dump_state()
assert not cloud._need_refresh(force=False, expiry=datetime.timedelta(days=2))
@pytest.mark.destructive
def test_cloud_refresh_force(live_cloud):
config.dump_state()
timestamp_before = live_cloud._getAttr('last_refresh')
token_before = live_cloud.token()
time.sleep(2) # ensure timestamp has a diff
live_cloud.refresh(force=True)
config.dump_state()
assert timestamp_before < live_cloud._getAttr('last_refresh')
assert token_before != live_cloud.token()
## integration tests for remote
<|code_end|>
, determine the next line of code. You have imports:
import os, pytest, tempfile, datetime, time
from cozify import cloud, config, hub
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import AuthenticationError
and context (class names, function names, or code) available:
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class AuthenticationError(Exception):
# """Error raised for nonrecoverable authentication failures.
#
# Args:
# message(str): Human readable error description
#
# Attributes:
# message(str): Human readable error description
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Authentication error: {}'.format(self.message)
. Output only the next line. | @pytest.mark.live |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
## basic cloud.authenticate() tests
@pytest.mark.live
def test_cloud_authenticate(live_cloud):
assert live_cloud.authenticate()
<|code_end|>
with the help of current file imports:
import os, pytest, tempfile, datetime, time
from cozify import cloud, config, hub
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import AuthenticationError
and context from other files:
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
#
# Path: cozify/config.py
# def _initXDG():
# def stateWrite(tmpstate=None):
# def setStatePath(filepath=_initXDG(), copy_current=False):
# def dump_state():
# def _initState(state_file):
#
# Path: cozify/hub.py
# def devices(*, capabilities=None, and_filter=False, **kwargs):
# def device_reachable(device_id, **kwargs):
# def device_exists(device_id, devs=None, state=None, **kwargs):
# def device_eligible(device_id, capability_filter, devs=None, state=None, **kwargs):
# def device_toggle(device_id, **kwargs):
# def device_state_replace(device_id, state, **kwargs):
# def device_on(device_id, **kwargs):
# def device_off(device_id, **kwargs):
# def light_temperature(device_id, temperature=2700, transition=0, **kwargs):
# def light_color(device_id, hue, saturation=1.0, transition=0, **kwargs):
# def light_brightness(device_id, brightness, transition=0, **kwargs):
# def remote(hub_id, new_state=None):
# def autoremote(hub_id, new_state=None):
# def tz(**kwargs):
# def ping(autorefresh=True, **kwargs):
# def name(hub_id):
# def host(hub_id):
# def token(hub_id, new_token=None):
# def hub_id(hub_name):
# def exists(hub_id):
# def default():
# def _getAttr(hub_id, attr, default=None, boolean=False):
# def _setAttr(hub_id, attr, value, commit=True):
# def _get_id(**kwargs):
# def _fill_kwargs(kwargs):
# def _clean_state(state):
# def _in_range(value, low, high, description='undefined'):
# def getDevices(**kwargs): # pragma: no cover
# def getDefaultHub(): # pragma: no cover
# def getHubId(hub_name): # pragma: no cover
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class AuthenticationError(Exception):
# """Error raised for nonrecoverable authentication failures.
#
# Args:
# message(str): Human readable error description
#
# Attributes:
# message(str): Human readable error description
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Authentication error: {}'.format(self.message)
, which may contain function names, class names, or code. Output only the next line. | live_cloud.resetState() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
def main():
assert cloud.authenticate()
if __name__ == "__main__":
<|code_end|>
using the current file's imports:
from cozify import cloud
and any relevant context from other files:
# Path: cozify/cloud.py
# def authenticate(trustCloud=True, trustHub=True, remote=False, autoremote=True):
# def resetState():
# def update_hubs():
# def ping(autorefresh=True, expiry=None):
# def refresh(force=False, expiry=datetime.timedelta(days=1)):
# def _need_refresh(force, expiry):
# def _need_cloud_token(trust=True):
# def _need_hub_token(trust=True):
# def _getotp():
# def _getEmail(): # pragma: no cover
# def _getAttr(attr):
# def _setAttr(attr, value, commit=True):
# def _isAttr(attr):
# def token(new_token=None):
# def email(new_email=None): # pragma: no cover
. Output only the next line. | main() |
Continue the code snippet: <|code_start|>
@pytest.mark.mbtest
def test_cloud_api_mock_lan_ip(mock_server):
imposter = Imposter(Stub(Predicate(path="/hub/lan_ip"), Response(body='[ "127.0.0.1" ]')))
with mock_server(imposter):
assert cloud_api.lan_ip(base=imposter.url)
@pytest.mark.mbtest
def test_cloud_api_timeout(mock_server):
imposter = Imposter(
Stub(Predicate(path="/hub/lan_ip"), Response(body='[ "127.0.0.1" ]', wait=6000)))
with pytest.raises(ConnectionError) as e_info:
with mock_server(imposter):
cloud_api.lan_ip(base=imposter.url)
@pytest.mark.mbtest
def test_cloud_api_emaillogin(mock_server, tmp_cloud):
imposter = Imposter(Stub(Predicate(path="/user/emaillogin"), Response(body=tmp_cloud.token)))
with mock_server(imposter):
token = cloud_api.emaillogin(email=tmp_cloud.email, otp='42', base=imposter.url)
assert isinstance(token, str)
@pytest.mark.mbtest
<|code_end|>
. Use current file imports:
import os, pytest, tempfile, datetime
from cozify import cloud_api
from cozify.test import debug
from cozify.test.fixtures import *
from cozify.Error import AuthenticationError, APIError, ConnectionError
from mbtest.imposters import Imposter, Predicate, Stub, Response
and context (classes, functions, or code) from other files:
# Path: cozify/cloud_api.py
# def get(call, headers=None, base=cloudBase, no_headers=False, json_output=True, raw=False,
# **kwargs):
# def post(call,
# headers=None,
# data=None,
# params=None,
# base=cloudBase,
# no_headers=False,
# raw=False,
# **kwargs):
# def put(call, headers=None, data=None, base=cloudBase, no_headers=False, raw=False, **kwargs):
# def requestlogin(email, **kwargs): # pragma: no cover
# def emaillogin(email, otp, **kwargs):
# def lan_ip(**kwargs):
# def hubkeys(cloud_token, **kwargs): # pragma: no cover
# def refreshsession(cloud_token, **kwargs): # pragma: no cover
# def remote(apicall, headers, data=None):
# def _call(*,
# call,
# method,
# headers,
# params=None,
# data=None,
# no_headers=False,
# json_output=True,
# raw=False,
# **kwargs):
#
# Path: cozify/test/debug.py
#
# Path: cozify/Error.py
# class AuthenticationError(Exception):
# """Error raised for nonrecoverable authentication failures.
#
# Args:
# message(str): Human readable error description
#
# Attributes:
# message(str): Human readable error description
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Authentication error: {}'.format(self.message)
#
# class APIError(Exception):
# """Error raised for non-200 API return codes
#
# Args:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
#
# Attributes:
# status_code(int): HTTP status code returned by the API
# message(str): Potential error message returned by the API
# """
#
# def __init__(self, status_code, message):
# self.status_code = status_code
# self.message = message
#
# def __str__(self):
# return 'API error, {code}: {message}'.format(code=self.status_code, message=self.message)
#
# class ConnectionError(ConnectionError):
# """Error raised for connection level failures,
# such as a lost internet connection.
#
# Args:
# message(str): Potential error message returned by the requests library
#
# Attributes:
# message(str): Potential error message returned by the requests library
# """
#
# def __init__(self, message):
# self.message = message
#
# def __str__(self):
# return 'Connection error: {}'.format(self.message)
. Output only the next line. | def test_cloud_api_requestlogin(mock_server, tmp_cloud): |
Given the following code snippet before the placeholder: <|code_start|> PressKey(D)
ReleaseKey(A)
ReleaseKey(S)
def reverse_left():
PressKey(S)
PressKey(A)
ReleaseKey(W)
ReleaseKey(D)
def reverse_right():
PressKey(S)
PressKey(D)
ReleaseKey(W)
ReleaseKey(A)
def no_keys():
PressKey(W)
ReleaseKey(A)
ReleaseKey(S)
ReleaseKey(D)
model = alexnet2(WIDTH, HEIGHT, LR, output = 9)
model.load(MODEL_NAME)
def main():
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet2
from getkeys import key_check
and context including class names, function names, and sometimes code from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | last_time = time.time() |
Predict the next line after this snippet: <|code_start|>
paused = False
while(True):
if not paused:
# 800x600 windowed mode
screen = grab_screen(region=(0,40,800,640))
print('loop took {} seconds'.format(time.time()-last_time))
last_time = time.time()
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
screen = cv2.resize(screen, (160,120))
prediction = model.predict([screen.reshape(160,120,1)])[0]
print(prediction)
if np.argmax(prediction) == np.argmax(w):
straight()
elif np.argmax(prediction) == np.argmax(s):
reverse()
if np.argmax(prediction) == np.argmax(a):
left()
if np.argmax(prediction) == np.argmax(d):
right()
if np.argmax(prediction) == np.argmax(wa):
forward_left()
if np.argmax(prediction) == np.argmax(wd):
forward_right()
if np.argmax(prediction) == np.argmax(sa):
reverse_left()
<|code_end|>
using the current file's imports:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet2
from getkeys import key_check
and any relevant context from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | if np.argmax(prediction) == np.argmax(sd): |
Given the following code snippet before the placeholder: <|code_start|> PressKey(S)
PressKey(A)
ReleaseKey(W)
ReleaseKey(D)
def reverse_right():
PressKey(S)
PressKey(D)
ReleaseKey(W)
ReleaseKey(A)
def no_keys():
PressKey(W)
ReleaseKey(A)
ReleaseKey(S)
ReleaseKey(D)
model = alexnet2(WIDTH, HEIGHT, LR, output = 9)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet2
from getkeys import key_check
and context including class names, function names, and sometimes code from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | while(True): |
Here is a snippet: <|code_start|>
model = alexnet2(WIDTH, HEIGHT, LR, output = 9)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
while(True):
if not paused:
# 800x600 windowed mode
screen = grab_screen(region=(0,40,800,640))
print('loop took {} seconds'.format(time.time()-last_time))
last_time = time.time()
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
screen = cv2.resize(screen, (160,120))
prediction = model.predict([screen.reshape(160,120,1)])[0]
print(prediction)
if np.argmax(prediction) == np.argmax(w):
straight()
elif np.argmax(prediction) == np.argmax(s):
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet2
from getkeys import key_check
and context from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
, which may include functions, classes, or code. Output only the next line. | reverse() |
Continue the code snippet: <|code_start|>
def reverse_right():
PressKey(S)
PressKey(D)
ReleaseKey(W)
ReleaseKey(A)
def no_keys():
PressKey(W)
ReleaseKey(A)
ReleaseKey(S)
ReleaseKey(D)
model = alexnet2(WIDTH, HEIGHT, LR, output = 9)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
while(True):
if not paused:
# 800x600 windowed mode
screen = grab_screen(region=(0,40,800,640))
<|code_end|>
. Use current file imports:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet2
from getkeys import key_check
and context (classes, functions, or code) from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | print('loop took {} seconds'.format(time.time()-last_time)) |
Given the code snippet: <|code_start|>model = alexnet2(WIDTH, HEIGHT, LR, output = 9)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
while(True):
if not paused:
# 800x600 windowed mode
screen = grab_screen(region=(0,40,800,640))
print('loop took {} seconds'.format(time.time()-last_time))
last_time = time.time()
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
screen = cv2.resize(screen, (160,120))
prediction = model.predict([screen.reshape(160,120,1)])[0]
print(prediction)
if np.argmax(prediction) == np.argmax(w):
straight()
elif np.argmax(prediction) == np.argmax(s):
reverse()
if np.argmax(prediction) == np.argmax(a):
left()
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet2
from getkeys import key_check
and context (functions, classes, or occasionally code) from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | if np.argmax(prediction) == np.argmax(d): |
Given the following code snippet before the placeholder: <|code_start|>
def draw_lanes(img, lines, color=[0, 255, 255], thickness=3):
# if this fails, go with some default line
try:
# finds the maximum y value for a lane marker
# (since we cannot assume the horizon will always be at the same point.)
ys = []
for i in lines:
for ii in i:
ys += [ii[1],ii[3]]
min_y = min(ys)
max_y = 600
new_lines = []
line_dict = {}
for idx,i in enumerate(lines):
for xyxy in i:
# These four lines:
# modified from http://stackoverflow.com/questions/21565994/method-to-return-the-equation-of-a-straight-line-given-two-points
# Used to calculate the definition of a line, given two sets of coords.
x_coords = (xyxy[0],xyxy[2])
y_coords = (xyxy[1],xyxy[3])
A = vstack([x_coords,ones(len(x_coords))]).T
m, b = lstsq(A, y_coords)[0]
# Calculating our new, and improved, xs
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import cv2
import time
import pyautogui
from PIL import ImageGrab
from numpy import ones,vstack
from numpy.linalg import lstsq
from directkeys import PressKey,ReleaseKey, W, A, S, D
from statistics import mean
and context including class names, function names, and sometimes code from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | x1 = (min_y-b) / m |
Given snippet: <|code_start|> except Exception as e:
print(str(e))
def process_img(image):
original_image = image
# edge detection
processed_img = cv2.Canny(image, threshold1 = 200, threshold2=300)
processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500],
], np.int32)
processed_img = roi(processed_img, [vertices])
# more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
# rho theta thresh min length, max gap:
lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15)
m1 = 0
m2 = 0
try:
l1, l2, m1,m2 = draw_lanes(original_image,lines)
cv2.line(original_image, (l1[0], l1[1]), (l1[2], l1[3]), [0,255,0], 30)
cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30)
except Exception as e:
print(str(e))
pass
try:
for coords in lines:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import cv2
import time
import pyautogui
from PIL import ImageGrab
from numpy import ones,vstack
from numpy.linalg import lstsq
from directkeys import PressKey,ReleaseKey, W, A, S, D
from statistics import mean
and context:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
which might include code, classes, or functions. Output only the next line. | coords = coords[0] |
Next line prediction: <|code_start|> else:
final_lanes[m] = [ [m,b,line] ]
line_counter = {}
for lanes in final_lanes:
line_counter[lanes] = len(final_lanes[lanes])
top_lanes = sorted(line_counter.items(), key=lambda item: item[1])[::-1][:2]
lane1_id = top_lanes[0][0]
lane2_id = top_lanes[1][0]
def average_lane(lane_data):
x1s = []
y1s = []
x2s = []
y2s = []
for data in lane_data:
x1s.append(data[2][0])
y1s.append(data[2][1])
x2s.append(data[2][2])
y2s.append(data[2][3])
return int(mean(x1s)), int(mean(y1s)), int(mean(x2s)), int(mean(y2s))
l1_x1, l1_y1, l1_x2, l1_y2 = average_lane(final_lanes[lane1_id])
l2_x1, l2_y1, l2_x2, l2_y2 = average_lane(final_lanes[lane2_id])
return [l1_x1, l1_y1, l1_x2, l1_y2], [l2_x1, l2_y1, l2_x2, l2_y2], lane1_id, lane2_id
except Exception as e:
<|code_end|>
. Use current file imports:
(import numpy as np
import cv2
import time
import pyautogui
from PIL import ImageGrab
from numpy import ones,vstack
from numpy.linalg import lstsq
from directkeys import PressKey,ReleaseKey, W, A, S, D
from statistics import mean)
and context including class names, function names, or small code snippets from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | print(str(e)) |
Given snippet: <|code_start|> new_lines.append([int(x1), min_y, int(x2), max_y])
final_lanes = {}
for idx in line_dict:
final_lanes_copy = final_lanes.copy()
m = line_dict[idx][0]
b = line_dict[idx][1]
line = line_dict[idx][2]
if len(final_lanes) == 0:
final_lanes[m] = [ [m,b,line] ]
else:
found_copy = False
for other_ms in final_lanes_copy:
if not found_copy:
if abs(other_ms*1.2) > abs(m) > abs(other_ms*0.8):
if abs(final_lanes_copy[other_ms][0][1]*1.2) > abs(b) > abs(final_lanes_copy[other_ms][0][1]*0.8):
final_lanes[other_ms].append([m,b,line])
found_copy = True
break
else:
final_lanes[m] = [ [m,b,line] ]
line_counter = {}
for lanes in final_lanes:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import cv2
import time
import pyautogui
from PIL import ImageGrab
from numpy import ones,vstack
from numpy.linalg import lstsq
from directkeys import PressKey,ReleaseKey, W, A, S, D
from statistics import mean
and context:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
which might include code, classes, or functions. Output only the next line. | line_counter[lanes] = len(final_lanes[lanes]) |
Predict the next line for this snippet: <|code_start|> original_image = image
# edge detection
processed_img = cv2.Canny(image, threshold1 = 200, threshold2=300)
processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500],
], np.int32)
processed_img = roi(processed_img, [vertices])
# more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
# rho theta thresh min length, max gap:
lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15)
m1 = 0
m2 = 0
try:
l1, l2, m1,m2 = draw_lanes(original_image,lines)
cv2.line(original_image, (l1[0], l1[1]), (l1[2], l1[3]), [0,255,0], 30)
cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30)
except Exception as e:
print(str(e))
pass
try:
for coords in lines:
coords = coords[0]
try:
cv2.line(processed_img, (coords[0], coords[1]), (coords[2], coords[3]), [255,0,0], 3)
<|code_end|>
with the help of current file imports:
import numpy as np
import cv2
import time
import pyautogui
from PIL import ImageGrab
from numpy import ones,vstack
from numpy.linalg import lstsq
from directkeys import PressKey,ReleaseKey, W, A, S, D
from statistics import mean
and context from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
, which may contain function names, class names, or code. Output only the next line. | except Exception as e: |
Predict the next line for this snippet: <|code_start|>
def roi(img, vertices):
#blank mask:
mask = np.zeros_like(img)
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, 255)
#returning the image only where mask pixels are nonzero
masked = cv2.bitwise_and(img, mask)
return masked
def process_img(image):
original_image = image
# convert to gray
<|code_end|>
with the help of current file imports:
import numpy as np
import cv2
import time
import pyautogui
from directkeys import PressKey,ReleaseKey, W, A, S, D
from draw_lanes import draw_lanes
from grabscreen import grab_screen
and context from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
, which may contain function names, class names, or code. Output only the next line. | processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
Predict the next line for this snippet: <|code_start|> cv2.fillPoly(mask, vertices, 255)
#returning the image only where mask pixels are nonzero
masked = cv2.bitwise_and(img, mask)
return masked
def process_img(image):
original_image = image
# convert to gray
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# edge detection
processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500],
], np.int32)
processed_img = roi(processed_img, [vertices])
# more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
# rho theta thresh min length, max gap:
lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15)
m1 = 0
m2 = 0
try:
l1, l2, m1,m2 = draw_lanes(original_image,lines)
cv2.line(original_image, (l1[0], l1[1]), (l1[2], l1[3]), [0,255,0], 30)
<|code_end|>
with the help of current file imports:
import numpy as np
import cv2
import time
import pyautogui
from directkeys import PressKey,ReleaseKey, W, A, S, D
from draw_lanes import draw_lanes
from grabscreen import grab_screen
and context from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
, which may contain function names, class names, or code. Output only the next line. | cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30) |
Given the following code snippet before the placeholder: <|code_start|> # edge detection
processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500],
], np.int32)
processed_img = roi(processed_img, [vertices])
# more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
# rho theta thresh min length, max gap:
lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15)
m1 = 0
m2 = 0
try:
l1, l2, m1,m2 = draw_lanes(original_image,lines)
cv2.line(original_image, (l1[0], l1[1]), (l1[2], l1[3]), [0,255,0], 30)
cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30)
except Exception as e:
print(str(e))
pass
try:
for coords in lines:
coords = coords[0]
try:
cv2.line(processed_img, (coords[0], coords[1]), (coords[2], coords[3]), [255,0,0], 3)
except Exception as e:
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import cv2
import time
import pyautogui
from directkeys import PressKey,ReleaseKey, W, A, S, D
from draw_lanes import draw_lanes
from grabscreen import grab_screen
and context including class names, function names, and sometimes code from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | print(str(e)) |
Predict the next line after this snippet: <|code_start|>
def process_img(image):
original_image = image
# convert to gray
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# edge detection
processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500],
], np.int32)
processed_img = roi(processed_img, [vertices])
# more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
# rho theta thresh min length, max gap:
lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180, 20, 15)
m1 = 0
m2 = 0
try:
l1, l2, m1,m2 = draw_lanes(original_image,lines)
cv2.line(original_image, (l1[0], l1[1]), (l1[2], l1[3]), [0,255,0], 30)
cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30)
except Exception as e:
print(str(e))
pass
try:
<|code_end|>
using the current file's imports:
import numpy as np
import cv2
import time
import pyautogui
from directkeys import PressKey,ReleaseKey, W, A, S, D
from draw_lanes import draw_lanes
from grabscreen import grab_screen
and any relevant context from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | for coords in lines: |
Here is a snippet: <|code_start|> except Exception as e:
print(str(e))
except Exception as e:
pass
return processed_img,original_image, m1, m2
def straight():
PressKey(W)
ReleaseKey(A)
ReleaseKey(D)
def left():
PressKey(A)
ReleaseKey(W)
ReleaseKey(D)
ReleaseKey(A)
def right():
PressKey(D)
ReleaseKey(A)
ReleaseKey(W)
ReleaseKey(D)
def slow_ya_roll():
ReleaseKey(W)
ReleaseKey(A)
ReleaseKey(D)
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import cv2
import time
import pyautogui
from directkeys import PressKey,ReleaseKey, W, A, S, D
from draw_lanes import draw_lanes
from grabscreen import grab_screen
and context from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
, which may include functions, classes, or code. Output only the next line. | for i in list(range(4))[::-1]: |
Next line prediction: <|code_start|>
def process_img(image):
original_image = image
# convert to gray
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# edge detection
<|code_end|>
. Use current file imports:
(import numpy as np
import cv2
import time
import pyautogui
from PIL import ImageGrab
from directkeys import PressKey, W, A, S, D)
and context including class names, function names, or small code snippets from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300) |
Next line prediction: <|code_start|>
def process_img(image):
original_image = image
# convert to gray
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# edge detection
processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
return processed_img
def main():
for i in list(range(4))[::-1]:
<|code_end|>
. Use current file imports:
(import numpy as np
import cv2
import time
import pyautogui
from PIL import ImageGrab
from directkeys import PressKey, W, A, S, D)
and context including class names, function names, or small code snippets from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | print(i+1) |
Continue the code snippet: <|code_start|> paused = False
while(True):
if not paused:
# 800x600 windowed mode
#screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
screen = grab_screen(region=(0,40,800,640))
print('loop took {} seconds'.format(time.time()-last_time))
last_time = time.time()
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
screen = cv2.resize(screen, (160,120))
prediction = model.predict([screen.reshape(160,120,1)])[0]
print(prediction)
turn_thresh = .75
fwd_thresh = 0.70
if prediction[1] > fwd_thresh:
straight()
elif prediction[0] > turn_thresh:
left()
elif prediction[2] > turn_thresh:
right()
else:
straight()
keys = key_check()
# p pauses game and can get annoying.
<|code_end|>
. Use current file imports:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet
from getkeys import key_check
and context (classes, functions, or code) from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | if 'T' in keys: |
Given the code snippet: <|code_start|> last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
while(True):
if not paused:
# 800x600 windowed mode
#screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
screen = grab_screen(region=(0,40,800,640))
print('loop took {} seconds'.format(time.time()-last_time))
last_time = time.time()
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
screen = cv2.resize(screen, (160,120))
prediction = model.predict([screen.reshape(160,120,1)])[0]
print(prediction)
turn_thresh = .75
fwd_thresh = 0.70
if prediction[1] > fwd_thresh:
straight()
elif prediction[0] > turn_thresh:
left()
elif prediction[2] > turn_thresh:
right()
else:
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet
from getkeys import key_check
and context (functions, classes, or occasionally code) from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | straight() |
Given the following code snippet before the placeholder: <|code_start|> PressKey(W)
PressKey(D)
ReleaseKey(A)
#ReleaseKey(W)
#ReleaseKey(D)
time.sleep(t_time)
ReleaseKey(D)
model = alexnet(WIDTH, HEIGHT, LR)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
while(True):
if not paused:
# 800x600 windowed mode
#screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
screen = grab_screen(region=(0,40,800,640))
print('loop took {} seconds'.format(time.time()-last_time))
last_time = time.time()
screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
screen = cv2.resize(screen, (160,120))
prediction = model.predict([screen.reshape(160,120,1)])[0]
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet
from getkeys import key_check
and context including class names, function names, and sometimes code from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | print(prediction) |
Given the following code snippet before the placeholder: <|code_start|> ReleaseKey(D)
#ReleaseKey(A)
time.sleep(t_time)
ReleaseKey(A)
def right():
PressKey(W)
PressKey(D)
ReleaseKey(A)
#ReleaseKey(W)
#ReleaseKey(D)
time.sleep(t_time)
ReleaseKey(D)
model = alexnet(WIDTH, HEIGHT, LR)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
while(True):
if not paused:
# 800x600 windowed mode
#screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
screen = grab_screen(region=(0,40,800,640))
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet
from getkeys import key_check
and context including class names, function names, and sometimes code from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | print('loop took {} seconds'.format(time.time()-last_time)) |
Next line prediction: <|code_start|> ReleaseKey(D)
def left():
PressKey(W)
PressKey(A)
#ReleaseKey(W)
ReleaseKey(D)
#ReleaseKey(A)
time.sleep(t_time)
ReleaseKey(A)
def right():
PressKey(W)
PressKey(D)
ReleaseKey(A)
#ReleaseKey(W)
#ReleaseKey(D)
time.sleep(t_time)
ReleaseKey(D)
model = alexnet(WIDTH, HEIGHT, LR)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
<|code_end|>
. Use current file imports:
(import numpy as np
import cv2
import time
import random
from grabscreen import grab_screen
from directkeys import PressKey,ReleaseKey, W, A, S, D
from alexnet import alexnet
from getkeys import key_check)
and context including class names, function names, or small code snippets from other files:
# Path: directkeys.py
# def PressKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# def ReleaseKey(hexKeyCode):
# extra = ctypes.c_ulong(0)
# ii_ = Input_I()
# ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
# x = Input( ctypes.c_ulong(1), ii_ )
# ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
#
# W = 0x11
#
# A = 0x1E
#
# S = 0x1F
#
# D = 0x20
. Output only the next line. | while(True): |
Given the code snippet: <|code_start|>
LOG = logging.getLogger('nativeconfig')
class ValueSource(Enum):
resolver = 1
default = 2
<|code_end|>
, generate the next line using the imports in this file:
from abc import ABCMeta
from collections.abc import Iterable
from enum import Enum
from nativeconfig.exceptions import ValidationError, DeserializationError
import copy
import json
import logging
import os
import sys
and context (functions, classes, or occasionally code) from other files:
# Path: nativeconfig/exceptions.py
# class ValidationError(OptionError):
# def __init__(self, msg, value, option_name):
# self.value = value
# super().__init__(msg, option_name)
#
# class DeserializationError(OptionError):
# def __init__(self, msg, raw_value, option_name):
# self.raw_value = raw_value
# super().__init__(msg, option_name)
. Output only the next line. | config = 3 |
Based on the snippet: <|code_start|>
LOG = logging.getLogger('nativeconfig')
class ValueSource(Enum):
resolver = 1
default = 2
config = 3
one_shot = 4
env = 5
<|code_end|>
, predict the immediate next line with the help of imports:
from abc import ABCMeta
from collections.abc import Iterable
from enum import Enum
from nativeconfig.exceptions import ValidationError, DeserializationError
import copy
import json
import logging
import os
import sys
and context (classes, functions, sometimes code) from other files:
# Path: nativeconfig/exceptions.py
# class ValidationError(OptionError):
# def __init__(self, msg, value, option_name):
# self.value = value
# super().__init__(msg, option_name)
#
# class DeserializationError(OptionError):
# def __init__(self, msg, raw_value, option_name):
# self.raw_value = raw_value
# super().__init__(msg, option_name)
. Output only the next line. | class BaseOption(property, metaclass=ABCMeta): |
Given the following code snippet before the placeholder: <|code_start|> print("Send command to all devices: " + cmd)
ips = get_ips()
processes = list()
for ip in ips:
proc = threading.Thread(target=single_device_command, args=(ip, cmd))
proc.start()
processes.append(proc)
for proc in processes:
proc.join()
def scp_up_file(local_file, target_location):
print("Copy file:")
ips = get_ips()
for ip in ips:
line = retrieve(scpcmd+" {1} root@{0}:{2}".format(ip, local_file, target_location))
print(ip + ":\t" + line.rstrip())
def scp_down_file(remote_file, target_file):
print("Copy file:")
ips = get_ips()
for ip in ips:
line = retrieve(scpcmd+" root@{0}:{1} {2}".format(ip, remote_file, target_file))
print(ip + ":\t" + line.rstrip())
def usage(argv):
print("Usage: {0} COMMAND [params]".format(argv[0]))
<|code_end|>
, predict the next line using imports from the current file:
import subprocess
import sys
import threading
import re
from time import sleep
from texttable import Texttable
from pyfeld.pingTest import ping_test_alive
from pyfeld.rfcmd import RfCmd
and context including class names, function names, and sometimes code from other files:
# Path: pyfeld/pingTest.py
# def ping_test_alive(ip):
# cmd = "ping -W 1 -c 1 " + ip
# try:
# process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# except Exception as e:
# return 0
# output_received = ""
# while True:
# line = process.stdout.readline()
# if len(line) == 0 and process.poll() != None:
# break
# v = line.decode('utf-8')
# output_received += v
# return "1 received" in output_received
. Output only the next line. | print("Execute macrocommands over ssh for interacting with raumfeld if you got many devices, these need SSH access allowed") |
Given the following code snippet before the placeholder: <|code_start|>
class SingleItem:
def __init__(self, value):
self.timeChanged = time.time()
self.value = value
def update(self, value):
self.value = value
self.timeChanged = time.time()
class SingleUuid:
def __init__(self, uuid, rf_type, name):
self.uuid = uuid
self.rf_type = rf_type
self.name = name
self.timeChanged = time.time()
self.itemMap = dict()
def update(self, xmldom):
# print(xmldom.toprettyxml())
key_list = list()
for item in UuidStoreKeys.get_key_and_setting():
key_list.append(item[0])
items = XmlHelper.xml_extract_dict_by_val(xmldom, key_list)
changed = False
try:
for key, value in items.items():
<|code_end|>
, predict the next line using imports from the current file:
import time
from pyfeld.xmlHelper import XmlHelper
and context including class names, function names, and sometimes code from other files:
# Path: pyfeld/xmlHelper.py
# class XmlHelper:
# @staticmethod
# def xml_extract_dict(xml, extract_keys):
# result_dict = {}
# for k in extract_keys:
# try:
# element = xml.getElementsByTagName(k)
# result_dict[k] = element[0].firstChild.nodeValue
# except Exception as e:
# result_dict[k] = ""
# return result_dict
#
# def xml_extract_dict_by_val(xml, extract_keys):
# result_dict = {}
# for k in extract_keys:
# try:
# element = xml.getElementsByTagName(k)
# result_dict[k] = element[0].getAttribute("val")
# except Exception as e:
# pass
# return result_dict
. Output only the next line. | if key in self.itemMap: |
Predict the next line after this snippet: <|code_start|>from __future__ import unicode_literals
class Room:
def __init__(self, udn, renderer_list, name, location):
self.name = name
self.udn = udn
self.renderer_list = renderer_list
self.volume = 0
self.mute = 0
self.upnp_service = None
self.location = location
base_url_parsed = urllib3.util.parse_url(location)
base_url = base_url_parsed.scheme + "://" + base_url_parsed.netloc
#we need to parse these out of the xml to make it robust
self.scpdurl = base_url+"/rendercontrol.xml"
self.controlURL = base_url+"/RenderingControl/ctrl"
self.eventSubURL = base_url+"/RenderingControl/evt"
def set_volume(self, volume):
self.volume = volume
def set_name(self, name):
self.name = name
def get_name(self):
<|code_end|>
using the current file's imports:
import urllib3
from pyfeld.upnpService import UpnpService
and any relevant context from other files:
# Path: pyfeld/upnpService.py
# class UpnpService:
# def __init__(self):
# self.services_list = list()
# self.xml_location = ""
# self.network_location = ""
#
# def set_location(self, location):
# self.xml_location = location
# result = urllib3.util.parse_url(location)
# self.network_location = result.netloc
# self.services_list = Services.get_services_from_location(location)
#
# def get_network_location(self):
# return self.network_location
#
# def get_services_list(self):
# return self.services_list
. Output only the next line. | return self.name |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
from __future__ import unicode_literals
returnString = None
class MainGui:
def __init__(self):
self.selected_index_stack = [0]
self.returnString = ""
<|code_end|>
. Write the next line using the current file imports:
import curses
import re
import sys
import subprocess
from pyfeld.dirBrowse import DirBrowse
and context from other files:
# Path: pyfeld/dirBrowse.py
# class DirBrowse:
#
# def __init__(self):
# dNull = DirLevel("0", "services", self.retrieve("0"))
# self.path = "0"
# self.pathes = ["0"]
# self.dirs = [dNull]
# self.depth = 0
# self.retrieve(self.pathes[self.depth])
#
# def get_current_path(self):
# return self.path
#
# @staticmethod
# def split_browse(lines, nextline):
# result = re.match('^([C+]) (.*) \\*(.*)$', nextline)
# if result:
# type_string = ""
# if result.group(1) == 'C':
# type_string = "D" #directory (container)
# if result.group(1) == '+':
# type_string = "F" #file (track)
# path = result.group(2).encode('utf-8')
# friendly_name = result.group(3)
# lines.append([type_string, path, friendly_name])
#
# def enter(self, index):
# self.path = self.dirs[self.depth].items[index][1]
# items = self.retrieve(self.path)
# new_dir = DirLevel(self.path, self.dirs[self.depth].items[index][2], items)
# self.depth += 1
# if len(self.dirs) <= self.depth:
# self.dirs.append(new_dir)
# else:
# self.dirs[self.depth] = new_dir
#
# def enter_by_friendly_name(self, name):
# pass
#
# def leave(self):
# if self.depth != 0:
# self.depth -= 1
# self.path = self.dirs[self.depth].path
#
# def retrieve(self, path):
# command = rfCmd()
# if type(path).__name__ == 'bytes':
# command += ' "' + path.decode('utf-8') + '"'
# else:
# command += ' "' + path + '"'
# try:
# process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# except Exception as e:
# return 0
# lines = list()
# while True:
# nextline = process.stdout.readline()
# if len(nextline) == 0 and process.poll() != None:
# break
# self.split_browse(lines, nextline.decode('utf-8'))
# return lines
#
# def get_friendly_path_name(self, separator=" -> "):
# s = ""
# for i in range(1, self.depth+1):
# s += self.dirs[i].friendly_name + separator
# return s[:-len(separator)] #remove padded separator
#
# def get_friendly_name(self, index):
# return self.dirs[self.depth].items[index][2]
#
# def get_path_for_index(self, index):
# return self.dirs[self.depth].items[index][1]
#
# def get_type(self, index):
# return self.dirs[self.depth].items[index][0]
#
# def max_entries_on_level(self):
# return len(self.dirs[self.depth].items)
, which may include functions, classes, or code. Output only the next line. | self.play_in_room = None |
Predict the next line after this snippet: <|code_start|> try:
t = time()
if self.verbose:
print(str(control_url), str(body), str(headers))
response = requests.post(control_url, data=body, headers=headers, verify=False)
if response.status_code < 300:
if self.verbose:
print(response.content)
result = minidom.parseString(response.content)
if self.verbose:
print(result.toprettyxml())
return result
else:
if self.verbose:
print("query {0} returned status_code:{1}".format(control_url, response.status_code))
except Exception as e:
if self.verbose:
print("warning! host send error {0}".format(e))
return None
def device_send_rendering(self, action, action_args):
return self.host_send(action,
"/RenderingControl/ctrl",
"RenderingControl",
action_args)
def host_send_rendering(self, action, action_args):
return self.host_send(action,
"/RenderingService/Control",
<|code_end|>
using the current file's imports:
import json
import requests
import sys
import cgi
from time import time
from xml.dom import minidom
from pyfeld.xmlHelper import XmlHelper
from pyfeld.didlInfo import DidlInfo
and any relevant context from other files:
# Path: pyfeld/xmlHelper.py
# class XmlHelper:
# @staticmethod
# def xml_extract_dict(xml, extract_keys):
# result_dict = {}
# for k in extract_keys:
# try:
# element = xml.getElementsByTagName(k)
# result_dict[k] = element[0].firstChild.nodeValue
# except Exception as e:
# result_dict[k] = ""
# return result_dict
#
# def xml_extract_dict_by_val(xml, extract_keys):
# result_dict = {}
# for k in extract_keys:
# try:
# element = xml.getElementsByTagName(k)
# result_dict[k] = element[0].getAttribute("val")
# except Exception as e:
# pass
# return result_dict
. Output only the next line. | "RenderingControl", |
Here is a snippet: <|code_start|>
from __future__ import unicode_literals
class Renderer:
def __init__(self, udn, name, location):
self.name = name
self.udn = udn
self.upnp_service = None
self.location = location
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def get_location(self):
return self.location
<|code_end|>
. Write the next line using the current file imports:
from pyfeld.upnpService import UpnpService
and context from other files:
# Path: pyfeld/upnpService.py
# class UpnpService:
# def __init__(self):
# self.services_list = list()
# self.xml_location = ""
# self.network_location = ""
#
# def set_location(self, location):
# self.xml_location = location
# result = urllib3.util.parse_url(location)
# self.network_location = result.netloc
# self.services_list = Services.get_services_from_location(location)
#
# def get_network_location(self):
# return self.network_location
#
# def get_services_list(self):
# return self.services_list
, which may include functions, classes, or code. Output only the next line. | def get_udn(self): |
Using the snippet: <|code_start|>from __future__ import unicode_literals
class Services:
@staticmethod
def get_services_from_location(location):
try:
(xml_headers, xml_data) = UpnpSoap.get(location)
if xml_data is not False:
xml_root = minidom.parseString(xml_data)
services_list = list()
for service in xml_root.getElementsByTagName("service"):
service_dict = XmlHelper.xml_extract_dict(service, ['serviceType',
'controlURL',
'eventSubURL',
'SCPDURL',
<|code_end|>
, determine the next line of code. You have imports:
import urllib3
from xml.dom import minidom
from pyfeld.upnpsoap import UpnpSoap
from pyfeld.xmlHelper import XmlHelper
and context (class names, function names, or code) available:
# Path: pyfeld/upnpsoap.py
# class UpnpSoap:
# @staticmethod
# def extractSingleTag(self, data, tag):
# startTag = "<%s" % tag
# endTag = "</%s>" % tag
# try:
# tmp = data.split(startTag)[1]
# index = tmp.find('>')
# if index != -1:
# index += 1
# return tmp[index:].split(endTag)[0].strip()
# except:
# pass
# return None
#
# @staticmethod
# def send(host_name, service_type, control_url, action_name, action_arguments):
#
# if '://' in control_url:
# urls = control_url.split('/', 3)
# if len(urls) < 4:
# control_url = '/'
# else:
# control_url = '/' + urls[3]
#
# request = 'POST %s HTTP/1.1\r\n' % control_url
#
# # Check if a port number was specified in the host name; default is port 80
# if ':' in host_name:
# host_names = host_name.split(':')
# host = host_names[0]
# try:
# port = int(host_names[1])
# except:
# print('Invalid port specified for host connection:', host_name[1])
# return False
# else:
# host = host_name
# port = 80
#
# argList = ''
# for arg, (val, dt) in action_arguments.items():
# argList += '<%s>%s</%s>' % (arg, val, arg)
#
# body = '<?xml version="1.0"?>\n' \
# '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" '\
# 'SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\n' \
# '<SOAP-ENV:Body>\n' \
# '<m:%s xmlns:m="%s">\n' \
# '%s\n' \
# '</m:%s>\n' \
# '</SOAP-ENV:Body>\n' \
# '</SOAP-ENV:Envelope>\n' % (action_name, service_type, argList, action_name)
#
# headers = {
# 'Host': host_name,
# 'Content-Length': len(body.encode('ascii')),
# 'Content-Type': 'text/xml',
# 'SOAPAction': '"%s#%s"' % (service_type, action_name)
# }
#
# for head, value in headers.items():
# request += '%s: %s\r\n' % (head, value)
# request += '\r\n%s' % body
# soap_envelope_end = re.compile('<\/.*:envelope>')
#
# try:
# sock = socket(AF_INET, SOCK_STREAM)
# sock.connect((host, port))
#
# sock.send(request.encode('ascii'))
# response = ''
# while True:
# data = sock.recv(8192)
# if not data:
# break
# else:
# response += data.decode('UTF-8')
#
# if soap_envelope_end.search(response.lower()) is not None:
# break
# sock.close()
#
# (header, body) = response.split('\r\n\r\n', 1)
# if not header.upper().startswith('HTTP/1.') and ' 200 ' in header.split('\r\n')[0]:
# print('SOAP request failed with error code:', header.split('\r\n')[0].split(' ', 1)[1])
# #print(UpnpSoap.extractSingleTag(body, 'errorDescription'))
# return False
# else:
# return body
# except Exception as e:
# print('UpnpSoap.send: Caught socket exception:', e)
# sock.close()
# return False
# except KeyboardInterrupt:
# sock.close()
# return False
#
# # Send GET request for a UPNP XML file
# @staticmethod
# def get(url):
# headers = {
# 'CONTENT-TYPE': 'text/xml; charset="utf-8"',
# 'USER-AGENT': 'uPNP/1.0'
# }
# try:
# timeout = urllib3.util.timeout.Timeout(connect=2.0, read=7.0)
# http = urllib3.PoolManager(timeout=timeout)
# r = http.request("GET", url, headers=headers)
# return r.status, r.data
# except Exception as e:
# print("Request for '%s' failed: %s" % (url, e))
# return False, False
#
# Path: pyfeld/xmlHelper.py
# class XmlHelper:
# @staticmethod
# def xml_extract_dict(xml, extract_keys):
# result_dict = {}
# for k in extract_keys:
# try:
# element = xml.getElementsByTagName(k)
# result_dict[k] = element[0].firstChild.nodeValue
# except Exception as e:
# result_dict[k] = ""
# return result_dict
#
# def xml_extract_dict_by_val(xml, extract_keys):
# result_dict = {}
# for k in extract_keys:
# try:
# element = xml.getElementsByTagName(k)
# result_dict[k] = element[0].getAttribute("val")
# except Exception as e:
# pass
# return result_dict
. Output only the next line. | 'serviceId']) |
Based on the snippet: <|code_start|> print(dir_browser.path)
show_dir(dir_browser)
retrieve("--discover rooms")
dir_browser.leave()
print(dir_browser.path)
show_dir(dir_browser)
retrieve("--discover zones")
dir_browser.leave()
print(dir_browser.path)
show_dir(dir_browser)
def play():
print("fetching rooms")
rooms = retrieve("--discover rooms")
room_list = rooms.splitlines(False)
dir_browser = DirBrowse()
dir_browser.enter(1)
dir_browser.enter(1)
path = dir_browser.get_path_for_index(2)
retrieve("--zonewithroom " + room_list[0] + ' play "' + path +'"')
print("waiting a moment, then we will look at some track info")
sleep(10)
print(retrieve("--zonewithroom " + room_list[0] + ' zoneinfo'))
print("seeking to 02:00 and again we will look at some track info")
<|code_end|>
, predict the immediate next line with the help of imports:
import re
import subprocess
import sys
from time import sleep
from pyfeld.dirBrowse import DirBrowse
and context (classes, functions, sometimes code) from other files:
# Path: pyfeld/dirBrowse.py
# class DirBrowse:
#
# def __init__(self):
# dNull = DirLevel("0", "services", self.retrieve("0"))
# self.path = "0"
# self.pathes = ["0"]
# self.dirs = [dNull]
# self.depth = 0
# self.retrieve(self.pathes[self.depth])
#
# def get_current_path(self):
# return self.path
#
# @staticmethod
# def split_browse(lines, nextline):
# result = re.match('^([C+]) (.*) \\*(.*)$', nextline)
# if result:
# type_string = ""
# if result.group(1) == 'C':
# type_string = "D" #directory (container)
# if result.group(1) == '+':
# type_string = "F" #file (track)
# path = result.group(2).encode('utf-8')
# friendly_name = result.group(3)
# lines.append([type_string, path, friendly_name])
#
# def enter(self, index):
# self.path = self.dirs[self.depth].items[index][1]
# items = self.retrieve(self.path)
# new_dir = DirLevel(self.path, self.dirs[self.depth].items[index][2], items)
# self.depth += 1
# if len(self.dirs) <= self.depth:
# self.dirs.append(new_dir)
# else:
# self.dirs[self.depth] = new_dir
#
# def enter_by_friendly_name(self, name):
# pass
#
# def leave(self):
# if self.depth != 0:
# self.depth -= 1
# self.path = self.dirs[self.depth].path
#
# def retrieve(self, path):
# command = rfCmd()
# if type(path).__name__ == 'bytes':
# command += ' "' + path.decode('utf-8') + '"'
# else:
# command += ' "' + path + '"'
# try:
# process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# except Exception as e:
# return 0
# lines = list()
# while True:
# nextline = process.stdout.readline()
# if len(nextline) == 0 and process.poll() != None:
# break
# self.split_browse(lines, nextline.decode('utf-8'))
# return lines
#
# def get_friendly_path_name(self, separator=" -> "):
# s = ""
# for i in range(1, self.depth+1):
# s += self.dirs[i].friendly_name + separator
# return s[:-len(separator)] #remove padded separator
#
# def get_friendly_name(self, index):
# return self.dirs[self.depth].items[index][2]
#
# def get_path_for_index(self, index):
# return self.dirs[self.depth].items[index][1]
#
# def get_type(self, index):
# return self.dirs[self.depth].items[index][0]
#
# def max_entries_on_level(self):
# return len(self.dirs[self.depth].items)
. Output only the next line. | print(retrieve("--zonewithroom " + room_list[0] + ' seek 00:01:34')) |
Using the snippet: <|code_start|>
class Widget():
def generateHTML(self, formid):
return ''
def parseForm(self, formData):
return formData
def default_value(self):
return self.default
class InputTagWidget(Widget):
<|code_end|>
, determine the next line of code. You have imports:
from .exceptions import ValidationError
from flask import render_template
from datetime import date, time, datetime, timedelta
from dateutil.relativedelta import *
from functools import singledispatch
from jsonschema import validate
and context (class names, function names, or code) available:
# Path: diva/exceptions.py
# class ValidationError(Exception):
# pass
. Output only the next line. | def generateHTML(self, formid): |
Using the snippet: <|code_start|># use matplotlib with the Agg backend to avoid opening an app
# to view the matplotlib figures
matplotlib.use('Agg')
@convert_to_html.register(matplotlib.figure.Figure)
def fig_to_html(fig):
<|code_end|>
, determine the next line of code. You have imports:
from .converters import convert_to_html
from .utilities import register_simple_util, register_widget_util, file_response
from .widgets import *
from bokeh.plotting.figure import Figure
from bokeh.resources import CDN
from bokeh.embed import components
import matplotlib
import matplotlib.pyplot as plt, mpld3
import numpy as np
import pandas as pd
import tempfile
and context (class names, function names, or code) available:
# Path: diva/converters.py
# @singledispatch
# def convert_to_html(val):
# # default is to just display the value as a string
# return '<p>{}</p>'.format(str(val))
#
# Path: diva/utilities.py
# def register_simple_util(ui_name, some_type, widgets=[]):
# """
# Helper function for register_widget_util.
#
# widgets: a list of widgets. The values of these widgets are passed to
# the decorated function like ``your_func(val, *widget_values)``
#
# This is meant to decorate a function that takes the view value as its first
# argument, followed by a list of arguments that are given by widgets. It returns
# the result of a call to ``file_response``
# """
# def decorator(user_func):
# """
# user_func must be like appy_func followed by widget-set args
# """
# register_widget_util(ui_name, some_type, lambda val: widgets, user_func)
# return user_func
#
# return decorator
#
# def register_widget_util(ui_name, some_type, gen_widgets, apply_with_params):
# """
# ui_name: the name of this utility in the UI
#
# some_type: this utility will appear in the sidebar whenever your view function
# returns a value of type ``some_type``
#
# gen_widgets(val): a function that takes the report value (of the specified type), and
# returns a list of widgets. These widget values will be passed like:
# ``apply_with_params(val, *widget_values)``.
#
# apply_with_params: a function that takes the report value (of the specified type) as
# its first parameter, followed by a list of arguments that are given by widgets. The function must
# return the result of a call to ``file_response``
# """
# def gen_html(val):
# widgets = gen_widgets(val)
# widget_data = widgets_template_data(widgets)
# return render_template('utility_button.html', name=ui_name, widgets=widget_data)
#
# def apply_util(val, data):
# widgets = gen_widgets(val)
# validate_widget_form_data(widgets, data)
# inputs = parse_widget_form_data(widgets, data)
# return apply_with_params(val, *inputs)
#
# register_util_for_type(some_type, gen_html, apply_util)
#
# def file_response(name, filepath):
# """
# name: when the client downloads the file, it will be called this (ex. "my_file.csv")
#
# filepath: path to the file that should be sent to the client
# """
# with open(filepath, 'rb') as content_file:
# file_bytes = content_file.read()
# encoded_bytes = base64.b64encode(file_bytes)
# response = {
# 'filename': name,
# 'content': encoded_bytes.decode('utf-8')
# }
# return jsonify(response)
. Output only the next line. | return mpld3.fig_to_html(fig) |
Given the following code snippet before the placeholder: <|code_start|> 'export',
matplotlib.figure.Figure,
[SelectOne('format: ', ['png', 'pdf', 'svg'])])
def export_matplot_fig(fig, file_format):
my_file = tempfile.NamedTemporaryFile()
fig.savefig(my_file.name, bbox_inches='tight', format=file_format)
return file_response('your_file.{}'.format(file_format), my_file.name)
@convert_to_html.register(pd.DataFrame)
def dataframe_to_html(df):
# Bootstrap table classes
css_classes = ['table', 'table-bordered', 'table-hover', 'table-sm']
return df.to_html(classes=css_classes)
@convert_to_html.register(pd.Series)
def series_to_html(series):
return dataframe_to_html(series.to_frame())
@register_simple_util('export to csv', pd.DataFrame)
@register_simple_util('export to csv', pd.Series)
def df_to_csv(p):
my_file = tempfile.NamedTemporaryFile()
p.to_csv(my_file.name)
return file_response('your_file.csv', my_file.name)
# Keep in mind:
# Inserting a script tag into the DOM using innerHTML does not
# execute any script tags in the transplanted HTML.
# see: http://bokeh.pydata.org/en/latest/docs/user_guide/embed.html
@convert_to_html.register(Figure)
<|code_end|>
, predict the next line using imports from the current file:
from .converters import convert_to_html
from .utilities import register_simple_util, register_widget_util, file_response
from .widgets import *
from bokeh.plotting.figure import Figure
from bokeh.resources import CDN
from bokeh.embed import components
import matplotlib
import matplotlib.pyplot as plt, mpld3
import numpy as np
import pandas as pd
import tempfile
and context including class names, function names, and sometimes code from other files:
# Path: diva/converters.py
# @singledispatch
# def convert_to_html(val):
# # default is to just display the value as a string
# return '<p>{}</p>'.format(str(val))
#
# Path: diva/utilities.py
# def register_simple_util(ui_name, some_type, widgets=[]):
# """
# Helper function for register_widget_util.
#
# widgets: a list of widgets. The values of these widgets are passed to
# the decorated function like ``your_func(val, *widget_values)``
#
# This is meant to decorate a function that takes the view value as its first
# argument, followed by a list of arguments that are given by widgets. It returns
# the result of a call to ``file_response``
# """
# def decorator(user_func):
# """
# user_func must be like appy_func followed by widget-set args
# """
# register_widget_util(ui_name, some_type, lambda val: widgets, user_func)
# return user_func
#
# return decorator
#
# def register_widget_util(ui_name, some_type, gen_widgets, apply_with_params):
# """
# ui_name: the name of this utility in the UI
#
# some_type: this utility will appear in the sidebar whenever your view function
# returns a value of type ``some_type``
#
# gen_widgets(val): a function that takes the report value (of the specified type), and
# returns a list of widgets. These widget values will be passed like:
# ``apply_with_params(val, *widget_values)``.
#
# apply_with_params: a function that takes the report value (of the specified type) as
# its first parameter, followed by a list of arguments that are given by widgets. The function must
# return the result of a call to ``file_response``
# """
# def gen_html(val):
# widgets = gen_widgets(val)
# widget_data = widgets_template_data(widgets)
# return render_template('utility_button.html', name=ui_name, widgets=widget_data)
#
# def apply_util(val, data):
# widgets = gen_widgets(val)
# validate_widget_form_data(widgets, data)
# inputs = parse_widget_form_data(widgets, data)
# return apply_with_params(val, *inputs)
#
# register_util_for_type(some_type, gen_html, apply_util)
#
# def file_response(name, filepath):
# """
# name: when the client downloads the file, it will be called this (ex. "my_file.csv")
#
# filepath: path to the file that should be sent to the client
# """
# with open(filepath, 'rb') as content_file:
# file_bytes = content_file.read()
# encoded_bytes = base64.b64encode(file_bytes)
# response = {
# 'filename': name,
# 'content': encoded_bytes.decode('utf-8')
# }
# return jsonify(response)
. Output only the next line. | def bokeh_figure_to_html(figure): |
Based on the snippet: <|code_start|>
def test_grid_size():
size = get_grid_size([[0, 0, 1, 1]])
assert size == (1, 1)
size = get_grid_size([[0, 0, 1, 1], [1, 0, 1, 1]])
assert size == (2, 1)
size = get_grid_size(row_layout(1, 2))
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from diva.dashboard import row_layout, get_grid_size
and context (classes, functions, sometimes code) from other files:
# Path: diva/dashboard.py
# def row_layout(*row_sizes):
# # calc a common-multiple so that can define all columns
# # (not actually the LCM using this lazy way)
# lcm = 1
# for size in row_sizes:
# lcm *= size
# layout = []
# for row_num, num_cols in enumerate(row_sizes):
# col_width = int(lcm / num_cols)
# for i in range(num_cols):
# layout.append([i * col_width, row_num, col_width, 1])
#
# return layout
#
# def get_grid_size(layout):
# max_x = max([x + w for x, y, w, h in layout])
# max_y = max([y + h for x, y, w, h in layout])
# return (max_x, max_y)
. Output only the next line. | assert size == (2, 2) |
Predict the next line after this snippet: <|code_start|>
# A 'layout' is a list of [x, y, width, height] items, 1 for each panel
# where x, y is the position of the top-left corner of the panel, and
# the parent container has (0, 0) in the top-left with +y downwards
# helpers for defining layouts
def row_layout(*row_sizes):
# calc a common-multiple so that can define all columns
# (not actually the LCM using this lazy way)
lcm = 1
for size in row_sizes:
lcm *= size
layout = []
<|code_end|>
using the current file's imports:
from .converters import convert_to_html
from .utilities import get_utilities_for_value, label_utility
from .utils import render_template
from functools import partial
and any relevant context from other files:
# Path: diva/converters.py
# @singledispatch
# def convert_to_html(val):
# # default is to just display the value as a string
# return '<p>{}</p>'.format(str(val))
#
# Path: diva/utilities.py
# @singledispatch
# def get_utilities_for_value(val):
# return type_utils.get(type(val), [])
#
# def label_utility(ui_name):
# """
# Get a label utility with the given name
# """
# def gen_html(val):
# return render_template('utility_label.html', name=ui_name)
# # this will never be called
# def apply(val, form_data):
# pass
# return {'generate_html': gen_html, 'apply': apply}
#
# Path: diva/utils.py
# def render_template(filename, **variables):
# return env.get_template(filename).render(variables)
. Output only the next line. | for row_num, num_cols in enumerate(row_sizes): |
Given the following code snippet before the placeholder: <|code_start|>
@convert_to_html.register(Dashboard)
def dashboard_to_html(dash):
grid = get_grid(dash)
return render_template('dashboard.html', grid=grid)
@get_utilities_for_value.register(Dashboard)
def dashboard_utilities(dash):
def gen_html_for_item(dash, util, item_index):
return util['generate_html'](dash.items[item_index])
def apply_for_item(dash, form_data, util, item_index):
return util['apply'](dash.items[item_index], form_data)
# compose the utilities of the child elements
all_utils = []
for index, child in enumerate(dash.items):
child_utilities = get_utilities_for_value(child)
if len(child_utilities) > 0:
# separate the utilities of different children with a label
label = label_utility('report {}'.format(index))
all_utils.append(label)
for child_util in child_utilities:
# partially apply the util and the child index to the child util
# so that the resulting util takes a dashboard object and delegrates
# it to the correct util of the correct child
util = {}
util['generate_html'] = partial(gen_html_for_item, util=child_util, item_index=index)
util['apply'] = partial(apply_for_item, util=child_util, item_index=index)
<|code_end|>
, predict the next line using imports from the current file:
from .converters import convert_to_html
from .utilities import get_utilities_for_value, label_utility
from .utils import render_template
from functools import partial
and context including class names, function names, and sometimes code from other files:
# Path: diva/converters.py
# @singledispatch
# def convert_to_html(val):
# # default is to just display the value as a string
# return '<p>{}</p>'.format(str(val))
#
# Path: diva/utilities.py
# @singledispatch
# def get_utilities_for_value(val):
# return type_utils.get(type(val), [])
#
# def label_utility(ui_name):
# """
# Get a label utility with the given name
# """
# def gen_html(val):
# return render_template('utility_label.html', name=ui_name)
# # this will never be called
# def apply(val, form_data):
# pass
# return {'generate_html': gen_html, 'apply': apply}
#
# Path: diva/utils.py
# def render_template(filename, **variables):
# return env.get_template(filename).render(variables)
. Output only the next line. | all_utils.append(util) |
Here is a snippet: <|code_start|> return {'size': grid_size, 'panes': panes}
@convert_to_html.register(Dashboard)
def dashboard_to_html(dash):
grid = get_grid(dash)
return render_template('dashboard.html', grid=grid)
@get_utilities_for_value.register(Dashboard)
def dashboard_utilities(dash):
def gen_html_for_item(dash, util, item_index):
return util['generate_html'](dash.items[item_index])
def apply_for_item(dash, form_data, util, item_index):
return util['apply'](dash.items[item_index], form_data)
# compose the utilities of the child elements
all_utils = []
for index, child in enumerate(dash.items):
child_utilities = get_utilities_for_value(child)
if len(child_utilities) > 0:
# separate the utilities of different children with a label
label = label_utility('report {}'.format(index))
all_utils.append(label)
for child_util in child_utilities:
# partially apply the util and the child index to the child util
# so that the resulting util takes a dashboard object and delegrates
# it to the correct util of the correct child
util = {}
util['generate_html'] = partial(gen_html_for_item, util=child_util, item_index=index)
<|code_end|>
. Write the next line using the current file imports:
from .converters import convert_to_html
from .utilities import get_utilities_for_value, label_utility
from .utils import render_template
from functools import partial
and context from other files:
# Path: diva/converters.py
# @singledispatch
# def convert_to_html(val):
# # default is to just display the value as a string
# return '<p>{}</p>'.format(str(val))
#
# Path: diva/utilities.py
# @singledispatch
# def get_utilities_for_value(val):
# return type_utils.get(type(val), [])
#
# def label_utility(ui_name):
# """
# Get a label utility with the given name
# """
# def gen_html(val):
# return render_template('utility_label.html', name=ui_name)
# # this will never be called
# def apply(val, form_data):
# pass
# return {'generate_html': gen_html, 'apply': apply}
#
# Path: diva/utils.py
# def render_template(filename, **variables):
# return env.get_template(filename).render(variables)
, which may include functions, classes, or code. Output only the next line. | util['apply'] = partial(apply_for_item, util=child_util, item_index=index) |
Given the following code snippet before the placeholder: <|code_start|>
@convert_to_html.register(Dashboard)
def dashboard_to_html(dash):
grid = get_grid(dash)
return render_template('dashboard.html', grid=grid)
@get_utilities_for_value.register(Dashboard)
def dashboard_utilities(dash):
def gen_html_for_item(dash, util, item_index):
return util['generate_html'](dash.items[item_index])
def apply_for_item(dash, form_data, util, item_index):
return util['apply'](dash.items[item_index], form_data)
# compose the utilities of the child elements
all_utils = []
for index, child in enumerate(dash.items):
child_utilities = get_utilities_for_value(child)
if len(child_utilities) > 0:
# separate the utilities of different children with a label
label = label_utility('report {}'.format(index))
all_utils.append(label)
for child_util in child_utilities:
# partially apply the util and the child index to the child util
# so that the resulting util takes a dashboard object and delegrates
# it to the correct util of the correct child
util = {}
util['generate_html'] = partial(gen_html_for_item, util=child_util, item_index=index)
util['apply'] = partial(apply_for_item, util=child_util, item_index=index)
<|code_end|>
, predict the next line using imports from the current file:
from .converters import convert_to_html
from .utilities import get_utilities_for_value, label_utility
from .utils import render_template
from functools import partial
and context including class names, function names, and sometimes code from other files:
# Path: diva/converters.py
# @singledispatch
# def convert_to_html(val):
# # default is to just display the value as a string
# return '<p>{}</p>'.format(str(val))
#
# Path: diva/utilities.py
# @singledispatch
# def get_utilities_for_value(val):
# return type_utils.get(type(val), [])
#
# def label_utility(ui_name):
# """
# Get a label utility with the given name
# """
# def gen_html(val):
# return render_template('utility_label.html', name=ui_name)
# # this will never be called
# def apply(val, form_data):
# pass
# return {'generate_html': gen_html, 'apply': apply}
#
# Path: diva/utils.py
# def render_template(filename, **variables):
# return env.get_template(filename).render(variables)
. Output only the next line. | all_utils.append(util) |
Predict the next line for this snippet: <|code_start|>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Factor integers in various Euclidean domains
"""
DOMAINS = {"i": factor.Integer,
"g": factor.Gaussian,
"e": factor.Eisenstein,
"s": factor.Steineisen}
DESC = """Factor various algebraic integers from Euclidean domains.
Input is of the form a + b*u, where u is the unit in whichever domain.
([g]aussian: the imaginary unit, [e]isenstein: third root of unity,
[s]teineisen: sixth root of unity, [i]nteger: zero)"""
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=DESC)
parser.add_argument("a", type=int, help="First part of integer")
parser.add_argument("b", nargs="?", default=0, type=int,
help="Second part of integer")
parser.add_argument("-d", choices=DOMAINS, default="g",
help="Specify domain. Defaults to [g]aussian.")
args = parser.parse_args()
if args.a == 0 and args.b == 0:
print('0')
exit()
<|code_end|>
with the help of current file imports:
import argparse
from collections import Counter
from antitile import factor
and context from other files:
# Path: antitile/factor.py
# def factor(self):
# """Factor this element."""
# constructor = type(self)
# one = constructor(1)
# factors = self._factor()
# nf = [f.normal_form()[0] for f in factors if f.anorm() > 1]
# if nf:
# backcalc = nf[-1]
# for i in range(len(nf)-1):
# f = nf[i]
# if f.anorm() > 1:
# backcalc *= f
# else:
# backcalc = one
# unit = self//backcalc
# if unit != one or not nf:
# nf.append(unit)
# return sorted(nf)
, which may contain function names, class names, or code. Output only the next line. | constructor = DOMAINS[args.d] |
Given the code snippet: <|code_start|>def vis_vertices(ax, vertices, verts, vertexcolors=None):
"""Plots vertices
Arguments:
ax: Axis to plot on
vertices: 3d coordinates of vertices (shape (n, 3))
verts: List of vertex indices to plot
vertexcolors: Color of vertices (optional)"""
these_vertices = vertices[verts]
ax.scatter(these_vertices[..., 0], these_vertices[..., 1],
these_vertices[..., 2], c=vertexcolors)
def vis_init(canvassize=4, viewangles=(45, 45), distance=10):
"""Initializes the visualization.
Arguments:
viewangles: Viewing elevation and azimuth
distance: Viewing distance
Returns:
fig: Figure object of the visualization
ax: Axis object"""
fig = plt.figure()
fig.set_size_inches(canvassize, canvassize)
ax = fig.add_subplot(111, projection='3d')
ax.set_aspect("equal")
ax.view_init(*viewangles)
ax.dist = distance
plt.axis('off')
return fig, ax
<|code_end|>
, generate the next line using the imports in this file:
import argparse
import numpy as np
import matplotlib.pyplot as plt
from sys import stdin
from antitile.off import load_off
from matplotlib.collections import LineCollection, PolyCollection
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
and context (functions, classes, or occasionally code) from other files:
# Path: antitile/off.py
# def load_off(file):
# """Loads OFF files from Antiprism.
#
# Args:
# file: file handle
#
# Returns:
# vertices: A numpy array of shape (# of vertices , 3) representing
# the vertices of the polyhedron.
# faces: A list of list of vertex indices. All faces from the OFF file
# where Nv >= 3 are included here.
# facecolors: A list of colors. If colors are not specified, this will
# be None.
# edges: A numpy array of shape (# of edges, 2) with values of
# vertex indices. Any entry in the face list in the OFF
# file where Nv = 2 will be here. May be None.
# edgecolors: A list of colors. If colors are not specified, entry will
# be None.
# verts: A numpy array of vertex indices. Any entry in the face
# list in the OFF file where Nv = 1 will be here. May be None.
# vertexcolors: A list of colors. If colors are not specified, will
# be None.
# """
# head = readline_comment(file)
# if not head:
# raise ValueError('empty input')
# elif head[:3] != 'OFF':
# raise ValueError('not an OFF file')
# count_line = readline_comment(file)
# nvertices, nfaces, _ = [int(x) for x in count_line.split()]
# vertices = []
# for _ in range(nvertices):
# line = readline_comment(file)
# split_line = line.split()
# if len(split_line) != 3:
# raise ValueError('bad vertex: need 3d xyz coordinates')
# vertices.append([float(x) for x in split_line])
# vertices = np.array(vertices)
# faces = []
# facecolors = []
# edges = []
# edgecolors = []
# verts = []
# vertexcolors = []
# for _ in range(nfaces):
# line = readline_comment(file)
# split_line = line.split()
# nv = int(split_line[0])
# vx = [int(x) for x in split_line[1:nv+1]]
# colorspec = split_line[nv+1:]
# lc = len(colorspec)
# if lc == 0:
# colorspec = None
# elif lc == 1:
# colorspec = int(colorspec[0])
# elif lc >= 3:
# colorspec = [float(x) for x in colorspec]
# if max(colorspec) > 1:
# colorspec = [x/255 for x in colorspec]
# if nv == 1:
# verts.append(vx[0])
# vertexcolors.append(colorspec)
# elif nv == 2:
# edges.append(vx)
# edgecolors.append(colorspec)
# else:
# faces.append(vx)
# facecolors.append(colorspec)
#
# edges = np.array(edges, dtype=int) if edges else None
# verts = np.array(verts, dtype=int) if verts else None
# facecolors = facecolors if facecolors else None
# edgecolors = edgecolors if edgecolors else None
# vertexcolors = vertexcolors if vertexcolors else None
#
# return (vertices, faces, facecolors, edges, edgecolors,
# verts, vertexcolors)
. Output only the next line. | def vis_bounds(ax, vertices): |
Next line prediction: <|code_start|> style = 'stroke="red" stroke-dasharray="3"'
statements += lines(g, 0, digits, shapeinfo, style)
statements += lines(n, m, digits, shapeinfo)
statements += [footer1, footer2]
return '\n'.join(statements)
square = {'name': 'square',
'shape': np.array([[1, 1],
[1, 181],
[181, 181],
[181, 1]]),
'size': [182,]*2,
'frame': lambda n, m: antitile.breakdown.frame_square(n, m)*180 + 1,
'diagonal': 'Diagonal subdivision'}
tri_shape = np.array([[1, 157],
[181, 157],
[91, 1.1154273188010393]])
triangle = {'name': 'triangle',
'shape': tri_shape,
'size': [182, 158],
'frame': lambda n, m: antitile.breakdown.frame_triangle(
tri_shape, n, m, interp=xmath.lerp),
'diagonal': 'Ortho subdivision'}
def factors(number):
"""Cheezy function to get the factors of a small number
other than 1 and itself"""
for i in range(2, number):
if number % i == 0:
<|code_end|>
. Use current file imports:
(import csv
import numpy as np
import antitile
from math import gcd
from antitile import xmath)
and context including class names, function names, or small code snippets from other files:
# Path: antitile/xmath.py
# def reflect_through_origin(normal):
# def complex_to_float2d(arr):
# def float2d_to_complex(arr):
# def line_intersection(a1, a2, b1, b2):
# def record_initialize(shape, dtype, default_bool=False,
# default_int=-1,
# default_float=np.nan):
# def transpose(long_array, filler=-1):
# def recordify(names, arrays):
# def renumber(in_array, fill=-1):
# def triple_product(a, b, c):
# def normalize(vectors, axis=-1):
# def slerp(pt1, pt2, intervals):
# def lerp(pt1, pt2, intervals):
# def nlerp(*args):
# def distance(x, y, p=2, axis=-1, scale=1):
# def triangle_area(a, b, c):
# def bearing(origin, destination, pole=np.array([0, 0, 1])):
# def central_angle(x, y, signed=False):
# def central_angle_equilateral(pts):
# def triangle_solid_angle(a, b, c):
# def spherical_bearing(origin, destination, pole=np.array([0, 0, 1])):
# def sqrt(x):
. Output only the next line. | yield i |
Given snippet: <|code_start|>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Cellular automata on the faces (or vertices) of polyhedra"""
#import pandas as pd
def ca_step(state, rule, adj):
neighbors = adj.dot(state)
#x, y, _ = sparse.find(adj)
#nbx = state[x]
#px = pd.DataFrame(data=nbx, index=y)
#neighbors = px.groupby(px.index).sum()
result = np.squeeze(neighbors) - 128*state
return np.in1d(result, rule)
def ruleparse(string):
return [int(x) for x in string.split(',')]
DESCRIPTION = """Colors tiling using semitotalistic cellular automata.
Colors indexes of the input file is used as the initial condition,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import warnings
import numpy as np
from sys import stdin
from scipy import sparse
from antitile import off, tiling
and context:
# Path: antitile/off.py
# def readline_comment(file, symbol='#'):
# def load_off(file):
# def write_off(vertices, faces, facecolors=None, edges=None, edgecolors=None,
# verts=None, vertexcolors=None):
#
# Path: antitile/tiling.py
# class Tiling:
# def __init__(self, vertices, faces):
# def edges(self):
# def face_size(self):
# def faces_by_size(self):
# def face_normals(self):
# def true_faces(self):
# def faces_by_edge(self, edges):
# def vertex_adjacency(self):
# def face_adjacency(self):
# def face_vertex_incidence(self):
# def vertex_f_adjacency(self):
# def face_v_adjacency(self):
# def normalize_faces(self):
# def id_dupe_faces(self, face_group=None, oriented=False):
# def edges_from_facelist(faces):
# def orient_face(face, edge):
# def energy(xyz, exponent=1, over=None):
# def center_of_gravity(xyz):
# def bentness(xyz, poly):
# def edge_length(xyz, edges, spherical=False):
# def face_area(xyz, poly, spherical=False):
# def aspect_ratio(xyz, poly, spherical=False):
which might include code, classes, or functions. Output only the next line. | interpreting 0 as dead and anything else as alive. If colors are not |
Given snippet: <|code_start|> help="Input file. Reads from stdin if not given.")
parser.add_argument("-n", help="Number of steps", default=100, type=int)
parser.add_argument("-b", help="Birth rule, comma-separated",
default=[1, 5, 6], type=ruleparse)
parser.add_argument("-s", help="Survival rule, comma-separated",
default=[1, 2], type=ruleparse)
parser.add_argument("-l", help="Lookback", type=int, default=12)
parser.add_argument("-v", help=NEIGHBOR, action='store_true')
parser.add_argument("-d", action='store_true', help="Color the vertices "
"as if the cellular automata were operating on "
"the dual polyhedron/tiling")
parser.add_argument("-o", help="Output prefix.", default="cellular")
args = parser.parse_args()
file = open(args.filename) if args.filename else stdin
with file as f:
vertices, faces, fc, e, ec, verts, vc = off.load_off(f)
init = vc if args.d else fc
if init is None or np.ptp(init) == 0:
init = np.random.randint(2, size=len(faces))
init = np.asarray(init)
if len(init.shape) > 1:
raise ValueError("Need color indexes, not color values")
elif np.any(init > 1):
init = init > (init.max()+init.min())/2
poly = tiling.Tiling(vertices, faces)
if args.d:
adj = poly.vertex_f_adjacency if args.v else poly.vertex_adjacency
else:
adj = poly.face_v_adjacency if args.v else poly.face_adjacency
rule = np.array(args.b + [i - 128 for i in args.s], dtype=np.int8)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import warnings
import numpy as np
from sys import stdin
from scipy import sparse
from antitile import off, tiling
and context:
# Path: antitile/off.py
# def readline_comment(file, symbol='#'):
# def load_off(file):
# def write_off(vertices, faces, facecolors=None, edges=None, edgecolors=None,
# verts=None, vertexcolors=None):
#
# Path: antitile/tiling.py
# class Tiling:
# def __init__(self, vertices, faces):
# def edges(self):
# def face_size(self):
# def faces_by_size(self):
# def face_normals(self):
# def true_faces(self):
# def faces_by_edge(self, edges):
# def vertex_adjacency(self):
# def face_adjacency(self):
# def face_vertex_incidence(self):
# def vertex_f_adjacency(self):
# def face_v_adjacency(self):
# def normalize_faces(self):
# def id_dupe_faces(self, face_group=None, oriented=False):
# def edges_from_facelist(faces):
# def orient_face(face, edge):
# def energy(xyz, exponent=1, over=None):
# def center_of_gravity(xyz):
# def bentness(xyz, poly):
# def edge_length(xyz, edges, spherical=False):
# def face_area(xyz, poly, spherical=False):
# def aspect_ratio(xyz, poly, spherical=False):
which might include code, classes, or functions. Output only the next line. | state = np.zeros((args.n + 1, len(init)), dtype=bool) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.