Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|>
@pytest.mark.parametrize('pattern,result', [
('/', [('exact', '/')]),
('/{{a}}', [('exact', '/{a}')]),
('{a}', [('placeholder', 'a')]),
('a/{a}', [('exact', 'a/'), ('placeholder', 'a')]),
('{a}/a', [('placeholder', 'a'), ('exact', '/a')]),
<|code_end|>
, determine the next line of code. You have imports:
import asyncio
import pytest
from collections import namedtuple
from .route import parse, MatcherEntry, Segment, SegmentType, Route, \
compile, roundto8
and context (class names, function names, or code) available:
# Path: src/japronto/router/route.py
# class RouteNotFoundException(Exception):
# class Route:
# class SegmentType(IntEnum):
# def __init__(self, pattern, handler, methods):
# def __repr__(self):
# def describe(self):
# def __eq__(self, other):
# def parse(pattern):
# def roundto8(v):
# def padto8(data):
# def compile(route):
# def compile_all(routes):
# EXACT = 0
# PLACEHOLDER = 1
. Output only the next line. | ('{a}/{{a}}', [('placeholder', 'a'), ('exact', '/{a}')]), |
Given snippet: <|code_start|> segments.append((typ, data))
methods = buffer[offset:offset + methods_len].strip().decode('ascii') \
.split()
return DecodedRoute(
route_id, handler_id, coro_func, simple,
placeholder_cnt, segments, methods)
def handler():
pass
async def coro():
# needs to have await to prevent being promoted to function
await asyncio.sleep(1)
@pytest.mark.parametrize('route', [
Route('/', handler, []),
Route('/', coro, ['GET']),
Route('/test/{hi}', handler, []),
Route('/test/{hi}', coro, ['POST']),
Route('/tést', coro, ['POST'])
], ids=Route.describe)
def test_compile(route):
decompiled = decompile(compile(route))
assert decompiled.route_id == id(route)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import pytest
from collections import namedtuple
from .route import parse, MatcherEntry, Segment, SegmentType, Route, \
compile, roundto8
and context:
# Path: src/japronto/router/route.py
# class RouteNotFoundException(Exception):
# class Route:
# class SegmentType(IntEnum):
# def __init__(self, pattern, handler, methods):
# def __repr__(self):
# def describe(self):
# def __eq__(self, other):
# def parse(pattern):
# def roundto8(v):
# def padto8(data):
# def compile(route):
# def compile_all(routes):
# EXACT = 0
# PLACEHOLDER = 1
which might include code, classes, or functions. Output only the next line. | assert decompiled.handler_id == id(route.handler) |
Here is a snippet: <|code_start|>
return DecodedRoute(
route_id, handler_id, coro_func, simple,
placeholder_cnt, segments, methods)
def handler():
pass
async def coro():
# needs to have await to prevent being promoted to function
await asyncio.sleep(1)
@pytest.mark.parametrize('route', [
Route('/', handler, []),
Route('/', coro, ['GET']),
Route('/test/{hi}', handler, []),
Route('/test/{hi}', coro, ['POST']),
Route('/tést', coro, ['POST'])
], ids=Route.describe)
def test_compile(route):
decompiled = decompile(compile(route))
assert decompiled.route_id == id(route)
assert decompiled.handler_id == id(route.handler)
assert decompiled.coro_func == asyncio.iscoroutinefunction(route.handler)
assert not decompiled.simple
assert decompiled.placeholder_cnt == route.placeholder_cnt
<|code_end|>
. Write the next line using the current file imports:
import asyncio
import pytest
from collections import namedtuple
from .route import parse, MatcherEntry, Segment, SegmentType, Route, \
compile, roundto8
and context from other files:
# Path: src/japronto/router/route.py
# class RouteNotFoundException(Exception):
# class Route:
# class SegmentType(IntEnum):
# def __init__(self, pattern, handler, methods):
# def __repr__(self):
# def describe(self):
# def __eq__(self, other):
# def parse(pattern):
# def roundto8(v):
# def padto8(data):
# def compile(route):
# def compile_all(routes):
# EXACT = 0
# PLACEHOLDER = 1
, which may include functions, classes, or code. Output only the next line. | assert decompiled.segments == route.segments |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.mark.parametrize('pattern,result', [
('/', [('exact', '/')]),
('/{{a}}', [('exact', '/{a}')]),
('{a}', [('placeholder', 'a')]),
('a/{a}', [('exact', 'a/'), ('placeholder', 'a')]),
('{a}/a', [('placeholder', 'a'), ('exact', '/a')]),
('{a}/{{a}}', [('placeholder', 'a'), ('exact', '/{a}')]),
('{a}/{b}', [('placeholder', 'a'), ('exact', '/'), ('placeholder', 'b')])
])
def test_parse(pattern, result):
assert parse(pattern) == result
@pytest.mark.parametrize('pattern,error', [
('{a', 'Unbalanced'),
('{a}/{b', 'Unbalanced'),
('{a}a', 'followed by'),
('{a}/{a}', 'Duplicate')
])
def test_parse_error(pattern, error):
with pytest.raises(ValueError) as info:
parse(pattern)
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import pytest
from collections import namedtuple
from .route import parse, MatcherEntry, Segment, SegmentType, Route, \
compile, roundto8
and context including class names, function names, and sometimes code from other files:
# Path: src/japronto/router/route.py
# class RouteNotFoundException(Exception):
# class Route:
# class SegmentType(IntEnum):
# def __init__(self, pattern, handler, methods):
# def __repr__(self):
# def describe(self):
# def __eq__(self, other):
# def parse(pattern):
# def roundto8(v):
# def padto8(data):
# def compile(route):
# def compile_all(routes):
# EXACT = 0
# PLACEHOLDER = 1
. Output only the next line. | assert error in info.value.args[0] |
Here is a snippet: <|code_start|>
assert lines[-1] == 'Termination request received'
@pytest.mark.parametrize('num', range(1, 3))
def test_pipelined(num, connect, server_terminate):
connections = []
for _ in range(num):
con = connect()
connections.append(con)
con.putrequest('GET', '/sleep/1')
con.endheaders()
lines = server_terminate()
assert '{} connections busy, read-end closed'.format(num) in lines
assert not any(l.startswith('Forcefully killing') for l in lines)
assert all(c.getresponse().status == 200 for c in connections)
@pytest.mark.parametrize('num', range(1, 3))
def test_pipelined_timeout(num, connect, server_terminate):
connections = []
for _ in range(num):
con = connect()
connections.append(con)
con.putrequest('GET', '/sleep/10')
<|code_end|>
. Write the next line using the current file imports:
import pytest
import subprocess
import time
import integration_tests.common
from misc import client
and context from other files:
# Path: misc/client.py
# def readline(sock):
# def readexact(sock, size):
# def __init__(self, sock):
# def read_status_line(self):
# def read_headers(self):
# def encoding(self):
# def read_body(self):
# def json(self):
# def __init__(self, addr):
# def maybe_connect(self):
# def putline(self, line=None):
# def putclose(self, data):
# def putrequest(self, method, path, query_string=None):
# def request(self, method, path, query_string=None, headers=None,
# body=None):
# def putheader(self, name, value):
# def endheaders(self, body=None):
# def getresponse(self):
# def close(self):
# def chunked_encoder(data):
# class Response:
# class Connection:
, which may include functions, classes, or code. Output only the next line. | con.endheaders() |
Predict the next line for this snippet: <|code_start|> line_getter.start()
connection.putclose(request_line)
assert line_getter.wait() == 'incomplete_headers'
full_header = 'X-Header: asd'
def make_truncated_header(cut):
return full_header[:-cut]
st_header_cut = st.integers(min_value=5, max_value=len(full_header) - 1)
st_header_line = st.builds(make_truncated_header, st_header_cut)
@given(header_line=st_header_line)
@settings(verbosity=Verbosity.verbose, max_examples=20)
def test_truncated_header(line_getter, connect, header_line):
connection = connect()
line_getter.start()
connection.putline(full_request_line)
connection.putline(header_line)
connection.putline()
assert line_getter.wait() == 'malformed_headers'
response = connection.getresponse()
<|code_end|>
with the help of current file imports:
import pytest
import subprocess
import queue
import threading
import integration_tests.common
from hypothesis import given, strategies as st, settings, Verbosity
from functools import partial
from misc import client
and context from other files:
# Path: misc/client.py
# def readline(sock):
# def readexact(sock, size):
# def __init__(self, sock):
# def read_status_line(self):
# def read_headers(self):
# def encoding(self):
# def read_body(self):
# def json(self):
# def __init__(self, addr):
# def maybe_connect(self):
# def putline(self, line=None):
# def putclose(self, data):
# def putrequest(self, method, path, query_string=None):
# def request(self, method, path, query_string=None, headers=None,
# body=None):
# def putheader(self, name, value):
# def endheaders(self, body=None):
# def getresponse(self):
# def close(self):
# def chunked_encoder(data):
# class Response:
# class Connection:
, which may contain function names, class names, or code. Output only the next line. | assert response.status == 400 |
Continue the code snippet: <|code_start|>
def print_request(request):
body = request['body']
if body:
if isinstance(body, list):
body = '{} chunks'.format(len(body))
else:
if len(body) > 32:
body = body[:32] + b'...'
print(repr(request['method']), repr(request['path']),
repr(request['query_string']), body)
def generate_request(*, method=None, path=None, query_string=None,
headers=None, body=None, size_k=None):
request = {}
request['method'] = makeval(method, st.method, 'GET')
request['path'] = makeval(path, st.path, '/')
request['query_string'] = makeval(query_string, st.query_string)
request['headers'] = makeval(headers, st.headers)
request['body'] = generate_body(makeval(body, st.body), size_k)
return request
def generate_combinations(reverse=False):
props = ['method', 'path', 'query_string', 'headers', 'body']
sizes = [None, 8, 32, 64]
if reverse:
<|code_end|>
. Use current file imports:
from integration_tests import strategies as st
from hypothesis.strategies import SearchStrategy
and context (classes, functions, or code) from other files:
# Path: integration_tests/strategies.py
. Output only the next line. | props = reversed(props) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class StationProfileTest(unittest.TestCase):
def test_station_profile(self):
sp = StationProfile()
sp.name = "Profile Station"
sp.location = sPoint(-77, 33)
sp.uid = "1234"
sp.set_property("authority", "IOOS")
# add a sequence of profiles
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.station_profile import StationProfile
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
and context including class names, function names, and sometimes code from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/station_profile.py
# class StationProfile(ProfileCollection):
# """
# A collection of Profiles at a single location.
#
# This mimics the Station class API, they should likely be merged somehow.
# """
# def __init__(self, **kwargs):
# super(StationProfile, self).__init__(**kwargs)
#
# self._type = "timeSeriesProfile"
# self._properties = {}
# self._location = None
# self.uid = None
# self.name = None
# self.description = None
#
# @property
# def location(self):
# return self._location
#
# @location.setter
# def location(self, value):
# self._location = value
#
# # Sets the location of every Profile in this station if it is not already set
# for profile in self._elements:
# if profile.location is None:
# profile.location == value
#
# def get_properties(self):
# return self._properties
#
# def get_property(self, prop):
# return self._properties.get(prop, None)
#
# def set_property(self, prop, value):
# self._properties[prop] = value
#
# def get_unique_members(self):
# all_members = [pt.members for prof in self._elements
# for pt in prof._elements]
#
# keys = ["name", "description", "standard", "units"]
# mwhat = []
# for mg in all_members:
# for m in mg:
# mwhat.append( { key: m[key] for key in keys if key in m } )
#
# # Now unique them on name
# mwhat = { x['name']:x for x in mwhat }.values()
#
# return mwhat
#
# def calculate_bounds(self):
# """
# Calculate the time_range, depth_range, bbox, and size of this collection.
# Will scan all data.
# Ensures that .size, .bbox and .time_range return non-null.
#
# If the collection already knows its bbox; time_range; and/or size,
# they are recomputed.
# """
# # tell all contained profiles to calculate their bounds
# map(lambda x: x.calculate_bounds(), self._elements)
#
# # @TODO size is just number of timesteps?
# self.size = len(self._elements)
#
# # bbox is just this point
# self.bbox = MultiPoint([self.location, self.location]).envelope
#
# time_set = set()
# map(time_set.add, AsaList.flatten([p.time for p in self._elements]))
# self.time_range = sorted(list(time_set))
#
# depth_set = set()
# map(depth_set.add, AsaList.flatten([p.depth_range for p in self._elements]))
# self.depth_range = sorted(list(depth_set))
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
. Output only the next line. | for y in xrange(3): |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class StationProfileTest(unittest.TestCase):
def test_station_profile(self):
sp = StationProfile()
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.station_profile import StationProfile
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
and context (functions, classes, or occasionally code) from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/station_profile.py
# class StationProfile(ProfileCollection):
# """
# A collection of Profiles at a single location.
#
# This mimics the Station class API, they should likely be merged somehow.
# """
# def __init__(self, **kwargs):
# super(StationProfile, self).__init__(**kwargs)
#
# self._type = "timeSeriesProfile"
# self._properties = {}
# self._location = None
# self.uid = None
# self.name = None
# self.description = None
#
# @property
# def location(self):
# return self._location
#
# @location.setter
# def location(self, value):
# self._location = value
#
# # Sets the location of every Profile in this station if it is not already set
# for profile in self._elements:
# if profile.location is None:
# profile.location == value
#
# def get_properties(self):
# return self._properties
#
# def get_property(self, prop):
# return self._properties.get(prop, None)
#
# def set_property(self, prop, value):
# self._properties[prop] = value
#
# def get_unique_members(self):
# all_members = [pt.members for prof in self._elements
# for pt in prof._elements]
#
# keys = ["name", "description", "standard", "units"]
# mwhat = []
# for mg in all_members:
# for m in mg:
# mwhat.append( { key: m[key] for key in keys if key in m } )
#
# # Now unique them on name
# mwhat = { x['name']:x for x in mwhat }.values()
#
# return mwhat
#
# def calculate_bounds(self):
# """
# Calculate the time_range, depth_range, bbox, and size of this collection.
# Will scan all data.
# Ensures that .size, .bbox and .time_range return non-null.
#
# If the collection already knows its bbox; time_range; and/or size,
# they are recomputed.
# """
# # tell all contained profiles to calculate their bounds
# map(lambda x: x.calculate_bounds(), self._elements)
#
# # @TODO size is just number of timesteps?
# self.size = len(self._elements)
#
# # bbox is just this point
# self.bbox = MultiPoint([self.location, self.location]).envelope
#
# time_set = set()
# map(time_set.add, AsaList.flatten([p.time for p in self._elements]))
# self.time_range = sorted(list(time_set))
#
# depth_set = set()
# map(depth_set.add, AsaList.flatten([p.depth_range for p in self._elements]))
# self.depth_range = sorted(list(depth_set))
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
. Output only the next line. | sp.name = "Profile Station" |
Predict the next line after this snippet: <|code_start|> def test_station_profile(self):
sp = StationProfile()
sp.name = "Profile Station"
sp.location = sPoint(-77, 33)
sp.uid = "1234"
sp.set_property("authority", "IOOS")
# add a sequence of profiles
for y in xrange(3):
dt1 = datetime(2013, 1, 1, 12, 0, 10 * y)
prof1 = Profile()
prof1.location = sPoint(-77, 33)
prof1.time = dt1
# add a string of points going down in z
for x in xrange(5):
p1 = Point()
p1.time = dt1
p1.location = sPoint(-77, 33, -5 * x)
member1 = Member(value=30 - (2 * x), units='°C', name='Water Temperature', description='water temperature', standard='sea_water_temperature')
member2 = Member(value=80 + (2 * x), units='PSU', name='Salinity', description='salinity', standard='salinity')
p1.add_member(member1)
p1.add_member(member2)
prof1.add_element(p1)
sp.add_element(prof1)
<|code_end|>
using the current file's imports:
import unittest
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.station_profile import StationProfile
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
and any relevant context from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/station_profile.py
# class StationProfile(ProfileCollection):
# """
# A collection of Profiles at a single location.
#
# This mimics the Station class API, they should likely be merged somehow.
# """
# def __init__(self, **kwargs):
# super(StationProfile, self).__init__(**kwargs)
#
# self._type = "timeSeriesProfile"
# self._properties = {}
# self._location = None
# self.uid = None
# self.name = None
# self.description = None
#
# @property
# def location(self):
# return self._location
#
# @location.setter
# def location(self, value):
# self._location = value
#
# # Sets the location of every Profile in this station if it is not already set
# for profile in self._elements:
# if profile.location is None:
# profile.location == value
#
# def get_properties(self):
# return self._properties
#
# def get_property(self, prop):
# return self._properties.get(prop, None)
#
# def set_property(self, prop, value):
# self._properties[prop] = value
#
# def get_unique_members(self):
# all_members = [pt.members for prof in self._elements
# for pt in prof._elements]
#
# keys = ["name", "description", "standard", "units"]
# mwhat = []
# for mg in all_members:
# for m in mg:
# mwhat.append( { key: m[key] for key in keys if key in m } )
#
# # Now unique them on name
# mwhat = { x['name']:x for x in mwhat }.values()
#
# return mwhat
#
# def calculate_bounds(self):
# """
# Calculate the time_range, depth_range, bbox, and size of this collection.
# Will scan all data.
# Ensures that .size, .bbox and .time_range return non-null.
#
# If the collection already knows its bbox; time_range; and/or size,
# they are recomputed.
# """
# # tell all contained profiles to calculate their bounds
# map(lambda x: x.calculate_bounds(), self._elements)
#
# # @TODO size is just number of timesteps?
# self.size = len(self._elements)
#
# # bbox is just this point
# self.bbox = MultiPoint([self.location, self.location]).envelope
#
# time_set = set()
# map(time_set.add, AsaList.flatten([p.time for p in self._elements]))
# self.time_range = sorted(list(time_set))
#
# depth_set = set()
# map(depth_set.add, AsaList.flatten([p.depth_range for p in self._elements]))
# self.depth_range = sorted(list(depth_set))
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
. Output only the next line. | sp.calculate_bounds() |
Using the snippet: <|code_start|> month = random.randint(1,12)
dt = datetime(2012, month, 1, 0)
# Starting point
lat = random.randint(40,44)
lon = random.randint(-74,-70)
depth = 0
# 100 points in each trajectory
for l in xrange(0,100):
lat += random.uniform(-0.25,0.25)
lon += random.uniform(-0.25,0.25)
depth += random.randint(-4,4)
if depth < 0:
depth = 0
p1 = Point()
p1.location = sPoint(lon,lat,depth)
dt += timedelta(hours=1)
p1.time = dt
member1 = Member(value=random.uniform(30,40), unit='°C', name='Water Temperature', description='water temperature', standard='sea_water_temperature')
member2 = Member(value=random.uniform(80,100), unit='PSU', name='Salinity', description='salinity', standard='salinity')
p1.add_member(member1)
p1.add_member(member2)
tr.add_element(p1)
t_collection.add_element(tr)
<|code_end|>
, determine the next line of code. You have imports:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.trajectory import Trajectory
from paegan.cdm.dsg.collections.base.trajectory_collection import TrajectoryCollection
from paegan.utils.asalist import AsaList
and context (class names, function names, or code) available:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/trajectory.py
# class Trajectory(PointCollection):
# """
# A collection of Points along a 1 dimensional path, connected in space and time.
# The Points are ordered in time (in other words, the time dimension must
# increase monotonically along the trajectory).
# """
#
# def __init__(self, **kwargs):
# super(Trajectory,self).__init__(**kwargs)
# self._type = "Trajectory"
#
# def get_path(self):
# """
# Returns the Points along the trajectory
# """
# return map(lambda x: [x.location, x.time], self._elements)
#
# Path: paegan/cdm/dsg/collections/base/trajectory_collection.py
# class TrajectoryCollection(NestedPointCollection):
# """
# A collection of Trajectories
# """
#
# def __init__(self, **kwargs):
# super(TrajectoryCollection,self).__init__(**kwargs)
#
# Path: paegan/utils/asalist.py
# class AsaList(object):
#
# @classmethod
# def flatten(cls, lst):
# """
# Returns Generator of non-iterable values
# """
# for x in lst:
# if not isinstance(x, collections.Iterable):
# yield x
# else:
# for x in AsaList.flatten(x):
# yield x
. Output only the next line. | t_collection.calculate_bounds() |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class TrajectoryCollectionTest(unittest.TestCase):
def test_trajectory_collection(self):
t_collection = TrajectoryCollection()
# 20 trajectories
for x in xrange(0,20):
tr = Trajectory()
month = random.randint(1,12)
dt = datetime(2012, month, 1, 0)
# Starting point
<|code_end|>
, predict the next line using imports from the current file:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.trajectory import Trajectory
from paegan.cdm.dsg.collections.base.trajectory_collection import TrajectoryCollection
from paegan.utils.asalist import AsaList
and context including class names, function names, and sometimes code from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/trajectory.py
# class Trajectory(PointCollection):
# """
# A collection of Points along a 1 dimensional path, connected in space and time.
# The Points are ordered in time (in other words, the time dimension must
# increase monotonically along the trajectory).
# """
#
# def __init__(self, **kwargs):
# super(Trajectory,self).__init__(**kwargs)
# self._type = "Trajectory"
#
# def get_path(self):
# """
# Returns the Points along the trajectory
# """
# return map(lambda x: [x.location, x.time], self._elements)
#
# Path: paegan/cdm/dsg/collections/base/trajectory_collection.py
# class TrajectoryCollection(NestedPointCollection):
# """
# A collection of Trajectories
# """
#
# def __init__(self, **kwargs):
# super(TrajectoryCollection,self).__init__(**kwargs)
#
# Path: paegan/utils/asalist.py
# class AsaList(object):
#
# @classmethod
# def flatten(cls, lst):
# """
# Returns Generator of non-iterable values
# """
# for x in lst:
# if not isinstance(x, collections.Iterable):
# yield x
# else:
# for x in AsaList.flatten(x):
# yield x
. Output only the next line. | lat = random.randint(40,44) |
Here is a snippet: <|code_start|> a = np.arange(0,13,2)
a_avg = rm.average_adjacents(a)
# array([ 1., 3., 5., 7., 9., 11.])
result_test = np.arange(1,12,2)
assert np.allclose(a_avg,result_test)
def test_2D_row_average(self):
# array([[ 0, 2, 4, 6, 8],
# [10, 12, 14, 16, 18],
# [20, 22, 24, 26, 28]])
a = np.arange(0,30,2).reshape(3,5)
a_avg = rm.average_adjacents(a)
result_test = np.arange(1,30,2).reshape(3,5)[:,0:-1]
# array([[ 1, 3, 5, 7],
# [11, 13, 15, 17],
# [21, 23, 25, 27]])
assert np.allclose(a_avg,result_test)
def test_2D_column_average(self):
# array([[ 0, 10, 20],
# [ 2, 12, 22],
# [ 4, 14, 24],
# [ 6, 16, 26],
# [ 8, 18, 28]])
<|code_end|>
. Write the next line using the current file imports:
import unittest, os, math, netCDF4
import numpy as np
from paegan.roms import roms as rm
and context from other files:
# Path: paegan/roms/roms.py
# def shrink(a, b):
# def _uv_to_rho(u_data, v_data, angle, rho_x, rho_y):
# def uv_to_rho(file):
# def rotate_complex_by_angle(points,angles):
# def average_adjacents(a, by_column=False):
# def regrid_roms(newfile, filename, lon_new, lat_new, t=None, z=None):
# def __init__(self, data, by_column=False):
# def run(self):
# U = np.empty([rho_y,rho_x], dtype=complex )
# U[:] = np.nan
# class AverageAdjacents(threading.Thread):
, which may include functions, classes, or code. Output only the next line. | a = np.arange(0,30,2).reshape(3,5).T |
Given the following code snippet before the placeholder: <|code_start|>
data_path = "/data/lm/tests"
class TimevarTest(unittest.TestCase):
def setUp(self):
pass
@unittest.skipIf(not os.path.exists(os.path.join(data_path, "pws_L2_2012040100.nc")) or \
not os.path.exists(os.path.join(data_path, "ocean_avg_synoptic_seg22.nc")),
<|code_end|>
, predict the next line using imports from the current file:
import unittest, os, netCDF4, pytz
import numpy as np
from datetime import timedelta, datetime, tzinfo
from paegan.cdm.timevar import Timevar
from dateutil.parser import parse
and context including class names, function names, and sometimes code from other files:
# Path: paegan/cdm/timevar.py
# class Timevar(np.ndarray):
#
# _unit2sec={}
# _unit2sec['seconds'] = 1.0
# _unit2sec['minutes'] = 60.0
# _unit2sec['hours'] = 3600.0
# _unit2sec['days'] = 3600.0*24.0
# _unit2sec['weeks'] = 3600.0*24.0*7.0
# _unit2sec['years'] = 3600.0*24.0*365.242198781 #ref to udunits
#
# _sec2unit={}
# _sec2unit['seconds'] = 1.0
# _sec2unit['minutes'] = 1.0/60.0
# _sec2unit['hours'] = 1.0/3600.0
# _sec2unit['days'] = 1.0/(24.0*3600.0)
#
# def __new__(self, ncfile, name='time', units=None, tzinfo=None, **kwargs):
# if type(ncfile) is str:
# ncfile = netCDF4.Dataset(ncfile)
# self._nc = ncfile
#
# if self._nc.variables[name].ndim > 1:
# _str_data = self._nc.variables[name][:,:]
# if units == None:
# units = timevar_units
# dates = [parse(_str_data[i, :].tostring()) for i in range(len(_str_data[:,0]))]
# data = netCDF4.date2num(dates, units)
# else:
# data = self._nc.variables[name][:]
#
# if units == None:
# try:
# self._units = self._nc.variables[name].units
# except StandardError:
# self._units = units
# else:
# self._units = units
#
# if tzinfo == None:
# self._tzinfo = pytz.utc
# else:
# self._tzinfo = tzinfo
#
#
# units_split=self._units.split(' ',2)
# assert len(units_split) == 3 and units_split[1] == 'since', \
# 'units string improperly formatted\n' + self._units
# self.origin=parse(units_split[2])
#
# self._units = units_split[0].lower()
#
# # compatibility to CF convention v1.0/udunits names:
# if self._units in ['second','sec','secs','s']:
# self._units='seconds'
# if self._units in ['min','minute','mins']:
# self._units='minutes'
# if self._units in ['h','hs','hr','hrs','hour']:
# self._units='hours'
# if self._units in ['day','d','ds']:
# self._units='days'
#
# return data.view(self)
#
# def gettimestep(self):
# return self.seconds[1] - self.seconds[0]
#
# def nearest_index(self, dateo, select='nearest'):
# to = date2num(dateo)
# if select == 'nearest':
# try:
# return [np.where(abs(self.datenum-t) == np.nanmin(abs(self.datenum-t)))[0][0] for t in to]
# except TypeError:
# return [np.where(abs(self.datenum-to) == np.nanmin(abs(self.datenum-to)))[0][0]]
# elif select == 'before':
# try:
# return np.asarray([bisect.bisect(self.datenum, t)-1 for t in to])
# except TypeError:
# return np.asarray([bisect.bisect(self.datenum, to)-1])
#
# def nearest(self, dateo, select='nearest'):
# """
# find nearest model timestep,
# input and output are datetime objects
# """
# # one might choose the second value for
# #if len(self.nearest_index(dateo)) == 1:
# # res=self.jd[self.nearest_index(dateo, select)][0]
# #else:
# # res=self.jd[self.nearest_index(dateo, select)][1]
# return self.dates[self.nearest_index(dateo, select)][0]
#
# def get_seconds(self):
# fac = self._unit2sec[self._units] * self._sec2unit['seconds']
# return self*fac
#
# def get_minutes(self):
# fac = self._unit2sec[self._units] * self._sec2unit['minutes']
# return self*fac
#
# def get_hours(self):
# fac = self._unit2sec[self._units] * self._sec2unit['hours']
# return self*fac
#
# def get_days(self):
# fac = self._unit2sec[self._units] * self._sec2unit['days']
# return np.asarray(self,dtype='float64')*fac
#
# def get_dates(self):
# return num2date(self, self._units + " since " + self.origin.strftime('%Y-%m-%dT%H:%M:%S'), tzinfo=self._tzinfo)
#
# def get_datenum(self):
# return date2num(self.dates)
#
# datenum = property(get_datenum, None, doc="datenum in seconds since 1970-01-01")
# seconds = property(get_seconds, None, doc="seconds")
# minutes = property(get_minutes, None, doc="minutes")
# hours = property(get_hours, None, doc="hours")
# days = property(get_days, None, doc="days")
# dates = property(get_dates, None, doc="datetime objects")
# timestep = property(gettimestep, None)
. Output only the next line. | "Resource files are missing that are required to perform the tests.") |
Predict the next line for this snippet: <|code_start|>
# 20 sections
for x in xrange(0,20):
day = 1
hour = 0
sc = Section()
dt = None
# 10 profiles per section
for x in xrange(0,10):
lat = random.randint(40,44)
lon = random.randint(-74,-70)
loc = sPoint(lon,lat,0)
minute = 0
dt = datetime(2012, 4, day, hour, minute)
hour += 1
prof = Profile()
prof.location = loc
prof.time = dt
# Each with 20 depths
for y in xrange(0,20):
p = Point()
p.time = dt
p.location = sPoint(loc.x, loc.y, y)
m1 = Member(value=random.uniform(30,40), unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
m2 = Member(value=random.uniform(80,100), unit='PSU', name='Salinity', description='salinity', standard='salinity')
p.add_member(m1)
<|code_end|>
with the help of current file imports:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.features.base.section import Section
from paegan.cdm.dsg.collections.base.section_collection import SectionCollection
and context from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/features/base/section.py
# class Section(ProfileCollection):
# """
# A collection of profiles along a trajectory
# """
#
# def __init__(self, **kwargs):
# super(Section,self).__init__(**kwargs)
# self._type = "Section"
#
# def get_path(self):
# """
# Returns the nominal times of the profiles and the Points
# the profile was taken at.
# """
# return map(lambda x: [x.location, x.time], self._elements)
#
# Path: paegan/cdm/dsg/collections/base/section_collection.py
# class SectionCollection(NestedPointCollection):
# """
# A collection of Sections
# """
#
# def __init__(self, **kwargs):
# super(SectionCollection,self).__init__(**kwargs)
, which may contain function names, class names, or code. Output only the next line. | p.add_member(m2) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class SectionCollectionTest(unittest.TestCase):
def test_section_collection(self):
s_collection = SectionCollection()
# 20 sections
for x in xrange(0,20):
day = 1
hour = 0
sc = Section()
dt = None
# 10 profiles per section
for x in xrange(0,10):
lat = random.randint(40,44)
lon = random.randint(-74,-70)
<|code_end|>
with the help of current file imports:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.features.base.section import Section
from paegan.cdm.dsg.collections.base.section_collection import SectionCollection
and context from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/features/base/section.py
# class Section(ProfileCollection):
# """
# A collection of profiles along a trajectory
# """
#
# def __init__(self, **kwargs):
# super(Section,self).__init__(**kwargs)
# self._type = "Section"
#
# def get_path(self):
# """
# Returns the nominal times of the profiles and the Points
# the profile was taken at.
# """
# return map(lambda x: [x.location, x.time], self._elements)
#
# Path: paegan/cdm/dsg/collections/base/section_collection.py
# class SectionCollection(NestedPointCollection):
# """
# A collection of Sections
# """
#
# def __init__(self, **kwargs):
# super(SectionCollection,self).__init__(**kwargs)
, which may contain function names, class names, or code. Output only the next line. | loc = sPoint(lon,lat,0) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class SectionCollectionTest(unittest.TestCase):
def test_section_collection(self):
s_collection = SectionCollection()
# 20 sections
for x in xrange(0,20):
day = 1
hour = 0
sc = Section()
dt = None
# 10 profiles per section
for x in xrange(0,10):
<|code_end|>
, determine the next line of code. You have imports:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.features.base.section import Section
from paegan.cdm.dsg.collections.base.section_collection import SectionCollection
and context (class names, function names, or code) available:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/features/base/section.py
# class Section(ProfileCollection):
# """
# A collection of profiles along a trajectory
# """
#
# def __init__(self, **kwargs):
# super(Section,self).__init__(**kwargs)
# self._type = "Section"
#
# def get_path(self):
# """
# Returns the nominal times of the profiles and the Points
# the profile was taken at.
# """
# return map(lambda x: [x.location, x.time], self._elements)
#
# Path: paegan/cdm/dsg/collections/base/section_collection.py
# class SectionCollection(NestedPointCollection):
# """
# A collection of Sections
# """
#
# def __init__(self, **kwargs):
# super(SectionCollection,self).__init__(**kwargs)
. Output only the next line. | lat = random.randint(40,44) |
Given the following code snippet before the placeholder: <|code_start|> prof = Profile()
prof.location = loc
prof.time = dt
# Each with 20 depths
for y in xrange(0,20):
p = Point()
p.time = dt
p.location = sPoint(loc.x, loc.y, y)
m1 = Member(value=random.uniform(30,40), unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
m2 = Member(value=random.uniform(80,100), unit='PSU', name='Salinity', description='salinity', standard='salinity')
p.add_member(m1)
p.add_member(m2)
prof.add_element(p)
# Next depth is 2 minutes from now
dt = dt + timedelta(minutes=2)
sc.add_element(prof)
s_collection.add_element(sc)
s_collection.calculate_bounds()
assert s_collection.depth_range[0] == 0
assert s_collection.depth_range[-1] == 19
assert s_collection.time_range[0] == datetime(2012, 4, 1, 0)
for section in s_collection:
assert section.type == "Section"
for profile in section:
<|code_end|>
, predict the next line using imports from the current file:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.features.base.section import Section
from paegan.cdm.dsg.collections.base.section_collection import SectionCollection
and context including class names, function names, and sometimes code from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/features/base/section.py
# class Section(ProfileCollection):
# """
# A collection of profiles along a trajectory
# """
#
# def __init__(self, **kwargs):
# super(Section,self).__init__(**kwargs)
# self._type = "Section"
#
# def get_path(self):
# """
# Returns the nominal times of the profiles and the Points
# the profile was taken at.
# """
# return map(lambda x: [x.location, x.time], self._elements)
#
# Path: paegan/cdm/dsg/collections/base/section_collection.py
# class SectionCollection(NestedPointCollection):
# """
# A collection of Sections
# """
#
# def __init__(self, **kwargs):
# super(SectionCollection,self).__init__(**kwargs)
. Output only the next line. | assert profile.type == "Profile" |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class SectionTest(unittest.TestCase):
def test_section(self):
day = 1
hour = 0
sc = Section()
dt = None
# 10 profiles
for x in xrange(0,10):
lat = random.randint(40,44)
lon = random.randint(-74,-70)
<|code_end|>
with the help of current file imports:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.features.base.section import Section
and context from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/features/base/section.py
# class Section(ProfileCollection):
# """
# A collection of profiles along a trajectory
# """
#
# def __init__(self, **kwargs):
# super(Section,self).__init__(**kwargs)
# self._type = "Section"
#
# def get_path(self):
# """
# Returns the nominal times of the profiles and the Points
# the profile was taken at.
# """
# return map(lambda x: [x.location, x.time], self._elements)
, which may contain function names, class names, or code. Output only the next line. | loc = sPoint(lon,lat,0) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class SectionTest(unittest.TestCase):
def test_section(self):
day = 1
hour = 0
sc = Section()
dt = None
# 10 profiles
for x in xrange(0,10):
lat = random.randint(40,44)
lon = random.randint(-74,-70)
loc = sPoint(lon,lat,0)
minute = 0
dt = datetime(2012, 4, day, hour, minute)
hour += 1
prof = Profile()
prof.location = loc
prof.time = dt
# Each with 20 depths
for y in xrange(0,20):
<|code_end|>
, predict the immediate next line with the help of imports:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.features.base.section import Section
and context (classes, functions, sometimes code) from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/features/base/section.py
# class Section(ProfileCollection):
# """
# A collection of profiles along a trajectory
# """
#
# def __init__(self, **kwargs):
# super(Section,self).__init__(**kwargs)
# self._type = "Section"
#
# def get_path(self):
# """
# Returns the nominal times of the profiles and the Points
# the profile was taken at.
# """
# return map(lambda x: [x.location, x.time], self._elements)
. Output only the next line. | p = Point() |
Given snippet: <|code_start|> lon = random.randint(-74,-70)
loc = sPoint(lon,lat,0)
minute = 0
dt = datetime(2012, 4, day, hour, minute)
hour += 1
prof = Profile()
prof.location = loc
prof.time = dt
# Each with 20 depths
for y in xrange(0,20):
p = Point()
p.time = dt
p.location = sPoint(loc.x, loc.y, y)
m1 = Member(value=random.uniform(30,40), unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
m2 = Member(value=random.uniform(80,100), unit='PSU', name='Salinity', description='salinity', standard='salinity')
p.add_member(m1)
p.add_member(m2)
prof.add_element(p)
# Next depth is 2 minutes from now
dt = dt + timedelta(minutes=2)
sc.add_element(prof)
sc.calculate_bounds()
assert len(sc.get_path()) == 10
assert sc.size == 10
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.features.base.section import Section
and context:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/features/base/section.py
# class Section(ProfileCollection):
# """
# A collection of profiles along a trajectory
# """
#
# def __init__(self, **kwargs):
# super(Section,self).__init__(**kwargs)
# self._type = "Section"
#
# def get_path(self):
# """
# Returns the nominal times of the profiles and the Points
# the profile was taken at.
# """
# return map(lambda x: [x.location, x.time], self._elements)
which might include code, classes, or functions. Output only the next line. | assert sc.point_size == 200 |
Given the following code snippet before the placeholder: <|code_start|>
data_path = "/data/lm/tests"
class DepthvarTest(unittest.TestCase):
def setUp(self):
pass
@unittest.skipIf(not os.path.exists(os.path.join(data_path, "pws_L2_2012040100.nc")),
"Resource files are missing that are required to perform the tests.")
def test_conversions(self):
<|code_end|>
, predict the next line using imports from the current file:
import unittest, os, netCDF4, pytz
import numpy as np
from datetime import timedelta, datetime, tzinfo
from paegan.cdm.depthvar import Depthvar
from dateutil.parser import parse
and context including class names, function names, and sometimes code from other files:
# Path: paegan/cdm/depthvar.py
# class Depthvar(np.ndarray):
#
# # How many meter in the unit
# _unit2meters={}
# _unit2meters['millimeters'] = 0.001
# _unit2meters['centimeters'] = 0.01
# _unit2meters['meters'] = 1
# _unit2meters['feet'] = 0.3048
# _unit2meters['yards'] = 0.9144
# _unit2meters['kilometers'] = 1000
# _unit2meters['miles'] = 1609.34
#
# # How many units in the meter
# _meters2unit={}
# _meters2unit['millimeters'] = 1000
# _meters2unit['centimeters'] = 100
# _meters2unit['meters'] = 1
# _meters2unit['feet'] = 3.2084
# _meters2unit['yards'] = 1.09361
# _meters2unit['kilometers'] = 0.001
# _meters2unit['miles'] = 0.000621371
#
# def __new__(self, ncfile, name, units=None, **kwargs):
# if type(ncfile) is str:
# ncfile = netCDF4.Dataset(ncfile)
# self._nc = ncfile
#
# data = self._nc.variables[name][:]
# if units == None:
# try:
# self._units = self._nc.variables[name].units
# except StandardError:
# self._units = 'meters'
# else:
# self._units = units
#
# # compatibility to CF convention v1.0/udunits names:
# if self._units in ['m','meter','meters from the sea surface']:
# self._units='meters'
# if self._units in ['cm','centimeter']:
# self._units='centimeters'
# if self._units in ['mm','millimeter']:
# self._units='millimeters'
# if self._units in ['km','kilometer']:
# self._units='kilometers'
# if self._units in ['ft','feets']:
# self._units='feet'
# if self._units in ['yd','yard']:
# self._units='yards'
# if self._units in ['mile']:
# self._units='miles'
#
# return data.view(self)
#
# def nearest_index(self, depth):
# return np.where(abs(self.meters-depth) == np.nanmin(abs(self.meters-depth)))[0]
#
# def nearest(self, depth):
# """
# find nearest depth,
# input and output are meters
# """
# return self.meters[self.nearest_index(depth)][0]
#
# def get_mm(self):
# fac = self._unit2meters[self._units] * self._meters2unit['millimeters']
# return self*fac
#
# def get_cm(self):
# fac = self._unit2meters[self._units] * self._meters2unit['centimeters']
# return self*fac
#
# def get_km(self):
# fac = self._unit2meters[self._units] * self._meters2unit['kilometers']
# return self*fac
#
# def get_m(self):
# fac = self._unit2meters[self._units] * self._meters2unit['meters']
# return self*fac
#
# meters = property(get_m, None, doc="meters")
# kilometers = property(get_km, None, doc="kilometers")
# centimeters = property(get_cm, None, doc="centimeters")
# millimeters = property(get_mm, None, doc="millimeters")
. Output only the next line. | datafile = os.path.join(data_path, "pws_L2_2012040100.nc") |
Here is a snippet: <|code_start|>
class TrajectoryTest(unittest.TestCase):
def test_trajectory(self):
dt1 = datetime(2012, 4, 1, 0)
p1 = Point()
p1.time = dt1
p1.location = sPoint(-121, 49, 40)
member1 = Member(value=random.uniform(30,40), unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
member2 = Member(value=random.uniform(80,100), unit='PSU', name='Salinity', description='salinity', standard='salinity')
p1.add_member(member1)
p1.add_member(member2)
dt2 = datetime(2012, 4, 1, 1)
p2 = Point()
p2.time = dt2
p2.location = sPoint(-120, 50, 60)
member3 = Member(value=random.uniform(30,40), unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
member4 = Member(value=random.uniform(80,100), unit='PSU', name='Salinity', description='salinity', standard='salinity')
p2.add_member(member3)
p2.add_member(member4)
tr = Trajectory(elements=[p1,p2])
tr.calculate_bounds()
assert len(tr.get_path()) == 2
assert tr.size == 2
assert tr.type == "Trajectory"
assert tr.time_range[0] == dt1
assert tr.time_range[-1] == dt2
<|code_end|>
. Write the next line using the current file imports:
import unittest
import random
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.trajectory import Trajectory
and context from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/trajectory.py
# class Trajectory(PointCollection):
# """
# A collection of Points along a 1 dimensional path, connected in space and time.
# The Points are ordered in time (in other words, the time dimension must
# increase monotonically along the trajectory).
# """
#
# def __init__(self, **kwargs):
# super(Trajectory,self).__init__(**kwargs)
# self._type = "Trajectory"
#
# def get_path(self):
# """
# Returns the Points along the trajectory
# """
# return map(lambda x: [x.location, x.time], self._elements)
, which may include functions, classes, or code. Output only the next line. | assert tr.depth_range[0] == p1.location.z |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class TrajectoryTest(unittest.TestCase):
def test_trajectory(self):
dt1 = datetime(2012, 4, 1, 0)
p1 = Point()
p1.time = dt1
p1.location = sPoint(-121, 49, 40)
member1 = Member(value=random.uniform(30,40), unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
member2 = Member(value=random.uniform(80,100), unit='PSU', name='Salinity', description='salinity', standard='salinity')
p1.add_member(member1)
p1.add_member(member2)
dt2 = datetime(2012, 4, 1, 1)
p2 = Point()
p2.time = dt2
<|code_end|>
with the help of current file imports:
import unittest
import random
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.trajectory import Trajectory
and context from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/trajectory.py
# class Trajectory(PointCollection):
# """
# A collection of Points along a 1 dimensional path, connected in space and time.
# The Points are ordered in time (in other words, the time dimension must
# increase monotonically along the trajectory).
# """
#
# def __init__(self, **kwargs):
# super(Trajectory,self).__init__(**kwargs)
# self._type = "Trajectory"
#
# def get_path(self):
# """
# Returns the Points along the trajectory
# """
# return map(lambda x: [x.location, x.time], self._elements)
, which may contain function names, class names, or code. Output only the next line. | p2.location = sPoint(-120, 50, 60) |
Next line prediction: <|code_start|>
class PointTest(unittest.TestCase):
def test_point(self):
dt = datetime.utcnow()
p = Point()
p.location = sPoint(-123.17, 48.33, 10)
p.time = dt
<|code_end|>
. Use current file imports:
(import os
import unittest
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point)
and context including class names, function names, or small code snippets from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
. Output only the next line. | assert p.location.x == -123.17 |
Continue the code snippet: <|code_start|> member4 = Member(value=70, unit='PSU', name='Salinity', description='salinity', standard='salinity')
p2.add_member(member3)
p2.add_member(member4)
dt3 = datetime(2012, 1, 1, 12, 20)
p3 = Point()
p3.time = dt3
member5 = Member(value=32.6, unit='°C', name='Water Temperature', description='water temperature', standard='sea_water_temperature')
member6 = Member(value=60, unit='PSU', name='Salinity', description='salinity', standard='salinity')
member6 = Member(value=112, unit='%', name='DO', description='do', standard='do')
p3.add_member(member5)
p3.add_member(member6)
pc = Station(elements=[p1,p2,p3])
pc.name = "Super Station"
pc.location = sPoint(-120, 50, 0)
pc.location_name = "Just south of the super pier"
pc.uid = "123097SDFJL2"
pc.set_property("authority", "IOOS")
pc.calculate_bounds()
assert pc.size == 3
assert len(pc.time_range) == 3
assert pc.time_range[0] == dt1
assert pc.time_range[-1] == dt3
assert len(pc.depth_range) == 3
assert pc.depth_range[0] == p1.location.z
assert pc.upper_right().equals(pc.location)
assert pc.lower_left().equals(pc.location)
<|code_end|>
. Use current file imports:
import unittest
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.station import Station
from paegan.cdm.dsg.features.base.point import Point
and context (classes, functions, or code) from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/station.py
# class Station(PointCollection):
# """
# A collection of points at a single location
# """
# def __init__(self, **kwargs):
# super(Station,self).__init__(**kwargs)
# self._type = "timeSeries"
# self._properties = dict()
# self.uid = None
# self.name = None
# self.description = None
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
#
# # Sets the location of every Point in this Station if it is not already set
# for p in self._elements:
# try:
# assert p.location is not None
# except:
# p.location = self._location
#
# location = property(get_location, set_location)
#
# def get_uid(self):
# return self._uid
# def set_uid(self, uid):
# self._uid = uid
# uid = property(get_uid, set_uid)
#
# def get_name(self):
# return self._name
# def set_name(self, name):
# self._name = name
# name = property(get_name, set_name)
#
# def get_unique_members(self):
# all_members = (m for m in (e.members for e in self.elements))
#
# keys = ["name", "description", "standard", "unit"]
# mwhat = []
# for mg in all_members:
# for m in mg:
# mwhat.append( { key: m[key] for key in keys if key in m } )
#
# # Now unique them on name
# mwhat = { x['name']:x for x in mwhat }.values()
#
# return mwhat
#
# def get_description(self):
# return self._description
# def set_description(self, description):
# self._description = description
# description = property(get_description, set_description)
#
# def properties(self):
# """ General properties to store things about a station """
# return self._properties
# def set_property(self, prop, value):
# self._properties[prop] = value
# def get_property(self, prop):
# return self._properties.get(prop, None)
#
# def calculate_bounds(self):
# """
# Calculate the time_range, bbox, and size of this collection.
# Will scan all data.
# Ensures that .size, .bbox and .time_range return non-null.
#
# If the collection already knows its bbox; time_range; and/or size,
# they are recomputed.
# """
# self.location = self._location # To set locations for all points that don't have one
# stuff = map(lambda x: [x.time, x.location], self._elements)
# self.time_range = sorted(map(lambda x: x[0], stuff))
# points = map(lambda x: x[1], stuff)
# try:
# self.depth_range = sorted(map(lambda x: x[1].z, stuff))
# except:
# self.depth_range = None
# self.bbox = MultiPoint([self.location, self.location]).envelope
# self.size = len(self._elements)
. Output only the next line. | assert pc.get_property("authority") == "IOOS" |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class StationTest(unittest.TestCase):
def test_station(self):
dt1 = datetime(2012, 1, 1, 12, 0)
p1 = Point()
p1.time = dt1
member1 = Member(value=34.7, unit='°C', name='Water Temperature', description='water temperature', standard='sea_water_temperature')
member2 = Member(value=80, unit='PSU', name='Salinity', description='salinity', standard='salinity')
p1.add_member(member1)
p1.add_member(member2)
dt2 = datetime(2012, 1, 1, 12, 10)
p2 = Point()
<|code_end|>
. Use current file imports:
(import unittest
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.station import Station
from paegan.cdm.dsg.features.base.point import Point)
and context including class names, function names, or small code snippets from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/station.py
# class Station(PointCollection):
# """
# A collection of points at a single location
# """
# def __init__(self, **kwargs):
# super(Station,self).__init__(**kwargs)
# self._type = "timeSeries"
# self._properties = dict()
# self.uid = None
# self.name = None
# self.description = None
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
#
# # Sets the location of every Point in this Station if it is not already set
# for p in self._elements:
# try:
# assert p.location is not None
# except:
# p.location = self._location
#
# location = property(get_location, set_location)
#
# def get_uid(self):
# return self._uid
# def set_uid(self, uid):
# self._uid = uid
# uid = property(get_uid, set_uid)
#
# def get_name(self):
# return self._name
# def set_name(self, name):
# self._name = name
# name = property(get_name, set_name)
#
# def get_unique_members(self):
# all_members = (m for m in (e.members for e in self.elements))
#
# keys = ["name", "description", "standard", "unit"]
# mwhat = []
# for mg in all_members:
# for m in mg:
# mwhat.append( { key: m[key] for key in keys if key in m } )
#
# # Now unique them on name
# mwhat = { x['name']:x for x in mwhat }.values()
#
# return mwhat
#
# def get_description(self):
# return self._description
# def set_description(self, description):
# self._description = description
# description = property(get_description, set_description)
#
# def properties(self):
# """ General properties to store things about a station """
# return self._properties
# def set_property(self, prop, value):
# self._properties[prop] = value
# def get_property(self, prop):
# return self._properties.get(prop, None)
#
# def calculate_bounds(self):
# """
# Calculate the time_range, bbox, and size of this collection.
# Will scan all data.
# Ensures that .size, .bbox and .time_range return non-null.
#
# If the collection already knows its bbox; time_range; and/or size,
# they are recomputed.
# """
# self.location = self._location # To set locations for all points that don't have one
# stuff = map(lambda x: [x.time, x.location], self._elements)
# self.time_range = sorted(map(lambda x: x[0], stuff))
# points = map(lambda x: x[1], stuff)
# try:
# self.depth_range = sorted(map(lambda x: x[1].z, stuff))
# except:
# self.depth_range = None
# self.bbox = MultiPoint([self.location, self.location]).envelope
# self.size = len(self._elements)
. Output only the next line. | p2.time = dt2 |
Given snippet: <|code_start|> p2 = Point()
p2.time = dt2
p2.location = sPoint(-120, 50, 10)
member3 = Member(value=34.1, unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
member4 = Member(value=70, unit='PSU', name='Salinity', description='salinity', standard='salinity')
p2.add_member(member3)
p2.add_member(member4)
dt3 = datetime(2012, 1, 1, 12, 20)
p3 = Point()
p3.time = dt3
p3.location = sPoint(-120, 50, 20)
member5 = Member(value=32.6, unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
member6 = Member(value=60, unit='PSU', name='Salinity', description='salinity', standard='salinity')
p3.add_member(member5)
p3.add_member(member6)
pc = Profile(elements=[p1,p2,p3])
pc.location = sPoint(-120, 50)
pc.time = dt1
pc.calculate_bounds()
assert pc.size == 3
assert pc.time == dt1
assert len(pc.time_range) == 3
assert pc.time_range[0] == dt1
assert pc.time_range[-1] == dt3
assert len(pc.depth_range) == 3
assert pc.depth_range[0] == p1.location.z
assert pc.depth_range[-1] == p3.location.z
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
and context:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
which might include code, classes, or functions. Output only the next line. | assert pc.upper_right().equals(pc.location) |
Given the following code snippet before the placeholder: <|code_start|>
class ProfileTest(unittest.TestCase):
def test_profile(self):
dt1 = datetime(2012, 1, 1, 12, 0)
p1 = Point()
p1.time = dt1
p1.location = sPoint(-120, 50, 0)
member1 = Member(value=34.7, unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
member2 = Member(value=80, unit='PSU', name='Salinity', description='salinity', standard='salinity')
p1.add_member(member1)
p1.add_member(member2)
dt2 = datetime(2012, 1, 1, 12, 10)
p2 = Point()
p2.time = dt2
p2.location = sPoint(-120, 50, 10)
member3 = Member(value=34.1, unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
member4 = Member(value=70, unit='PSU', name='Salinity', description='salinity', standard='salinity')
p2.add_member(member3)
p2.add_member(member4)
dt3 = datetime(2012, 1, 1, 12, 20)
p3 = Point()
p3.time = dt3
p3.location = sPoint(-120, 50, 20)
member5 = Member(value=32.6, unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
member6 = Member(value=60, unit='PSU', name='Salinity', description='salinity', standard='salinity')
p3.add_member(member5)
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from datetime import datetime
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
and context including class names, function names, and sometimes code from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
. Output only the next line. | p3.add_member(member6) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class ProfileCollectionTest(unittest.TestCase):
def test_profile_collection(self):
day = 1
pc = ProfileCollection()
dt = None
# 10 profiles
for x in xrange(0,10):
lat = random.randint(40,44)
lon = random.randint(-74,-70)
loc = sPoint(lon,lat,0)
hour = 0
minute = 0
<|code_end|>
. Write the next line using the current file imports:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.collections.base.profile_collection import ProfileCollection
and context from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/collections/base/profile_collection.py
# class ProfileCollection(NestedPointCollection):
# """
# A collection of Profiles
# """
#
# def __init__(self, **kwargs):
# super(ProfileCollection,self).__init__(**kwargs)
, which may include functions, classes, or code. Output only the next line. | dt = datetime(2012, 4, day, hour, minute) |
Next line prediction: <|code_start|> day = 1
pc = ProfileCollection()
dt = None
# 10 profiles
for x in xrange(0,10):
lat = random.randint(40,44)
lon = random.randint(-74,-70)
loc = sPoint(lon,lat,0)
hour = 0
minute = 0
dt = datetime(2012, 4, day, hour, minute)
prof = Profile()
prof.location = loc
prof.time = dt
# Each with 20 depths
for y in xrange(0,20):
p = Point()
p.time = dt
p.location = sPoint(loc.x, loc.y, y)
m1 = Member(value=random.uniform(30,40), unit='°C', name='Water Temperatire', description='water temperature', standard='sea_water_temperature')
m2 = Member(value=random.uniform(80,100), unit='PSU', name='Salinity', description='salinity', standard='salinity')
p.add_member(m1)
p.add_member(m2)
prof.add_element(p)
# Next depth is 2 minutes from now
dt = dt + timedelta(minutes=2)
<|code_end|>
. Use current file imports:
(import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.collections.base.profile_collection import ProfileCollection)
and context including class names, function names, or small code snippets from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/collections/base/profile_collection.py
# class ProfileCollection(NestedPointCollection):
# """
# A collection of Profiles
# """
#
# def __init__(self, **kwargs):
# super(ProfileCollection,self).__init__(**kwargs)
. Output only the next line. | pc.add_element(prof) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class ProfileCollectionTest(unittest.TestCase):
def test_profile_collection(self):
day = 1
pc = ProfileCollection()
dt = None
# 10 profiles
for x in xrange(0,10):
lat = random.randint(40,44)
lon = random.randint(-74,-70)
loc = sPoint(lon,lat,0)
hour = 0
minute = 0
dt = datetime(2012, 4, day, hour, minute)
prof = Profile()
prof.location = loc
prof.time = dt
# Each with 20 depths
for y in xrange(0,20):
p = Point()
<|code_end|>
, predict the next line using imports from the current file:
import random
import unittest
from datetime import datetime, timedelta
from shapely.geometry import Point as sPoint
from paegan.cdm.dsg.member import Member
from paegan.cdm.dsg.features.base.point import Point
from paegan.cdm.dsg.features.base.profile import Profile
from paegan.cdm.dsg.collections.base.profile_collection import ProfileCollection
and context including class names, function names, and sometimes code from other files:
# Path: paegan/cdm/dsg/member.py
# class Member(dict):
# def __init__(self, *args, **kwargs):
# super(Member, self).__init__(*args, **kwargs)
#
# Path: paegan/cdm/dsg/features/base/profile.py
# class Profile(PointCollection):
# """
# A collection of points along a vertical (z) access
# ie. A single profile from an ADCP or CTD
#
# A profile has a nominal lat/lon and time.
# Actual time may be constant, or vary with z.
# The z coordinates are monotonic, and may be increasing or decreasing.
# """
# def __init__(self, **kwargs):
# super(Profile,self).__init__(**kwargs)
# self._type = "Profile"
#
# def get_location(self):
# return self._location
# def set_location(self, location):
# self._location = location
# location = property(get_location, set_location)
#
# def get_time(self):
# """
# Nominal time of the profile. This is usually the first time a reading was taken,
# since a profile's time can be constant or vary with z.
# """
# return self._time
# def set_time(self, time):
# self._time = time
# time = property(get_time, set_time)
#
# Path: paegan/cdm/dsg/collections/base/profile_collection.py
# class ProfileCollection(NestedPointCollection):
# """
# A collection of Profiles
# """
#
# def __init__(self, **kwargs):
# super(ProfileCollection,self).__init__(**kwargs)
. Output only the next line. | p.time = dt |
Given the following code snippet before the placeholder: <|code_start|> progress_handler.setLevel(level)
self.logger.addHandler(progress_handler)
self.e = threading.Event()
def save_progress():
while self.e.wait(5) != True:
try:
record = progress_deque.pop()
if record == StopIteration:
break
print record
except Exception:
pass
return
t = threading.Thread(name="ProgressUpdater", target=save_progress)
t.daemon = True
t.start()
def close_handlers(self):
(hand.close() for hand in self.logger.handlers)
def close_queue(self):
self.queue.put_nowait(StopIteration)
self.e.set()
def close(self):
self.close_handlers()
<|code_end|>
, predict the next line using imports from the current file:
import logging
import collections
import multiprocessing
import threading
from paegan.logger.multi_process_logging import MultiProcessingLogHandler
from paegan.logger.progress_handler import ProgressHandler
and context including class names, function names, and sometimes code from other files:
# Path: paegan/logger/multi_process_logging.py
# class MultiProcessingLogHandler(logging.Handler):
# def __init__(self, name, queue):
# logging.Handler.__init__(self)
#
# self._handler = FileHandler(name)
# self.queue = queue
#
# t = threading.Thread(target=self.receive)
# t.daemon = True
# t.start()
#
# def setFormatter(self, fmt):
# logging.Handler.setFormatter(self, fmt)
# self._handler.setFormatter(fmt)
#
# def receive(self):
# while True:
# try:
# record = self.queue.get()
# if record == StopIteration:
# break
# self._handler.emit(record)
# except (KeyboardInterrupt, SystemExit):
# raise
# except EOFError:
# break
# except Exception:
# traceback.print_exc(file=sys.stderr)
# break
#
# return
#
# def send(self, s):
# self.queue.put_nowait(s)
#
# def _format_record(self, record):
# # ensure that exc_info and args
# # have been stringified. Removes any chance of
# # unpickleable things inside and possibly reduces
# # message size sent over the pipe
# if record.args:
# record.msg = record.msg % record.args
# record.args = None
# if record.exc_info:
# dummy = self.format(record)
# record.exc_info = None
#
# return record
#
# def emit(self, record):
# try:
# s = self._format_record(record)
# self.send(s)
# except (KeyboardInterrupt, SystemExit):
# raise
# except Exception:
# self.handleError(record)
#
# def close(self):
# self.queue.put_nowait(StopIteration)
# self._handler.close()
# logging.Handler.close(self)
#
# Path: paegan/logger/progress_handler.py
# class ProgressHandler(logging.Handler):
# def __init__(self, progress_deque):
# logging.Handler.__init__(self)
# self.addFilter(OnlyProgressFilter())
# self._progress_deque = progress_deque
#
# def send(self, s):
# self._progress_deque.append(s)
#
# def emit(self, record):
# try:
# s = self._format_record(record)
# self.send(s)
# except (KeyboardInterrupt, SystemExit):
# raise
# except Exception:
# self.handleError(record)
#
# def _format_record(self, record):
# # format log into tuple of:
# # (datetime, progress, message)
#
# # Get a timezone aware datetime from time.time()
# dt = datetime.fromtimestamp(record.created).replace(tzinfo=pytz.timezone(time.strftime("%Z",time.gmtime()))).astimezone(pytz.utc)
#
# msg = record.msg
#
# if isinstance(msg, list):
# msg = tuple(msg)
#
# if isinstance(msg, tuple):
# return tuple([dt]) + msg
# elif isinstance(msg, str) or isinstance(msg, unicode):
# return (dt, -1, unicode(msg))
# elif isinstance(msg, float) or isinstance(msg, int):
# return (dt, msg, None)
# else:
# return (dt, None, None)
#
# def close(self):
# self._progress_deque.append(StopIteration)
# logging.Handler.close(self)
. Output only the next line. | self.close_queue() |
Using the snippet: <|code_start|> handler = MultiProcessingLogHandler(logpath, self.queue)
handler.setLevel(level)
formatter = logging.Formatter('[%(asctime)s] - %(levelname)s - %(processName)s - %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
progress_deque = collections.deque(maxlen=1)
progress_handler = ProgressHandler(progress_deque)
progress_handler.setLevel(level)
self.logger.addHandler(progress_handler)
self.e = threading.Event()
def save_progress():
while self.e.wait(5) != True:
try:
record = progress_deque.pop()
if record == StopIteration:
break
print record
except Exception:
pass
return
t = threading.Thread(name="ProgressUpdater", target=save_progress)
t.daemon = True
t.start()
def close_handlers(self):
<|code_end|>
, determine the next line of code. You have imports:
import logging
import collections
import multiprocessing
import threading
from paegan.logger.multi_process_logging import MultiProcessingLogHandler
from paegan.logger.progress_handler import ProgressHandler
and context (class names, function names, or code) available:
# Path: paegan/logger/multi_process_logging.py
# class MultiProcessingLogHandler(logging.Handler):
# def __init__(self, name, queue):
# logging.Handler.__init__(self)
#
# self._handler = FileHandler(name)
# self.queue = queue
#
# t = threading.Thread(target=self.receive)
# t.daemon = True
# t.start()
#
# def setFormatter(self, fmt):
# logging.Handler.setFormatter(self, fmt)
# self._handler.setFormatter(fmt)
#
# def receive(self):
# while True:
# try:
# record = self.queue.get()
# if record == StopIteration:
# break
# self._handler.emit(record)
# except (KeyboardInterrupt, SystemExit):
# raise
# except EOFError:
# break
# except Exception:
# traceback.print_exc(file=sys.stderr)
# break
#
# return
#
# def send(self, s):
# self.queue.put_nowait(s)
#
# def _format_record(self, record):
# # ensure that exc_info and args
# # have been stringified. Removes any chance of
# # unpickleable things inside and possibly reduces
# # message size sent over the pipe
# if record.args:
# record.msg = record.msg % record.args
# record.args = None
# if record.exc_info:
# dummy = self.format(record)
# record.exc_info = None
#
# return record
#
# def emit(self, record):
# try:
# s = self._format_record(record)
# self.send(s)
# except (KeyboardInterrupt, SystemExit):
# raise
# except Exception:
# self.handleError(record)
#
# def close(self):
# self.queue.put_nowait(StopIteration)
# self._handler.close()
# logging.Handler.close(self)
#
# Path: paegan/logger/progress_handler.py
# class ProgressHandler(logging.Handler):
# def __init__(self, progress_deque):
# logging.Handler.__init__(self)
# self.addFilter(OnlyProgressFilter())
# self._progress_deque = progress_deque
#
# def send(self, s):
# self._progress_deque.append(s)
#
# def emit(self, record):
# try:
# s = self._format_record(record)
# self.send(s)
# except (KeyboardInterrupt, SystemExit):
# raise
# except Exception:
# self.handleError(record)
#
# def _format_record(self, record):
# # format log into tuple of:
# # (datetime, progress, message)
#
# # Get a timezone aware datetime from time.time()
# dt = datetime.fromtimestamp(record.created).replace(tzinfo=pytz.timezone(time.strftime("%Z",time.gmtime()))).astimezone(pytz.utc)
#
# msg = record.msg
#
# if isinstance(msg, list):
# msg = tuple(msg)
#
# if isinstance(msg, tuple):
# return tuple([dt]) + msg
# elif isinstance(msg, str) or isinstance(msg, unicode):
# return (dt, -1, unicode(msg))
# elif isinstance(msg, float) or isinstance(msg, int):
# return (dt, msg, None)
# else:
# return (dt, None, None)
#
# def close(self):
# self._progress_deque.append(StopIteration)
# logging.Handler.close(self)
. Output only the next line. | (hand.close() for hand in self.logger.handlers) |
Here is a snippet: <|code_start|>#!/usr/local/bin/python
# -*- coding: utf-8 -*-
def graph(request, id, template='goflow/graphics/graph.html'):
processes = Process.objects.all()
graph = Graph.objects.get(id=(int(id)))
<|code_end|>
. Write the next line using the current file imports:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from goflow.workflow.models import Process
from .models import Graph
and context from other files:
# Path: goflow/workflow/models.py
# class Process(models.Model):
# """A process holds the map that describes the flow of work.
#
# The process map is made of activities and transitions.
# The instances you create on the map will begin the flow in
# the configured begin activity. Instances can be moved
# forward from activity to activity, going through transitions,
# until they reach the End activity.
# """
# enabled = models.BooleanField(default=True)
# date = models.DateTimeField(auto_now=True)
# title = models.CharField(max_length=100)
# description = models.TextField()
# description.allow_tags=True
# begin = models.ForeignKey('Activity', related_name='bprocess', verbose_name='initial activity', null=True, blank=True)
# end = models.ForeignKey('Activity', related_name='eprocess', verbose_name='final activity', null=True, blank=True,
# help_text='a default end activity will be created if blank')
# priority = models.IntegerField(default=0)
#
# # add new ProcessManager
# objects = ProcessManager()
#
# class Meta:
# verbose_name_plural = 'Processes'
# permissions = (
# ("can_instantiate", "Can instantiate"),
# ("can_browse", "Can browse"),
# )
#
# def __unicode__(self):
# return self.title
#
# @allow_tags
# def summary(self):
# return '<pre>%s</pre>' % self.description
#
# @allow_tags
# def action(self):
# return 'add <a href=../activity/add/>a new activity</a> or <a href=../activity/>copy</a> an activity from another process'
#
#
# def add_activity(self, name):
# '''
# name: name of activity (get or created)
# '''
# a, created = Activity.objects.get_or_create(title=name, process=self,
# defaults={'description':'(add description)'})
# return a
#
# def add_transition(self, name, activity_out, activity_in):
# t, created = Transition.objects.get_or_create(name=name, process=self,
# output=activity_out,
# defaults={'input':activity_in})
# return t
#
# def create_authorized_group_if_not_exists(self):
# g, created = Group.objects.get_or_create(name=self.title)
# if created:
# ptype = ContentType.objects.get_for_model(Process)
# cip = Permission.objects.get(content_type=ptype, codename='can_instantiate')
# g.permissions.add(cip)
#
# def save(self, no_end=False):
# models.Model.save(self)
# # instantiation group
# self.create_authorized_group_if_not_exists()
#
# if not no_end and not self.end:
# self.end = Activity.objects.create(title='End', process=self, kind='dummy', autostart=True)
# models.Model.save(self)
# try:
# if self.end and self.end.process.id != self.id:
# a = self.end
# a.id = None
# a.process = self
# a.save()
# self.end = a
# models.Model.save(self)
# if self.begin and self.begin.process.id != self.id:
# a = self.begin
# a.id = None
# a.process = self
# a.save()
# self.begin = a
# models.Model.save(self)
# except Exception:
# # admin console error ?!?
# pass
#
# Path: goflow/graphics/models.py
# class Graph(models.Model):
# name = models.CharField(max_length=100)
# parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
# background = models.ForeignKey('Visual', null=True, blank=True, related_name='bg_graphes')
# def __unicode__(self):
# return self.name
, which may include functions, classes, or code. Output only the next line. | return render_to_response(template, {'processes':processes, 'graph':graph}) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/local/bin/python
# -*- coding: utf-8 -*-
def graph(request, id, template='goflow/graphics/graph.html'):
processes = Process.objects.all()
graph = Graph.objects.get(id=(int(id)))
<|code_end|>
, predict the next line using imports from the current file:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from goflow.workflow.models import Process
from .models import Graph
and context including class names, function names, and sometimes code from other files:
# Path: goflow/workflow/models.py
# class Process(models.Model):
# """A process holds the map that describes the flow of work.
#
# The process map is made of activities and transitions.
# The instances you create on the map will begin the flow in
# the configured begin activity. Instances can be moved
# forward from activity to activity, going through transitions,
# until they reach the End activity.
# """
# enabled = models.BooleanField(default=True)
# date = models.DateTimeField(auto_now=True)
# title = models.CharField(max_length=100)
# description = models.TextField()
# description.allow_tags=True
# begin = models.ForeignKey('Activity', related_name='bprocess', verbose_name='initial activity', null=True, blank=True)
# end = models.ForeignKey('Activity', related_name='eprocess', verbose_name='final activity', null=True, blank=True,
# help_text='a default end activity will be created if blank')
# priority = models.IntegerField(default=0)
#
# # add new ProcessManager
# objects = ProcessManager()
#
# class Meta:
# verbose_name_plural = 'Processes'
# permissions = (
# ("can_instantiate", "Can instantiate"),
# ("can_browse", "Can browse"),
# )
#
# def __unicode__(self):
# return self.title
#
# @allow_tags
# def summary(self):
# return '<pre>%s</pre>' % self.description
#
# @allow_tags
# def action(self):
# return 'add <a href=../activity/add/>a new activity</a> or <a href=../activity/>copy</a> an activity from another process'
#
#
# def add_activity(self, name):
# '''
# name: name of activity (get or created)
# '''
# a, created = Activity.objects.get_or_create(title=name, process=self,
# defaults={'description':'(add description)'})
# return a
#
# def add_transition(self, name, activity_out, activity_in):
# t, created = Transition.objects.get_or_create(name=name, process=self,
# output=activity_out,
# defaults={'input':activity_in})
# return t
#
# def create_authorized_group_if_not_exists(self):
# g, created = Group.objects.get_or_create(name=self.title)
# if created:
# ptype = ContentType.objects.get_for_model(Process)
# cip = Permission.objects.get(content_type=ptype, codename='can_instantiate')
# g.permissions.add(cip)
#
# def save(self, no_end=False):
# models.Model.save(self)
# # instantiation group
# self.create_authorized_group_if_not_exists()
#
# if not no_end and not self.end:
# self.end = Activity.objects.create(title='End', process=self, kind='dummy', autostart=True)
# models.Model.save(self)
# try:
# if self.end and self.end.process.id != self.id:
# a = self.end
# a.id = None
# a.process = self
# a.save()
# self.end = a
# models.Model.save(self)
# if self.begin and self.begin.process.id != self.id:
# a = self.begin
# a.id = None
# a.process = self
# a.save()
# self.begin = a
# models.Model.save(self)
# except Exception:
# # admin console error ?!?
# pass
#
# Path: goflow/graphics/models.py
# class Graph(models.Model):
# name = models.CharField(max_length=100)
# parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
# background = models.ForeignKey('Visual', null=True, blank=True, related_name='bg_graphes')
# def __unicode__(self):
# return self.name
. Output only the next line. | return render_to_response(template, {'processes':processes, 'graph':graph}) |
Continue the code snippet: <|code_start|>
_dir = join(dirname(__file__))
admin.autodiscover()
urlpatterns = patterns('',
# FOR DEBUG AND TEST ONLY
url(r'^.*/accounts/login.*switch/(?P<username>.*)/(?P<password>.*)/$', 'goflow.workflow.views.debug_switch_user', {'redirect':'/leave/'}),
url(r'^.*/switch/(?P<username>.*)/(?P<password>.*)/$', 'goflow.workflow.views.debug_switch_user'),
# user connection
url(r'^.*/logout/$', 'django.contrib.auth.views.logout'),
url(r'^.*/accounts/login/$', 'django.contrib.auth.views.login', {'template_name':'goflow/login.html'}),
# static
url(r'^images/(?P<path>.*)$', 'django.views.static.serve', {'document_root': join(_dir, 'media/img'), 'show_indexes': True}),
url(r'^files/(.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# home redirection
url(r'^.*/home/$', RedirectView.as_view(url='/leave/')),
# home page
<|code_end|>
. Use current file imports:
from django.conf.urls import patterns,url,include
from django.conf import settings
from django.views.generic.base import RedirectView,TemplateView
from .leave.forms import StartRequestForm, RequesterForm, CheckRequestForm
from os.path import join, dirname
from django.contrib import admin
and context (classes, functions, or code) from other files:
# Path: leavedemo/leave/forms.py
# class StartRequestForm(StartForm):
# day_start = forms.DateField(widget=forms.TextInput(attrs={'class': 'vDateField'}))
# day_end = forms.DateField(widget=forms.TextInput(attrs={'class': 'vDateField'}))
#
# def save(self, user, data=None, commit=True):
# ''' overriden for adding the requester
# '''
# obj = super(StartForm, self).save(commit=False)
# obj.requester = user
# obj.save()
# return obj
#
# class Meta:
# model = LeaveRequest
# exclude = ('reason_denial', 'requester')
#
# class RequesterForm(BaseForm):
# class Meta:
# model = LeaveRequest
# exclude = ('reason_denial', 'requester')
#
# class CheckRequestForm(BaseForm):
# class Meta:
# model = LeaveRequest
# fields = ('reason_denial',)
. Output only the next line. | url(r'^leave/$', TemplateView.as_view(template_name='leave.html')), |
Given snippet: <|code_start|> # home redirection
url(r'^.*/home/$', RedirectView.as_view(url='/leave/')),
# home page
url(r'^leave/$', TemplateView.as_view(template_name='leave.html')),
# starting application
url(r'^leave/start/$', 'goflow.apptools.views.start_application', {'process_name':'leave',
'form_class':StartRequestForm,
'template':'start_leave.html'}),
# applications
url(r'^leave/checkstatus/(?P<id>.*)/$', 'goflow.apptools.views.edit_model', {'form_class':CheckRequestForm,
'template':'checkstatus.html'}),
url(r'^leave/checkstatus_auto/$', 'leavedemo.leave.views.checkstatus_auto', {'notif_user':True}),
url(r'^leave/refine/(?P<id>.*)/$', 'goflow.apptools.views.edit_model', {'form_class':RequesterForm,
'template':'refine.html'}),
url(r'^leave/approvalform/(?P<id>.*)/$', 'goflow.apptools.views.edit_model', {'form_class':CheckRequestForm,
'template':'approval.html'}),
url(r'^leave/hrform/(?P<id>.*)/$', 'goflow.apptools.views.view_application', {'template':'hrform.html'}),
url(r'^leave/hr_auto/$', 'leavedemo.leave.auto.update_hr'),
url(r'^leave/finalinfo/(?P<id>.*)/$', 'goflow.apptools.views.view_application', {'template':'finalinfo.html'}),
# administration
url(r'^leave/admin/apptools/', include('goflow.apptools.urls_admin')),
url(r'^leave/admin/workflow/', include('goflow.apptools.urls_admin')),
url(r'^leave/admin/graphics2/', include('goflow.graphics2.urls_admin')),
url(r'^leave/admin/(.*)', admin.site.urls),
# Goflow pages
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import patterns,url,include
from django.conf import settings
from django.views.generic.base import RedirectView,TemplateView
from .leave.forms import StartRequestForm, RequesterForm, CheckRequestForm
from os.path import join, dirname
from django.contrib import admin
and context:
# Path: leavedemo/leave/forms.py
# class StartRequestForm(StartForm):
# day_start = forms.DateField(widget=forms.TextInput(attrs={'class': 'vDateField'}))
# day_end = forms.DateField(widget=forms.TextInput(attrs={'class': 'vDateField'}))
#
# def save(self, user, data=None, commit=True):
# ''' overriden for adding the requester
# '''
# obj = super(StartForm, self).save(commit=False)
# obj.requester = user
# obj.save()
# return obj
#
# class Meta:
# model = LeaveRequest
# exclude = ('reason_denial', 'requester')
#
# class RequesterForm(BaseForm):
# class Meta:
# model = LeaveRequest
# exclude = ('reason_denial', 'requester')
#
# class CheckRequestForm(BaseForm):
# class Meta:
# model = LeaveRequest
# fields = ('reason_denial',)
which might include code, classes, or functions. Output only the next line. | url(r'^leave/', include('goflow.urls')), |
Predict the next line after this snippet: <|code_start|> url(r'^images/(?P<path>.*)$', 'django.views.static.serve', {'document_root': join(_dir, 'media/img'), 'show_indexes': True}),
url(r'^files/(.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
# home redirection
url(r'^.*/home/$', RedirectView.as_view(url='/leave/')),
# home page
url(r'^leave/$', TemplateView.as_view(template_name='leave.html')),
# starting application
url(r'^leave/start/$', 'goflow.apptools.views.start_application', {'process_name':'leave',
'form_class':StartRequestForm,
'template':'start_leave.html'}),
# applications
url(r'^leave/checkstatus/(?P<id>.*)/$', 'goflow.apptools.views.edit_model', {'form_class':CheckRequestForm,
'template':'checkstatus.html'}),
url(r'^leave/checkstatus_auto/$', 'leavedemo.leave.views.checkstatus_auto', {'notif_user':True}),
url(r'^leave/refine/(?P<id>.*)/$', 'goflow.apptools.views.edit_model', {'form_class':RequesterForm,
'template':'refine.html'}),
url(r'^leave/approvalform/(?P<id>.*)/$', 'goflow.apptools.views.edit_model', {'form_class':CheckRequestForm,
'template':'approval.html'}),
url(r'^leave/hrform/(?P<id>.*)/$', 'goflow.apptools.views.view_application', {'template':'hrform.html'}),
url(r'^leave/hr_auto/$', 'leavedemo.leave.auto.update_hr'),
url(r'^leave/finalinfo/(?P<id>.*)/$', 'goflow.apptools.views.view_application', {'template':'finalinfo.html'}),
# administration
url(r'^leave/admin/apptools/', include('goflow.apptools.urls_admin')),
url(r'^leave/admin/workflow/', include('goflow.apptools.urls_admin')),
url(r'^leave/admin/graphics2/', include('goflow.graphics2.urls_admin')),
<|code_end|>
using the current file's imports:
from django.conf.urls import patterns,url,include
from django.conf import settings
from django.views.generic.base import RedirectView,TemplateView
from .leave.forms import StartRequestForm, RequesterForm, CheckRequestForm
from os.path import join, dirname
from django.contrib import admin
and any relevant context from other files:
# Path: leavedemo/leave/forms.py
# class StartRequestForm(StartForm):
# day_start = forms.DateField(widget=forms.TextInput(attrs={'class': 'vDateField'}))
# day_end = forms.DateField(widget=forms.TextInput(attrs={'class': 'vDateField'}))
#
# def save(self, user, data=None, commit=True):
# ''' overriden for adding the requester
# '''
# obj = super(StartForm, self).save(commit=False)
# obj.requester = user
# obj.save()
# return obj
#
# class Meta:
# model = LeaveRequest
# exclude = ('reason_denial', 'requester')
#
# class RequesterForm(BaseForm):
# class Meta:
# model = LeaveRequest
# exclude = ('reason_denial', 'requester')
#
# class CheckRequestForm(BaseForm):
# class Meta:
# model = LeaveRequest
# fields = ('reason_denial',)
. Output only the next line. | url(r'^leave/admin/(.*)', admin.site.urls), |
Predict the next line after this snippet: <|code_start|>#!/usr/local/bin/python
# -*- coding: utf-8 -*-
def route_to_secretary(workitem):
user = workitem.instance.user
mgr_secretary = Manager.objects.get(category='secretary', users=user)
<|code_end|>
using the current file's imports:
from .models import Manager
from goflow.workflow.logger import Log; log = Log('leavedemo.leave.pushapplications')
and any relevant context from other files:
# Path: leavedemo/leave/models.py
# class Manager(models.Model):
# MANAGER_CHOICES = (
# ('secretary','Secretary'),
# ('supervisor','Supervisor'),
# )
# user = models.ForeignKey(User, related_name='manager_set')
# category = models.CharField(max_length=50, choices=MANAGER_CHOICES, help_text='secretary, supervisor, ...')
# users = models.ManyToManyField(User, related_name='managers')
# def __unicode__(self):
# return '%s as %s' % (self.user.username, self.category)
#
# Path: goflow/workflow/logger.py
# class Log(object):
# def __init__(self, module):
# self.log = logging.getLogger(module)
# # self._event = get_model('runtime', 'Event').objects
#
# def __getattr__(self, name):
# try:
# return getattr(self.log, name)
# except AttributeError as e:
# return getattr(self, name)
#
# def __call__(self, *args):
# if len(args) == 0:
# return
# elif len(args) == 1:
# self.log.info(args[0] )
# else:
# self.log.info(" ".join([str(i) for i in args]))
#
# def event(self, msg, workitem):
# # self._event.create(name=msg, workitem=workitem)
# self.log.info('EVENT: [%s] %s' % (workitem.__unicode__(), msg))
. Output only the next line. | return mgr_secretary.user |
Given snippet: <|code_start|>#!/usr/local/bin/python
# -*- coding: utf-8 -*-
def route_to_secretary(workitem):
user = workitem.instance.user
mgr_secretary = Manager.objects.get(category='secretary', users=user)
return mgr_secretary.user
def route_to_supervisor(workitem):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .models import Manager
from goflow.workflow.logger import Log; log = Log('leavedemo.leave.pushapplications')
and context:
# Path: leavedemo/leave/models.py
# class Manager(models.Model):
# MANAGER_CHOICES = (
# ('secretary','Secretary'),
# ('supervisor','Supervisor'),
# )
# user = models.ForeignKey(User, related_name='manager_set')
# category = models.CharField(max_length=50, choices=MANAGER_CHOICES, help_text='secretary, supervisor, ...')
# users = models.ManyToManyField(User, related_name='managers')
# def __unicode__(self):
# return '%s as %s' % (self.user.username, self.category)
#
# Path: goflow/workflow/logger.py
# class Log(object):
# def __init__(self, module):
# self.log = logging.getLogger(module)
# # self._event = get_model('runtime', 'Event').objects
#
# def __getattr__(self, name):
# try:
# return getattr(self.log, name)
# except AttributeError as e:
# return getattr(self, name)
#
# def __call__(self, *args):
# if len(args) == 0:
# return
# elif len(args) == 1:
# self.log.info(args[0] )
# else:
# self.log.info(" ".join([str(i) for i in args]))
#
# def event(self, msg, workitem):
# # self._event.create(name=msg, workitem=workitem)
# self.log.info('EVENT: [%s] %s' % (workitem.__unicode__(), msg))
which might include code, classes, or functions. Output only the next line. | user = workitem.instance.user |
Predict the next line for this snippet: <|code_start|>
class LeaveRequestAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields':('day_start', 'day_end', 'type', 'requester', 'reason', 'reason_denial')}),
)
list_display = ('type', 'date', 'day_start', 'day_end', 'requester')
list_filter = ('type', 'requester')
admin.site.register(LeaveRequest, LeaveRequestAdmin)
class AccountAdmin(admin.ModelAdmin):
list_display = ('user', 'category', 'days')
admin.site.register(Account, AccountAdmin)
class ManagerInline(admin.TabularInline):
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from .models import *
from django.contrib.auth.models import User
from goflow.workflow.admin import GoFlowUserAdmin, UserProfileInline
and context from other files:
# Path: goflow/workflow/admin.py
# class GoFlowUserAdmin(UserAdmin):
# inlines = [UserProfileInline]
#
# class UserProfileInline(admin.StackedInline):
# model = UserProfile
# max_num = 1
, which may contain function names, class names, or code. Output only the next line. | model = Manager |
Next line prediction: <|code_start|>
class LeaveRequestAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields':('day_start', 'day_end', 'type', 'requester', 'reason', 'reason_denial')}),
)
list_display = ('type', 'date', 'day_start', 'day_end', 'requester')
list_filter = ('type', 'requester')
admin.site.register(LeaveRequest, LeaveRequestAdmin)
class AccountAdmin(admin.ModelAdmin):
<|code_end|>
. Use current file imports:
(from django.contrib import admin
from .models import *
from django.contrib.auth.models import User
from goflow.workflow.admin import GoFlowUserAdmin, UserProfileInline)
and context including class names, function names, or small code snippets from other files:
# Path: goflow/workflow/admin.py
# class GoFlowUserAdmin(UserAdmin):
# inlines = [UserProfileInline]
#
# class UserProfileInline(admin.StackedInline):
# model = UserProfile
# max_num = 1
. Output only the next line. | list_display = ('user', 'category', 'days') |
Continue the code snippet: <|code_start|>#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# allows calendar widgets
class StartRequestForm(StartForm):
day_start = forms.DateField(widget=forms.TextInput(attrs={'class': 'vDateField'}))
day_end = forms.DateField(widget=forms.TextInput(attrs={'class': 'vDateField'}))
<|code_end|>
. Use current file imports:
from .models import LeaveRequest
from goflow.apptools.forms import BaseForm, StartForm
from django import forms
and context (classes, functions, or code) from other files:
# Path: leavedemo/leave/models.py
# class LeaveRequest(models.Model):
# TYPE_CHOICES = (
# ('Vacation','Vacation'),
# ('Birth or marriage of child','Birth or marriage of child'),
# ('Change of residence','Change of residence'),
# ('Death of a child','Death of a child'),
# ('Death of a relative in the ascending line','Death of a relative in the ascending line'),
# ('Death of parent-in-law, brother or sister','Death of parent-in-law, brother or sister'),
# ('Death of spouse','Death of spouse'),
# ('Marriage','Marriage'),
# ('Maternity','Maternity'),
# ('Serious illness of a child','Serious illness of a child'),
# ('Serious illness of a relative in the asc line','Serious illness of a relative in the asc line'),
# ('Serious illness of a parent-in-law','Serious illness of a parent-in-law'),
# ('Serious illness of spouse','Serious illness of spouse'))
# date = models.DateTimeField(auto_now=True)
# day_start = models.DateField()
# day_end = models.DateField()
# type = models.CharField(max_length=50, choices=TYPE_CHOICES, default='Vacation')
# reason = models.TextField(null=True, blank=True)
# reason_denial = models.TextField(null=True, blank=True, verbose_name='reason of denial')
# requester = models.ForeignKey(User, null=True, blank=True)
#
# def __unicode__(self):
# return 'leaverequest-%s' % str(self.pk)
#
# Path: goflow/apptools/forms.py
# class BaseForm(ModelForm):
# '''
# base class for edition forms
# '''
#
# workitem_id = forms.IntegerField(widget=forms.HiddenInput, required=False)
# priority = forms.ChoiceField(label='Priority', widget=forms.RadioSelect, initial='0',
# choices=(('0','normal'), ('1','urgent'), ('5','emergency')),
# )
# def save(self, workitem=None, submit_value=None, commit=True):
# ob = super(BaseForm, self).save(commit=commit)
# if workitem and workitem.can_priority_change():
# workitem.priority = int(self.cleaned_data['priority'])
# workitem.save()
# return ob
#
# def pre_check(self, obj_context=None, user=None):
# """may be overriden to do some check before.
#
# obj_context object instance (if cmp_attr is set, this is the root object)
# an exception should be risen if pre-conditions are not fullfilled
# """
# pass
#
# class Meta:
# exclude = ('workitem_id',)
#
# class StartForm(ModelForm):
# '''
# base class for starting a workflow
# '''
# priority = forms.ChoiceField(label='Priority', widget=forms.RadioSelect, initial='0',
# choices=(('0','normal'), ('1','urgent'), ('5','emergency')),
# )
#
# def save(self, user=None, data=None, commit=True):
# ob = super(StartForm, self).save(commit=commit)
# return ob
#
# def pre_check(self, user=None):
# """may be overriden to do some check before.
#
# an exception should be risen if pre-conditions are not fullfilled
# """
# pass
. Output only the next line. | def save(self, user, data=None, commit=True): |
Given the following code snippet before the placeholder: <|code_start|> self.assertEqual(sentences, [[u'hey', u'look'], [u'i\'m', u'unicode']])
def test_make_tree__with_small_text(self):
corpus = Corpus(text=u'a hit is a hit',
sentence_start_token=u'#')
self.assertDictEqual(
corpus.tree,
{
u'a': self._build_ngram(
token=u'a',
after=[{u'hit': 2}, {u'is': 1}],
count=2
),
u'hit': self._build_ngram(
token=u'hit',
after=[{u'is': 1}, {u'a': 1}],
count=2
),
u'is': self._build_ngram(
token=u'is',
after=[{u'a': 1}, {u'hit': 1}],
count=1
),
u'a hit': self._build_ngram(
token=u'a hit',
after=[{u'is': 1}, {u'a': 1}],
count=2
),
u'hit is': self._build_ngram(
<|code_end|>
, predict the next line using imports from the current file:
from unittest import TestCase
from server.src.voicebox.corpus import Corpus
from server.src.voicebox.ngram import Ngram
from server.tests.voicebox import test_data
and context including class names, function names, and sometimes code from other files:
# Path: server/src/voicebox/corpus.py
# class Corpus(object):
#
# def __init__(self, text, max_ngram_size=2, hindsight=2, sentence_start_token='^^'):
# self.text = text
# self.max_ngram_size = max_ngram_size
# self.hindsight = hindsight
# self.sentence_start_token = sentence_start_token
#
# self.max_reach = 2
#
# self.wordcount = 0
# self.tree = {}
# self.build()
#
# def build(self):
# sentences = self.get_sentences()
#
# for sentence in sentences:
# sentence = [self.sentence_start_token] + sentence
#
# for ngram_size in range(1, self.max_ngram_size + 1):
# for start in range(1, len(sentence)):
# end = start + ngram_size
#
# if start >= 0 and end < len(sentence) + 1:
# before, current, after = sentence[:start], sentence[start:end], sentence[end:]
#
# if len(current) == 1:
# self.wordcount += 1
#
# ngram = " ".join(current)
#
# if ngram in self.tree:
# self.tree[ngram].count += 1
# else:
# self.tree[ngram] = Ngram(ngram)
#
# for reach in range(1, self.max_reach + 1):
# if len(after) >= reach:
# word = after[reach - 1]
# self.tree[ngram].add_after(word, reach)
#
# def get_sentences(self):
# remove_punctuation_map = dict((ord(char), None) for char in string.punctuation.replace('\'', ''))
# sentences = re.split(r'\n|\. |!|\?', self.text)
#
# return [(
# sentence.decode('utf-8')
# .strip('\n')
# .translate(remove_punctuation_map)
# .lower()
# .split()
# ) for sentence in sentences if sentence]
#
# Path: server/src/voicebox/ngram.py
# class Ngram(object):
#
# def __init__(self, token):
# self.token = token
# self.count = 1
# self.after = []
#
# def __str__(self):
# return str({
# 'after': self.after,
# 'count': self.count
# })
#
# def __repr__(self):
# return str({
# 'after': self.after,
# 'count': self.count
# })
#
# def __len__(self):
# return len(self.token)
#
# def __eq__(self, other):
# if type(self) is type(other):
# return self.__dict__ == other.__dict__
# return False
#
# def add_after(self, token, reach):
# if len(self.after) < reach:
# self.after.append({})
# target_dict = self.after[reach - 1]
# if token in target_dict:
# target_dict[token] += 1
# else:
# target_dict[token] = 1
#
# Path: server/tests/voicebox/test_data.py
. Output only the next line. | token=u'hit is', |
Continue the code snippet: <|code_start|> corpus = Corpus(text=u'a hit is a hit',
sentence_start_token=u'#')
self.assertDictEqual(
corpus.tree,
{
u'a': self._build_ngram(
token=u'a',
after=[{u'hit': 2}, {u'is': 1}],
count=2
),
u'hit': self._build_ngram(
token=u'hit',
after=[{u'is': 1}, {u'a': 1}],
count=2
),
u'is': self._build_ngram(
token=u'is',
after=[{u'a': 1}, {u'hit': 1}],
count=1
),
u'a hit': self._build_ngram(
token=u'a hit',
after=[{u'is': 1}, {u'a': 1}],
count=2
),
u'hit is': self._build_ngram(
token=u'hit is',
after=[{u'a': 1}, {u'hit': 1}],
count=1
<|code_end|>
. Use current file imports:
from unittest import TestCase
from server.src.voicebox.corpus import Corpus
from server.src.voicebox.ngram import Ngram
from server.tests.voicebox import test_data
and context (classes, functions, or code) from other files:
# Path: server/src/voicebox/corpus.py
# class Corpus(object):
#
# def __init__(self, text, max_ngram_size=2, hindsight=2, sentence_start_token='^^'):
# self.text = text
# self.max_ngram_size = max_ngram_size
# self.hindsight = hindsight
# self.sentence_start_token = sentence_start_token
#
# self.max_reach = 2
#
# self.wordcount = 0
# self.tree = {}
# self.build()
#
# def build(self):
# sentences = self.get_sentences()
#
# for sentence in sentences:
# sentence = [self.sentence_start_token] + sentence
#
# for ngram_size in range(1, self.max_ngram_size + 1):
# for start in range(1, len(sentence)):
# end = start + ngram_size
#
# if start >= 0 and end < len(sentence) + 1:
# before, current, after = sentence[:start], sentence[start:end], sentence[end:]
#
# if len(current) == 1:
# self.wordcount += 1
#
# ngram = " ".join(current)
#
# if ngram in self.tree:
# self.tree[ngram].count += 1
# else:
# self.tree[ngram] = Ngram(ngram)
#
# for reach in range(1, self.max_reach + 1):
# if len(after) >= reach:
# word = after[reach - 1]
# self.tree[ngram].add_after(word, reach)
#
# def get_sentences(self):
# remove_punctuation_map = dict((ord(char), None) for char in string.punctuation.replace('\'', ''))
# sentences = re.split(r'\n|\. |!|\?', self.text)
#
# return [(
# sentence.decode('utf-8')
# .strip('\n')
# .translate(remove_punctuation_map)
# .lower()
# .split()
# ) for sentence in sentences if sentence]
#
# Path: server/src/voicebox/ngram.py
# class Ngram(object):
#
# def __init__(self, token):
# self.token = token
# self.count = 1
# self.after = []
#
# def __str__(self):
# return str({
# 'after': self.after,
# 'count': self.count
# })
#
# def __repr__(self):
# return str({
# 'after': self.after,
# 'count': self.count
# })
#
# def __len__(self):
# return len(self.token)
#
# def __eq__(self, other):
# if type(self) is type(other):
# return self.__dict__ == other.__dict__
# return False
#
# def add_after(self, token, reach):
# if len(self.after) < reach:
# self.after.append({})
# target_dict = self.after[reach - 1]
# if token in target_dict:
# target_dict[token] += 1
# else:
# target_dict[token] = 1
#
# Path: server/tests/voicebox/test_data.py
. Output only the next line. | ), |
Continue the code snippet: <|code_start|> def test_get_sentences__with_unicode_string(self):
corpus = Corpus(text=test_data.text_unicode)
sentences = corpus.get_sentences()
self.assertEqual(sentences, [[u'hey', u'look'], [u'i\'m', u'unicode']])
def test_make_tree__with_small_text(self):
corpus = Corpus(text=u'a hit is a hit',
sentence_start_token=u'#')
self.assertDictEqual(
corpus.tree,
{
u'a': self._build_ngram(
token=u'a',
after=[{u'hit': 2}, {u'is': 1}],
count=2
),
u'hit': self._build_ngram(
token=u'hit',
after=[{u'is': 1}, {u'a': 1}],
count=2
),
u'is': self._build_ngram(
token=u'is',
after=[{u'a': 1}, {u'hit': 1}],
count=1
),
u'a hit': self._build_ngram(
token=u'a hit',
<|code_end|>
. Use current file imports:
from unittest import TestCase
from server.src.voicebox.corpus import Corpus
from server.src.voicebox.ngram import Ngram
from server.tests.voicebox import test_data
and context (classes, functions, or code) from other files:
# Path: server/src/voicebox/corpus.py
# class Corpus(object):
#
# def __init__(self, text, max_ngram_size=2, hindsight=2, sentence_start_token='^^'):
# self.text = text
# self.max_ngram_size = max_ngram_size
# self.hindsight = hindsight
# self.sentence_start_token = sentence_start_token
#
# self.max_reach = 2
#
# self.wordcount = 0
# self.tree = {}
# self.build()
#
# def build(self):
# sentences = self.get_sentences()
#
# for sentence in sentences:
# sentence = [self.sentence_start_token] + sentence
#
# for ngram_size in range(1, self.max_ngram_size + 1):
# for start in range(1, len(sentence)):
# end = start + ngram_size
#
# if start >= 0 and end < len(sentence) + 1:
# before, current, after = sentence[:start], sentence[start:end], sentence[end:]
#
# if len(current) == 1:
# self.wordcount += 1
#
# ngram = " ".join(current)
#
# if ngram in self.tree:
# self.tree[ngram].count += 1
# else:
# self.tree[ngram] = Ngram(ngram)
#
# for reach in range(1, self.max_reach + 1):
# if len(after) >= reach:
# word = after[reach - 1]
# self.tree[ngram].add_after(word, reach)
#
# def get_sentences(self):
# remove_punctuation_map = dict((ord(char), None) for char in string.punctuation.replace('\'', ''))
# sentences = re.split(r'\n|\. |!|\?', self.text)
#
# return [(
# sentence.decode('utf-8')
# .strip('\n')
# .translate(remove_punctuation_map)
# .lower()
# .split()
# ) for sentence in sentences if sentence]
#
# Path: server/src/voicebox/ngram.py
# class Ngram(object):
#
# def __init__(self, token):
# self.token = token
# self.count = 1
# self.after = []
#
# def __str__(self):
# return str({
# 'after': self.after,
# 'count': self.count
# })
#
# def __repr__(self):
# return str({
# 'after': self.after,
# 'count': self.count
# })
#
# def __len__(self):
# return len(self.token)
#
# def __eq__(self, other):
# if type(self) is type(other):
# return self.__dict__ == other.__dict__
# return False
#
# def add_after(self, token, reach):
# if len(self.after) < reach:
# self.after.append({})
# target_dict = self.after[reach - 1]
# if token in target_dict:
# target_dict[token] += 1
# else:
# target_dict[token] = 1
#
# Path: server/tests/voicebox/test_data.py
. Output only the next line. | after=[{u'is': 1}, {u'a': 1}], |
Next line prediction: <|code_start|> }
}
)
# TODO: Should a two-gram frequency be based off of number of two-grams?
# TODO: (i.e. 6 two-grams for 7 words) word_count - (n - 1) for n-gram
def test_make_voicebox(self):
voicebox = Voicebox.build(texts=[u'a penny saved is a penny earned'])
self.assertDictEqual(
voicebox,
{
u'wordcount': 7,
u'a': {
u'after': [{u'penny': 1.0}, {u'earned': 0.5, u'saved': 0.5}],
u'frequency': 2.0 / 7.0
},
u'a penny': {
u'after': [{u'earned': 0.5, u'saved': 0.5}, {u'is': 1.0}],
u'frequency': 2.0 / 7.0
},
u'earned': {
u'after': [],
u'frequency': 1.0 / 7.0
},
u'is': {
u'after': [{u'a': 1.0}, {u'penny': 1.0}],
u'frequency': 1.0 / 7.0
},
u'is a': {
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from server.src.voicebox.voicebox import Voicebox)
and context including class names, function names, or small code snippets from other files:
# Path: server/src/voicebox/voicebox.py
# class Voicebox(object):
#
# @staticmethod
# def build(texts):
# corpus = Corpus('. '.join(texts))
#
# voicebox = {}
#
# for ngram, ngram_data in corpus.tree.iteritems():
# voicebox[ngram] = {
# u'frequency': float(ngram_data.count) / float(corpus.wordcount)
# }
#
# voicebox[ngram][u'after'] = ngram_data.after
# for index, after in enumerate(ngram_data.after):
# ngram_after_total = sum([ngram_after_count for _, ngram_after_count in after.iteritems()])
# for ngram_after, ngram_after_count in after.iteritems():
# voicebox[ngram][u'after'][index][ngram_after] = float(ngram_after_count) / float(ngram_after_total)
#
# voicebox[u'wordcount'] = corpus.wordcount
#
# return voicebox
. Output only the next line. | u'after': [{u'penny': 1.0}, {u'earned': 1.0}], |
Given the code snippet: <|code_start|> self.build()
def build(self):
sentences = self.get_sentences()
for sentence in sentences:
sentence = [self.sentence_start_token] + sentence
for ngram_size in range(1, self.max_ngram_size + 1):
for start in range(1, len(sentence)):
end = start + ngram_size
if start >= 0 and end < len(sentence) + 1:
before, current, after = sentence[:start], sentence[start:end], sentence[end:]
if len(current) == 1:
self.wordcount += 1
ngram = " ".join(current)
if ngram in self.tree:
self.tree[ngram].count += 1
else:
self.tree[ngram] = Ngram(ngram)
for reach in range(1, self.max_reach + 1):
if len(after) >= reach:
word = after[reach - 1]
self.tree[ngram].add_after(word, reach)
<|code_end|>
, generate the next line using the imports in this file:
import string
import re
from .ngram import Ngram
and context (functions, classes, or occasionally code) from other files:
# Path: server/src/voicebox/ngram.py
# class Ngram(object):
#
# def __init__(self, token):
# self.token = token
# self.count = 1
# self.after = []
#
# def __str__(self):
# return str({
# 'after': self.after,
# 'count': self.count
# })
#
# def __repr__(self):
# return str({
# 'after': self.after,
# 'count': self.count
# })
#
# def __len__(self):
# return len(self.token)
#
# def __eq__(self, other):
# if type(self) is type(other):
# return self.__dict__ == other.__dict__
# return False
#
# def add_after(self, token, reach):
# if len(self.after) < reach:
# self.after.append({})
# target_dict = self.after[reach - 1]
# if token in target_dict:
# target_dict[token] += 1
# else:
# target_dict[token] = 1
. Output only the next line. | def get_sentences(self): |
Here is a snippet: <|code_start|>
class Voicebox(object):
@staticmethod
def build(texts):
corpus = Corpus('. '.join(texts))
voicebox = {}
for ngram, ngram_data in corpus.tree.iteritems():
voicebox[ngram] = {
u'frequency': float(ngram_data.count) / float(corpus.wordcount)
}
voicebox[ngram][u'after'] = ngram_data.after
for index, after in enumerate(ngram_data.after):
<|code_end|>
. Write the next line using the current file imports:
from .corpus import Corpus
and context from other files:
# Path: server/src/voicebox/corpus.py
# class Corpus(object):
#
# def __init__(self, text, max_ngram_size=2, hindsight=2, sentence_start_token='^^'):
# self.text = text
# self.max_ngram_size = max_ngram_size
# self.hindsight = hindsight
# self.sentence_start_token = sentence_start_token
#
# self.max_reach = 2
#
# self.wordcount = 0
# self.tree = {}
# self.build()
#
# def build(self):
# sentences = self.get_sentences()
#
# for sentence in sentences:
# sentence = [self.sentence_start_token] + sentence
#
# for ngram_size in range(1, self.max_ngram_size + 1):
# for start in range(1, len(sentence)):
# end = start + ngram_size
#
# if start >= 0 and end < len(sentence) + 1:
# before, current, after = sentence[:start], sentence[start:end], sentence[end:]
#
# if len(current) == 1:
# self.wordcount += 1
#
# ngram = " ".join(current)
#
# if ngram in self.tree:
# self.tree[ngram].count += 1
# else:
# self.tree[ngram] = Ngram(ngram)
#
# for reach in range(1, self.max_reach + 1):
# if len(after) >= reach:
# word = after[reach - 1]
# self.tree[ngram].add_after(word, reach)
#
# def get_sentences(self):
# remove_punctuation_map = dict((ord(char), None) for char in string.punctuation.replace('\'', ''))
# sentences = re.split(r'\n|\. |!|\?', self.text)
#
# return [(
# sentence.decode('utf-8')
# .strip('\n')
# .translate(remove_punctuation_map)
# .lower()
# .split()
# ) for sentence in sentences if sentence]
, which may include functions, classes, or code. Output only the next line. | ngram_after_total = sum([ngram_after_count for _, ngram_after_count in after.iteritems()]) |
Continue the code snippet: <|code_start|>CAT_CHOICES = (
('electronics', 'Electronics'),
('accessories', 'Accessories'),
)
class ProductFilterForm(forms.Form):
q = forms.CharField(label='Search', required=False)
category_id = forms.ModelMultipleChoiceField(
label='Category',
queryset=Category.objects.all(),
widget=forms.CheckboxSelectMultiple,
required=False)
# category_title = forms.ChoiceField(
# label='Category',
# choices=CAT_CHOICES,
# widget=forms.CheckboxSelectMultiple,
# required=False)
max_price = forms.DecimalField(decimal_places=2, max_digits=12, required=False)
min_price = forms.DecimalField(decimal_places=2, max_digits=12, required=False)
class VariationInventoryForm(forms.ModelForm):
class Meta:
model = Variation
fields = [
"price",
"sale_price",
"inventory",
"active",
<|code_end|>
. Use current file imports:
from django import forms
from django.forms.models import modelformset_factory
from .models import Variation, Category
and context (classes, functions, or code) from other files:
# Path: src/products/models.py
# class Variation(models.Model):
# product = models.ForeignKey(Product)
# title = models.CharField(max_length=120)
# price = models.DecimalField(decimal_places=2, max_digits=20)
# sale_price = models.DecimalField(decimal_places=2, max_digits=20, null=True, blank=True)
# active = models.BooleanField(default=True)
# inventory = models.IntegerField(null=True, blank=True) #refer none == unlimited amount
#
# def __unicode__(self):
# return self.title
#
# def get_price(self):
# if self.sale_price is not None:
# return self.sale_price
# else:
# return self.price
#
# def get_html_price(self):
# if self.sale_price is not None:
# html_text = "<span class='sale-price'>%s</span> <span class='og-price'>%s</span>" %(self.sale_price, self.price)
# else:
# html_text = "<span class='price'>%s</span>" %(self.price)
# return mark_safe(html_text)
#
# def get_absolute_url(self):
# return self.product.get_absolute_url()
#
# def add_to_cart(self):
# return "%s?item=%s&qty=1" %(reverse("cart"), self.id)
#
# def remove_from_cart(self):
# return "%s?item=%s&qty=1&delete=True" %(reverse("cart"), self.id)
#
# def get_title(self):
# return "%s - %s" %(self.product.title, self.title)
#
# class Category(models.Model):
# title = models.CharField(max_length=120, unique=True)
# slug = models.SlugField(unique=True)
# description = models.TextField(null=True, blank=True)
# active = models.BooleanField(default=True)
# timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
#
# def __unicode__(self):
# return self.title
#
#
# def get_absolute_url(self):
# return reverse("category_detail", kwargs={"slug": self.slug })
. Output only the next line. | ] |
Predict the next line for this snippet: <|code_start|> @ivar name: Liquid Crystal name.
@ivar nO: Ordinary refractive index.
@ivar nE: Extraordinary refractive index.
@ivar K11: Elastic tensor, first component.
@ivar K22: Elastic tensor, second component.
@ivar K33: Elastic tensor, third component.
@ivar q0: Chirality.
"""
def __init__(
self,
name="",
nO=1.0,
nE=1.0,
nO_electrical=1.0,
nE_electrical=1.0,
K11=0.0,
K22=0.0,
K33=0.0,
q0=0.0,
):
"""Set name, the refractive indices, the elastic constants and
the chirality."""
Material.__init__(self, name)
self.nO = nO
self.nE = nE
self.nO_electrical = nO_electrical
self.nE_electrical = nE_electrical
<|code_end|>
with the help of current file imports:
from builtins import str
from builtins import object
from functools import partial
from scipy.integrate import quad
from EMpy.constants import eps0
import numpy
and context from other files:
# Path: EMpy/constants.py
, which may contain function names, class names, or code. Output only the next line. | self.K11 = K11 |
Predict the next line after this snippet: <|code_start|> )
def _format_key(self, key):
return '.' + key
def _get_value(self, main_value, key):
return getattr(main_value, key)
class Keys(CommonVariable):
def _keys(self, main_value):
return main_value.keys()
def _format_key(self, key):
return '[{}]'.format(my_cheap_repr(key).replace('\n', ' ').replace('\r', ' '))
def _get_value(self, main_value, key):
return main_value[key]
class Indices(Keys):
_slice = slice(None)
def _keys(self, main_value):
return range(len(main_value))[self._slice]
def __getitem__(self, item):
assert isinstance(item, slice)
result = deepcopy(self)
result._slice = item
<|code_end|>
using the current file's imports:
import itertools
import six
from copy import deepcopy
from snoop.utils import with_needed_parentheses, my_cheap_repr, ensure_tuple
from collections import Mapping, Sequence
from collections.abc import Mapping, Sequence
and any relevant context from other files:
# Path: snoop/utils.py
# def with_needed_parentheses(source):
# if needs_parentheses(source):
# return '({})'.format(source)
# else:
# return source
#
# def my_cheap_repr(x):
# return cheap_repr(x, target_length=REPR_TARGET_LENGTH)
#
# def ensure_tuple(x, split=False):
# if split and isinstance(x, six.string_types):
# x = x.replace(',', ' ').split()
# if not isinstance(x, (list, set, tuple)):
# x = (x,)
# return tuple(x)
. Output only the next line. | return result |
Here is a snippet: <|code_start|> self.code = compile(source, '<variable>', 'eval')
self.unambiguous_source = with_needed_parentheses(source)
def items(self, frame):
try:
main_value = eval(self.code, frame.f_globals or {}, frame.f_locals)
except Exception:
return ()
return self._items(main_value)
def _items(self, key):
raise NotImplementedError
class CommonVariable(BaseVariable):
def _items(self, main_value):
result = [(self.source, main_value)]
for key in self._safe_keys(main_value):
try:
if key in self.exclude:
continue
value = self._get_value(main_value, key)
except Exception:
continue
result.append((
'{}{}'.format(self.unambiguous_source, self._format_key(key)),
value,
))
return result
<|code_end|>
. Write the next line using the current file imports:
import itertools
import six
from copy import deepcopy
from snoop.utils import with_needed_parentheses, my_cheap_repr, ensure_tuple
from collections import Mapping, Sequence
from collections.abc import Mapping, Sequence
and context from other files:
# Path: snoop/utils.py
# def with_needed_parentheses(source):
# if needs_parentheses(source):
# return '({})'.format(source)
# else:
# return source
#
# def my_cheap_repr(x):
# return cheap_repr(x, target_length=REPR_TARGET_LENGTH)
#
# def ensure_tuple(x, split=False):
# if split and isinstance(x, six.string_types):
# x = x.replace(',', ' ').split()
# if not isinstance(x, (list, set, tuple)):
# x = (x,)
# return tuple(x)
, which may include functions, classes, or code. Output only the next line. | def _safe_keys(self, main_value): |
Predict the next line after this snippet: <|code_start|>
if six.PY2:
else:
class BaseVariable(object):
def __init__(self, source, exclude=()):
self.source = source
self.exclude = ensure_tuple(exclude)
self.code = compile(source, '<variable>', 'eval')
self.unambiguous_source = with_needed_parentheses(source)
def items(self, frame):
try:
main_value = eval(self.code, frame.f_globals or {}, frame.f_locals)
<|code_end|>
using the current file's imports:
import itertools
import six
from copy import deepcopy
from snoop.utils import with_needed_parentheses, my_cheap_repr, ensure_tuple
from collections import Mapping, Sequence
from collections.abc import Mapping, Sequence
and any relevant context from other files:
# Path: snoop/utils.py
# def with_needed_parentheses(source):
# if needs_parentheses(source):
# return '({})'.format(source)
# else:
# return source
#
# def my_cheap_repr(x):
# return cheap_repr(x, target_length=REPR_TARGET_LENGTH)
#
# def ensure_tuple(x, split=False):
# if split and isinstance(x, six.string_types):
# x = x.replace(',', ' ').split()
# if not isinstance(x, (list, set, tuple)):
# x = (x,)
# return tuple(x)
. Output only the next line. | except Exception: |
Using the snippet: <|code_start|>
snoop = Config(columns='time thread thread_ident file full_file function function_qualname').snoop
def main():
@snoop
def foo():
x = 1
<|code_end|>
, determine the next line of code. You have imports:
from snoop.configuration import Config
and context (class names, function names, or code) available:
# Path: snoop/configuration.py
# class Config(object):
# """"
# If you need more control than the global `install` function, e.g. if you want to write to several different files in one process, you can create a `Config` object, e.g: `config = snoop.Config(out=filename)`. Then `config.snoop`, `config.pp` and `config.spy` will use that configuration rather than the global one.
#
# The arguments are the same as the arguments of `install()` relating to output configuration and `enabled`.
# """
#
# def __init__(
# self,
# out=None,
# prefix='',
# columns='time',
# overwrite=False,
# color=None,
# enabled=True,
# watch_extras=(),
# replace_watch_extras=None,
# formatter_class=DefaultFormatter,
# pformat=None,
# ):
# if can_color:
# if color is None:
# isatty = getattr(out or sys.stderr, 'isatty', lambda: False)
# color = bool(isatty())
# else:
# color = False
#
# self.write = get_write_function(out, overwrite)
# self.formatter = formatter_class(prefix, columns, color)
# self.enabled = enabled
#
# if pformat is None:
# try:
# from prettyprinter import pformat
# except Exception:
# try:
# from pprintpp import pformat
# except Exception:
# from pprint import pformat
#
# self.pformat = pformat
#
# self.pp = PP(self)
#
# class ConfiguredTracer(Tracer):
# config = self
#
# self.snoop = ConfiguredTracer
# self.spy = Spy(self)
#
# self.last_frame = None
# self.thread_local = threading.local()
#
# if replace_watch_extras is not None:
# self.watch_extras = ensure_tuple(replace_watch_extras)
# else:
# self.watch_extras = (len_shape_watch, dtype_watch) + ensure_tuple(watch_extras)
. Output only the next line. | y = x + 2 |
Next line prediction: <|code_start|>from __future__ import print_function
config = Config(color=True)
snoop = config.snoop
pp = config.pp
def foo():
raise TypeError
@snoop(depth=2)
def main():
try:
(None
or foo)()
except:
pass
pp(
[
x + y
for x, y in zip(range(1000, 1020), range(2000, 2020))
]
<|code_end|>
. Use current file imports:
(from snoop import Config)
and context including class names, function names, or small code snippets from other files:
# Path: snoop/configuration.py
# class Config(object):
# """"
# If you need more control than the global `install` function, e.g. if you want to write to several different files in one process, you can create a `Config` object, e.g: `config = snoop.Config(out=filename)`. Then `config.snoop`, `config.pp` and `config.spy` will use that configuration rather than the global one.
#
# The arguments are the same as the arguments of `install()` relating to output configuration and `enabled`.
# """
#
# def __init__(
# self,
# out=None,
# prefix='',
# columns='time',
# overwrite=False,
# color=None,
# enabled=True,
# watch_extras=(),
# replace_watch_extras=None,
# formatter_class=DefaultFormatter,
# pformat=None,
# ):
# if can_color:
# if color is None:
# isatty = getattr(out or sys.stderr, 'isatty', lambda: False)
# color = bool(isatty())
# else:
# color = False
#
# self.write = get_write_function(out, overwrite)
# self.formatter = formatter_class(prefix, columns, color)
# self.enabled = enabled
#
# if pformat is None:
# try:
# from prettyprinter import pformat
# except Exception:
# try:
# from pprintpp import pformat
# except Exception:
# from pprint import pformat
#
# self.pformat = pformat
#
# self.pp = PP(self)
#
# class ConfiguredTracer(Tracer):
# config = self
#
# self.snoop = ConfiguredTracer
# self.spy = Spy(self)
#
# self.last_frame = None
# self.thread_local = threading.local()
#
# if replace_watch_extras is not None:
# self.watch_extras = ensure_tuple(replace_watch_extras)
# else:
# self.watch_extras = (len_shape_watch, dtype_watch) + ensure_tuple(watch_extras)
. Output only the next line. | ) |
Continue the code snippet: <|code_start|>
snoop = Config(prefix='ZZZ').snoop
class Baz(object):
def __init__(self):
self.x = 2
@snoop(watch='self.x')
def square(self):
foo = 7
<|code_end|>
. Use current file imports:
from snoop.configuration import Config
and context (classes, functions, or code) from other files:
# Path: snoop/configuration.py
# class Config(object):
# """"
# If you need more control than the global `install` function, e.g. if you want to write to several different files in one process, you can create a `Config` object, e.g: `config = snoop.Config(out=filename)`. Then `config.snoop`, `config.pp` and `config.spy` will use that configuration rather than the global one.
#
# The arguments are the same as the arguments of `install()` relating to output configuration and `enabled`.
# """
#
# def __init__(
# self,
# out=None,
# prefix='',
# columns='time',
# overwrite=False,
# color=None,
# enabled=True,
# watch_extras=(),
# replace_watch_extras=None,
# formatter_class=DefaultFormatter,
# pformat=None,
# ):
# if can_color:
# if color is None:
# isatty = getattr(out or sys.stderr, 'isatty', lambda: False)
# color = bool(isatty())
# else:
# color = False
#
# self.write = get_write_function(out, overwrite)
# self.formatter = formatter_class(prefix, columns, color)
# self.enabled = enabled
#
# if pformat is None:
# try:
# from prettyprinter import pformat
# except Exception:
# try:
# from pprintpp import pformat
# except Exception:
# from pprint import pformat
#
# self.pformat = pformat
#
# self.pp = PP(self)
#
# class ConfiguredTracer(Tracer):
# config = self
#
# self.snoop = ConfiguredTracer
# self.spy = Spy(self)
#
# self.last_frame = None
# self.thread_local = threading.local()
#
# if replace_watch_extras is not None:
# self.watch_extras = ensure_tuple(replace_watch_extras)
# else:
# self.watch_extras = (len_shape_watch, dtype_watch) + ensure_tuple(watch_extras)
. Output only the next line. | self.x **= 2 |
Predict the next line for this snippet: <|code_start|>
@snoop
def main():
x = 1
y = 2
try:
pp.deep(lambda: x + y + bad() + 2)
except:
sample_traceback()
def bad():
<|code_end|>
with the help of current file imports:
from tests.test_snoop import sample_traceback
and context from other files:
# Path: tests/test_snoop.py
# def sample_traceback():
# raw = u''.join(
# traceback.format_exception(*sys.exc_info())
# ).splitlines(True)
# tb = u''.join(
# line for line in raw
# if not line.strip().startswith("File")
# if not line.strip() == "raise value" # part of six.reraise
# )
# sys.stderr.write(tb)
, which may contain function names, class names, or code. Output only the next line. | raise TypeError('bad') |
Given the code snippet: <|code_start|>
try:
except ImportError:
class StatementsDict(dict):
def __init__(self, source):
super(StatementsDict, self).__init__()
self.source = source
def __missing__(self, key):
statements = self.source.statements_at_line(key)
if len(statements) == 1:
result = list(statements)[0]
else:
result = None
self[key] = result
return result
class Source(executing.Source):
def __init__(self, *args, **kwargs):
super(Source, self).__init__(*args, **kwargs)
if self.tree and self.text:
self.highlighted = ArgDefaultDict(
lambda style: raw_highlight(self.text, style).splitlines()
)
else:
<|code_end|>
, generate the next line using the imports in this file:
import ast
import opcode
import threading
import traceback
import executing
import six
from collections import defaultdict
from datetime import datetime
from textwrap import dedent
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.python import Python3Lexer
from pygments.styles.monokai import MonokaiStyle
from six import PY3
from snoop.utils import ensure_tuple, short_filename, my_cheap_repr, \
NO_ASTTOKENS, optional_numeric_label, try_statement, FormattedValue, ArgDefaultDict, lru_cache
from pygments.lexers.python import Python2Lexer
from pygments.lexers.python import PythonLexer as Python2Lexer
and context (functions, classes, or occasionally code) from other files:
# Path: snoop/utils.py
# PY34 = sys.version_info[:2] == (3, 4)
# NO_ASTTOKENS = PY34
# PYPY = 'pypy' in sys.version.lower()
# NO_BIRDSEYE = NO_ASTTOKENS or PYPY
# REPR_TARGET_LENGTH = 100
# def shitcode(s):
# def truncate(seq, max_length, middle):
# def truncate_string(string, max_length):
# def truncate_list(lst, max_length):
# def ensure_tuple(x, split=False):
# def short_filename(code):
# def is_comprehension_frame(frame):
# def needs_parentheses(source):
# def code(s):
# def with_needed_parentheses(source):
# def my_cheap_repr(x):
# def __init__(self, factory):
# def __missing__(self, key):
# def optional_numeric_label(i, lst):
# def is_pathlike(x):
# def iscoroutinefunction(_):
# def no_args_decorator(args, kwargs):
# def __repr__(self):
# def _register_cheap_reprs():
# def _sample_indices(length, max_length):
# def _repr_series_one_line(x, helper):
# class ArgDefaultDict(dict):
# class FormattedValue(object):
# class DirectRepr(str):
# class QuerySet(object):
. Output only the next line. | self.lines = defaultdict(lambda: u'SOURCE IS UNAVAILABLE') |
Continue the code snippet: <|code_start|>
try:
except ImportError:
class StatementsDict(dict):
def __init__(self, source):
super(StatementsDict, self).__init__()
self.source = source
def __missing__(self, key):
statements = self.source.statements_at_line(key)
<|code_end|>
. Use current file imports:
import ast
import opcode
import threading
import traceback
import executing
import six
from collections import defaultdict
from datetime import datetime
from textwrap import dedent
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.python import Python3Lexer
from pygments.styles.monokai import MonokaiStyle
from six import PY3
from snoop.utils import ensure_tuple, short_filename, my_cheap_repr, \
NO_ASTTOKENS, optional_numeric_label, try_statement, FormattedValue, ArgDefaultDict, lru_cache
from pygments.lexers.python import Python2Lexer
from pygments.lexers.python import PythonLexer as Python2Lexer
and context (classes, functions, or code) from other files:
# Path: snoop/utils.py
# PY34 = sys.version_info[:2] == (3, 4)
# NO_ASTTOKENS = PY34
# PYPY = 'pypy' in sys.version.lower()
# NO_BIRDSEYE = NO_ASTTOKENS or PYPY
# REPR_TARGET_LENGTH = 100
# def shitcode(s):
# def truncate(seq, max_length, middle):
# def truncate_string(string, max_length):
# def truncate_list(lst, max_length):
# def ensure_tuple(x, split=False):
# def short_filename(code):
# def is_comprehension_frame(frame):
# def needs_parentheses(source):
# def code(s):
# def with_needed_parentheses(source):
# def my_cheap_repr(x):
# def __init__(self, factory):
# def __missing__(self, key):
# def optional_numeric_label(i, lst):
# def is_pathlike(x):
# def iscoroutinefunction(_):
# def no_args_decorator(args, kwargs):
# def __repr__(self):
# def _register_cheap_reprs():
# def _sample_indices(length, max_length):
# def _repr_series_one_line(x, helper):
# class ArgDefaultDict(dict):
# class FormattedValue(object):
# class DirectRepr(str):
# class QuerySet(object):
. Output only the next line. | if len(statements) == 1: |
Predict the next line after this snippet: <|code_start|>class StatementsDict(dict):
def __init__(self, source):
super(StatementsDict, self).__init__()
self.source = source
def __missing__(self, key):
statements = self.source.statements_at_line(key)
if len(statements) == 1:
result = list(statements)[0]
else:
result = None
self[key] = result
return result
class Source(executing.Source):
def __init__(self, *args, **kwargs):
super(Source, self).__init__(*args, **kwargs)
if self.tree and self.text:
self.highlighted = ArgDefaultDict(
lambda style: raw_highlight(self.text, style).splitlines()
)
else:
self.lines = defaultdict(lambda: u'SOURCE IS UNAVAILABLE')
self.highlighted = defaultdict(lambda: self.lines)
self.statements = StatementsDict(self)
self.nodes = []
if self.tree:
self.tree._depth = 0
for node in ast.walk(self.tree):
<|code_end|>
using the current file's imports:
import ast
import opcode
import threading
import traceback
import executing
import six
from collections import defaultdict
from datetime import datetime
from textwrap import dedent
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.python import Python3Lexer
from pygments.styles.monokai import MonokaiStyle
from six import PY3
from snoop.utils import ensure_tuple, short_filename, my_cheap_repr, \
NO_ASTTOKENS, optional_numeric_label, try_statement, FormattedValue, ArgDefaultDict, lru_cache
from pygments.lexers.python import Python2Lexer
from pygments.lexers.python import PythonLexer as Python2Lexer
and any relevant context from other files:
# Path: snoop/utils.py
# PY34 = sys.version_info[:2] == (3, 4)
# NO_ASTTOKENS = PY34
# PYPY = 'pypy' in sys.version.lower()
# NO_BIRDSEYE = NO_ASTTOKENS or PYPY
# REPR_TARGET_LENGTH = 100
# def shitcode(s):
# def truncate(seq, max_length, middle):
# def truncate_string(string, max_length):
# def truncate_list(lst, max_length):
# def ensure_tuple(x, split=False):
# def short_filename(code):
# def is_comprehension_frame(frame):
# def needs_parentheses(source):
# def code(s):
# def with_needed_parentheses(source):
# def my_cheap_repr(x):
# def __init__(self, factory):
# def __missing__(self, key):
# def optional_numeric_label(i, lst):
# def is_pathlike(x):
# def iscoroutinefunction(_):
# def no_args_decorator(args, kwargs):
# def __repr__(self):
# def _register_cheap_reprs():
# def _sample_indices(length, max_length):
# def _repr_series_one_line(x, helper):
# class ArgDefaultDict(dict):
# class FormattedValue(object):
# class DirectRepr(str):
# class QuerySet(object):
. Output only the next line. | node._tree_index = len(self.nodes) |
Given snippet: <|code_start|>
try:
except ImportError:
class StatementsDict(dict):
def __init__(self, source):
super(StatementsDict, self).__init__()
self.source = source
def __missing__(self, key):
statements = self.source.statements_at_line(key)
if len(statements) == 1:
result = list(statements)[0]
else:
result = None
self[key] = result
return result
class Source(executing.Source):
def __init__(self, *args, **kwargs):
super(Source, self).__init__(*args, **kwargs)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import ast
import opcode
import threading
import traceback
import executing
import six
from collections import defaultdict
from datetime import datetime
from textwrap import dedent
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.python import Python3Lexer
from pygments.styles.monokai import MonokaiStyle
from six import PY3
from snoop.utils import ensure_tuple, short_filename, my_cheap_repr, \
NO_ASTTOKENS, optional_numeric_label, try_statement, FormattedValue, ArgDefaultDict, lru_cache
from pygments.lexers.python import Python2Lexer
from pygments.lexers.python import PythonLexer as Python2Lexer
and context:
# Path: snoop/utils.py
# PY34 = sys.version_info[:2] == (3, 4)
# NO_ASTTOKENS = PY34
# PYPY = 'pypy' in sys.version.lower()
# NO_BIRDSEYE = NO_ASTTOKENS or PYPY
# REPR_TARGET_LENGTH = 100
# def shitcode(s):
# def truncate(seq, max_length, middle):
# def truncate_string(string, max_length):
# def truncate_list(lst, max_length):
# def ensure_tuple(x, split=False):
# def short_filename(code):
# def is_comprehension_frame(frame):
# def needs_parentheses(source):
# def code(s):
# def with_needed_parentheses(source):
# def my_cheap_repr(x):
# def __init__(self, factory):
# def __missing__(self, key):
# def optional_numeric_label(i, lst):
# def is_pathlike(x):
# def iscoroutinefunction(_):
# def no_args_decorator(args, kwargs):
# def __repr__(self):
# def _register_cheap_reprs():
# def _sample_indices(length, max_length):
# def _repr_series_one_line(x, helper):
# class ArgDefaultDict(dict):
# class FormattedValue(object):
# class DirectRepr(str):
# class QuerySet(object):
which might include code, classes, or functions. Output only the next line. | if self.tree and self.text: |
Next line prediction: <|code_start|> def __missing__(self, key):
statements = self.source.statements_at_line(key)
if len(statements) == 1:
result = list(statements)[0]
else:
result = None
self[key] = result
return result
class Source(executing.Source):
def __init__(self, *args, **kwargs):
super(Source, self).__init__(*args, **kwargs)
if self.tree and self.text:
self.highlighted = ArgDefaultDict(
lambda style: raw_highlight(self.text, style).splitlines()
)
else:
self.lines = defaultdict(lambda: u'SOURCE IS UNAVAILABLE')
self.highlighted = defaultdict(lambda: self.lines)
self.statements = StatementsDict(self)
self.nodes = []
if self.tree:
self.tree._depth = 0
for node in ast.walk(self.tree):
node._tree_index = len(self.nodes)
self.nodes.append(node)
for child in ast.iter_child_nodes(node):
child._depth = node._depth + 1
<|code_end|>
. Use current file imports:
(import ast
import opcode
import threading
import traceback
import executing
import six
from collections import defaultdict
from datetime import datetime
from textwrap import dedent
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.python import Python3Lexer
from pygments.styles.monokai import MonokaiStyle
from six import PY3
from snoop.utils import ensure_tuple, short_filename, my_cheap_repr, \
NO_ASTTOKENS, optional_numeric_label, try_statement, FormattedValue, ArgDefaultDict, lru_cache
from pygments.lexers.python import Python2Lexer
from pygments.lexers.python import PythonLexer as Python2Lexer)
and context including class names, function names, or small code snippets from other files:
# Path: snoop/utils.py
# PY34 = sys.version_info[:2] == (3, 4)
# NO_ASTTOKENS = PY34
# PYPY = 'pypy' in sys.version.lower()
# NO_BIRDSEYE = NO_ASTTOKENS or PYPY
# REPR_TARGET_LENGTH = 100
# def shitcode(s):
# def truncate(seq, max_length, middle):
# def truncate_string(string, max_length):
# def truncate_list(lst, max_length):
# def ensure_tuple(x, split=False):
# def short_filename(code):
# def is_comprehension_frame(frame):
# def needs_parentheses(source):
# def code(s):
# def with_needed_parentheses(source):
# def my_cheap_repr(x):
# def __init__(self, factory):
# def __missing__(self, key):
# def optional_numeric_label(i, lst):
# def is_pathlike(x):
# def iscoroutinefunction(_):
# def no_args_decorator(args, kwargs):
# def __repr__(self):
# def _register_cheap_reprs():
# def _sample_indices(length, max_length):
# def _repr_series_one_line(x, helper):
# class ArgDefaultDict(dict):
# class FormattedValue(object):
# class DirectRepr(str):
# class QuerySet(object):
. Output only the next line. | def get_text_with_indentation(self, node): |
Predict the next line after this snippet: <|code_start|> statements = self.source.statements_at_line(key)
if len(statements) == 1:
result = list(statements)[0]
else:
result = None
self[key] = result
return result
class Source(executing.Source):
def __init__(self, *args, **kwargs):
super(Source, self).__init__(*args, **kwargs)
if self.tree and self.text:
self.highlighted = ArgDefaultDict(
lambda style: raw_highlight(self.text, style).splitlines()
)
else:
self.lines = defaultdict(lambda: u'SOURCE IS UNAVAILABLE')
self.highlighted = defaultdict(lambda: self.lines)
self.statements = StatementsDict(self)
self.nodes = []
if self.tree:
self.tree._depth = 0
for node in ast.walk(self.tree):
node._tree_index = len(self.nodes)
self.nodes.append(node)
for child in ast.iter_child_nodes(node):
child._depth = node._depth + 1
def get_text_with_indentation(self, node):
<|code_end|>
using the current file's imports:
import ast
import opcode
import threading
import traceback
import executing
import six
from collections import defaultdict
from datetime import datetime
from textwrap import dedent
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.python import Python3Lexer
from pygments.styles.monokai import MonokaiStyle
from six import PY3
from snoop.utils import ensure_tuple, short_filename, my_cheap_repr, \
NO_ASTTOKENS, optional_numeric_label, try_statement, FormattedValue, ArgDefaultDict, lru_cache
from pygments.lexers.python import Python2Lexer
from pygments.lexers.python import PythonLexer as Python2Lexer
and any relevant context from other files:
# Path: snoop/utils.py
# PY34 = sys.version_info[:2] == (3, 4)
# NO_ASTTOKENS = PY34
# PYPY = 'pypy' in sys.version.lower()
# NO_BIRDSEYE = NO_ASTTOKENS or PYPY
# REPR_TARGET_LENGTH = 100
# def shitcode(s):
# def truncate(seq, max_length, middle):
# def truncate_string(string, max_length):
# def truncate_list(lst, max_length):
# def ensure_tuple(x, split=False):
# def short_filename(code):
# def is_comprehension_frame(frame):
# def needs_parentheses(source):
# def code(s):
# def with_needed_parentheses(source):
# def my_cheap_repr(x):
# def __init__(self, factory):
# def __missing__(self, key):
# def optional_numeric_label(i, lst):
# def is_pathlike(x):
# def iscoroutinefunction(_):
# def no_args_decorator(args, kwargs):
# def __repr__(self):
# def _register_cheap_reprs():
# def _sample_indices(length, max_length):
# def _repr_series_one_line(x, helper):
# class ArgDefaultDict(dict):
# class FormattedValue(object):
# class DirectRepr(str):
# class QuerySet(object):
. Output only the next line. | result = self.asttokens().get_text(node) |
Predict the next line after this snippet: <|code_start|> result = None
self[key] = result
return result
class Source(executing.Source):
def __init__(self, *args, **kwargs):
super(Source, self).__init__(*args, **kwargs)
if self.tree and self.text:
self.highlighted = ArgDefaultDict(
lambda style: raw_highlight(self.text, style).splitlines()
)
else:
self.lines = defaultdict(lambda: u'SOURCE IS UNAVAILABLE')
self.highlighted = defaultdict(lambda: self.lines)
self.statements = StatementsDict(self)
self.nodes = []
if self.tree:
self.tree._depth = 0
for node in ast.walk(self.tree):
node._tree_index = len(self.nodes)
self.nodes.append(node)
for child in ast.iter_child_nodes(node):
child._depth = node._depth + 1
def get_text_with_indentation(self, node):
result = self.asttokens().get_text(node)
if not result:
if isinstance(node, FormattedValue):
<|code_end|>
using the current file's imports:
import ast
import opcode
import threading
import traceback
import executing
import six
from collections import defaultdict
from datetime import datetime
from textwrap import dedent
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.python import Python3Lexer
from pygments.styles.monokai import MonokaiStyle
from six import PY3
from snoop.utils import ensure_tuple, short_filename, my_cheap_repr, \
NO_ASTTOKENS, optional_numeric_label, try_statement, FormattedValue, ArgDefaultDict, lru_cache
from pygments.lexers.python import Python2Lexer
from pygments.lexers.python import PythonLexer as Python2Lexer
and any relevant context from other files:
# Path: snoop/utils.py
# PY34 = sys.version_info[:2] == (3, 4)
# NO_ASTTOKENS = PY34
# PYPY = 'pypy' in sys.version.lower()
# NO_BIRDSEYE = NO_ASTTOKENS or PYPY
# REPR_TARGET_LENGTH = 100
# def shitcode(s):
# def truncate(seq, max_length, middle):
# def truncate_string(string, max_length):
# def truncate_list(lst, max_length):
# def ensure_tuple(x, split=False):
# def short_filename(code):
# def is_comprehension_frame(frame):
# def needs_parentheses(source):
# def code(s):
# def with_needed_parentheses(source):
# def my_cheap_repr(x):
# def __init__(self, factory):
# def __missing__(self, key):
# def optional_numeric_label(i, lst):
# def is_pathlike(x):
# def iscoroutinefunction(_):
# def no_args_decorator(args, kwargs):
# def __repr__(self):
# def _register_cheap_reprs():
# def _sample_indices(length, max_length):
# def _repr_series_one_line(x, helper):
# class ArgDefaultDict(dict):
# class FormattedValue(object):
# class DirectRepr(str):
# class QuerySet(object):
. Output only the next line. | fvals = [ |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
class StatementsDict(dict):
def __init__(self, source):
super(StatementsDict, self).__init__()
self.source = source
def __missing__(self, key):
statements = self.source.statements_at_line(key)
if len(statements) == 1:
result = list(statements)[0]
else:
<|code_end|>
with the help of current file imports:
import ast
import opcode
import threading
import traceback
import executing
import six
from collections import defaultdict
from datetime import datetime
from textwrap import dedent
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.python import Python3Lexer
from pygments.styles.monokai import MonokaiStyle
from six import PY3
from snoop.utils import ensure_tuple, short_filename, my_cheap_repr, \
NO_ASTTOKENS, optional_numeric_label, try_statement, FormattedValue, ArgDefaultDict, lru_cache
from pygments.lexers.python import Python2Lexer
from pygments.lexers.python import PythonLexer as Python2Lexer
and context from other files:
# Path: snoop/utils.py
# PY34 = sys.version_info[:2] == (3, 4)
# NO_ASTTOKENS = PY34
# PYPY = 'pypy' in sys.version.lower()
# NO_BIRDSEYE = NO_ASTTOKENS or PYPY
# REPR_TARGET_LENGTH = 100
# def shitcode(s):
# def truncate(seq, max_length, middle):
# def truncate_string(string, max_length):
# def truncate_list(lst, max_length):
# def ensure_tuple(x, split=False):
# def short_filename(code):
# def is_comprehension_frame(frame):
# def needs_parentheses(source):
# def code(s):
# def with_needed_parentheses(source):
# def my_cheap_repr(x):
# def __init__(self, factory):
# def __missing__(self, key):
# def optional_numeric_label(i, lst):
# def is_pathlike(x):
# def iscoroutinefunction(_):
# def no_args_decorator(args, kwargs):
# def __repr__(self):
# def _register_cheap_reprs():
# def _sample_indices(length, max_length):
# def _repr_series_one_line(x, helper):
# class ArgDefaultDict(dict):
# class FormattedValue(object):
# class DirectRepr(str):
# class QuerySet(object):
, which may contain function names, class names, or code. Output only the next line. | result = None |
Here is a snippet: <|code_start|>
snoop = Config(columns='').snoop
@snoop
def main():
<|code_end|>
. Write the next line using the current file imports:
from snoop.configuration import Config
and context from other files:
# Path: snoop/configuration.py
# class Config(object):
# """"
# If you need more control than the global `install` function, e.g. if you want to write to several different files in one process, you can create a `Config` object, e.g: `config = snoop.Config(out=filename)`. Then `config.snoop`, `config.pp` and `config.spy` will use that configuration rather than the global one.
#
# The arguments are the same as the arguments of `install()` relating to output configuration and `enabled`.
# """
#
# def __init__(
# self,
# out=None,
# prefix='',
# columns='time',
# overwrite=False,
# color=None,
# enabled=True,
# watch_extras=(),
# replace_watch_extras=None,
# formatter_class=DefaultFormatter,
# pformat=None,
# ):
# if can_color:
# if color is None:
# isatty = getattr(out or sys.stderr, 'isatty', lambda: False)
# color = bool(isatty())
# else:
# color = False
#
# self.write = get_write_function(out, overwrite)
# self.formatter = formatter_class(prefix, columns, color)
# self.enabled = enabled
#
# if pformat is None:
# try:
# from prettyprinter import pformat
# except Exception:
# try:
# from pprintpp import pformat
# except Exception:
# from pprint import pformat
#
# self.pformat = pformat
#
# self.pp = PP(self)
#
# class ConfiguredTracer(Tracer):
# config = self
#
# self.snoop = ConfiguredTracer
# self.spy = Spy(self)
#
# self.last_frame = None
# self.thread_local = threading.local()
#
# if replace_watch_extras is not None:
# self.watch_extras = ensure_tuple(replace_watch_extras)
# else:
# self.watch_extras = (len_shape_watch, dtype_watch) + ensure_tuple(watch_extras)
, which may include functions, classes, or code. Output only the next line. | x = 1 |
Using the snippet: <|code_start|>
snoop = Config(columns='thread').snoop
@snoop
def foo():
return 1
def run(name):
thread = Thread(target=foo, name=name)
thread.start()
<|code_end|>
, determine the next line of code. You have imports:
from threading import Thread
from snoop.configuration import Config
and context (class names, function names, or code) available:
# Path: snoop/configuration.py
# class Config(object):
# """"
# If you need more control than the global `install` function, e.g. if you want to write to several different files in one process, you can create a `Config` object, e.g: `config = snoop.Config(out=filename)`. Then `config.snoop`, `config.pp` and `config.spy` will use that configuration rather than the global one.
#
# The arguments are the same as the arguments of `install()` relating to output configuration and `enabled`.
# """
#
# def __init__(
# self,
# out=None,
# prefix='',
# columns='time',
# overwrite=False,
# color=None,
# enabled=True,
# watch_extras=(),
# replace_watch_extras=None,
# formatter_class=DefaultFormatter,
# pformat=None,
# ):
# if can_color:
# if color is None:
# isatty = getattr(out or sys.stderr, 'isatty', lambda: False)
# color = bool(isatty())
# else:
# color = False
#
# self.write = get_write_function(out, overwrite)
# self.formatter = formatter_class(prefix, columns, color)
# self.enabled = enabled
#
# if pformat is None:
# try:
# from prettyprinter import pformat
# except Exception:
# try:
# from pprintpp import pformat
# except Exception:
# from pprint import pformat
#
# self.pformat = pformat
#
# self.pp = PP(self)
#
# class ConfiguredTracer(Tracer):
# config = self
#
# self.snoop = ConfiguredTracer
# self.spy = Spy(self)
#
# self.last_frame = None
# self.thread_local = threading.local()
#
# if replace_watch_extras is not None:
# self.watch_extras = ensure_tuple(replace_watch_extras)
# else:
# self.watch_extras = (len_shape_watch, dtype_watch) + ensure_tuple(watch_extras)
. Output only the next line. | thread.join() |
Based on the snippet: <|code_start|>
class FakeResponse(object):
json_data = {}
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def json(self):
return self.json_data
class ExceptionsArgsTest(test_base.BaseTestCase):
def assert_exception(self, ex_cls, method, url, status_code, json_data,
error_msg=None, error_details=None,
check_description=True):
ex = exceptions.from_response(
FakeResponse(status_code=status_code,
headers={"Content-Type": "application/json"},
json_data=json_data),
method,
url)
self.assertIsInstance(ex, ex_cls)
if check_description:
expected_msg = error_msg or json_data["error"]["message"]
expected_details = error_details or json_data["error"]["details"]
<|code_end|>
, predict the immediate next line with the help of imports:
from http import client as http_client
from oslotest import base as test_base
from ironicclient.common.apiclient import exceptions
and context (classes, functions, sometimes code) from other files:
# Path: ironicclient/common/apiclient/exceptions.py
# class ClientException(Exception):
# class ValidationError(ClientException):
# class UnsupportedVersion(ClientException):
# class CommandError(ClientException):
# class AuthorizationFailure(ClientException):
# class ConnectionError(ClientException):
# class ConnectionRefused(ConnectionError):
# class AuthPluginOptionsMissing(AuthorizationFailure):
# class AuthSystemNotFound(AuthorizationFailure):
# class NoUniqueMatch(ClientException):
# class EndpointException(ClientException):
# class EndpointNotFound(EndpointException):
# class AmbiguousEndpoints(EndpointException):
# class HttpError(ClientException):
# class HTTPRedirection(HttpError):
# class HTTPClientError(HttpError):
# class HttpServerError(HttpError):
# class MultipleChoices(HTTPRedirection):
# class BadRequest(HTTPClientError):
# class Unauthorized(HTTPClientError):
# class PaymentRequired(HTTPClientError):
# class Forbidden(HTTPClientError):
# class NotFound(HTTPClientError):
# class MethodNotAllowed(HTTPClientError):
# class NotAcceptable(HTTPClientError):
# class ProxyAuthenticationRequired(HTTPClientError):
# class RequestTimeout(HTTPClientError):
# class Conflict(HTTPClientError):
# class Gone(HTTPClientError):
# class LengthRequired(HTTPClientError):
# class PreconditionFailed(HTTPClientError):
# class RequestEntityTooLarge(HTTPClientError):
# class RequestUriTooLong(HTTPClientError):
# class UnsupportedMediaType(HTTPClientError):
# class RequestedRangeNotSatisfiable(HTTPClientError):
# class ExpectationFailed(HTTPClientError):
# class UnprocessableEntity(HTTPClientError):
# class InternalServerError(HttpServerError):
# class HttpNotImplemented(HttpServerError):
# class BadGateway(HttpServerError):
# class ServiceUnavailable(HttpServerError):
# class GatewayTimeout(HttpServerError):
# class HttpVersionNotSupported(HttpServerError):
# def __init__(self, opt_names):
# def __init__(self, auth_system):
# def __init__(self, endpoints=None):
# def __init__(self, message=None, details=None,
# response=None, request_id=None,
# url=None, method=None, http_status=None):
# def __init__(self, *args, **kwargs):
# def from_response(response, method, url):
. Output only the next line. | self.assertEqual(expected_msg, ex.message) |
Given snippet: <|code_start|>
self.xorrisofs_cmd = ['xorrisofs', '-o', mock.ANY,
'-ldots', '-allow-lowercase',
'-allow-multidot', '-l',
'-publisher', 'ironicclient-configdrive 0.1',
'-quiet', '-J', '-r', '-V',
'config-2', mock.ANY]
def test_make_configdrive(self, mock_popen):
fake_process = mock.Mock(returncode=0)
fake_process.communicate.return_value = ('', '')
mock_popen.return_value = fake_process
with utils.tempdir() as dirname:
utils.make_configdrive(dirname)
mock_popen.assert_called_once_with(self.genisoimage_cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
fake_process.communicate.assert_called_once_with()
def test_make_configdrive_fallsback(self, mock_popen):
fake_process = mock.Mock(returncode=0)
fake_process.communicate.return_value = ('', '')
mock_popen.side_effect = iter([OSError('boom'),
OSError('boom'),
fake_process])
with utils.tempdir() as dirname:
utils.make_configdrive(dirname)
mock_popen.assert_has_calls([
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import builtins
import json
import os
import subprocess
import sys
import tempfile
from unittest import mock
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.tests.unit import utils as test_utils
and context:
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
which might include code, classes, or functions. Output only the next line. | mock.call(self.genisoimage_cmd, stderr=subprocess.PIPE, |
Given the code snippet: <|code_start|> self.assertRaises(exc.CommandError,
utils.common_params_for_list,
self.args,
['field', 'field2'],
[])
def test_sort_dir_invalid(self):
self.args.sort_dir = 'something'
self.assertRaises(exc.CommandError,
utils.common_params_for_list,
self.args,
[],
[])
def test_detail(self):
self.args.detail = True
self.expected_params['detail'] = True
self.assertEqual(self.expected_params,
utils.common_params_for_list(self.args, [], []))
def test_fields(self):
self.args.fields = [['a', 'b', 'c']]
self.expected_params.update({'fields': ['a', 'b', 'c']})
self.assertEqual(self.expected_params,
utils.common_params_for_list(self.args, [], []))
class CommonFiltersTest(test_utils.BaseTestCase):
def test_limit(self):
result = utils.common_filters(limit=42)
<|code_end|>
, generate the next line using the imports in this file:
import builtins
import json
import os
import subprocess
import sys
import tempfile
from unittest import mock
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.tests.unit import utils as test_utils
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | self.assertEqual(['limit=42'], result) |
Given the following code snippet before the placeholder: <|code_start|> ])
fake_process.communicate.assert_called_once_with()
@mock.patch.object(os, 'access', autospec=True)
def test_make_configdrive_non_readable_dir(self, mock_access, mock_popen):
mock_access.return_value = False
self.assertRaises(exc.CommandError, utils.make_configdrive, 'fake-dir')
mock_access.assert_called_once_with('fake-dir', os.R_OK)
self.assertFalse(mock_popen.called)
@mock.patch.object(os, 'access', autospec=True)
def test_make_configdrive_oserror(self, mock_access, mock_popen):
mock_access.return_value = True
mock_popen.side_effect = OSError('boom')
self.assertRaises(exc.CommandError, utils.make_configdrive, 'fake-dir')
mock_access.assert_called_once_with('fake-dir', os.R_OK)
mock_popen.assert_has_calls([
mock.call(self.genisoimage_cmd, stderr=subprocess.PIPE,
stdout=subprocess.PIPE),
mock.call(self.mkisofs_cmd, stderr=subprocess.PIPE,
stdout=subprocess.PIPE),
mock.call(self.xorrisofs_cmd, stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
])
@mock.patch.object(os, 'access', autospec=True)
def test_make_configdrive_non_zero_returncode(self, mock_access,
mock_popen):
fake_process = mock.Mock(returncode=123)
<|code_end|>
, predict the next line using imports from the current file:
import builtins
import json
import os
import subprocess
import sys
import tempfile
from unittest import mock
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.tests.unit import utils as test_utils
and context including class names, function names, and sometimes code from other files:
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | fake_process.communicate.return_value = ('', '') |
Given the following code snippet before the placeholder: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
FAKE_EVENT = {"event": "type.event"}
FAKE_NETWORK_PORT_EVENT = {
'event': "network.bind_port",
'port_id': '11111111-aaaa-bbbb-cccc-555555555555',
'mac_address': 'de:ad:ca:fe:ba:be',
'status': 'ACTIVE',
'device_id': '22222222-aaaa-bbbb-cccc-555555555555',
'binding:host_id': '22222222-aaaa-bbbb-cccc-555555555555',
'binding:vnic_type': 'baremetal',
}
FAKE_EVENTS = {'events': [FAKE_EVENT]}
<|code_end|>
, predict the next line using imports from the current file:
import testtools
from ironicclient.tests.unit import utils
from ironicclient.v1 import events
and context including class names, function names, and sometimes code from other files:
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/events.py
# class Event(base.Resource):
# class EventManager(base.CreateManager):
# def __repr__(self):
. Output only the next line. | FAKE_NETWORK_PORT_EVENTS = {'events': [FAKE_NETWORK_PORT_EVENT]} |
Next line prediction: <|code_start|> resources_files = ['file.json']
self.assertRaises(exc.ClientException,
create_resources.create_resources,
self.client, resources_files)
mock_load.assert_has_calls([
mock.call('file.json')
])
mock_validate.assert_called_once_with(schema_pov_invalid_json,
mock.ANY)
self.assertFalse(mock_chassis.called)
self.assertFalse(mock_nodes.called)
@mock.patch.object(create_resources, 'create_nodes', autospec=True)
@mock.patch.object(create_resources, 'create_chassis', autospec=True)
@mock.patch.object(jsonschema, 'validate',
side_effect=[None, jsonschema.ValidationError('')],
autospec=True)
@mock.patch.object(create_resources, 'load_from_file',
side_effect=[valid_json, schema_pov_invalid_json],
autospec=True)
def test_create_resources_validation_fails_multiple(
self, mock_load, mock_validate, mock_chassis, mock_nodes):
resources_files = ['file.json', 'file2.json']
self.assertRaises(exc.ClientException,
create_resources.create_resources,
self.client, resources_files)
mock_load.assert_has_calls([
mock.call('file.json'), mock.call('file2.json')
])
mock_validate.assert_has_calls([
<|code_end|>
. Use current file imports:
(import builtins
import jsonschema
from unittest import mock
from ironicclient import exc
from ironicclient.tests.unit import utils
from ironicclient.v1 import create_resources)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/create_resources.py
# def create_resources(client, filenames):
# """Create resources using their JSON or YAML descriptions.
#
# :param client: an instance of ironic client;
# :param filenames: a list of filenames containing JSON or YAML resources
# definitions.
# :raises: ClientException if any operation during files processing/resource
# creation fails.
# """
# errors = []
# resources = []
# for resource_file in filenames:
# try:
# resource = load_from_file(resource_file)
# jsonschema.validate(resource, _CREATE_SCHEMA)
# resources.append(resource)
# except (exc.ClientException, jsonschema.ValidationError) as e:
# errors.append(e)
# if errors:
# raise exc.ClientException('While validating the resources file(s), the'
# ' following error(s) were encountered:\n%s' %
# '\n'.join(str(e) for e in errors))
# for r in resources:
# errors.extend(create_chassis(client, r.get('chassis', [])))
# errors.extend(create_nodes(client, r.get('nodes', [])))
# if errors:
# raise exc.ClientException('During resources creation, the following '
# 'error(s) were encountered:\n%s' %
# '\n'.join(str(e) for e in errors))
. Output only the next line. | mock.call(valid_json, mock.ANY), |
Here is a snippet: <|code_start|> },
"properties": {
"a": "c"
},
"ports": [{
"address": "00:00:00:00:00:01",
"extra": {
"a": "b"
}
}],
"portgroups": [{
"address": "00:00:00:00:00:02",
"name": "portgroup1",
"ports": [{
"address": "00:00:00:00:00:03"
}]
}]
}]
}],
"nodes": [{
"driver": "fake",
"driver_info": {
"fake_key": "fake",
"dict_prop": {
"a": "b"
},
"arr_prop": [
1, 2, 3
]
},
<|code_end|>
. Write the next line using the current file imports:
import builtins
import jsonschema
from unittest import mock
from ironicclient import exc
from ironicclient.tests.unit import utils
from ironicclient.v1 import create_resources
and context from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/create_resources.py
# def create_resources(client, filenames):
# """Create resources using their JSON or YAML descriptions.
#
# :param client: an instance of ironic client;
# :param filenames: a list of filenames containing JSON or YAML resources
# definitions.
# :raises: ClientException if any operation during files processing/resource
# creation fails.
# """
# errors = []
# resources = []
# for resource_file in filenames:
# try:
# resource = load_from_file(resource_file)
# jsonschema.validate(resource, _CREATE_SCHEMA)
# resources.append(resource)
# except (exc.ClientException, jsonschema.ValidationError) as e:
# errors.append(e)
# if errors:
# raise exc.ClientException('While validating the resources file(s), the'
# ' following error(s) were encountered:\n%s' %
# '\n'.join(str(e) for e in errors))
# for r in resources:
# errors.extend(create_chassis(client, r.get('chassis', [])))
# errors.extend(create_nodes(client, r.get('nodes', [])))
# if errors:
# raise exc.ClientException('During resources creation, the following '
# 'error(s) were encountered:\n%s' %
# '\n'.join(str(e) for e in errors))
, which may include functions, classes, or code. Output only the next line. | "chassis_uuid": "10f99593-b8c2-4fcb-8858-494c1a47cee6" |
Given the code snippet: <|code_start|># not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
valid_json = {
"chassis": [{
"description": "testing resources import",
"nodes": [{
"driver": "agent_ssh",
"extra": {
"kv1": True,
"vk1": None
},
"properties": {
"a": "c"
},
"ports": [{
"address": "00:00:00:00:00:01",
"extra": {
"a": "b"
<|code_end|>
, generate the next line using the imports in this file:
import builtins
import jsonschema
from unittest import mock
from ironicclient import exc
from ironicclient.tests.unit import utils
from ironicclient.v1 import create_resources
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
#
# Path: ironicclient/v1/create_resources.py
# def create_resources(client, filenames):
# """Create resources using their JSON or YAML descriptions.
#
# :param client: an instance of ironic client;
# :param filenames: a list of filenames containing JSON or YAML resources
# definitions.
# :raises: ClientException if any operation during files processing/resource
# creation fails.
# """
# errors = []
# resources = []
# for resource_file in filenames:
# try:
# resource = load_from_file(resource_file)
# jsonschema.validate(resource, _CREATE_SCHEMA)
# resources.append(resource)
# except (exc.ClientException, jsonschema.ValidationError) as e:
# errors.append(e)
# if errors:
# raise exc.ClientException('While validating the resources file(s), the'
# ' following error(s) were encountered:\n%s' %
# '\n'.join(str(e) for e in errors))
# for r in resources:
# errors.extend(create_chassis(client, r.get('chassis', [])))
# errors.extend(create_nodes(client, r.get('nodes', [])))
# if errors:
# raise exc.ClientException('During resources creation, the following '
# 'error(s) were encountered:\n%s' %
# '\n'.join(str(e) for e in errors))
. Output only the next line. | } |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Port(base.Resource):
def __repr__(self):
return "<Port %s>" % self._info
class PortManager(base.CreateManager):
resource_class = Port
_creation_attributes = ['address', 'extra', 'local_link_connection',
'node_uuid', 'physical_network', 'portgroup_uuid',
'pxe_enabled', 'uuid', 'is_smartnic']
<|code_end|>
, predict the next line using imports from the current file:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context including class names, function names, and sometimes code from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | _resource_name = 'ports' |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Port(base.Resource):
def __repr__(self):
return "<Port %s>" % self._info
class PortManager(base.CreateManager):
resource_class = Port
<|code_end|>
. Write the next line using the current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may include functions, classes, or code. Output only the next line. | _creation_attributes = ['address', 'extra', 'local_link_connection', |
Here is a snippet: <|code_start|>#
# Copyright © 2013 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Port(base.Resource):
def __repr__(self):
return "<Port %s>" % self._info
class PortManager(base.CreateManager):
resource_class = Port
_creation_attributes = ['address', 'extra', 'local_link_connection',
'node_uuid', 'physical_network', 'portgroup_uuid',
'pxe_enabled', 'uuid', 'is_smartnic']
_resource_name = 'ports'
def list(self, address=None, limit=None, marker=None, sort_key=None,
<|code_end|>
. Write the next line using the current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
, which may include functions, classes, or code. Output only the next line. | sort_dir=None, detail=False, fields=None, node=None, |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright © 2013 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Port(base.Resource):
def __repr__(self):
return "<Port %s>" % self._info
class PortManager(base.CreateManager):
resource_class = Port
_creation_attributes = ['address', 'extra', 'local_link_connection',
'node_uuid', 'physical_network', 'portgroup_uuid',
<|code_end|>
. Use current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (classes, functions, or code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | 'pxe_enabled', 'uuid', 'is_smartnic'] |
Based on the snippet: <|code_start|> {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertIsNone(volume_connector)
def test_update(self):
patch = {'op': 'replace',
'connector_id': NEW_CONNECTOR_ID,
'path': '/connector_id'}
volume_connector = self.mgr.update(
volume_connector_id=CONNECTOR1['uuid'], patch=patch)
expect = [
('PATCH', '/v1/volume/connectors/%s' % CONNECTOR1['uuid'],
{}, patch),
]
self.assertEqual(expect, self.api.calls)
self._validate_obj(UPDATED_CONNECTOR, volume_connector)
class VolumeConnectorManagerPaginationTest(VolumeConnectorManagerTestBase):
def setUp(self):
super(VolumeConnectorManagerPaginationTest, self).setUp()
self.api = utils.FakeAPI(fake_responses_pagination)
self.mgr = ironicclient.v1.volume_connector.VolumeConnectorManager(
self.api)
def test_volume_connectors_list_limit(self):
volume_connectors = self.mgr.list(limit=1)
expect = [
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
import testtools
import ironicclient.v1.port
from ironicclient import exc
from ironicclient.tests.unit import utils
and context (classes, functions, sometimes code) from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | ('GET', '/v1/volume/connectors/?limit=1', {}, None), |
Next line prediction: <|code_start|># Copyright 2015 Hitachi Data Systems
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
NODE_UUID = '55555555-4444-3333-2222-111111111111'
CONNECTOR1 = {'uuid': '11111111-2222-3333-4444-555555555555',
'node_uuid': NODE_UUID,
'type': 'iqn',
'connector_id': 'iqn.2010-10.org.openstack:test',
'extra': {}}
CONNECTOR2 = {'uuid': '66666666-7777-8888-9999-000000000000',
'node_uuid': NODE_UUID,
<|code_end|>
. Use current file imports:
(import copy
import testtools
import ironicclient.v1.port
from ironicclient import exc
from ironicclient.tests.unit import utils)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | 'type': 'wwpn', |
Continue the code snippet: <|code_start|> self.assertEqual(1, len(allocations))
expected_resp = ({}, {"allocations": [ALLOCATION, ALLOCATION2]},)
self.assertEqual(expected_resp,
self.api.responses['/v1/allocations']['GET'])
def test_allocations_list_by_owner(self):
allocations = self.mgr.list(owner=ALLOCATION2['owner'])
expect = [
('GET', '/v1/allocations/?owner=%s' % ALLOCATION2['owner'], {},
None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(1, len(allocations))
expected_resp = ({}, {"allocations": [ALLOCATION, ALLOCATION2]},)
self.assertEqual(expected_resp,
self.api.responses['/v1/allocations']['GET'])
def test_allocations_show(self):
allocation = self.mgr.get(ALLOCATION['uuid'])
expect = [
('GET', '/v1/allocations/%s' % ALLOCATION['uuid'], {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(ALLOCATION['uuid'], allocation.uuid)
self.assertEqual(ALLOCATION['name'], allocation.name)
self.assertEqual(ALLOCATION['owner'], allocation.owner)
self.assertEqual(ALLOCATION['node_uuid'], allocation.node_uuid)
self.assertEqual(ALLOCATION['state'], allocation.state)
<|code_end|>
. Use current file imports:
import copy
import testtools
import ironicclient.v1.allocation
from unittest import mock
from ironicclient import exc
from ironicclient.tests.unit import utils
and context (classes, functions, or code) from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | self.assertEqual(ALLOCATION['resource_class'], |
Using the snippet: <|code_start|> 'GET': (
{},
{"allocations": [ALLOCATION2]}
),
},
}
fake_responses_sorting = {
'/v1/allocations/?sort_key=updated_at':
{
'GET': (
{},
{"allocations": [ALLOCATION2, ALLOCATION]}
),
},
'/v1/allocations/?sort_dir=desc':
{
'GET': (
{},
{"allocations": [ALLOCATION2, ALLOCATION]}
),
},
}
class AllocationManagerTest(testtools.TestCase):
def setUp(self):
super(AllocationManagerTest, self).setUp()
self.api = utils.FakeAPI(fake_responses)
<|code_end|>
, determine the next line of code. You have imports:
import copy
import testtools
import ironicclient.v1.allocation
from unittest import mock
from ironicclient import exc
from ironicclient.tests.unit import utils
and context (class names, function names, or code) available:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | self.mgr = ironicclient.v1.allocation.AllocationManager(self.api) |
Next line prediction: <|code_start|># Copyright 2016 Hitachi, Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class VolumeTarget(base.Resource):
def __repr__(self):
return "<VolumeTarget %s>" % self._info
class VolumeTargetManager(base.CreateManager):
<|code_end|>
. Use current file imports:
(from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | resource_class = VolumeTarget |
Given snippet: <|code_start|># Copyright 2016 Hitachi, Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class VolumeTarget(base.Resource):
def __repr__(self):
return "<VolumeTarget %s>" % self._info
class VolumeTargetManager(base.CreateManager):
resource_class = VolumeTarget
_creation_attributes = ['extra', 'node_uuid', 'volume_type',
'properties', 'boot_index', 'volume_id',
'uuid']
_resource_name = 'volume/targets'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
which might include code, classes, or functions. Output only the next line. | def list(self, node=None, limit=None, marker=None, sort_key=None, |
Continue the code snippet: <|code_start|># Copyright 2016 Hitachi, Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class VolumeTarget(base.Resource):
def __repr__(self):
return "<VolumeTarget %s>" % self._info
class VolumeTargetManager(base.CreateManager):
resource_class = VolumeTarget
_creation_attributes = ['extra', 'node_uuid', 'volume_type',
'properties', 'boot_index', 'volume_id',
'uuid']
_resource_name = 'volume/targets'
<|code_end|>
. Use current file imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (classes, functions, or code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | def list(self, node=None, limit=None, marker=None, sort_key=None, |
Given the code snippet: <|code_start|># Copyright 2016 SAP Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Portgroup(base.Resource):
def __repr__(self):
return "<Portgroup %s>" % self._info
class PortgroupManager(base.CreateManager):
resource_class = Portgroup
_resource_name = 'portgroups'
_creation_attributes = ['address', 'extra', 'name', 'node_uuid',
<|code_end|>
, generate the next line using the imports in this file:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | 'standalone_ports_supported', 'mode', 'properties'] |
Next line prediction: <|code_start|># Copyright 2016 SAP Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Portgroup(base.Resource):
def __repr__(self):
return "<Portgroup %s>" % self._info
class PortgroupManager(base.CreateManager):
resource_class = Portgroup
_resource_name = 'portgroups'
_creation_attributes = ['address', 'extra', 'name', 'node_uuid',
'standalone_ports_supported', 'mode', 'properties']
<|code_end|>
. Use current file imports:
(from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc)
and context including class names, function names, or small code snippets from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | def list(self, node=None, address=None, limit=None, marker=None, |
Given the code snippet: <|code_start|># Copyright 2016 SAP Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Portgroup(base.Resource):
def __repr__(self):
return "<Portgroup %s>" % self._info
class PortgroupManager(base.CreateManager):
resource_class = Portgroup
_resource_name = 'portgroups'
_creation_attributes = ['address', 'extra', 'name', 'node_uuid',
'standalone_ports_supported', 'mode', 'properties']
def list(self, node=None, address=None, limit=None, marker=None,
sort_key=None, sort_dir=None, detail=False, fields=None,
<|code_end|>
, generate the next line using the imports in this file:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (functions, classes, or occasionally code) from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | os_ironic_api_version=None, global_request_id=None): |
Using the snippet: <|code_start|># Copyright 2016 SAP Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class Portgroup(base.Resource):
def __repr__(self):
return "<Portgroup %s>" % self._info
class PortgroupManager(base.CreateManager):
resource_class = Portgroup
_resource_name = 'portgroups'
_creation_attributes = ['address', 'extra', 'name', 'node_uuid',
<|code_end|>
, determine the next line of code. You have imports:
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
and context (class names, function names, or code) available:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
. Output only the next line. | 'standalone_ports_supported', 'mode', 'properties'] |
Given the following code snippet before the placeholder: <|code_start|> def test_portgroups_list_detail(self):
portgroups = self.mgr.list(detail=True)
expect = [
('GET', '/v1/portgroups/detail', {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(2, len(portgroups))
expected_resp = ({}, {"portgroups": [PORTGROUP, PORTGROUP2]},)
self.assertEqual(expected_resp,
self.api.responses['/v1/portgroups']['GET'])
def test_portgroups_show(self):
portgroup = self.mgr.get(PORTGROUP['uuid'])
expect = [
('GET', '/v1/portgroups/%s' % PORTGROUP['uuid'], {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(PORTGROUP['uuid'], portgroup.uuid)
self.assertEqual(PORTGROUP['name'], portgroup.name)
self.assertEqual(PORTGROUP['node_uuid'], portgroup.node_uuid)
self.assertEqual(PORTGROUP['address'], portgroup.address)
expected_resp = ({}, PORTGROUP,)
self.assertEqual(
expected_resp,
self.api.responses['/v1/portgroups/%s'
% PORTGROUP['uuid']]['GET'])
def test_portgroups_show_by_address(self):
<|code_end|>
, predict the next line using imports from the current file:
import copy
import testtools
import ironicclient.v1.portgroup
from ironicclient.tests.unit import utils
and context including class names, function names, and sometimes code from other files:
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | portgroup = self.mgr.get_by_address(PORTGROUP['address']) |
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
DEFAULT_TIMEOUT = 600
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = '1234'
def _get_error_body(faultstring=None, debuginfo=None, description=None):
if description:
error_body = {'description': description}
else:
error_body = {
'faultstring': faultstring,
'debuginfo': debuginfo
}
<|code_end|>
using the current file's imports:
from http import client as http_client
from unittest import mock
from keystoneauth1 import exceptions as kexc
from ironicclient.common import filecache
from ironicclient.common import http
from ironicclient import exc
from ironicclient.tests.unit import utils
import json
import time
and any relevant context from other files:
# Path: ironicclient/common/filecache.py
# LOG = logging.getLogger(__name__)
# AUTHOR = 'openstack'
# PROGNAME = 'python-ironicclient'
# CACHE = None
# CACHE_DIR = appdirs.user_cache_dir(PROGNAME, AUTHOR)
# CACHE_EXPIRY_ENV_VAR = 'IRONICCLIENT_CACHE_EXPIRY' # environment variable
# CACHE_FILENAME = os.path.join(CACHE_DIR, 'ironic-api-version.dbm')
# DEFAULT_EXPIRY = 300 # seconds
# CACHE = dogpile.cache.make_region(key_mangler=str).configure(
# 'dogpile.cache.dbm',
# expiration_time=expiry_time,
# arguments={
# "filename": CACHE_FILENAME,
# }
# )
# def _get_cache():
# def _build_key(host, port):
# def save_data(host, port, data):
# def retrieve_data(host, port, expiry=None):
#
# Path: ironicclient/common/http.py
# DEFAULT_VER = '1.9'
# LAST_KNOWN_API_VERSION = 78
# LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
# LOG = logging.getLogger(__name__)
# USER_AGENT = 'python-ironicclient'
# CHUNKSIZE = 1024 * 64 # 64kB
# _MAJOR_VERSION = 1
# API_VERSION = '/v%d' % _MAJOR_VERSION
# API_VERSION_SELECTED_STATES = ('user', 'negotiated', 'cached', 'default')
# DEFAULT_MAX_RETRIES = 5
# DEFAULT_RETRY_INTERVAL = 2
# SENSITIVE_HEADERS = ('X-Auth-Token',)
# SUPPORTED_ENDPOINT_SCHEME = ('http', 'https')
# _API_VERSION_RE = re.compile(r'/+(v%d)?/*$' % _MAJOR_VERSION)
# _RETRY_EXCEPTIONS = (exc.Conflict, exc.ServiceUnavailable,
# exc.ConnectionRefused, kexc.RetriableConnectionFailure)
# def _trim_endpoint_api_version(url):
# def _extract_error_json(body):
# def get_server(url):
# def negotiate_version(self, conn, resp):
# def _query_server(conn):
# def _generic_parse_version_headers(self, accessor_func):
# def _parse_version_headers(self, accessor_func):
# def _make_simple_request(self, conn, method, url):
# def _must_negotiate_version(self):
# def with_retries(func):
# def wrapper(self, url, method, **kwargs):
# def __init__(self,
# os_ironic_api_version,
# api_version_select_state,
# max_retries,
# retry_interval,
# **kwargs):
# def _parse_version_headers(self, resp):
# def _get_endpoint_filter(self):
# def _make_simple_request(self, conn, method, url):
# def _http_request(self, url, method, **kwargs):
# def json_request(self, method, url, **kwargs):
# def raw_request(self, method, url, **kwargs):
# def _construct_http_client(session,
# token=None,
# auth_ref=None,
# os_ironic_api_version=DEFAULT_VER,
# api_version_select_state='default',
# max_retries=DEFAULT_MAX_RETRIES,
# retry_interval=DEFAULT_RETRY_INTERVAL,
# timeout=600,
# ca_file=None,
# cert_file=None,
# key_file=None,
# insecure=None,
# **kwargs):
# class VersionNegotiationMixin(object):
# class SessionClient(VersionNegotiationMixin, adapter.LegacyJsonAdapter):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | raw_error_body = json.dumps(error_body) |
Using the snippet: <|code_start|>
def test_chassis_node_list_sort_key(self):
self.api = utils.FakeAPI(fake_responses_sorting)
self.mgr = ironicclient.v1.chassis.ChassisManager(self.api)
nodes = self.mgr.list_nodes(CHASSIS['uuid'], sort_key='updated_at')
expect = [
('GET',
'/v1/chassis/%s/nodes?sort_key=updated_at' % CHASSIS['uuid'], {},
None),
]
self.assertEqual(expect, self.api.calls)
self.assertThat(nodes, HasLength(1))
self.assertEqual(NODE['uuid'], nodes[0].uuid)
def test_chassis_node_list_sort_dir(self):
self.api = utils.FakeAPI(fake_responses_sorting)
self.mgr = ironicclient.v1.chassis.ChassisManager(self.api)
nodes = self.mgr.list_nodes(CHASSIS['uuid'], sort_dir='desc')
expect = [
('GET',
'/v1/chassis/%s/nodes?sort_dir=desc' % CHASSIS['uuid'], {},
None),
]
self.assertEqual(expect, self.api.calls)
self.assertThat(nodes, HasLength(1))
self.assertEqual(NODE['uuid'], nodes[0].uuid)
def test_chassis_node_list_marker(self):
self.api = utils.FakeAPI(fake_responses_pagination)
self.mgr = ironicclient.v1.chassis.ChassisManager(self.api)
<|code_end|>
, determine the next line of code. You have imports:
import copy
import testtools
import ironicclient.v1.chassis
from testtools.matchers import HasLength
from ironicclient import exc
from ironicclient.tests.unit import utils
and context (class names, function names, or code) available:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
. Output only the next line. | nodes = self.mgr.list_nodes(CHASSIS['uuid'], marker=NODE['uuid']) |
Here is a snippet: <|code_start|> def test_chassis_node_list_maintenance(self):
nodes = self.mgr.list_nodes(CHASSIS['uuid'], maintenance=False)
expect = [
('GET', '/v1/chassis/%s/nodes?maintenance=False' %
CHASSIS['uuid'], {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(1, len(nodes))
def test_chassis_node_list_associated(self):
nodes = self.mgr.list_nodes(CHASSIS['uuid'], associated=True)
expect = [
('GET', '/v1/chassis/%s/nodes?associated=True' %
CHASSIS['uuid'], {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(1, len(nodes))
def test_chassis_node_list_provision_state(self):
nodes = self.mgr.list_nodes(CHASSIS['uuid'],
provision_state="available")
expect = [
('GET', '/v1/chassis/%s/nodes?provision_state=available' %
CHASSIS['uuid'], {}, None),
]
self.assertEqual(expect, self.api.calls)
self.assertEqual(1, len(nodes))
def test_chassis_node_list_detail_and_fields_fail(self):
self.assertRaises(exc.InvalidAttribute, self.mgr.list_nodes,
<|code_end|>
. Write the next line using the current file imports:
import copy
import testtools
import ironicclient.v1.chassis
from testtools.matchers import HasLength
from ironicclient import exc
from ironicclient.tests.unit import utils
and context from other files:
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/tests/unit/utils.py
# class BaseTestCase(testtools.TestCase):
# class FakeAPI(object):
# class FakeConnection(object):
# class FakeResponse(object):
# def setUp(self):
# def __init__(self, responses, path_prefix=None):
# def _request(self, method, url, headers=None, body=None, params=None):
# def raw_request(self, *args, **kwargs):
# def json_request(self, *args, **kwargs):
# def __init__(self, response=None, path_prefix=None):
# def request(self, method, conn_url, **kwargs):
# def setresponse(self, response):
# def getresponse(self):
# def __repr__(self):
# def __init__(self, headers, body=None, version=None, status=None,
# reason=None, request_headers={}):
# def getheaders(self):
# def getheader(self, key, default):
# def read(self, amt):
# def __repr__(self):
# def mockSessionResponse(headers, content=None, status_code=None, version=None,
# request_headers={}):
# def mockSession(headers, content=None, status_code=None, version=None):
, which may include functions, classes, or code. Output only the next line. | CHASSIS['uuid'], detail=True, |
Predict the next line after this snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
_power_states = {
'on': 'power on',
'off': 'power off',
'reboot': 'rebooting',
'soft off': 'soft power off',
'soft reboot': 'soft rebooting',
}
LOG = logging.getLogger(__name__)
_DEFAULT_POLL_INTERVAL = 2
class Node(base.Resource):
def __repr__(self):
return "<Node %s>" % self._info
class NodeManager(base.CreateManager):
resource_class = Node
_creation_attributes = ['chassis_uuid', 'driver', 'driver_info',
<|code_end|>
using the current file's imports:
import logging
import os
from oslo_utils import strutils
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.v1 import volume_connector
from ironicclient.v1 import volume_target
and any relevant context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/volume_connector.py
# class VolumeConnector(base.Resource):
# class VolumeConnectorManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_connector_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def delete(self, volume_connector_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_connector_id, patch, os_ironic_api_version=None,
# global_request_id=None):
#
# Path: ironicclient/v1/volume_target.py
# class VolumeTarget(base.Resource):
# class VolumeTargetManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_target_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def delete(self, volume_target_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_target_id, patch, os_ironic_api_version=None,
# global_request_id=None):
. Output only the next line. | 'extra', 'uuid', 'properties', 'name', |
Using the snippet: <|code_start|>}
LOG = logging.getLogger(__name__)
_DEFAULT_POLL_INTERVAL = 2
class Node(base.Resource):
def __repr__(self):
return "<Node %s>" % self._info
class NodeManager(base.CreateManager):
resource_class = Node
_creation_attributes = ['chassis_uuid', 'driver', 'driver_info',
'extra', 'uuid', 'properties', 'name',
'bios_interface', 'boot_interface',
'console_interface', 'deploy_interface',
'inspect_interface', 'management_interface',
'network_interface', 'power_interface',
'raid_interface', 'rescue_interface',
'storage_interface', 'vendor_interface',
'resource_class', 'conductor_group',
'automated_clean', 'network_data']
_resource_name = 'nodes'
def list(self, associated=None, maintenance=None, marker=None,
limit=None, detail=False, sort_key=None, sort_dir=None,
fields=None, provision_state=None, driver=None,
resource_class=None, chassis=None, fault=None,
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os
from oslo_utils import strutils
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.v1 import volume_connector
from ironicclient.v1 import volume_target
and context (class names, function names, or code) available:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/volume_connector.py
# class VolumeConnector(base.Resource):
# class VolumeConnectorManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_connector_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def delete(self, volume_connector_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_connector_id, patch, os_ironic_api_version=None,
# global_request_id=None):
#
# Path: ironicclient/v1/volume_target.py
# class VolumeTarget(base.Resource):
# class VolumeTargetManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_target_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def delete(self, volume_target_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_target_id, patch, os_ironic_api_version=None,
# global_request_id=None):
. Output only the next line. | os_ironic_api_version=None, conductor_group=None, |
Given snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
_power_states = {
'on': 'power on',
'off': 'power off',
'reboot': 'rebooting',
'soft off': 'soft power off',
'soft reboot': 'soft rebooting',
}
LOG = logging.getLogger(__name__)
_DEFAULT_POLL_INTERVAL = 2
class Node(base.Resource):
def __repr__(self):
return "<Node %s>" % self._info
class NodeManager(base.CreateManager):
resource_class = Node
_creation_attributes = ['chassis_uuid', 'driver', 'driver_info',
'extra', 'uuid', 'properties', 'name',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import os
from oslo_utils import strutils
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.v1 import volume_connector
from ironicclient.v1 import volume_target
and context:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/volume_connector.py
# class VolumeConnector(base.Resource):
# class VolumeConnectorManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_connector_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def delete(self, volume_connector_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_connector_id, patch, os_ironic_api_version=None,
# global_request_id=None):
#
# Path: ironicclient/v1/volume_target.py
# class VolumeTarget(base.Resource):
# class VolumeTargetManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_target_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def delete(self, volume_target_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_target_id, patch, os_ironic_api_version=None,
# global_request_id=None):
which might include code, classes, or functions. Output only the next line. | 'bios_interface', 'boot_interface', |
Predict the next line after this snippet: <|code_start|>_power_states = {
'on': 'power on',
'off': 'power off',
'reboot': 'rebooting',
'soft off': 'soft power off',
'soft reboot': 'soft rebooting',
}
LOG = logging.getLogger(__name__)
_DEFAULT_POLL_INTERVAL = 2
class Node(base.Resource):
def __repr__(self):
return "<Node %s>" % self._info
class NodeManager(base.CreateManager):
resource_class = Node
_creation_attributes = ['chassis_uuid', 'driver', 'driver_info',
'extra', 'uuid', 'properties', 'name',
'bios_interface', 'boot_interface',
'console_interface', 'deploy_interface',
'inspect_interface', 'management_interface',
'network_interface', 'power_interface',
'raid_interface', 'rescue_interface',
'storage_interface', 'vendor_interface',
'resource_class', 'conductor_group',
'automated_clean', 'network_data']
<|code_end|>
using the current file's imports:
import logging
import os
from oslo_utils import strutils
from ironicclient.common import base
from ironicclient.common.i18n import _
from ironicclient.common import utils
from ironicclient import exc
from ironicclient.v1 import volume_connector
from ironicclient.v1 import volume_target
and any relevant context from other files:
# Path: ironicclient/common/base.py
# def getid(obj):
# def __init__(self, api):
# def _path(self, resource_id=None):
# def resource_class(self):
# def _resource_name(self):
# def _get(self, resource_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def _get_as_dict(self, resource_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def _format_body_data(self, body, response_key):
# def _list_pagination(self, url, response_key=None, obj_class=None,
# limit=None, os_ironic_api_version=None,
# global_request_id=None):
# def __list(self, url, response_key=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list(self, url, response_key=None, obj_class=None, body=None,
# os_ironic_api_version=None, global_request_id=None):
# def _list_primitives(self, url, response_key=None,
# os_ironic_api_version=None, global_request_id=None):
# def _update(self, resource_id, patch, method='PATCH',
# os_ironic_api_version=None, global_request_id=None,
# params=None):
# def _delete(self, resource_id,
# os_ironic_api_version=None, global_request_id=None):
# def _creation_attributes(self):
# def create(self, os_ironic_api_version=None, global_request_id=None,
# **kwargs):
# def to_dict(self):
# class Manager(object, metaclass=abc.ABCMeta):
# class CreateManager(Manager, metaclass=abc.ABCMeta):
# class Resource(base.Resource):
#
# Path: ironicclient/common/i18n.py
# def _(msg):
# return msg
#
# Path: ironicclient/common/utils.py
# class HelpFormatter(argparse.HelpFormatter):
# def start_section(self, heading):
# def define_command(subparsers, command, callback, cmd_mapper):
# def define_commands_from_module(subparsers, command_module, cmd_mapper):
# def split_and_deserialize(string):
# def key_value_pairs_to_dict(key_value_pairs):
# def args_array_to_dict(kwargs, key_to_convert):
# def args_array_to_patch(op, attributes):
# def convert_list_props_to_comma_separated(data, props=None):
# def common_params_for_list(args, fields, field_labels):
# def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
# fields=None, detail=False):
# def tempdir(*args, **kwargs):
# def make_configdrive(path):
# def check_empty_arg(arg, arg_descriptor):
# def bool_argument_value(arg_name, bool_str, strict=True, default=False):
# def check_for_invalid_fields(fields, valid_fields):
# def get_from_stdin(info_desc):
# def handle_json_or_file_arg(json_arg):
# def poll(timeout, poll_interval, poll_delay_function, timeout_message):
# def handle_json_arg(json_arg, info_desc):
#
# Path: ironicclient/exc.py
# class AmbiguousAuthSystem(exceptions.ClientException):
# class InvalidAttribute(exceptions.ClientException):
# class StateTransitionFailed(exceptions.ClientException):
# class StateTransitionTimeout(exceptions.ClientException):
# def from_response(response, message=None, traceback=None, method=None,
# url=None):
#
# Path: ironicclient/v1/volume_connector.py
# class VolumeConnector(base.Resource):
# class VolumeConnectorManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_connector_id, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def delete(self, volume_connector_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_connector_id, patch, os_ironic_api_version=None,
# global_request_id=None):
#
# Path: ironicclient/v1/volume_target.py
# class VolumeTarget(base.Resource):
# class VolumeTargetManager(base.CreateManager):
# def __repr__(self):
# def list(self, node=None, limit=None, marker=None, sort_key=None,
# sort_dir=None, detail=False, fields=None,
# os_ironic_api_version=None, global_request_id=None):
# def get(self, volume_target_id, fields=None, os_ironic_api_version=None,
# global_request_id=None):
# def delete(self, volume_target_id, os_ironic_api_version=None,
# global_request_id=None):
# def update(self, volume_target_id, patch, os_ironic_api_version=None,
# global_request_id=None):
. Output only the next line. | _resource_name = 'nodes' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.