Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|> variable_id = self.variable_id
variable_definition = self.variable_definition
data_uri = b.get_data_uri(variable_definition, x)
body_text = (
f'<table id="{x.id}" '
f'class="{self.mode_name} {self.view_name} {variable_id}">'
... | raise CrossComputeConfigurationError( |
Given the following code snippet before the placeholder: <|code_start|> }
def render_output(self, b: Batch, x: Element):
value = self.get_value(b)
try:
value = apply_functions(
value, x.function_names, self.function_by_name)
except KeyError as e:
... | raise CrossComputeDataError(f'{value} is not a number') |
Given snippet: <|code_start|> const thead = nodes[0], tbody = nodes[1];
let tr = document.createElement('tr');
for (let i = 0; i < columnCount; i++) {
const column = columns[i];
const th = document.createElement('th');
th.innerText = column;
tr.append(th);
}
thead.append(tr);
for (let i = 0; ... | FILE_DATA_CACHE = FileCache( |
Using the snippet: <|code_start|># IMAGE_JS_TEMPLATE = Template('''''')
TABLE_JS_TEMPLATE = Template('''\
(async function () {
const response = await fetch('$data_uri');
const d = await response.json();
const columns = d['columns'], columnCount = columns.length;
const rows = d['data'], rowCount = rows.length;
... | VARIABLE_VIEW_BY_NAME = {_.name: import_attribute( |
Predict the next line for this snippet: <|code_start|> view_name = 'text'
def render_input(self, b: Batch, x: Element):
view_name = self.view_name
variable_id = self.variable_id
value = self.get_value(b)
body_text = (
f'<textarea id="{x.id}" '
f'class="{se... | data = get_html_from_markdown(value) |
Next line prediction: <|code_start|> base_uri: str
mode_name: str
for_print: bool
function_names: list[str]
class VariableView():
view_name = 'variable'
environment_variable_definitions = []
def __init__(self, variable_definition):
self.variable_definition = variable_definition
... | def render(self, b: Batch, x: Element): |
Predict the next line after this snippet: <|code_start|>
def test_update_variable_data(tmp_path):
target_path = tmp_path / 'variables.dictionary'
update_variable_data(target_path, {'a': 1})
with target_path.open('r') as f:
d = json.load(f)
assert d['a'] == 1
update_variable_data(target_path... | with raises(CrossComputeDataError): |
Predict the next line for this snippet: <|code_start|># TODO: Define /mutations/{path}
# TODO: Trigger reload intelligently only if relevant
class MutationRoutes():
def __init__(self, server_timestamp_object):
self._server_timestamp_object = server_timestamp_object
def includeme(self, config):
<|cod... | config.add_route('mutations', MUTATIONS_ROUTE) |
Given the code snippet: <|code_start|>
class FetchResourceRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/a.json':
self.send_response(500)
elif self.path == '/b.json':
self.send_response(401)
elif self.path == '/c.json':
self... | environ['CROSSCOMPUTE_CLIENT'] = CLIENT_URL |
Next line prediction: <|code_start|>
class FetchResourceRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/a.json':
self.send_response(500)
elif self.path == '/b.json':
self.send_response(401)
elif self.path == '/c.json':
self.s... | environ['CROSSCOMPUTE_SERVER'] = SERVER_URL |
Given the following code snippet before the placeholder: <|code_start|> elif self.path == '/b.json':
self.send_response(401)
elif self.path == '/c.json':
self.send_response(400)
else:
self.send_response(200)
self.end_headers()
try:
l... | with raises(CrossComputeConnectionError): |
Given snippet: <|code_start|> length = int(self.headers['Content-Length'])
except TypeError:
pass
else:
self.wfile.write(self.rfile.read(length))
def test_get_bash_configuration_text():
environ['CROSSCOMPUTE_CLIENT'] = CLIENT_URL
environ['CROSSCOMPUTE_SERVER'... | with raises(CrossComputeExecutionError): |
Given the code snippet: <|code_start|> else:
self.send_response(200)
self.end_headers()
try:
length = int(self.headers['Content-Length'])
except TypeError:
pass
else:
self.wfile.write(self.rfile.read(length))
def test_get_bash_conf... | with raises(CrossComputeImplementationError): |
Given the following code snippet before the placeholder: <|code_start|> server_url = server_url if server_url else get_server_url()
url = get_resource_url(server_url, resource_name, resource_id)
token = token if token else get_token()
kw = {} if data is None else {'json': data}
try:
response ... | return get_environment_value('CROSSCOMPUTE_CLIENT', CLIENT_URL) |
Given the following code snippet before the placeholder: <|code_start|> try:
response = f(url, headers={'Authorization': 'Bearer ' + token}, **kw)
except requests.ConnectionError:
raise CrossComputeConnectionError({
'url': 'could not connect to server ' + url})
status_code = respo... | return get_environment_value('CROSSCOMPUTE_SERVER', SERVER_URL) |
Given snippet: <|code_start|>
def get_bash_configuration_text():
return BASH_CONFIGURATION_TEXT.format(
client_url=get_client_url(),
server_url=get_server_url(),
token=get_token('YOUR-TOKEN'))
def fetch_resource(
resource_name, resource_id=None, method='GET', data=None,
s... | raise CrossComputeConnectionError({ |
Given the following code snippet before the placeholder: <|code_start|>
def fetch_resource(
resource_name, resource_id=None, method='GET', data=None,
server_url=None, token=None):
f = getattr(requests, method.lower())
server_url = server_url if server_url else get_server_url()
url = get_res... | CrossComputeExecutionError if status_code == 400 else |
Using the snippet: <|code_start|>
def fetch_resource(
resource_name, resource_id=None, method='GET', data=None,
server_url=None, token=None):
f = getattr(requests, method.lower())
server_url = server_url if server_url else get_server_url()
url = get_resource_url(server_url, resource_name, re... | CrossComputeImplementationError)(d) |
Given snippet: <|code_start|> if resource_id:
url += '/' + resource_id
return url + '.json'
def get_echoes_client():
echoes_url = get_echoes_url()
try:
client = SSEClient(echoes_url)
except Exception:
raise CrossComputeConnectionError({
'url': 'could not connect ... | raise CrossComputeKeyboardInterrupt |
Given snippet: <|code_start|> server_url = server_url if server_url else get_server_url()
url = get_resource_url(server_url, resource_name, resource_id)
token = token if token else get_token()
kw = {} if data is None else {'json': data}
try:
response = f(url, headers={'Authorization': 'Bearer... | return get_environment_value('CROSSCOMPUTE_CLIENT', CLIENT_URL) |
Next line prediction: <|code_start|>
class WheeType(StringType):
@classmethod
def parse(Class, x, default_value=None):
if x != 'whee':
<|code_end|>
. Use current file imports:
(from collections import OrderedDict
from invisibleroads_macros.disk import copy_folder
from os.path import dirname, join
fr... | raise DataTypeError('whee expected') |
Given the following code snippet before the placeholder: <|code_start|>
@classmethod
def parse(Class, x, default_value=None):
if x != 'whee':
raise DataTypeError('whee expected')
return x
@fixture
def tool_definition():
return OrderedDict([
('argument_names', ()),
... | return ResultRequest(posts_request) |
Using the snippet: <|code_start|>
class ADataType(DataType):
@classmethod
def load(Class, path):
if path == 'x':
raise Exception
instance = Class()
instance.path = path
return instance
@classmethod
def parse(Class, x, default_value=None):
if x == 'd... | raise DataTypeError |
Predict the next line after this snippet: <|code_start|>ID_LENGTH = 16
AUTOMATION_NAME = 'Automation X'
AUTOMATION_VERSION = '0.0.0'
AUTOMATION_PATH = Path('automate.yml')
HOST = '127.0.0.1'
PORT = 7000
DISK_POLL_IN_MILLISECONDS = 1000
DISK_DEBOUNCE_IN_MILLISECONDS = 1000
AUTOMATION_ROUTE = '/a/{automation_slug}'... | 'slug': format_slug, |
Based on the snippet: <|code_start|> if self._has_duplicates(self.data):
raise ValueError("Time sequence has duplicate entries")
super(Time, self).__init__(*args, **kwargs)
@classmethod
def from_netCDF(cls,
filename=None,
dataset=None,
... | dataset = get_dataset(filename) |
Predict the next line for this snippet: <|code_start|>
# used to parametrize tests for both methods
try:
methods = ['simple', 'celltree']
except ImportError:
# no cell tree -- only test simple
methods = ['simple']
@pytest.mark.parametrize("method", methods)
<|code_end|>
with the help of current file imp... | def test_single(method, twenty_one_triangles): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# py2/3 compatibility
from __future__ import absolute_import, division, print_function, unicode_literals
data_dir = os.path.join(os.path.split(__file__)[0], 'test_data')
def test_gen_celltree_mask_from_center_mask():
center_mask = np.array(([True, ... | m = utilities.gen_celltree_mask_from_center_mask(center_mask, center_sl) |
Continue the code snippet: <|code_start|> pts_2 = [(1,), (2,), (3,)]
pts_3 = np.array([[1, 2, 3], [4, 5, 6]])
pts_4 = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
res_1 = np.array([[1, ], ])
res_2 = np.array([[1, 2, 3, 4, 5, 6], ])
res_3 = np.array([[1, 2, 3, 4, 5, 6],
[2,... | def test_regrid_variable_TDStoS(get_s_depth): |
Next line prediction: <|code_start|>
Just for tests. All it does is add a few expected attributes
This will need to be updated when the function is changed.
"""
must_have = ['dtype', 'shape', 'ndim', '__len__', '__getitem__', '__getattribute__']
# pretty kludgy way to do this..
def __new__(cl... | result = util.asarraylike(lst) |
Predict the next line after this snippet: <|code_start|> 'simple' is very, very slow for large grids.
:type simple: str
This version utilizes the CellTree data structure.
"""
points = np.asarray(points, dtype=np.float64)
just_one = (points.ndim ... | if point_in_tri(f, point): |
Next line prediction: <|code_start|> :param filename: full path to file to save to.
:param format: format to save -- 'netcdf3' or 'netcdf4'
are the only options at this point.
"""
self.save(filename, format='netcdf4')
def save(self, filepath, format='netcdf4'... | nclocal = get_writable_dataset(filepath) |
Given the code snippet: <|code_start|>"""
Created on Apr 7, 2015
@author: ayan
"""
from __future__ import (absolute_import, division, print_function)
def test_xyz_axis_parse():
xyz = 'X: NMAX Y: MMAXZ Z: KMAX'
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from gridded.p... | result = parse_axes(xyz) |
Given the code snippet: <|code_start|>from __future__ import (absolute_import, division, print_function)
def test_xyz_axis_parse():
xyz = 'X: NMAX Y: MMAXZ Z: KMAX'
result = parse_axes(xyz)
expected = ('NMAX', 'MMAXZ', 'KMAX')
assert result == expected
def test_xy_axis_parse():
xy = 'X: xi_psi... | result = parse_padding(pad_1, grid_topology) |
Based on the snippet: <|code_start|> assert sub_dim == expected_sub_dim
assert dim == expected_dim
def test_one_padding_type(parse_pad):
grid_topology, pad_1, pad_2, pad_no = parse_pad
result = parse_padding(pad_1, grid_topology)
expected_len = 1
padding_datum_0 = result[0]
padding_type = p... | direction = parse_vector_axis(standard_name_1) |
Continue the code snippet: <|code_start|># is the same as `two_triangles`. If so use that.
# Some sample grid data: about the simplest triangle grid possible.
# 4 nodes, two triangles, five edges.
nodes = [(0.1, 0.1),
(2.1, 0.1),
(1.1, 2.1),
(3.1, 2.1)]
node_lon = np.array(nodes)[:, 0]
nod... | grid = UGrid(nodes=nodes, |
Based on the snippet: <|code_start|>node_lat = np.array(nodes)[:, 1]
faces = [(0, 1, 2),
(1, 3, 2)]
edges = [(0, 1),
(1, 3),
(3, 2),
(2, 0),
(1, 2)]
boundaries = [(0, 1),
(0, 2),
(1, 3),
(2, 3)]
def test_full_set():
grid = ... | assert grid.faces.dtype == IND_DT |
Here is a snippet: <|code_start|>node_lon = np.array(nodes)[:, 0]
node_lat = np.array(nodes)[:, 1]
faces = [(0, 1, 2),
(1, 3, 2)]
edges = [(0, 1),
(1, 3),
(3, 2),
(2, 0),
(1, 2)]
boundaries = [(0, 1),
(0, 2),
(1, 3),
(2, 3)]
de... | assert grid.nodes.dtype == NODE_DT |
Next line prediction: <|code_start|>#!/usr/bin/env python
"""
Tests for testing a UGrid file read.
We really need a **lot** more sample data files...
"""
from __future__ import (absolute_import, division, print_function)
UGrid = ugrid.UGrid
files = os.path.join(os.path.split(__file__)[0], 'files')
def test_s... | with chdir(files): |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
"""
Tests for testing a UGrid file read.
We really need a **lot** more sample data files...
"""
from __future__ import (absolute_import, division, print_function)
<|code_end|>
, predict the next line using imports from ... | UGrid = ugrid.UGrid |
Given the code snippet: <|code_start|>Tests for testing a UGrid file read.
We really need a **lot** more sample data files...
"""
from __future__ import (absolute_import, division, print_function)
UGrid = ugrid.UGrid
files = os.path.join(os.path.split(__file__)[0], 'files')
def test_simple_read():
"""Can ... | names = read_netcdf.find_mesh_names(nc) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
"""
Testing of various utilities to manipulate the grid.
"""
from __future__ import (absolute_import, division, print_function)
def test_build_face_face_connectivity_small(two_triangles):
ugrid = two_triangles
ugrid.build_face_f... | def test_build_face_face_connectivity_big(twenty_one_triangles): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
Tests for adding a data attribute to a UGrid object.
"""
from __future__ import (absolute_import, division, print_function)
# from gridded.pyugrid import UVar
pytestmark = pytest.mark.skipif(True, reason="gridded does not support UVars anymore")
... | def test_add_all_data(two_triangles): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
Tests for the UVar object
"""
from __future__ import (absolute_import, division, print_function)
# pytestmark = pytest.mark.skipif(True, reason="gridded does not support UVars anymore")
test_files = os.path.join(os.path.dirname(__file__), 'files')
... | d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0]) |
Predict the next line after this snippet: <|code_start|>
def test_delete_data():
d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0])
del d.data
assert np.array_equal(d.data, [])
def test_str():
d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0])
assert str(d) == ('UVar object... | with chdir(test_files): |
Given the code snippet: <|code_start|>"""Test file for building the face_edge_connectivity"""
def test_build_face_edge_connectivity():
faces = [[0, 1, 2], [1, 2, 3]]
edges = [[0, 1], [1, 2], [2, 0], [2, 3], [3, 1]]
nodes = [1, 2, 3, 4]
<|code_end|>
, generate the next line using the imports in this file:... | grid = ugrid.UGrid( |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
Testing of code to find nodes.
Currently only nearest neighbor.
"""
from __future__ import (absolute_import, division, print_function)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from .utilities import ... | def test_locate_node(twenty_one_triangles): |
Predict the next line for this snippet: <|code_start|>from __future__ import (absolute_import, division, print_function)
def test_point_in_tri():
test_datasets = [
{
'triangle': np.array([[0., 0.], [1., 0.], [0., 1.]]),
'points_inside': [np.array([0.1, 0.1]), np.array([0.3, 0.3])... | assert point_in_tri(dataset['triangle'], point) |
Given snippet: <|code_start|>
def get_test_file_dir():
"""
returns the test file dir path
"""
test_file_dir = os.path.join(os.path.dirname(__file__), 'test_data')
return test_file_dir
def get_temp_test_file(filename):
"""
returns the path to a temporary test file.
If it exists, it wil... | get_datafile(filepath) |
Given snippet: <|code_start|>Assorted utilities useful for the tests.
"""
from __future__ import (absolute_import, division, print_function)
@pytest.fixture
def two_triangles():
"""
Returns a simple triangular grid: 4 nodes, two triangles, five edges.
"""
nodes = [(0.1, 0.1),
(2.1, ... | return ugrid.UGrid(nodes=nodes, faces=faces, edges=edges) |
Predict the next line for this snippet: <|code_start|> Use regex expressions to break apart an
attribute string containing padding types
for each variable with a cf_role of
'grid_topology'.
Padding information is returned within a named tuple
for each node dimension of an edge, face, or ve... | grid_padding = GridPadding(mesh_topology_var=mesh_topology_var,
|
Given the code snippet: <|code_start|>
@pytest.fixture
def check_element():
"""
FIXME: These tests only check for a True return and not for correctness.
"""
a = [7, 7, 7, 7]
b = [7, 8, 9, 10]
return a, b
def test_list_with_identical_elements(check_element):
a, b = check_element
resul... | result = calculate_bearing(point_1, point_2) |
Next line prediction: <|code_start|>def test_bearing_calculation():
points = np.array([(-93.51105439, 11.88846735),
(-93.46607342, 11.90917952)])
point_1 = points[:-1, :]
point_2 = points[1:, :]
result = calculate_bearing(point_1, point_2)
expected = 64.7947
np.testing.ass... | angle_from_true_east = calculate_angle_from_true_east(bearing_start_points, bearing_end_points) # noqa |
Given the code snippet: <|code_start|> a, b, c = intersection_data
result = does_intersection_exist(a, c)
assert result is False
def test_pair_arrays():
a1, a2, a3 = (1, 2), (3, 4), (5, 6)
b1, b2, b3 = (10, 20), (30, 40), (50, 60)
a = np.array([a1, a2, a3])
b = np.array([b1, b2, b3])
re... | result = check_element_equal(a) |
Given the code snippet: <|code_start|>"""
Created on Mar 23, 2015
@author: ayan
"""
from __future__ import (absolute_import, division, print_function)
@pytest.fixture
def intersection_data():
a = (718, 903, 1029, 1701)
b = (718, 828)
c = (15, 20)
return a, b, c
def test_intersect_exists(inters... | result = does_intersection_exist(a, b) |
Given the code snippet: <|code_start|>
@pytest.fixture
def intersection_data():
a = (718, 903, 1029, 1701)
b = (718, 828)
c = (15, 20)
return a, b, c
def test_intersect_exists(intersection_data):
a, b, c = intersection_data
result = does_intersection_exist(a, b)
assert result
def tes... | result = pair_arrays(a, b) |
Given the code snippet: <|code_start|>
class sampleAdmin(admin.ModelAdmin):
fields = ("QCStatus","overrepresentedSequences","sampleReference",\
"sampleName", "readNumber","libraryReference","trimmed" )
list_display = ("sampleReference","sampleName","readNumber","run","lane","project",\
... | admin.site.register(Sample, sampleAdmin) |
Given snippet: <|code_start|>
class sampleAdmin(admin.ModelAdmin):
fields = ("QCStatus","overrepresentedSequences","sampleReference",\
"sampleName", "readNumber","libraryReference","trimmed" )
list_display = ("sampleReference","sampleName","readNumber","run","lane","project",\
"l... | admin.site.register(Project, projectAdmin) |
Continue the code snippet: <|code_start|>
class sampleAdmin(admin.ModelAdmin):
fields = ("QCStatus","overrepresentedSequences","sampleReference",\
"sampleName", "readNumber","libraryReference","trimmed" )
list_display = ("sampleReference","sampleName","readNumber","run","lane","project",\
... | admin.site.register(Run, runAdmin) |
Using the snippet: <|code_start|>
logger = logging.getLogger('website')
class Communicator(object):
"""
The Communicator with the backend api server.
"""
client = None
def __init__(self, cookies={}):
self.client = requests.session()
for name, value in cookies.items():
... | url = get_api_server_url('/api/auth/login/') |
Continue the code snippet: <|code_start|> return False
def download_from_volume(self, project_id, volume_id):
"""
Download data from volume with id volume_id.
"""
url = get_api_server_url('/api/projects/{}/volumes/{}/download/'
.format(project_id, volume_id))
... | url = get_url_of_monitor_iframe(type, namespace, pod_name) |
Based on the snippet: <|code_start|>
logger = logging.getLogger('hummer')
class ImageBuilder(object):
"""
ImageBuilder is to build image. One way is to use image file directly, the
other way is to use Dockerfile to build image.
is_image: 0|1|2, 0 represents build file, 1 represents image file,
... | self.image = Image.objects.get(id=image_id) |
Next line prediction: <|code_start|> logger.info('There is no image called %s on docker host %s' %
(image_complete_name, base_url))
return None
logger.info('Image %s on docker host %s has been deleted.' %
(image_complete_name, base_url))
def _push_ima... | digest = fetch_digest_from_response(response[-1]) |
Continue the code snippet: <|code_start|>
def __init__(self, build_file, is_image, dockerfile, image_id,
old_image_name, old_image_version):
self.build_file = build_file
self.is_image = is_image
self.dockerfile = dockerfile
self.image = Image.objects.get(id=image_id)
... | docker_host = get_optimal_docker_host() |
Using the snippet: <|code_start|>
# TODO: create image on docker host
base_url = self._get_docker_host_base_url(docker_host)
image_name = self._get_image_name()
if self.is_image == 1:
token = self._load_image_on_docker_host(base_url, self.build_file,
image_na... | remove_file_from_disk(self.build_file) |
Predict the next line for this snippet: <|code_start|>
digest = self._push_image_to_registry(base_url, image_name,
self.image.version, token)
if not digest:
logger.error("Push image from docker host to registry failed")
self._update_image_status(status="failed")
... | scheduler = DockerSchedulerFactory.get_scheduler() |
Given the following code snippet before the placeholder: <|code_start|>
class DockerSchedulerTestCase(unittest.TestCase):
def setUp(self):
self.scheduler = DockerScheduler('192.168.0.10', 4001)
def tearDown(self):
self.scheduler = None
def test_docker_hosts(self):
hosts = self.sc... | scheduler1 = DockerSchedulerFactory.get_scheduler() |
Given snippet: <|code_start|>#
# Unit tests for the two quetzal classes.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with open("stories/curses.z5", "rb") as story... | return zmachine.ZMachine(story_image, ui, debugmode=True) |
Based on the snippet: <|code_start|>#
# Unit tests for the two quetzal classes.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with open("stories/curses.z5", "rb") a... | ui = trivialzui.create_zui() |
Continue the code snippet: <|code_start|>#
# Unit tests for the two quetzal classes.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with open("stories/curses.z5", "r... | writer = quetzal.QuetzalWriter(machine) |
Using the snippet: <|code_start|>#!/usr/bin/env python
def usage():
print("""Usage: %s <story file>
Run a Z-Machine story under ZVM.
""" % sys.argv[0])
sys.exit(1)
def main():
if len(sys.argv) != 2:
usage()
story_file = sys.argv[1]
if not os.path.isfile(story_file):
print("%s is ... | machine = zmachine.ZMachine(story_image, |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
def usage():
print("""Usage: %s <story file>
Run a Z-Machine story under ZVM.
""" % sys.argv[0])
sys.exit(1)
def main():
if len(sys.argv) != 2:
usage()
story_file = sys.argv[1]
if not os.path.isfile(story_file):
... | ui=trivialzui.create_zui(), |
Based on the snippet: <|code_start|>#
# Unit tests for the bitfield class.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
class BitFieldTests(TestCase):
def testCreateInt(self):
for i in range(0,1024,3):
<|code_end|>
, predict the immediate... | bf = BitField(i) |
Using the snippet: <|code_start|> pass
class ZStackPopError(ZStackError):
"Nothing to pop from stack!"
pass
# Helper class used by ZStackManager; a 'routine' object which
# includes its own private stack of data.
class ZRoutine(object):
def __init__(self, start_addr, return_addr, zmem, args,
lo... | log("num local vars is %d" % num_local_vars) |
Given the following code snippet before the placeholder: <|code_start|>#
# Unit tests for the Example class.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with ope... | return zmachine.ZMachine(story_image, ui, debugmode=True) |
Using the snippet: <|code_start|>#
# Unit tests for the Example class.
#
# For the license of this file, please consult the LICENSE file in the
# root directory of this distribution.
#
def make_zmachine():
# We use Graham Nelson's 'curses' game for our unittests.
with open("stories/curses.z5", "rb") as story:... | ui = trivialzui.create_zui() |
Using the snippet: <|code_start|>
class TeamAuthenticationForm(AuthenticationForm):
"""
Custom variant of the login form that replaces "Username" with "Team name".
"""
username = forms.CharField(max_length=254, label=_('Team name'))
class FormalPasswordResetForm(PasswordResetForm):
"""
Cust... | context['competition_name'] = GameControl.get_instance().competition_name |
Using the snippet: <|code_start|>
class InlineTeamAdmin(admin.StackedInline):
"""
InlineModelAdmin for Team objects. Primarily designed to be used within a UserAdmin.
"""
model = Team
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from django.utils... | form = AdminTeamForm |
Here is a snippet: <|code_start|>
def registration_open_required(view):
"""
View decorator which prohibits access to the decorated view if registration is closed from the
GameControl object.
"""
@wraps(view)
def func(request, *args, **kwargs):
<|code_end|>
. Write the next line using the cur... | if not GameControl.get_instance().registration_open: |
Using the snippet: <|code_start|>
class CTFAdminSite(admin.AdminSite):
"""
Custom variant of the AdminSite which replaces the default headers and titles.
"""
index_title = _('Administration home')
# Declare this lazily through a classproperty in order to avoid a circular dependency when creating... | competition_name=GameControl.get_instance().competition_name) |
Given the following code snippet before the placeholder: <|code_start|>
class CTFAdminSite(admin.AdminSite):
"""
Custom variant of the AdminSite which replaces the default headers and titles.
"""
index_title = _('Administration home')
# Declare this lazily through a classproperty in order to avo... | return format_lazy(_('{competition_name} administration'), |
Next line prediction: <|code_start|> team_entry = {
'id': team.user.pk,
'nop': team.nop_team,
'name': team.user.username,
'ticks': [],
}
if team.image:
team_entry['image'] = team.image.url
team_entry['thumbnail'] = team.image... | @registration_closed_required |
Here is a snippet: <|code_start|>
def _gen_image_name(instance, _):
"""
Returns the upload path (relative to settings.MEDIA_ROOT) for the specified Team's image.
"""
# Must "return a Unix-style path (with forward slashes)"
return 'team-images' + '/' + str(instance.user.id) + '.png'
class Team(m... | image = ThumbnailImageField(upload_to=_gen_image_name, blank=True) |
Here is a snippet: <|code_start|>
def game_control(_):
"""
Context processor which adds information from the Game Control table to the context.
"""
control_instance = scoring_models.GameControl.get_instance()
return {
'competition_name': control_instance.competition_name,
'regist... | categories = flatpages_models.Category.objects.all() |
Given the code snippet: <|code_start|> return redirect(settings.HOME_URL)
else:
delete_form = forms.DeleteForm(user=request.user, prefix='delete')
return render(request, 'edit_team.html', {
'user_form': user_form,
'team_form': team_form,
'delete_form': delete_form
... | if not email_token_generator.check_token(user, token): |
Given the code snippet: <|code_start|> url(r'^auth/change-password/$',
auth_views.PasswordChangeView.as_view(template_name='password_change.html',
success_url=reverse_lazy('edit_team')),
name='password_change'
),
url(r'^auth/reset-password/$',
... | scoring_views.teams_json, |
Given the code snippet: <|code_start|> url(r'^competition/scoreboard-ctftime\.json$',
scoring_views.scoreboard_json_ctftime,
name='scoreboard_json_ctftime'
),
url(r'^competition/status/$',
scoring_views.service_status,
name='service_status'
),
url(r'^competition/status... | flatpages_views.flatpage, |
Predict the next line for this snippet: <|code_start|> ),
url(r'^competition/scoreboard\.json$',
scoring_views.scoreboard_json,
name='scoreboard_json'
),
url(r'^competition/scoreboard-ctftime\.json$',
scoring_views.scoreboard_json_ctftime,
name='scoreboard_json_ctftime'
... | url(r'^admin/', admin_site.urls), |
Based on the snippet: <|code_start|>
# pylint: disable=invalid-name, bad-continuation
urlpatterns = [
url(r'^auth/register/$',
registration_views.register,
name='register'
), # noqa
url(r'^auth/confirm-email/$',
registration_views.confirm_email,
name='confirm_email'
... | auth_views.LoginView.as_view(template_name='login.html', authentication_form=TeamAuthenticationForm), |
Here is a snippet: <|code_start|> url(r'^auth/confirm-email/$',
registration_views.confirm_email,
name='confirm_email'
),
url(r'^auth/edit-team/$',
registration_views.edit_team,
name='edit_team'
),
url(r'^auth/delete-team/$',
registration_views.delete_team,
... | form_class=FormalPasswordResetForm), |
Given snippet: <|code_start|> Sends an email containing the address confirmation link to the user associated with this form. As it
requires a User instance, it should only be called after the object has initially been saved.
Args:
request: The HttpRequest from which this function is ... | model = Team |
Predict the next line after this snippet: <|code_start|> competition_name = scoring_models.GameControl.get_instance().competition_name
context = {
'competition_name': competition_name,
'protocol': 'https' if request.is_secure() else 'http',
'domain': get_current_site(... | 'image': ClearableThumbnailImageInput |
Based on the snippet: <|code_start|> been changed. It should stay that way until the address is confirmed.
"""
user = super().save(commit=False)
if self.cleaned_data.get('password'):
user.set_password(self.cleaned_data['password'])
if 'email' in self.changed_data:
... | 'token': email_token_generator.make_token(self.instance) |
Based on the snippet: <|code_start|>
def send_confirmation_mail(self, request):
"""
Sends an email containing the address confirmation link to the user associated with this form. As it
requires a User instance, it should only be called after the object has initially been saved.
Args... | country = forms.ChoiceField(choices=[(name, name) for name in get_country_names()]) |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
"""
jinja2schema.util
~~~~~~~~~~~~~~~~~
"""
def _format_attrs(var):
return (u'label={0.label}, required={0.required}, '
u'constant={0.constant}, linenos={0.linenos}, may_be_d={0.may_be_defined}, '
u'c_as... | if isinstance(var, (Dictionary, Tuple, List)): |
Based on the snippet: <|code_start|>def _indent(lines, spaces):
indent = ' ' * spaces
return [indent + line for line in lines]
def _debug_repr(var):
rv = []
if isinstance(var, (Dictionary, Tuple, List)):
if isinstance(var, Dictionary):
rv.append('Dictionary({}, {{'.format(_format_a... | elif isinstance(var, Scalar): |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
"""
jinja2schema.util
~~~~~~~~~~~~~~~~~
"""
def _format_attrs(var):
return (u'label={0.label}, required={0.required}, '
u'constant={0.constant}, linenos={0.linenos}, may_be_d={0.may_be_defined}, '
u'c_as... | if isinstance(var, (Dictionary, Tuple, List)): |
Predict the next line after this snippet: <|code_start|> return [indent + line for line in lines]
def _debug_repr(var):
rv = []
if isinstance(var, (Dictionary, Tuple, List)):
if isinstance(var, Dictionary):
rv.append('Dictionary({}, {{'.format(_format_attrs(var)))
content = ... | elif isinstance(var, Unknown): |
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8
"""
jinja2schema.util
~~~~~~~~~~~~~~~~~
"""
def _format_attrs(var):
return (u'label={0.label}, required={0.required}, '
u'constant={0.constant}, linenos={0.linenos}, may_be_d={0.may_be_defined}, '
u'c_as... | if isinstance(var, (Dictionary, Tuple, List)): |
Next line prediction: <|code_start|># coding: utf-8
def test_to_json_schema():
struct = Dictionary({
'list': List(
Tuple((
Dictionary({
<|code_end|>
. Use current file imports:
(from jinja2schema import core
from jinja2schema.model import Dictionary, Scalar, List, Unknown, Tup... | 'field': Scalar(label='field', linenos=[3]), |
Next line prediction: <|code_start|># coding: utf-8
def test_to_json_schema():
struct = Dictionary({
'list': List(
Tuple((
Dictionary({
'field': Scalar(label='field', linenos=[3]),
}, label='a', linenos=[3]),
Scalar(label='b',... | 'x': Unknown(may_be_defined=True), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.