Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>"""
Base page renderer class
"""
#Nonsense to make PTVS happy
class PdfBaseRenderer(object):
"""PdfRenderer object. PdfOperations act on this to produce a
representation of the contents of the pdf document. This class primarily
serves to mainta... | self._state_stack = [] |
Next line prediction: <|code_start|>"""
PDF Operations base class
"""
__all__ =['PdfOperation']
@six.add_metaclass(MetaGettable)
class PdfOperation(object):
"""PDF content stream operations dispatcher. Content stream operations are
registered by calling PdfOperation.register(), passing the opcode, the type... | MARKED_CONTENT = 16384 |
Predict the next line after this snippet: <|code_start|>"""
PDF Operations base class
"""
__all__ =['PdfOperation']
@six.add_metaclass(MetaGettable)
class PdfOperation(object):
"""PDF content stream operations dispatcher. Content stream operations are
registered by calling PdfOperation.register(), passing ... | MARKED_CONTENT = 16384 |
Next line prediction: <|code_start|>"""
PDF Operations base class
"""
__all__ =['PdfOperation']
@six.add_metaclass(MetaGettable)
class PdfOperation(object):
"""PDF content stream operations dispatcher. Content stream operations are
registered by calling PdfOperation.register(), passing the opcode, the type... | CLIPPING_PATHS = 16 |
Predict the next line for this snippet: <|code_start|> # Also, for some reason, some header keys change when that happens.
try:
with open(header['F'], 'rb') as f:
data = f.read()
except KeyError:
self._data = data
self._filedata = False
... | return self._decoded_data |
Here is a snippet: <|code_start|> # to specify another file with the data, ignoring the stream data.
# Also, for some reason, some header keys change when that happens.
try:
with open(header['F'], 'rb') as f:
data = f.read()
except KeyError:
self._d... | if self._decoded: |
Given the code snippet: <|code_start|>
if self._filter_key in header:
self._decoded = False
else:
self._decoded = True
self._decoded_data = self._data
@property
def header(self):
"""Stream header"""
return self._header
@property
def _... | for f, p in zip(filters, params))) |
Continue the code snippet: <|code_start|>"""
PdfTypes for indirect objects and references to them
"""
class PdfIndirectObject(PdfType):
"""PDF indirect object definition"""
def __init__(self, object_number, generation, obj, document):
super(PdfIndirectObject, self).__init__()
self._object_num... | obj_types = {'Page' : pdf_elements.PdfPage, |
Given snippet: <|code_start|>PdfTypes for indirect objects and references to them
"""
class PdfIndirectObject(PdfType):
"""PDF indirect object definition"""
def __init__(self, object_number, generation, obj, document):
super(PdfIndirectObject, self).__init__()
self._object_number = object_num... | 'FontDescriptor': pdf_elements.FontDescriptor, |
Given the following code snippet before the placeholder: <|code_start|>"""
class PdfIndirectObject(PdfType):
"""PDF indirect object definition"""
def __init__(self, object_number, generation, obj, document):
super(PdfIndirectObject, self).__init__()
self._object_number = object_number
... | 'Encoding' : pdf_elements.FontEncoding, |
Based on the snippet: <|code_start|> elif isinstance(data.raw, io.BytesIO): return True
elif isinstance(data.raw, io.FileIO) and 'b' in data.mode: return True
return False
def read_until(data, char_set):
"""Reads buffered io object until an element of char_set is encountered,
ret... | def force_decode(bstring): |
Here is a snippet: <|code_start|>
class TestStringTypes(ParserTestCase):
def test_literal_string(self):
func = self.parser._parse_literal_string
self.set_data(b'simple string)')
<|code_end|>
. Write the next line using the current file imports:
from .parser_test import ParserTestCase
from ..pdf_par... | self.assertEqual(func(None)._parsed_bytes, b'simple string') |
Next line prediction: <|code_start|>"""
PDF objects that represent the low-level document structure
"""
class PdfXref(PdfType):
"""Cross reference objects. These forms the basic scaffolding of the PDF
file, indicating where in the file each object is located."""
<|code_end|>
. Use current file imports:
(im... | LINE_PAT = re.compile(r'^(\d{10}) (\d{5}) (n|f)\s{0,2}$') |
Predict the next line for this snippet: <|code_start|>class PdfXref(PdfType):
"""Cross reference objects. These forms the basic scaffolding of the PDF
file, indicating where in the file each object is located."""
LINE_PAT = re.compile(r'^(\d{10}) (\d{5}) (n|f)\s{0,2}$')
def __init__(self, document, ob... | else: |
Given the code snippet: <|code_start|>"""
Text positioning operations - Reference p. 406
"""
def opcode_Td(renderer, t_x, t_y):
"""Move to a new line, parallel to the current one, at text space
coordinates offset from the start of the current line by (t_x, t_y)"""
renderer.ts.m = PdfMatrix(1, 0, 0, 1, t_x... | def opcode_TD(renderer, t_x, t_y): |
Predict the next line after this snippet: <|code_start|>"""
Text positioning operations - Reference p. 406
"""
def opcode_Td(renderer, t_x, t_y):
"""Move to a new line, parallel to the current one, at text space
coordinates offset from the start of the current line by (t_x, t_y)"""
renderer.ts.m = PdfMatr... | def opcode_TD(renderer, t_x, t_y): |
Predict the next line for this snippet: <|code_start|> self.h = 1.0 # Horizontal text scale
self.l = 0.0 # Text leading
self.f = None # Font
self.fs = None # Font scaling
self.mode = 0 # Text render mode
self.rise = 0.0 # Text rise
... | self.flatness = 0 # See S6.5.1 - p. 508 |
Here is a snippet: <|code_start|> def __iter__(self):
return self._object.__iter__()
# OO style access
def __getattr__(self, name):
try:
val = self.__dict__[name]
except KeyError:
try:
val = self._object[name]
except KeyError:
... | if isinstance(v, property) |
Next line prediction: <|code_start|> # OO style access
def __getattr__(self, name):
try:
val = self.__dict__[name]
except KeyError:
try:
val = self._object[name]
except KeyError:
raise AttributeError('Object has no attribute "{}"... | ) |
Predict the next line for this snippet: <|code_start|>"""
Simple PDF types (numbers, nulls, and booleans). These mostly exist so that we
will be able to write PDFs by calling their .pdf_encode() methods
"""
@six.add_metaclass(MetaNonelike)
class PdfNull(PdfType):
"""None-like singleton representing PDF's equival... | def __getattr__(self, name): |
Predict the next line after this snippet: <|code_start|>Simple PDF types (numbers, nulls, and booleans). These mostly exist so that we
will be able to write PDFs by calling their .pdf_encode() methods
"""
@six.add_metaclass(MetaNonelike)
class PdfNull(PdfType):
"""None-like singleton representing PDF's equivalen... | def pdf_encode(self): |
Given the code snippet: <|code_start|>"""
Simple PDF types (numbers, nulls, and booleans). These mostly exist so that we
will be able to write PDFs by calling their .pdf_encode() methods
"""
@six.add_metaclass(MetaNonelike)
class PdfNull(PdfType):
"""None-like singleton representing PDF's equivalent of None."""
... | return float.__new__(cls, val) |
Here is a snippet: <|code_start|>"""
TrueType Fonts
"""
class TrueTypeFont(PdfBaseFont):
"""For our purposes, these are just a more restricted form of the Type 1
Fonts, so...we're done here."""
<|code_end|>
. Write the next line using the current file imports:
from .base_font import PdfBaseFont
and c... | def text_space_coords(self, x, y): |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def main():
fh, tmp = tempfile.mkstemp()
config.setStatePath(tmp)
assert cloud.authenticate()
config.dump_state()
print(hub.tz())
os.remove(tmp)
if __name__ == "__main__":
<|code_end|>
, generate the next line using the imports in... | main() |
Using the snippet: <|code_start|>#!/usr/bin/env python3
def main(start=hub_api.apiPath):
hub_id = hub.default()
host = hub.host(hub_id)
token = hub.token(hub_id)
api_ver = start
base = hub_api._getBase(host)
print('Testing against {0}, starting from {1}{2}'.format(hub_id, base, start))
w... | print('Works: {0}'.format(api_ver)) |
Given snippet: <|code_start|>def main(start=hub_api.apiPath):
hub_id = hub.default()
host = hub.host(hub_id)
token = hub.token(hub_id)
api_ver = start
base = hub_api._getBase(host)
print('Testing against {0}, starting from {1}{2}'.format(hub_id, base, start))
while True:
if not pin... | return True |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
def main(statepath):
config.setStatePath(statepath)
cloud_token = cloud.token()
hub_id = hub.default()
hub_token = hub.token(hub_id)
pp = pprint.PrettyPrinter(indent=2)
for token in cloud_token, hub_token:
... | sys.exit(1) |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
def main(statepath):
config.setStatePath(statepath)
cloud_token = cloud.token()
hub_id = hub.default()
hub_token = hub.token(hub_id)
pp = pprint.PrettyPrinter(indent=2)
<|code_end|>
, predict the immediate next line with the help of imp... | for token in cloud_token, hub_token: |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def main(statepath):
config.setStatePath(statepath)
cloud_token = cloud.token()
hub_id = hub.default()
hub_token = hub.token(hub_id)
pp = pprint.PrettyPrinter(indent=2)
for token in cloud_token, hub_token:
claims = jwt.dec... | else: |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
FLAGS = flags.FLAGS
flags.DEFINE_string('device', None,
'Device ID of a controllable socket into which the Lightify device is plugged')
flags.DEFINE_float('ontime', 5, 'Time to keep the light on', lower_bound=0.0)
flags... | time.sleep(FLAGS.ontime) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
@pytest.mark.live
def test_hub(live_cloud, live_hub):
assert live_hub.ping()
<|code_end|>
. Use current file imports:
import pytest
from cozify import cloud, hub, hub_api, config
from cozify.test import debug
from cozify.test.fixtures import *
fro... | hub_id = live_hub.default() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
@pytest.mark.live
def test_hub(live_cloud, live_hub):
assert live_hub.ping()
hub_id = live_hub.default()
assert hub_api.hub(
<|code_end|>
with the help of current file imports:
import pytest
from cozify import cloud, hub, hub... | hub_id=hub_id, |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
@pytest.mark.live
def test_hub(live_cloud, live_hub):
assert live_hub.ping()
hub_id = live_hub.default()
assert hub_api.hub(
hub_id=hub_id,
host=live_hub.host(hub_id),
remote=live_hub.re... | imposter = Imposter( |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
@pytest.mark.logic
def test_config_XDG(tmp_hub):
assert config._initXDG()
@pytest.mark.logic
def test_config_XDG_env(tmp_hub):
with tempfile.TemporaryDirectory() as td:
os.environ["XDG_CONFIG_HOME"] = td
config.setStatePath(c... | @pytest.mark.logic |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
@pytest.mark.logic
def test_config_XDG(tmp_hub):
assert config._initXDG()
@pytest.mark.logic
def test_config_XDG_env(tmp_hub):
with tempfile.TemporaryDirectory() as td:
os.environ["XDG_CONFIG_HOME"] = td
config... | td = tempfile.mktemp() |
Given snippet: <|code_start|>
@pytest.mark.logic
def test_hub_clean_state(tmp_hub):
states = tmp_hub.states()
assert states['clean'] == hub._clean_state(states['dirty'])
@pytest.mark.logic
def test_hub_in_range():
assert hub._in_range(0.5, low=0.0, high=1.0)
assert hub._in_range(0.0, low=0.0, high=1.0... | assert live_hub.ping() |
Using the snippet: <|code_start|> assert hub.autoremote(tmp_hub.id, False) == False
assert hub.autoremote(tmp_hub.id) == False
@pytest.mark.logic
def test_hub_id_to_name(tmp_hub):
assert hub.name(tmp_hub.id) == tmp_hub.name
@pytest.mark.logic
def test_hub_name_to_id(tmp_hub):
assert hub.hub_id(tmp_hu... | def test_hub_get_id(tmp_hub): |
Continue the code snippet: <|code_start|> assert hub._getAttr(tmp_hub.id, 'testkey') == 'deadbeef'
@pytest.mark.live
def test_multisensor(live_hub):
assert hub.ping()
data = hub.devices()
print(multisensor.getMultisensorData(data))
@pytest.mark.logic
def test_hub_get_id(tmp_hub):
assert hub._get_... | assert live_hub.ping(autorefresh=True) |
Given the code snippet: <|code_start|> assert kwargs[key] is not None, 'key {0} was set to None'.format(key)
@pytest.mark.logic
def test_hub_clean_state(tmp_hub):
states = tmp_hub.states()
assert states['clean'] == hub._clean_state(states['dirty'])
@pytest.mark.logic
def test_hub_in_range():
... | assert not live_hub.remote(live_hub.default(), False) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
def main():
hub_id = hub.default()
print(
hub_api.tz(
host=hub.host(hub_id),
cloud_token=cloud.token(),
hub_token=hub.token(hub_id),
<|code_end|>
with the help of current file imports:
... | remote=True)) |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
def main():
hub_id = hub.default()
print(
hub_api.tz(
host=hub.host(hub_id),
cloud_token=cloud.token(),
hub_token=hub.token(hub_id),
remote=True))
if __name__ == "__main__":
<|code_end|>
, pr... | main() |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def main():
hub_id = hub.default()
print(
hub_api.tz(
host=hub.host(hub_id),
cloud_token=cloud.token(),
hub_token=hub.token(hub_id),
remote=True))
<|code_end|>
, generate the next line usin... | if __name__ == "__main__": |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
FLAGS = flags.FLAGS
flags.DEFINE_string('device', None, 'Device to operate on.')
def main(argv):
<|code_end|>
. Write the next line using the current file imports:
from cozify import hub
from absl import flags, app
from cozify.test import debug
import pprint... | del argv |
Using the snippet: <|code_start|>#!/usr/bin/env python3
def dedup(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
def main():
capabilities = []
devs = hub.devices()
for id, dev in devs.items():
capabilities = capabilities + dev['capabi... | print('Not currently implemented ({0}): {1}'.format(len(not_implemented), not_implemented)) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
FLAGS = flags.FLAGS
flags.DEFINE_string('device', None, 'Device to operate on.')
flags.DEFINE_float('delay', 0.5, 'Step length in seconds.')
flags.DEFINE_float('steps', 20, 'Amount of steps to divide into.')
flags.DEFINE_bool('verify', False, 'Verify if ... | read = 'N/A' |
Given the following code snippet before the placeholder: <|code_start|> obj = lambda: 0
obj.configfile, obj.configpath = tempfile.mkstemp(suffix='tmp_cloud')
obj.section = 'Cloud'
obj.email = 'example@example.com'
obj.token = 'eyJkb20iOiJ1ayIsImFsZyI6IkhTNTEyIiwidHlwIjoiSldUIn0.eyJyb2xlIjo4LCJpYXQiOj... | def mock_server(): |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture(scope="module")
def vcr_config():
return {"filter_headers": ["authorization", "X-Hub-Key"], "record_mode": "rewrite"}
@pytest.fixture
def tmp_cloud():
obj = lambda: 0
obj.configfile, obj.configpath = tempfile.mkstemp(... | configfile, configpath = tempfile.mkstemp(suffix='live_cloud') |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
def main(capability=None):
devs = None
if capability:
devs = hub.devices(capabilities=hub.capability[capability])
else:
devs = hub.devices()
for key, dev in devs.items():
print('{0}: {1}'.format(key... | if len(sys.argv) > 1: |
Given the code snippet: <|code_start|>#!/usr/bin/env python3
def main(device):
hub.device_on(device)
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1])
else:
<|code_end|>
, generate the next line using the imports in this file:
from cozify import hub
from cozify.test import deb... | sys.exit(1) |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
## basic cloud.authenticate() tests
@pytest.mark.live
def test_cloud_authenticate(live_cloud):
assert live_cloud.authenticate()
live_cloud.resetState()
<|code_end|>
. Write the next line using the current file imports:
import os, pytest, tempfile, da... | with pytest.raises(OSError): |
Using the snippet: <|code_start|> assert cloud._need_refresh(force=False, expiry=datetime.timedelta(days=365))
@pytest.mark.logic
def test_cloud_refresh_expiry_over(tmp_cloud):
config.dump_state()
assert cloud._need_refresh(force=False, expiry=datetime.timedelta(hours=1))
@pytest.mark.logic
def test_clou... | @pytest.mark.live |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
## basic cloud.authenticate() tests
@pytest.mark.live
def test_cloud_authenticate(live_cloud):
assert live_cloud.authenticate()
<|code_end|>
with the help of current file imports:
import os, pytest, tempfile, datetime, time
from coz... | live_cloud.resetState() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3
def main():
assert cloud.authenticate()
if __name__ == "__main__":
<|code_end|>
using the current file's imports:
from cozify import cloud
and any relevant context from other files:
# Path: cozify/cloud.py
# def authenticate(trus... | main() |
Continue the code snippet: <|code_start|>
@pytest.mark.mbtest
def test_cloud_api_mock_lan_ip(mock_server):
imposter = Imposter(Stub(Predicate(path="/hub/lan_ip"), Response(body='[ "127.0.0.1" ]')))
with mock_server(imposter):
assert cloud_api.lan_ip(base=imposter.url)
@pytest.mark.mbtest
def test_... | def test_cloud_api_requestlogin(mock_server, tmp_cloud): |
Given the following code snippet before the placeholder: <|code_start|> PressKey(D)
ReleaseKey(A)
ReleaseKey(S)
def reverse_left():
PressKey(S)
PressKey(A)
ReleaseKey(W)
ReleaseKey(D)
def reverse_right():
PressKey(S)
PressKey(D)
ReleaseKey(W)
ReleaseKey(A)
def no_... | last_time = time.time() |
Predict the next line after this snippet: <|code_start|>
paused = False
while(True):
if not paused:
# 800x600 windowed mode
screen = grab_screen(region=(0,40,800,640))
print('loop took {} seconds'.format(time.time()-last_time))
last_time = time.ti... | if np.argmax(prediction) == np.argmax(sd): |
Given the following code snippet before the placeholder: <|code_start|> PressKey(S)
PressKey(A)
ReleaseKey(W)
ReleaseKey(D)
def reverse_right():
PressKey(S)
PressKey(D)
ReleaseKey(W)
ReleaseKey(A)
def no_keys():
PressKey(W)
ReleaseKey(A)
ReleaseKey(S)
ReleaseKey(D)
... | while(True): |
Here is a snippet: <|code_start|>
model = alexnet2(WIDTH, HEIGHT, LR, output = 9)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
while(True):
if not paused:
# 800x600 w... | reverse() |
Continue the code snippet: <|code_start|>
def reverse_right():
PressKey(S)
PressKey(D)
ReleaseKey(W)
ReleaseKey(A)
def no_keys():
PressKey(W)
ReleaseKey(A)
ReleaseKey(S)
ReleaseKey(D)
model = alexnet2(WIDTH, HEIGHT, LR, output = 9)
model.load(MODEL_NAME)
def main():
last... | print('loop took {} seconds'.format(time.time()-last_time)) |
Given the code snippet: <|code_start|>model = alexnet2(WIDTH, HEIGHT, LR, output = 9)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
while(True):
if not paused:
# 800x600 win... | if np.argmax(prediction) == np.argmax(d): |
Given the following code snippet before the placeholder: <|code_start|>
def draw_lanes(img, lines, color=[0, 255, 255], thickness=3):
# if this fails, go with some default line
try:
# finds the maximum y value for a lane marker
# (since we cannot assume the horizon will always be at the same... | x1 = (min_y-b) / m |
Given snippet: <|code_start|> except Exception as e:
print(str(e))
def process_img(image):
original_image = image
# edge detection
processed_img = cv2.Canny(image, threshold1 = 200, threshold2=300)
processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
vertices = np.array([[... | coords = coords[0] |
Next line prediction: <|code_start|> else:
final_lanes[m] = [ [m,b,line] ]
line_counter = {}
for lanes in final_lanes:
line_counter[lanes] = len(final_lanes[lanes])
top_lanes = sorted(line_counter.items(), key=lambda item: item[1]... | print(str(e)) |
Given snippet: <|code_start|> new_lines.append([int(x1), min_y, int(x2), max_y])
final_lanes = {}
for idx in line_dict:
final_lanes_copy = final_lanes.copy()
m = line_dict[idx][0]
b = line_dict[idx][1]
line = line_dict[idx][2]
... | line_counter[lanes] = len(final_lanes[lanes]) |
Predict the next line for this snippet: <|code_start|> original_image = image
# edge detection
processed_img = cv2.Canny(image, threshold1 = 200, threshold2=300)
processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[80... | except Exception as e: |
Predict the next line for this snippet: <|code_start|>
def roi(img, vertices):
#blank mask:
mask = np.zeros_like(img)
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, 255)
#returning the image only where mask pixels are n... | processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
Predict the next line for this snippet: <|code_start|> cv2.fillPoly(mask, vertices, 255)
#returning the image only where mask pixels are nonzero
masked = cv2.bitwise_and(img, mask)
return masked
def process_img(image):
original_image = image
# convert to gray
processed_img = cv2.cvtCo... | cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30) |
Given the following code snippet before the placeholder: <|code_start|> # edge detection
processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,... | print(str(e)) |
Predict the next line after this snippet: <|code_start|>
def process_img(image):
original_image = image
# convert to gray
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# edge detection
processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
processed_img = cv... | for coords in lines: |
Here is a snippet: <|code_start|> except Exception as e:
print(str(e))
except Exception as e:
pass
return processed_img,original_image, m1, m2
def straight():
PressKey(W)
ReleaseKey(A)
ReleaseKey(D)
def left():
PressKey(A)
ReleaseKey(W)
ReleaseKey(D)... | for i in list(range(4))[::-1]: |
Next line prediction: <|code_start|>
def process_img(image):
original_image = image
# convert to gray
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# edge detection
<|code_end|>
. Use current file imports:
(import numpy as np
import cv2
import time
import pyautogui
from PIL import ImageGrab
f... | processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300) |
Next line prediction: <|code_start|>
def process_img(image):
original_image = image
# convert to gray
processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# edge detection
processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
return processed_img
def main():
fo... | print(i+1) |
Continue the code snippet: <|code_start|> paused = False
while(True):
if not paused:
# 800x600 windowed mode
#screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
screen = grab_screen(region=(0,40,800,640))
print('loop took {} seconds'.format(ti... | if 'T' in keys: |
Given the code snippet: <|code_start|> last_time = time.time()
for i in list(range(4))[::-1]:
print(i+1)
time.sleep(1)
paused = False
while(True):
if not paused:
# 800x600 windowed mode
#screen = np.array(ImageGrab.grab(bbox=(0,40,800,640)))
... | straight() |
Given the following code snippet before the placeholder: <|code_start|> PressKey(W)
PressKey(D)
ReleaseKey(A)
#ReleaseKey(W)
#ReleaseKey(D)
time.sleep(t_time)
ReleaseKey(D)
model = alexnet(WIDTH, HEIGHT, LR)
model.load(MODEL_NAME)
def main():
last_time = time.time()
for i in lis... | print(prediction) |
Given the following code snippet before the placeholder: <|code_start|> ReleaseKey(D)
#ReleaseKey(A)
time.sleep(t_time)
ReleaseKey(A)
def right():
PressKey(W)
PressKey(D)
ReleaseKey(A)
#ReleaseKey(W)
#ReleaseKey(D)
time.sleep(t_time)
ReleaseKey(D)
model = alexnet(WIDTH, ... | print('loop took {} seconds'.format(time.time()-last_time)) |
Next line prediction: <|code_start|> ReleaseKey(D)
def left():
PressKey(W)
PressKey(A)
#ReleaseKey(W)
ReleaseKey(D)
#ReleaseKey(A)
time.sleep(t_time)
ReleaseKey(A)
def right():
PressKey(W)
PressKey(D)
ReleaseKey(A)
#ReleaseKey(W)
#ReleaseKey(D)
time.sleep(t_time)... | while(True): |
Given the code snippet: <|code_start|>
LOG = logging.getLogger('nativeconfig')
class ValueSource(Enum):
resolver = 1
default = 2
<|code_end|>
, generate the next line using the imports in this file:
from abc import ABCMeta
from collections.abc import Iterable
from enum import Enum
from nativeconfig.excepti... | config = 3 |
Based on the snippet: <|code_start|>
LOG = logging.getLogger('nativeconfig')
class ValueSource(Enum):
resolver = 1
default = 2
config = 3
one_shot = 4
env = 5
<|code_end|>
, predict the immediate next line with the help of imports:
from abc import ABCMeta
from collections.abc import Iterable
... | class BaseOption(property, metaclass=ABCMeta): |
Given the following code snippet before the placeholder: <|code_start|> print("Send command to all devices: " + cmd)
ips = get_ips()
processes = list()
for ip in ips:
proc = threading.Thread(target=single_device_command, args=(ip, cmd))
proc.start()
processes.append(proc)
for ... | print("Execute macrocommands over ssh for interacting with raumfeld if you got many devices, these need SSH access allowed") |
Given the following code snippet before the placeholder: <|code_start|>
class SingleItem:
def __init__(self, value):
self.timeChanged = time.time()
self.value = value
def update(self, value):
self.value = value
self.timeChanged = time.time()
class SingleUuid:
def __init_... | if key in self.itemMap: |
Predict the next line after this snippet: <|code_start|>from __future__ import unicode_literals
class Room:
def __init__(self, udn, renderer_list, name, location):
self.name = name
self.udn = udn
self.renderer_list = renderer_list
self.volume = 0
self.mute = 0
self... | return self.name |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
from __future__ import unicode_literals
returnString = None
class MainGui:
def __init__(self):
self.selected_index_stack = [0]
self.returnString = ""
<|code_end|>
. Write the next line using the current file imports:
import curses
import ... | self.play_in_room = None |
Predict the next line after this snippet: <|code_start|> try:
t = time()
if self.verbose:
print(str(control_url), str(body), str(headers))
response = requests.post(control_url, data=body, headers=headers, verify=False)
if response.status_code < 300:... | "RenderingControl", |
Here is a snippet: <|code_start|>
from __future__ import unicode_literals
class Renderer:
def __init__(self, udn, name, location):
self.name = name
self.udn = udn
self.upnp_service = None
self.location = location
def set_name(self, name):
self.name = name
def get_... | def get_udn(self): |
Using the snippet: <|code_start|>from __future__ import unicode_literals
class Services:
@staticmethod
def get_services_from_location(location):
try:
(xml_headers, xml_data) = UpnpSoap.get(location)
if xml_data is not False:
xml_root = minidom.parseString(xm... | 'serviceId']) |
Based on the snippet: <|code_start|> print(dir_browser.path)
show_dir(dir_browser)
retrieve("--discover rooms")
dir_browser.leave()
print(dir_browser.path)
show_dir(dir_browser)
retrieve("--discover zones")
dir_browser.leave()
print(dir_browser.path)
show_dir(dir_browser)
de... | print(retrieve("--zonewithroom " + room_list[0] + ' seek 00:01:34')) |
Using the snippet: <|code_start|>
class Widget():
def generateHTML(self, formid):
return ''
def parseForm(self, formData):
return formData
def default_value(self):
return self.default
class InputTagWidget(Widget):
<|code_end|>
, determine the next line of code. You have imports:
... | def generateHTML(self, formid): |
Using the snippet: <|code_start|># use matplotlib with the Agg backend to avoid opening an app
# to view the matplotlib figures
matplotlib.use('Agg')
@convert_to_html.register(matplotlib.figure.Figure)
def fig_to_html(fig):
<|code_end|>
, determine the next line of code. You have imports:
from .converters import conv... | return mpld3.fig_to_html(fig) |
Given the following code snippet before the placeholder: <|code_start|> 'export',
matplotlib.figure.Figure,
[SelectOne('format: ', ['png', 'pdf', 'svg'])])
def export_matplot_fig(fig, file_format):
my_file = tempfile.NamedTemporaryFile()
fig.savefig(my_file.name, bbox_inches='tight', form... | def bokeh_figure_to_html(figure): |
Based on the snippet: <|code_start|>
def test_grid_size():
size = get_grid_size([[0, 0, 1, 1]])
assert size == (1, 1)
size = get_grid_size([[0, 0, 1, 1], [1, 0, 1, 1]])
assert size == (2, 1)
size = get_grid_size(row_layout(1, 2))
<|code_end|>
, predict the immediate next line with the help of import... | assert size == (2, 2) |
Predict the next line after this snippet: <|code_start|>
# A 'layout' is a list of [x, y, width, height] items, 1 for each panel
# where x, y is the position of the top-left corner of the panel, and
# the parent container has (0, 0) in the top-left with +y downwards
# helpers for defining layouts
def row_layout(*r... | for row_num, num_cols in enumerate(row_sizes): |
Given the following code snippet before the placeholder: <|code_start|>
@convert_to_html.register(Dashboard)
def dashboard_to_html(dash):
grid = get_grid(dash)
return render_template('dashboard.html', grid=grid)
@get_utilities_for_value.register(Dashboard)
def dashboard_utilities(dash):
def gen_html_... | all_utils.append(util) |
Here is a snippet: <|code_start|> return {'size': grid_size, 'panes': panes}
@convert_to_html.register(Dashboard)
def dashboard_to_html(dash):
grid = get_grid(dash)
return render_template('dashboard.html', grid=grid)
@get_utilities_for_value.register(Dashboard)
def dashboard_utilities(dash):
def ... | util['apply'] = partial(apply_for_item, util=child_util, item_index=index) |
Given the following code snippet before the placeholder: <|code_start|>
@convert_to_html.register(Dashboard)
def dashboard_to_html(dash):
grid = get_grid(dash)
return render_template('dashboard.html', grid=grid)
@get_utilities_for_value.register(Dashboard)
def dashboard_utilities(dash):
def gen_html_... | all_utils.append(util) |
Predict the next line for this snippet: <|code_start|>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Factor integers in various Euclidean domains
"""
DOMAINS = {"i": factor.Integer,
"g": factor.Gaussian,
"e": factor.Eisenstein,
"s": factor.Steineisen}
DESC = """Factor various alg... | constructor = DOMAINS[args.d] |
Given the code snippet: <|code_start|>def vis_vertices(ax, vertices, verts, vertexcolors=None):
"""Plots vertices
Arguments:
ax: Axis to plot on
vertices: 3d coordinates of vertices (shape (n, 3))
verts: List of vertex indices to plot
vertexcolors: Color of vertices (optional)"""... | def vis_bounds(ax, vertices): |
Next line prediction: <|code_start|> style = 'stroke="red" stroke-dasharray="3"'
statements += lines(g, 0, digits, shapeinfo, style)
statements += lines(n, m, digits, shapeinfo)
statements += [footer1, footer2]
return '\n'.join(statements)
square = {'name': 'square',
'shape': np.ar... | yield i |
Given snippet: <|code_start|>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Cellular automata on the faces (or vertices) of polyhedra"""
#import pandas as pd
def ca_step(state, rule, adj):
neighbors = adj.dot(state)
#x, y, _ = sparse.find(adj)
#nbx = state[x]
#px = pd.DataFrame(data=nbx, index=y)... | interpreting 0 as dead and anything else as alive. If colors are not |
Given snippet: <|code_start|> help="Input file. Reads from stdin if not given.")
parser.add_argument("-n", help="Number of steps", default=100, type=int)
parser.add_argument("-b", help="Birth rule, comma-separated",
default=[1, 5, 6], type=ruleparse)
parser.add... | state = np.zeros((args.n + 1, len(init)), dtype=bool) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.