Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> __all__ = [ 'Zorrolet', 'Hub', 'gethub', 'Future', 'Condition', 'Lock', ] FUTURE_EXCEPTION = marker_object('FUTURE_EXCEPTION') FUTURE_PENDING = marker_object('FUTURE_PENDING') <|code_end|> with the help of current file imports: import heapq import time import threading import select import weakref import logging import errno import greenlet from collections import deque, defaultdict from functools import partial from operator import methodcaller from math import ceil from .util import priorityqueue, orderedset, socket_pair, marker_object and context from other files: # Path: zorro/util.py # class priorityqueue(object): # # def __init__(self): # self.heap = [] # self.counter = 0 # # def add(self, pri, task): # self.counter += 1 # item = [pri, self.counter, task] # heappush(self.heap, item) # def remover(*a): # item[2] = None # return remover # # def min(self): # while self.heap and self.heap[0][2] is None: # heappop(self.heap) # if self.heap: # return self.heap[0][0] # return None # # def pop(self, value): # val = self.min() # if val is not None and val <= value: # return self.heap[0][2] # return None # # def __bool__(self): # return bool(self.heap) # # class orderedset(object): # # def __init__(self): # self.deque = deque() # # def add(self, *val): # self.deque.append(val) # def remover(*a): # self.deque.remove(val) # return remover # # def update(self, value): # self.deque.extend(value) # # def first(self): # if self.deque: # return self.deque[0] # return None # # def remove(self, value): # self.deque.remove(value) # # def __bool__(self): # return bool(self.deque) # # def socket_pair(): # a, b = socketpair() # a.setblocking(0) # b.setblocking(0) # return a, b # # class marker_object(object): # __slots__ = ('name',) # # def __init__(self, name): # self.name = name # # def __repr__(self): # return '<{}>'.format(self.name) , which may contain function names, class names, or code. Output only the next line.
os_errors = (IOError, OSError)
Here is a snippet: <|code_start|> __all__ = [ 'Zorrolet', 'Hub', 'gethub', 'Future', 'Condition', <|code_end|> . Write the next line using the current file imports: import heapq import time import threading import select import weakref import logging import errno import greenlet from collections import deque, defaultdict from functools import partial from operator import methodcaller from math import ceil from .util import priorityqueue, orderedset, socket_pair, marker_object and context from other files: # Path: zorro/util.py # class priorityqueue(object): # # def __init__(self): # self.heap = [] # self.counter = 0 # # def add(self, pri, task): # self.counter += 1 # item = [pri, self.counter, task] # heappush(self.heap, item) # def remover(*a): # item[2] = None # return remover # # def min(self): # while self.heap and self.heap[0][2] is None: # heappop(self.heap) # if self.heap: # return self.heap[0][0] # return None # # def pop(self, value): # val = self.min() # if val is not None and val <= value: # return self.heap[0][2] # return None # # def __bool__(self): # return bool(self.heap) # # class orderedset(object): # # def __init__(self): # self.deque = deque() # # def add(self, *val): # self.deque.append(val) # def remover(*a): # self.deque.remove(val) # return remover # # def update(self, value): # self.deque.extend(value) # # def first(self): # if self.deque: # return self.deque[0] # return None # # def remove(self, value): # self.deque.remove(value) # # def __bool__(self): # return bool(self.deque) # # def socket_pair(): # a, b = socketpair() # a.setblocking(0) # b.setblocking(0) # return a, b # # class marker_object(object): # __slots__ = ('name',) # # def __init__(self, name): # self.name = name # # def __repr__(self): # return '<{}>'.format(self.name) , which may include functions, classes, or code. Output only the next line.
'Lock',
Using the snippet: <|code_start|> __all__ = [ 'Zorrolet', 'Hub', 'gethub', 'Future', 'Condition', 'Lock', ] FUTURE_EXCEPTION = marker_object('FUTURE_EXCEPTION') FUTURE_PENDING = marker_object('FUTURE_PENDING') os_errors = (IOError, OSError) class TimeoutError(Exception): pass <|code_end|> , determine the next line of code. You have imports: import heapq import time import threading import select import weakref import logging import errno import greenlet from collections import deque, defaultdict from functools import partial from operator import methodcaller from math import ceil from .util import priorityqueue, orderedset, socket_pair, marker_object and context (class names, function names, or code) available: # Path: zorro/util.py # class priorityqueue(object): # # def __init__(self): # self.heap = [] # self.counter = 0 # # def add(self, pri, task): # self.counter += 1 # item = [pri, self.counter, task] # heappush(self.heap, item) # def remover(*a): # item[2] = None # return remover # # def min(self): # while self.heap and self.heap[0][2] is None: # heappop(self.heap) # if self.heap: # return self.heap[0][0] # return None # # def pop(self, value): # val = self.min() # if val is not None and val <= value: # return self.heap[0][2] # return None # # def __bool__(self): # return bool(self.heap) # # class orderedset(object): # # def __init__(self): # self.deque = deque() # # def add(self, *val): # self.deque.append(val) # def remover(*a): # self.deque.remove(val) # return remover # # def update(self, value): # self.deque.extend(value) # # def first(self): # if self.deque: # return self.deque[0] # return None # # def remove(self, value): # self.deque.remove(value) # # def __bool__(self): # return bool(self.deque) # # def socket_pair(): # a, b = socketpair() # a.setblocking(0) # b.setblocking(0) # return a, b # # class marker_object(object): # __slots__ = ('name',) # # def __init__(self, name): # self.name = name # # def __repr__(self): # return '<{}>'.format(self.name) . Output only the next line.
class WaitingError(Exception):
Given snippet: <|code_start|> def setUp(self): super().setUp() def collectd_putval(self): self.z.sleep(0.1) sock = self.z.collectd.Connection(unixsock=TEST_SOCKET) self.assertEqual((bytearray(b'0 Success'),), sock.putval('test/test/test', [('123', '256')], time=1234)) self.assertEqual((bytearray(b'0 Success'),), sock.putnotif("hello", time=1234)) self.assertEqual((bytearray(b'0 Success'),), sock.flush()) self.assertEqual({'in': 123, 'out': 234}, sock.getval('test/test/test')) self.assertEqual({'test/test/test': 235, 'test/test/test2': 657}, dict(sock.listval())) @interactive(collectd_putval) def test_hello(self): if os.access(TEST_SOCKET, os.F_OK): os.unlink(TEST_SOCKET) sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) with sock: sock.bind(TEST_SOCKET) sock.listen(1024) s, a = sock.accept() with s: self.assertEqual(s.recv(4096), b'PUTVAL test/test/test 1234:123.0:256.0') s.sendall(b'0 Success\n') self.assertEqual(s.recv(4096), <|code_end|> , continue by predicting the next line. Consider current file imports: import os import time import socket import zmq import zorro.collectd from .base import Test, interactive, passive and context: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def interactive(zfun): # def wrapper(fun): # @wraps(fun) # def wrapping(self, *a, **kw): # self.hub.add_task(partial(zfun, self, *a, **kw)) # self.thread.start() # fun(self, *a, **kw) # return wrapping # return wrapper # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping which might include code, classes, or functions. Output only the next line.
b'PUTNOTIF message="hello" severity=warning time=1234')
Next line prediction: <|code_start|> def make_request(self): sock = self.z.zmq.req_socket() sock.connect('tcp://127.0.0.1:9999') self.assertEqual(sock.request([b"hello", b"world"]).get(), [b"world", b"hello"]) self.assertEqual(sock.request([b"abra", b"kadabra"]).get(), [b"kadabra", b"abra"]) @interactive(make_request) def test_req(self): ctx = zmq.Context(1) sock = ctx.socket(zmq.REP) sock.bind('tcp://127.0.0.1:9999') data = sock.recv_multipart() sock.send_multipart(list(reversed(data))) data = sock.recv_multipart() sock.send_multipart(list(reversed(data))) def subscriber(self, *words): if len(words) < 5: self.pub.publish('real', *words) else: self.pub2.publish(repr(words)) @passive def test_pubsub(self): sock = self.z.zmq.sub_socket(self.subscriber) sock.bind('tcp://127.0.0.1:9999') sock.setsockopt(self.z.zmq.SUBSCRIBE, b"") <|code_end|> . Use current file imports: (import time import pickle import zmq import zorro.pool import unittest from .base import Test, interactive, passive) and context including class names, function names, or small code snippets from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def interactive(zfun): # def wrapper(fun): # @wraps(fun) # def wrapping(self, *a, **kw): # self.hub.add_task(partial(zfun, self, *a, **kw)) # self.thread.start() # fun(self, *a, **kw) # return wrapping # return wrapper # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping . Output only the next line.
self.pub = self.z.zmq.pub_socket()
Continue the code snippet: <|code_start|> [b"kadabra", b"abra"]) @interactive(make_request) def test_req(self): ctx = zmq.Context(1) sock = ctx.socket(zmq.REP) sock.bind('tcp://127.0.0.1:9999') data = sock.recv_multipart() sock.send_multipart(list(reversed(data))) data = sock.recv_multipart() sock.send_multipart(list(reversed(data))) def subscriber(self, *words): if len(words) < 5: self.pub.publish('real', *words) else: self.pub2.publish(repr(words)) @passive def test_pubsub(self): sock = self.z.zmq.sub_socket(self.subscriber) sock.bind('tcp://127.0.0.1:9999') sock.setsockopt(self.z.zmq.SUBSCRIBE, b"") self.pub = self.z.zmq.pub_socket() self.pub.connect('tcp://127.0.0.1:9999') f = self.z.Future() sock = self.z.zmq.sub_socket(f.set) sock.bind('tcp://127.0.0.1:9998') sock.setsockopt(self.z.zmq.SUBSCRIBE, b"") self.pub2 = self.z.zmq.pub_socket() <|code_end|> . Use current file imports: import time import pickle import zmq import zorro.pool import unittest from .base import Test, interactive, passive and context (classes, functions, or code) from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def interactive(zfun): # def wrapper(fun): # @wraps(fun) # def wrapping(self, *a, **kw): # self.hub.add_task(partial(zfun, self, *a, **kw)) # self.thread.start() # fun(self, *a, **kw) # return wrapping # return wrapper # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping . Output only the next line.
self.pub2.connect('tcp://127.0.0.1:9998')
Continue the code snippet: <|code_start|> b'1_end', b'2_end', b'3_start', b'4_start', b'3_end', b'4_end', ]) def subscriber(self, name, time): self.data.append(name+b'_start') if float(time) > 0.15: with self.assertRaises(self.z.pool.TimeoutError): self.z.sleep(float(time)) self.data.append(name+b'_timeout') else: self.z.sleep(float(time)) self.data.append(name+b'_end') def setup_subscr(self): sock = self.z.zmq.pull_socket(self.z.pool.Pool(self.subscriber, limit=2, timeout=0.15)) sock.connect('ipc:///tmp/zorro-pool-test') @interactive(setup_subscr) def test_pool_sub(self): self.data = [] ctx = zmq.Context(1) sock = ctx.socket(zmq.PUSH) sock.bind('ipc:///tmp/zorro-pool-test') <|code_end|> . Use current file imports: import time import pickle import zmq import zorro.pool import unittest from .base import Test, interactive, passive and context (classes, functions, or code) from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def interactive(zfun): # def wrapper(fun): # @wraps(fun) # def wrapping(self, *a, **kw): # self.hub.add_task(partial(zfun, self, *a, **kw)) # self.thread.start() # fun(self, *a, **kw) # return wrapping # return wrapper # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping . Output only the next line.
sock.send_multipart([b'1', b"0.1"])
Predict the next line for this snippet: <|code_start|> except TypeError: pass #------------------------------------------------------------------------------ to_string_converters = { int: str, float: str, str: str, list: list_to_str, tuple: list_to_str, bool: lambda x: 'True' if x else 'False', dict: json.dumps, datetime.datetime: datetime_to_ISO_string, datetime.date: date_to_ISO_string, datetime.timedelta: timedelta_to_str, type: arbitrary_object_to_string, types.ModuleType: arbitrary_object_to_string, types.FunctionType: arbitrary_object_to_string, compiled_regexp_type: lambda x: x.pattern, } if six.PY2: to_string_converters[six.text_type] = py2_to_str if six.PY3: to_string_converters[six.binary_type] = py3_to_str #------------------------------------------------------------------------------ def to_str(a_thing): try: <|code_end|> with the help of current file imports: import sys import re import datetime import types import json import six import six.moves.builtins as builtins from configman.datetime_util import ( datetime_from_ISO_string, date_from_ISO_string, datetime_to_ISO_string, date_to_ISO_string, ) from configman.config_exceptions import CannotConvertError from configman.datetime_util import ( str_to_timedelta, # don't worry about pyflakes here, unused in this file timedelta_to_str, # but used elsewhere ) from configman.namespace import Namespace from configman.required_config import RequiredConfig and context from other files: # Path: configman/datetime_util.py # def datetime_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DDTHH:MM:SS.S # and convert it into an instance of datetime.datetime # """ # try: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') # except ValueError: # try: # return datetime.datetime.strptime(s, '%Y-%m-%d') # except ValueError: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f') # # def date_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DD # and convert it into an instance of datetime.date # """ # return datetime.datetime.strptime(s, '%Y-%m-%d').date() # # def datetime_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DDTHH:MM:SS.S # """ # return aDate.isoformat() # # def date_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DD # """ # return aDate.strftime('%Y-%m-%d') # # Path: configman/datetime_util.py # def str_to_timedelta(input_str): # """ a string conversion function for timedelta for strings in the format # DD:HH:MM:SS or D HH:MM:SS # """ # try: # input_str = input_str.replace(' ', ':') # except (TypeError, AttributeError): # from configman.converters import to_str # raise TypeError('%s should have been a string' % to_str(input_str)) # days, hours, minutes, seconds = 0, 0, 0, 0 # details = input_str.split(':') # if len(details) >= 4: # days = int(details[-4]) # if len(details) >= 3: # hours = int(details[-3]) # if len(details) >= 2: # minutes = int(details[-2]) # if len(details) >= 1: # seconds = int(details[-1]) # return datetime.timedelta(days=days, # hours=hours, # minutes=minutes, # seconds=seconds) # # def timedelta_to_str(aTimedelta): # """ a conversion function for time deltas to string in the form # DD:HH:MM:SS # """ # days = aTimedelta.days # temp_seconds = aTimedelta.seconds # hours = int(temp_seconds / 3600) # minutes = int((temp_seconds - hours * 3600) / 60) # seconds = temp_seconds - hours * 3600 - minutes * 60 # return '%d %02d:%02d:%02d' % (days, hours, minutes, seconds) , which may contain function names, class names, or code. Output only the next line.
return to_string_converters[type(a_thing)](a_thing)
Predict the next line for this snippet: <|code_start|> into "subject_key, function -> function_key, etc.""" # is it None? if a_thing is None: return '' # is it already a string? if isinstance(a_thing, six.string_types): return a_thing if six.PY3 and isinstance(a_thing, six.binary_type): try: return a_thing.decode('utf-8') except UnicodeDecodeError: pass # does it have a to_str function? try: return a_thing.to_str() except (AttributeError, KeyError, TypeError): # AttributeError - no to_str function? # KeyError - DotDict has no to_str? # TypeError - problem converting # nope, no to_str function pass # is this a type proxy? try: return arbitrary_object_to_string(a_thing.a_type) except (AttributeError, KeyError, TypeError): # # nope, no a_type property pass # is it a built in? try: <|code_end|> with the help of current file imports: import sys import re import datetime import types import json import six import six.moves.builtins as builtins from configman.datetime_util import ( datetime_from_ISO_string, date_from_ISO_string, datetime_to_ISO_string, date_to_ISO_string, ) from configman.config_exceptions import CannotConvertError from configman.datetime_util import ( str_to_timedelta, # don't worry about pyflakes here, unused in this file timedelta_to_str, # but used elsewhere ) from configman.namespace import Namespace from configman.required_config import RequiredConfig and context from other files: # Path: configman/datetime_util.py # def datetime_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DDTHH:MM:SS.S # and convert it into an instance of datetime.datetime # """ # try: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') # except ValueError: # try: # return datetime.datetime.strptime(s, '%Y-%m-%d') # except ValueError: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f') # # def date_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DD # and convert it into an instance of datetime.date # """ # return datetime.datetime.strptime(s, '%Y-%m-%d').date() # # def datetime_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DDTHH:MM:SS.S # """ # return aDate.isoformat() # # def date_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DD # """ # return aDate.strftime('%Y-%m-%d') # # Path: configman/datetime_util.py # def str_to_timedelta(input_str): # """ a string conversion function for timedelta for strings in the format # DD:HH:MM:SS or D HH:MM:SS # """ # try: # input_str = input_str.replace(' ', ':') # except (TypeError, AttributeError): # from configman.converters import to_str # raise TypeError('%s should have been a string' % to_str(input_str)) # days, hours, minutes, seconds = 0, 0, 0, 0 # details = input_str.split(':') # if len(details) >= 4: # days = int(details[-4]) # if len(details) >= 3: # hours = int(details[-3]) # if len(details) >= 2: # minutes = int(details[-2]) # if len(details) >= 1: # seconds = int(details[-1]) # return datetime.timedelta(days=days, # hours=hours, # minutes=minutes, # seconds=seconds) # # def timedelta_to_str(aTimedelta): # """ a conversion function for time deltas to string in the form # DD:HH:MM:SS # """ # days = aTimedelta.days # temp_seconds = aTimedelta.seconds # hours = int(temp_seconds / 3600) # minutes = int((temp_seconds - hours * 3600) / 60) # seconds = temp_seconds - hours * 3600 - minutes * 60 # return '%d %02d:%02d:%02d' % (days, hours, minutes, seconds) , which may contain function names, class names, or code. Output only the next line.
return known_mapping_type_to_str[a_thing]
Continue the code snippet: <|code_start|> .strip('.') ) else: module_name = a_thing.__module__ return "%s.%s" % (module_name, a_thing.__name__) except AttributeError: # nope, not one of these pass # maybe it has a __name__ attribute? try: return a_thing.__name__ except AttributeError: # nope, not one of these pass # punt and see what happens if we just cast it to string return str(a_thing) py_obj_to_str = arbitrary_object_to_string # for backwards compatibility #------------------------------------------------------------------------------ def list_to_str(a_list, delimiter=', '): return delimiter.join(to_str(x) for x in a_list) #------------------------------------------------------------------------------ def py2_to_str(a_unicode): return six.text_type(a_unicode) <|code_end|> . Use current file imports: import sys import re import datetime import types import json import six import six.moves.builtins as builtins from configman.datetime_util import ( datetime_from_ISO_string, date_from_ISO_string, datetime_to_ISO_string, date_to_ISO_string, ) from configman.config_exceptions import CannotConvertError from configman.datetime_util import ( str_to_timedelta, # don't worry about pyflakes here, unused in this file timedelta_to_str, # but used elsewhere ) from configman.namespace import Namespace from configman.required_config import RequiredConfig and context (classes, functions, or code) from other files: # Path: configman/datetime_util.py # def datetime_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DDTHH:MM:SS.S # and convert it into an instance of datetime.datetime # """ # try: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') # except ValueError: # try: # return datetime.datetime.strptime(s, '%Y-%m-%d') # except ValueError: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f') # # def date_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DD # and convert it into an instance of datetime.date # """ # return datetime.datetime.strptime(s, '%Y-%m-%d').date() # # def datetime_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DDTHH:MM:SS.S # """ # return aDate.isoformat() # # def date_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DD # """ # return aDate.strftime('%Y-%m-%d') # # Path: configman/datetime_util.py # def str_to_timedelta(input_str): # """ a string conversion function for timedelta for strings in the format # DD:HH:MM:SS or D HH:MM:SS # """ # try: # input_str = input_str.replace(' ', ':') # except (TypeError, AttributeError): # from configman.converters import to_str # raise TypeError('%s should have been a string' % to_str(input_str)) # days, hours, minutes, seconds = 0, 0, 0, 0 # details = input_str.split(':') # if len(details) >= 4: # days = int(details[-4]) # if len(details) >= 3: # hours = int(details[-3]) # if len(details) >= 2: # minutes = int(details[-2]) # if len(details) >= 1: # seconds = int(details[-1]) # return datetime.timedelta(days=days, # hours=hours, # minutes=minutes, # seconds=seconds) # # def timedelta_to_str(aTimedelta): # """ a conversion function for time deltas to string in the form # DD:HH:MM:SS # """ # days = aTimedelta.days # temp_seconds = aTimedelta.seconds # hours = int(temp_seconds / 3600) # minutes = int((temp_seconds - hours * 3600) / 60) # seconds = temp_seconds - hours * 3600 - minutes * 60 # return '%d %02d:%02d:%02d' % (days, hours, minutes, seconds) . Output only the next line.
def py3_to_str(a_bytes):
Continue the code snippet: <|code_start|> return a_bytes.decode('utf-8') #------------------------------------------------------------------------------ known_mapping_type_to_str = {} for key, val in sorted(builtins.__dict__.items()): if val not in (True, False, list, dict): try: known_mapping_type_to_str[val] = key except TypeError: pass #------------------------------------------------------------------------------ to_string_converters = { int: str, float: str, str: str, list: list_to_str, tuple: list_to_str, bool: lambda x: 'True' if x else 'False', dict: json.dumps, datetime.datetime: datetime_to_ISO_string, datetime.date: date_to_ISO_string, datetime.timedelta: timedelta_to_str, type: arbitrary_object_to_string, types.ModuleType: arbitrary_object_to_string, types.FunctionType: arbitrary_object_to_string, compiled_regexp_type: lambda x: x.pattern, } if six.PY2: <|code_end|> . Use current file imports: import sys import re import datetime import types import json import six import six.moves.builtins as builtins from configman.datetime_util import ( datetime_from_ISO_string, date_from_ISO_string, datetime_to_ISO_string, date_to_ISO_string, ) from configman.config_exceptions import CannotConvertError from configman.datetime_util import ( str_to_timedelta, # don't worry about pyflakes here, unused in this file timedelta_to_str, # but used elsewhere ) from configman.namespace import Namespace from configman.required_config import RequiredConfig and context (classes, functions, or code) from other files: # Path: configman/datetime_util.py # def datetime_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DDTHH:MM:SS.S # and convert it into an instance of datetime.datetime # """ # try: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') # except ValueError: # try: # return datetime.datetime.strptime(s, '%Y-%m-%d') # except ValueError: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f') # # def date_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DD # and convert it into an instance of datetime.date # """ # return datetime.datetime.strptime(s, '%Y-%m-%d').date() # # def datetime_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DDTHH:MM:SS.S # """ # return aDate.isoformat() # # def date_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DD # """ # return aDate.strftime('%Y-%m-%d') # # Path: configman/datetime_util.py # def str_to_timedelta(input_str): # """ a string conversion function for timedelta for strings in the format # DD:HH:MM:SS or D HH:MM:SS # """ # try: # input_str = input_str.replace(' ', ':') # except (TypeError, AttributeError): # from configman.converters import to_str # raise TypeError('%s should have been a string' % to_str(input_str)) # days, hours, minutes, seconds = 0, 0, 0, 0 # details = input_str.split(':') # if len(details) >= 4: # days = int(details[-4]) # if len(details) >= 3: # hours = int(details[-3]) # if len(details) >= 2: # minutes = int(details[-2]) # if len(details) >= 1: # seconds = int(details[-1]) # return datetime.timedelta(days=days, # hours=hours, # minutes=minutes, # seconds=seconds) # # def timedelta_to_str(aTimedelta): # """ a conversion function for time deltas to string in the form # DD:HH:MM:SS # """ # days = aTimedelta.days # temp_seconds = aTimedelta.seconds # hours = int(temp_seconds / 3600) # minutes = int((temp_seconds - hours * 3600) / 60) # seconds = temp_seconds - hours * 3600 - minutes * 60 # return '%d %02d:%02d:%02d' % (days, hours, minutes, seconds) . Output only the next line.
to_string_converters[six.text_type] = py2_to_str
Continue the code snippet: <|code_start|> # does it have a to_str function? try: return a_thing.to_str() except (AttributeError, KeyError, TypeError): # AttributeError - no to_str function? # KeyError - DotDict has no to_str? # TypeError - problem converting # nope, no to_str function pass # is this a type proxy? try: return arbitrary_object_to_string(a_thing.a_type) except (AttributeError, KeyError, TypeError): # # nope, no a_type property pass # is it a built in? try: return known_mapping_type_to_str[a_thing] except (KeyError, TypeError): # nope, not a builtin pass # is it something from a loaded module? try: if a_thing.__module__ not in ('__builtin__', 'builtins', 'exceptions'): if a_thing.__module__ == "__main__": module_name = ( sys.modules['__main__'] .__file__[:-3] .replace('/', '.') <|code_end|> . Use current file imports: import sys import re import datetime import types import json import six import six.moves.builtins as builtins from configman.datetime_util import ( datetime_from_ISO_string, date_from_ISO_string, datetime_to_ISO_string, date_to_ISO_string, ) from configman.config_exceptions import CannotConvertError from configman.datetime_util import ( str_to_timedelta, # don't worry about pyflakes here, unused in this file timedelta_to_str, # but used elsewhere ) from configman.namespace import Namespace from configman.required_config import RequiredConfig and context (classes, functions, or code) from other files: # Path: configman/datetime_util.py # def datetime_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DDTHH:MM:SS.S # and convert it into an instance of datetime.datetime # """ # try: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') # except ValueError: # try: # return datetime.datetime.strptime(s, '%Y-%m-%d') # except ValueError: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f') # # def date_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DD # and convert it into an instance of datetime.date # """ # return datetime.datetime.strptime(s, '%Y-%m-%d').date() # # def datetime_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DDTHH:MM:SS.S # """ # return aDate.isoformat() # # def date_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DD # """ # return aDate.strftime('%Y-%m-%d') # # Path: configman/datetime_util.py # def str_to_timedelta(input_str): # """ a string conversion function for timedelta for strings in the format # DD:HH:MM:SS or D HH:MM:SS # """ # try: # input_str = input_str.replace(' ', ':') # except (TypeError, AttributeError): # from configman.converters import to_str # raise TypeError('%s should have been a string' % to_str(input_str)) # days, hours, minutes, seconds = 0, 0, 0, 0 # details = input_str.split(':') # if len(details) >= 4: # days = int(details[-4]) # if len(details) >= 3: # hours = int(details[-3]) # if len(details) >= 2: # minutes = int(details[-2]) # if len(details) >= 1: # seconds = int(details[-1]) # return datetime.timedelta(days=days, # hours=hours, # minutes=minutes, # seconds=seconds) # # def timedelta_to_str(aTimedelta): # """ a conversion function for time deltas to string in the form # DD:HH:MM:SS # """ # days = aTimedelta.days # temp_seconds = aTimedelta.seconds # hours = int(temp_seconds / 3600) # minutes = int((temp_seconds - hours * 3600) / 60) # seconds = temp_seconds - hours * 3600 - minutes * 60 # return '%d %02d:%02d:%02d' % (days, hours, minutes, seconds) . Output only the next line.
.strip('.')
Continue the code snippet: <|code_start|> datetime.date: date_converter, datetime.timedelta: timedelta_converter, type: class_converter, types.FunctionType: class_converter, compiled_regexp_type: regex_converter, } if six.PY2: str_to_instance_of_type_converters[six.text_type] = py2_to_unicode if six.PY3: str_to_instance_of_type_converters[six.binary_type] = py3_to_bytes # backward compatibility from_string_converters = str_to_instance_of_type_converters #------------------------------------------------------------------------------ def arbitrary_object_to_string(a_thing): """take a python object of some sort, and convert it into a human readable string. this function is used extensively to convert things like "subject" into "subject_key, function -> function_key, etc.""" # is it None? if a_thing is None: return '' # is it already a string? if isinstance(a_thing, six.string_types): return a_thing if six.PY3 and isinstance(a_thing, six.binary_type): try: return a_thing.decode('utf-8') except UnicodeDecodeError: <|code_end|> . Use current file imports: import sys import re import datetime import types import json import six import six.moves.builtins as builtins from configman.datetime_util import ( datetime_from_ISO_string, date_from_ISO_string, datetime_to_ISO_string, date_to_ISO_string, ) from configman.config_exceptions import CannotConvertError from configman.datetime_util import ( str_to_timedelta, # don't worry about pyflakes here, unused in this file timedelta_to_str, # but used elsewhere ) from configman.namespace import Namespace from configman.required_config import RequiredConfig and context (classes, functions, or code) from other files: # Path: configman/datetime_util.py # def datetime_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DDTHH:MM:SS.S # and convert it into an instance of datetime.datetime # """ # try: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') # except ValueError: # try: # return datetime.datetime.strptime(s, '%Y-%m-%d') # except ValueError: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f') # # def date_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DD # and convert it into an instance of datetime.date # """ # return datetime.datetime.strptime(s, '%Y-%m-%d').date() # # def datetime_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DDTHH:MM:SS.S # """ # return aDate.isoformat() # # def date_to_ISO_string(aDate): # """ Take a datetime and convert to string of the form YYYY-MM-DD # """ # return aDate.strftime('%Y-%m-%d') # # Path: configman/datetime_util.py # def str_to_timedelta(input_str): # """ a string conversion function for timedelta for strings in the format # DD:HH:MM:SS or D HH:MM:SS # """ # try: # input_str = input_str.replace(' ', ':') # except (TypeError, AttributeError): # from configman.converters import to_str # raise TypeError('%s should have been a string' % to_str(input_str)) # days, hours, minutes, seconds = 0, 0, 0, 0 # details = input_str.split(':') # if len(details) >= 4: # days = int(details[-4]) # if len(details) >= 3: # hours = int(details[-3]) # if len(details) >= 2: # minutes = int(details[-2]) # if len(details) >= 1: # seconds = int(details[-1]) # return datetime.timedelta(days=days, # hours=hours, # minutes=minutes, # seconds=seconds) # # def timedelta_to_str(aTimedelta): # """ a conversion function for time deltas to string in the form # DD:HH:MM:SS # """ # days = aTimedelta.days # temp_seconds = aTimedelta.seconds # hours = int(temp_seconds / 3600) # minutes = int((temp_seconds - hours * 3600) / 60) # seconds = temp_seconds - hours * 3600 - minutes * 60 # return '%d %02d:%02d:%02d' % (days, hours, minutes, seconds) . Output only the next line.
pass
Given snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import, division, print_function def setup_definitions(source, destination): try: <|code_end|> , continue by predicting the next line. Consider current file imports: import json from configman.def_sources import for_mappings and context: # Path: configman/def_sources/for_mappings.py # def setup_definitions(source, destination): which might include code, classes, or functions. Output only the next line.
json_dict = json.loads(source)
Based on the snippet: <|code_start|> namespace.alpha = 1 my_birthday = datetime.datetime(1960, 5, 4, 15, 10) namespace.beta = my_birthday self.assertEqual(namespace.alpha.name, 'alpha') self.assertEqual(namespace.alpha.doc, None) self.assertEqual(namespace.alpha.default, 1) self.assertEqual(namespace.alpha.from_string_converter, int) self.assertEqual(namespace.alpha.value, 1) self.assertEqual(namespace.beta.name, 'beta') self.assertEqual(namespace.beta.doc, None) self.assertEqual(namespace.beta.default, my_birthday) self.assertEqual( namespace.beta.from_string_converter, datetime_from_ISO_string ) self.assertEqual(namespace.beta.value, my_birthday) #-------------------------------------------------------------------------- def test_configuration_with_namespace(self): namespace = config_manager.Namespace() namespace.add_option('a') namespace.a.default = 1 namespace.a.doc = 'the a' namespace.b = 17 config = config_manager.ConfigurationManager( [namespace], argv_source=[] ) self.assertTrue( isinstance(config.option_definitions.b, config_manager.Option) <|code_end|> , predict the immediate next line with the help of imports: import unittest import datetime import functools import configman.config_manager as config_manager from configman.datetime_util import datetime_from_ISO_string from configman.option import Option from configman.orderedset import OrderedSet from copy import deepcopy and context (classes, functions, sometimes code) from other files: # Path: configman/datetime_util.py # def datetime_from_ISO_string(s): # """ Take an ISO date string of the form YYYY-MM-DDTHH:MM:SS.S # and convert it into an instance of datetime.datetime # """ # try: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') # except ValueError: # try: # return datetime.datetime.strptime(s, '%Y-%m-%d') # except ValueError: # return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f') . Output only the next line.
)
Given the code snippet: <|code_start|> self.assertEqual(b.counter, 10) #-------------------------------------------------------------------------- def test_memoize_class_method(self): class A(object): counter = 0 @classmethod @memoize() def foo(klass, a, b, c): klass.counter += 1 return (a, b, c) for i in range(5): # repeatable and exactly 10 function calls results = [A.foo(x, x, x) for x in range(10)] expected = [(x, x, x) for x in range(10)] self.assertEqual(results, expected) self.assertEqual(A.counter, 10) #-------------------------------------------------------------------------- def test_memoize_static_method(self): class A(object): counter = 0 @staticmethod @memoize() def foo(a, b, c): <|code_end|> , generate the next line using the imports in this file: import unittest from configman.memoize import memoize and context (functions, classes, or occasionally code) from other files: # Path: configman/memoize.py # def memoize(max_cache_size=1000): # """Python 2.4 compatible memoize decorator. # It creates a cache that has a maximum size. If the cache exceeds the max, # it is thrown out and a new one made. With such behavior, it is wise to set # the cache just a little larger that the maximum expected need. # # Parameters: # max_cache_size - the size to which a cache can grow # """ # def wrapper(f): # @wraps(f) # def fn(*args, **kwargs): # if kwargs: # key = (args, tuple(kwargs.items())) # else: # key = args # try: # return fn.cache[key] # except KeyError: # if fn.count >= max_cache_size: # fn.cache = {} # fn.count = 0 # result = f(*args, **kwargs) # fn.cache[key] = result # fn.count += 1 # return result # except TypeError: # return f(*args, **kwargs) # fn.cache = {} # fn.count = 0 # return fn # return wrapper . Output only the next line.
A.counter += 1
Predict the next line for this snippet: <|code_start|> assert 'c' not in d.a.b d = DotDict() d['a.b.c'] = 8 del d.a assert 'a' not in d """ key_split = key.split('.') current = self for k in key_split[:-1]: current = getattr(current, k) current.__delattr__(key_split[-1]) #-------------------------------------------------------------------------- def __iter__(self): """redirect the default iterator to iterate over the object's __dict__ making sure that it ignores the special '_' keys. We want those items ignored or we risk infinite recursion, not with this function, but with the clients of this class deep within configman""" return iter(self._key_order) #-------------------------------------------------------------------------- def __len__(self): """makes the len function also ignore the '_' keys""" return len(self._key_order) #-------------------------------------------------------------------------- def keys_breadth_first(self, include_dicts=False): """a generator that returns all the keys in a set of nested DotDict instances. The keys take the form X.Y.Z""" <|code_end|> with the help of current file imports: import collections import weakref import six from configman.orderedset import OrderedSet from configman.memoize import memoize and context from other files: # Path: configman/memoize.py # def memoize(max_cache_size=1000): # """Python 2.4 compatible memoize decorator. # It creates a cache that has a maximum size. If the cache exceeds the max, # it is thrown out and a new one made. With such behavior, it is wise to set # the cache just a little larger that the maximum expected need. # # Parameters: # max_cache_size - the size to which a cache can grow # """ # def wrapper(f): # @wraps(f) # def fn(*args, **kwargs): # if kwargs: # key = (args, tuple(kwargs.items())) # else: # key = args # try: # return fn.cache[key] # except KeyError: # if fn.count >= max_cache_size: # fn.cache = {} # fn.count = 0 # result = f(*args, **kwargs) # fn.cache[key] = result # fn.count += 1 # return result # except TypeError: # return f(*args, **kwargs) # fn.cache = {} # fn.count = 0 # return fn # return wrapper , which may contain function names, class names, or code. Output only the next line.
namespaces = []
Using the snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import, division, print_function #------------------------------------------------------------------------------ def setup_definitions(source, destination): for key, val in source.items(): <|code_end|> , determine the next line of code. You have imports: import collections from configman.converters import str_dict_keys from configman.namespace import Namespace from configman.option import ( Option, Aggregation, ) and context (class names, function names, or code) available: # Path: configman/converters.py # def str_dict_keys(a_dict): # """return a modified dict where all the keys that are anything but str get # converted to str. # E.g. # # >>> result = str_dict_keys({u'name': u'Peter', u'age': 99, 1: 2}) # >>> # can't compare whole dicts in doctests # >>> result['name'] # u'Peter' # >>> result['age'] # 99 # >>> result[1] # 2 # # The reason for this is that in Python <= 2.6.4 doing # ``MyClass(**{u'name': u'Peter'})`` would raise a TypeError # # Note that only unicode types are converted to str types. # The reason for that is you might have a class that looks like this:: # # class Option(object): # def __init__(self, foo=None, bar=None, **kwargs): # ... # # And it's being used like this:: # # Option(**{u'foo':1, u'bar':2, 3:4}) # # Then you don't want to change that {3:4} part which becomes part of # `**kwargs` inside the __init__ method. # Using integers as parameter keys is a silly example but the point is that # due to the python 2.6.4 bug only unicode keys are converted to str. # """ # new_dict = {} # for key in a_dict: # if six.PY2 and isinstance(key, six.text_type): # new_dict[str(key)] = a_dict[key] # else: # new_dict[key] = a_dict[key] # return new_dict . Output only the next line.
if key.startswith('__'):
Predict the next line for this snippet: <|code_start|> else: self.add_msg = add_msg class cls_pilconfig: # # initialize: create instance # def __init__(self): self.__config__= { } self.__userconfig__ = None return # # open: read in the configuration file into the dictionary # if the configuration file does not exist, an empty file is created # If clean is true do not read the config file # def open(self,name,configversion,instance,production,clean): self.__userconfig__= cls_userconfig(name,name,configversion,instance,production) if clean: return try: self.__config__= self.__userconfig__.read(self.__config__) except ConfigError as e: raise PilConfigError(e.msg,e.add_msg) # # Get a key from the configuration dictionary. To initialize a key a default # value can be specified # <|code_end|> with the help of current file imports: from .userconfig import cls_userconfig, ConfigError and context from other files: # Path: pyilper/userconfig.py # class cls_userconfig: # # def __init__(self,progname,filename,configversion,instance,production): # # # # determine config file name # # # self.__configfile__,self.__configpath__=buildconfigfilename(progname,filename,configversion,instance,production) # # # # # read configuration, if no configuration exists write default configuration # # # def read(self,default): # if not os.path.isfile(self.__configfile__): # if not os.path.exists(self.__configpath__): # try: # os.makedirs(self.__configpath__) # except OSError as e: # raise ConfigError("Cannot create path for configuration file", e.strerror) # try: # self.write(default) # except OSError as e: # raise ConfigError("Cannot write default configuration file", e.strerror) # return default # f=None # try: # f= open(self.__configfile__,"r") # config= json.load(f) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot decode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot read configuration file", e.strerror) # finally: # if f is not None: # f.close() # # return config # # # # Store configuration, create file if it does not exist # # # def write(self,config): # f=None # try: # f= open(self.__configfile__,"w") # json.dump(config,f,sort_keys=True,indent=3) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot encode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot write to configuration file", e.strerror) # finally: # if f is not None: # f.close() # # class ConfigError(Exception): # def __init__(self,msg,add_msg= None): # self.msg= msg # self.add_msg = add_msg , which may contain function names, class names, or code. Output only the next line.
def get(self,name,param,default=None):
Continue the code snippet: <|code_start|># - class statement syntax update # 17.09.2016 jsi: # - open method introduced # 14.10.2016 jsi: # - added filename parameter to cls_userconfig # 17.08.2017 jsi: # - assign "" to self.add_msg if parameter is none in PilConfigError # 20.01.2018 jsi # - added get_dual method # 12.02.2018 jsi # - added the clean parameter to the open method # 12.12.2021 jsi # - add configversion parameter to open method # class PilConfigError(Exception): def __init__(self,msg,add_msg= None): self.msg= msg if add_msg is None: self.add_msg="" else: self.add_msg = add_msg class cls_pilconfig: # # initialize: create instance # def __init__(self): <|code_end|> . Use current file imports: from .userconfig import cls_userconfig, ConfigError and context (classes, functions, or code) from other files: # Path: pyilper/userconfig.py # class cls_userconfig: # # def __init__(self,progname,filename,configversion,instance,production): # # # # determine config file name # # # self.__configfile__,self.__configpath__=buildconfigfilename(progname,filename,configversion,instance,production) # # # # # read configuration, if no configuration exists write default configuration # # # def read(self,default): # if not os.path.isfile(self.__configfile__): # if not os.path.exists(self.__configpath__): # try: # os.makedirs(self.__configpath__) # except OSError as e: # raise ConfigError("Cannot create path for configuration file", e.strerror) # try: # self.write(default) # except OSError as e: # raise ConfigError("Cannot write default configuration file", e.strerror) # return default # f=None # try: # f= open(self.__configfile__,"r") # config= json.load(f) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot decode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot read configuration file", e.strerror) # finally: # if f is not None: # f.close() # # return config # # # # Store configuration, create file if it does not exist # # # def write(self,config): # f=None # try: # f= open(self.__configfile__,"w") # json.dump(config,f,sort_keys=True,indent=3) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot encode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot write to configuration file", e.strerror) # finally: # if f is not None: # f.close() # # class ConfigError(Exception): # def __init__(self,msg,add_msg= None): # self.msg= msg # self.add_msg = add_msg . Output only the next line.
self.__config__= { }
Based on the snippet: <|code_start|> t=get_finfo_type(ft)[0] l= getLifInt(e,16,4)*256 # HP-75 ROM elif ft== 0xE08B: t=get_finfo_type(ft)[0] l= getLifInt(e,16,4)*256 # other ... else: t= "0x{:4X}".format(ft) l= getLifInt(e,16,4)* 256 return [t , l] class cls_LifFile: def __init__(self): self.filename= None # Name of LIF File self.filehd= None # File descriptor self.isWindows=False # platform idicator for i/o self.isLifFile= False # Valid lif file self.buffer= bytearray(256) # read write buffer self.header= bytearray(256) # lif header self.label = None self.dir_start=0 self.dir_length=0 self.no_tracks=0 self.no_surfaces=0 self.no_blocks=0 if isWINDOWS(): <|code_end|> , predict the immediate next line with the help of imports: import os from .lifcore import * from .pilcore import isWINDOWS and context (classes, functions, sometimes code) from other files: # Path: pyilper/pilcore.py # def isWINDOWS(): # return platform.system()=="Windows" . Output only the next line.
self.isWindows= True
Given snippet: <|code_start|> self.screen[pos:pos + len(s)] = s def fill(self, y0, x0, y1, x1, char): n = self.w * (y1 - y0 - 1) + (x1 - x0) self.poke(y0, x0, array.array('i', [char] * n)) def clear(self, y0, x0, y1, x1): self.fill(y0, x0, y1, x1, CHAR_ATTRIB_NONE | 0x20) # # utility functions for wrapped lines # # get length of a wrapped line # def get_wrapped_linelength(self,cy): if self.linelength[cy]==-1: return(self.linelength[cy-1]) else: return(self.linelength[cy]) # # set length of a wrapped line # def set_wrapped_linelength(self,cy,ll): if self.linelength[cy]==-1: self.linelength[cy-1]= ll else: self.linelength[cy]= ll # # get the position of the cursor in the wrapped line # def get_wrapped_cursor_x(self,cx,cy): <|code_end|> , continue by predicting the next line. Consider current file imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() which might include code, classes, or functions. Output only the next line.
if self.linelength[cy]==-1:
Given the following code snippet before the placeholder: <|code_start|> if item == CHAR_ATTRIB_UNDERLINE_SHORT: self._font.setUnderline(True) y += self._char_height # # add selection area to scene # cursor_in_selection= False if start_row is not None: # # check if cursor is in selection # startidx= start_row* self._cols+ start_col endidx= end_row* self._cols+ end_col cursoridx= self._cursor_row* self._cols + self._cursor_col if cursoridx >= startidx and cursoridx <= endidx: cursor_in_selection= True selectAreaItem= cls_SelectArea(start_row, start_col, end_row, end_col, self._cols, self._char_height, self._true_w, self._cursor_color) selectAreaItem.setPos(0,start_row* self._char_height) self._scene.addItem(selectAreaItem) # # add cursor at cursor position to scene # if self._cursortype != CURSOR_OFF and not cursor_in_selection: if self._cursor_attr: cursor_foreground_color= self._color_scheme[0] else: cursor_foreground_color= self._color_scheme[1] <|code_end|> , predict the next line using imports from the current file: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context including class names, function names, and sometimes code from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
self._cursorItem= TermCursor(self._char_width,self._char_height,self._cursortype, cursor_foreground_color)
Next line prediction: <|code_start|># # enable: start update timer (one shot timer) # def enable(self): self.UpdateTimer.start(UPDATE_TIMER) pass # # disable: do nothing # def disable(self): pass # # Terminal window was resized, update display and scrollbar # def resize_rows(self,rows): if self.view_h == rows: return self.view_h= rows if self.view_y1 == -1: self.view_y1 = self.view_h-1 else: self.view_y1= self.view_y0 +rows -1 # if self.view_y1 > rows: # self.view_y1= rows-1 # self.view_y0= self.view_y1-rows # if self.view_y0<0: # self.view_y0=0 # self.view_y1= self.view_y0+rows-1 ## fix if self.actual_h >= self.view_h: self.win.scrollbar.setMaximum(self.actual_h-self.view_h+1) <|code_end|> . Use current file imports: (import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import *) and context including class names, function names, or small code snippets from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
self.win.scrollbar.setPageStep(self.view_h)
Predict the next line after this snippet: <|code_start|> self.terminalwidget.setHPTerminal(self.HPTerminal) # # initialize scrollbar # self.scrollbar.valueChanged.connect(self.do_scrollbar) self.scrollbar.setEnabled(False) # # enable/disable # def enable(self): self.scrollbar.setEnabled(True) self.HPTerminal.enable() return def disable(self): self.scrollbar.setEnabled(False) self.HPTerminal.disable() return # # enable/disable keyboard input # def enable_keyboard(self): self.terminalwidget.set_kbdfunc(self.pildevice.putDataToHPIL) def disable_keyboard(self): self.terminalwidget.set_kbdfunc(None) # # scrollbar value changed action # <|code_end|> using the current file's imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and any relevant context from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
def do_scrollbar(self):
Given the code snippet: <|code_start|> def __init__(self,parent,name,tabwidget): super().__init__(parent) # # initialize Variables # self._name= name # name of tab self._tabwidget=tabwidget # widget of tab self._cols= -1 # terminal config, initialized in reconfigure self._rows= -1 # rows, calculated at resize event self._font_size=size= -1 # dto self._color_scheme_index= -1 # dto self._scrollupbuffersize= -1 # dto self._keyboard_type=-1 # keyboard type (HP-71 or HP-75) self._HPTerminal= None # backend object,set by setHPterminal self._screen = [] # frontend screen buffer self._cursor_col = 0 # cursor position self._cursor_row = 0 # dto. self._kbdfunc= None # function that is called to send keyboard input # to the loop, set by setkbdfunc self._alt_sequence= False # Variables for parsing ALT keyboard sequences self._alt_seq_length=0 # self._alt_seq_value=0 # self._alt_modifier= False # Alt key pressed self._shift_modifier=False # Shift key pressed self._ctrl_modifier=False # Ctrl key pressed self._modifier_flags=0 # Modifier flags for look up self._cursortype= CURSOR_OFF # cursor mode (off, overwrite, insert) self._cursor_char= 0x20 # character at cursor position self._cursor_attr=-1 # attribute at cursor position self._font=QtGui.QFont(FONT) # monospaced font <|code_end|> , generate the next line using the imports in this file: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context (functions, classes, or occasionally code) from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
self._isVisible= False # visible state
Based on the snippet: <|code_start|> self.linewrapped[cy-1]=True self.linelength[cy]=-1 self.linewrapped[cy]=False # # remove wrapped part of a line, cy must be in the non wrapped part # def remove_wrapped_part(self,cy): self.linewrapped[cy]=False self.linelength[cy+1]=0 self.linewrapped[cy+1]=False # # scroll screen buffer up if no room to add a new line # note: this adjust the object variables self.cy and self.actual_h # the method returns the new value of self.cy # def scroll_screenbuffer_up(self,n): self.poke(0, 0, self.peek(0 + n, 0, self.h, self.w)) self.clear(self.h - n, 0, self.h, self.w) self.linelength[0:self.h-n]=self.linelength[n:] self.linewrapped[0:self.h-n]=self.linewrapped[n:] for i in range(n): self.linelength[self.h-n]=0 self.linewrapped[self.h-n]=False self.cy-=n self.actual_h-=n return(self.cy) # # Scroll line right, add wrapped part if needed. If we exceed the length of the # wrapped line, ignore characters # <|code_end|> , predict the immediate next line with the help of imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context (classes, functions, sometimes code) from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
def scroll_line_right(self, y, x):
Predict the next line for this snippet: <|code_start|> self._HPTerminal.selectionStop() self._selectionText="" self._press_pos = event.pos() if not self._HPTerminal.selectionStart(self._press_pos,self._true_w, self._char_height): self._press_pos = None # # Mouse move event, draw selection area and get selection text # def mouseMoveEvent(self, event): if self._press_pos: move_pos = event.pos() self._saved_pos= move_pos if move_pos.y() < self._ScrollUpAreaY and move_pos.y() >=0 : self.set_autoscroll(AUTOSCROLL_UP) elif move_pos.y() > self._ScrollDownAreaY and move_pos.y() <=self.height() : self.set_autoscroll(AUTOSCROLL_DOWN) else: self.set_autoscroll(AUTOSCROLL_OFF) if self._HPTerminal.selectionMove(move_pos,self._true_w, self._char_height): self._selectionText= self._HPTerminal.getSelectionText() # # Mouse release event, stop autoscroll unconditionally # def mouseReleaseEvent(self, event): self.set_autoscroll(AUTOSCROLL_OFF) # # autoscroll control function # def set_autoscroll(self,mode): <|code_end|> with the help of current file imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() , which may contain function names, class names, or code. Output only the next line.
if mode != self._autoscrollMode:
Predict the next line after this snippet: <|code_start|> self.actual_h+=1 self.update_scrollbar() return(newcy) # # remove buffer line # def remove_bufferline(self,cy): newcy= cy-1 self.actual_h= newcy self.update_scrollbar() return(newcy) # # Update scroll bar parameters # def update_scrollbar(self): if self.actual_h < self.view_h: self.win.scrollbar.setMaximum(0) else: self.win.scrollbar.setMaximum(self.actual_h-self.view_h+1) self.win.scrollbar.setValue(self.actual_h-self.view_h+1) ## fix # # clear from cursor to end of display # def clear_to_eod(self): self.clear(self.cy,self.cx,self.h, self.w) self.actual_h= self.cy self.update_scrollbar() # # Cursor functions, up and down # <|code_end|> using the current file's imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and any relevant context from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
def cursor_up(self):
Predict the next line for this snippet: <|code_start|># # keyboard pressed event, process keys and put them into the HP-IL outdata buffer # def keyPressEvent(self, event): if self._kbdfunc is None: event.accept() return if event.isAutoRepeat(): if self.isAutorepeatInhibited(): event.accept() return self.inhibitAutorepeat() text = event.text() key = event.key() # # handle modifier keys first # if key == QtCore.Qt.Key_Alt: self._alt_modifier= True self._modifier_flags= self._modifier_flags | KEYBOARD_ALT elif key == QtCore.Qt.Key_Shift: self._shift_modifier= True self._modifier_flags= self._modifier_flags | KEYBOARD_SHIFT elif key == QtCore.Qt.Key_Control: self._modifier_flags= self._modifier_flags | KEYBOARD_CTRL if not isMACOS(): self._ctrl_modifier=True elif key == QtCore.Qt.Key_Meta: if isMACOS(): <|code_end|> with the help of current file imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() , which may contain function names, class names, or code. Output only the next line.
self._ctrl_modifier=True
Continue the code snippet: <|code_start|># def set_charset(self,charset): self.HPTerminal.set_charset(charset) # # set keyboard type # def set_keyboardtype(self,t): self.terminalwidget.set_keyboardtype(t) # # tab becomes visible, call appropriate methods to: # - stop cursor blink # - disable update of the graphics scene (the buffer gets still updated) # def becomes_visible(self): self.terminalwidget.becomes_visible() self.HPTerminal.becomes_visible() # # tab becomes invisible, call appropriate methods to: # - restart cursor blink # - enable update of the graphics scene # - redraw graphics scene # def becomes_invisible(self): self.terminalwidget.becomes_invisible() self.HPTerminal.becomes_invisible() # # output character to terminal # def out_terminal(self,t): <|code_end|> . Use current file imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context (classes, functions, or code) from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
self.HPTerminal.out_terminal(t)
Given snippet: <|code_start|> return self.inhibitAutorepeat() text = event.text() key = event.key() # # handle modifier keys first # if key == QtCore.Qt.Key_Alt: self._alt_modifier= True self._modifier_flags= self._modifier_flags | KEYBOARD_ALT elif key == QtCore.Qt.Key_Shift: self._shift_modifier= True self._modifier_flags= self._modifier_flags | KEYBOARD_SHIFT elif key == QtCore.Qt.Key_Control: self._modifier_flags= self._modifier_flags | KEYBOARD_CTRL if not isMACOS(): self._ctrl_modifier=True elif key == QtCore.Qt.Key_Meta: if isMACOS(): self._ctrl_modifier=True self._modifier_flags= self._modifier_flags | KEYBOARD_CTRL # # Alt pressed without Shift or Ctrl # elif self._modifier_flags== KEYBOARD_ALT: # # process Altnnn # if self._alt_sequence: <|code_end|> , continue by predicting the next line. Consider current file imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() which might include code, classes, or functions. Output only the next line.
if key >= QtCore.Qt.Key_0 and key <= QtCore.Qt.Key_9:
Given snippet: <|code_start|> def ctrl_CR(self): if self.is_wrapped(self.cy) and self.in_wrapped_part(self.cy): self.cy-=1 self.cursor_set_x(0) # # Dumb echo, if we exceed the wrapped part then issue a CR/LF # def dumb_echo(self, char): # print("dumb_echo ",char) if self.insert: self.scroll_line_right(self.cy, self.cx) self.poke(self.cy, self.cx, array.array('i', [self.attr | char])) else: oldwrappedlinelength=self.get_wrapped_linelength(self.cy) # print("dumb echo ",oldwrappedlinelength, self.w*2) if oldwrappedlinelength == self.w*2: # print("dumb_echo cr/lf") self.ctrl_CR() self.ctrl_LF() self.poke(self.cy, self.cx, array.array('i', [self.attr | char])) # # do not increase line length if we overwrite existing text # cursor_pos=self.get_wrapped_cursor_x(self.cx,self.cy) if cursor_pos== oldwrappedlinelength: self.set_wrapped_linelength(self.cy,oldwrappedlinelength+1) self.cursor_right() # # dump screen to terminal window, the data are painted during a paint event # <|code_end|> , continue by predicting the next line. Consider current file imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() which might include code, classes, or functions. Output only the next line.
def dump(self):
Predict the next line for this snippet: <|code_start|> self._cols, self._char_height, self._true_w, self._cursor_color) selectAreaItem.setPos(0,start_row* self._char_height) self._scene.addItem(selectAreaItem) # # add cursor at cursor position to scene # if self._cursortype != CURSOR_OFF and not cursor_in_selection: if self._cursor_attr: cursor_foreground_color= self._color_scheme[0] else: cursor_foreground_color= self._color_scheme[1] self._cursorItem= TermCursor(self._char_width,self._char_height,self._cursortype, cursor_foreground_color) self._cursorItem.setPos(self._true_w[self._cursor_col],self._cursor_row*self._char_height) self._scene.addItem(self._cursorItem) self._font.setUnderline(False) # # Terminal backend class ----------------------------------------------------------- # # The terminal backend class maintains the terminal line buffer. The terminal # line buffer content is arranged by the input of text and escape sequences that # control editing and and the cursor position. # The backend class also maintains the boundaries of the visible part of the # line buffer that is rendered by the frontend widget and sets the scrollbar parameters. # class HPTerminal: def __init__(self, win, name): <|code_end|> with the help of current file imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and context from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() , which may contain function names, class names, or code. Output only the next line.
self.name=name # name of tab
Predict the next line after this snippet: <|code_start|># - removed special Mac key lookup # - update self.actual_h on "delete to end of display" # 28.01.2019 jsi # - autorepeat delay improved # 10.02.2019 jsi # - disable tab widget switching in terminal widget and enable TAB key for # keyboard input # 11.02.2019 jsi # - prevent possible crash in shortcut lookup # - use inverse video instead of underline for HP-75 character set # 06.12.2021 jsi # - fixed _kbdfunc call in paste # # to do: # fix the reason for a possible index error in HPTerminal.dump() CURSOR_OFF=0 CURSOR_INSERT=1 CURSOR_OVERWRITE=2 AUTOSCROLL_OFF=0 AUTOSCROLL_UP=1 AUTOSCROLL_DOWN=2 # # character attributes # CHAR_ATTRIB_NONE= 0x00000000 CHAR_ATTRIB_INVERSE= 0x020000000 <|code_end|> using the current file's imports: import array import queue import threading import time from PyQt5 import QtCore, QtGui, QtWidgets from .pilcharconv import icharconv, CHARSET_HP71, CHARSET_HP75, CHARSET_HP41 from .pilcore import UPDATE_TIMER, CURSOR_BLINK, TERMINAL_MINIMUM_ROWS,FONT, AUTOSCROLL_RATE, isMACOS, KEYBOARD_DELAY from .shortcutconfig import SHORTCUTCONFIG, SHORTCUT_EXEC, SHORTCUT_EDIT, SHORTCUT_INSERT from .pilconfig import PILCONFIG from .pilkeymap import * and any relevant context from other files: # Path: pyilper/pilcharconv.py # def icharconv(i, charset): # return convert_to_unicode[charset][i] # # CHARSET_HP71=0 # # CHARSET_HP75=2 # # CHARSET_HP41=1 # # Path: pyilper/pilcore.py # UPDATE_TIMER=25 # Poll timer (ms) for terminal output queue # # CURSOR_BLINK=500 # 500 ms cursor blink rate # # TERMINAL_MINIMUM_ROWS=24 # can't get beyond that # # FONT="Monospace" # # AUTOSCROLL_RATE=100 # 500 ms cursor blink rate # # def isMACOS(): # return platform.system()=="Darwin" # # KEYBOARD_DELAY=500 # autorepeat delay to prevent too fast kbd input # # Path: pyilper/shortcutconfig.py # SHORTCUTCONFIG= cls_shortcutconfig() # # SHORTCUT_EXEC=1 # # SHORTCUT_EDIT=2 # # SHORTCUT_INSERT=3 # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
CHAR_ATTRIB_INVERSE_SHORT= CHAR_ATTRIB_INVERSE >> 16
Here is a snippet: <|code_start|> @staticmethod def getPenConfig(): dialog= cls_PenConfigWindow() dialog.resize(650,600) result= dialog.exec_() if result== QtWidgets.QDialog.Accepted: return True else: return False class PenConfigError(Exception): def __init__(self,msg,add_msg= None): self.msg= msg self.add_msg = add_msg class cls_penconfig: # # initialize: set penconfig to the default configuration # def __init__(self): self.__penconfig__= None self.__userconfig__ = None return # # default config # def default_config(self): return [ ["Black 0.3 mm", 0x00,0x00,0x00,0xff,1.0], ["Red 0.3 mm", 0xff,0x00,0x00,0xff,1.0], <|code_end|> . Write the next line using the current file imports: import copy from PyQt5 import QtCore, QtGui, QtWidgets from .userconfig import cls_userconfig, ConfigError and context from other files: # Path: pyilper/userconfig.py # class cls_userconfig: # # def __init__(self,progname,filename,configversion,instance,production): # # # # determine config file name # # # self.__configfile__,self.__configpath__=buildconfigfilename(progname,filename,configversion,instance,production) # # # # # read configuration, if no configuration exists write default configuration # # # def read(self,default): # if not os.path.isfile(self.__configfile__): # if not os.path.exists(self.__configpath__): # try: # os.makedirs(self.__configpath__) # except OSError as e: # raise ConfigError("Cannot create path for configuration file", e.strerror) # try: # self.write(default) # except OSError as e: # raise ConfigError("Cannot write default configuration file", e.strerror) # return default # f=None # try: # f= open(self.__configfile__,"r") # config= json.load(f) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot decode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot read configuration file", e.strerror) # finally: # if f is not None: # f.close() # # return config # # # # Store configuration, create file if it does not exist # # # def write(self,config): # f=None # try: # f= open(self.__configfile__,"w") # json.dump(config,f,sort_keys=True,indent=3) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot encode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot write to configuration file", e.strerror) # finally: # if f is not None: # f.close() # # class ConfigError(Exception): # def __init__(self,msg,add_msg= None): # self.msg= msg # self.add_msg = add_msg , which may include functions, classes, or code. Output only the next line.
["Green 0.3 mm", 0x00,0xff,0x00,0xff,1.0],
Based on the snippet: <|code_start|># self.tablemodel=PenTableModel(PENCONFIG.get_all()) self.tableview= QtWidgets.QTableView() self.tableview.setModel(self.tablemodel) self.tableview.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch) self.tableview.verticalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch) self.delegate= PenDelegate() self.tableview.setItemDelegate(self.delegate) self.vlayout.addWidget(self.tableview) # # ok/cancel button box # self.buttonBox = QtWidgets.QDialogButtonBox() self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Reset| QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setCenterButtons(True) self.buttonBox.accepted.connect(self.do_ok) self.buttonBox.rejected.connect(self.do_cancel) self.buttonBox.button(QtWidgets.QDialogButtonBox.Reset).clicked.connect(self.do_reset) self.vlayout.addWidget(self.buttonBox) self.setLayout(self.vlayout) def do_ok(self): PENCONFIG.set_all(self.tablemodel.getTable()) super().accept() def do_cancel(self): super().reject() # # reset populates table with the default configuration # <|code_end|> , predict the immediate next line with the help of imports: import copy from PyQt5 import QtCore, QtGui, QtWidgets from .userconfig import cls_userconfig, ConfigError and context (classes, functions, sometimes code) from other files: # Path: pyilper/userconfig.py # class cls_userconfig: # # def __init__(self,progname,filename,configversion,instance,production): # # # # determine config file name # # # self.__configfile__,self.__configpath__=buildconfigfilename(progname,filename,configversion,instance,production) # # # # # read configuration, if no configuration exists write default configuration # # # def read(self,default): # if not os.path.isfile(self.__configfile__): # if not os.path.exists(self.__configpath__): # try: # os.makedirs(self.__configpath__) # except OSError as e: # raise ConfigError("Cannot create path for configuration file", e.strerror) # try: # self.write(default) # except OSError as e: # raise ConfigError("Cannot write default configuration file", e.strerror) # return default # f=None # try: # f= open(self.__configfile__,"r") # config= json.load(f) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot decode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot read configuration file", e.strerror) # finally: # if f is not None: # f.close() # # return config # # # # Store configuration, create file if it does not exist # # # def write(self,config): # f=None # try: # f= open(self.__configfile__,"w") # json.dump(config,f,sort_keys=True,indent=3) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot encode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot write to configuration file", e.strerror) # finally: # if f is not None: # f.close() # # class ConfigError(Exception): # def __init__(self,msg,add_msg= None): # self.msg= msg # self.add_msg = add_msg . Output only the next line.
def do_reset(self):
Given the code snippet: <|code_start|> except OSError as e: raise ConfigError("Cannot write default configuration file", e.strerror) return default f=None try: f= open(self.__configfile__,"r") config= json.load(f) except json.JSONDecodeError as e: add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) raise ConfigError("Cannot decode configuration data",add_msg) except OSError as e: raise ConfigError("Cannot read configuration file", e.strerror) finally: if f is not None: f.close() return config # # Store configuration, create file if it does not exist # def write(self,config): f=None try: f= open(self.__configfile__,"w") json.dump(config,f,sort_keys=True,indent=3) except json.JSONDecodeError as e: add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) raise ConfigError("Cannot encode configuration data",add_msg) except OSError as e: raise ConfigError("Cannot write to configuration file", e.strerror) <|code_end|> , generate the next line using the imports in this file: import json import os from .pilcore import buildconfigfilename and context (functions, classes, or occasionally code) from other files: # Path: pyilper/pilcore.py # def buildconfigfilename(progname,filename,configversion,instance,production): # # # # determine config file name # # # fname=filename+instance+configversion # if not production: # fname+= "d" # # # # determine path (os dependend) # # # userhome=os.path.expanduser("~") # # if platform.system()=="Linux": # # # # LINUX # # # configpath=os.path.join(userhome,".config",progname) # elif platform.system()=="Windows": # # # # Windows # # # configpath=os.path.join(os.environ['APPDATA'],progname) # elif platform.system()=="Darwin": # # # # Mac OS X # # # configpath=os.path.join(userhome,"Library","Application Support",progname) # # # else: # # # # Fallback # # # configpath=os.path.join(userhome,progname) # configfilename=os.path.join(configpath,fname) # # return configfilename,configpath . Output only the next line.
finally:
Given the code snippet: <|code_start|> submenu=QtWidgets.QMenu(option_text,parent=self.menu) self.menu.addMenu(submenu) submenu.aboutToShow.connect(functools.partial(self.do_before_show_submenu,n)) k=0 option_actions=[] for choice in option_choices: if option_type== T_BOOLEAN: if choice== True: choice="On" else: choice="Off" if option_type== T_INTEGER: if choice== -1: choice="Default" else: choice= str(choice) action= submenu.addAction(choice) option_actions.append(action) action.triggered.connect(functools.partial(self. do_choice_submenu,n,k)) k+=1 self.options.append([option_name, option_type, option_choices, option_actions]) # # clears the variable which contains the changed option # def do_before_show_menu(self): self.config_changed=None # # returns the name of the changed option or None # def get_changed_option_name(self): <|code_end|> , generate the next line using the imports in this file: import os import glob import datetime import re import sys import functools import pyilper import winreg from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtWebKitWidgets from PyQt5 import QtWebEngineWidgets from .pilqterm import QScrolledTerminalWidget from .pilcharconv import CHARSET_HP71, charsets from .pilconfig import PILCONFIG from .pilcore import * and context (functions, classes, or occasionally code) from other files: # Path: pyilper/pilqterm.py # class QScrolledTerminalWidget(QtWidgets.QWidget): # # def __init__(self,parent,name): # super().__init__(parent) # self.pildevice= None # self.name= name # self.tabwidget=parent # # # # create terminal window and scrollbar # # # self.hbox= QtWidgets.QHBoxLayout() # self.hbox.addStretch(1) # self.terminalwidget= QTerminalWidget(self,self.name,self.tabwidget) # self.hbox.addWidget(self.terminalwidget) # self.scrollbar= QtWidgets.QScrollBar() # self.hbox.addWidget(self.scrollbar) # self.hbox.addStretch(1) # self.setLayout(self.hbox) # self.HPTerminal= HPTerminal(self,self.name) # self.terminalwidget.setHPTerminal(self.HPTerminal) # # # # initialize scrollbar # # # self.scrollbar.valueChanged.connect(self.do_scrollbar) # self.scrollbar.setEnabled(False) # # # # enable/disable # # # def enable(self): # self.scrollbar.setEnabled(True) # self.HPTerminal.enable() # return # # def disable(self): # self.scrollbar.setEnabled(False) # self.HPTerminal.disable() # return # # # # enable/disable keyboard input # # # def enable_keyboard(self): # self.terminalwidget.set_kbdfunc(self.pildevice.putDataToHPIL) # # def disable_keyboard(self): # self.terminalwidget.set_kbdfunc(None) # # # # # scrollbar value changed action # # # def do_scrollbar(self): # self.HPTerminal.scroll_to(self.scrollbar.value()) # self.scrollbar.setEnabled(True) # # # # setting function pass through to backend # # # def set_charset(self,charset): # self.HPTerminal.set_charset(charset) # # # # # set keyboard type # # # def set_keyboardtype(self,t): # self.terminalwidget.set_keyboardtype(t) # # # # tab becomes visible, call appropriate methods to: # # - stop cursor blink # # - disable update of the graphics scene (the buffer gets still updated) # # # def becomes_visible(self): # self.terminalwidget.becomes_visible() # self.HPTerminal.becomes_visible() # # # # tab becomes invisible, call appropriate methods to: # # - restart cursor blink # # - enable update of the graphics scene # # - redraw graphics scene # # # def becomes_invisible(self): # self.terminalwidget.becomes_invisible() # self.HPTerminal.becomes_invisible() # # # # output character to terminal # # # def out_terminal(self,t): # self.HPTerminal.out_terminal(t) # # # # reset terminal # # # def reset_terminal(self): # self.HPTerminal.reset_terminal() # # # # redraw do nothing # # # def redraw(self): # return # # # # set pildevice # # # def set_pildevice(self,device): # self.pildevice= device # # # # reconfigure # # # def reconfigure(self): # self.terminalwidget.reconfigure() # self.HPTerminal.reconfigure() # # # # get actual number of columns # # # def get_cols(self): # return self.terminalwidget.get_cols() # # # # get actual number of rows # # # def get_rows(self): # return self.terminalwidget.get_rows() # # Path: pyilper/pilcharconv.py # CHARSET_HP71=0 # CHARSET_HP41=1 # CHARSET_HP75=2 # CHARSET_ROMAN8=3 # CHARSET_HP2225=4 # def charconv(s, charset): # def icharconv(i, charset): # def barrconv(barr, charset): # def stringconv(string, charset): # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
if self.config_changed==None:
Based on the snippet: <|code_start|> self.vlayout = QtWidgets.QVBoxLayout() # # item list and up/down buttons # self.hlayout = QtWidgets.QHBoxLayout() self.devList = QtWidgets.QListWidget() self.hlayout.addWidget(self.devList) self.vlayout2= QtWidgets.QVBoxLayout() self.buttonUp= QtWidgets.QPushButton("^") self.vlayout2.addWidget(self.buttonUp) self.buttonDown= QtWidgets.QPushButton("v") self.vlayout2.addWidget(self.buttonDown) self.buttonAdd= QtWidgets.QPushButton("Add") self.vlayout2.addWidget(self.buttonAdd) self.buttonRemove= QtWidgets.QPushButton("Remove") self.vlayout2.addWidget(self.buttonRemove) self.hlayout.addLayout(self.vlayout2) self.vlayout.addLayout(self.hlayout) self.buttonUp.clicked.connect(self.do_itemUp) self.buttonDown.clicked.connect(self.do_itemDown) self.buttonAdd.clicked.connect(self.do_itemAdd) self.buttonRemove.clicked.connect(self.do_itemRemove) # # ok/cancel button box # self.buttonBox = QtWidgets.QDialogButtonBox() self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setCenterButtons(True) self.buttonBox.accepted.connect(self.do_ok) <|code_end|> , predict the immediate next line with the help of imports: import os import glob import datetime import re import sys import functools import pyilper import winreg from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtWebKitWidgets from PyQt5 import QtWebEngineWidgets from .pilqterm import QScrolledTerminalWidget from .pilcharconv import CHARSET_HP71, charsets from .pilconfig import PILCONFIG from .pilcore import * and context (classes, functions, sometimes code) from other files: # Path: pyilper/pilqterm.py # class QScrolledTerminalWidget(QtWidgets.QWidget): # # def __init__(self,parent,name): # super().__init__(parent) # self.pildevice= None # self.name= name # self.tabwidget=parent # # # # create terminal window and scrollbar # # # self.hbox= QtWidgets.QHBoxLayout() # self.hbox.addStretch(1) # self.terminalwidget= QTerminalWidget(self,self.name,self.tabwidget) # self.hbox.addWidget(self.terminalwidget) # self.scrollbar= QtWidgets.QScrollBar() # self.hbox.addWidget(self.scrollbar) # self.hbox.addStretch(1) # self.setLayout(self.hbox) # self.HPTerminal= HPTerminal(self,self.name) # self.terminalwidget.setHPTerminal(self.HPTerminal) # # # # initialize scrollbar # # # self.scrollbar.valueChanged.connect(self.do_scrollbar) # self.scrollbar.setEnabled(False) # # # # enable/disable # # # def enable(self): # self.scrollbar.setEnabled(True) # self.HPTerminal.enable() # return # # def disable(self): # self.scrollbar.setEnabled(False) # self.HPTerminal.disable() # return # # # # enable/disable keyboard input # # # def enable_keyboard(self): # self.terminalwidget.set_kbdfunc(self.pildevice.putDataToHPIL) # # def disable_keyboard(self): # self.terminalwidget.set_kbdfunc(None) # # # # # scrollbar value changed action # # # def do_scrollbar(self): # self.HPTerminal.scroll_to(self.scrollbar.value()) # self.scrollbar.setEnabled(True) # # # # setting function pass through to backend # # # def set_charset(self,charset): # self.HPTerminal.set_charset(charset) # # # # # set keyboard type # # # def set_keyboardtype(self,t): # self.terminalwidget.set_keyboardtype(t) # # # # tab becomes visible, call appropriate methods to: # # - stop cursor blink # # - disable update of the graphics scene (the buffer gets still updated) # # # def becomes_visible(self): # self.terminalwidget.becomes_visible() # self.HPTerminal.becomes_visible() # # # # tab becomes invisible, call appropriate methods to: # # - restart cursor blink # # - enable update of the graphics scene # # - redraw graphics scene # # # def becomes_invisible(self): # self.terminalwidget.becomes_invisible() # self.HPTerminal.becomes_invisible() # # # # output character to terminal # # # def out_terminal(self,t): # self.HPTerminal.out_terminal(t) # # # # reset terminal # # # def reset_terminal(self): # self.HPTerminal.reset_terminal() # # # # redraw do nothing # # # def redraw(self): # return # # # # set pildevice # # # def set_pildevice(self,device): # self.pildevice= device # # # # reconfigure # # # def reconfigure(self): # self.terminalwidget.reconfigure() # self.HPTerminal.reconfigure() # # # # get actual number of columns # # # def get_cols(self): # return self.terminalwidget.get_cols() # # # # get actual number of rows # # # def get_rows(self): # return self.terminalwidget.get_rows() # # Path: pyilper/pilcharconv.py # CHARSET_HP71=0 # CHARSET_HP41=1 # CHARSET_HP75=2 # CHARSET_ROMAN8=3 # CHARSET_HP2225=4 # def charconv(s, charset): # def icharconv(i, charset): # def barrconv(barr, charset): # def stringconv(string, charset): # # Path: pyilper/pilconfig.py # PILCONFIG= cls_pilconfig() . Output only the next line.
self.buttonBox.rejected.connect(self.do_cancel)
Predict the next line for this snippet: <|code_start|> class cls_pilbox: def __init__(self,ttydevice,baudrate,idyframe): self.__baudrate__= baudrate # baudrate of connection or 0 for autodetect self.__idyframe__= idyframe # switch box to send idy frames self.__tty__= cls_rs232() # serial device object self.__ttydevice__=ttydevice # serial port name # # get connection speed # def getBaudRate(self): return(self.__baudrate__) # # send command to PIL-Box, check return value # def __sendCmd__(self,cmdfrm,tmout): hbyt,lbyt= disassemble_frame(cmdfrm) try: self.write(lbyt,hbyt) bytrx= self.__tty__.rcv(tmout) except Rs232Error as e: raise PilBoxError("PIL-Box command error:", e.value) if bytrx is None: raise PilBoxError("PIL-Box command error: timeout","") try: if ((ord(bytrx) & 0x3F) != (cmdfrm & 0x3F)): raise PilBoxError("PIL-Box command error: illegal retval","") <|code_end|> with the help of current file imports: from .pilrs232 import Rs232Error, cls_rs232 from .pilcore import * and context from other files: # Path: pyilper/pilrs232.py # class Rs232Error(Exception): # def __init__(self,value): # self.value=value # def __str__(self): # return repr(self.value) # # class cls_rs232: # # def __init__(self,parent=None): # self.__device__= None # self.__isOpen__= False # self.__timeout__=0 # # # # # Windows needs much time to reconfigure the timeout value of the serial # # device, so alter the device settings only if necessary. Give the device # # some time to settle. # # # def __settimeout__(self,timeout): # if timeout != self.__timeout__: # try: # self.__ser__.timeout= timeout # except: # raise Rs232Error('cannot set timeout value of serial device') # self.__timeout__=timeout # # def isOpen(self): # return self.__isOpen__ # # # def open(self,device,baudrate): # # # # use Windows device naming (hint by cg) # # # if isWINDOWS(): # self.__device__="\\\\.\\"+device # else: # self.__device__= device # # self.__device__= device # try: # self.__ser__= serial.Serial(port=device,baudrate=baudrate,timeout=0.10) # self.__isOpen__= True # time.sleep(0.5) # except: # self.__device__="" # raise Rs232Error('cannot open serial device') # def close(self): # try: # self.__ser__.close() # self.__isOpen__=False # except: # raise Rs232Error('cannot close serial device') # self.__device__="" # # def snd(self,buf): # try: # self.__ser__.write(buf) # except: # raise Rs232Error('cannot write to serial device') # # def rcv(self,timeout): # self.__settimeout__(timeout) # try: # c= self.__ser__.read(1) # except: # raise Rs232Error('cannot read from serial device') # return c # # def flushInput(self): # try: # self.__ser__.flushInput() # except: # raise Rs232Error('cannot reset serial device') # # def setBaudrate(self,baudrate): # try: # self.__ser__.baudrate= baudrate # except: # raise Rs232Error('cannot set baudrate') , which may contain function names, class names, or code. Output only the next line.
except TypeError:
Based on the snippet: <|code_start|># # no success with any baud rate, throw exception and exit # if not success: self.__tty__.close() raise PilBoxError("Cannot connect to PIL-Box", errmsg) if self.__idyframe__: self.__sendCmd__(COFI,TMOUTCMD) # # Disconnect PIL-Box # def close(self): try: self.__sendCmd__(TDIS,TMOUTCMD) finally: self.__tty__.close() # # Read byte from PIL-Box # def read(self): try: bytrx= self.__tty__.rcv(TMOUTFRM) except Rs232Error as e: raise PilBoxError("PIL-Box read frame error", e.value) return bytrx # # Send one or two bytes to the PIL-Box # <|code_end|> , predict the immediate next line with the help of imports: from .pilrs232 import Rs232Error, cls_rs232 from .pilcore import * and context (classes, functions, sometimes code) from other files: # Path: pyilper/pilrs232.py # class Rs232Error(Exception): # def __init__(self,value): # self.value=value # def __str__(self): # return repr(self.value) # # class cls_rs232: # # def __init__(self,parent=None): # self.__device__= None # self.__isOpen__= False # self.__timeout__=0 # # # # # Windows needs much time to reconfigure the timeout value of the serial # # device, so alter the device settings only if necessary. Give the device # # some time to settle. # # # def __settimeout__(self,timeout): # if timeout != self.__timeout__: # try: # self.__ser__.timeout= timeout # except: # raise Rs232Error('cannot set timeout value of serial device') # self.__timeout__=timeout # # def isOpen(self): # return self.__isOpen__ # # # def open(self,device,baudrate): # # # # use Windows device naming (hint by cg) # # # if isWINDOWS(): # self.__device__="\\\\.\\"+device # else: # self.__device__= device # # self.__device__= device # try: # self.__ser__= serial.Serial(port=device,baudrate=baudrate,timeout=0.10) # self.__isOpen__= True # time.sleep(0.5) # except: # self.__device__="" # raise Rs232Error('cannot open serial device') # def close(self): # try: # self.__ser__.close() # self.__isOpen__=False # except: # raise Rs232Error('cannot close serial device') # self.__device__="" # # def snd(self,buf): # try: # self.__ser__.write(buf) # except: # raise Rs232Error('cannot write to serial device') # # def rcv(self,timeout): # self.__settimeout__(timeout) # try: # c= self.__ser__.read(1) # except: # raise Rs232Error('cannot read from serial device') # return c # # def flushInput(self): # try: # self.__ser__.flushInput() # except: # raise Rs232Error('cannot reset serial device') # # def setBaudrate(self,baudrate): # try: # self.__ser__.baudrate= baudrate # except: # raise Rs232Error('cannot set baudrate') . Output only the next line.
def write(self,lbyt,hbyt=None):
Here is a snippet: <|code_start|> QtCore.Qt.Key_Semicolon | KEYBOARD_CTRL: [30], # Sterling QtCore.Qt.Key_8 | KEYBOARD_CTRL: [31], # smear QtCore.Qt.Key_9 | KEYBOARD_CTRL: [127], # append QtCore.Qt.Key_0 | KEYBOARD_CTRL: [176], # underscore 0 QtCore.Qt.Key_1 | KEYBOARD_CTRL: [177], # underscore 1 QtCore.Qt.Key_2 | KEYBOARD_CTRL: [178], # underscore 2 QtCore.Qt.Key_3 | KEYBOARD_CTRL: [179], # underscore 3 QtCore.Qt.Key_4 | KEYBOARD_CTRL: [180], # underscore 4 QtCore.Qt.Key_5 | KEYBOARD_CTRL: [181], # underscore 5 QtCore.Qt.Key_6 | KEYBOARD_CTRL: [182], # underscore 6 QtCore.Qt.Key_F1 | KEYBOARD_CTRL : [192], # -- QtCore.Qt.Key_F2 | KEYBOARD_CTRL : [193], # -- QtCore.Qt.Key_F3 | KEYBOARD_CTRL : [194], # -- QtCore.Qt.Key_F4 | KEYBOARD_CTRL : [195], # -- QtCore.Qt.Key_Up | KEYBOARD_CTRL : [196], # send ESC S QtCore.Qt.Key_Down | KEYBOARD_CTRL : [197], # send ESC T QtCore.Qt.Key_Left | KEYBOARD_CTRL : [198], # 32 <- QtCore.Qt.Key_Right| KEYBOARD_CTRL : [199], # 32 -> QtCore.Qt.Key_Insert | KEYBOARD_CTRL : [200], # lit+undersc. QtCore.Qt.Key_F5 | KEYBOARD_CTRL : [201], # last entry QtCore.Qt.Key_F6 | KEYBOARD_CTRL : [203], # reset display QtCore.Qt.Key_Delete | KEYBOARD_CTRL : [202], # Delete to BOL QtCore.Qt.Key_F8 | KEYBOARD_CTRL : [205], # -- QtCore.Qt.Key_F7 | KEYBOARD_CTRL : [201], # lit+undersc. QtCore.Qt.Key_Tab | KEYBOARD_CTRL : [206], # -- # Shift+Control modifier group QtCore.Qt.Key_F1 | KEYBOARD_CTRL | KEYBOARD_SHIFT: [224], # -- QtCore.Qt.Key_F2 | KEYBOARD_CTRL | KEYBOARD_SHIFT: [225], # -- QtCore.Qt.Key_F3 | KEYBOARD_CTRL | KEYBOARD_SHIFT: [226], # -- <|code_end|> . Write the next line using the current file imports: from PyQt5 import QtCore from .pilcore import isMACOS and context from other files: # Path: pyilper/pilcore.py # def isMACOS(): # return platform.system()=="Darwin" , which may include functions, classes, or code. Output only the next line.
QtCore.Qt.Key_F4 | KEYBOARD_CTRL | KEYBOARD_SHIFT: [227], # --
Based on the snippet: <|code_start|># - text editing for the second column (shortcut text) # - combo box editing for the third column (shortcut type) # class ShortcutDelegate(QtWidgets.QItemDelegate): def __init__(self, parent=None): super(ShortcutDelegate, self).__init__(parent) self.items = ["Input only","Input+Endline","Input+2*Cursor left","Input+2*Cursor left+Insert"] # # do not create an editor for the first column, create text editor for # the second column and a QComboBox for the third column # def createEditor(self, parent, option, index): editor= None if index.column()==1: editor= super(ShortcutDelegate,self).createEditor(parent,option,index) if index.column()==2: editor=QtWidgets.QComboBox(parent) editor.addItems(self.items) return(editor) # # set text for editing (second column) or current index (third column) # def setEditorData(self, editor, index): # Gets display text if edit data hasn't been set. text = index.data(QtCore.Qt.EditRole) or index.data(QtCore.Qt.DisplayRole) if index.column()==1: editor.setText(str(text)) if index.column()==2: <|code_end|> , predict the immediate next line with the help of imports: import copy from PyQt5 import QtCore, QtGui, QtWidgets from .userconfig import cls_userconfig, ConfigError and context (classes, functions, sometimes code) from other files: # Path: pyilper/userconfig.py # class cls_userconfig: # # def __init__(self,progname,filename,configversion,instance,production): # # # # determine config file name # # # self.__configfile__,self.__configpath__=buildconfigfilename(progname,filename,configversion,instance,production) # # # # # read configuration, if no configuration exists write default configuration # # # def read(self,default): # if not os.path.isfile(self.__configfile__): # if not os.path.exists(self.__configpath__): # try: # os.makedirs(self.__configpath__) # except OSError as e: # raise ConfigError("Cannot create path for configuration file", e.strerror) # try: # self.write(default) # except OSError as e: # raise ConfigError("Cannot write default configuration file", e.strerror) # return default # f=None # try: # f= open(self.__configfile__,"r") # config= json.load(f) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot decode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot read configuration file", e.strerror) # finally: # if f is not None: # f.close() # # return config # # # # Store configuration, create file if it does not exist # # # def write(self,config): # f=None # try: # f= open(self.__configfile__,"w") # json.dump(config,f,sort_keys=True,indent=3) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot encode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot write to configuration file", e.strerror) # finally: # if f is not None: # f.close() # # class ConfigError(Exception): # def __init__(self,msg,add_msg= None): # self.msg= msg # self.add_msg = add_msg . Output only the next line.
editor.setCurrentIndex(int(text))
Next line prediction: <|code_start|> self.tablemodel.setAll(SHORTCUTCONFIG.default_config()) @staticmethod def getShortcutConfig(): dialog= cls_ShortcutConfigWindow() dialog.resize(650,600) result= dialog.exec_() if result== QtWidgets.QDialog.Accepted: return True else: return False class ShortcutConfigError(Exception): def __init__(self,msg,add_msg= None): self.msg= msg self.add_msg = add_msg class cls_shortcutconfig: # # initialize: set shortcutconfig to the default configuration # def __init__(self): self.__shortcutconfig__= None self.__userconfig__ = None return # # default config # <|code_end|> . Use current file imports: (import copy from PyQt5 import QtCore, QtGui, QtWidgets from .userconfig import cls_userconfig, ConfigError) and context including class names, function names, or small code snippets from other files: # Path: pyilper/userconfig.py # class cls_userconfig: # # def __init__(self,progname,filename,configversion,instance,production): # # # # determine config file name # # # self.__configfile__,self.__configpath__=buildconfigfilename(progname,filename,configversion,instance,production) # # # # # read configuration, if no configuration exists write default configuration # # # def read(self,default): # if not os.path.isfile(self.__configfile__): # if not os.path.exists(self.__configpath__): # try: # os.makedirs(self.__configpath__) # except OSError as e: # raise ConfigError("Cannot create path for configuration file", e.strerror) # try: # self.write(default) # except OSError as e: # raise ConfigError("Cannot write default configuration file", e.strerror) # return default # f=None # try: # f= open(self.__configfile__,"r") # config= json.load(f) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot decode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot read configuration file", e.strerror) # finally: # if f is not None: # f.close() # # return config # # # # Store configuration, create file if it does not exist # # # def write(self,config): # f=None # try: # f= open(self.__configfile__,"w") # json.dump(config,f,sort_keys=True,indent=3) # except json.JSONDecodeError as e: # add_msg="File: "+self.__configfile__+". Error: "+e.msg+" at line: "+str(e.lineno) # raise ConfigError("Cannot encode configuration data",add_msg) # except OSError as e: # raise ConfigError("Cannot write to configuration file", e.strerror) # finally: # if f is not None: # f.close() # # class ConfigError(Exception): # def __init__(self,msg,add_msg= None): # self.msg= msg # self.add_msg = add_msg . Output only the next line.
def default_config(self):
Based on the snippet: <|code_start|># You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # serial device object class -------------------------------------------- # # Changelog # # 07.06.2014 jsi: # - baudrate support # 06.10.2015 jsi: # - class statement syntax update # 16.05.2016 jsi # - use Windows device naming syntax for serial device (hint by cg) # 03.07.2016 jsi # - introduced setBaudrate and flushInput methods # 11.07.2016 jsi # - use platform function from pilcore.py # # class Rs232Error(Exception): def __init__(self,value): self.value=value def __str__(self): return repr(self.value) class cls_rs232: <|code_end|> , predict the immediate next line with the help of imports: import serial,time from .pilcore import isWINDOWS and context (classes, functions, sometimes code) from other files: # Path: pyilper/pilcore.py # def isWINDOWS(): # return platform.system()=="Windows" . Output only the next line.
def __init__(self,parent=None):
Given the following code snippet before the placeholder: <|code_start|>sys.stdout = codecs.getwriter('utf-8')(sys.stdout) headers = u""" Geography Climate Economy Transport Education <|code_end|> , predict the next line using imports from the current file: import codecs import sys import orm from wikihead import headings and context including class names, function names, and sometimes code from other files: # Path: wikihead.py # def headings(): # xml = requests.get("http://en.wikipedia.org/wiki/Special:Export/List_of_sovereign_states").content # root = lxml.etree.fromstring(xml) # text = root.xpath("//*[local-name()='text']")[0].text # # wrapped_text = u"".join([u"<html>", text, u"</html>"]) # w_root = lxml.html.fromstring(wrapped_text) # countries = w_root.xpath("//span/@id") # # builder = {} # for country in countries: # html = requests.get("http://en.wikipedia.org/wiki/%s" % country).content # root = lxml.html.fromstring(html) # cats = {2: root.xpath("//div[@id='mw-content-text']/h2/span/@id"), # 3: root.xpath("//div[@id='mw-content-text']/h3/span/@id")} # if cats == {2: [], 3: []}: # print repr(country) # raise RuntimeError() # builder[country] = cats # return builder . Output only the next line.
Demographics
Based on the snippet: <|code_start|> indicator_list = """ SP.POP.TOTL SP.POP.DPND.OL SP.POP.DPND.YG SH.DTH.IMRT SM.POP.TOTL.ZS AG.LND.TOTL.K2 SP.POP.GROW EN.POP.DNST EN.URB.MCTY NY.GNP.MKTP.CD SI.POV.DDAY SP.DYN.AMRT.FE SP.DYN.AMRT.MA LP.LPI.OVRL.XQ IS.ROD.TOTL.KM IS.RRS.TOTL.KM NY.GNP.MKTP.PP.CD <|code_end|> , predict the immediate next line with the help of imports: import xypath import messytables import orm import re import time import dl from hamcrest import equal_to, is_in from orm import session, Value, DataSet, Indicator and context (classes, functions, sometimes code) from other files: # Path: orm.py # def now(): # def set_sqlite_pragma(dbapi_connection, connection_record): # def is_blank(self): # def save(self): # def save(self): # def save(self): # def counter(): # def exithandler(): # class Value(Base): # class DataSet(Base): # class Indicator(Base): . Output only the next line.
NY.GDP.PCAP.PP.CD
Next line prediction: <|code_start|> indicator_list = """ SP.POP.TOTL SP.POP.DPND.OL SP.POP.DPND.YG SH.DTH.IMRT SM.POP.TOTL.ZS AG.LND.TOTL.K2 SP.POP.GROW EN.POP.DNST EN.URB.MCTY NY.GNP.MKTP.CD SI.POV.DDAY SP.DYN.AMRT.FE SP.DYN.AMRT.MA LP.LPI.OVRL.XQ IS.ROD.TOTL.KM IS.RRS.TOTL.KM <|code_end|> . Use current file imports: (import xypath import messytables import orm import re import time import dl from hamcrest import equal_to, is_in from orm import session, Value, DataSet, Indicator) and context including class names, function names, or small code snippets from other files: # Path: orm.py # def now(): # def set_sqlite_pragma(dbapi_connection, connection_record): # def is_blank(self): # def save(self): # def save(self): # def save(self): # def counter(): # def exithandler(): # class Value(Base): # class DataSet(Base): # class Indicator(Base): . Output only the next line.
NY.GNP.MKTP.PP.CD
Continue the code snippet: <|code_start|> indicator_list = """ SP.POP.TOTL SP.POP.DPND.OL SP.POP.DPND.YG SH.DTH.IMRT SM.POP.TOTL.ZS AG.LND.TOTL.K2 SP.POP.GROW <|code_end|> . Use current file imports: import xypath import messytables import orm import re import time import dl from hamcrest import equal_to, is_in from orm import session, Value, DataSet, Indicator and context (classes, functions, or code) from other files: # Path: orm.py # def now(): # def set_sqlite_pragma(dbapi_connection, connection_record): # def is_blank(self): # def save(self): # def save(self): # def save(self): # def counter(): # def exithandler(): # class Value(Base): # class DataSet(Base): # class Indicator(Base): . Output only the next line.
EN.POP.DNST
Given the code snippet: <|code_start|> __tablename__ = "dataset" dsID = Column(String, primary_key=True) last_updated = Column(String) last_scraped = Column(String) name = Column(String) def save(self): session.merge(self) class Indicator(Base): __tablename__ = "indicator" indID = Column(String, primary_key=True) name = Column(String) units = Column(String) def save(self): self.indID = chd_id(self.indID) session.merge(self) def counter(): counts = [session.query(DataSet).count(), session.query(Indicator).count(), session.query(Value).count()] print "COUNTER: {} datasets, {} indicators, {} values".format(*counts) Base.metadata.create_all(engine) counter() <|code_end|> , generate the next line using the imports in this file: from sqlalchemy import Column, String, Boolean from sqlalchemy import ForeignKey, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.engine import Engine from sqlalchemy import event from canon import canonicalise, canon_number, canon_period, chd_id import datetime import atexit and context (functions, classes, or occasionally code) from other files: # Path: canon.py # class Memoize: # def __init__(self, f): # def __call__(self, *args): # def getpair(text): # def chd_id_nomemo(text): # def country_id_nomemo(rawname): # def canon_number(f): # def canon_period(p): # def updatedb(): # def _ignore(): . Output only the next line.
@atexit.register
Next line prediction: <|code_start|> def now(): return datetime.datetime.now().isoformat() @event.listens_for(Engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() echo = False <|code_end|> . Use current file imports: (from sqlalchemy import Column, String, Boolean from sqlalchemy import ForeignKey, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.engine import Engine from sqlalchemy import event from canon import canonicalise, canon_number, canon_period, chd_id import datetime import atexit) and context including class names, function names, or small code snippets from other files: # Path: canon.py # class Memoize: # def __init__(self, f): # def __call__(self, *args): # def getpair(text): # def chd_id_nomemo(text): # def country_id_nomemo(rawname): # def canon_number(f): # def canon_period(p): # def updatedb(): # def _ignore(): . Output only the next line.
engine = create_engine("sqlite:///ocha.db", echo=echo)
Given the following code snippet before the placeholder: <|code_start|> self.value = canon_number(self.value) if self.value is None: return assert not self.is_blank() try: session.merge(self) except: print self.__dict__ raise class DataSet(Base): __tablename__ = "dataset" dsID = Column(String, primary_key=True) last_updated = Column(String) last_scraped = Column(String) name = Column(String) def save(self): session.merge(self) class Indicator(Base): __tablename__ = "indicator" indID = Column(String, primary_key=True) name = Column(String) units = Column(String) def save(self): self.indID = chd_id(self.indID) <|code_end|> , predict the next line using imports from the current file: from sqlalchemy import Column, String, Boolean from sqlalchemy import ForeignKey, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.engine import Engine from sqlalchemy import event from canon import canonicalise, canon_number, canon_period, chd_id import datetime import atexit and context including class names, function names, and sometimes code from other files: # Path: canon.py # class Memoize: # def __init__(self, f): # def __call__(self, *args): # def getpair(text): # def chd_id_nomemo(text): # def country_id_nomemo(rawname): # def canon_number(f): # def canon_period(p): # def updatedb(): # def _ignore(): . Output only the next line.
session.merge(self)
Given snippet: <|code_start|>engine = create_engine("sqlite:///ocha.db", echo=echo) Session = sessionmaker(bind=engine) session = Session() Base = declarative_base() class Value(Base): __tablename__ = "value" dsID = Column(String, ForeignKey('dataset.dsID'), primary_key=True) region = Column(String, primary_key=True) indID = Column(String, ForeignKey('indicator.indID'), primary_key=True) period = Column(String, primary_key=True) value = Column(String, nullable=False) is_number = Column(Boolean) source = Column(String) def is_blank(self): if type(self.value) in [float, int]: return False return self.value is None or self.value.strip() == '' def save(self): self.region = canonicalise(self.region) self.period = canon_period(self.period) self.indID = chd_id(self.indID) if self.region is None: return if self.period is None or self.period == '': self.period = now()[:10] # YYYY-MM-DD self.is_number=bool(self.is_number) <|code_end|> , continue by predicting the next line. Consider current file imports: from sqlalchemy import Column, String, Boolean from sqlalchemy import ForeignKey, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.engine import Engine from sqlalchemy import event from canon import canonicalise, canon_number, canon_period, chd_id import datetime import atexit and context: # Path: canon.py # class Memoize: # def __init__(self, f): # def __call__(self, *args): # def getpair(text): # def chd_id_nomemo(text): # def country_id_nomemo(rawname): # def canon_number(f): # def canon_period(p): # def updatedb(): # def _ignore(): which might include code, classes, or functions. Output only the next line.
if self.is_number:
Given the following code snippet before the placeholder: <|code_start|> rawformdata = '''__Click:85256981006B94CD.d6a31b1f4f85ddbb8525716a0059e321/$Body/0.44EA %%Surrogate_col3:1 %%Surrogate_col4:1 col4:Fr %%Surrogate_col6:1 col6:Sp %%Surrogate_col5:1 col5:Ru %%Surrogate_col2:1 col2:Ch %%Surrogate_col1:1 col1:Ar Query: FTSearch: %%Surrogate_Sub:1 Sub:country name En: Ea: Fr: Fa: Sp: Sa: Ru: Ra: Ch: Ca: <|code_end|> , predict the next line using imports from the current file: import datetime import lxml.html import requests import xypath import StringIO import messytables import orm from orm import session, Value, DataSet, Indicator and context including class names, function names, and sometimes code from other files: # Path: orm.py # def now(): # def set_sqlite_pragma(dbapi_connection, connection_record): # def is_blank(self): # def save(self): # def save(self): # def save(self): # def counter(): # def exithandler(): # class Value(Base): # class DataSet(Base): # class Indicator(Base): . Output only the next line.
Ar:
Given snippet: <|code_start|>En: Ea: Fr: Fa: Sp: Sa: Ru: Ra: Ch: Ca: Ar: %%Surrogate_MaxResults:1 MaxResults:2500 %%Surrogate_SearchWv:1 SearchWv:1 %%Surrogate_SearchFuzzy:1 %%Surrogate_Sort:1 Sort:1''' indicators = {"Date of Entry into UN": xypath.RIGHT, "ISO Country alpha-3-code": xypath.RIGHT, "ISO Country alpha-2-code": xypath.RIGHT, "ISO Currency Code": xypath.RIGHT, "Short Name": xypath.RIGHT, "Formal Name": xypath.RIGHT, "Capital City": xypath.RIGHT, "Languages": xypath.RIGHT, "Currency Abbr.": xypath.DOWN} dataset_data = {'dsID': 'unterm', <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import lxml.html import requests import xypath import StringIO import messytables import orm from orm import session, Value, DataSet, Indicator and context: # Path: orm.py # def now(): # def set_sqlite_pragma(dbapi_connection, connection_record): # def is_blank(self): # def save(self): # def save(self): # def save(self): # def counter(): # def exithandler(): # class Value(Base): # class DataSet(Base): # class Indicator(Base): which might include code, classes, or functions. Output only the next line.
'last_updated': "",
Given the following code snippet before the placeholder: <|code_start|> rawformdata = '''__Click:85256981006B94CD.d6a31b1f4f85ddbb8525716a0059e321/$Body/0.44EA %%Surrogate_col3:1 %%Surrogate_col4:1 col4:Fr %%Surrogate_col6:1 col6:Sp %%Surrogate_col5:1 col5:Ru %%Surrogate_col2:1 col2:Ch %%Surrogate_col1:1 col1:Ar Query: FTSearch: %%Surrogate_Sub:1 Sub:country name En: Ea: Fr: Fa: Sp: Sa: Ru: Ra: Ch: Ca: <|code_end|> , predict the next line using imports from the current file: import datetime import lxml.html import requests import xypath import StringIO import messytables import orm from orm import session, Value, DataSet, Indicator and context including class names, function names, and sometimes code from other files: # Path: orm.py # def now(): # def set_sqlite_pragma(dbapi_connection, connection_record): # def is_blank(self): # def save(self): # def save(self): # def save(self): # def counter(): # def exithandler(): # class Value(Base): # class DataSet(Base): # class Indicator(Base): . Output only the next line.
Ar:
Predict the next line after this snippet: <|code_start|> rawformdata = '''__Click:85256981006B94CD.d6a31b1f4f85ddbb8525716a0059e321/$Body/0.44EA %%Surrogate_col3:1 %%Surrogate_col4:1 col4:Fr %%Surrogate_col6:1 col6:Sp %%Surrogate_col5:1 col5:Ru %%Surrogate_col2:1 col2:Ch %%Surrogate_col1:1 col1:Ar Query: FTSearch: %%Surrogate_Sub:1 Sub:country name En: <|code_end|> using the current file's imports: import datetime import lxml.html import requests import xypath import StringIO import messytables import orm from orm import session, Value, DataSet, Indicator and any relevant context from other files: # Path: orm.py # def now(): # def set_sqlite_pragma(dbapi_connection, connection_record): # def is_blank(self): # def save(self): # def save(self): # def save(self): # def counter(): # def exithandler(): # class Value(Base): # class DataSet(Base): # class Indicator(Base): . Output only the next line.
Ea:
Next line prediction: <|code_start|> urlpatterns = [ url('^create/$', views.Create.as_view(), name='create'), url('^c:(?P<slug>[-\w]+)/$', views.Detail.as_view(), name='detail'), url('^$', views.List.as_view(), name='list'), <|code_end|> . Use current file imports: (from django.conf.urls import url from ..views import collections as views) and context including class names, function names, or small code snippets from other files: # Path: dj_bookmarks/bookmarks/views/collections.py # class List(LoginRequiredMixin, generic.ListView): # class Detail(LoginRequiredMixin, generic.DetailView): # class Create(LoginRequiredMixin, generic.CreateView): # def get_queryset(self): # def get_queryset(self): # def form_valid(self, form): . Output only the next line.
]
Based on the snippet: <|code_start|> urlpatterns = [ url('^create/$', views.Create.as_view(), name='create'), url('^trash/$', views.Trash.as_view(), name='trash'), url('^search/$', views.Search.as_view(), name='search'), url('^update/(?P<pk>\d+)/$', views.Update.as_view(), name='update'), url('^delete/(?P<pk>\d+)/$', views.Delete.as_view(), name='delete'), url('^undelete/(?P<pk>\d+)/$', views.Undelete.as_view(), name='undelete'), url( '^add-to-collection/$', views.AddBookmarkToCollection.as_view(), name='add_to_collection' ), url('^t:(?P<tag>[-\w]+)/$', views.List.as_view(), name='tag_search'), url('^$', views.List.as_view(), name='list'), <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import url from ..views import bookmarks as views and context (classes, functions, sometimes code) from other files: # Path: dj_bookmarks/bookmarks/views/bookmarks.py # class List(LoginRequiredMixin, generic.ListView): # class Create(LoginRequiredMixin, generic.CreateView): # class Update(LoginRequiredMixin, generic.UpdateView): # class Delete(LoginRequiredMixin, generic.UpdateView): # class Trash(LoginRequiredMixin, generic.ListView): # class Undelete(LoginRequiredMixin, RedirectView): # class Search(LoginRequiredMixin, generic.ListView): # class AddBookmarkToCollection(LoginRequiredMixin, generic.View): # def get_queryset(self): # def form_valid(self, form): # def get_queryset(self): # def get_queryset(self): # def get_context_data(self, **kwargs): # def form_valid(self, form): # def get_context_data(self, **kwargs): # def get_queryset(self): # def get_object(self): # def get(self, request, *args, **kwargs): # def get_queryset(self): # def get_bookmark(self, request): # def get_collection(self, request): # def get_redirect_url(self, *args, **kwargs): # def get(self, request, *args, **kwargs): . Output only the next line.
]
Predict the next line after this snippet: <|code_start|> def get(self, section, option, option_type=str): """Try to get option value in section of configuration. Raise HPCStatsConfigurationException if not found. """ try: if option_type is bool: return super(HPCStatsConf, self).getboolean(section, option) if option_type is int: return super(HPCStatsConf, self).getint(section, option) else: return super(HPCStatsConf, self).get(section, option) except ConfigParser.NoSectionError: raise HPCStatsConfigurationException( \ "section %s not found" % (section)) except ConfigParser.NoOptionError: raise HPCStatsConfigurationException( \ "option %s not found in section %s" % (option, section)) def get_default(self, section, option, default, option_type=str): """Try to get option value in section of configuration. Return default if not found. """ try: return self.get(section, option, option_type) except HPCStatsConfigurationException: return default def get_list(self, section, option): """Returns a comma separated multi-values parameter formatted into a list. If the parameter is not set, it returns an empty list.""" <|code_end|> using the current file's imports: import ConfigParser import os import sys from HPCStats.Exceptions import HPCStatsConfigurationException and any relevant context from other files: # Path: HPCStats/Exceptions.py # class HPCStatsConfigurationException(HPCStatsException): # # """Class for configuration file exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsConfigurationException, self).__init__(msg) . Output only the next line.
items = self.get_default(section, option, '')
Based on the snippet: <|code_start|> """ logger = logging.getLogger(__name__) class Cluster(object): """Model class for Cluster table""" def __init__(self, name, cluster_id=None): self.cluster_id = cluster_id self.name = name def __str__(self): return self.name def __eq__(self, other): return self.name == other.name def find(self, db): """Search the Cluster in the database based on its name. If exactly one cluster matches in database, set cluster_id attribute properly and returns its value. If more than one cluster matches, raises HPCStatsDBIntegrityError. If no cluster is found, returns None. """ req = """ SELECT cluster_id <|code_end|> , predict the immediate next line with the help of imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (classes, functions, sometimes code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
FROM Cluster
Given the code snippet: <|code_start|> if self.cluster_id is None: raise HPCStatsRuntimeError( "could not search for data with cluster %s since not " \ "found in database" \ % (str(self))) req = """ SELECT SUM(node_nbCpu) FROM Node WHERE cluster_id = %s """ params = ( self.cluster_id, ) #print db.cur.mogrify(req, params) db.execute(req, params) return db.cur.fetchone()[0] def get_min_datetime(self, db): """Returns the start datetime of the oldest started and unfinished job on the cluster. """ if self.cluster_id is None: raise HPCStatsRuntimeError( "could not search for data with cluster %s since not " \ "found in database" \ % (str(self))) req = """ SELECT MIN(job_start) <|code_end|> , generate the next line using the imports in this file: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (functions, classes, or occasionally code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
FROM Job
Predict the next line for this snippet: <|code_start|># modify it under the terms of the GNU General Public License, # version 2, as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with HPCStats. If not, see # <http://www.gnu.org/licenses/>. # # On Calibre systems, the complete text of the GNU General # Public License can be found in `/usr/share/common-licenses/GPL'. CONFIG = { 'sectiona': { 'option_str': 'test_value', 'option_int': 123, 'option_bool': False, 'option_list': 'john,doe', }, } module = "HPCStats.Conf.HPCStatsConf" class TestsHPCStatsConf(HPCStatsTestCase): <|code_end|> with the help of current file imports: import copy from HPCStats.Conf.HPCStatsConf import HPCStatsConf from HPCStats.Tests.Mocks.MockConfigParser import MockConfigParser from HPCStats.Tests.Utils import HPCStatsTestCase, loadtestcase and context from other files: # Path: HPCStats/Conf/HPCStatsConf.py # class HPCStatsConf(ConfigParser.ConfigParser, object): # # def __init__(self, filename, cluster): # # super(HPCStatsConf, self).__init__() # # self.cluster = cluster # self.filename = filename # # def read(self): # """Check if configuration file exists and then read it. Raises # HPCStatsConfigurationException if configuration file does not exist. # """ # # if not os.path.exists(self.filename): # raise HPCStatsConfigurationException( # "file %s does not exist" % (self.filename)) # # super(HPCStatsConf, self).read(self.filename) # # def get(self, section, option, option_type=str): # """Try to get option value in section of configuration. Raise # HPCStatsConfigurationException if not found. # """ # try: # if option_type is bool: # return super(HPCStatsConf, self).getboolean(section, option) # if option_type is int: # return super(HPCStatsConf, self).getint(section, option) # else: # return super(HPCStatsConf, self).get(section, option) # except ConfigParser.NoSectionError: # raise HPCStatsConfigurationException( \ # "section %s not found" % (section)) # except ConfigParser.NoOptionError: # raise HPCStatsConfigurationException( \ # "option %s not found in section %s" % (option, section)) # # def get_default(self, section, option, default, option_type=str): # """Try to get option value in section of configuration. Return default # if not found. # """ # try: # return self.get(section, option, option_type) # except HPCStatsConfigurationException: # return default # # def get_list(self, section, option): # """Returns a comma separated multi-values parameter formatted into a # list. If the parameter is not set, it returns an empty list.""" # items = self.get_default(section, option, '') # return [ item.strip() # for item in items.split(',') # if item.strip() != '' ] # # def get_clusters_list(self): # """Returns the list of clusters in configuration file. If any problem # is encountered, HPCStatsConfigurationException is raised. # """ # try: # cluster_list_str = self.get("clusters","clusters") # except ConfigParser.NoSectionError: # raise HPCStatsConfigurationException( # "section clusters is not present in configuration file") # except ConfigParser.NoOptionError: # raise HPCStatsConfigurationException( # "option clusters is not present in configuration file") # return cluster_list_str.split(",") # # def check_cluster(self): # """Check for presence of cluster in configuration file. If any problem # is encountered, HPCStatsConfigurationException is raised. # """ # # clusters = self.get_clusters_list() # if self.cluster not in clusters: # raise HPCStatsConfigurationException( # "cluster %s is not present in configuration file" \ # % self.cluster) # # Path: HPCStats/Tests/Mocks/MockConfigParser.py # class MockConfigParser(): # # def __init__(self): # self.conf = None # # def read(self, filename): # pass # # def get(self, section, option): # if section not in self.conf.keys(): # raise NoSectionError(section) # if option not in self.conf[section].keys(): # raise NoOptionError(section, option) # return self.conf[section][option] # # def getint(self, section, option): # value = self.get(section, option) # if type(value) is not int: # raise ValueError( \ # "invalid literal for int() with base 10: '%s'" \ # % (value)) # return value # # def getboolean(self, section, option): # value = self.get(section, option) # if type(value) is not bool: # raise ValueError("invalid boolean: '%s'" % (value)) # return value # # def sections(self): # # return self.conf.keys() # # def options(self, section): # # return self.conf[section].keys() # # Path: HPCStats/Tests/Utils.py # class HPCStatsTestCase(unittest.TestCase): # # def __init__(self, methodName="runTest"): # # super(HPCStatsTestCase,self).__init__(methodName) # # def loadtestcase(testcase): # suite = unittest.TestLoader().loadTestsFromTestCase(testcase) # unittest.TextTestRunner(verbosity=2).run(suite) , which may contain function names, class names, or code. Output only the next line.
def setUp(self):
Given the following code snippet before the placeholder: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with HPCStats. If not, see # <http://www.gnu.org/licenses/>. # # On Calibre systems, the complete text of the GNU General # Public License can be found in `/usr/share/common-licenses/GPL'. CONFIG = { 'sectiona': { 'option_str': 'test_value', 'option_int': 123, 'option_bool': False, 'option_list': 'john,doe', }, } module = "HPCStats.Conf.HPCStatsConf" class TestsHPCStatsConf(HPCStatsTestCase): def setUp(self): self.filename = 'fake' self.cluster = 'test_cluster' HPCStatsConf.__bases__ = (MockConfigParser, object) self.conf = HPCStatsConf(self.filename, self.cluster) <|code_end|> , predict the next line using imports from the current file: import copy from HPCStats.Conf.HPCStatsConf import HPCStatsConf from HPCStats.Tests.Mocks.MockConfigParser import MockConfigParser from HPCStats.Tests.Utils import HPCStatsTestCase, loadtestcase and context including class names, function names, and sometimes code from other files: # Path: HPCStats/Conf/HPCStatsConf.py # class HPCStatsConf(ConfigParser.ConfigParser, object): # # def __init__(self, filename, cluster): # # super(HPCStatsConf, self).__init__() # # self.cluster = cluster # self.filename = filename # # def read(self): # """Check if configuration file exists and then read it. Raises # HPCStatsConfigurationException if configuration file does not exist. # """ # # if not os.path.exists(self.filename): # raise HPCStatsConfigurationException( # "file %s does not exist" % (self.filename)) # # super(HPCStatsConf, self).read(self.filename) # # def get(self, section, option, option_type=str): # """Try to get option value in section of configuration. Raise # HPCStatsConfigurationException if not found. # """ # try: # if option_type is bool: # return super(HPCStatsConf, self).getboolean(section, option) # if option_type is int: # return super(HPCStatsConf, self).getint(section, option) # else: # return super(HPCStatsConf, self).get(section, option) # except ConfigParser.NoSectionError: # raise HPCStatsConfigurationException( \ # "section %s not found" % (section)) # except ConfigParser.NoOptionError: # raise HPCStatsConfigurationException( \ # "option %s not found in section %s" % (option, section)) # # def get_default(self, section, option, default, option_type=str): # """Try to get option value in section of configuration. Return default # if not found. # """ # try: # return self.get(section, option, option_type) # except HPCStatsConfigurationException: # return default # # def get_list(self, section, option): # """Returns a comma separated multi-values parameter formatted into a # list. If the parameter is not set, it returns an empty list.""" # items = self.get_default(section, option, '') # return [ item.strip() # for item in items.split(',') # if item.strip() != '' ] # # def get_clusters_list(self): # """Returns the list of clusters in configuration file. If any problem # is encountered, HPCStatsConfigurationException is raised. # """ # try: # cluster_list_str = self.get("clusters","clusters") # except ConfigParser.NoSectionError: # raise HPCStatsConfigurationException( # "section clusters is not present in configuration file") # except ConfigParser.NoOptionError: # raise HPCStatsConfigurationException( # "option clusters is not present in configuration file") # return cluster_list_str.split(",") # # def check_cluster(self): # """Check for presence of cluster in configuration file. If any problem # is encountered, HPCStatsConfigurationException is raised. # """ # # clusters = self.get_clusters_list() # if self.cluster not in clusters: # raise HPCStatsConfigurationException( # "cluster %s is not present in configuration file" \ # % self.cluster) # # Path: HPCStats/Tests/Mocks/MockConfigParser.py # class MockConfigParser(): # # def __init__(self): # self.conf = None # # def read(self, filename): # pass # # def get(self, section, option): # if section not in self.conf.keys(): # raise NoSectionError(section) # if option not in self.conf[section].keys(): # raise NoOptionError(section, option) # return self.conf[section][option] # # def getint(self, section, option): # value = self.get(section, option) # if type(value) is not int: # raise ValueError( \ # "invalid literal for int() with base 10: '%s'" \ # % (value)) # return value # # def getboolean(self, section, option): # value = self.get(section, option) # if type(value) is not bool: # raise ValueError("invalid boolean: '%s'" % (value)) # return value # # def sections(self): # # return self.conf.keys() # # def options(self, section): # # return self.conf[section].keys() # # Path: HPCStats/Tests/Utils.py # class HPCStatsTestCase(unittest.TestCase): # # def __init__(self, methodName="runTest"): # # super(HPCStatsTestCase,self).__init__(methodName) # # def loadtestcase(testcase): # suite = unittest.TestLoader().loadTestsFromTestCase(testcase) # unittest.TextTestRunner(verbosity=2).run(suite) . Output only the next line.
self.conf.conf = CONFIG.copy()
Predict the next line after this snippet: <|code_start|># 1, Avenue du General de Gaulle # 92140 Clamart # # Authors: CCN - HPC <dsp-cspit-ccn-hpc@edf.fr> # # This file is part of HPCStats. # # HPCStats is free software: you can redistribute in and/or # modify it under the terms of the GNU General Public License, # version 2, as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with HPCStats. If not, see # <http://www.gnu.org/licenses/>. # # On Calibre systems, the complete text of the GNU General # Public License can be found in `/usr/share/common-licenses/GPL'. CONFIG = { 'sectiona': { 'option_str': 'test_value', 'option_int': 123, 'option_bool': False, <|code_end|> using the current file's imports: import copy from HPCStats.Conf.HPCStatsConf import HPCStatsConf from HPCStats.Tests.Mocks.MockConfigParser import MockConfigParser from HPCStats.Tests.Utils import HPCStatsTestCase, loadtestcase and any relevant context from other files: # Path: HPCStats/Conf/HPCStatsConf.py # class HPCStatsConf(ConfigParser.ConfigParser, object): # # def __init__(self, filename, cluster): # # super(HPCStatsConf, self).__init__() # # self.cluster = cluster # self.filename = filename # # def read(self): # """Check if configuration file exists and then read it. Raises # HPCStatsConfigurationException if configuration file does not exist. # """ # # if not os.path.exists(self.filename): # raise HPCStatsConfigurationException( # "file %s does not exist" % (self.filename)) # # super(HPCStatsConf, self).read(self.filename) # # def get(self, section, option, option_type=str): # """Try to get option value in section of configuration. Raise # HPCStatsConfigurationException if not found. # """ # try: # if option_type is bool: # return super(HPCStatsConf, self).getboolean(section, option) # if option_type is int: # return super(HPCStatsConf, self).getint(section, option) # else: # return super(HPCStatsConf, self).get(section, option) # except ConfigParser.NoSectionError: # raise HPCStatsConfigurationException( \ # "section %s not found" % (section)) # except ConfigParser.NoOptionError: # raise HPCStatsConfigurationException( \ # "option %s not found in section %s" % (option, section)) # # def get_default(self, section, option, default, option_type=str): # """Try to get option value in section of configuration. Return default # if not found. # """ # try: # return self.get(section, option, option_type) # except HPCStatsConfigurationException: # return default # # def get_list(self, section, option): # """Returns a comma separated multi-values parameter formatted into a # list. If the parameter is not set, it returns an empty list.""" # items = self.get_default(section, option, '') # return [ item.strip() # for item in items.split(',') # if item.strip() != '' ] # # def get_clusters_list(self): # """Returns the list of clusters in configuration file. If any problem # is encountered, HPCStatsConfigurationException is raised. # """ # try: # cluster_list_str = self.get("clusters","clusters") # except ConfigParser.NoSectionError: # raise HPCStatsConfigurationException( # "section clusters is not present in configuration file") # except ConfigParser.NoOptionError: # raise HPCStatsConfigurationException( # "option clusters is not present in configuration file") # return cluster_list_str.split(",") # # def check_cluster(self): # """Check for presence of cluster in configuration file. If any problem # is encountered, HPCStatsConfigurationException is raised. # """ # # clusters = self.get_clusters_list() # if self.cluster not in clusters: # raise HPCStatsConfigurationException( # "cluster %s is not present in configuration file" \ # % self.cluster) # # Path: HPCStats/Tests/Mocks/MockConfigParser.py # class MockConfigParser(): # # def __init__(self): # self.conf = None # # def read(self, filename): # pass # # def get(self, section, option): # if section not in self.conf.keys(): # raise NoSectionError(section) # if option not in self.conf[section].keys(): # raise NoOptionError(section, option) # return self.conf[section][option] # # def getint(self, section, option): # value = self.get(section, option) # if type(value) is not int: # raise ValueError( \ # "invalid literal for int() with base 10: '%s'" \ # % (value)) # return value # # def getboolean(self, section, option): # value = self.get(section, option) # if type(value) is not bool: # raise ValueError("invalid boolean: '%s'" % (value)) # return value # # def sections(self): # # return self.conf.keys() # # def options(self, section): # # return self.conf[section].keys() # # Path: HPCStats/Tests/Utils.py # class HPCStatsTestCase(unittest.TestCase): # # def __init__(self, methodName="runTest"): # # super(HPCStatsTestCase,self).__init__(methodName) # # def loadtestcase(testcase): # suite = unittest.TestLoader().loadTestsFromTestCase(testcase) # unittest.TextTestRunner(verbosity=2).run(suite) . Output only the next line.
'option_list': 'john,doe',
Given the code snippet: <|code_start|> % (str(self))) req = """ INSERT INTO Userhpc ( userhpc_login, userhpc_firstname, userhpc_name, userhpc_department) VALUES ( %s, %s, %s, %s) RETURNING userhpc_id """ params = ( self.login, self.firstname, self.lastname, self.department ) #print db.cur.mogrify(req, params) db.execute(req, params) self.user_id = db.cur.fetchone()[0] def update(self, db): """Update User firstname, lastname and department fields in database. Raises HPCStatsRuntimeError is user_id is None. """ if self.user_id is None: raise HPCStatsRuntimeError( "could not update user %s since not found in database" \ % (str(self))) req = """ <|code_end|> , generate the next line using the imports in this file: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (functions, classes, or occasionally code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
UPDATE Userhpc
Using the snippet: <|code_start|> return None elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several user_id found in DB for user %s" \ % (str(self))) else: self.user_id = db.cur.fetchone()[0] logger.debug("user %s found in DB with id %d", str(self), self.user_id ) return self.user_id def save(self, db): """Insert User in database. You must make sure that the User does not already exist in database yet (typically using User.find() method else there is a risk of future integrity errors because of duplicated users. If user_id attribute is set, it raises HPCStatsRuntimeError. """ if self.user_id is not None: raise HPCStatsRuntimeError( "could not insert user %s since already existing in "\ "database" \ % (str(self))) req = """ INSERT INTO Userhpc ( userhpc_login, userhpc_firstname, userhpc_name, <|code_end|> , determine the next line of code. You have imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (class names, function names, or code) available: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
userhpc_department)
Given snippet: <|code_start|> creation, deletion FROM users WHERE uid = %s AND cluster = %s; """ data = ( uid, cluster_name ) cur = self._db.cur #print cur.mogrify(req, data) cur.execute(req, data) nb_rows = cur.rowcount if nb_rows == 1: row = cur.fetchone() return User( name = row[0], login = row[1], cluster_name = cluster_name, department = row[2], uid = uid, gid = row[3], creation_date = row[4], deletion_date = row[5] ) elif nb_rows == 0: raise UserWarning, ("no user found with uid %d \ on cluster %s" % \ ( uid, cluster_name ) ) <|code_end|> , continue by predicting the next line. Consider current file imports: from HPCStats.Model.User import User and context: # Path: HPCStats/Model/User.py # class User(object): # # """Model class for the Userhpc table.""" # # def __init__(self, login, firstname, lastname, department, user_id=None): # # self.user_id = user_id # self.login = login # self.lastname = lastname # self.firstname = firstname # self.department = department # # def __str__(self): # # return str(self.firstname) + " " + str(self.lastname) \ # + " [" + str(self.department) + "] " + str(self.login) # # def __eq__(self, other): # # return self.login == other.login # # def find(self, db): # """Search the User in the database based on its login. If exactly # one user matches in database, set user_id attribute properly # and returns its value. If more than one user matches, raises # HPCStatsDBIntegrityError. If no user is found, returns None. # """ # # req = """ # SELECT userhpc_id # FROM Userhpc # WHERE userhpc_login = %s # """ # params = ( self.login, ) # db.execute(req, params) # nb_rows = db.cur.rowcount # if nb_rows == 0: # logger.debug("user %s not found in DB", str(self)) # return None # elif nb_rows > 1: # raise HPCStatsDBIntegrityError( # "several user_id found in DB for user %s" \ # % (str(self))) # else: # self.user_id = db.cur.fetchone()[0] # logger.debug("user %s found in DB with id %d", # str(self), # self.user_id ) # return self.user_id # # def save(self, db): # """Insert User in database. You must make sure that the User does # not already exist in database yet (typically using User.find() # method else there is a risk of future integrity errors because of # duplicated users. If user_id attribute is set, it raises # HPCStatsRuntimeError. # """ # # if self.user_id is not None: # raise HPCStatsRuntimeError( # "could not insert user %s since already existing in "\ # "database" \ # % (str(self))) # # req = """ # INSERT INTO Userhpc ( userhpc_login, # userhpc_firstname, # userhpc_name, # userhpc_department) # VALUES ( %s, %s, %s, %s) # RETURNING userhpc_id # """ # params = ( self.login, # self.firstname, # self.lastname, # self.department ) # # #print db.cur.mogrify(req, params) # db.execute(req, params) # self.user_id = db.cur.fetchone()[0] # # def update(self, db): # """Update User firstname, lastname and department fields in database. # Raises HPCStatsRuntimeError is user_id is None. # """ # # if self.user_id is None: # raise HPCStatsRuntimeError( # "could not update user %s since not found in database" \ # % (str(self))) # # req = """ # UPDATE Userhpc # SET userhpc_firstname = %s, # userhpc_name = %s, # userhpc_department = %s # WHERE userhpc_id = %s # """ # params = ( self.firstname, # self.lastname, # self.department, # self.user_id ) # # #print db.cur.mogrify(req, params) # db.execute(req, params) which might include code, classes, or functions. Output only the next line.
else:
Next line prediction: <|code_start|># HPCStats is free software: you can redistribute in and/or # modify it under the terms of the GNU General Public License, # version 2, as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with HPCStats. If not, see # <http://www.gnu.org/licenses/>. # # On Calibre systems, the complete text of the GNU General # Public License can be found in `/usr/share/common-licenses/GPL'. logger = logging.getLogger(__name__) class HPCStatsErrorMgr(object): def __init__(self, conf): ignored_errors_s = conf.get_default('constraints', 'ignored_errors', '') self.ignored_errors = set() for error_s in ignored_errors_s.split(','): error_s = error_s.strip() if len(error_s) and Errors.is_valid(error_s): error = Errors.to_error(error_s) if error not in self.ignored_errors: <|code_end|> . Use current file imports: (import logging from HPCStats.Errors.Registry import HPCStatsErrorsRegistry as Errors) and context including class names, function names, or small code snippets from other files: # Path: HPCStats/Errors/Registry.py # class HPCStatsErrorsRegistry(object): # # """This class contains the full list of HPCStatsError that may occur when # running the Importer application. # # When adding new errors in this registry, please mind to also update the # table in doc/architecture.rst in the documentation. # """ # # # testing purpose errors # E_T0001 = HPCStatsError('E_T0001', "Fake error 1 for testing purpose") # E_T0002 = HPCStatsError('E_T0002', "Fake error 2 for testing purpose") # # # business codes importers errors # E_B0001 = HPCStatsError('E_B0001', "Invalid wckey format in SlurmDBD") # # # projects importers errors # E_P0001 = HPCStatsError('E_P0001', "Invalid wckey format in SlurmDBD") # # # jobs importers errors # E_J0001 = HPCStatsError('E_J0001', "Job found with an unknown account") # E_J0002 = HPCStatsError('E_J0002', "Invalid wckey format in SlurmDBD") # E_J0003 = HPCStatsError('E_J0003', "Job found with an unknown project") # E_J0004 = HPCStatsError('E_J0004', "Job found with an unknown business " # "code") # E_J0005 = HPCStatsError('E_J0005', "Unable to define job partition based " # "on job nodes list") # E_J0006 = HPCStatsError('E_J0006', "Unable to find job node in loaded " # "architecture") # # # users importers errors # E_U0001 = HPCStatsError('E_U0001', "User is member of the users group in " # "the LDAP directory but does not have " # "user entry in this directory") # E_U0002 = HPCStatsError('E_U0002', "Missing attribute in LDAP user entry") # E_U0003 = HPCStatsError('E_U0003', "Unable to determine user department " # "in LDAP directory") # E_U0004 = HPCStatsError('E_U0004', "User found in SlurmDBD but not found " # "in LDAP, probably due to user removed " # "from LDAP directory") # E_U0005 = HPCStatsError('E_U0005', "Deprecated configuration parameter") # E_U0006 = HPCStatsError('E_U0006', "User primary group does not exist in " # "LDAP directory") # # # events importers errors # E_E0001 = HPCStatsError('E_E0001', "Event node is unknown in cluster " # "architecture") # # def __init__(self): # # pass # # @classmethod # def is_valid(cls, error_s): # return error_s in [a for a in dir(cls) # if type(getattr(cls, a)) is HPCStatsError] # # @classmethod # def to_error(cls, error_s): # # return getattr(cls, error_s) . Output only the next line.
logger.debug("adding error %s to set of ignored errors", error_s)
Based on the snippet: <|code_start|> fsquota_file_limit, fsquota_file_in_doubt, fsquota_file_grace ) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s ) """ params = ( self.filesystem.fs_id, self.filesystem.cluster.cluster_id, self.timestamp, self.name, self.block_KB, self.block_quota, self.block_limit, self.block_in_doubt, self.block_grace, self.file_files, self.file_quota, self.file_limit, self.file_in_doubt, self.file_grace ) #print db.cur.mogrify(req, params) db.execute(req, params) def get_last_fsquota_datetime(db, cluster, filesystem):#, name """Get the datetime of the last fsquota for the fs and the name in DB.""" req = """ SELECT MAX(fsquota_time) AS last_usage FROM fsquota WHERE cluster_id = %s <|code_end|> , predict the immediate next line with the help of imports: import logging from datetime import datetime from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (classes, functions, sometimes code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
AND filesystem_id = %s
Predict the next line after this snippet: <|code_start|> db.execute(req, params) nb_rows = db.cur.rowcount if nb_rows == 0: logger.debug("fsusage %s not found in DB", str(self)) self.exists = False elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several fsusage found in DB for fsusage %s" \ % (str(self))) else: logger.debug("fsusage %s found in DB", str(self)) self.exists = True return self.exists def save(self, db): """Insert FSQuota in database. It first makes sure that the FSQuota does not already exist in database yet by calling FSQuota.existing() method if needed. If the fsquota already exists in database, it raises HPCStatsRuntimeError. """ if self.exists is None: # not checked yet self.existing(db) if self.exists is True: raise HPCStatsRuntimeError( "could not insert fsquota %s since already existing in "\ "database" % (str(self))) req = """ INSERT INTO fsquota ( filesystem_id, <|code_end|> using the current file's imports: import logging from datetime import datetime from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and any relevant context from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
cluster_id,
Given the following code snippet before the placeholder: <|code_start|> str(self), self.job_id ) return self.job_id def save(self, db): """Insert Job in database. You must make sure that the Job does not already exist in database yet (typically using Job.find() method else there is a risk of future integrity errors because of duplicated jobs. If job_id attribute is set, it raises HPCStatsRuntimeError. """ if self.job_id is not None: raise HPCStatsRuntimeError( "could not insert job %s since already existing in "\ "database" \ % (str(self))) req = """ INSERT INTO job ( job_sched_id, job_batch_id, job_name, job_nbCpu, job_state, job_queue, job_account, job_department, job_submission, job_start, job_end, <|code_end|> , predict the next line using imports from the current file: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context including class names, function names, and sometimes code from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
job_walltime,
Next line prediction: <|code_start|> self.end, self.walltime, self.account.cluster.cluster_id, self.account.user.user_id, project_id, business_code ) #print db.cur.mogrify(req, params) db.execute(req, params) self.job_id = db.cur.fetchone()[0] def update(self, db): """Update Job sched_id, nbcpu, name, state, queue, account, department, submission, start, end and walltime in database. Raises HPCStatsRuntimeError if self.job_id is None. """ if self.job_id is None: raise HPCStatsRuntimeError( "could not update job %s since not found in database" \ % (str(self))) req = """ UPDATE Job SET job_sched_id = %s, job_nbCpu = %s, job_name = %s, job_state = %s, job_queue = %s, job_account = %s, <|code_end|> . Use current file imports: (import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError) and context including class names, function names, or small code snippets from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
job_department = %s,
Given snippet: <|code_start|> db.execute(req, params) nb_rows = db.cur.rowcount if nb_rows == 0: logger.debug("project %s not found in DB", str(self)) return None elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several project_id found in DB for project %s" \ % (str(self))) else: self.project_id = db.cur.fetchone()[0] logger.debug("project %s found in DB with id %d", str(self), self.project_id ) return self.project_id def load(self, db): """Load the Project based on the content of the DB and set objects attributes accordingly. The project_id attribute must have been set previously, typically by calling find() method. It raises raises HPCStatsRuntimeError if the Project is not found in DB. """ if self.project_id is None: raise HPCStatsRuntimeError( "could not load project %s since not found in database" \ % (str(self))) req = """ SELECT project_code, <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError from HPCStats.Model.Domain import Domain and context: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) # # Path: HPCStats/Model/Domain.py # class Domain(object): # # """Model class for the Domain table.""" # # def __init__(self, key, name): # # self.key = key # self.name = name # # self.exists = None # # def __str__(self): # # return "domain [%s] %s" % (self.key, self.name) # # def __eq__(self, domain): # # return domain.key == self.key # # def existing(self, db): # """Returns True if the domain already exists in database (same key), or # False if not. # """ # # req = """ # SELECT domain_id # FROM Domain # WHERE domain_id = %s # """ # params = ( self.key, ) # db.execute(req, params) # nb_rows = db.cur.rowcount # if nb_rows == 0: # logger.debug("domain %s not found in DB", str(self)) # self.exists = False # elif nb_rows > 1: # raise HPCStatsDBIntegrityError( # "several domain found in DB for domain %s" \ # % (str(self))) # else: # logger.debug("domain %s found in DB", str(self)) # self.exists = True # return self.exists # # def save(self, db): # """Insert Domain in database. It first makes sure that the Domain does # not already exist in database yet by calling Domain.existing() # method if needed. If the domain already exists in database, it # raises HPCStatsRuntimeError. # """ # # if self.exists is None: # not checked yet # self.existing(db) # if self.exists is True: # raise HPCStatsRuntimeError( # "could not insert domain %s since already existing in "\ # "database" % (str(self))) # # req = """ # INSERT INTO Domain ( domain_id, # domain_name ) # VALUES ( %s, %s ) # """ # params = ( self.key, # self.name ) # #print db.cur.mogrify(req, params) # db.execute(req, params) # self.exists = True # # def update(self, db): # """Update Domain name in database. Raises HPCStatsRuntimeError if # exists is False. # """ # # if self.exists is None: # not checked yet # self.existing(db) # if self.exists is False: # raise HPCStatsRuntimeError( # "could not update domain %s since not found in database" \ # % (str(self))) # # req = """ # UPDATE Domain # SET domain_name = %s # WHERE domain_id = %s # """ # params = ( self.name, # self.key ) # #print db.cur.mogrify(req, params) # db.execute(req, params) which might include code, classes, or functions. Output only the next line.
project_description,
Continue the code snippet: <|code_start|> if nb_rows == 0: logger.debug("project %s not found in DB", str(self)) return None elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several project_id found in DB for project %s" \ % (str(self))) else: self.project_id = db.cur.fetchone()[0] logger.debug("project %s found in DB with id %d", str(self), self.project_id ) return self.project_id def load(self, db): """Load the Project based on the content of the DB and set objects attributes accordingly. The project_id attribute must have been set previously, typically by calling find() method. It raises raises HPCStatsRuntimeError if the Project is not found in DB. """ if self.project_id is None: raise HPCStatsRuntimeError( "could not load project %s since not found in database" \ % (str(self))) req = """ SELECT project_code, project_description, domain_id <|code_end|> . Use current file imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError from HPCStats.Model.Domain import Domain and context (classes, functions, or code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) # # Path: HPCStats/Model/Domain.py # class Domain(object): # # """Model class for the Domain table.""" # # def __init__(self, key, name): # # self.key = key # self.name = name # # self.exists = None # # def __str__(self): # # return "domain [%s] %s" % (self.key, self.name) # # def __eq__(self, domain): # # return domain.key == self.key # # def existing(self, db): # """Returns True if the domain already exists in database (same key), or # False if not. # """ # # req = """ # SELECT domain_id # FROM Domain # WHERE domain_id = %s # """ # params = ( self.key, ) # db.execute(req, params) # nb_rows = db.cur.rowcount # if nb_rows == 0: # logger.debug("domain %s not found in DB", str(self)) # self.exists = False # elif nb_rows > 1: # raise HPCStatsDBIntegrityError( # "several domain found in DB for domain %s" \ # % (str(self))) # else: # logger.debug("domain %s found in DB", str(self)) # self.exists = True # return self.exists # # def save(self, db): # """Insert Domain in database. It first makes sure that the Domain does # not already exist in database yet by calling Domain.existing() # method if needed. If the domain already exists in database, it # raises HPCStatsRuntimeError. # """ # # if self.exists is None: # not checked yet # self.existing(db) # if self.exists is True: # raise HPCStatsRuntimeError( # "could not insert domain %s since already existing in "\ # "database" % (str(self))) # # req = """ # INSERT INTO Domain ( domain_id, # domain_name ) # VALUES ( %s, %s ) # """ # params = ( self.key, # self.name ) # #print db.cur.mogrify(req, params) # db.execute(req, params) # self.exists = True # # def update(self, db): # """Update Domain name in database. Raises HPCStatsRuntimeError if # exists is False. # """ # # if self.exists is None: # not checked yet # self.existing(db) # if self.exists is False: # raise HPCStatsRuntimeError( # "could not update domain %s since not found in database" \ # % (str(self))) # # req = """ # UPDATE Domain # SET domain_name = %s # WHERE domain_id = %s # """ # params = ( self.name, # self.key ) # #print db.cur.mogrify(req, params) # db.execute(req, params) . Output only the next line.
FROM Project
Given snippet: <|code_start|> db.execute(req, params) nb_rows = db.cur.rowcount if nb_rows == 0: logger.debug("project %s not found in DB", str(self)) return None elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several project_id found in DB for project %s" \ % (str(self))) else: self.project_id = db.cur.fetchone()[0] logger.debug("project %s found in DB with id %d", str(self), self.project_id ) return self.project_id def load(self, db): """Load the Project based on the content of the DB and set objects attributes accordingly. The project_id attribute must have been set previously, typically by calling find() method. It raises raises HPCStatsRuntimeError if the Project is not found in DB. """ if self.project_id is None: raise HPCStatsRuntimeError( "could not load project %s since not found in database" \ % (str(self))) req = """ SELECT project_code, <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError from HPCStats.Model.Domain import Domain and context: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) # # Path: HPCStats/Model/Domain.py # class Domain(object): # # """Model class for the Domain table.""" # # def __init__(self, key, name): # # self.key = key # self.name = name # # self.exists = None # # def __str__(self): # # return "domain [%s] %s" % (self.key, self.name) # # def __eq__(self, domain): # # return domain.key == self.key # # def existing(self, db): # """Returns True if the domain already exists in database (same key), or # False if not. # """ # # req = """ # SELECT domain_id # FROM Domain # WHERE domain_id = %s # """ # params = ( self.key, ) # db.execute(req, params) # nb_rows = db.cur.rowcount # if nb_rows == 0: # logger.debug("domain %s not found in DB", str(self)) # self.exists = False # elif nb_rows > 1: # raise HPCStatsDBIntegrityError( # "several domain found in DB for domain %s" \ # % (str(self))) # else: # logger.debug("domain %s found in DB", str(self)) # self.exists = True # return self.exists # # def save(self, db): # """Insert Domain in database. It first makes sure that the Domain does # not already exist in database yet by calling Domain.existing() # method if needed. If the domain already exists in database, it # raises HPCStatsRuntimeError. # """ # # if self.exists is None: # not checked yet # self.existing(db) # if self.exists is True: # raise HPCStatsRuntimeError( # "could not insert domain %s since already existing in "\ # "database" % (str(self))) # # req = """ # INSERT INTO Domain ( domain_id, # domain_name ) # VALUES ( %s, %s ) # """ # params = ( self.key, # self.name ) # #print db.cur.mogrify(req, params) # db.execute(req, params) # self.exists = True # # def update(self, db): # """Update Domain name in database. Raises HPCStatsRuntimeError if # exists is False. # """ # # if self.exists is None: # not checked yet # self.existing(db) # if self.exists is False: # raise HPCStatsRuntimeError( # "could not update domain %s since not found in database" \ # % (str(self))) # # req = """ # UPDATE Domain # SET domain_name = %s # WHERE domain_id = %s # """ # params = ( self.name, # self.key ) # #print db.cur.mogrify(req, params) # db.execute(req, params) which might include code, classes, or functions. Output only the next line.
project_description,
Given the code snippet: <|code_start|> if nb_rows == 0: logger.debug("node %s not found in DB", str(self)) return None elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several node_id found in DB for node %s" \ % (str(self))) else: self.node_id = db.cur.fetchone()[0] logger.debug("node %s found in DB with id %d", str(self), self.node_id ) return self.node_id def save(self, db): """Insert Node in database. You must make sure that the Node does not already exist in database yet (typically using Node.find() method else there is a risk of future integrity errors because of duplicated nodes. If node_id attribute is set, it raises HPCStatsRuntimeError. """ if self.node_id is not None: raise HPCStatsRuntimeError( "could not insert node %s since already existing in "\ "database" \ % (str(self))) req = """ <|code_end|> , generate the next line using the imports in this file: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (functions, classes, or occasionally code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
INSERT INTO Node ( node_name,
Next line prediction: <|code_start|> % (str(self))) else: self.node_id = db.cur.fetchone()[0] logger.debug("node %s found in DB with id %d", str(self), self.node_id ) return self.node_id def save(self, db): """Insert Node in database. You must make sure that the Node does not already exist in database yet (typically using Node.find() method else there is a risk of future integrity errors because of duplicated nodes. If node_id attribute is set, it raises HPCStatsRuntimeError. """ if self.node_id is not None: raise HPCStatsRuntimeError( "could not insert node %s since already existing in "\ "database" \ % (str(self))) req = """ INSERT INTO Node ( node_name, cluster_id, node_model, node_partition, node_nbCpu, node_memory, node_flops ) <|code_end|> . Use current file imports: (import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError) and context including class names, function names, or small code snippets from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
VALUES ( %s, %s, %s, %s, %s, %s, %s )
Here is a snippet: <|code_start|> logger.info("creating business code %s" % str(self)) req = """ INSERT INTO Business ( business_code, business_description ) VALUES (%s, %s) """ params = ( self.code, self.description ) #print db.cur.mogrify(req, params) db.execute(req, params) self.exists = True def update(self, db): """Update Business description in database. Raises HPCStatsRuntimeError if exists is False. """ if self.exists is None: # not checked yet self.existing(db) if self.exists is False: raise HPCStatsRuntimeError( "could not update business %s since not found in " \ "database" \ % (str(self))) logger.debug("updating business code %s" % str(self)) req = """ UPDATE Business SET business_description = %s <|code_end|> . Write the next line using the current file imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) , which may include functions, classes, or code. Output only the next line.
WHERE business_code = %s
Using the snippet: <|code_start|> logger = logging.getLogger(__name__) class Business(object): """Model class for the Business table.""" def __init__(self, code, description): self.code = code self.description = description self.exists = None def __str__(self): if self.description == None: description = "(empty)" else: description = self.description return self.code + " - " + description def __eq__(self, other): return other.code == self.code def existing(self, db): """Returns True if the business already exists in database (with same code), or False if not. """ req = """ <|code_end|> , determine the next line of code. You have imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (class names, function names, or code) available: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
SELECT business_code
Given snippet: <|code_start|># Contact: # CCN - HPC <dsp-cspit-ccn-hpc@edf.fr> # 1, Avenue du General de Gaulle # 92140 Clamart # # Authors: CCN - HPC <dsp-cspit-ccn-hpc@edf.fr> # # This file is part of HPCStats. # # HPCStats is free software: you can redistribute in and/or # modify it under the terms of the GNU General Public License, # version 2, as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with HPCStats. If not, see # <http://www.gnu.org/licenses/>. # # On Calibre systems, the complete text of the GNU General # Public License can be found in `/usr/share/common-licenses/GPL'. class MockApp(object): def __init__(self, db, config, cluster): self.params = { 'since_event': '1970-01-01', <|code_end|> , continue by predicting the next line. Consider current file imports: from HPCStats.Tests.Mocks.ArchitectureImporter import MockArchitectureImporter from HPCStats.Tests.Mocks.UserImporter import MockUserImporter from HPCStats.Tests.Mocks.ProjectImporter import MockProjectImporter from HPCStats.Tests.Mocks.BusinessCodeImporter import MockBusinessCodeImporter and context: # Path: HPCStats/Tests/Mocks/ArchitectureImporter.py # class MockArchitectureImporter(ArchitectureImporter): # # def __init__(self, app, db, config, cluster_name): # # super(MockArchitectureImporter, self).__init__(app, db, config, cluster_name) # # Path: HPCStats/Tests/Mocks/UserImporter.py # class MockUserImporter(UserImporter): # # def __init__(self, app, db, config, cluster): # # super(MockUserImporter, self).__init__(app, db, config, cluster) # # Path: HPCStats/Tests/Mocks/ProjectImporter.py # class MockProjectImporter(ProjectImporter): # # def __init__(self, app, db, config): # # super(MockProjectImporter, self).__init__(app, db, config) # # Path: HPCStats/Tests/Mocks/BusinessCodeImporter.py # class MockBusinessCodeImporter(BusinessCodeImporter): # # def __init__(self, app, db, config): # # super(MockBusinessCodeImporter, self).__init__(app, db, config) which might include code, classes, or functions. Output only the next line.
'since_jobid': -1 }
Based on the snippet: <|code_start|> self.job.job_id ) db.execute(req, params) nb_rows = db.cur.rowcount if nb_rows == 0: logger.debug("run %s not found in DB", str(self)) self.exists = False elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several run found in DB for run %s" \ % (str(self))) else: logger.debug("run %s found in DB", str(self)) self.exists = True return self.exists def save(self, db): """Insert Run in database. It first makes sure that the Run does not already exist in database yet by calling Run.existing() method if needed. If the Run already exists in database, it raises HPCStatsRuntimeError. """ if self.exists is None: # not checked yet self.existing(db) if self.exists is True: raise HPCStatsRuntimeError( "could not insert run %s since already existing in "\ "database" % (str(self))) req = """ <|code_end|> , predict the immediate next line with the help of imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (classes, functions, sometimes code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
INSERT INTO Run ( job_id,
Predict the next line for this snippet: <|code_start|> logger = logging.getLogger(__name__) class Run(object): """Model class for the Run table.""" def __init__(self, cluster, node, job): self.cluster = cluster self.node = node self.job = job self.exists = None def __str__(self): return "run on %s [%s] for job %d" % \ ( self.node.name, self.cluster.name, self.job.sched_id ) def existing(self, db): """Returns True if theRunt already exists in database (same cluster, node and job), or False if not. """ req = """ SELECT node_id FROM Run WHERE cluster_id = %s <|code_end|> with the help of current file imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) , which may contain function names, class names, or code. Output only the next line.
AND node_id = %s
Continue the code snippet: <|code_start|> params = ( self.user.user_id, self.cluster.cluster_id ) db.execute(req, params) # We know here there is only one result thanks to existing() method result = db.cur.fetchone() self.uid = result[0] self.gid = result[1] self.creation_date = result[2] self.deletion_date = result[3] def save(self, db): """Insert Account in database. It first makes sure that the Account does not already exist in database yet by calling Account.existing() method if needed. If the account already exists in database, it raises HPCStatsRuntimeError. """ if self.exists is None: # not checked yet self.existing(db) if self.exists is True: raise HPCStatsRuntimeError( "could not insert account %s since already existing in "\ "database" % (str(self))) req = """ INSERT INTO Account ( account_uid, account_gid, account_creation, account_deletion, userhpc_id, <|code_end|> . Use current file imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError from HPCStats.Model.User import User and context (classes, functions, or code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) # # Path: HPCStats/Model/User.py # class User(object): # # """Model class for the Userhpc table.""" # # def __init__(self, login, firstname, lastname, department, user_id=None): # # self.user_id = user_id # self.login = login # self.lastname = lastname # self.firstname = firstname # self.department = department # # def __str__(self): # # return str(self.firstname) + " " + str(self.lastname) \ # + " [" + str(self.department) + "] " + str(self.login) # # def __eq__(self, other): # # return self.login == other.login # # def find(self, db): # """Search the User in the database based on its login. If exactly # one user matches in database, set user_id attribute properly # and returns its value. If more than one user matches, raises # HPCStatsDBIntegrityError. If no user is found, returns None. # """ # # req = """ # SELECT userhpc_id # FROM Userhpc # WHERE userhpc_login = %s # """ # params = ( self.login, ) # db.execute(req, params) # nb_rows = db.cur.rowcount # if nb_rows == 0: # logger.debug("user %s not found in DB", str(self)) # return None # elif nb_rows > 1: # raise HPCStatsDBIntegrityError( # "several user_id found in DB for user %s" \ # % (str(self))) # else: # self.user_id = db.cur.fetchone()[0] # logger.debug("user %s found in DB with id %d", # str(self), # self.user_id ) # return self.user_id # # def save(self, db): # """Insert User in database. You must make sure that the User does # not already exist in database yet (typically using User.find() # method else there is a risk of future integrity errors because of # duplicated users. If user_id attribute is set, it raises # HPCStatsRuntimeError. # """ # # if self.user_id is not None: # raise HPCStatsRuntimeError( # "could not insert user %s since already existing in "\ # "database" \ # % (str(self))) # # req = """ # INSERT INTO Userhpc ( userhpc_login, # userhpc_firstname, # userhpc_name, # userhpc_department) # VALUES ( %s, %s, %s, %s) # RETURNING userhpc_id # """ # params = ( self.login, # self.firstname, # self.lastname, # self.department ) # # #print db.cur.mogrify(req, params) # db.execute(req, params) # self.user_id = db.cur.fetchone()[0] # # def update(self, db): # """Update User firstname, lastname and department fields in database. # Raises HPCStatsRuntimeError is user_id is None. # """ # # if self.user_id is None: # raise HPCStatsRuntimeError( # "could not update user %s since not found in database" \ # % (str(self))) # # req = """ # UPDATE Userhpc # SET userhpc_firstname = %s, # userhpc_name = %s, # userhpc_department = %s # WHERE userhpc_id = %s # """ # params = ( self.firstname, # self.lastname, # self.department, # self.user_id ) # # #print db.cur.mogrify(req, params) # db.execute(req, params) . Output only the next line.
cluster_id )
Based on the snippet: <|code_start|> if nb_rows == 0: logger.debug("account %s not found in DB", str(self)) self.exists = False elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several account found in DB for account %s" \ % (str(self))) else: logger.debug("account %s found in DB", str(self)) self.exists = True return self.exists def load(self, db): """Load the Account based on the content of the DB and set objects attributes accordingly. It calls existing() method if needed and raises HPCStatsRuntimeError if the Account is not found in DB. """ if self.exists is None: # not checked yet self.existing(db) if self.exists is False: raise HPCStatsRuntimeError( "could not update load %s since not found in database" \ % (str(self))) req = """ SELECT account_uid, account_gid, account_creation, account_deletion <|code_end|> , predict the immediate next line with the help of imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError from HPCStats.Model.User import User and context (classes, functions, sometimes code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) # # Path: HPCStats/Model/User.py # class User(object): # # """Model class for the Userhpc table.""" # # def __init__(self, login, firstname, lastname, department, user_id=None): # # self.user_id = user_id # self.login = login # self.lastname = lastname # self.firstname = firstname # self.department = department # # def __str__(self): # # return str(self.firstname) + " " + str(self.lastname) \ # + " [" + str(self.department) + "] " + str(self.login) # # def __eq__(self, other): # # return self.login == other.login # # def find(self, db): # """Search the User in the database based on its login. If exactly # one user matches in database, set user_id attribute properly # and returns its value. If more than one user matches, raises # HPCStatsDBIntegrityError. If no user is found, returns None. # """ # # req = """ # SELECT userhpc_id # FROM Userhpc # WHERE userhpc_login = %s # """ # params = ( self.login, ) # db.execute(req, params) # nb_rows = db.cur.rowcount # if nb_rows == 0: # logger.debug("user %s not found in DB", str(self)) # return None # elif nb_rows > 1: # raise HPCStatsDBIntegrityError( # "several user_id found in DB for user %s" \ # % (str(self))) # else: # self.user_id = db.cur.fetchone()[0] # logger.debug("user %s found in DB with id %d", # str(self), # self.user_id ) # return self.user_id # # def save(self, db): # """Insert User in database. You must make sure that the User does # not already exist in database yet (typically using User.find() # method else there is a risk of future integrity errors because of # duplicated users. If user_id attribute is set, it raises # HPCStatsRuntimeError. # """ # # if self.user_id is not None: # raise HPCStatsRuntimeError( # "could not insert user %s since already existing in "\ # "database" \ # % (str(self))) # # req = """ # INSERT INTO Userhpc ( userhpc_login, # userhpc_firstname, # userhpc_name, # userhpc_department) # VALUES ( %s, %s, %s, %s) # RETURNING userhpc_id # """ # params = ( self.login, # self.firstname, # self.lastname, # self.department ) # # #print db.cur.mogrify(req, params) # db.execute(req, params) # self.user_id = db.cur.fetchone()[0] # # def update(self, db): # """Update User firstname, lastname and department fields in database. # Raises HPCStatsRuntimeError is user_id is None. # """ # # if self.user_id is None: # raise HPCStatsRuntimeError( # "could not update user %s since not found in database" \ # % (str(self))) # # req = """ # UPDATE Userhpc # SET userhpc_firstname = %s, # userhpc_name = %s, # userhpc_department = %s # WHERE userhpc_id = %s # """ # params = ( self.firstname, # self.lastname, # self.department, # self.user_id ) # # #print db.cur.mogrify(req, params) # db.execute(req, params) . Output only the next line.
FROM Account
Predict the next line after this snippet: <|code_start|> cluster_id ) VALUES ( %s, %s, %s, %s, %s, %s ) """ params = ( self.uid, self.gid, self.creation_date, self.deletion_date, self.user.user_id, self.cluster.cluster_id ) #print db.cur.mogrify(req, params) db.execute(req, params) self.exists = True def update(self, db): """Update Account uid, gid, creation date and deletion date in database. Raises HPCStatsRuntimeError is exists is False. """ if self.exists is None: # not checked yet self.existing(db) if self.exists is False: raise HPCStatsRuntimeError( "could not update account %s since not found in database" \ % (str(self))) req = """ UPDATE Account SET account_uid = %s, account_gid = %s, account_creation = %s, <|code_end|> using the current file's imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError from HPCStats.Model.User import User and any relevant context from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) # # Path: HPCStats/Model/User.py # class User(object): # # """Model class for the Userhpc table.""" # # def __init__(self, login, firstname, lastname, department, user_id=None): # # self.user_id = user_id # self.login = login # self.lastname = lastname # self.firstname = firstname # self.department = department # # def __str__(self): # # return str(self.firstname) + " " + str(self.lastname) \ # + " [" + str(self.department) + "] " + str(self.login) # # def __eq__(self, other): # # return self.login == other.login # # def find(self, db): # """Search the User in the database based on its login. If exactly # one user matches in database, set user_id attribute properly # and returns its value. If more than one user matches, raises # HPCStatsDBIntegrityError. If no user is found, returns None. # """ # # req = """ # SELECT userhpc_id # FROM Userhpc # WHERE userhpc_login = %s # """ # params = ( self.login, ) # db.execute(req, params) # nb_rows = db.cur.rowcount # if nb_rows == 0: # logger.debug("user %s not found in DB", str(self)) # return None # elif nb_rows > 1: # raise HPCStatsDBIntegrityError( # "several user_id found in DB for user %s" \ # % (str(self))) # else: # self.user_id = db.cur.fetchone()[0] # logger.debug("user %s found in DB with id %d", # str(self), # self.user_id ) # return self.user_id # # def save(self, db): # """Insert User in database. You must make sure that the User does # not already exist in database yet (typically using User.find() # method else there is a risk of future integrity errors because of # duplicated users. If user_id attribute is set, it raises # HPCStatsRuntimeError. # """ # # if self.user_id is not None: # raise HPCStatsRuntimeError( # "could not insert user %s since already existing in "\ # "database" \ # % (str(self))) # # req = """ # INSERT INTO Userhpc ( userhpc_login, # userhpc_firstname, # userhpc_name, # userhpc_department) # VALUES ( %s, %s, %s, %s) # RETURNING userhpc_id # """ # params = ( self.login, # self.firstname, # self.lastname, # self.department ) # # #print db.cur.mogrify(req, params) # db.execute(req, params) # self.user_id = db.cur.fetchone()[0] # # def update(self, db): # """Update User firstname, lastname and department fields in database. # Raises HPCStatsRuntimeError is user_id is None. # """ # # if self.user_id is None: # raise HPCStatsRuntimeError( # "could not update user %s since not found in database" \ # % (str(self))) # # req = """ # UPDATE Userhpc # SET userhpc_firstname = %s, # userhpc_name = %s, # userhpc_department = %s # WHERE userhpc_id = %s # """ # params = ( self.firstname, # self.lastname, # self.department, # self.user_id ) # # #print db.cur.mogrify(req, params) # db.execute(req, params) . Output only the next line.
account_deletion = %s
Predict the next line after this snippet: <|code_start|> """Set Event end datetime equals to event in parameter end datetime. """ self.end_datetime = event.end_datetime def get_datetime_end_last_event(db, cluster): """Returns the end datetime of the last event on the cluster in DB. Returns None if no event found. """ req = """ SELECT MAX(event_end) AS last FROM Event WHERE cluster_id = %s """ params = ( cluster.cluster_id, ) db.execute(req, params) if db.cur.rowcount == 0: return None db_row = db.cur.fetchone() return db_row[0] def get_datetime_start_oldest_unfinished_event(db, cluster): """Returns the start datetime of the oldest event on the cluster in DB. Returns None if no unfinished event found. """ req = """ SELECT MIN(event_start) FROM Event <|code_end|> using the current file's imports: import logging from HPCStats.Exceptions import HPCStatsRuntimeError, HPCStatsDBIntegrityError and any relevant context from other files: # Path: HPCStats/Exceptions.py # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) # # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) . Output only the next line.
WHERE cluster_id = %s
Given snippet: <|code_start|> """Returns the start datetime of the oldest event on the cluster in DB. Returns None if no unfinished event found. """ req = """ SELECT MIN(event_start) FROM Event WHERE cluster_id = %s AND event_end IS NULL """ params = ( cluster.cluster_id, ) db.execute(req, params) if db.cur.rowcount == 0: return None db_row = db.cur.fetchone() return db_row[0] def get_unfinished_events(db, cluster): """Get the list of unfinished Events on the cluster out of DB. Returns None if no unfinished event found. """ req = """ SELECT event_id, node_name, event_type, event_reason, event_nbCpu, event_start FROM Events WHERE cluster_id = %s <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from HPCStats.Exceptions import HPCStatsRuntimeError, HPCStatsDBIntegrityError and context: # Path: HPCStats/Exceptions.py # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) # # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) which might include code, classes, or functions. Output only the next line.
AND event_end IS NULL
Using the snippet: <|code_start|> return None elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several filesystem_id found in DB for filesystem %s" \ % (str(self))) else: self.fs_id = db.cur.fetchone()[0] logger.debug("filesystem %s found in DB with id %d", str(self), self.fs_id ) return self.fs_id def save(self, db): """Insert Filesystem in database. You must make sure that the Filesystem does not already exist in database yet (typically using Filesystem.find() method else there is a risk of future integrity errors because of duplicated filesystems. If fs_id attribute is set, it raises HPCStatsRuntimeError. """ if self.fs_id is not None: raise HPCStatsRuntimeError( "could not insert filesystem %s since already existing " \ "in database" \ % (str(self))) req = """ INSERT INTO filesystem ( filesystem_name, cluster_id ) VALUES ( %s, %s) <|code_end|> , determine the next line of code. You have imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (class names, function names, or code) available: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
RETURNING filesystem_id
Here is a snippet: <|code_start|>class Filesystem(object): """Model class for the filesystem table.""" def __init__(self, mountpoint, cluster, fs_id=None): self.fs_id = fs_id self.mountpoint = mountpoint self.cluster = cluster def __str__(self): return "filesystem: %s [cluster: %s]" % \ ( self.mountpoint, self.cluster.name ) def __eq__(self, other): return other.mountpoint == self.mountpoint and \ other.cluster == self.cluster def find(self, db): """Search the Filesystem in the database based on its mountpoint and cluster. If exactly one filesystem matches in database, set fs_id attribute properly and returns its value. If more than one filesystem matches, raises HPCStatsDBIntegrityError. If no filesystem is found, returns None. """ req = """ SELECT filesystem_id <|code_end|> . Write the next line using the current file imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) , which may include functions, classes, or code. Output only the next line.
FROM filesystem
Predict the next line after this snippet: <|code_start|> db.execute(req, params) nb_rows = db.cur.rowcount if nb_rows == 0: logger.debug("fsusage %s not found in DB", str(self)) self.exists = False elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several fsusage found in DB for fsusage %s" \ % (str(self))) else: logger.debug("fsusage %s found in DB", str(self)) self.exists = True return self.exists def save(self, db): """Insert FSUsage in database. It first makes sure that the FSUsage does not already exist in database yet by calling FSUsage.existing() method if needed. If the fsusage already exists in database, it raises HPCStatsRuntimeError. """ if self.exists is None: # not checked yet self.existing(db) if self.exists is True: raise HPCStatsRuntimeError( "could not insert fsusage %s since already existing in "\ "database" % (str(self))) req = """ <|code_end|> using the current file's imports: import logging from datetime import datetime from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and any relevant context from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
INSERT INTO fsusage ( filesystem_id,
Given the code snippet: <|code_start|> self.existing(db) if self.exists is True: raise HPCStatsRuntimeError( "could not insert fsusage %s since already existing in "\ "database" % (str(self))) req = """ INSERT INTO fsusage ( filesystem_id, cluster_id, fsusage_time, fsusage_usage, fsusage_inode ) VALUES ( %s, %s, %s, %s, %s ) """ params = ( self.filesystem.fs_id, self.filesystem.cluster.cluster_id, self.timestamp, self.usage, self.inode ) #print db.cur.mogrify(req, params) db.execute(req, params) def get_last_fsusage_datetime(db, cluster, filesystem): """Get the datetime of the last fsusage for the fs in DB.""" req = """ SELECT MAX(fsusage_time) AS last_usage FROM fsusage <|code_end|> , generate the next line using the imports in this file: import logging from datetime import datetime from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (functions, classes, or occasionally code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
WHERE cluster_id = %s
Continue the code snippet: <|code_start|> logger = logging.getLogger(__name__) class Domain(object): """Model class for the Domain table.""" def __init__(self, key, name): self.key = key self.name = name self.exists = None def __str__(self): return "domain [%s] %s" % (self.key, self.name) def __eq__(self, domain): return domain.key == self.key def existing(self, db): """Returns True if the domain already exists in database (same key), or False if not. """ req = """ SELECT domain_id FROM Domain <|code_end|> . Use current file imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (classes, functions, or code) from other files: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
WHERE domain_id = %s
Using the snippet: <|code_start|> nb_rows = db.cur.rowcount if nb_rows == 0: logger.debug("domain %s not found in DB", str(self)) self.exists = False elif nb_rows > 1: raise HPCStatsDBIntegrityError( "several domain found in DB for domain %s" \ % (str(self))) else: logger.debug("domain %s found in DB", str(self)) self.exists = True return self.exists def save(self, db): """Insert Domain in database. It first makes sure that the Domain does not already exist in database yet by calling Domain.existing() method if needed. If the domain already exists in database, it raises HPCStatsRuntimeError. """ if self.exists is None: # not checked yet self.existing(db) if self.exists is True: raise HPCStatsRuntimeError( "could not insert domain %s since already existing in "\ "database" % (str(self))) req = """ INSERT INTO Domain ( domain_id, domain_name ) <|code_end|> , determine the next line of code. You have imports: import logging from HPCStats.Exceptions import HPCStatsDBIntegrityError, HPCStatsRuntimeError and context (class names, function names, or code) available: # Path: HPCStats/Exceptions.py # class HPCStatsDBIntegrityError(HPCStatsException): # # """Class for DB intregrity errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsDBIntegrityError, self).__init__(msg) # # class HPCStatsRuntimeError(HPCStatsException): # # """Class for runtime errors exceptions in HPCStats""" # # def __init__(self, msg): # # super(HPCStatsRuntimeError, self).__init__(msg) . Output only the next line.
VALUES ( %s, %s )
Given snippet: <|code_start|> wcounter += 1 # dictionaries elif command in ['dict', 'dicts', 'dictionary', 'dictionaries']: log.info('Wait for it...') dicts_summary = db['dict'].get_summary() print(dicts_summary) """if len(dicts) > 0: # compute column width maxd = max([len(x) for x in dicts] + [10]) maxn = max([len(str(len(dicts[x]))) for x in dicts] + [5]) # print header log.writeline('%*s %-*s' % (maxd, 'DICTIONARY', maxn, 'WORDS')) log.writeline('%s %s' % ('-' * maxd, '-' * maxn), log.Color.PURPLE) # print entries keys = sorted(list(dicts)) for k in keys: log.writeline('%*s %d' % (maxd, k, len(dicts[k]))) log.writeline()""" # empty, new line, comment elif command == '' or command[0] == '#': lib.command_history.pop() pass # force exit (no prompt) <|code_end|> , continue by predicting the next line. Consider current file imports: from source.libs.include import * from source.libs.include import command as cmd from source.libs.define import * from source.libs.search import * from source.libs.db import * import termios import msvcrt and context: # Path: source/libs/include.py # def command(provided_command, value=False, stdout=True): # """ Run a given command """ # sp = subprocess.Popen(provided_command, shell=True, env={'PATH': os.environ['PATH']}, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # if stdout: # return sp.stdout.read() # if value: # return sp.returncode which might include code, classes, or functions. Output only the next line.
elif command.lower() == 'force_exit':
Given snippet: <|code_start|> def __missing__(self, key: str): """Get the missing name. The missing name will be returned. The result is not cached to avoid surprise. """ if key.startswith('__') and key.endswith('__'): raise KeyError(key) for entry, excl in self._path: if hasattr(entry, key) and key not in excl: resolv = getattr(entry, key) break else: continue else: resolv = DrsSymbol(self._drudge, key) return resolv # # The main driver. # _DRUDGE_MAGIC = 'DRUDGE' _CONF_HELP = ''' The config file for the drudge to be used, it needs to be a Python script <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse import ast import collections import inspect import drudge import gristmill import sympy import builtins from sympy import Symbol, Indexed, IndexedBase from .term import ATerms from .drudge import current_drudge from .drudge import current_drudge from drudge import Drudge and context: # Path: drudge/term.py # class ATerms(abc.ABC): # """Abstract base class for terms. # # This abstract class is meant for things that can be interpreted as a local # collection of some tensor terms, mostly used for user input of tensor terms. # # """ # # @property # @abc.abstractmethod # def terms(self) -> typing.List['Term']: # """Get an list for the terms. # """ # pass # # # # # Mathematical operations. # # # # _op_priority = 19.0 # Just less than the full tensor. # # def __mul__(self, other): # """Multiply something on the right.""" # # if is_higher(other, self._op_priority): # return NotImplemented # return self._mul(self.terms, parse_terms(other)) # # def __rmul__(self, other): # """Multiply something on the left.""" # # if is_higher(other, self._op_priority): # return NotImplemented # return self._mul(parse_terms(other), self.terms) # # @staticmethod # def _mul(left_terms, right_terms): # """Multiply the left terms with the right terms. # # Note that the terms should not have any conflict in dummies. Actually, # by the common scheme in user input by drudge, the terms should normally # have no summations at all. So this function has different semantics # than the term multiplication function from the Terms class. # """ # # prod_terms = [] # for i, j in itertools.product(left_terms, right_terms): # # A shallow checking on sums, normally we have no sums by design. # sums = _cat_sums(i.sums, j.sums) # amp = i.amp * j.amp # vecs = i.vecs + j.vecs # # prod_terms.append(Term(sums, amp, vecs)) # continue # # return Terms(prod_terms) # # def __add__(self, other): # """Add something on the right.""" # # if is_higher(other, self._op_priority): # return NotImplemented # return self._add(self.terms, parse_terms(other)) # # def __radd__(self, other): # """Add something on the left.""" # # if is_higher(other, self._op_priority): # return NotImplemented # return self._add(parse_terms(other), self.terms) # # def __sub__(self, other): # """Subtract something on the right.""" # # if is_higher(other, self._op_priority): # return NotImplemented # other_terms = self._neg_terms(parse_terms(other)) # return self._add(self.terms, other_terms) # # def __rsub__(self, other): # """Be subtracted from something on the left.""" # # if is_higher(other, self._op_priority): # return NotImplemented # self_terms = self._neg_terms(parse_terms(self)) # return self._add(parse_terms(other), self_terms) # # def __neg__(self): # """Negate the terms.""" # return Terms(self._neg_terms(parse_terms(self))) # # @staticmethod # def _add(left_terms, right_terms): # """Add the terms together. # """ # return Terms(itertools.chain(left_terms, right_terms)) # # @staticmethod # def _neg_terms(terms: typing.Iterable['Term']): # """Negate the given terms. # # The resulted terms are lazily evaluated. # """ # return ( # Term(i.sums, i.amp * _NEG_UNITY, i.vecs) # for i in terms # ) # # def __truediv__(self, other): # """Make division with another object.""" # other = sympify(other) # return Terms([ # i.scale(1 / other) for i in self.terms # ]) # # def __rtruediv__(self, other): # """Being divided over by other object.""" # raise NotImplementedError('General tensors cannot inversed') # # def __or__(self, other): # """Compute the commutator with another object. # """ # if is_higher(other, self._op_priority): # return NotImplemented # return self * other - other * self # # def __ror__(self, other): # """Compute the commutator with another object on the right.""" # if is_higher(other, self._op_priority): # return NotImplemented # return other * self - self * other which might include code, classes, or functions. Output only the next line.
finally setting a global variable named ``{}`` for the drudge.
Next line prediction: <|code_start|> @mock.patch("pytube.request.urlopen") def test_streaming(mock_urlopen): # Given fake_stream_binary = [ os.urandom(8 * 1024), os.urandom(8 * 1024), os.urandom(8 * 1024), None, ] mock_response = mock.Mock() mock_response.read.side_effect = fake_stream_binary mock_response.info.return_value = {"Content-Range": "bytes 200-1000/24576"} mock_urlopen.return_value = mock_response # When response = request.stream("http://fakeassurl.gov/streaming_test") # Then assert len(b''.join(response)) == 3 * 8 * 1024 assert mock_response.read.call_count == 4 @mock.patch('pytube.request.urlopen') def test_timeout(mock_urlopen): exc = URLError(reason=socket.timeout('timed_out')) <|code_end|> . Use current file imports: (import socket import os import pytest from unittest import mock from urllib.error import URLError from pytube import request from pytube.exceptions import MaxRetriesExceeded) and context including class names, function names, or small code snippets from other files: # Path: pytube/request.py # def _execute_request( # url, # method=None, # headers=None, # data=None, # timeout=socket._GLOBAL_DEFAULT_TIMEOUT # ): # def get(url, extra_headers=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): # def post(url, extra_headers=None, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): # def seq_stream( # url, # timeout=socket._GLOBAL_DEFAULT_TIMEOUT, # max_retries=0 # ): # def stream( # url, # timeout=socket._GLOBAL_DEFAULT_TIMEOUT, # max_retries=0 # ): # def filesize(url): # def seq_filesize(url): # def head(url): # # Path: pytube/exceptions.py # class MaxRetriesExceeded(PytubeError): # """Maximum number of retries exceeded.""" . Output only the next line.
mock_urlopen.side_effect = exc
Predict the next line for this snippet: <|code_start|> assert result == {} def test_parse_longer_empty_object(): test_html = """test = { }""" result = parse_for_object(test_html, r'test\s*=\s*') assert result == {} def test_parse_empty_object_with_trailing_characters(): test_html = 'test = {};' result = parse_for_object(test_html, r'test\s*=\s*') assert result == {} def test_parse_simple_object(): test_html = 'test = {"foo": [], "bar": {}};' result = parse_for_object(test_html, r'test\s*=\s*') assert result == { 'foo': [], 'bar': {} } def test_parse_context_closer_in_string_value(): test_html = 'test = {"foo": "};"};' result = parse_for_object(test_html, r'test\s*=\s*') <|code_end|> with the help of current file imports: import json import pytest from pytube.exceptions import HTMLParseError from pytube.parser import parse_for_object and context from other files: # Path: pytube/exceptions.py # class HTMLParseError(PytubeError): # """HTML could not be parsed""" # # Path: pytube/parser.py # def parse_for_object(html, preceding_regex): # """Parses input html to find the end of a JavaScript object. # # :param str html: # HTML to be parsed for an object. # :param str preceding_regex: # Regex to find the string preceding the object. # :rtype dict: # :returns: # A dict created from parsing the object. # """ # regex = re.compile(preceding_regex) # result = regex.search(html) # if not result: # raise HTMLParseError(f'No matches for regex {preceding_regex}') # # start_index = result.end() # return parse_for_object_from_startpoint(html, start_index) , which may contain function names, class names, or code. Output only the next line.
assert result == {
Here is a snippet: <|code_start|> def test_invalid_start(): with pytest.raises(HTMLParseError): parse_for_object('test = {}', r'invalid_regex') def test_parse_simple_empty_object(): result = parse_for_object('test = {}', r'test\s*=\s*') <|code_end|> . Write the next line using the current file imports: import json import pytest from pytube.exceptions import HTMLParseError from pytube.parser import parse_for_object and context from other files: # Path: pytube/exceptions.py # class HTMLParseError(PytubeError): # """HTML could not be parsed""" # # Path: pytube/parser.py # def parse_for_object(html, preceding_regex): # """Parses input html to find the end of a JavaScript object. # # :param str html: # HTML to be parsed for an object. # :param str preceding_regex: # Regex to find the string preceding the object. # :rtype dict: # :returns: # A dict created from parsing the object. # """ # regex = re.compile(preceding_regex) # result = regex.search(html) # if not result: # raise HTMLParseError(f'No matches for regex {preceding_regex}') # # start_index = result.end() # return parse_for_object_from_startpoint(html, start_index) , which may include functions, classes, or code. Output only the next line.
assert result == {}