Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|>"""
Implementation of the squared-exponential kernels.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
# local imports
# exported symbols
__all__ = ['Matern']
@printable
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context (class names, function names, or code) available:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
. Output only the next line. | class Matern(RealKernel): |
Using the snippet: <|code_start|>
if self._d not in {1, 3, 5}:
raise ValueError('d must be one of 1, 3, or 5')
def _f(self, r):
return (
1 if (self._d == 1) else
1+r if (self._d == 3) else
1+r*(1+r/3.))
def _df(self, r):
return (
1 if (self._d == 1) else
r if (self._d == 3) else
r*(1+r)/3.)
def _params(self):
return [
('sf', 1, True),
('ell', self.nhyper-1, True),
]
def get_hyper(self):
return np.r_[self._logsf, self._logell]
def set_hyper(self, hyper):
self._logsf = hyper[0]
self._logell = hyper[1] if self._iso else hyper[1:]
def get(self, X1, X2=None):
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context (class names, function names, or code) available:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
. Output only the next line. | X1, X2 = rescale(np.exp(self._logell)/np.sqrt(self._d), X1, X2) |
Given the code snippet: <|code_start|> K = S * self._f(D)
return K
def grad(self, X1, X2=None):
X1, X2 = rescale(np.exp(self._logell)/np.sqrt(self._d), X1, X2)
D = np.sqrt(sqdist(X1, X2))
S = np.exp(self._logsf*2 - D)
K = S * self._f(D)
M = S * self._df(D)
yield 2*K # derivative wrt logsf
if self._iso:
yield M*D # derivative wrt logell (iso)
else:
for D_ in sqdist_foreach(X1, X2):
# derivative(s) wrt logell (ard)
with np.errstate(invalid='ignore'):
yield np.where(D < 1e-12, 0, M*D_/D)
def dget(self, X1):
return np.exp(self._logsf*2) * np.ones(len(X1))
def dgrad(self, X1):
yield 2 * self.dget(X1)
for _ in xrange(self.nhyper-1):
yield np.zeros(len(X1))
def gradx(self, X1, X2=None):
ell = np.exp(self._logell) / np.sqrt(self._d)
X1, X2 = rescale(ell, X1, X2)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context (functions, classes, or occasionally code) from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
. Output only the next line. | D1 = diff(X1, X2) |
Given the code snippet: <|code_start|> if self._d not in {1, 3, 5}:
raise ValueError('d must be one of 1, 3, or 5')
def _f(self, r):
return (
1 if (self._d == 1) else
1+r if (self._d == 3) else
1+r*(1+r/3.))
def _df(self, r):
return (
1 if (self._d == 1) else
r if (self._d == 3) else
r*(1+r)/3.)
def _params(self):
return [
('sf', 1, True),
('ell', self.nhyper-1, True),
]
def get_hyper(self):
return np.r_[self._logsf, self._logell]
def set_hyper(self, hyper):
self._logsf = hyper[0]
self._logell = hyper[1] if self._iso else hyper[1:]
def get(self, X1, X2=None):
X1, X2 = rescale(np.exp(self._logell)/np.sqrt(self._d), X1, X2)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context (functions, classes, or occasionally code) from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
. Output only the next line. | D = np.sqrt(sqdist(X1, X2)) |
Predict the next line for this snippet: <|code_start|> return [
('sf', 1, True),
('ell', self.nhyper-1, True),
]
def get_hyper(self):
return np.r_[self._logsf, self._logell]
def set_hyper(self, hyper):
self._logsf = hyper[0]
self._logell = hyper[1] if self._iso else hyper[1:]
def get(self, X1, X2=None):
X1, X2 = rescale(np.exp(self._logell)/np.sqrt(self._d), X1, X2)
D = np.sqrt(sqdist(X1, X2))
S = np.exp(self._logsf*2 - D)
K = S * self._f(D)
return K
def grad(self, X1, X2=None):
X1, X2 = rescale(np.exp(self._logell)/np.sqrt(self._d), X1, X2)
D = np.sqrt(sqdist(X1, X2))
S = np.exp(self._logsf*2 - D)
K = S * self._f(D)
M = S * self._df(D)
yield 2*K # derivative wrt logsf
if self._iso:
yield M*D # derivative wrt logell (iso)
else:
<|code_end|>
with the help of current file imports:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
, which may contain function names, class names, or code. Output only the next line. | for D_ in sqdist_foreach(X1, X2): |
Predict the next line after this snippet: <|code_start|>"""
Implementation of the squared-exponential kernels.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
# local imports
# exported symbols
__all__ = ['Matern']
<|code_end|>
using the current file's imports:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and any relevant context from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
. Output only the next line. | @printable |
Given the code snippet: <|code_start|> new_llh = dir_logprob(new_z)
if np.isnan(new_llh):
raise Exception("Slice sampler got a NaN")
if new_llh > llh_s:
break
elif new_z < 0:
lower = new_z
elif new_z > 0:
upper = new_z
else:
raise Exception("Slice sampler shrank to zero!")
return new_z*direction + x0
# FIXME: I've removed how blocks work because I want to rewrite that bit.
# so right now this samples everything as one big block.
direction = rng.randn(x0.shape[0])
direction = direction / np.sqrt(np.sum(direction**2))
return direction_slice(direction, x0)
#==============================================================================
# interface for sampling hyperparameters from a GP.
def sample(gp, priors, n, raw=True, rng=None):
rng = rstate(rng)
priors = dict(priors)
active = np.ones(gp.nhyper, dtype=bool)
logged = np.ones(gp.nhyper, dtype=bool)
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from mwhutils.random import rstate
from ..utils.models import get_params
and context (functions, classes, or occasionally code) from other files:
# Path: pygp/utils/models.py
# def get_params(obj):
# """
# Helper function which translates the values returned by _params() into
# something more meaningful.
# """
# offset = 0
# for param in obj._params():
# key, size, log = param
# block = slice(offset, offset+size)
# offset += size
# yield key, block, log
. Output only the next line. | for (key, block, log) in get_params(gp): |
Given snippet: <|code_start|> """
The equivalent object to sum but for products.
"""
return ft.reduce(op.mul, fiterable, 1)
def product_but(fiterable):
"""
Given an iterator over function evaluations return an array such that
`M[i]` is the product of every evaluation except for the ith one.
"""
A = list(fiterable)
# allocate memory for M and fill everything but the last element with
# the product of A[i+1:]. Note that we're using the cumprod in place.
M = np.empty_like(A)
np.cumprod(A[:0:-1], axis=0, out=M[:-1][::-1])
# use an explicit loop to iteratively set M[-1] equal to the product of
# A[:-1]. While doing this we can multiply M[i] by A[:i].
M[-1] = A[0]
for i in xrange(1, len(A)-1):
M[i] *= M[-1]
M[-1] *= A[i]
return M
### GENERAL COMBINATION KERNEL ################################################
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import itertools as it
import functools as ft
import operator as op
from ._base import Kernel
and context:
# Path: pygp/kernels/_base.py
# class Kernel(Parameterized):
# """
# The base Kernel interface.
# """
# def __call__(self, x1, x2):
# return self.get(x1[None], x2[None])[0]
#
# @abstractmethod
# def get(self, X1, X2=None):
# """
# Evaluate the kernel.
#
# Returns the matrix of covariances between points in `X1` and `X2`. If
# `X2` is not given this will return the pairwise covariances between
# points in `X1`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def dget(self, X):
# """Evaluate the self covariances."""
# raise NotImplementedError
#
# @abstractmethod
# def grad(self, X1, X2=None):
# """
# Evaluate the gradient of the kernel.
#
# Returns an iterator over the gradients of the covariances between
# points in `X1` and `X2`. If `X2` is not given this will iterate over
# the the gradients of the pairwise covariances.
# """
# raise NotImplementedError
#
# @abstractmethod
# def dgrad(self, X):
# """Evaluate the gradients of the self covariances."""
# raise NotImplementedError
#
# @abstractmethod
# def transform(self, X):
# """Format the inputs X as arrays."""
# raise NotImplementedError
which might include code, classes, or functions. Output only the next line. | class ComboKernel(Kernel): |
Next line prediction: <|code_start|>"""
Implementation of the squared-exponential kernels.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
# local imports
# exported symbols
__all__ = ['Likelihood', 'RealLikelihood']
<|code_end|>
. Use current file imports:
(import numpy as np
from abc import abstractmethod
from ..utils.models import Parameterized)
and context including class names, function names, or small code snippets from other files:
# Path: pygp/utils/models.py
# class Parameterized(object):
# """
# Interface for objects that are parameterized by some set of
# hyperparameters.
# """
# __metaclass__ = ABCMeta
#
# @abstractmethod
# def _params(self):
# """
# Define the set of parameters for the model. This should return a list
# of tuples of the form `(name, size, islog)`. If only a 2-tuple is given
# then islog will be assumed to be `True`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def get_hyper(self):
# """Return a vector of model hyperparameters."""
# raise NotImplementedError
#
# @abstractmethod
# def set_hyper(self, hyper):
# """Set the model hyperparameters to the given vector."""
# raise NotImplementedError
#
# def copy(self, hyper=None):
# """
# Copy the model. If `hyper` is given use this vector to immediately set
# the copied model's hyperparameters.
# """
# model = copy.deepcopy(self)
# if hyper is not None:
# model.set_hyper(hyper)
# return model
. Output only the next line. | class Likelihood(Parameterized): |
Predict the next line for this snippet: <|code_start|>"""
Implementation of the squared-exponential kernels.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
# local imports
# exported symbols
__all__ = ['SE']
@printable
<|code_end|>
with the help of current file imports:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
, which may contain function names, class names, or code. Output only the next line. | class SE(RealKernel): |
Given the code snippet: <|code_start|>class SE(RealKernel):
def __init__(self, sf, ell, ndim=None):
self._logsf = np.log(float(sf))
self._logell = np.log(ell)
self._iso = False
self.ndim = np.size(self._logell)
self.nhyper = 1 + np.size(self._logell)
if ndim is not None:
if np.size(self._logell) == 1:
self._logell = float(self._logell)
self._iso = True
self.ndim = ndim
else:
raise ValueError('ndim only usable with scalar lengthscales')
def _params(self):
return [
('sf', 1, True),
('ell', self.nhyper-1, True),
]
def get_hyper(self):
return np.r_[self._logsf, self._logell]
def set_hyper(self, hyper):
self._logsf = hyper[0]
self._logell = hyper[1] if self._iso else hyper[1:]
def get(self, X1, X2=None):
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context (functions, classes, or occasionally code) from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
. Output only the next line. | X1, X2 = rescale(np.exp(self._logell), X1, X2) |
Predict the next line for this snippet: <|code_start|> self._logsf = hyper[0]
self._logell = hyper[1] if self._iso else hyper[1:]
def get(self, X1, X2=None):
X1, X2 = rescale(np.exp(self._logell), X1, X2)
return np.exp(self._logsf*2 - sqdist(X1, X2)/2)
def grad(self, X1, X2=None):
X1, X2 = rescale(np.exp(self._logell), X1, X2)
D = sqdist(X1, X2)
K = np.exp(self._logsf*2 - D/2)
yield 2*K # derivative wrt logsf
if self._iso:
yield K*D # derivative wrt logell (iso)
else:
for D in sqdist_foreach(X1, X2):
yield K*D # derivatives wrt logell (ard)
def dget(self, X1):
return np.exp(self._logsf*2) * np.ones(len(X1))
def dgrad(self, X):
yield 2 * self.dget(X)
for _ in xrange(self.nhyper-1):
yield np.zeros(len(X))
def gradx(self, X1, X2=None):
ell = np.exp(self._logell)
X1, X2 = rescale(ell, X1, X2)
<|code_end|>
with the help of current file imports:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
, which may contain function names, class names, or code. Output only the next line. | D = diff(X1, X2) |
Continue the code snippet: <|code_start|> def __init__(self, sf, ell, ndim=None):
self._logsf = np.log(float(sf))
self._logell = np.log(ell)
self._iso = False
self.ndim = np.size(self._logell)
self.nhyper = 1 + np.size(self._logell)
if ndim is not None:
if np.size(self._logell) == 1:
self._logell = float(self._logell)
self._iso = True
self.ndim = ndim
else:
raise ValueError('ndim only usable with scalar lengthscales')
def _params(self):
return [
('sf', 1, True),
('ell', self.nhyper-1, True),
]
def get_hyper(self):
return np.r_[self._logsf, self._logell]
def set_hyper(self, hyper):
self._logsf = hyper[0]
self._logell = hyper[1] if self._iso else hyper[1:]
def get(self, X1, X2=None):
X1, X2 = rescale(np.exp(self._logell), X1, X2)
<|code_end|>
. Use current file imports:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context (classes, functions, or code) from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
. Output only the next line. | return np.exp(self._logsf*2 - sqdist(X1, X2)/2) |
Predict the next line after this snippet: <|code_start|> self._iso = True
self.ndim = ndim
else:
raise ValueError('ndim only usable with scalar lengthscales')
def _params(self):
return [
('sf', 1, True),
('ell', self.nhyper-1, True),
]
def get_hyper(self):
return np.r_[self._logsf, self._logell]
def set_hyper(self, hyper):
self._logsf = hyper[0]
self._logell = hyper[1] if self._iso else hyper[1:]
def get(self, X1, X2=None):
X1, X2 = rescale(np.exp(self._logell), X1, X2)
return np.exp(self._logsf*2 - sqdist(X1, X2)/2)
def grad(self, X1, X2=None):
X1, X2 = rescale(np.exp(self._logell), X1, X2)
D = sqdist(X1, X2)
K = np.exp(self._logsf*2 - D/2)
yield 2*K # derivative wrt logsf
if self._iso:
yield K*D # derivative wrt logell (iso)
else:
<|code_end|>
using the current file's imports:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and any relevant context from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
. Output only the next line. | for D in sqdist_foreach(X1, X2): |
Given the following code snippet before the placeholder: <|code_start|>"""
Implementation of the squared-exponential kernels.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
# local imports
# exported symbols
__all__ = ['SE']
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
from mwhutils.random import rstate
from ._real import RealKernel
from ._distances import rescale, diff, sqdist, sqdist_foreach
from ..utils.models import printable
and context including class names, function names, and sometimes code from other files:
# Path: pygp/kernels/_real.py
# class RealKernel(Kernel):
# """Kernel whose inputs are real-valued vectors."""
#
# def __add__(self, other):
# return SumKernel(*combine(SumKernel, self, other))
#
# def __mul__(self, other):
# return ProductKernel(*combine(ProductKernel, self, other))
#
# def transform(self, X):
# return np.array(X, ndmin=2, dtype=float, copy=False)
#
# @abstractmethod
# def gradx(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its first argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def grady(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to its second argument. Returns
# an (m,n,d)-array.
# """
# raise NotImplementedError
#
# @abstractmethod
# def gradxy(self, X1, X2=None):
# """
# Derivatives of the kernel with respect to both its first and second
# arguments. Returns an (m,n,d,d)-array. The (a,b,i,j)th element
# corresponds to the derivative with respect to `X1[a,i]` and `X2[b,j]`.
# """
# raise NotImplementedError
#
# @abstractmethod
# def sample_spectrum(self, N, rng=None):
# """
# Sample N values from the spectral density of the kernel, returning a
# set of weights W of size (n,d) and a scalar value representing the
# normalizing constant.
# """
# raise NotImplementedError
#
# Path: pygp/kernels/_distances.py
# def rescale(ell, X1, X2):
# """
# Rescale the two sets of vectors by `ell`.
# """
# X1 = X1 / ell
# X2 = X2 / ell if (X2 is not None) else None
# return X1, X2
#
# def diff(X1, X2=None):
# """
# Return the differences between vectors in `X1` and `X2`. If `X2` is not
# given this will return the pairwise differences in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return X1[:, None, :] - X2[None, :, :]
#
# def sqdist(X1, X2=None):
# """
# Return the squared-distance between two sets of vector. If `X2` is not
# given this will return the pairwise squared-distances in `X1`.
# """
# X2 = X1 if (X2 is None) else X2
# return ssd.cdist(X1, X2, 'sqeuclidean')
#
# def sqdist_foreach(X1, X2=None):
# """
# Return an iterator over each dimension returning the squared-distance
# between two sets of vector. If `X2` is not given this will iterate over the
# pairwise squared-distances in `X1` in each dimension.
# """
# X2 = X1 if (X2 is None) else X2
# for i in xrange(X1.shape[1]):
# yield ssd.cdist(X1[:, i, None], X2[:, i, None], 'sqeuclidean')
#
# Path: pygp/utils/models.py
# def printable(cls):
# """
# Decorator which marks classes as being able to be pretty-printed as a
# function of their hyperparameters. This decorator defines a __repr__ method
# for the given class which uses the class's `get_hyper` and `_params`
# methods to print it.
# """
# def _repr(obj):
# """Represent the object as a function of its hyperparameters."""
# hyper = obj.get_hyper()
# substrings = []
# for key, block, log in get_params(obj):
# val = hyper[block]
# val = val[0] if (len(val) == 1) else val
# val = np.exp(val) if log else val
# substrings += ['%s=%s' % (key, val)]
# return obj.__class__.__name__ + '(' + ', '.join(substrings) + ')'
# cls.__repr__ = _repr
# return cls
. Output only the next line. | @printable |
Continue the code snippet: <|code_start|>
__all__ = ['app']
def app(name, settings=None):
if settings:
<|code_end|>
. Use current file imports:
import os
import inspect
from shrubbery.conf.base import app_settings
and context (classes, functions, or code) from other files:
# Path: shrubbery/conf/base.py
# class Setting(object):
# class Registry(object):
# class SettingsBase(type):
# class Settings(object):
# def __init__(self, validators=None, legacy_setting=None, help=None, resolve_callable=False, **kwargs):
# def normalize(self, value):
# def __get__(self, instance, cls=None):
# def __set__(self, instance, value):
# def __delete__(self, instance):
# def __init__(self):
# def __getitem__(self, module_name):
# def __getattr__(self, name):
# def __new__(cls, name, bases, attribs):
# def instance(cls):
# def configure(cls, config):
# def __init__(self, config=None):
# def __iter__(self):
# def __getitem__(self, name):
# def __setitem__(self, name, value):
# def __delitem__(self, name):
# def as_dict(self):
# def load(self, config):
# def validate(self):
# def app_module(self):
# def app_label(self):
# def missing_setting(self, setting):
. Output only the next line. | app_settings[name] = settings |
Using the snippet: <|code_start|> key = (cls, queryset_cls)
if key not in _queryset_manager_cache:
manager_cls = type("%sManager" % queryset_cls.__name__.replace('QuerySet', ''), (cls,), {
'__module__': queryset_cls.__module__,
'Meta': type('Meta', (object,), {
'queryset': queryset_cls
})
})
_queryset_manager_cache[key] = manager_cls
return _queryset_manager_cache[key]
class QuerySetPlus(models.query.QuerySet):
@Manager.proxy_method
def filter(self, *args, **kwargs):
if args and hasattr(args[0], 'add_to_query'):
return self.complex_filter(*args)
return super(QuerySetPlus, self).filter(*args, **kwargs)
@Manager.proxy_method
def exclude(self, *args, **kwargs):
if args and hasattr(args[0], 'add_to_query'):
try:
q = ~args[0]
except TypeError:
raise TypeError('QuerySetPlus.exclude() requires a ')
return self.complex_filter(q)
return super(QuerySetPlus, self).exclude(*args, **kwargs)
@Manager.proxy_method
<|code_end|>
, determine the next line of code. You have imports:
from django.db import models
from django.db.models.query import QuerySet
from shrubbery.db.utils import fetch
and context (class names, function names, or code) available:
# Path: shrubbery/db/utils.py
# def fetch(qs, *args):
# qs = get_query_set(qs)
# for arg in args:
# try:
# q = get_q(arg)
# except ValueError:
# if callable(arg):
# try:
# arg = arg()
# except qs.model.DoesNotExist:
# continue
# if isinstance(arg, Exception):
# raise arg
# return arg
# try:
# return qs.get(q)
# except qs.model.DoesNotExist:
# pass
# raise qs.model.DoesNotExist()
. Output only the next line. | def fetch(self, *args): |
Based on the snippet: <|code_start|>
class TagWidget(forms.TextInput):
def render(self, name, value, attrs=None, choices=()):
value_list = encode_tags(value or ())
return super(TagWidget, self).render(name, value_list, attrs=attrs)
class TagField(forms.CharField):
def __init__(self, *args, **kwargs):
kwargs.setdefault('widget', TagWidget())
kwargs.setdefault('required', False)
super(TagField, self).__init__(*args, **kwargs)
def clean(self, value):
value = super(TagField, self).clean(value)
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from shrubbery.tagging.encoding import parse_tags, encode_tags
from shrubbery.tagging.models import get_tags
and context (classes, functions, sometimes code) from other files:
# Path: shrubbery/tagging/encoding.py
# def parse_tags(tag_input):
# buf = []
# quoted = False
# i = iter(tag_input)
# def _current():
# return "".join(buf).strip()
# try:
# while True:
# c = i.next()
# if c == TAG_QUOTE_CHAR:
# if quoted:
# tag = _current()
# if tag:
# yield tag
# buf = []
# quoted = False
# else:
# quoted = True
# elif c == TAG_SEPARATOR:
# if quoted:
# buf.append(c)
# else:
# tag = _current()
# if tag:
# yield tag
# buf = []
# elif c == TAG_ESCAPE_CHAR:
# if quoted:
# c = i.next()
# if not c in (TAG_ESCAPE_CHAR, TAG_QUOTE_CHAR):
# raise ValueError("illegal escape sequence")
# buf.append(c)
# else:
# buf.append(c)
# except StopIteration:
# if quoted:
# raise ValueError("quotes mismatch")
# tag = _current()
# if tag:
# yield tag
#
# def encode_tags(tags):
# return (TAG_SEPARATOR + " ").join([quote_tag(unicode(tag)) for tag in tags])
#
# Path: shrubbery/tagging/models.py
# def get_tags(tags, create=False, str_pk=False):
# if isinstance(tags, (str, unicode)):
# tags = parse_tags(tags)
# tag_set = set()
# names = set()
# tag_lookups = set()
# for tag in tags:
# if isinstance(tag, Tag):
# tag_set.add(tag)
# if create and not tag.pk:
# tag.save()
# elif isinstance(tag, basestring):
# try:
# tag_lookups.add(models.Q(pk=int(tag)))
# except ValueError:
# if create:
# names.add(tag)
# tag_lookups.add(models.Q(name=tag))
# elif isinstance(tag, (int, long)):
# tag_lookups.add(models.Q(pk=tag))
# if tag_lookups:
# for tag in Tag.objects.filter(reduce_or(tag_lookups)):
# tag_set.add(tag)
# for name in names.difference(tag.name for tag in tag_set):
# tag_set.add(Tag.objects.create(name=name))
# return tag_set
. Output only the next line. | tag_names = list(parse_tags(value)) |
Here is a snippet: <|code_start|>
class TagWidget(forms.TextInput):
def render(self, name, value, attrs=None, choices=()):
value_list = encode_tags(value or ())
return super(TagWidget, self).render(name, value_list, attrs=attrs)
class TagField(forms.CharField):
def __init__(self, *args, **kwargs):
kwargs.setdefault('widget', TagWidget())
kwargs.setdefault('required', False)
super(TagField, self).__init__(*args, **kwargs)
def clean(self, value):
value = super(TagField, self).clean(value)
tag_names = list(parse_tags(value))
<|code_end|>
. Write the next line using the current file imports:
from django import forms
from shrubbery.tagging.encoding import parse_tags, encode_tags
from shrubbery.tagging.models import get_tags
and context from other files:
# Path: shrubbery/tagging/encoding.py
# def parse_tags(tag_input):
# buf = []
# quoted = False
# i = iter(tag_input)
# def _current():
# return "".join(buf).strip()
# try:
# while True:
# c = i.next()
# if c == TAG_QUOTE_CHAR:
# if quoted:
# tag = _current()
# if tag:
# yield tag
# buf = []
# quoted = False
# else:
# quoted = True
# elif c == TAG_SEPARATOR:
# if quoted:
# buf.append(c)
# else:
# tag = _current()
# if tag:
# yield tag
# buf = []
# elif c == TAG_ESCAPE_CHAR:
# if quoted:
# c = i.next()
# if not c in (TAG_ESCAPE_CHAR, TAG_QUOTE_CHAR):
# raise ValueError("illegal escape sequence")
# buf.append(c)
# else:
# buf.append(c)
# except StopIteration:
# if quoted:
# raise ValueError("quotes mismatch")
# tag = _current()
# if tag:
# yield tag
#
# def encode_tags(tags):
# return (TAG_SEPARATOR + " ").join([quote_tag(unicode(tag)) for tag in tags])
#
# Path: shrubbery/tagging/models.py
# def get_tags(tags, create=False, str_pk=False):
# if isinstance(tags, (str, unicode)):
# tags = parse_tags(tags)
# tag_set = set()
# names = set()
# tag_lookups = set()
# for tag in tags:
# if isinstance(tag, Tag):
# tag_set.add(tag)
# if create and not tag.pk:
# tag.save()
# elif isinstance(tag, basestring):
# try:
# tag_lookups.add(models.Q(pk=int(tag)))
# except ValueError:
# if create:
# names.add(tag)
# tag_lookups.add(models.Q(name=tag))
# elif isinstance(tag, (int, long)):
# tag_lookups.add(models.Q(pk=tag))
# if tag_lookups:
# for tag in Tag.objects.filter(reduce_or(tag_lookups)):
# tag_set.add(tag)
# for name in names.difference(tag.name for tag in tag_set):
# tag_set.add(Tag.objects.create(name=name))
# return tag_set
, which may include functions, classes, or code. Output only the next line. | return get_tags(tag_names, create=True) |
Here is a snippet: <|code_start|>
class Dt(models.Model):
d = models.DateField()
dt = models.DateTimeField()
class Meta:
app_label = "db"
<|code_end|>
. Write the next line using the current file imports:
from unittest import TestCase
from django.db import models
from shrubbery.db.utils import MappedQ
import datetime
and context from other files:
# Path: shrubbery/db/utils.py
# def no_related_name(hidden=False):
# def _remove_related_accessors(sender, **kwargs):
# def as_q(self):
# def add_to_query(self, query, aliases=None):
# def __and__(self, other):
# def __or__(self, other):
# def __invert__(self):
# def __init__(self, objects, conjunction=True):
# def __invert__(self):
# def combine(self, other, conjunction):
# def __and__(self, other):
# def __or__(self, other):
# def __rand__(self, other):
# def __ror__(self, other):
# def connector(self):
# def add_to_query(self, query, aliases):
# def get_q(obj):
# def get_model(obj, allow_import=False, proxy=True):
# def get_manager(obj):
# def get_query_set(obj):
# def fetch(qs, *args):
# def _collect_sub_models(model, abstract, proxy, virtual, direct, sub_models):
# def get_sub_models(model, abstract=False, proxy=False, virtual=False, direct=False):
# def force_empty(query):
# def remove_join(query, alias, traceless=False):
# def forge_join(query, table, alias, lhs, lhs_alias, lhs_col, col, nullable=False, join_type=None):
# def replace_text(pattern, replacement, model):
# def unordered_pairs(qs):
# def create_intermediate_model(cls, rel_name, attrs, bases=None, meta=None):
# def clean_slice(s, count_func, replace_none=False, allow_step=True):
# def get_model_ref(model):
# def get_app_path(module):
# def get_app_label(module):
# def get_by_ref(s, callback, module=None, app_label=None, field=None):
# def _fire_ref_callback(model, field, callback):
# def _do_pending_reference_lookups(sender, **kwargs):
# class ImplicitQMixin(object):
# class CompoundQ(object):
, which may include functions, classes, or code. Output only the next line. | class DateQ(MappedQ): |
Continue the code snippet: <|code_start|>
class AuthenticationMiddleware(object):
def process_request(self, request):
for context in get_authentication_contexts():
context.user = lambda: context.get_user(request)
def process_response(self, request, response):
for context in get_authentication_contexts():
context.user = None
return response
def process_exception(self, request, exception):
<|code_end|>
. Use current file imports:
from django.utils.functional import SimpleLazyObject
from django.core.signals import request_started, request_finished
from django.http import HttpResponseForbidden
from shrubbery.authentication.exceptions import Http403
from shrubbery.authentication.contexts import get_authentication_contexts
and context (classes, functions, or code) from other files:
# Path: shrubbery/authentication/exceptions.py
# class Http403(Exception): pass
#
# Path: shrubbery/authentication/contexts.py
# def get_authentication_contexts():
# global _authentication_contexts
# if _authentication_contexts is None:
# _authentication_contexts = []
# for path in settings['shrubbery.authentication'].CONTEXTS:
# module_name, name = path.rsplit('.', 1)
# module = import_module(module_name)
# context = getattr(module, name)
# _authentication_contexts.append(context)
# return _authentication_contexts
. Output only the next line. | if isinstance(exception, Http403): |
Next line prediction: <|code_start|>
class TestModel(models.Model):
class Meta:
abstract = True
app_label = "db"
class A(TestModel):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class B(TestModel):
name = models.CharField(max_length=30)
a_set = ManyToManyList(A)
def __str__(self):
return self.name
class Attrib(TestModel):
<|code_end|>
. Use current file imports:
(import unittest
from django.db import models
from shrubbery.db.fields.reverse import ReverseDictField, ReverseListField, ListField, ManyToManyList)
and context including class names, function names, or small code snippets from other files:
# Path: shrubbery/db/fields/reverse/reverse_dict.py
# class ReverseDictField(models.ForeignKey):
# def __init__(self, target, key='key', value='value', **kwargs):
# assert kwargs.get('null', False) is False, "ReverseDictField may not be null"
# super(ReverseDictField, self).__init__(target, **kwargs)
# self.value = value
# self.key = key
#
# def contribute_to_related_class(self, cls, related):
# setattr(cls, related.get_accessor_name(), ReverseDictDescriptor(related))
#
# Path: shrubbery/db/fields/reverse/reverse_list.py
# class ReverseListField(models.ForeignKey):
# def __init__(self, to, index='index', value='value', **kwargs):
# assert kwargs.get('null', False) is False, "ReverseDictField may not be null"
# super(ReverseListField, self).__init__(to, **kwargs)
# self.index = index
# self.value = value
#
# def slice(self, manager, s):
# return [getattr(item, self.value) for item in manager._slice(s)]
#
# def contribute_to_related_class(self, cls, related):
# setattr(cls, related.get_accessor_name(), ReverseListDescriptor(related))
#
# class ListField(VirtualField):
# def __init__(self, value_field, **kwargs):
# if isinstance(value_field, (str, models.base.ModelBase)):
# value_field = models.ForeignKey(value_field,
# null=kwargs.pop('null', False),
# blank=kwargs.pop('blank', False),
# related_name=kwargs.pop('related_name', None),
# )
# else:
# assert "null" not in kwargs, "ListField does not support `null`, use `null` on its value field."
# assert "blank" not in kwargs, "ListField does not support `blank`, use `blank` on its value field."
# self.value_field = value_field
# self.index_field_name = kwargs.pop('index_field_name', 'index')
# self.value_field_name = kwargs.pop('value_field_name', 'value')
# self.db_table = kwargs.pop('db_table', None)
# super(VirtualField, self).__init__(**kwargs)
#
# def contribute_to_class(self, cls, name):
# super(ListField, self).contribute_to_class(cls, name)
# self.list_model = create_list_model(cls, name, self.value_field,
# index=self.index_field_name,
# value=self.value_field_name,
# db_table=self.db_table,
# field_cls=ReverseListField,
# )
#
# class ManyToManyList(models.ManyToManyField):
# def __init__(self, to, **kwargs):
# assert "through" not in kwargs, "ManyToManyList cannot use an explicit through model."
# self.list_descriptor = kwargs.pop('list_descriptor', None)
# self.index_field_name = kwargs.pop('index_field_name', 'index')
# self.value_field_name = kwargs.pop('value_field_name', 'value')
# super(ManyToManyList, self).__init__(to, **kwargs)
#
# def contribute_to_class(self, cls, name):
# if not self.list_descriptor:
# self.list_descriptor = "%s_list" % name.replace('_set', '')
# to = self.rel.to
# self.rel.through = create_list_model(cls, self.list_descriptor, models.ForeignKey(to),
# index=self.index_field_name,
# value=self.value_field_name,
# db_table=self.db_table,
# field_cls=ReverseManyToManyListField,
# )
# self.creates_table = False
# super(ManyToManyList, self).contribute_to_class(cls, name)
. Output only the next line. | b = ReverseDictField('B', key='key', value='value', related_name='attribs') |
Given the following code snippet before the placeholder: <|code_start|>
def __str__(self):
return self.name
class B(TestModel):
name = models.CharField(max_length=30)
a_set = ManyToManyList(A)
def __str__(self):
return self.name
class Attrib(TestModel):
b = ReverseDictField('B', key='key', value='value', related_name='attribs')
key = models.CharField(max_length=30)
value = models.CharField(max_length=30)
def __str__(self):
return 'attribute of %s key=%s value=%s' % (self.b, self.key, self.value)
class AttribType(TestModel):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class TypedAttrib(TestModel):
b = ReverseDictField('B', key='type', value='value', related_name='tattribs')
type = models.ForeignKey(AttribType)
value = models.CharField(max_length=10)
class CharSequence(TestModel):
<|code_end|>
, predict the next line using imports from the current file:
import unittest
from django.db import models
from shrubbery.db.fields.reverse import ReverseDictField, ReverseListField, ListField, ManyToManyList
and context including class names, function names, and sometimes code from other files:
# Path: shrubbery/db/fields/reverse/reverse_dict.py
# class ReverseDictField(models.ForeignKey):
# def __init__(self, target, key='key', value='value', **kwargs):
# assert kwargs.get('null', False) is False, "ReverseDictField may not be null"
# super(ReverseDictField, self).__init__(target, **kwargs)
# self.value = value
# self.key = key
#
# def contribute_to_related_class(self, cls, related):
# setattr(cls, related.get_accessor_name(), ReverseDictDescriptor(related))
#
# Path: shrubbery/db/fields/reverse/reverse_list.py
# class ReverseListField(models.ForeignKey):
# def __init__(self, to, index='index', value='value', **kwargs):
# assert kwargs.get('null', False) is False, "ReverseDictField may not be null"
# super(ReverseListField, self).__init__(to, **kwargs)
# self.index = index
# self.value = value
#
# def slice(self, manager, s):
# return [getattr(item, self.value) for item in manager._slice(s)]
#
# def contribute_to_related_class(self, cls, related):
# setattr(cls, related.get_accessor_name(), ReverseListDescriptor(related))
#
# class ListField(VirtualField):
# def __init__(self, value_field, **kwargs):
# if isinstance(value_field, (str, models.base.ModelBase)):
# value_field = models.ForeignKey(value_field,
# null=kwargs.pop('null', False),
# blank=kwargs.pop('blank', False),
# related_name=kwargs.pop('related_name', None),
# )
# else:
# assert "null" not in kwargs, "ListField does not support `null`, use `null` on its value field."
# assert "blank" not in kwargs, "ListField does not support `blank`, use `blank` on its value field."
# self.value_field = value_field
# self.index_field_name = kwargs.pop('index_field_name', 'index')
# self.value_field_name = kwargs.pop('value_field_name', 'value')
# self.db_table = kwargs.pop('db_table', None)
# super(VirtualField, self).__init__(**kwargs)
#
# def contribute_to_class(self, cls, name):
# super(ListField, self).contribute_to_class(cls, name)
# self.list_model = create_list_model(cls, name, self.value_field,
# index=self.index_field_name,
# value=self.value_field_name,
# db_table=self.db_table,
# field_cls=ReverseListField,
# )
#
# class ManyToManyList(models.ManyToManyField):
# def __init__(self, to, **kwargs):
# assert "through" not in kwargs, "ManyToManyList cannot use an explicit through model."
# self.list_descriptor = kwargs.pop('list_descriptor', None)
# self.index_field_name = kwargs.pop('index_field_name', 'index')
# self.value_field_name = kwargs.pop('value_field_name', 'value')
# super(ManyToManyList, self).__init__(to, **kwargs)
#
# def contribute_to_class(self, cls, name):
# if not self.list_descriptor:
# self.list_descriptor = "%s_list" % name.replace('_set', '')
# to = self.rel.to
# self.rel.through = create_list_model(cls, self.list_descriptor, models.ForeignKey(to),
# index=self.index_field_name,
# value=self.value_field_name,
# db_table=self.db_table,
# field_cls=ReverseManyToManyListField,
# )
# self.creates_table = False
# super(ManyToManyList, self).contribute_to_class(cls, name)
. Output only the next line. | b = ReverseListField('B', index='index', value='value', related_name='seq') |
Using the snippet: <|code_start|>class Attrib(TestModel):
b = ReverseDictField('B', key='key', value='value', related_name='attribs')
key = models.CharField(max_length=30)
value = models.CharField(max_length=30)
def __str__(self):
return 'attribute of %s key=%s value=%s' % (self.b, self.key, self.value)
class AttribType(TestModel):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class TypedAttrib(TestModel):
b = ReverseDictField('B', key='type', value='value', related_name='tattribs')
type = models.ForeignKey(AttribType)
value = models.CharField(max_length=10)
class CharSequence(TestModel):
b = ReverseListField('B', index='index', value='value', related_name='seq')
index = models.PositiveIntegerField()
value = models.CharField(max_length=30)
class AbRel(TestModel):
a = models.ForeignKey('AModelWithSeq')
b = models.ForeignKey('B')
index = models.PositiveIntegerField()
class AModelWithSeq(TestModel):
b_objects = models.ManyToManyField(B, through=AbRel, related_name='a_objects')
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from django.db import models
from shrubbery.db.fields.reverse import ReverseDictField, ReverseListField, ListField, ManyToManyList
and context (class names, function names, or code) available:
# Path: shrubbery/db/fields/reverse/reverse_dict.py
# class ReverseDictField(models.ForeignKey):
# def __init__(self, target, key='key', value='value', **kwargs):
# assert kwargs.get('null', False) is False, "ReverseDictField may not be null"
# super(ReverseDictField, self).__init__(target, **kwargs)
# self.value = value
# self.key = key
#
# def contribute_to_related_class(self, cls, related):
# setattr(cls, related.get_accessor_name(), ReverseDictDescriptor(related))
#
# Path: shrubbery/db/fields/reverse/reverse_list.py
# class ReverseListField(models.ForeignKey):
# def __init__(self, to, index='index', value='value', **kwargs):
# assert kwargs.get('null', False) is False, "ReverseDictField may not be null"
# super(ReverseListField, self).__init__(to, **kwargs)
# self.index = index
# self.value = value
#
# def slice(self, manager, s):
# return [getattr(item, self.value) for item in manager._slice(s)]
#
# def contribute_to_related_class(self, cls, related):
# setattr(cls, related.get_accessor_name(), ReverseListDescriptor(related))
#
# class ListField(VirtualField):
# def __init__(self, value_field, **kwargs):
# if isinstance(value_field, (str, models.base.ModelBase)):
# value_field = models.ForeignKey(value_field,
# null=kwargs.pop('null', False),
# blank=kwargs.pop('blank', False),
# related_name=kwargs.pop('related_name', None),
# )
# else:
# assert "null" not in kwargs, "ListField does not support `null`, use `null` on its value field."
# assert "blank" not in kwargs, "ListField does not support `blank`, use `blank` on its value field."
# self.value_field = value_field
# self.index_field_name = kwargs.pop('index_field_name', 'index')
# self.value_field_name = kwargs.pop('value_field_name', 'value')
# self.db_table = kwargs.pop('db_table', None)
# super(VirtualField, self).__init__(**kwargs)
#
# def contribute_to_class(self, cls, name):
# super(ListField, self).contribute_to_class(cls, name)
# self.list_model = create_list_model(cls, name, self.value_field,
# index=self.index_field_name,
# value=self.value_field_name,
# db_table=self.db_table,
# field_cls=ReverseListField,
# )
#
# class ManyToManyList(models.ManyToManyField):
# def __init__(self, to, **kwargs):
# assert "through" not in kwargs, "ManyToManyList cannot use an explicit through model."
# self.list_descriptor = kwargs.pop('list_descriptor', None)
# self.index_field_name = kwargs.pop('index_field_name', 'index')
# self.value_field_name = kwargs.pop('value_field_name', 'value')
# super(ManyToManyList, self).__init__(to, **kwargs)
#
# def contribute_to_class(self, cls, name):
# if not self.list_descriptor:
# self.list_descriptor = "%s_list" % name.replace('_set', '')
# to = self.rel.to
# self.rel.through = create_list_model(cls, self.list_descriptor, models.ForeignKey(to),
# index=self.index_field_name,
# value=self.value_field_name,
# db_table=self.db_table,
# field_cls=ReverseManyToManyListField,
# )
# self.creates_table = False
# super(ManyToManyList, self).contribute_to_class(cls, name)
. Output only the next line. | seq = ListField(B, related_name='a_list_reverse') |
Predict the next line for this snippet: <|code_start|>
class TestModel(models.Model):
class Meta:
abstract = True
app_label = "db"
class A(TestModel):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class B(TestModel):
name = models.CharField(max_length=30)
<|code_end|>
with the help of current file imports:
import unittest
from django.db import models
from shrubbery.db.fields.reverse import ReverseDictField, ReverseListField, ListField, ManyToManyList
and context from other files:
# Path: shrubbery/db/fields/reverse/reverse_dict.py
# class ReverseDictField(models.ForeignKey):
# def __init__(self, target, key='key', value='value', **kwargs):
# assert kwargs.get('null', False) is False, "ReverseDictField may not be null"
# super(ReverseDictField, self).__init__(target, **kwargs)
# self.value = value
# self.key = key
#
# def contribute_to_related_class(self, cls, related):
# setattr(cls, related.get_accessor_name(), ReverseDictDescriptor(related))
#
# Path: shrubbery/db/fields/reverse/reverse_list.py
# class ReverseListField(models.ForeignKey):
# def __init__(self, to, index='index', value='value', **kwargs):
# assert kwargs.get('null', False) is False, "ReverseDictField may not be null"
# super(ReverseListField, self).__init__(to, **kwargs)
# self.index = index
# self.value = value
#
# def slice(self, manager, s):
# return [getattr(item, self.value) for item in manager._slice(s)]
#
# def contribute_to_related_class(self, cls, related):
# setattr(cls, related.get_accessor_name(), ReverseListDescriptor(related))
#
# class ListField(VirtualField):
# def __init__(self, value_field, **kwargs):
# if isinstance(value_field, (str, models.base.ModelBase)):
# value_field = models.ForeignKey(value_field,
# null=kwargs.pop('null', False),
# blank=kwargs.pop('blank', False),
# related_name=kwargs.pop('related_name', None),
# )
# else:
# assert "null" not in kwargs, "ListField does not support `null`, use `null` on its value field."
# assert "blank" not in kwargs, "ListField does not support `blank`, use `blank` on its value field."
# self.value_field = value_field
# self.index_field_name = kwargs.pop('index_field_name', 'index')
# self.value_field_name = kwargs.pop('value_field_name', 'value')
# self.db_table = kwargs.pop('db_table', None)
# super(VirtualField, self).__init__(**kwargs)
#
# def contribute_to_class(self, cls, name):
# super(ListField, self).contribute_to_class(cls, name)
# self.list_model = create_list_model(cls, name, self.value_field,
# index=self.index_field_name,
# value=self.value_field_name,
# db_table=self.db_table,
# field_cls=ReverseListField,
# )
#
# class ManyToManyList(models.ManyToManyField):
# def __init__(self, to, **kwargs):
# assert "through" not in kwargs, "ManyToManyList cannot use an explicit through model."
# self.list_descriptor = kwargs.pop('list_descriptor', None)
# self.index_field_name = kwargs.pop('index_field_name', 'index')
# self.value_field_name = kwargs.pop('value_field_name', 'value')
# super(ManyToManyList, self).__init__(to, **kwargs)
#
# def contribute_to_class(self, cls, name):
# if not self.list_descriptor:
# self.list_descriptor = "%s_list" % name.replace('_set', '')
# to = self.rel.to
# self.rel.through = create_list_model(cls, self.list_descriptor, models.ForeignKey(to),
# index=self.index_field_name,
# value=self.value_field_name,
# db_table=self.db_table,
# field_cls=ReverseManyToManyListField,
# )
# self.creates_table = False
# super(ManyToManyList, self).contribute_to_class(cls, name)
, which may contain function names, class names, or code. Output only the next line. | a_set = ManyToManyList(A) |
Based on the snippet: <|code_start|>
class ForeignRelatedObjectsDescriptor(django_models.fields.related.ForeignRelatedObjectsDescriptor):
def create_manager(self, instance, superclass):
field = self.related.field
superclass = field.related_manager_class or superclass
cls = super(ForeignRelatedObjectsDescriptor, self).create_manager(instance, superclass)
if field.related_manager_class_decorator:
cls = field.related_manager_class_decorator(cls)
return cls
class ForeignKey(django_models.ForeignKey):
def __init__(self, *args, **kwargs):
self.related_manager_class = kwargs.pop('related_manager_class', None)
self.related_manager_class_decorator = kwargs.pop('related_manager_class_decorator', None)
if 'related_name' in kwargs and not kwargs['related_name']:
<|code_end|>
, predict the immediate next line with the help of imports:
from django.db import models as django_models
from shrubbery.db.utils import no_related_name
from south.modelsinspector import add_introspection_rules
and context (classes, functions, sometimes code) from other files:
# Path: shrubbery/db/utils.py
# def no_related_name(hidden=False):
# no_related_name._next += 1
# name = "_no_related_name_%%(class)s_%s" % (no_related_name._next)
# if hidden:
# name += '+'
# return name
. Output only the next line. | kwargs['related_name'] = no_related_name() |
Here is a snippet: <|code_start|> pattern = re.compile(pattern)
fields = []
for field in model._meta.fields:
if isinstance(field, (models.TextField, models.CharField)):
fields.append(field.name)
for obj in get_query_set(model):
for field in fields:
val = getattr(obj, field)
if val and pattern.search(val):
val = pattern.sub(replacement, val)
setattr(obj, field, val)
obj.save()
def unordered_pairs(qs):
objects = list(qs.order_by())
for a in objects:
for b in objects:
if b.pk > a.pk:
yield a, b
def create_intermediate_model(cls, rel_name, attrs, bases=None, meta=None):
if not meta:
meta = {}
if not bases:
bases = (models.Model,)
meta.setdefault('app_label', cls._meta.app_label)
attrs['Meta'] = type('Meta', (object,), meta)
attrs.setdefault('__module__', cls.__module__)
<|code_end|>
. Write the next line using the current file imports:
import re
from django.db import models
from shrubbery.utils.text import camel_case
from django.db.models.loading import get_model
from django.db.models.loading import get_models
and context from other files:
# Path: shrubbery/utils/text.py
# def camel_case(s, initial_cap=None):
# s = _camel_case_re.sub(lambda m: m.group(1).upper(), s)
# if initial_cap is not None:
# if initial_cap:
# s = s[0].upper() + s[1:]
# else:
# s = s[0].lower() + s[1:]
# return s
, which may include functions, classes, or code. Output only the next line. | return type("%s%s" % (cls.__name__, camel_case(rel_name, True)), bases, attrs) |
Continue the code snippet: <|code_start|> return base64.urlsafe_b64encode(data).rstrip('=')
def decode(self, data):
return base64.urlsafe_b64decode("%s%s" % (data, '=' * (-len(data) % 4)))
def sign(self, data):
signature = self.encode(hmac.new(self.secret, data, hashlib.sha1).digest())
if self.hash_length:
signature = signature[:self.hash_length]
return signature
def dumps(self, data):
data = self.encode(data)
return "%s%s" % (self.sign(data), data)
def loads(self, data):
try:
data = str(data)
except UnicodeEncodeError:
raise InvalidSignature("non-ascii data")
signature, data = data[:self.hash_length], data[self.hash_length:]
if self.sign(data) != signature:
raise InvalidSignature
return self.decode(data)
class TimestampedTokenFactory(SignedTokenFactory):
def __init__(self, ttl=1800, **kwargs):
super(TimestampedTokenFactory, self).__init__(**kwargs)
if isinstance(ttl, timedelta):
<|code_end|>
. Use current file imports:
import time
import hashlib
import hmac
import base64
from datetime import timedelta
from functools import wraps
from django.conf import settings
from django.http import HttpResponseForbidden
from shrubbery.utils.dt import timedelta_seconds
and context (classes, functions, or code) from other files:
# Path: shrubbery/utils/dt.py
# def timedelta_seconds(delta):
# return delta.seconds + SECONDS_PER_DAY * delta.days
. Output only the next line. | ttl = timedelta_seconds(ttl) |
Given snippet: <|code_start|> user = self.root
return Sudo(self, user)
def is_anonymous(self, user):
return user is self.anonymous
def login(self, request, user):
self.set_user(request, user)
def logout(self, request):
self.set_user(request, self.anonymous)
def get_user_id(self, user):
raise NotImplemented()
def get_user_by_id(self, id):
raise NotImplemented()
def set_user(self, request, user=_unset):
if user is not _unset:
self.user = user
if self.user:
request.session[self.session_key] = self.get_user_id(self.user)
elif self.session_key in request.session:
del request.session[self.session_key]
def get_user(self, request):
if self.session_key in request.session:
try:
return self.get_user_by_id(request.session[self.session_key])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import threading
from functools import wraps
from django.utils.importlib import import_module
from shrubbery.authentication.exceptions import AuthenticationError, Http403
from shrubbery.conf import settings
and context:
# Path: shrubbery/authentication/exceptions.py
# class AuthenticationError(Exception): pass
#
# class Http403(Exception): pass
#
# Path: shrubbery/conf/base.py
# class Setting(object):
# class Registry(object):
# class SettingsBase(type):
# class Settings(object):
# def __init__(self, validators=None, legacy_setting=None, help=None, resolve_callable=False, **kwargs):
# def normalize(self, value):
# def __get__(self, instance, cls=None):
# def __set__(self, instance, value):
# def __delete__(self, instance):
# def __init__(self):
# def __getitem__(self, module_name):
# def __getattr__(self, name):
# def __new__(cls, name, bases, attribs):
# def instance(cls):
# def configure(cls, config):
# def __init__(self, config=None):
# def __iter__(self):
# def __getitem__(self, name):
# def __setitem__(self, name, value):
# def __delitem__(self, name):
# def as_dict(self):
# def load(self, config):
# def validate(self):
# def app_module(self):
# def app_label(self):
# def missing_setting(self, setting):
which might include code, classes, or functions. Output only the next line. | except (AuthenticationError, ValueError) as e: |
Based on the snippet: <|code_start|> elif self.session_key in request.session:
del request.session[self.session_key]
def get_user(self, request):
if self.session_key in request.session:
try:
return self.get_user_by_id(request.session[self.session_key])
except (AuthenticationError, ValueError) as e:
pass
return self.anonymous
def _set_user(self, user):
self.stack.user = user
def _get_user(self):
if callable(self.stack.user):
self.stack.user = self.stack.user()
return self.stack.user
def _del_user(self):
self.stack.user = self.anonymous
user = property(_get_user, _set_user, _del_user)
def required(self, func=None):
if not func:
return self.required
@wraps(func)
def _decorated(*args, **kwargs):
if self.is_anonymous(self.user):
<|code_end|>
, predict the immediate next line with the help of imports:
import threading
from functools import wraps
from django.utils.importlib import import_module
from shrubbery.authentication.exceptions import AuthenticationError, Http403
from shrubbery.conf import settings
and context (classes, functions, sometimes code) from other files:
# Path: shrubbery/authentication/exceptions.py
# class AuthenticationError(Exception): pass
#
# class Http403(Exception): pass
#
# Path: shrubbery/conf/base.py
# class Setting(object):
# class Registry(object):
# class SettingsBase(type):
# class Settings(object):
# def __init__(self, validators=None, legacy_setting=None, help=None, resolve_callable=False, **kwargs):
# def normalize(self, value):
# def __get__(self, instance, cls=None):
# def __set__(self, instance, value):
# def __delete__(self, instance):
# def __init__(self):
# def __getitem__(self, module_name):
# def __getattr__(self, name):
# def __new__(cls, name, bases, attribs):
# def instance(cls):
# def configure(cls, config):
# def __init__(self, config=None):
# def __iter__(self):
# def __getitem__(self, name):
# def __setitem__(self, name, value):
# def __delitem__(self, name):
# def as_dict(self):
# def load(self, config):
# def validate(self):
# def app_module(self):
# def app_label(self):
# def missing_setting(self, setting):
. Output only the next line. | raise Http403() |
Next line prediction: <|code_start|>
_authentication_contexts = None
def get_authentication_contexts():
global _authentication_contexts
if _authentication_contexts is None:
_authentication_contexts = []
<|code_end|>
. Use current file imports:
(import threading
from functools import wraps
from django.utils.importlib import import_module
from shrubbery.authentication.exceptions import AuthenticationError, Http403
from shrubbery.conf import settings)
and context including class names, function names, or small code snippets from other files:
# Path: shrubbery/authentication/exceptions.py
# class AuthenticationError(Exception): pass
#
# class Http403(Exception): pass
#
# Path: shrubbery/conf/base.py
# class Setting(object):
# class Registry(object):
# class SettingsBase(type):
# class Settings(object):
# def __init__(self, validators=None, legacy_setting=None, help=None, resolve_callable=False, **kwargs):
# def normalize(self, value):
# def __get__(self, instance, cls=None):
# def __set__(self, instance, value):
# def __delete__(self, instance):
# def __init__(self):
# def __getitem__(self, module_name):
# def __getattr__(self, name):
# def __new__(cls, name, bases, attribs):
# def instance(cls):
# def configure(cls, config):
# def __init__(self, config=None):
# def __iter__(self):
# def __getitem__(self, name):
# def __setitem__(self, name, value):
# def __delitem__(self, name):
# def as_dict(self):
# def load(self, config):
# def validate(self):
# def app_module(self):
# def app_label(self):
# def missing_setting(self, setting):
. Output only the next line. | for path in settings['shrubbery.authentication'].CONTEXTS: |
Given the code snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
class ExceptionTest(unittest.TestCase):
# TODO figure out a way to determine which names are unused aka imports
#
# Tests to add:
# - Test httpexp with bad code
# - Test httpexp with no message
# - Test using a custom error handler
#
def test_success(self):
""" Control test. Default content type (json) """
def handler():
return "basic string"
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import time
import unittest
import urlparse
import StringIO
import nudge.validator
import nudge.arg as args
import nudge.json as json
import httplib
from nudge.publisher import ServicePublisher, Endpoint, Args, WSGIRequest,\
HTTPException, responses
from nudge.renderer import Result
from nose.tools import raises
from test_publisher import create_req, MockResponse, response_buf
and context (functions, classes, or occasionally code) from other files:
# Path: nudge/publisher.py
# def lazyprop(fn):
# def _lazyprop(self):
# def Args(*args, **kwargs):
# def __init__(self, name=None, method=None, uri=None, uris=None,
# function=None, args=None, renderer=None):
# def match(self, reqline):
# def __call__(self, *args, **kwargs):
# def _write(req, content):
# def __init__(self, *args, **kwargs):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def get(self, key, default=None):
# def set(self, key, value):
# def normalize_name(n):
# def __init__(self, req_dict):
# def path(self):
# def uri(self):
# def headers(self):
# def cookies(self):
# def arguments(self):
# def write(self, content):
# def request_time(self):
# def redirect(uri, headers=None):
# def __init__(self, fallbackapp=None, endpoints=None,
# debug=False, options=None, default_error_handler=None):
# def verify_options(self):
# def add_endpoint(self, endpoint):
# def _add_args(self, req):
# def __call__(self, environ, start_response):
# def _finish_request(req, start_response, code, content_type, content, headers):
# def _gen_trace_str(f, args, kwargs, res):
# def _generate_headers(version, status_code, content_length, headers={}):
# def serve(service_description, args=None):
# class Endpoint(object):
# class WSGIHeaders(dict):
# class WSGIRequest(object):
# class ServicePublisher(object):
#
# Path: nudge/renderer.py
# class Result(object):
# def __init__(self, content, content_type, http_status=200, headers=None):
# self.content = content
# self.content_type = content_type
# self.http_status = http_status
# if not headers:
# headers = {}
# self.headers = headers
. Output only the next line. | sp = ServicePublisher() |
Given snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
class ExceptionTest(unittest.TestCase):
# TODO figure out a way to determine which names are unused aka imports
#
# Tests to add:
# - Test httpexp with bad code
# - Test httpexp with no message
# - Test using a custom error handler
#
def test_success(self):
""" Control test. Default content type (json) """
def handler():
return "basic string"
sp = ServicePublisher()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import time
import unittest
import urlparse
import StringIO
import nudge.validator
import nudge.arg as args
import nudge.json as json
import httplib
from nudge.publisher import ServicePublisher, Endpoint, Args, WSGIRequest,\
HTTPException, responses
from nudge.renderer import Result
from nose.tools import raises
from test_publisher import create_req, MockResponse, response_buf
and context:
# Path: nudge/publisher.py
# def lazyprop(fn):
# def _lazyprop(self):
# def Args(*args, **kwargs):
# def __init__(self, name=None, method=None, uri=None, uris=None,
# function=None, args=None, renderer=None):
# def match(self, reqline):
# def __call__(self, *args, **kwargs):
# def _write(req, content):
# def __init__(self, *args, **kwargs):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def get(self, key, default=None):
# def set(self, key, value):
# def normalize_name(n):
# def __init__(self, req_dict):
# def path(self):
# def uri(self):
# def headers(self):
# def cookies(self):
# def arguments(self):
# def write(self, content):
# def request_time(self):
# def redirect(uri, headers=None):
# def __init__(self, fallbackapp=None, endpoints=None,
# debug=False, options=None, default_error_handler=None):
# def verify_options(self):
# def add_endpoint(self, endpoint):
# def _add_args(self, req):
# def __call__(self, environ, start_response):
# def _finish_request(req, start_response, code, content_type, content, headers):
# def _gen_trace_str(f, args, kwargs, res):
# def _generate_headers(version, status_code, content_length, headers={}):
# def serve(service_description, args=None):
# class Endpoint(object):
# class WSGIHeaders(dict):
# class WSGIRequest(object):
# class ServicePublisher(object):
#
# Path: nudge/renderer.py
# class Result(object):
# def __init__(self, content, content_type, http_status=200, headers=None):
# self.content = content
# self.content_type = content_type
# self.http_status = http_status
# if not headers:
# headers = {}
# self.headers = headers
which might include code, classes, or functions. Output only the next line. | sp.add_endpoint(Endpoint( |
Given the code snippet: <|code_start|> resp.write(result)
self.assertEqual(req._buffer,response_buf(
500, '{"message": "%s", "code": 500}' % (responses[500])))
def test_assertion_exp(self):
""" Test throwing an assertion error which will result in 400 and
return the actual exception message. """
def handler():
raise AssertionError("Someone screwed the pooch")
sp = ServicePublisher()
sp.add_endpoint(Endpoint(
name='test',
method='GET',
uri='/location',
function=handler,
))
req = create_req('GET', '/location')
resp = MockResponse(req, 400)
result = sp(req, resp.start_response)
resp.write(result)
self.assertEqual(req._buffer,response_buf(
400, '{"message": "Someone screwed the pooch", "code": 400}'))
def test_http_exp_with_msg(self):
""" Test using HTTPException which will give back an actual
http code and a custom message """
def handler():
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import time
import unittest
import urlparse
import StringIO
import nudge.validator
import nudge.arg as args
import nudge.json as json
import httplib
from nudge.publisher import ServicePublisher, Endpoint, Args, WSGIRequest,\
HTTPException, responses
from nudge.renderer import Result
from nose.tools import raises
from test_publisher import create_req, MockResponse, response_buf
and context (functions, classes, or occasionally code) from other files:
# Path: nudge/publisher.py
# def lazyprop(fn):
# def _lazyprop(self):
# def Args(*args, **kwargs):
# def __init__(self, name=None, method=None, uri=None, uris=None,
# function=None, args=None, renderer=None):
# def match(self, reqline):
# def __call__(self, *args, **kwargs):
# def _write(req, content):
# def __init__(self, *args, **kwargs):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def get(self, key, default=None):
# def set(self, key, value):
# def normalize_name(n):
# def __init__(self, req_dict):
# def path(self):
# def uri(self):
# def headers(self):
# def cookies(self):
# def arguments(self):
# def write(self, content):
# def request_time(self):
# def redirect(uri, headers=None):
# def __init__(self, fallbackapp=None, endpoints=None,
# debug=False, options=None, default_error_handler=None):
# def verify_options(self):
# def add_endpoint(self, endpoint):
# def _add_args(self, req):
# def __call__(self, environ, start_response):
# def _finish_request(req, start_response, code, content_type, content, headers):
# def _gen_trace_str(f, args, kwargs, res):
# def _generate_headers(version, status_code, content_length, headers={}):
# def serve(service_description, args=None):
# class Endpoint(object):
# class WSGIHeaders(dict):
# class WSGIRequest(object):
# class ServicePublisher(object):
#
# Path: nudge/renderer.py
# class Result(object):
# def __init__(self, content, content_type, http_status=200, headers=None):
# self.content = content
# self.content_type = content_type
# self.http_status = http_status
# if not headers:
# headers = {}
# self.headers = headers
. Output only the next line. | raise HTTPException(503, "This message is used when provided") |
Next line prediction: <|code_start|> name='test',
method='GET',
uri='/location',
function=handler
))
req = create_req('GET', '/location')
resp = MockResponse(req, 200)
result = sp(req, resp.start_response)
resp.write(result)
self.assertEqual(req._buffer,response_buf(200, '"basic string"'))
def test_default_exp(self):
""" Test the base exception handling where we dont have a callable
function, but we have some defaults to use """
def handler():
raise Exception("Someone screwed the pooch")
sp = ServicePublisher()
sp.add_endpoint(Endpoint(
name='test',
method='GET',
uri='/location',
function=handler,
))
req = create_req('GET', '/location')
resp = MockResponse(req, 500)
result = sp(req, resp.start_response)
resp.write(result)
self.assertEqual(req._buffer,response_buf(
<|code_end|>
. Use current file imports:
(import datetime
import time
import unittest
import urlparse
import StringIO
import nudge.validator
import nudge.arg as args
import nudge.json as json
import httplib
from nudge.publisher import ServicePublisher, Endpoint, Args, WSGIRequest,\
HTTPException, responses
from nudge.renderer import Result
from nose.tools import raises
from test_publisher import create_req, MockResponse, response_buf)
and context including class names, function names, or small code snippets from other files:
# Path: nudge/publisher.py
# def lazyprop(fn):
# def _lazyprop(self):
# def Args(*args, **kwargs):
# def __init__(self, name=None, method=None, uri=None, uris=None,
# function=None, args=None, renderer=None):
# def match(self, reqline):
# def __call__(self, *args, **kwargs):
# def _write(req, content):
# def __init__(self, *args, **kwargs):
# def __getitem__(self, key):
# def __setitem__(self, key, value):
# def get(self, key, default=None):
# def set(self, key, value):
# def normalize_name(n):
# def __init__(self, req_dict):
# def path(self):
# def uri(self):
# def headers(self):
# def cookies(self):
# def arguments(self):
# def write(self, content):
# def request_time(self):
# def redirect(uri, headers=None):
# def __init__(self, fallbackapp=None, endpoints=None,
# debug=False, options=None, default_error_handler=None):
# def verify_options(self):
# def add_endpoint(self, endpoint):
# def _add_args(self, req):
# def __call__(self, environ, start_response):
# def _finish_request(req, start_response, code, content_type, content, headers):
# def _gen_trace_str(f, args, kwargs, res):
# def _generate_headers(version, status_code, content_length, headers={}):
# def serve(service_description, args=None):
# class Endpoint(object):
# class WSGIHeaders(dict):
# class WSGIRequest(object):
# class ServicePublisher(object):
#
# Path: nudge/renderer.py
# class Result(object):
# def __init__(self, content, content_type, http_status=200, headers=None):
# self.content = content
# self.content_type = content_type
# self.http_status = http_status
# if not headers:
# headers = {}
# self.headers = headers
. Output only the next line. | 500, '{"message": "%s", "code": 500}' % (responses[500]))) |
Here is a snippet: <|code_start|> # assert not exceptions or isinstance(exceptions, dict), \
# "exceptions must be a dict, but was type %s" % type(exceptions)
self.name = name
self.method = method
self.uris = [uri] if uri else uris
self.function = function
if args:
self.sequential, self.named = args
assert not self.sequential or isinstance(self.sequential, list), \
"sequential must be a list but was type %s" %\
type(self.sequential)
assert not self.named or isinstance(self.named, dict), \
"named must be a dict, but was type %s" % type(self.named)
# TODO remove this fully later
self.exceptions = None
# self.exceptions = exceptions
if renderer:
if isinstance(renderer, types.TypeType):
# support cases where the renderer was specified by the
# type and not an instance - todo: Cache renderer
self.renderer = renderer()
warnings.warn(
"Endpoint %s was passed an uninstantiated renderer" %\
(name))
else:
self.renderer = renderer
else:
# Nudge default renderer
<|code_end|>
. Write the next line using the current file imports:
import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app
and context from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
, which may include functions, classes, or code. Output only the next line. | self.renderer = Json() |
Continue the code snippet: <|code_start|> else:
raise HTTPException(404)
# convert all values in req.arguments from lists to scalars,
# then combine with path args.
arguments = dict((k, v[0]) for k, v in req.arguments.iteritems()\
if isinstance(v, list) and len(v) > 0)
inargs = dict(match.groupdict(), **arguments)
# compile positional arguments
args = []
for arg in endpoint.sequential:
args.append(arg.argspec(req, inargs))
# compile keyword arguments
kwargs = {}
for argname, arg in endpoint.named.iteritems():
r = arg.argspec(req, inargs)
if r != None:
kwargs[argname] = r
# invoke the service endpoint
result = endpoint(*args, **kwargs)
# TODO make sure this works with unicode
# This is real, super annoying, lets only use if in debug mode
if self._debug:
_log.debug(_gen_trace_str(
endpoint.function, args, kwargs, result))
<|code_end|>
. Use current file imports:
import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app
and context (classes, functions, or code) from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | if isinstance(endpoint.renderer, RequestAwareRenderer): |
Given the code snippet: <|code_start|> def __getitem__(self, key):
return super(WSGIHeaders, self).__getitem__(
WSGIHeaders.normalize_name(key)
)
def __setitem__(self, key, value):
return super(WSGIHeaders, self).__setitem__(
WSGIHeaders.normalize_name(key), value
)
def get(self, key, default=None):
return super(WSGIHeaders, self).get(
WSGIHeaders.normalize_name(key), default
)
def set(self, key, value):
return super(WSGIHeaders, self).set(
WSGIHeaders.normalize_name(key), value
)
@staticmethod
def normalize_name(n):
return n.lower().replace('-','_')
class WSGIRequest(object):
def __init__(self, req_dict):
# Should we use dictomatic here? (tiny slowdown)
# REVIEW: From the following items, it feels like we can remove the Dictomatic wrapper.
<|code_end|>
, generate the next line using the imports in this file:
import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app
and context (functions, classes, or occasionally code) from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | self.req = Dictomatic.wrap(req_dict) |
Continue the code snippet: <|code_start|>
# invoke the service endpoint
result = endpoint(*args, **kwargs)
# TODO make sure this works with unicode
# This is real, super annoying, lets only use if in debug mode
if self._debug:
_log.debug(_gen_trace_str(
endpoint.function, args, kwargs, result))
if isinstance(endpoint.renderer, RequestAwareRenderer):
r = endpoint.renderer(req, result)
else:
r = endpoint.renderer(result)
content, content_type, code, extra_headers = \
r.content, r.content_type, r.http_status, r.headers
except (Exception), e:
error_response = None
logged_trace = False
#
# Try to use this endpoint's exception handler(s)
# If the raised exception is not mapped in this endpoint, or
# this endpoint raises an exception when trying to handle,
# we will then try to the default handler, and ultimately
# fallback to the self._options.default_error_response, which
# is guaranteed to be valid at app initialization.
#
if endpoint and endpoint.exceptions:
try:
<|code_end|>
. Use current file imports:
import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app
and context (classes, functions, or code) from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | error_response = handle_exception( |
Next line prediction: <|code_start|> content_type = self.headers.get("Content-Type", '')
# TODO make sure these come out as unicode
if content_type.startswith("application/x-www-form-urlencoded"):
for name, values in cgi.parse_qs(self.body).iteritems():
_arguments.setdefault(name, []).extend(values)
# multipart form
elif content_type.startswith("multipart/form-data"):
try:
fs = cgi.FieldStorage(
fp=StringIO.StringIO(self.body),
environ=self.req,
keep_blank_values=1
)
for k in fs.keys():
part = fs[k]
if part.filename:
_files[k] = part
_arguments[k] = part.value
except:
_log.exception(
"problem parsing multipart/form-data"
)
# add any arguments from JSON body
elif content_type.startswith("application/json"):
try:
body = nudge.json.json_decode(self.body)
if isinstance(body, types.DictType):
_arguments = dict(_arguments, **body)
except (ValueError):
<|code_end|>
. Use current file imports:
(import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app)
and context including class names, function names, or small code snippets from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | raise HTTPException(400, "body is not JSON") |
Continue the code snippet: <|code_start|><HTML>
<HEAD>
<TITLE>Moved</TITLE>
</HEAD>
<BODY>
<H2>Moved</H2>
<A HREF="%s">The requested URL has moved here.</A>
</BODY>
</HTML>""" % uri,
headers
)
class ServicePublisher(object):
def __init__(self, fallbackapp=None, endpoints=None,
debug=False, options=None, default_error_handler=None):
# Note fallback app needs to be a wsgi-compatible callable
if fallbackapp:
assert callable(fallbackapp), "Fallback app must be callable"
self._fallbackapp = fallbackapp
self._debug = debug
if self._debug:
_log.setLevel(logging.DEBUG)
self._endpoints = []
if endpoints:
assert isinstance(endpoints, list), "endpoints must be a list"
for ep in endpoints:
self.add_endpoint(ep)
if not default_error_handler:
<|code_end|>
. Use current file imports:
import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app
and context (classes, functions, or code) from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | default_error_handler = JsonErrorHandler |
Continue the code snippet: <|code_start|> final_content = _finish_request(
req,
start_response,
code,
content_type,
content,
extra_headers
)
return [final_content + "\r\n"]
def _finish_request(req, start_response, code, content_type, content, headers):
try:
if isinstance(content, unicode):
content = content.encode("utf-8", 'replace')
assert isinstance(content, str), "Content was not a byte string"
assert isinstance(content_type, str), \
"Content Type was not a byte string"
final_headers = []
final_headers.append(('Content-Type', content_type))
if headers:
for k, v in headers.items():
assert isinstance(k, str), \
"Headers keys and values must be a byte string"
final_headers.append((k,v))
except (Exception), e:
_log.exception(e)
final_headers = [('Content-Type', DEFAULT_ERROR_CONTENT_TYPE)]
content = DEFAULT_ERROR_CONTENT
<|code_end|>
. Use current file imports:
import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app
and context (classes, functions, or code) from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | code = DEFAULT_ERROR_CODE |
Given the following code snippet before the placeholder: <|code_start|> error_response or self._options.default_error_response
final_content = _finish_request(
req,
start_response,
code,
content_type,
content,
extra_headers
)
return [final_content + "\r\n"]
def _finish_request(req, start_response, code, content_type, content, headers):
try:
if isinstance(content, unicode):
content = content.encode("utf-8", 'replace')
assert isinstance(content, str), "Content was not a byte string"
assert isinstance(content_type, str), \
"Content Type was not a byte string"
final_headers = []
final_headers.append(('Content-Type', content_type))
if headers:
for k, v in headers.items():
assert isinstance(k, str), \
"Headers keys and values must be a byte string"
final_headers.append((k,v))
except (Exception), e:
_log.exception(e)
<|code_end|>
, predict the next line using imports from the current file:
import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app
and context including class names, function names, and sometimes code from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | final_headers = [('Content-Type', DEFAULT_ERROR_CONTENT_TYPE)] |
Given the following code snippet before the placeholder: <|code_start|>
final_content = _finish_request(
req,
start_response,
code,
content_type,
content,
extra_headers
)
return [final_content + "\r\n"]
def _finish_request(req, start_response, code, content_type, content, headers):
try:
if isinstance(content, unicode):
content = content.encode("utf-8", 'replace')
assert isinstance(content, str), "Content was not a byte string"
assert isinstance(content_type, str), \
"Content Type was not a byte string"
final_headers = []
final_headers.append(('Content-Type', content_type))
if headers:
for k, v in headers.items():
assert isinstance(k, str), \
"Headers keys and values must be a byte string"
final_headers.append((k,v))
except (Exception), e:
_log.exception(e)
final_headers = [('Content-Type', DEFAULT_ERROR_CONTENT_TYPE)]
<|code_end|>
, predict the next line using imports from the current file:
import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app
and context including class names, function names, and sometimes code from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | content = DEFAULT_ERROR_CONTENT |
Given the following code snippet before the placeholder: <|code_start|> debug=False, options=None, default_error_handler=None):
# Note fallback app needs to be a wsgi-compatible callable
if fallbackapp:
assert callable(fallbackapp), "Fallback app must be callable"
self._fallbackapp = fallbackapp
self._debug = debug
if self._debug:
_log.setLevel(logging.DEBUG)
self._endpoints = []
if endpoints:
assert isinstance(endpoints, list), "endpoints must be a list"
for ep in endpoints:
self.add_endpoint(ep)
if not default_error_handler:
default_error_handler = JsonErrorHandler
self._options = Dictomatic({
"default_error_handler": default_error_handler,
})
if options:
assert isinstance(options, dict), "options must be of type dict"
self._options.update(options)
self.verify_options()
def verify_options(self):
msg = "Default exception handler "
assert self._options.default_error_handler, msg + "must exist"
assert isinstance(self._options.default_error_handler.code, int),\
msg + "http code must be an int"
<|code_end|>
, predict the next line using imports from the current file:
import cgi
import logging
import re
import sys
import time
import types
import urllib
import warnings
import cStringIO as StringIO
import StringIO
import nudge.json
import nudge.log
import paste.httpserver
import eventlet.wsgi
from functools import partial
from nudge.renderer import Json, RequestAwareRenderer
from nudge.json import Dictomatic
from nudge.error import handle_exception, HTTPException, JsonErrorHandler,\
DEFAULT_ERROR_CODE, DEFAULT_ERROR_CONTENT_TYPE, DEFAULT_ERROR_CONTENT, responses
from optparse import OptionParser
from google.appengine.ext.webapp.util import run_wsgi_app
and context including class names, function names, and sometimes code from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# class RequestAwareRenderer(object):
#
# def __call__(self, req, result):
# pass
#
# Path: nudge/json.py
# class Dictomatic(dict):
#
# @classmethod
# def wrap(cls, data, decode=True, start=True):
# return wrap(data, cls, decode, start)
#
# def __getattr__(self, name, default=None):
# '''
# Makes a dictionary behave like an object with magic dehumping action.
# '''
#
# # try it normally
# try:
# return self[name]
# except KeyError:
# if name.startswith('__'):
# raise AttributeError()
# # try it humped, so camel_case_is_awesome => camelCaseIsAwesome
# try:
# return self[skyline_case.sub(hump, name)]
# # it's really not here, let them know
# except KeyError:
# try:
# return self[camel_case.sub(dehump, name)]
# # it's really not here, let them know
# except KeyError:
# return default
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | assert self._options.default_error_handler.code in responses,\ |
Predict the next line after this snippet: <|code_start|>class PythonStubGenerator(DefaultGenerator):
extension = 'py'
template = get_template('python.txt')
def _prepare_data(self, project):
def arg_string(endpoint):
args = []
args.extend([arg_repr(arg) for arg in endpoint.sequential])
args.extend([arg_repr(arg, True) for arg in endpoint.named])
return ', '.join(args)
def arg_repr(arg, named=False):
if named:
return '='.join([str(arg.name), str(None)])
return arg.name
modules = {}
for section in project.sections:
for ep in section.endpoints:
# -- module_name and class_name can both be ''. They'll be put
# in the default module as simple functions
# -- module_name..function_name means a module level function
# in the given module
# -- something.otherthing = default module, something =
# class_name, otherthing = function_name
# -- something = default module, module level function called
# something
module, class_name, function = breakup_path(ep.function_name)
current = (modules.setdefault(module,{})
.setdefault(class_name, {})
.setdefault(function,
<|code_end|>
using the current file's imports:
from nudge.automagic.scribes.default import DefaultGenerator, get_template
from nudge.utils import Dict, breakup_path
and any relevant context from other files:
# Path: nudge/automagic/scribes/default.py
# class DefaultGenerator(object):
# extension = 'txt'
# template = get_template('default.txt')
#
# def __init__(self, dir='/tmp', filename='autogenerated_output'):
# self.dir = dir
# if not os.path.exists(dir):
# os.makedirs(dir)
# self.filename = filename
# self.output_file = self._filepath(self.filename)
# self.ensure_output_file()
#
# def _filepath(self, filename, subdir=None, extension=None):
# dir = self.dir
# if subdir:
# dir += '/' + subdir
# if not os.path.exists(dir):
# os.makedirs(dir)
# extension = extension or self.extension
# full_path = os.path.join(dir,'%s.%s' % (filename, extension))
# return full_path
#
# def ensure_output_file(self, overwrite=False):
# if not os.path.exists(self.output_file):
# return True
# if overwrite:
# os.remove(self.output_file)
# return True
# raise Exception("This filename already exists. Please remove it.")
#
# def generate(self, project):
# data = self._prepare_data(Dict(project))
# self._render_and_write(self.template, data, self.output_file)
#
# def _render_and_write(self, template, data, filename):
# result = template.render(data)
# file = open(filename, 'wr')
# file.write(result)
# file.close()
#
#
# def _prepare_data(self, project):
# return {'project':project}
#
# def get_template(filename=None):
# assert filename, "I need a filename, smartypants"
# text=None
# filepath = os.path.join(template_dir, filename)
# assert os.path.exists(filepath), "The template file doesn't exist"
# text = open(filepath, "r").read()
# assert text, "How about some text"
# return template_env.get_template(filename)
#
# Path: nudge/utils.py
# class Dict(dict):
# def __getattr__(self, attr):
# return self.get(attr, None)
# __setattr__= dict.__setitem__
# __delattr__= dict.__delitem__
#
# def breakup_path(input, camel_case=True):
# package = ''
# class_name, dot, function_name = input.rpartition('.')
# if not function_name:
# function_name = class_name
# class_name = None
# if class_name:
# package, dot, class_name = class_name.rpartition('.')
# if camel_case:
# class_name = build_class_name(class_name)
# if package:
# garbage, dot, package = package.rpartition('.')
# return package, class_name, function_name
. Output only the next line. | Dict({'sequential':[], |
Based on the snippet: <|code_start|># License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
class PythonStubGenerator(DefaultGenerator):
extension = 'py'
template = get_template('python.txt')
def _prepare_data(self, project):
def arg_string(endpoint):
args = []
args.extend([arg_repr(arg) for arg in endpoint.sequential])
args.extend([arg_repr(arg, True) for arg in endpoint.named])
return ', '.join(args)
def arg_repr(arg, named=False):
if named:
return '='.join([str(arg.name), str(None)])
return arg.name
modules = {}
for section in project.sections:
for ep in section.endpoints:
# -- module_name and class_name can both be ''. They'll be put
# in the default module as simple functions
# -- module_name..function_name means a module level function
# in the given module
# -- something.otherthing = default module, something =
# class_name, otherthing = function_name
# -- something = default module, module level function called
# something
<|code_end|>
, predict the immediate next line with the help of imports:
from nudge.automagic.scribes.default import DefaultGenerator, get_template
from nudge.utils import Dict, breakup_path
and context (classes, functions, sometimes code) from other files:
# Path: nudge/automagic/scribes/default.py
# class DefaultGenerator(object):
# extension = 'txt'
# template = get_template('default.txt')
#
# def __init__(self, dir='/tmp', filename='autogenerated_output'):
# self.dir = dir
# if not os.path.exists(dir):
# os.makedirs(dir)
# self.filename = filename
# self.output_file = self._filepath(self.filename)
# self.ensure_output_file()
#
# def _filepath(self, filename, subdir=None, extension=None):
# dir = self.dir
# if subdir:
# dir += '/' + subdir
# if not os.path.exists(dir):
# os.makedirs(dir)
# extension = extension or self.extension
# full_path = os.path.join(dir,'%s.%s' % (filename, extension))
# return full_path
#
# def ensure_output_file(self, overwrite=False):
# if not os.path.exists(self.output_file):
# return True
# if overwrite:
# os.remove(self.output_file)
# return True
# raise Exception("This filename already exists. Please remove it.")
#
# def generate(self, project):
# data = self._prepare_data(Dict(project))
# self._render_and_write(self.template, data, self.output_file)
#
# def _render_and_write(self, template, data, filename):
# result = template.render(data)
# file = open(filename, 'wr')
# file.write(result)
# file.close()
#
#
# def _prepare_data(self, project):
# return {'project':project}
#
# def get_template(filename=None):
# assert filename, "I need a filename, smartypants"
# text=None
# filepath = os.path.join(template_dir, filename)
# assert os.path.exists(filepath), "The template file doesn't exist"
# text = open(filepath, "r").read()
# assert text, "How about some text"
# return template_env.get_template(filename)
#
# Path: nudge/utils.py
# class Dict(dict):
# def __getattr__(self, attr):
# return self.get(attr, None)
# __setattr__= dict.__setitem__
# __delattr__= dict.__delitem__
#
# def breakup_path(input, camel_case=True):
# package = ''
# class_name, dot, function_name = input.rpartition('.')
# if not function_name:
# function_name = class_name
# class_name = None
# if class_name:
# package, dot, class_name = class_name.rpartition('.')
# if camel_case:
# class_name = build_class_name(class_name)
# if package:
# garbage, dot, package = package.rpartition('.')
# return package, class_name, function_name
. Output only the next line. | module, class_name, function = breakup_path(ep.function_name) |
Here is a snippet: <|code_start|>#
# Copyright (C) 2011 Evite LLC
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
'''
Sphinx does one index page, then a page for each method...
'''
class SphinxDocGenerator(DefaultGenerator):
extension = 'rst'
<|code_end|>
. Write the next line using the current file imports:
import os
from nudge.automagic.scribes.default import DefaultGenerator, get_template
from nudge.utils import Dict, skyline_text
and context from other files:
# Path: nudge/automagic/scribes/default.py
# class DefaultGenerator(object):
# extension = 'txt'
# template = get_template('default.txt')
#
# def __init__(self, dir='/tmp', filename='autogenerated_output'):
# self.dir = dir
# if not os.path.exists(dir):
# os.makedirs(dir)
# self.filename = filename
# self.output_file = self._filepath(self.filename)
# self.ensure_output_file()
#
# def _filepath(self, filename, subdir=None, extension=None):
# dir = self.dir
# if subdir:
# dir += '/' + subdir
# if not os.path.exists(dir):
# os.makedirs(dir)
# extension = extension or self.extension
# full_path = os.path.join(dir,'%s.%s' % (filename, extension))
# return full_path
#
# def ensure_output_file(self, overwrite=False):
# if not os.path.exists(self.output_file):
# return True
# if overwrite:
# os.remove(self.output_file)
# return True
# raise Exception("This filename already exists. Please remove it.")
#
# def generate(self, project):
# data = self._prepare_data(Dict(project))
# self._render_and_write(self.template, data, self.output_file)
#
# def _render_and_write(self, template, data, filename):
# result = template.render(data)
# file = open(filename, 'wr')
# file.write(result)
# file.close()
#
#
# def _prepare_data(self, project):
# return {'project':project}
#
# def get_template(filename=None):
# assert filename, "I need a filename, smartypants"
# text=None
# filepath = os.path.join(template_dir, filename)
# assert os.path.exists(filepath), "The template file doesn't exist"
# text = open(filepath, "r").read()
# assert text, "How about some text"
# return template_env.get_template(filename)
#
# Path: nudge/utils.py
# class Dict(dict):
# def __getattr__(self, attr):
# return self.get(attr, None)
# __setattr__= dict.__setitem__
# __delattr__= dict.__delitem__
#
# def skyline_text(string):
# def fix_spaces(match):
# result = ''
# for group in match.groups():
# result += '_' + group[len(group)-1]
# return result
# return title_case.sub(fix_spaces, string).lower().strip()
, which may include functions, classes, or code. Output only the next line. | index_template = get_template('sphinx_index.txt') |
Here is a snippet: <|code_start|># This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
'''
Sphinx does one index page, then a page for each method...
'''
class SphinxDocGenerator(DefaultGenerator):
extension = 'rst'
index_template = get_template('sphinx_index.txt')
endpoint_template = get_template('sphinx_endpoint.txt')
conf_template = get_template('sphinx_conf.txt')
def _prepare_data(self, project):
endpoints = {}
sections = {}
for section in project.sections:
section_name = skyline_text(section.name)
<|code_end|>
. Write the next line using the current file imports:
import os
from nudge.automagic.scribes.default import DefaultGenerator, get_template
from nudge.utils import Dict, skyline_text
and context from other files:
# Path: nudge/automagic/scribes/default.py
# class DefaultGenerator(object):
# extension = 'txt'
# template = get_template('default.txt')
#
# def __init__(self, dir='/tmp', filename='autogenerated_output'):
# self.dir = dir
# if not os.path.exists(dir):
# os.makedirs(dir)
# self.filename = filename
# self.output_file = self._filepath(self.filename)
# self.ensure_output_file()
#
# def _filepath(self, filename, subdir=None, extension=None):
# dir = self.dir
# if subdir:
# dir += '/' + subdir
# if not os.path.exists(dir):
# os.makedirs(dir)
# extension = extension or self.extension
# full_path = os.path.join(dir,'%s.%s' % (filename, extension))
# return full_path
#
# def ensure_output_file(self, overwrite=False):
# if not os.path.exists(self.output_file):
# return True
# if overwrite:
# os.remove(self.output_file)
# return True
# raise Exception("This filename already exists. Please remove it.")
#
# def generate(self, project):
# data = self._prepare_data(Dict(project))
# self._render_and_write(self.template, data, self.output_file)
#
# def _render_and_write(self, template, data, filename):
# result = template.render(data)
# file = open(filename, 'wr')
# file.write(result)
# file.close()
#
#
# def _prepare_data(self, project):
# return {'project':project}
#
# def get_template(filename=None):
# assert filename, "I need a filename, smartypants"
# text=None
# filepath = os.path.join(template_dir, filename)
# assert os.path.exists(filepath), "The template file doesn't exist"
# text = open(filepath, "r").read()
# assert text, "How about some text"
# return template_env.get_template(filename)
#
# Path: nudge/utils.py
# class Dict(dict):
# def __getattr__(self, attr):
# return self.get(attr, None)
# __setattr__= dict.__setitem__
# __delattr__= dict.__delitem__
#
# def skyline_text(string):
# def fix_spaces(match):
# result = ''
# for group in match.groups():
# result += '_' + group[len(group)-1]
# return result
# return title_case.sub(fix_spaces, string).lower().strip()
, which may include functions, classes, or code. Output only the next line. | section_default = Dict({'name': section.name, |
Given snippet: <|code_start|>
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
'''
Sphinx does one index page, then a page for each method...
'''
class SphinxDocGenerator(DefaultGenerator):
extension = 'rst'
index_template = get_template('sphinx_index.txt')
endpoint_template = get_template('sphinx_endpoint.txt')
conf_template = get_template('sphinx_conf.txt')
def _prepare_data(self, project):
endpoints = {}
sections = {}
for section in project.sections:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from nudge.automagic.scribes.default import DefaultGenerator, get_template
from nudge.utils import Dict, skyline_text
and context:
# Path: nudge/automagic/scribes/default.py
# class DefaultGenerator(object):
# extension = 'txt'
# template = get_template('default.txt')
#
# def __init__(self, dir='/tmp', filename='autogenerated_output'):
# self.dir = dir
# if not os.path.exists(dir):
# os.makedirs(dir)
# self.filename = filename
# self.output_file = self._filepath(self.filename)
# self.ensure_output_file()
#
# def _filepath(self, filename, subdir=None, extension=None):
# dir = self.dir
# if subdir:
# dir += '/' + subdir
# if not os.path.exists(dir):
# os.makedirs(dir)
# extension = extension or self.extension
# full_path = os.path.join(dir,'%s.%s' % (filename, extension))
# return full_path
#
# def ensure_output_file(self, overwrite=False):
# if not os.path.exists(self.output_file):
# return True
# if overwrite:
# os.remove(self.output_file)
# return True
# raise Exception("This filename already exists. Please remove it.")
#
# def generate(self, project):
# data = self._prepare_data(Dict(project))
# self._render_and_write(self.template, data, self.output_file)
#
# def _render_and_write(self, template, data, filename):
# result = template.render(data)
# file = open(filename, 'wr')
# file.write(result)
# file.close()
#
#
# def _prepare_data(self, project):
# return {'project':project}
#
# def get_template(filename=None):
# assert filename, "I need a filename, smartypants"
# text=None
# filepath = os.path.join(template_dir, filename)
# assert os.path.exists(filepath), "The template file doesn't exist"
# text = open(filepath, "r").read()
# assert text, "How about some text"
# return template_env.get_template(filename)
#
# Path: nudge/utils.py
# class Dict(dict):
# def __getattr__(self, attr):
# return self.get(attr, None)
# __setattr__= dict.__setitem__
# __delattr__= dict.__delitem__
#
# def skyline_text(string):
# def fix_spaces(match):
# result = ''
# for group in match.groups():
# result += '_' + group[len(group)-1]
# return result
# return title_case.sub(fix_spaces, string).lower().strip()
which might include code, classes, or functions. Output only the next line. | section_name = skyline_text(section.name) |
Predict the next line after this snippet: <|code_start|>
class JsonRendererTest(unittest.TestCase):
@raises(SecurityException)
def test_list_throws_500(self):
<|code_end|>
using the current file's imports:
import unittest
from nose.tools import raises
from nudge.renderer import Json
from nudge.error import SecurityException
and any relevant context from other files:
# Path: nudge/renderer.py
# class Json(object):
# ''' Default Nudge HTTP Content Type. Encodes the entire endpoint
# result as json, and returns.
#
# Note this renderer will not allow you to pass back a top level
# list or tuple (javascript array) because it is insecure, and could
# allow a CSRF attack. See here:
# http://flask.pocoo.org/docs/security/#json-security
# '''
# def __call__(self, result):
# if result == None:
# raise HTTPException(404)
# if isinstance(result, (types.ListType, types.TupleType)):
# raise SecurityException(
# 'Results that encode as json arrays are not '+\
# 'allowed for security concerns'
# )
# return Result(
# content=json_encode(result),
# content_type='application/json; charset=UTF-8',
# http_status=200,
# )
#
# Path: nudge/error.py
# class SecurityException(Exception):
# pass
. Output only the next line. | Json()([1,2,3]) |
Given snippet: <|code_start|> extension = 'txt'
template = get_template('default.txt')
def __init__(self, dir='/tmp', filename='autogenerated_output'):
self.dir = dir
if not os.path.exists(dir):
os.makedirs(dir)
self.filename = filename
self.output_file = self._filepath(self.filename)
self.ensure_output_file()
def _filepath(self, filename, subdir=None, extension=None):
dir = self.dir
if subdir:
dir += '/' + subdir
if not os.path.exists(dir):
os.makedirs(dir)
extension = extension or self.extension
full_path = os.path.join(dir,'%s.%s' % (filename, extension))
return full_path
def ensure_output_file(self, overwrite=False):
if not os.path.exists(self.output_file):
return True
if overwrite:
os.remove(self.output_file)
return True
raise Exception("This filename already exists. Please remove it.")
def generate(self, project):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from nudge.utils import Dict
from jinja2 import Environment, FileSystemLoader
and context:
# Path: nudge/utils.py
# class Dict(dict):
# def __getattr__(self, attr):
# return self.get(attr, None)
# __setattr__= dict.__setitem__
# __delattr__= dict.__delitem__
which might include code, classes, or functions. Output only the next line. | data = self._prepare_data(Dict(project)) |
Predict the next line after this snippet: <|code_start|>
class WSGIRequestTest(unittest.TestCase):
def test_xff_header(self):
input = StringIO.StringIO()
<|code_end|>
using the current file's imports:
import unittest
import StringIO
from nudge.publisher import WSGIRequest
and any relevant context from other files:
# Path: nudge/publisher.py
# class WSGIRequest(object):
#
# def __init__(self, req_dict):
# # Should we use dictomatic here? (tiny slowdown)
# # REVIEW: From the following items, it feels like we can remove the Dictomatic wrapper.
# self.req = Dictomatic.wrap(req_dict)
# self.start_time = time.time()
# self.method = self.req.get('REQUEST_METHOD')
# self.remote_ip = self.req.get('REMOTE_ADDR', self.req.get('HTTP_REMOTE_ADDR'))
# self.body = self.req.get('wsgi.input').read()
# self._buffer = ''
# self.files = {}
#
# @lazyprop
# def path(self):
# return self.req['PATH_INFO']
#
# @lazyprop
# def uri(self):
# return '%s://%s%s' % (
# self.req['wsgi.url_scheme'],
# self.req['HTTP_HOST'],
# self.req['PATH_INFO']
# )
#
# @lazyprop
# def headers(self):
# _headers = WSGIHeaders()
# for k,v in self.req.iteritems():
# if k.startswith('HTTP_'):
# _headers[k.replace('HTTP_', '').lower()] = v
# elif k == 'CONTENT_TYPE':
# _headers['Content-Type'] = v
# return _headers
#
# @lazyprop
# def cookies(self):
# ''' I am assuming it is valid to have multiple cookies with the same
# name even though that seems silly.
#
# Also the individual cookies are split on the FIRST = so as to support
# later = for unknown benefit.
#
# TODO - support/test with unicode?
# - Maybe nuke the HTTP_COOKIE from regular headers?
# '''
# _cookies = {}
# if 'HTTP_COOKIE' in self.req:
# for cookie in self.req['HTTP_COOKIE'].split(';'):
# cookie = cookie.split('=')
# if len(cookie) < 2: # Empty values will still be >= 2
# continue
# if cookie[0] in _cookies:
# _cookies[cookie[0].strip()].append(
# '='.join(cookie[1:]).strip()
# )
# else:
# _cookies[cookie[0].strip()] = ['='.join(cookie[1:]).strip()]
# return _cookies
#
# @lazyprop
# def arguments(self):
# _arguments = {}
# _files = {}
# try:
# # First url decode
# tmp = self.req.get('QUERY_STRING', '')
# if tmp:
# # make sure to split before unquoting
# # to handle arg keys/values that contain & or =
# tmp = tmp.split('&')
# tmp = [a.split('=') for a in tmp]
# tmp = [map(urllib.unquote_plus, a) for a in tmp]
# # Consider making the unicode decoding type a Nudge option.
# tmp = [map(partial(unicode, encoding='utf-8'), a) for a in tmp]
# # Only keep args with k and v. f= will stay and be [u'f', u'']
# tmp = filter(lambda x: len(x) == 2, tmp)
# for k, v in tmp:
# if k in _arguments:
# _arguments[k].append(v)
# else:
# _arguments[k] = [v]
# except (Exception), e:
# _log.exception(
# "problem making arguments out of QUERY_STRING: %s",
# self.req['QUERY_STRING']
# )
#
# if self.method in ('POST', 'PUT') and self.body:
# content_type = self.headers.get("Content-Type", '')
# # TODO make sure these come out as unicode
# if content_type.startswith("application/x-www-form-urlencoded"):
# for name, values in cgi.parse_qs(self.body).iteritems():
# _arguments.setdefault(name, []).extend(values)
# # multipart form
# elif content_type.startswith("multipart/form-data"):
# try:
# fs = cgi.FieldStorage(
# fp=StringIO.StringIO(self.body),
# environ=self.req,
# keep_blank_values=1
# )
# for k in fs.keys():
# part = fs[k]
# if part.filename:
# _files[k] = part
# _arguments[k] = part.value
# except:
# _log.exception(
# "problem parsing multipart/form-data"
# )
# # add any arguments from JSON body
# elif content_type.startswith("application/json"):
# try:
# body = nudge.json.json_decode(self.body)
# if isinstance(body, types.DictType):
# _arguments = dict(_arguments, **body)
#
# except (ValueError):
# raise HTTPException(400, "body is not JSON")
#
# self.files = _files
# return _arguments
#
# def write(self, content):
# self._buffer += content
#
# def request_time(self):
# return time.time() - self.start_time
. Output only the next line. | req = WSGIRequest({ |
Based on the snippet: <|code_start|> {"we": "dont", "care":{"about":0,"sub": "types"}},
]
val_func = vals.Dict(max_=3)
for input in inputs:
val_func(input)
@raises(vals.ValidationError)
def test_dict_max_fail(self):
inputs = [
[],
{"test":"skickass"},
{"we": "dont", "care":{"about":0,"sub": "types"}},
]
val_func = vals.Dict(max_=1)
for input in inputs:
val_func(input)
_base_environ = {
"REQUEST_METHOD": "GET",
"CONTENT_TYPE": "application/json",
"PATH_INFO": "/",
"HTTP_HOST": "localhost",
"REMOTE_ADDR": "127.0.0.1",
"wsgi.url_scheme": "http",
}
def create_req(environ):
new_env = copy.copy(_base_environ)
new_env.update(environ)
new_env['wsgi.input'] = StringIO.StringIO(new_env.get('body', ''))
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
import datetime
import unittest
import StringIO
import nudge.arg as args
import nudge.json as json
import nudge.publisher as servicepublisher
import nudge.validator as vals
from nose.tools import raises
from nudge.publisher import WSGIRequest
and context (classes, functions, sometimes code) from other files:
# Path: nudge/publisher.py
# class WSGIRequest(object):
#
# def __init__(self, req_dict):
# # Should we use dictomatic here? (tiny slowdown)
# # REVIEW: From the following items, it feels like we can remove the Dictomatic wrapper.
# self.req = Dictomatic.wrap(req_dict)
# self.start_time = time.time()
# self.method = self.req.get('REQUEST_METHOD')
# self.remote_ip = self.req.get('REMOTE_ADDR', self.req.get('HTTP_REMOTE_ADDR'))
# self.body = self.req.get('wsgi.input').read()
# self._buffer = ''
# self.files = {}
#
# @lazyprop
# def path(self):
# return self.req['PATH_INFO']
#
# @lazyprop
# def uri(self):
# return '%s://%s%s' % (
# self.req['wsgi.url_scheme'],
# self.req['HTTP_HOST'],
# self.req['PATH_INFO']
# )
#
# @lazyprop
# def headers(self):
# _headers = WSGIHeaders()
# for k,v in self.req.iteritems():
# if k.startswith('HTTP_'):
# _headers[k.replace('HTTP_', '').lower()] = v
# elif k == 'CONTENT_TYPE':
# _headers['Content-Type'] = v
# return _headers
#
# @lazyprop
# def cookies(self):
# ''' I am assuming it is valid to have multiple cookies with the same
# name even though that seems silly.
#
# Also the individual cookies are split on the FIRST = so as to support
# later = for unknown benefit.
#
# TODO - support/test with unicode?
# - Maybe nuke the HTTP_COOKIE from regular headers?
# '''
# _cookies = {}
# if 'HTTP_COOKIE' in self.req:
# for cookie in self.req['HTTP_COOKIE'].split(';'):
# cookie = cookie.split('=')
# if len(cookie) < 2: # Empty values will still be >= 2
# continue
# if cookie[0] in _cookies:
# _cookies[cookie[0].strip()].append(
# '='.join(cookie[1:]).strip()
# )
# else:
# _cookies[cookie[0].strip()] = ['='.join(cookie[1:]).strip()]
# return _cookies
#
# @lazyprop
# def arguments(self):
# _arguments = {}
# _files = {}
# try:
# # First url decode
# tmp = self.req.get('QUERY_STRING', '')
# if tmp:
# # make sure to split before unquoting
# # to handle arg keys/values that contain & or =
# tmp = tmp.split('&')
# tmp = [a.split('=') for a in tmp]
# tmp = [map(urllib.unquote_plus, a) for a in tmp]
# # Consider making the unicode decoding type a Nudge option.
# tmp = [map(partial(unicode, encoding='utf-8'), a) for a in tmp]
# # Only keep args with k and v. f= will stay and be [u'f', u'']
# tmp = filter(lambda x: len(x) == 2, tmp)
# for k, v in tmp:
# if k in _arguments:
# _arguments[k].append(v)
# else:
# _arguments[k] = [v]
# except (Exception), e:
# _log.exception(
# "problem making arguments out of QUERY_STRING: %s",
# self.req['QUERY_STRING']
# )
#
# if self.method in ('POST', 'PUT') and self.body:
# content_type = self.headers.get("Content-Type", '')
# # TODO make sure these come out as unicode
# if content_type.startswith("application/x-www-form-urlencoded"):
# for name, values in cgi.parse_qs(self.body).iteritems():
# _arguments.setdefault(name, []).extend(values)
# # multipart form
# elif content_type.startswith("multipart/form-data"):
# try:
# fs = cgi.FieldStorage(
# fp=StringIO.StringIO(self.body),
# environ=self.req,
# keep_blank_values=1
# )
# for k in fs.keys():
# part = fs[k]
# if part.filename:
# _files[k] = part
# _arguments[k] = part.value
# except:
# _log.exception(
# "problem parsing multipart/form-data"
# )
# # add any arguments from JSON body
# elif content_type.startswith("application/json"):
# try:
# body = nudge.json.json_decode(self.body)
# if isinstance(body, types.DictType):
# _arguments = dict(_arguments, **body)
#
# except (ValueError):
# raise HTTPException(400, "body is not JSON")
#
# self.files = _files
# return _arguments
#
# def write(self, content):
# self._buffer += content
#
# def request_time(self):
# return time.time() - self.start_time
. Output only the next line. | return WSGIRequest(new_env) |
Given the code snippet: <|code_start|> self.content_type = content_type
self.http_status = http_status
if not headers:
headers = {}
self.headers = headers
class RequestAwareRenderer(object):
def __call__(self, req, result):
pass
class Json(object):
''' Default Nudge HTTP Content Type. Encodes the entire endpoint
result as json, and returns.
Note this renderer will not allow you to pass back a top level
list or tuple (javascript array) because it is insecure, and could
allow a CSRF attack. See here:
http://flask.pocoo.org/docs/security/#json-security
'''
def __call__(self, result):
if result == None:
raise HTTPException(404)
if isinstance(result, (types.ListType, types.TupleType)):
raise SecurityException(
'Results that encode as json arrays are not '+\
'allowed for security concerns'
)
return Result(
<|code_end|>
, generate the next line using the imports in this file:
import base64
import types
from cStringIO import StringIO
from nudge.json import json_encode
from nudge.error import HTTPException, SecurityException
and context (functions, classes, or occasionally code) from other files:
# Path: nudge/json.py
# def json_encode(o):
# return _encoder.encode(o)
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | content=json_encode(result), |
Here is a snippet: <|code_start|> 'Identity',
'Plain',
]
class Result(object):
def __init__(self, content, content_type, http_status=200, headers=None):
self.content = content
self.content_type = content_type
self.http_status = http_status
if not headers:
headers = {}
self.headers = headers
class RequestAwareRenderer(object):
def __call__(self, req, result):
pass
class Json(object):
''' Default Nudge HTTP Content Type. Encodes the entire endpoint
result as json, and returns.
Note this renderer will not allow you to pass back a top level
list or tuple (javascript array) because it is insecure, and could
allow a CSRF attack. See here:
http://flask.pocoo.org/docs/security/#json-security
'''
def __call__(self, result):
if result == None:
<|code_end|>
. Write the next line using the current file imports:
import base64
import types
from cStringIO import StringIO
from nudge.json import json_encode
from nudge.error import HTTPException, SecurityException
and context from other files:
# Path: nudge/json.py
# def json_encode(o):
# return _encoder.encode(o)
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
, which may include functions, classes, or code. Output only the next line. | raise HTTPException(404) |
Continue the code snippet: <|code_start|>]
class Result(object):
def __init__(self, content, content_type, http_status=200, headers=None):
self.content = content
self.content_type = content_type
self.http_status = http_status
if not headers:
headers = {}
self.headers = headers
class RequestAwareRenderer(object):
def __call__(self, req, result):
pass
class Json(object):
''' Default Nudge HTTP Content Type. Encodes the entire endpoint
result as json, and returns.
Note this renderer will not allow you to pass back a top level
list or tuple (javascript array) because it is insecure, and could
allow a CSRF attack. See here:
http://flask.pocoo.org/docs/security/#json-security
'''
def __call__(self, result):
if result == None:
raise HTTPException(404)
if isinstance(result, (types.ListType, types.TupleType)):
<|code_end|>
. Use current file imports:
import base64
import types
from cStringIO import StringIO
from nudge.json import json_encode
from nudge.error import HTTPException, SecurityException
and context (classes, functions, or code) from other files:
# Path: nudge/json.py
# def json_encode(o):
# return _encoder.encode(o)
#
# Path: nudge/error.py
# DEFAULT_ERROR_CODE = 500
# DEFAULT_ERROR_CONTENT_TYPE = "application/json; charset=UTF-8"
# DEFAULT_ERROR_CONTENT = '{"message": "%s", "code": %i}' % (
# "Internal Server Error",
# DEFAULT_ERROR_CODE,
# )
# class JsonErrorHandler(object):
# class HTTPError(Exception):
# class SecurityException(Exception):
# def __call__(self, exp, req=None, log_assert=True):
# def handle_exception(exp, exp_handlers, default_handler=None):
# def __init__(self, status_code, message=None):
. Output only the next line. | raise SecurityException( |
Given snippet: <|code_start|> if self.optional:
return self.default
elif exists:
msg = " is required, exists, but is empty"
else:
msg = " is required but does not exist"
raise nudge.publisher.HTTPException(
400,
self.name + msg
)
# Query string args will come in list format, take the first.
# Unless of course we are expecting a list from the json body.
if type(data) in [types.ListType] and not isinstance(self, List):
data = data[0]
try:
return self.validator(data)
except (validate.ValidationError), e:
msg = "invalid value for argument '%s': '%s'" % (
self.name,
data
)
if e.message:
msg += ': %s' % e.message
raise nudge.publisher.HTTPException(400, msg)
self.argspec = func
class CustomArg(Arg):
def __init__(self, name=None):
if not name and hasattr(self, '__name__'):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import types
import nudge
import nudge.validator as validate
from nudge.utils import dehump
and context:
# Path: nudge/utils.py
# def dehump(string):
# def fix_caps(match):
# result = ''
# for group in match.groups():
# result += group[0:len(group)-1]+"_"+group[len(group)-1].lower()
# return result
# return camel_case.sub(fix_caps, string).strip()
which might include code, classes, or functions. Output only the next line. | name = dehump(self.__name__) |
Given the following code snippet before the placeholder: <|code_start|>
<form action="/hello" method="get">
<input type="text" name="name" value="Joe"/>
<input type="submit" value="get"/>
</form>
</html>
"""
def post_hello(self, name):
return "Hello %s" % name
def put_hello(self, name):
return "Hello %s" % name
def get_hello(sef, name, number=0):
if number:
name = '%s %i' % (name, number)
return "Hello %s" % name
hws = HelloWorldService()
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write(hws.index())
class HelloHandler(tornado.web.RequestHandler):
def post(self, name=None):
<|code_end|>
, predict the next line using imports from the current file:
from optparse import OptionParser
from nudge.json import json_decode
import tornado.httpserver
import tornado.ioloop
import tornado.web
and context including class names, function names, and sometimes code from other files:
# Path: nudge/json.py
# def json_decode(o):
# # remove tabs if they exists
# o = o.replace('\t','')
# data = _decoder.decode(o)
# return data
. Output only the next line. | body = json_decode(self.request.body) |
Continue the code snippet: <|code_start|> context_instance=RequestContext(request))
def contacts_advertising(request):
return render_to_response('ifiltr/contacts_advertising.html',
{},
context_instance=RequestContext(request))
def contacts_partnerships(request):
return render_to_response('ifiltr/contacts_partnerships.html',
{},
context_instance=RequestContext(request))
def search(request):
required = ['q']
optional = ['brands', 'minPrice', 'maxPrice', 'startIndex', 'maxResults']
for param in required:
if param not in request.GET:
return HttpResponseBadRequest(param + " was not found in request.")
params = {}
for param in optional:
if param in request.GET:
params[param] = request.GET[param]
return render_to_response('ifiltr/results.html',
{'title':'Search Results',
'pagename':'results'},
context_instance=RequestContext(request))
def goToItem(request):
<|code_end|>
. Use current file imports:
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound, HttpResponseBadRequest
from django.shortcuts import render_to_response
from django.template import RequestContext
from ifiltr_site.models import clickThrough, Category
import time, json
and context (classes, functions, or code) from other files:
# Path: ifiltr_site/models.py
# class clickThrough(models.Model):
# person = models.ForeignKey(Person)
# item = models.URLField()
#
# class Category(models.Model):
# parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL)
# name = models.CharField(max_length=50)
# depth = models.IntegerField()
. Output only the next line. | thisClick = clickThrough(person=request.GET['person'], item=request.GET['url']) |
Given the following code snippet before the placeholder: <|code_start|>
def contacts_partnerships(request):
return render_to_response('ifiltr/contacts_partnerships.html',
{},
context_instance=RequestContext(request))
def search(request):
required = ['q']
optional = ['brands', 'minPrice', 'maxPrice', 'startIndex', 'maxResults']
for param in required:
if param not in request.GET:
return HttpResponseBadRequest(param + " was not found in request.")
params = {}
for param in optional:
if param in request.GET:
params[param] = request.GET[param]
return render_to_response('ifiltr/results.html',
{'title':'Search Results',
'pagename':'results'},
context_instance=RequestContext(request))
def goToItem(request):
thisClick = clickThrough(person=request.GET['person'], item=request.GET['url'])
thisClick.save()
return HttpResponseRedirect(thisClick.item)
def getCategories(request):
if 'parent' not in request.GET:
<|code_end|>
, predict the next line using imports from the current file:
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound, HttpResponseBadRequest
from django.shortcuts import render_to_response
from django.template import RequestContext
from ifiltr_site.models import clickThrough, Category
import time, json
and context including class names, function names, and sometimes code from other files:
# Path: ifiltr_site/models.py
# class clickThrough(models.Model):
# person = models.ForeignKey(Person)
# item = models.URLField()
#
# class Category(models.Model):
# parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL)
# name = models.CharField(max_length=50)
# depth = models.IntegerField()
. Output only the next line. | categories = Category.objects.filter(parent__exact = None) |
Predict the next line for this snippet: <|code_start|> 'Commercial':{},
'Condo':{},
'Coop':{},
'Duplex':{},
'Foreclosure':{},
'Houseboat':{},
'Income/Investment':{},
'Loft':{},
'Lot/Land':{},
'Mobile/Manufactured':{},
'Multi-Family Home':{},
'New Home':{},
'Ranch [Single Family Home]':{},
'Resort':{},
'Studio':{},
'TIC':{},
'Timeshare':{},
'Townhome':{}}
mainCategories['Fashion']['Shirts'] = [
'Size',
'Style',
'Color',
'Brand',
'Minimum Price',
'Max Price',
'Sleeve Length'
]
print 'deleting errthang'
<|code_end|>
with the help of current file imports:
import os
from ifiltr_site.models import Category
and context from other files:
# Path: ifiltr_site/models.py
# class Category(models.Model):
# parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL)
# name = models.CharField(max_length=50)
# depth = models.IntegerField()
, which may contain function names, class names, or code. Output only the next line. | Category.objects.all().delete() |
Predict the next line for this snippet: <|code_start|>"""
iFiltr, Simple & Secure Social Shopping.
Copyright (C) 2012-2013 iFiltr (<https://ifiltr.com>).
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
@csrf_exempt
def login(request):
pre_login.send(JanrainSignal, request=request)
try:
token = request.POST['token']
except KeyError:
# TODO: set ERROR to something
login_failure.send(JanrainSignal, message='Error retreiving token', data=None)
return HttpResponseRedirect('/')
try:
<|code_end|>
with the help of current file imports:
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib import auth
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
from django.template import RequestContext
from janrain import api
from janrain.models import JanrainUser
from janrain.signals import *
and context from other files:
# Path: janrain/api.py
# class JanrainAuthenticationError(Exception):
# def auth_info(token):
# def get_contacts(ident):
# def set_status(ident, status, loc=None, truncate=True):
# def map(ident, pk, overwrite=True):
# def unmap(pk, identifier=None, all_identifiers=False, unlink=False):
# def mappings(pk):
# def activity(ident, activity, trunc=True, loc=None):
# def analytics_access(start, end):
# def set_auth_providers(providers):
# def _api_call(function, **kwargs):
#
# Path: janrain/models.py
# class JanrainUser(models.Model):
# user = models.ForeignKey(User, related_name='janrain_user')
# username = models.CharField(max_length=512, blank=False)
# provider = models.CharField(max_length=64, blank=False)
# identifier = models.URLField(max_length=512, blank=False)
# avatar = models.URLField(max_length=512, blank=True)
# url = models.URLField(max_length=512, blank=True)
, which may contain function names, class names, or code. Output only the next line. | profile = api.auth_info(token) |
Given the following code snippet before the placeholder: <|code_start|> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
@csrf_exempt
def login(request):
pre_login.send(JanrainSignal, request=request)
try:
token = request.POST['token']
except KeyError:
# TODO: set ERROR to something
login_failure.send(JanrainSignal, message='Error retreiving token', data=None)
return HttpResponseRedirect('/')
try:
profile = api.auth_info(token)
except api.JanrainAuthenticationError:
login_failure.send(JanrainSignal, message='Error retreiving profile', data=None)
return HttpResponseRedirect('/')
post_profile_data.send(JanrainSignal, profile_data=profile)
u = None
p = profile['profile']
u = auth.authenticate(profile=p)
post_authenticate.send(JanrainSignal, user=u, profile_data=profile)
<|code_end|>
, predict the next line using imports from the current file:
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib import auth
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
from django.template import RequestContext
from janrain import api
from janrain.models import JanrainUser
from janrain.signals import *
and context including class names, function names, and sometimes code from other files:
# Path: janrain/api.py
# class JanrainAuthenticationError(Exception):
# def auth_info(token):
# def get_contacts(ident):
# def set_status(ident, status, loc=None, truncate=True):
# def map(ident, pk, overwrite=True):
# def unmap(pk, identifier=None, all_identifiers=False, unlink=False):
# def mappings(pk):
# def activity(ident, activity, trunc=True, loc=None):
# def analytics_access(start, end):
# def set_auth_providers(providers):
# def _api_call(function, **kwargs):
#
# Path: janrain/models.py
# class JanrainUser(models.Model):
# user = models.ForeignKey(User, related_name='janrain_user')
# username = models.CharField(max_length=512, blank=False)
# provider = models.CharField(max_length=64, blank=False)
# identifier = models.URLField(max_length=512, blank=False)
# avatar = models.URLField(max_length=512, blank=True)
# url = models.URLField(max_length=512, blank=True)
. Output only the next line. | juser = JanrainUser.objects.get_or_create( |
Using the snippet: <|code_start|>"""
iFiltr, Simple & Secure Social Shopping.
Copyright (C) 2012-2013 iFiltr (<https://ifiltr.com>).
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
TEST_PATH_PREFIX = 'django-storages-test'
class HashPathStorageTest(TestCase):
def setUp(self):
self.test_path = os.path.join(settings.MEDIA_ROOT, TEST_PATH_PREFIX)
<|code_end|>
, determine the next line of code. You have imports:
import os
import shutil
from django.test import TestCase
from django.core.files.base import ContentFile
from django.conf import settings
from storages.backends.hashpath import HashPathStorage
and context (class names, function names, or code) available:
# Path: storages/backends/hashpath.py
# class HashPathStorage(FileSystemStorage):
# """
# Creates a hash from the uploaded file to build the path.
# """
#
# def save(self, name, content):
# # Get the content name if name is not given
# if name is None: name = content.name
#
# # Get the SHA1 hash of the uploaded file
# sha1 = hashlib.sha1()
# for chunk in content.chunks():
# sha1.update(chunk)
# sha1sum = sha1.hexdigest()
#
# # Build the new path and split it into directory and filename
# name = os.path.join(os.path.split(name)[0], sha1sum[:1], sha1sum[1:2], sha1sum)
# dir_name, file_name = os.path.split(name)
#
# # Return the name if the file is already there
# if self.exists(name):
# return name
#
# # Try to create the directory relative to location specified in __init__
# try:
# os.makedirs(os.path.join(self.location, dir_name))
# except OSError, e:
# if e.errno is not errno.EEXIST:
# raise e
#
# # Save the file
# name = self._save(name, content)
#
# # Store filenames with forward slashes, even on Windows
# return force_unicode(name.replace('\\', '/'))
. Output only the next line. | self.storage = HashPathStorage(location=self.test_path) |
Given the code snippet: <|code_start|>"""
iFiltr, Simple & Secure Social Shopping.
Copyright (C) 2012-2013 iFiltr (<https://ifiltr.com>).
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
__all__ = (
'SafeJoinTest',
'S3BotoStorageTests',
#'S3BotoStorageFileTests',
)
class S3BotoTestCase(TestCase):
@mock.patch('storages.backends.s3boto.S3Connection')
def setUp(self, S3Connection):
<|code_end|>
, generate the next line using the imports in this file:
import os
import mock
from uuid import uuid4
from urllib2 import urlopen
from django.test import TestCase
from django.core.files.base import ContentFile
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from boto.s3.key import Key
from storages.backends import s3boto
and context (functions, classes, or occasionally code) from other files:
# Path: storages/backends/s3boto.py
# ACCESS_KEY_NAME = getattr(settings, 'AWS_S3_ACCESS_KEY_ID', getattr(settings, 'AWS_ACCESS_KEY_ID', None))
# SECRET_KEY_NAME = getattr(settings, 'AWS_S3_SECRET_ACCESS_KEY', getattr(settings, 'AWS_SECRET_ACCESS_KEY', None))
# HEADERS = getattr(settings, 'AWS_HEADERS', {})
# STORAGE_BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', None)
# AUTO_CREATE_BUCKET = getattr(settings, 'AWS_AUTO_CREATE_BUCKET', False)
# DEFAULT_ACL = getattr(settings, 'AWS_DEFAULT_ACL', 'public-read')
# BUCKET_ACL = getattr(settings, 'AWS_BUCKET_ACL', DEFAULT_ACL)
# QUERYSTRING_AUTH = getattr(settings, 'AWS_QUERYSTRING_AUTH', True)
# QUERYSTRING_EXPIRE = getattr(settings, 'AWS_QUERYSTRING_EXPIRE', 3600)
# REDUCED_REDUNDANCY = getattr(settings, 'AWS_REDUCED_REDUNDANCY', False)
# LOCATION = getattr(settings, 'AWS_LOCATION', '')
# CUSTOM_DOMAIN = getattr(settings, 'AWS_S3_CUSTOM_DOMAIN', None)
# CALLING_FORMAT = getattr(settings, 'AWS_S3_CALLING_FORMAT',
# SubdomainCallingFormat())
# SECURE_URLS = getattr(settings, 'AWS_S3_SECURE_URLS', True)
# FILE_NAME_CHARSET = getattr(settings, 'AWS_S3_FILE_NAME_CHARSET', 'utf-8')
# FILE_OVERWRITE = getattr(settings, 'AWS_S3_FILE_OVERWRITE', True)
# FILE_BUFFER_SIZE = getattr(settings, 'AWS_S3_FILE_BUFFER_SIZE', 5242880)
# IS_GZIPPED = getattr(settings, 'AWS_IS_GZIPPED', False)
# PRELOAD_METADATA = getattr(settings, 'AWS_PRELOAD_METADATA', False)
# GZIP_CONTENT_TYPES = getattr(settings, 'GZIP_CONTENT_TYPES', (
# 'text/css',
# 'application/javascript',
# 'application/x-javascript',
# ))
# MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
# 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# DATESTR_RE = re.compile(r"^.+, (?P<day>\d{1,2}) (?P<month_name>%s) (?P<year>\d{4}) (?P<hour>\d{1,2}):(?P<minute>\d{1,2}):(?P<second>\d{1,2}) (GMT|UTC)$" % ("|".join(MONTH_NAMES)))
# def safe_join(base, *paths):
# def _parse_datestring(dstr):
# def __init__(self, bucket=STORAGE_BUCKET_NAME, access_key=None,
# secret_key=None, bucket_acl=BUCKET_ACL, acl=DEFAULT_ACL,
# headers=HEADERS, gzip=IS_GZIPPED,
# gzip_content_types=GZIP_CONTENT_TYPES,
# querystring_auth=QUERYSTRING_AUTH,
# querystring_expire=QUERYSTRING_EXPIRE,
# reduced_redundancy=REDUCED_REDUNDANCY,
# custom_domain=CUSTOM_DOMAIN,
# secure_urls=SECURE_URLS,
# location=LOCATION,
# file_name_charset=FILE_NAME_CHARSET,
# preload_metadata=PRELOAD_METADATA,
# calling_format=CALLING_FORMAT):
# def bucket(self):
# def entries(self):
# def _get_access_keys(self):
# def _get_or_create_bucket(self, name):
# def _clean_name(self, name):
# def _normalize_name(self, name):
# def _encode_name(self, name):
# def _decode_name(self, name):
# def _compress_content(self, content):
# def _open(self, name, mode='rb'):
# def _save(self, name, content):
# def delete(self, name):
# def exists(self, name):
# def listdir(self, name):
# def size(self, name):
# def modified_time(self, name):
# def url(self, name):
# def get_available_name(self, name):
# def __init__(self, name, mode, storage, buffer_size=FILE_BUFFER_SIZE):
# def size(self):
# def file(self):
# def read(self, *args, **kwargs):
# def write(self, *args, **kwargs):
# def _buffer_file_size(self):
# def _flush_write_buffer(self):
# def close(self):
# class S3BotoStorage(Storage):
# class S3BotoStorageFile(File):
. Output only the next line. | self.storage = s3boto.S3BotoStorage()
|
Continue the code snippet: <|code_start|> else:
factor_suffix = "bytes"
factored_bytes = 0
for factor, suffix in ABBREVS:
if abs_num_bytes >= factor:
factored_bytes = int(abs_num_bytes / factor)
factor_suffix = suffix
break
if factored_bytes == 1:
precision = 0
return f"{neg}{factored_bytes:.{precision}f} {factor_suffix}"
def new_percent_saved(report_stats: ReportStats) -> str:
"""Spit out how much space the optimization saved."""
size_in = report_stats.bytes_in
if size_in > 0:
size_out = report_stats.bytes_out
ratio = size_out / size_in
kb_saved = _humanize_bytes(size_in - size_out)
else:
ratio = 1
kb_saved = f"0 {ABBREVS[-1][1]}"
percent_saved = (1 - ratio) * 100
result = "{:.{prec}f}% ({})".format(percent_saved, kb_saved, prec=2)
return result
<|code_end|>
. Use current file imports:
from pathlib import Path
from typing import List
from typing import Optional
from typing import Tuple
from .settings import Settings
and context (classes, functions, or code) from other files:
# Path: picopt/settings.py
# class Settings(Namespace):
# """Global settings class."""
#
# # advpng: bool = False
# bigger: bool = False
# comics: bool = False
# destroy_metadata: bool = False
# follow_symlinks: bool = True
# formats: Set[str] = set()
# gifsicle: bool = True
# jobs: int = multiprocessing.cpu_count()
# # jpegrescan: bool = True
# # jpegrescan_multithread: bool = False
# jpegtran: bool = True
# jpegtran_prog: bool = True
# list_only: bool = False
# mozjpeg: bool = True
# optimize_after: Optional[float] = None
# optipng: bool = True
# paths: Set[str] = set()
# pngout: bool = True
# record_timestamp: bool = False
# recurse: bool = False
# test: bool = False
# to_png_formats: Set[str] = set()
# verbose: int = 1
#
# def __init__(
# self,
# programs: Optional[Set[Callable]] = None,
# namespace: Optional[Namespace] = None,
# ) -> None:
# """Initialize settings object with arguments namespace."""
# self._update(namespace)
# self._config_program_reqs(programs)
# self.verbose += 1
# self.paths = set(self.paths)
# self._update_formats()
# self.jobs = max(self.jobs, 1)
#
# # self._set_jpegrescan_threading()
#
# @staticmethod
# def parse_date_string(date_str: str) -> float:
# """Turn a datetime string into an epoch float."""
# after_dt = dateutil.parser.parse(date_str)
# return time.mktime(after_dt.timetuple())
#
# def _update_formats(self) -> None:
# """Update the format list from to_png_formats & comics flag."""
# from .formats.comic import Comic
# from .formats.gif import Gif
# from .formats.jpeg import Jpeg
# from .formats.png import Png
#
# if not self.to_png_formats:
# self.to_png_formats = Png.CONVERTABLE_FORMATS
# if not self.formats:
# self.formats = self.to_png_formats | Jpeg.FORMATS | Gif.FORMATS
# if self.comics:
# self.formats |= Comic.FORMATS
#
# print("Optimizing formats:", *sorted(self.formats))
#
# # def _set_jpegrescan_threading(self) -> None:
# # """
# # Make a rough guess about weather or not to invoke multithreading.
# #
# # jpegrescan '-t' uses three threads
# # """
# # files_in_paths = 0
# # non_file_in_paths = False
# # for filename in self.paths:
# # path = Path(filename)
# # if path.is_file():
# # files_in_paths += 1
# # else:
# # non_file_in_paths = True
# #
# # self.jpegrescan_multithread = (
# # not non_file_in_paths and self.jobs - (files_in_paths * 3) > -1
# # )
#
# def _update(self, namespace: Optional[Namespace]) -> None:
# """Update settings with a dict."""
# if not namespace:
# return
# for key, val in namespace.__dict__.items():
# if key.startswith("_"):
# continue
# setattr(self, key, val)
#
# def _set_program_defaults(self, programs: Optional[Set[Callable]]) -> None:
# """Run the external program tester on the required binaries."""
# if not programs:
# from .formats.gif import Gif
# from .formats.jpeg import Jpeg
# from .formats.png import Png
#
# programs = set(Png.PROGRAMS + Gif.PROGRAMS + Jpeg.PROGRAMS)
# for program in programs:
# prog_name = program.__func__.__name__ # type: ignore
# val = getattr(self, prog_name) and extern.does_external_program_run(
# prog_name, Settings.verbose
# )
# setattr(self, prog_name, val)
#
# def _config_program_reqs(self, programs: Optional[Set[Callable]]) -> None:
# """Run the program tester and determine if we can do anything."""
# self._set_program_defaults(programs)
#
# do_png = self.optipng or self.pngout # or self.advpng
# do_jpeg = self.mozjpeg or self.jpegtran # of self.jpegrescan
# do_comics = self.comics
#
# self.can_do = do_png or do_jpeg or do_comics
. Output only the next line. | def _report_saved(settings: Settings, report_stats: ReportStats) -> str: |
Next line prediction: <|code_start|>"""Test stats module."""
__all__ = () # hides module from pydocstring
TYPE_NAME = "png"
PATH = Path("dummyPath")
def test_skip() -> None:
<|code_end|>
. Use current file imports:
(from argparse import Namespace
from pathlib import Path
from picopt import stats
from picopt.settings import Settings)
and context including class names, function names, or small code snippets from other files:
# Path: picopt/stats.py
# ABBREVS = (
# (1 << int(50), "PiB"),
# (1 << int(40), "TiB"),
# (1 << int(30), "GiB"),
# (1 << int(20), "MiB"),
# (1 << int(10), "kiB"),
# (1, "bytes"),
# )
# class ReportStats(object):
# def __init__(
# self,
# final_path: Path,
# report: Optional[str] = None,
# bytes_count: Optional[Tuple[int, int]] = None,
# nag_about_gifs: bool = False,
# error: Optional[str] = None,
# ) -> None:
# def _humanize_bytes(num_bytes: int, precision: int = 1) -> str:
# def new_percent_saved(report_stats: ReportStats) -> str:
# def _report_saved(settings: Settings, report_stats: ReportStats) -> str:
# def report_saved(settings: Settings, report_stats: ReportStats) -> None:
# def report_totals(
# settings: Settings,
# bytes_in: int,
# bytes_out: int,
# nag_about_gifs: bool,
# errors: List[Tuple[Path, str]],
# ) -> None:
# def skip(type_name: str, path: Path) -> ReportStats:
#
# Path: picopt/settings.py
# class Settings(Namespace):
# """Global settings class."""
#
# # advpng: bool = False
# bigger: bool = False
# comics: bool = False
# destroy_metadata: bool = False
# follow_symlinks: bool = True
# formats: Set[str] = set()
# gifsicle: bool = True
# jobs: int = multiprocessing.cpu_count()
# # jpegrescan: bool = True
# # jpegrescan_multithread: bool = False
# jpegtran: bool = True
# jpegtran_prog: bool = True
# list_only: bool = False
# mozjpeg: bool = True
# optimize_after: Optional[float] = None
# optipng: bool = True
# paths: Set[str] = set()
# pngout: bool = True
# record_timestamp: bool = False
# recurse: bool = False
# test: bool = False
# to_png_formats: Set[str] = set()
# verbose: int = 1
#
# def __init__(
# self,
# programs: Optional[Set[Callable]] = None,
# namespace: Optional[Namespace] = None,
# ) -> None:
# """Initialize settings object with arguments namespace."""
# self._update(namespace)
# self._config_program_reqs(programs)
# self.verbose += 1
# self.paths = set(self.paths)
# self._update_formats()
# self.jobs = max(self.jobs, 1)
#
# # self._set_jpegrescan_threading()
#
# @staticmethod
# def parse_date_string(date_str: str) -> float:
# """Turn a datetime string into an epoch float."""
# after_dt = dateutil.parser.parse(date_str)
# return time.mktime(after_dt.timetuple())
#
# def _update_formats(self) -> None:
# """Update the format list from to_png_formats & comics flag."""
# from .formats.comic import Comic
# from .formats.gif import Gif
# from .formats.jpeg import Jpeg
# from .formats.png import Png
#
# if not self.to_png_formats:
# self.to_png_formats = Png.CONVERTABLE_FORMATS
# if not self.formats:
# self.formats = self.to_png_formats | Jpeg.FORMATS | Gif.FORMATS
# if self.comics:
# self.formats |= Comic.FORMATS
#
# print("Optimizing formats:", *sorted(self.formats))
#
# # def _set_jpegrescan_threading(self) -> None:
# # """
# # Make a rough guess about weather or not to invoke multithreading.
# #
# # jpegrescan '-t' uses three threads
# # """
# # files_in_paths = 0
# # non_file_in_paths = False
# # for filename in self.paths:
# # path = Path(filename)
# # if path.is_file():
# # files_in_paths += 1
# # else:
# # non_file_in_paths = True
# #
# # self.jpegrescan_multithread = (
# # not non_file_in_paths and self.jobs - (files_in_paths * 3) > -1
# # )
#
# def _update(self, namespace: Optional[Namespace]) -> None:
# """Update settings with a dict."""
# if not namespace:
# return
# for key, val in namespace.__dict__.items():
# if key.startswith("_"):
# continue
# setattr(self, key, val)
#
# def _set_program_defaults(self, programs: Optional[Set[Callable]]) -> None:
# """Run the external program tester on the required binaries."""
# if not programs:
# from .formats.gif import Gif
# from .formats.jpeg import Jpeg
# from .formats.png import Png
#
# programs = set(Png.PROGRAMS + Gif.PROGRAMS + Jpeg.PROGRAMS)
# for program in programs:
# prog_name = program.__func__.__name__ # type: ignore
# val = getattr(self, prog_name) and extern.does_external_program_run(
# prog_name, Settings.verbose
# )
# setattr(self, prog_name, val)
#
# def _config_program_reqs(self, programs: Optional[Set[Callable]]) -> None:
# """Run the program tester and determine if we can do anything."""
# self._set_program_defaults(programs)
#
# do_png = self.optipng or self.pngout # or self.advpng
# do_jpeg = self.mozjpeg or self.jpegtran # of self.jpegrescan
# do_comics = self.comics
#
# self.can_do = do_png or do_jpeg or do_comics
. Output only the next line. | res = stats.skip(TYPE_NAME, PATH) |
Here is a snippet: <|code_start|> "x"/Int16ul,
"y"/Int16ul
),
"construction_radius"/Struct(
"x"/Float32l,
"y"/Float32l
),
"elevation_flag"/Byte,
"fog_flag"/Byte,
"terrain_restriction_id"/Int16ul,
"movement_type"/Byte,
"attribute_max"/Int16ul,
"attribute_rot"/Float32l,
"area_effect_level"/Byte,
"combat_level"/Byte,
"select_level"/Byte,
"map_draw_level"/Byte,
"unit_level"/Byte,
"multiple_attribute_mod"/Float32l,
"map_color"/Byte,
"help_string_id"/Int32ul,
"help_page_id"/Int32ul,
"hotkey_id"/Int32ul,
"recyclable"/Byte,
"track_as_resource"/Byte,
"create_doppleganger"/Byte,
"resource_group"/Byte,
"occlusion_mask"/Byte,
"obstruction_type"/Byte,
"selection_shape"/Byte,
<|code_end|>
. Write the next line using the current file imports:
from construct import (
Struct, Float32l, Int16ul, Byte, Embedded, Switch, If,
Int32ul, Array, String, Padding, IfThenElse, this
)
from mgz.util import find_version, find_save_version, Version
and context from other files:
# Path: mgz/util.py
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
, which may include functions, classes, or code. Output only the next line. | "object_flags"/If(lambda ctx: find_version(ctx) != Version.AOK, Int32ul), |
Next line prediction: <|code_start|> "group"/Int16ul
)
animated = "animated"/Struct(
base,
"speed"/Float32l
)
moving = "moving"/Struct(
animated,
"move_sprite"/Int16ul,
"run_sprite"/Int16ul,
"turn_speed"/Float32l,
"size_class"/Byte,
"trailing_unit"/Int16ul,
"trailing_options"/Byte,
"trailing_spacing"/Float32l,
"move_algorithm"/Byte,
"turn_radius"/Float32l,
"turn_radius_speed"/Float32l,
"maximum_yaw_per_second_moving"/Float32l,
"stationary_yaw_per_revolution_time"/Float32l,
"maximum_yaw_per_second_stationary"/Float32l
)
action = "action"/Struct(
moving,
"default_task"/Int16ul,
"search_radius"/Float32l,
"work_rate"/Float32l,
<|code_end|>
. Use current file imports:
(from construct import (
Struct, Float32l, Int16ul, Byte, Embedded, Switch, If,
Int32ul, Array, String, Padding, IfThenElse, this
)
from mgz.util import find_version, find_save_version, Version)
and context including class names, function names, or small code snippets from other files:
# Path: mgz/util.py
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
. Output only the next line. | "handicap_work_rate"/If(lambda ctx: find_save_version(ctx) >= 25.06, Float32l), |
Using the snippet: <|code_start|> "x"/Int16ul,
"y"/Int16ul
),
"construction_radius"/Struct(
"x"/Float32l,
"y"/Float32l
),
"elevation_flag"/Byte,
"fog_flag"/Byte,
"terrain_restriction_id"/Int16ul,
"movement_type"/Byte,
"attribute_max"/Int16ul,
"attribute_rot"/Float32l,
"area_effect_level"/Byte,
"combat_level"/Byte,
"select_level"/Byte,
"map_draw_level"/Byte,
"unit_level"/Byte,
"multiple_attribute_mod"/Float32l,
"map_color"/Byte,
"help_string_id"/Int32ul,
"help_page_id"/Int32ul,
"hotkey_id"/Int32ul,
"recyclable"/Byte,
"track_as_resource"/Byte,
"create_doppleganger"/Byte,
"resource_group"/Byte,
"occlusion_mask"/Byte,
"obstruction_type"/Byte,
"selection_shape"/Byte,
<|code_end|>
, determine the next line of code. You have imports:
from construct import (
Struct, Float32l, Int16ul, Byte, Embedded, Switch, If,
Int32ul, Array, String, Padding, IfThenElse, this
)
from mgz.util import find_version, find_save_version, Version
and context (class names, function names, or code) available:
# Path: mgz/util.py
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
. Output only the next line. | "object_flags"/If(lambda ctx: find_version(ctx) != Version.AOK, Int32ul), |
Using the snippet: <|code_start|>
class TestFastUserPatch15(unittest.TestCase):
@classmethod
def setUpClass(cls):
with open('tests/recs/small.mgz', 'rb') as handle:
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from mgz.fast.header import parse
from mgz.util import Version
and context (class names, function names, or code) available:
# Path: mgz/fast/header.py
# def parse(data):
# """Parse recorded game header."""
# try:
# header = decompress(data)
# version, game, save, log = parse_version(header, data)
# if version not in (Version.USERPATCH15, Version.DE, Version.HD):
# raise RuntimeError(f"{version} not supported")
# de = parse_de(header, version, save)
# hd = parse_hd(header, version, save)
# metadata, num_players = parse_metadata(header)
# map_ = parse_map(header, version)
# players, mod = parse_players(header, num_players, version)
# scenario = parse_scenario(header, num_players, version, save)
# lobby = parse_lobby(header, version, save)
# except (struct.error, zlib.error, AssertionError, MemoryError):
# raise RuntimeError("could not parse")
# return dict(
# version=version,
# game_version=game,
# save_version=save,
# log_version=log,
# players=players,
# map=map_,
# de=de,
# hd=hd,
# mod=mod,
# metadata=metadata,
# scenario=scenario,
# lobby=lobby
# )
#
# Path: mgz/util.py
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
. Output only the next line. | cls.data = parse(handle) |
Given the code snippet: <|code_start|>
class TestFastUserPatch15(unittest.TestCase):
@classmethod
def setUpClass(cls):
with open('tests/recs/small.mgz', 'rb') as handle:
cls.data = parse(handle)
def test_version(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
from mgz.fast.header import parse
from mgz.util import Version
and context (functions, classes, or occasionally code) from other files:
# Path: mgz/fast/header.py
# def parse(data):
# """Parse recorded game header."""
# try:
# header = decompress(data)
# version, game, save, log = parse_version(header, data)
# if version not in (Version.USERPATCH15, Version.DE, Version.HD):
# raise RuntimeError(f"{version} not supported")
# de = parse_de(header, version, save)
# hd = parse_hd(header, version, save)
# metadata, num_players = parse_metadata(header)
# map_ = parse_map(header, version)
# players, mod = parse_players(header, num_players, version)
# scenario = parse_scenario(header, num_players, version, save)
# lobby = parse_lobby(header, version, save)
# except (struct.error, zlib.error, AssertionError, MemoryError):
# raise RuntimeError("could not parse")
# return dict(
# version=version,
# game_version=game,
# save_version=save,
# log_version=log,
# players=players,
# map=map_,
# de=de,
# hd=hd,
# mod=mod,
# metadata=metadata,
# scenario=scenario,
# lobby=lobby
# )
#
# Path: mgz/util.py
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
. Output only the next line. | self.assertEqual(self.data['version'], Version.USERPATCH15) |
Given snippet: <|code_start|> "dat_crc"/Bytes(4),
"mp_game_version"/Byte,
"team_index"/Int32ul,
"civ_id"/Int32ul,
"ai_type"/hd_string,
"ai_civ_name_index"/Byte,
"ai_name"/If(lambda ctx: ctx._._.version >= 1005, hd_string),
"name"/hd_string,
"type"/PlayerTypeEnum(Int32ul),
"steam_id"/Int64ul,
"player_number"/Int32sl,
Embedded(If(lambda ctx: ctx._._.version >= 1006 and not ctx._.test_57.is_57, Struct(
"hd_rm_rating"/Int32ul,
"hd_dm_rating"/Int32ul,
)))
)
hd = "hd"/Struct(
"version"/Float32l,
"interval_version"/Int32ul,
"game_options_version"/Int32ul,
"dlc_count"/Int32ul,
"dlc_ids"/Array(lambda ctx: ctx.dlc_count, Int32ul),
"dataset_ref"/Int32ul,
Peek("difficulty_id"/Int32ul),
DifficultyEnum("difficulty"/Int32ul),
"selected_map_id"/Int32ul,
"resolved_map_id"/Int32ul,
"reveal_map"/Int32ul,
Peek("victory_type_id"/Int32ul),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed, Embedded, IfThenElse
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
which might include code, classes, or functions. Output only the next line. | VictoryEnum("victory_type"/Int32ul), |
Given snippet: <|code_start|> "team_index"/Int32ul,
"civ_id"/Int32ul,
"ai_type"/hd_string,
"ai_civ_name_index"/Byte,
"ai_name"/If(lambda ctx: ctx._._.version >= 1005, hd_string),
"name"/hd_string,
"type"/PlayerTypeEnum(Int32ul),
"steam_id"/Int64ul,
"player_number"/Int32sl,
Embedded(If(lambda ctx: ctx._._.version >= 1006 and not ctx._.test_57.is_57, Struct(
"hd_rm_rating"/Int32ul,
"hd_dm_rating"/Int32ul,
)))
)
hd = "hd"/Struct(
"version"/Float32l,
"interval_version"/Int32ul,
"game_options_version"/Int32ul,
"dlc_count"/Int32ul,
"dlc_ids"/Array(lambda ctx: ctx.dlc_count, Int32ul),
"dataset_ref"/Int32ul,
Peek("difficulty_id"/Int32ul),
DifficultyEnum("difficulty"/Int32ul),
"selected_map_id"/Int32ul,
"resolved_map_id"/Int32ul,
"reveal_map"/Int32ul,
Peek("victory_type_id"/Int32ul),
VictoryEnum("victory_type"/Int32ul),
Peek("starting_resources_id"/Int32ul),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed, Embedded, IfThenElse
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
which might include code, classes, or functions. Output only the next line. | ResourceLevelEnum("starting_resources"/Int32ul), |
Based on the snippet: <|code_start|> "ai_type"/hd_string,
"ai_civ_name_index"/Byte,
"ai_name"/If(lambda ctx: ctx._._.version >= 1005, hd_string),
"name"/hd_string,
"type"/PlayerTypeEnum(Int32ul),
"steam_id"/Int64ul,
"player_number"/Int32sl,
Embedded(If(lambda ctx: ctx._._.version >= 1006 and not ctx._.test_57.is_57, Struct(
"hd_rm_rating"/Int32ul,
"hd_dm_rating"/Int32ul,
)))
)
hd = "hd"/Struct(
"version"/Float32l,
"interval_version"/Int32ul,
"game_options_version"/Int32ul,
"dlc_count"/Int32ul,
"dlc_ids"/Array(lambda ctx: ctx.dlc_count, Int32ul),
"dataset_ref"/Int32ul,
Peek("difficulty_id"/Int32ul),
DifficultyEnum("difficulty"/Int32ul),
"selected_map_id"/Int32ul,
"resolved_map_id"/Int32ul,
"reveal_map"/Int32ul,
Peek("victory_type_id"/Int32ul),
VictoryEnum("victory_type"/Int32ul),
Peek("starting_resources_id"/Int32ul),
ResourceLevelEnum("starting_resources"/Int32ul),
"starting_age_id"/Int32ul,
<|code_end|>
, predict the immediate next line with the help of imports:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed, Embedded, IfThenElse
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context (classes, functions, sometimes code) from other files:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | "starting_age"/AgeEnum(Computed(lambda ctx: ctx.starting_age_id)), |
Using the snippet: <|code_start|> "value"/Bytes(lambda ctx: ctx.length)
)
test_57 = "test_57"/Struct(
"check"/Int32ul,
Padding(4),
If(lambda ctx: ctx._._.version >= 1006, Bytes(1)),
Padding(15),
hd_string,
Padding(1),
If(lambda ctx: ctx._._.version >= 1005, hd_string),
hd_string,
Padding(16),
"test"/Int32ul,
"is_57"/Computed(lambda ctx: ctx.check == ctx.test)
)
player = Struct(
"dlc_id"/Int32ul,
"color_id"/Int32ul,
"unk1_1006"/If(lambda ctx: ctx._._.version >= 1006, Bytes(1)),
"unk"/Bytes(2),
"dat_crc"/Bytes(4),
"mp_game_version"/Byte,
"team_index"/Int32ul,
"civ_id"/Int32ul,
"ai_type"/hd_string,
"ai_civ_name_index"/Byte,
"ai_name"/If(lambda ctx: ctx._._.version >= 1005, hd_string),
"name"/hd_string,
<|code_end|>
, determine the next line of code. You have imports:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed, Embedded, IfThenElse
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context (class names, function names, or code) available:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | "type"/PlayerTypeEnum(Int32ul), |
Here is a snippet: <|code_start|>player = Struct(
"dlc_id"/Int32ul,
"color_id"/Int32ul,
"unk1_1006"/If(lambda ctx: ctx._._.version >= 1006, Bytes(1)),
"unk"/Bytes(2),
"dat_crc"/Bytes(4),
"mp_game_version"/Byte,
"team_index"/Int32ul,
"civ_id"/Int32ul,
"ai_type"/hd_string,
"ai_civ_name_index"/Byte,
"ai_name"/If(lambda ctx: ctx._._.version >= 1005, hd_string),
"name"/hd_string,
"type"/PlayerTypeEnum(Int32ul),
"steam_id"/Int64ul,
"player_number"/Int32sl,
Embedded(If(lambda ctx: ctx._._.version >= 1006 and not ctx._.test_57.is_57, Struct(
"hd_rm_rating"/Int32ul,
"hd_dm_rating"/Int32ul,
)))
)
hd = "hd"/Struct(
"version"/Float32l,
"interval_version"/Int32ul,
"game_options_version"/Int32ul,
"dlc_count"/Int32ul,
"dlc_ids"/Array(lambda ctx: ctx.dlc_count, Int32ul),
"dataset_ref"/Int32ul,
Peek("difficulty_id"/Int32ul),
<|code_end|>
. Write the next line using the current file imports:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed, Embedded, IfThenElse
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context from other files:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
, which may include functions, classes, or code. Output only the next line. | DifficultyEnum("difficulty"/Int32ul), |
Here is a snippet: <|code_start|> "civ_id"/Int32ul,
"ai_type"/de_string,
"ai_civ_name_index"/Byte,
"ai_name"/de_string,
"name"/de_string,
"type"/PlayerTypeEnum(Int32ul),
"profile_id"/Int32ul,
Const(b"\x00\x00\x00\x00"),
"player_number"/Int32sl,
"hd_rm_elo"/If(lambda ctx: find_save_version(ctx) < 25.22, Int32ul),
"hd_dm_elo"/If(lambda ctx: find_save_version(ctx) < 25.22, Int32ul),
"prefer_random"/Flag,
"custom_ai"/Flag,
If(lambda ctx: find_save_version(ctx) >= 25.06, "handicap"/Bytes(8)),
)
de = "de"/Struct(
"build"/If(lambda ctx: find_save_version(ctx) >= 25.22, Int32ul),
"version"/Float32l,
"interval_version"/Int32ul,
"game_options_version"/Int32ul,
"dlc_count"/Int32ul,
"dlc_ids"/Array(lambda ctx: ctx.dlc_count, Int32ul),
"dataset_ref"/Int32ul,
Peek("difficulty_id"/Int32ul),
DifficultyEnum("difficulty"/Int32ul),
"selected_map_id"/Int32ul,
"resolved_map_id"/Int32ul,
"reveal_map"/Int32ul,
Peek("victory_type_id"/Int32ul),
<|code_end|>
. Write the next line using the current file imports:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context from other files:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
, which may include functions, classes, or code. Output only the next line. | VictoryEnum("victory_type"/Int32ul), |
Given the following code snippet before the placeholder: <|code_start|> "ai_civ_name_index"/Byte,
"ai_name"/de_string,
"name"/de_string,
"type"/PlayerTypeEnum(Int32ul),
"profile_id"/Int32ul,
Const(b"\x00\x00\x00\x00"),
"player_number"/Int32sl,
"hd_rm_elo"/If(lambda ctx: find_save_version(ctx) < 25.22, Int32ul),
"hd_dm_elo"/If(lambda ctx: find_save_version(ctx) < 25.22, Int32ul),
"prefer_random"/Flag,
"custom_ai"/Flag,
If(lambda ctx: find_save_version(ctx) >= 25.06, "handicap"/Bytes(8)),
)
de = "de"/Struct(
"build"/If(lambda ctx: find_save_version(ctx) >= 25.22, Int32ul),
"version"/Float32l,
"interval_version"/Int32ul,
"game_options_version"/Int32ul,
"dlc_count"/Int32ul,
"dlc_ids"/Array(lambda ctx: ctx.dlc_count, Int32ul),
"dataset_ref"/Int32ul,
Peek("difficulty_id"/Int32ul),
DifficultyEnum("difficulty"/Int32ul),
"selected_map_id"/Int32ul,
"resolved_map_id"/Int32ul,
"reveal_map"/Int32ul,
Peek("victory_type_id"/Int32ul),
VictoryEnum("victory_type"/Int32ul),
Peek("starting_resources_id"/Int32ul),
<|code_end|>
, predict the next line using imports from the current file:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context including class names, function names, and sometimes code from other files:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | ResourceLevelEnum("starting_resources"/Int32ul), |
Predict the next line for this snippet: <|code_start|> "name"/de_string,
"type"/PlayerTypeEnum(Int32ul),
"profile_id"/Int32ul,
Const(b"\x00\x00\x00\x00"),
"player_number"/Int32sl,
"hd_rm_elo"/If(lambda ctx: find_save_version(ctx) < 25.22, Int32ul),
"hd_dm_elo"/If(lambda ctx: find_save_version(ctx) < 25.22, Int32ul),
"prefer_random"/Flag,
"custom_ai"/Flag,
If(lambda ctx: find_save_version(ctx) >= 25.06, "handicap"/Bytes(8)),
)
de = "de"/Struct(
"build"/If(lambda ctx: find_save_version(ctx) >= 25.22, Int32ul),
"version"/Float32l,
"interval_version"/Int32ul,
"game_options_version"/Int32ul,
"dlc_count"/Int32ul,
"dlc_ids"/Array(lambda ctx: ctx.dlc_count, Int32ul),
"dataset_ref"/Int32ul,
Peek("difficulty_id"/Int32ul),
DifficultyEnum("difficulty"/Int32ul),
"selected_map_id"/Int32ul,
"resolved_map_id"/Int32ul,
"reveal_map"/Int32ul,
Peek("victory_type_id"/Int32ul),
VictoryEnum("victory_type"/Int32ul),
Peek("starting_resources_id"/Int32ul),
ResourceLevelEnum("starting_resources"/Int32ul),
"starting_age_id"/Int32ul,
<|code_end|>
with the help of current file imports:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context from other files:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
, which may contain function names, class names, or code. Output only the next line. | "starting_age"/AgeEnum(Computed(lambda ctx: ctx.starting_age_id - 2)), |
Given the following code snippet before the placeholder: <|code_start|>"""Definitive Edition structure."""
# pylint: disable=invalid-name, bad-continuation
de_string = Struct(
Const(b"\x60\x0A"),
"length"/Int16ul,
"value"/Bytes(lambda ctx: ctx.length)
)
separator = Const(b"\xa3_\x02\x00")
player = Struct(
"dlc_id"/Int32ul,
"color_id"/Int32sl,
"selected_color"/Byte,
"selected_team_id"/Byte,
"resolved_team_id"/Byte,
"dat_crc"/Bytes(8),
"mp_game_version"/Byte,
"civ_id"/Int32ul,
"ai_type"/de_string,
"ai_civ_name_index"/Byte,
"ai_name"/de_string,
"name"/de_string,
<|code_end|>
, predict the next line using imports from the current file:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context including class names, function names, and sometimes code from other files:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | "type"/PlayerTypeEnum(Int32ul), |
Given snippet: <|code_start|> "selected_color"/Byte,
"selected_team_id"/Byte,
"resolved_team_id"/Byte,
"dat_crc"/Bytes(8),
"mp_game_version"/Byte,
"civ_id"/Int32ul,
"ai_type"/de_string,
"ai_civ_name_index"/Byte,
"ai_name"/de_string,
"name"/de_string,
"type"/PlayerTypeEnum(Int32ul),
"profile_id"/Int32ul,
Const(b"\x00\x00\x00\x00"),
"player_number"/Int32sl,
"hd_rm_elo"/If(lambda ctx: find_save_version(ctx) < 25.22, Int32ul),
"hd_dm_elo"/If(lambda ctx: find_save_version(ctx) < 25.22, Int32ul),
"prefer_random"/Flag,
"custom_ai"/Flag,
If(lambda ctx: find_save_version(ctx) >= 25.06, "handicap"/Bytes(8)),
)
de = "de"/Struct(
"build"/If(lambda ctx: find_save_version(ctx) >= 25.22, Int32ul),
"version"/Float32l,
"interval_version"/Int32ul,
"game_options_version"/Int32ul,
"dlc_count"/Int32ul,
"dlc_ids"/Array(lambda ctx: ctx.dlc_count, Int32ul),
"dataset_ref"/Int32ul,
Peek("difficulty_id"/Int32ul),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
which might include code, classes, or functions. Output only the next line. | DifficultyEnum("difficulty"/Int32ul), |
Here is a snippet: <|code_start|>
# pylint: disable=invalid-name, bad-continuation
de_string = Struct(
Const(b"\x60\x0A"),
"length"/Int16ul,
"value"/Bytes(lambda ctx: ctx.length)
)
separator = Const(b"\xa3_\x02\x00")
player = Struct(
"dlc_id"/Int32ul,
"color_id"/Int32sl,
"selected_color"/Byte,
"selected_team_id"/Byte,
"resolved_team_id"/Byte,
"dat_crc"/Bytes(8),
"mp_game_version"/Byte,
"civ_id"/Int32ul,
"ai_type"/de_string,
"ai_civ_name_index"/Byte,
"ai_name"/de_string,
"name"/de_string,
"type"/PlayerTypeEnum(Int32ul),
"profile_id"/Int32ul,
Const(b"\x00\x00\x00\x00"),
"player_number"/Int32sl,
<|code_end|>
. Write the next line using the current file imports:
from construct import (
Struct, Int32ul, Float32l, Array, Padding, Flag, If,
Byte, Int16ul, Bytes, Int32sl, Peek, Const, RepeatUntil,
Int64ul, Computed
)
from mgz.enums import VictoryEnum, ResourceLevelEnum, AgeEnum, PlayerTypeEnum, DifficultyEnum
from mgz.util import find_save_version
and context from other files:
# Path: mgz/enums.py
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# Path: mgz/util.py
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
, which may include functions, classes, or code. Output only the next line. | "hd_rm_elo"/If(lambda ctx: find_save_version(ctx) < 25.22, Int32ul), |
Given the following code snippet before the placeholder: <|code_start|> "scenario_filename"/String(32, padchar=b'\x00', trimdir='right', encoding='latin1'),
"player_num"/Byte,
"computer_num"/Byte,
Padding(2),
Peek("duration_int"/Int32ul),
TimeSecAdapter("duration"/Int32ul),
"cheats"/Flag,
"complete"/Flag,
Padding(2),
"db_checksum"/Int32ul,
"code_checksum"/Int32ul,
"version"/Float32l,
"map_size"/Byte,
"map_id"/Byte,
"population"/Int16ul,
Peek("victory_type_id"/Byte),
VictoryEnum("victory_type"/Byte),
Peek("starting_age_id"/Byte),
AgeEnum("starting_age"/Byte),
Peek("starting_resources_id"/Byte),
ResourceLevelEnum("starting_resources"/Byte),
"all_techs"/Flag,
"random_positions"/Flag,
RevealMapEnum("reveal_map"/Byte),
"is_deathmatch"/Flag,
"is_regicide"/Flag,
"starting_units"/Byte,
"lock_teams"/Flag,
"lock_speed"/Flag,
Padding(1),
<|code_end|>
, predict the next line using imports from the current file:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context including class names, function names, and sometimes code from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | Array(lambda ctx: ctx.player_num, achievements), |
Here is a snippet: <|code_start|> "exited"/Flag,
"player_id"/Byte,
"filename"/CString(encoding='latin1'),
Padding(lambda ctx: ctx._._.length - 23),
"checksum"/Int32ul
)
chapter = "chapter"/Struct(
"player_id"/Byte
)
build = "build"/Struct(
"selected"/Byte,
"player_id"/Int16ul,
"x"/Float32l,
"y"/Float32l,
"building_type"/Int32ul,
Padding(4),
"sprite_id"/Int32ul,
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul)
)
game = "game"/Struct(
"mode"/GameActionModeEnum("mode_id"/Byte),
"player_id"/Byte,
Padding(1),
"diplomacy"/If(this.mode == 'diplomacy', Struct(
"target_player_id"/Byte,
Padding(3),
"stance_float"/Float32l,
<|code_end|>
. Write the next line using the current file imports:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
, which may include functions, classes, or code. Output only the next line. | "stance"/DiplomacyStanceEnum("stance_id"/Byte), |
Predict the next line for this snippet: <|code_start|>)
stop = "stop"/Struct(
"selected"/Byte,
Array(lambda ctx: ctx.selected, "object_ids"/Int32ul)
)
stance = "stance"/Struct(
"selected"/Byte,
StanceEnum("stance_type"/Byte),
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul)
)
guard = "guard"/Struct(
"selected"/Byte,
Padding(2),
"guarded_unit_id"/Int32ul,
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul)
)
follow = "follow"/Struct(
"selected"/Byte,
Padding(2),
"followed_unit_id"/Int32ul,
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul)
)
formation = "formation"/Struct(
"selected"/Byte,
"player_id"/Int16ul,
<|code_end|>
with the help of current file imports:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
, which may contain function names, class names, or code. Output only the next line. | FormationEnum("formation_type"/Int32ul), |
Given the code snippet: <|code_start|> "selected"/Byte,
"player_id"/Int16ul,
FormationEnum("formation_type"/Int32ul),
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul)
)
save = "save"/Struct(
"exited"/Flag,
"player_id"/Byte,
"filename"/CString(encoding='latin1'),
Padding(lambda ctx: ctx._._.length - 23),
"checksum"/Int32ul
)
chapter = "chapter"/Struct(
"player_id"/Byte
)
build = "build"/Struct(
"selected"/Byte,
"player_id"/Int16ul,
"x"/Float32l,
"y"/Float32l,
"building_type"/Int32ul,
Padding(4),
"sprite_id"/Int32ul,
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul)
)
game = "game"/Struct(
<|code_end|>
, generate the next line using the imports in this file:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context (functions, classes, or occasionally code) from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | "mode"/GameActionModeEnum("mode_id"/Byte), |
Based on the snippet: <|code_start|> "selected"/Int16ul,
Padding(1),
"x"/Float32l, # -1 if none
"y"/Float32l, # -1 if none
Padding(4),
Padding(4), # 0xffffffff
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul)
)
"""
togglegate = "togglegate"/Struct(
Padding(3),
"gate_id"/Int32ul
)
flare = "flare"/Struct(
Padding(7),
Array(9, "player_ids"/Byte),
Padding(3),
"x"/Float32l,
"y"/Float32l,
"player_id"/Byte,
"player_number"/Byte,
Padding(2)
)
order = "order"/Struct(
"selected"/Byte,
Padding(2),
"building_id"/Int32sl, # -1 cancels production queue
<|code_end|>
, predict the immediate next line with the help of imports:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context (classes, functions, sometimes code) from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | OrderTypeEnum("order_type"/Byte), |
Next line prediction: <|code_start|> "x"/Float32l,
"y"/Float32l,
"next"/Peek(Bytes(4)),
"flags"/If(lambda ctx: check_flags(ctx.next), Bytes(4)),
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul)
)
tribute = "tribute"/Struct(
"player_id"/Byte,
"player_id_to"/Byte,
ResourceEnum("resource_type"/Byte),
"amount"/Float32l,
"fee"/Float32l
)
repair = "repair"/Struct(
"selected"/Byte,
Padding(2),
"repaired_id"/Int32ul,
"next"/Peek(Bytes(4)),
"flags"/If(lambda ctx: check_flags(ctx.next), Bytes(4)),
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul)
)
release = "release"/Struct(
"selected"/Int16ul,
Padding(1),
"x"/Float32l, # -1 if none
"y"/Float32l, # -1 if none
<|code_end|>
. Use current file imports:
(from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags)
and context including class names, function names, or small code snippets from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | ReleaseTypeEnum("release_type"/Byte), |
Predict the next line for this snippet: <|code_start|> "player_id"/Int16ul,
"unit_type"/Int16ul,
Padding(4)
)
research = "research"/Struct(
Padding(3),
"building_id"/Int32ul,
"player_id"/Int16ul,
"next"/Peek(
Struct(
Padding(6),
"check"/Int32sl
)
),
IfThenElse(lambda ctx: ctx.next.check == -1,
Embedded(Struct(
"selected"/Int16ul,
"technology_type"/Int32ul,
Array(lambda ctx: ctx.selected, "selected_ids"/Int32sl)
)),
Embedded(Struct(
"technology_type"/Int16ul,
Array(1, "selected_ids"/Int32sl)
))
)
)
sell = "sell"/Struct(
"player_id"/Byte,
<|code_end|>
with the help of current file imports:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
, which may contain function names, class names, or code. Output only the next line. | ResourceEnum("resource_type"/Byte), |
Using the snippet: <|code_start|> "waypoints"/Int16ul,
"x"/Float32l,
Array(9, "x_more"/Float32l),
"y"/Float32l,
Array(9, "y_more"/Float32l),
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul),
)
postgame = "achievements"/Struct(
Padding(3),
"scenario_filename"/String(32, padchar=b'\x00', trimdir='right', encoding='latin1'),
"player_num"/Byte,
"computer_num"/Byte,
Padding(2),
Peek("duration_int"/Int32ul),
TimeSecAdapter("duration"/Int32ul),
"cheats"/Flag,
"complete"/Flag,
Padding(2),
"db_checksum"/Int32ul,
"code_checksum"/Int32ul,
"version"/Float32l,
"map_size"/Byte,
"map_id"/Byte,
"population"/Int16ul,
Peek("victory_type_id"/Byte),
VictoryEnum("victory_type"/Byte),
Peek("starting_age_id"/Byte),
AgeEnum("starting_age"/Byte),
Peek("starting_resources_id"/Byte),
<|code_end|>
, determine the next line of code. You have imports:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context (class names, function names, or code) available:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | ResourceLevelEnum("starting_resources"/Byte), |
Predict the next line for this snippet: <|code_start|> "y"/Float32l,
Array(9, "y_more"/Float32l),
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul),
)
postgame = "achievements"/Struct(
Padding(3),
"scenario_filename"/String(32, padchar=b'\x00', trimdir='right', encoding='latin1'),
"player_num"/Byte,
"computer_num"/Byte,
Padding(2),
Peek("duration_int"/Int32ul),
TimeSecAdapter("duration"/Int32ul),
"cheats"/Flag,
"complete"/Flag,
Padding(2),
"db_checksum"/Int32ul,
"code_checksum"/Int32ul,
"version"/Float32l,
"map_size"/Byte,
"map_id"/Byte,
"population"/Int16ul,
Peek("victory_type_id"/Byte),
VictoryEnum("victory_type"/Byte),
Peek("starting_age_id"/Byte),
AgeEnum("starting_age"/Byte),
Peek("starting_resources_id"/Byte),
ResourceLevelEnum("starting_resources"/Byte),
"all_techs"/Flag,
"random_positions"/Flag,
<|code_end|>
with the help of current file imports:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
, which may contain function names, class names, or code. Output only the next line. | RevealMapEnum("reveal_map"/Byte), |
Given the code snippet: <|code_start|> Array(lambda ctx: ctx.selected, "selected_ids"/Int32sl)
)),
Embedded(Struct(
"technology_type"/Int16ul,
Array(1, "selected_ids"/Int32sl)
))
)
)
sell = "sell"/Struct(
"player_id"/Byte,
ResourceEnum("resource_type"/Byte),
"amount"/Byte,
Padding(4)
)
buy = "buy"/Struct(
"player_id"/Byte,
ResourceEnum("resource_type"/Byte),
"amount"/Byte,
Padding(4)
)
stop = "stop"/Struct(
"selected"/Byte,
Array(lambda ctx: ctx.selected, "object_ids"/Int32ul)
)
stance = "stance"/Struct(
"selected"/Byte,
<|code_end|>
, generate the next line using the imports in this file:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context (functions, classes, or occasionally code) from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | StanceEnum("stance_type"/Byte), |
Using the snippet: <|code_start|>de_attackmove = "de_attackmove"/Struct(
"selected"/Byte,
"waypoints"/Int16ul,
"x"/Float32l,
Array(9, "x_more"/Float32l),
"y"/Float32l,
Array(9, "y_more"/Float32l),
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul),
)
postgame = "achievements"/Struct(
Padding(3),
"scenario_filename"/String(32, padchar=b'\x00', trimdir='right', encoding='latin1'),
"player_num"/Byte,
"computer_num"/Byte,
Padding(2),
Peek("duration_int"/Int32ul),
TimeSecAdapter("duration"/Int32ul),
"cheats"/Flag,
"complete"/Flag,
Padding(2),
"db_checksum"/Int32ul,
"code_checksum"/Int32ul,
"version"/Float32l,
"map_size"/Byte,
"map_id"/Byte,
"population"/Int16ul,
Peek("victory_type_id"/Byte),
VictoryEnum("victory_type"/Byte),
Peek("starting_age_id"/Byte),
<|code_end|>
, determine the next line of code. You have imports:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context (class names, function names, or code) available:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | AgeEnum("starting_age"/Byte), |
Given the following code snippet before the placeholder: <|code_start|>First of each is popped off for consistency with other actions
"""
de_attackmove = "de_attackmove"/Struct(
"selected"/Byte,
"waypoints"/Int16ul,
"x"/Float32l,
Array(9, "x_more"/Float32l),
"y"/Float32l,
Array(9, "y_more"/Float32l),
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul),
)
postgame = "achievements"/Struct(
Padding(3),
"scenario_filename"/String(32, padchar=b'\x00', trimdir='right', encoding='latin1'),
"player_num"/Byte,
"computer_num"/Byte,
Padding(2),
Peek("duration_int"/Int32ul),
TimeSecAdapter("duration"/Int32ul),
"cheats"/Flag,
"complete"/Flag,
Padding(2),
"db_checksum"/Int32ul,
"code_checksum"/Int32ul,
"version"/Float32l,
"map_size"/Byte,
"map_id"/Byte,
"population"/Int16ul,
Peek("victory_type_id"/Byte),
<|code_end|>
, predict the next line using imports from the current file:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context including class names, function names, and sometimes code from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | VictoryEnum("victory_type"/Byte), |
Predict the next line after this snippet: <|code_start|> "unit_type"/Int16ul,
"queue_amount"/Byte,
Padding(1),
Array(lambda ctx: ctx.selected, "building_ids"/Int32ul)
)
"""DE Attack Move
It's almost the same as Patrol.
10 X-coordinates followed by 10 Y-coordinates
First of each is popped off for consistency with other actions
"""
de_attackmove = "de_attackmove"/Struct(
"selected"/Byte,
"waypoints"/Int16ul,
"x"/Float32l,
Array(9, "x_more"/Float32l),
"y"/Float32l,
Array(9, "y_more"/Float32l),
Array(lambda ctx: ctx.selected, "unit_ids"/Int32ul),
)
postgame = "achievements"/Struct(
Padding(3),
"scenario_filename"/String(32, padchar=b'\x00', trimdir='right', encoding='latin1'),
"player_num"/Byte,
"computer_num"/Byte,
Padding(2),
Peek("duration_int"/Int32ul),
<|code_end|>
using the current file's imports:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and any relevant context from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | TimeSecAdapter("duration"/Int32ul), |
Given the code snippet: <|code_start|>"""Actions."""
# pylint: disable=invalid-name, bad-continuation
# Not all actions are defined, not all actions are complete.
interact = "interact"/Struct(
"player_id"/Byte,
Const(b"\x00\x00"),
"target_id"/Int32ul,
"selected"/Int32ul,
"x"/Float32l,
"y"/Float32l,
"next"/Peek(Bytes(8)),
<|code_end|>
, generate the next line using the imports in this file:
from construct import (Array, Byte, Const, CString, Flag, Float32l, If,
Int16ul, Int32sl, Int32ul, Padding, Peek, String,
Struct, this, Bytes, Embedded, IfThenElse)
from mgz.body.achievements import achievements
from mgz.enums import (DiplomacyStanceEnum, FormationEnum, GameActionModeEnum,
OrderTypeEnum, ReleaseTypeEnum, ResourceEnum,
ResourceLevelEnum, RevealMapEnum, StanceEnum,
AgeEnum, VictoryEnum)
from mgz.util import TimeSecAdapter, check_flags
and context (functions, classes, or occasionally code) from other files:
# Path: mgz/body/achievements.py
#
# Path: mgz/enums.py
# def DiplomacyStanceEnum(ctx):
# """Diplomacy stance."""
# return Enum(
# ctx,
# allied=0,
# neutral=1,
# enemy=3
# )
#
# def FormationEnum(ctx):
# """Types of formations."""
# return Enum(
# ctx,
# line=2,
# box=4,
# staggered=7,
# flank=8
# )
#
# def GameActionModeEnum(ctx):
# """Game Action Modes."""
# return Enum(
# ctx,
# diplomacy=0,
# speed=1,
# instant_build=2,
# quick_build=4,
# allied_victory=5,
# cheat=6,
# unk0=9,
# spy=10,
# unk1=11,
# farm_queue=13,
# farm_unqueue=14,
# farm_autoqueue=16,
# fishtrap_queue=17,
# fishtrap_unqueue=18,
# fishtrap_autoqueue=19,
# default_stance=20,
# default=Pass
# )
#
# def OrderTypeEnum(ctx):
# """Types of Orders."""
# return Enum(
# ctx,
# packtreb=1,
# unpacktreb=2,
# garrison=5,
# default=Pass
# )
#
# def ReleaseTypeEnum(ctx):
# """Types of Releases."""
# return Enum(
# ctx,
# all=0,
# selected=3,
# sametype=4,
# notselected=5,
# inversetype=6,
# default=Pass
# )
#
# def ResourceEnum(ctx):
# """Resource Type Enumeration."""
# return Enum(
# ctx,
# food=0,
# wood=1,
# stone=2,
# gold=3,
# decay=12,
# fish=17,
# default=Pass # lots of resource types exist
# )
#
# def ResourceLevelEnum(ctx):
# """Resource Level Enumeration."""
# return Enum(
# ctx,
# none=-1,
# standard=0,
# low=1,
# medium=2,
# high=3,
# unknown1=4,
# unknown2=5,
# unknown3=6
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# def StanceEnum(ctx):
# """Types of stances."""
# return Enum(
# ctx,
# aggressive=0,
# defensive=1,
# stand_ground=2,
# passive=3
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# def VictoryEnum(ctx):
# """Victory Type Enumeration."""
# return Enum(
# ctx,
# standard=0,
# conquest=1,
# exploration=2,
# ruins=3,
# artifacts=4,
# discoveries=5,
# gold=6,
# time_limit=7,
# score=8,
# standard2=9,
# regicide=10,
# last_man=11
# )
#
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
#
# def check_flags(peek):
# """Check byte sequence for only flag bytes."""
# for i in peek:
# if i not in [0, 1]:
# return False
# return True
. Output only the next line. | "flags"/If(lambda ctx: check_flags(ctx.next), Bytes(8)), |
Next line prediction: <|code_start|> """
for team in teams:
if i not in team:
continue
for j in team:
if j in resigned:
return False
if len(resigned) > 0:
return True
return None
def get_civilization(header, index):
"""Get civilization ID."""
if header.save_version >= 20.06:
return header.de.players[index].civ_id
return header.initial.players[index + 1].attributes.civilization
def get_color(header, index):
"""Get color ID."""
if header.save_version >= 20.06:
return header.de.players[index].color_id
return header.initial.players[index + 1].attributes.player_color
def get_position(header, index):
"""Get position."""
if header.save_version >= 20.06:
for obj in header.initial.players[index + 1].objects:
<|code_end|>
. Use current file imports:
(from mgz.summary.objects import TC_IDS
from collections import defaultdict)
and context including class names, function names, or small code snippets from other files:
# Path: mgz/summary/objects.py
# TC_IDS = [71, 109, 141, 142]
. Output only the next line. | if obj.object_type in TC_IDS: |
Here is a snippet: <|code_start|>"""Lobby."""
# pylint: disable=invalid-name, bad-continuation
# Player inputs in the lobby, and several host settings.
lobby = "lobby"/Struct(
If(lambda ctx: find_save_version(ctx) >= 13.34, Padding(5)),
If(lambda ctx: find_save_version(ctx) >= 20.06, Padding(9)),
Array(8, "teams"/Byte), # team number selected by each player
If(lambda ctx: ctx._.version not in (Version.DE, Version.HD),
Padding(1),
),
Peek("reveal_map_id"/Int32ul),
RevealMapEnum("reveal_map"/Int32ul),
"fog_of_war"/Int32ul,
"map_size"/Int32ul,
"population_limit_encoded"/Int32ul,
"population_limit"/Computed(lambda ctx: ctx.population_limit_encoded * (25 if ctx._.version in [Version.USERPATCH14, Version.USERPATCH15] else 1)),
Embedded(If(lambda ctx: ctx._.version != Version.AOK,
Struct(
Peek("game_type_id"/Byte),
<|code_end|>
. Write the next line using the current file imports:
from construct import Array, Byte, Bytes, Flag, Int32ul, Padding, Peek, Struct, If, Computed, Embedded, Int32sl
from mgz.enums import GameTypeEnum, RevealMapEnum
from mgz.util import Version, find_save_version
and context from other files:
# Path: mgz/enums.py
# def GameTypeEnum(ctx):
# """Game Type Enumeration."""
# return Enum(
# ctx,
# RM=0,
# Regicide=1,
# DM=2,
# Scenario=3,
# Campaign=4,
# KingOfTheHill=5,
# WonderRace=6,
# DefendTheWonder=7,
# TurboRandom=8,
# CaptureTheRelic=10,
# SuddenDeath=11,
# BattleRoyale=12,
# EmpireWars=13
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# Path: mgz/util.py
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
, which may include functions, classes, or code. Output only the next line. | GameTypeEnum("game_type"/Byte), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.