Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class LoopTest(test_util.JaxoptTestCase): @parameterized.product(unroll=[True, False], jit=[True, False]) def test_while_loop(self, unroll, jit): def my_pow(x, y): def body_fun(val): return val * x def cond_fun(val): return True return loop.while_loop(cond_fun=cond_fun, body_fun=body_fun, init_val=1.0, maxiter=y, unroll=unroll, jit=jit) if not unroll and not jit: <|code_end|> , continue by predicting the next line. Consider current file imports: from absl.testing import absltest from absl.testing import parameterized from jaxopt import loop from jaxopt._src import test_util import jax import jax.numpy as jnp and context: # Path: jaxopt/loop.py # # Path: jaxopt/_src/test_util.py # def ridge_solver(X, y, lam): # def ridge_solver_jac(X, y, lam, eps=1e-4): # def lasso_skl(X, y, lam, tol=1e-5, fit_intercept=False): # def lasso_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, eps=1e-4): # def enet_skl(X, y, params_prox, tol=1e-5, fit_intercept=False): # def enet_skl_jac(X, y, params_prox, tol=1e-5, fit_intercept=False, eps=1e-5): # def multitask_lasso_skl(X, Y, lam, tol=1e-5): # def logreg_skl(X, y, lam, tol=1e-5, fit_intercept=False, # penalty="l2", multiclass=True): # def _reshape_coef(coef): # def logreg_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, penalty="l2", # multiclass=True, eps=1e-5): # def multiclass_linear_svm_skl(X, y, lam, tol=1e-5): # def multiclass_linear_svm_skl_jac(X, y, lam, tol=1e-5, eps=1e-5): # def lsq_linear_osp(X, y, bounds, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp(X, y, l, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp_jac(X, y, l, eps=1e-5, tol=1e-10, max_iter=None): # def check_states_have_same_types(state1, state2): # def _canonicalize_dtype(x64_enabled, dtype): # def canonicalize_dtype(dtype): # def _dtype(x): # def default_tolerance(): # def tolerance(dtype, tol=None): # def device_under_test(): # def _assert_numpy_allclose(a, b, atol=None, rtol=None, err_msg=''): # def is_sequence(x): # def assertArraysEqual(self, x, y, *, check_dtypes=True, err_msg=''): # def assertArraysAllClose(self, x, y, *, check_dtypes=True, atol=None, # rtol=None, err_msg=''): # def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True): # def assertAllClose(self, x, y, *, check_dtypes=True, atol=None, rtol=None, # canonicalize_dtypes=True, err_msg=''): # XX = jnp.dot(X.T, X) # I = jnp.eye(X.shape[1]) # class JaxoptTestCase(parameterized.TestCase): which might include code, classes, or functions. Output only the next line.
self.assertRaises(ValueError, my_pow, 3, 4)
Here is a snippet: <|code_start|> @parameterized.product(unroll=[True, False], jit=[True, False]) def test_while_loop(self, unroll, jit): def my_pow(x, y): def body_fun(val): return val * x def cond_fun(val): return True return loop.while_loop(cond_fun=cond_fun, body_fun=body_fun, init_val=1.0, maxiter=y, unroll=unroll, jit=jit) if not unroll and not jit: self.assertRaises(ValueError, my_pow, 3, 4) return self.assertEqual(my_pow(3, 4), pow(3, 4)) if unroll: # unroll=False uses lax.while_loop, whichs is not differentiable. self.assertEqual(jax.grad(my_pow)(3.0, 4), jax.grad(jnp.power)(3.0, 4)) @parameterized.product(unroll=[True, False], jit=[True, False]) def test_while_loop_stopped(self, unroll, jit): def my_pow(x, y, max_val): def body_fun(val): return val * x def cond_fun(val): return val < max_val return loop.while_loop(cond_fun=cond_fun, body_fun=body_fun, init_val=1.0, <|code_end|> . Write the next line using the current file imports: from absl.testing import absltest from absl.testing import parameterized from jaxopt import loop from jaxopt._src import test_util import jax import jax.numpy as jnp and context from other files: # Path: jaxopt/loop.py # # Path: jaxopt/_src/test_util.py # def ridge_solver(X, y, lam): # def ridge_solver_jac(X, y, lam, eps=1e-4): # def lasso_skl(X, y, lam, tol=1e-5, fit_intercept=False): # def lasso_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, eps=1e-4): # def enet_skl(X, y, params_prox, tol=1e-5, fit_intercept=False): # def enet_skl_jac(X, y, params_prox, tol=1e-5, fit_intercept=False, eps=1e-5): # def multitask_lasso_skl(X, Y, lam, tol=1e-5): # def logreg_skl(X, y, lam, tol=1e-5, fit_intercept=False, # penalty="l2", multiclass=True): # def _reshape_coef(coef): # def logreg_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, penalty="l2", # multiclass=True, eps=1e-5): # def multiclass_linear_svm_skl(X, y, lam, tol=1e-5): # def multiclass_linear_svm_skl_jac(X, y, lam, tol=1e-5, eps=1e-5): # def lsq_linear_osp(X, y, bounds, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp(X, y, l, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp_jac(X, y, l, eps=1e-5, tol=1e-10, max_iter=None): # def check_states_have_same_types(state1, state2): # def _canonicalize_dtype(x64_enabled, dtype): # def canonicalize_dtype(dtype): # def _dtype(x): # def default_tolerance(): # def tolerance(dtype, tol=None): # def device_under_test(): # def _assert_numpy_allclose(a, b, atol=None, rtol=None, err_msg=''): # def is_sequence(x): # def assertArraysEqual(self, x, y, *, check_dtypes=True, err_msg=''): # def assertArraysAllClose(self, x, y, *, check_dtypes=True, atol=None, # rtol=None, err_msg=''): # def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True): # def assertAllClose(self, x, y, *, check_dtypes=True, atol=None, rtol=None, # canonicalize_dtypes=True, err_msg=''): # XX = jnp.dot(X.T, X) # I = jnp.eye(X.shape[1]) # class JaxoptTestCase(parameterized.TestCase): , which may include functions, classes, or code. Output only the next line.
maxiter=y, unroll=unroll, jit=jit)
Given the following code snippet before the placeholder: <|code_start|> self.assertArraysAllClose(x, x3) # Tensor case. A = rng.randn(5, 3, 5, 3) A_mat = A.reshape(15, 15) b = rng.randn(5, 3) def matvec(x): return jnp.dot(A_mat, x.ravel()).reshape(5, 3) x = linear_solve.solve_lu(matvec, b) x2 = linear_solve.solve_gmres(matvec, b) x3 = linear_solve.solve_iterative_refinement(matvec, b) self.assertArraysAllClose(x, x2, atol=1e-4) self.assertArraysAllClose(x, x3, atol=1e-4) def test_solve_dense_psd(self): rng = onp.random.RandomState(0) A = rng.randn(5, 5) A = jnp.dot(A.T, A) b = rng.randn(5) matvec = lambda x: jnp.dot(A, x) x = linear_solve.solve_cholesky(matvec, b) x2 = jax.numpy.linalg.solve(A, b) self.assertArraysAllClose(x, x2, atol=1e-2) def test_solve_sparse(self): rng = onp.random.RandomState(0) # Matrix case. <|code_end|> , predict the next line using imports from the current file: from absl.testing import absltest from jaxopt._src import linear_solve as _linear_solve from jaxopt import linear_solve from jaxopt._src import test_util import jax import jax.numpy as jnp import numpy as onp and context including class names, function names, and sometimes code from other files: # Path: jaxopt/_src/linear_solve.py # def _materialize_array(matvec, shape, dtype=None): # def _make_ridge_matvec(matvec: Callable, ridge: float = 0.0): # def ridge_matvec(v: Any) -> Any: # def solve_lu(matvec: Callable, b: jnp.ndarray) -> jnp.ndarray: # def solve_cholesky(matvec: Callable, b: jnp.ndarray) -> jnp.ndarray: # def solve_cg(matvec: Callable, # b: Any, # ridge: Optional[float] = None, # init: Optional[Any] = None, # **kwargs) -> Any: # def _rmatvec(matvec, x): # def _normal_matvec(matvec, x): # def solve_normal_cg(matvec: Callable, # b: Any, # ridge: Optional[float] = None, # init: Optional[Any] = None, # **kwargs) -> Any: # def _matvec(x): # def solve_gmres(matvec: Callable, # b: Any, # ridge: Optional[float] = None, # init: Optional[Any] = None, # tol: float = 1e-5, # **kwargs) -> Any: # def solve_bicgstab(matvec: Callable, # b: Any, # ridge: Optional[float] = None, # init: Optional[Any] = None, # **kwargs) -> Any: # A = _materialize_array(matvec, b.shape, b.dtype) # A = _materialize_array(matvec, b.shape, b.dtype) # 4d array (tensor) # A = A.reshape(-1, b.shape[0] * b.shape[1]) # 2d array (matrix) # A = _materialize_array(matvec, b.shape) # A = _materialize_array(matvec, b.shape) # # Path: jaxopt/linear_solve.py # # Path: jaxopt/_src/test_util.py # def ridge_solver(X, y, lam): # def ridge_solver_jac(X, y, lam, eps=1e-4): # def lasso_skl(X, y, lam, tol=1e-5, fit_intercept=False): # def lasso_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, eps=1e-4): # def enet_skl(X, y, params_prox, tol=1e-5, fit_intercept=False): # def enet_skl_jac(X, y, params_prox, tol=1e-5, fit_intercept=False, eps=1e-5): # def multitask_lasso_skl(X, Y, lam, tol=1e-5): # def logreg_skl(X, y, lam, tol=1e-5, fit_intercept=False, # penalty="l2", multiclass=True): # def _reshape_coef(coef): # def logreg_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, penalty="l2", # multiclass=True, eps=1e-5): # def multiclass_linear_svm_skl(X, y, lam, tol=1e-5): # def multiclass_linear_svm_skl_jac(X, y, lam, tol=1e-5, eps=1e-5): # def lsq_linear_osp(X, y, bounds, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp(X, y, l, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp_jac(X, y, l, eps=1e-5, tol=1e-10, max_iter=None): # def check_states_have_same_types(state1, state2): # def _canonicalize_dtype(x64_enabled, dtype): # def canonicalize_dtype(dtype): # def _dtype(x): # def default_tolerance(): # def tolerance(dtype, tol=None): # def device_under_test(): # def _assert_numpy_allclose(a, b, atol=None, rtol=None, err_msg=''): # def is_sequence(x): # def assertArraysEqual(self, x, y, *, check_dtypes=True, err_msg=''): # def assertArraysAllClose(self, x, y, *, check_dtypes=True, atol=None, # rtol=None, err_msg=''): # def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True): # def assertAllClose(self, x, y, *, check_dtypes=True, atol=None, rtol=None, # canonicalize_dtypes=True, err_msg=''): # XX = jnp.dot(X.T, X) # I = jnp.eye(X.shape[1]) # class JaxoptTestCase(parameterized.TestCase): . Output only the next line.
A = rng.randn(5, 5)
Next line prediction: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class LinearSolveTest(test_util.JaxoptTestCase): def test_materialize_array(self): rng = onp.random.RandomState(0) # Matrix case. A = rng.randn(5, 5) matvec = lambda x: jnp.dot(A, x) A2 = _linear_solve._materialize_array(matvec, (5,)) self.assertArraysAllClose(A, A2) # Tensor case. A = rng.randn(5, 3, 5, 3) A_mat = A.reshape(15, 15) matvec = lambda x: jnp.dot(A_mat, x.ravel()).reshape(5, 3) A2 = _linear_solve._materialize_array(matvec, (5, 3)) self.assertArraysAllClose(A, A2, atol=1e-3) def test_rmatvec(self): <|code_end|> . Use current file imports: (from absl.testing import absltest from jaxopt._src import linear_solve as _linear_solve from jaxopt import linear_solve from jaxopt._src import test_util import jax import jax.numpy as jnp import numpy as onp) and context including class names, function names, or small code snippets from other files: # Path: jaxopt/_src/linear_solve.py # def _materialize_array(matvec, shape, dtype=None): # def _make_ridge_matvec(matvec: Callable, ridge: float = 0.0): # def ridge_matvec(v: Any) -> Any: # def solve_lu(matvec: Callable, b: jnp.ndarray) -> jnp.ndarray: # def solve_cholesky(matvec: Callable, b: jnp.ndarray) -> jnp.ndarray: # def solve_cg(matvec: Callable, # b: Any, # ridge: Optional[float] = None, # init: Optional[Any] = None, # **kwargs) -> Any: # def _rmatvec(matvec, x): # def _normal_matvec(matvec, x): # def solve_normal_cg(matvec: Callable, # b: Any, # ridge: Optional[float] = None, # init: Optional[Any] = None, # **kwargs) -> Any: # def _matvec(x): # def solve_gmres(matvec: Callable, # b: Any, # ridge: Optional[float] = None, # init: Optional[Any] = None, # tol: float = 1e-5, # **kwargs) -> Any: # def solve_bicgstab(matvec: Callable, # b: Any, # ridge: Optional[float] = None, # init: Optional[Any] = None, # **kwargs) -> Any: # A = _materialize_array(matvec, b.shape, b.dtype) # A = _materialize_array(matvec, b.shape, b.dtype) # 4d array (tensor) # A = A.reshape(-1, b.shape[0] * b.shape[1]) # 2d array (matrix) # A = _materialize_array(matvec, b.shape) # A = _materialize_array(matvec, b.shape) # # Path: jaxopt/linear_solve.py # # Path: jaxopt/_src/test_util.py # def ridge_solver(X, y, lam): # def ridge_solver_jac(X, y, lam, eps=1e-4): # def lasso_skl(X, y, lam, tol=1e-5, fit_intercept=False): # def lasso_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, eps=1e-4): # def enet_skl(X, y, params_prox, tol=1e-5, fit_intercept=False): # def enet_skl_jac(X, y, params_prox, tol=1e-5, fit_intercept=False, eps=1e-5): # def multitask_lasso_skl(X, Y, lam, tol=1e-5): # def logreg_skl(X, y, lam, tol=1e-5, fit_intercept=False, # penalty="l2", multiclass=True): # def _reshape_coef(coef): # def logreg_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, penalty="l2", # multiclass=True, eps=1e-5): # def multiclass_linear_svm_skl(X, y, lam, tol=1e-5): # def multiclass_linear_svm_skl_jac(X, y, lam, tol=1e-5, eps=1e-5): # def lsq_linear_osp(X, y, bounds, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp(X, y, l, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp_jac(X, y, l, eps=1e-5, tol=1e-10, max_iter=None): # def check_states_have_same_types(state1, state2): # def _canonicalize_dtype(x64_enabled, dtype): # def canonicalize_dtype(dtype): # def _dtype(x): # def default_tolerance(): # def tolerance(dtype, tol=None): # def device_under_test(): # def _assert_numpy_allclose(a, b, atol=None, rtol=None, err_msg=''): # def is_sequence(x): # def assertArraysEqual(self, x, y, *, check_dtypes=True, err_msg=''): # def assertArraysAllClose(self, x, y, *, check_dtypes=True, atol=None, # rtol=None, err_msg=''): # def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True): # def assertAllClose(self, x, y, *, check_dtypes=True, atol=None, rtol=None, # canonicalize_dtypes=True, err_msg=''): # XX = jnp.dot(X.T, X) # I = jnp.eye(X.shape[1]) # class JaxoptTestCase(parameterized.TestCase): . Output only the next line.
rng = onp.random.RandomState(0)
Continue the code snippet: <|code_start|> logit = 1.2 grad = jax.grad(loss_fun, argnums=1)(0, logit) self.assertArraysAllClose(grad, inv_link_fun(logit)) grad = jax.grad(loss_fun, argnums=1)(1, logit) self.assertArraysAllClose(grad, inv_link_fun(logit) - 1) # Check that vmap works as expected. logits = jnp.array([1.2, -0.3, 0.7]) labels = jnp.array([0, 0, 1]) losses = jax.vmap(loss_fun)(labels, logits) losses2 = jnp.array([loss_fun(labels[0], logits[0]), loss_fun(labels[1], logits[1]), loss_fun(labels[2], logits[2])]) self.assertArraysAllClose(losses, losses2) def test_binary_logistic_loss(self): self._test_binary_loss_function(loss.binary_logistic_loss, sigmoid) def _test_multiclass_loss_function(self, loss_fun, inv_link_fun): # Check that loss is zero when all weights goes to the correct label. loss_val = loss_fun(0, jnp.array([1e5, 0, 0])) self.assertEqual(loss_val, 0) # Check that gradient has the expected form. logits = jnp.array([1.2, 0.3, 2.3]) grad = jax.grad(loss_fun, argnums=1)(0, logits) self.assertArraysAllClose(grad, inv_link_fun(logits) - jnp.array([1, 0, 0])) # Check that vmap works as expected. logits = jnp.array([[1.3, 2.5], <|code_end|> . Use current file imports: from absl.testing import absltest from jax.nn import softmax from jax.scipy.special import expit as sigmoid from jaxopt import loss from jaxopt import projection from jaxopt._src import test_util import jax import jax.numpy as jnp and context (classes, functions, or code) from other files: # Path: jaxopt/loss.py # # Path: jaxopt/projection.py # # Path: jaxopt/_src/test_util.py # def ridge_solver(X, y, lam): # def ridge_solver_jac(X, y, lam, eps=1e-4): # def lasso_skl(X, y, lam, tol=1e-5, fit_intercept=False): # def lasso_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, eps=1e-4): # def enet_skl(X, y, params_prox, tol=1e-5, fit_intercept=False): # def enet_skl_jac(X, y, params_prox, tol=1e-5, fit_intercept=False, eps=1e-5): # def multitask_lasso_skl(X, Y, lam, tol=1e-5): # def logreg_skl(X, y, lam, tol=1e-5, fit_intercept=False, # penalty="l2", multiclass=True): # def _reshape_coef(coef): # def logreg_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, penalty="l2", # multiclass=True, eps=1e-5): # def multiclass_linear_svm_skl(X, y, lam, tol=1e-5): # def multiclass_linear_svm_skl_jac(X, y, lam, tol=1e-5, eps=1e-5): # def lsq_linear_osp(X, y, bounds, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp(X, y, l, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp_jac(X, y, l, eps=1e-5, tol=1e-10, max_iter=None): # def check_states_have_same_types(state1, state2): # def _canonicalize_dtype(x64_enabled, dtype): # def canonicalize_dtype(dtype): # def _dtype(x): # def default_tolerance(): # def tolerance(dtype, tol=None): # def device_under_test(): # def _assert_numpy_allclose(a, b, atol=None, rtol=None, err_msg=''): # def is_sequence(x): # def assertArraysEqual(self, x, y, *, check_dtypes=True, err_msg=''): # def assertArraysAllClose(self, x, y, *, check_dtypes=True, atol=None, # rtol=None, err_msg=''): # def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True): # def assertAllClose(self, x, y, *, check_dtypes=True, atol=None, rtol=None, # canonicalize_dtypes=True, err_msg=''): # XX = jnp.dot(X.T, X) # I = jnp.eye(X.shape[1]) # class JaxoptTestCase(parameterized.TestCase): . Output only the next line.
[1.7, -0.3],
Predict the next line for this snippet: <|code_start|> losses = jax.vmap(loss_fun)(labels, logits) losses2 = jnp.array([loss_fun(labels[0], logits[0]), loss_fun(labels[1], logits[1]), loss_fun(labels[2], logits[2])]) self.assertArraysAllClose(losses, losses2) def test_binary_logistic_loss(self): self._test_binary_loss_function(loss.binary_logistic_loss, sigmoid) def _test_multiclass_loss_function(self, loss_fun, inv_link_fun): # Check that loss is zero when all weights goes to the correct label. loss_val = loss_fun(0, jnp.array([1e5, 0, 0])) self.assertEqual(loss_val, 0) # Check that gradient has the expected form. logits = jnp.array([1.2, 0.3, 2.3]) grad = jax.grad(loss_fun, argnums=1)(0, logits) self.assertArraysAllClose(grad, inv_link_fun(logits) - jnp.array([1, 0, 0])) # Check that vmap works as expected. logits = jnp.array([[1.3, 2.5], [1.7, -0.3], [0.2, 1.2]]) labels = jnp.array([0, 0, 1]) losses = jax.vmap(loss_fun)(labels, logits) losses2 = jnp.array([loss_fun(labels[0], logits[0]), loss_fun(labels[1], logits[1]), loss_fun(labels[2], logits[2])]) self.assertArraysAllClose(losses, losses2) <|code_end|> with the help of current file imports: from absl.testing import absltest from jax.nn import softmax from jax.scipy.special import expit as sigmoid from jaxopt import loss from jaxopt import projection from jaxopt._src import test_util import jax import jax.numpy as jnp and context from other files: # Path: jaxopt/loss.py # # Path: jaxopt/projection.py # # Path: jaxopt/_src/test_util.py # def ridge_solver(X, y, lam): # def ridge_solver_jac(X, y, lam, eps=1e-4): # def lasso_skl(X, y, lam, tol=1e-5, fit_intercept=False): # def lasso_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, eps=1e-4): # def enet_skl(X, y, params_prox, tol=1e-5, fit_intercept=False): # def enet_skl_jac(X, y, params_prox, tol=1e-5, fit_intercept=False, eps=1e-5): # def multitask_lasso_skl(X, Y, lam, tol=1e-5): # def logreg_skl(X, y, lam, tol=1e-5, fit_intercept=False, # penalty="l2", multiclass=True): # def _reshape_coef(coef): # def logreg_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, penalty="l2", # multiclass=True, eps=1e-5): # def multiclass_linear_svm_skl(X, y, lam, tol=1e-5): # def multiclass_linear_svm_skl_jac(X, y, lam, tol=1e-5, eps=1e-5): # def lsq_linear_osp(X, y, bounds, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp(X, y, l, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp_jac(X, y, l, eps=1e-5, tol=1e-10, max_iter=None): # def check_states_have_same_types(state1, state2): # def _canonicalize_dtype(x64_enabled, dtype): # def canonicalize_dtype(dtype): # def _dtype(x): # def default_tolerance(): # def tolerance(dtype, tol=None): # def device_under_test(): # def _assert_numpy_allclose(a, b, atol=None, rtol=None, err_msg=''): # def is_sequence(x): # def assertArraysEqual(self, x, y, *, check_dtypes=True, err_msg=''): # def assertArraysAllClose(self, x, y, *, check_dtypes=True, atol=None, # rtol=None, err_msg=''): # def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True): # def assertAllClose(self, x, y, *, check_dtypes=True, atol=None, rtol=None, # canonicalize_dtypes=True, err_msg=''): # XX = jnp.dot(X.T, X) # I = jnp.eye(X.shape[1]) # class JaxoptTestCase(parameterized.TestCase): , which may contain function names, class names, or code. Output only the next line.
def test_multiclass_logistic_loss(self):
Using the snippet: <|code_start|> self.assertEqual(loss_val, 0) loss_val = loss_fun(1, 1e5) self.assertEqual(loss_val, 0) # Check that gradient has the expected form. logit = 1.2 grad = jax.grad(loss_fun, argnums=1)(0, logit) self.assertArraysAllClose(grad, inv_link_fun(logit)) grad = jax.grad(loss_fun, argnums=1)(1, logit) self.assertArraysAllClose(grad, inv_link_fun(logit) - 1) # Check that vmap works as expected. logits = jnp.array([1.2, -0.3, 0.7]) labels = jnp.array([0, 0, 1]) losses = jax.vmap(loss_fun)(labels, logits) losses2 = jnp.array([loss_fun(labels[0], logits[0]), loss_fun(labels[1], logits[1]), loss_fun(labels[2], logits[2])]) self.assertArraysAllClose(losses, losses2) def test_binary_logistic_loss(self): self._test_binary_loss_function(loss.binary_logistic_loss, sigmoid) def _test_multiclass_loss_function(self, loss_fun, inv_link_fun): # Check that loss is zero when all weights goes to the correct label. loss_val = loss_fun(0, jnp.array([1e5, 0, 0])) self.assertEqual(loss_val, 0) # Check that gradient has the expected form. logits = jnp.array([1.2, 0.3, 2.3]) <|code_end|> , determine the next line of code. You have imports: from absl.testing import absltest from jax.nn import softmax from jax.scipy.special import expit as sigmoid from jaxopt import loss from jaxopt import projection from jaxopt._src import test_util import jax import jax.numpy as jnp and context (class names, function names, or code) available: # Path: jaxopt/loss.py # # Path: jaxopt/projection.py # # Path: jaxopt/_src/test_util.py # def ridge_solver(X, y, lam): # def ridge_solver_jac(X, y, lam, eps=1e-4): # def lasso_skl(X, y, lam, tol=1e-5, fit_intercept=False): # def lasso_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, eps=1e-4): # def enet_skl(X, y, params_prox, tol=1e-5, fit_intercept=False): # def enet_skl_jac(X, y, params_prox, tol=1e-5, fit_intercept=False, eps=1e-5): # def multitask_lasso_skl(X, Y, lam, tol=1e-5): # def logreg_skl(X, y, lam, tol=1e-5, fit_intercept=False, # penalty="l2", multiclass=True): # def _reshape_coef(coef): # def logreg_skl_jac(X, y, lam, tol=1e-5, fit_intercept=False, penalty="l2", # multiclass=True, eps=1e-5): # def multiclass_linear_svm_skl(X, y, lam, tol=1e-5): # def multiclass_linear_svm_skl_jac(X, y, lam, tol=1e-5, eps=1e-5): # def lsq_linear_osp(X, y, bounds, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp(X, y, l, tol=1e-10, max_iter=None): # def lsq_linear_cube_osp_jac(X, y, l, eps=1e-5, tol=1e-10, max_iter=None): # def check_states_have_same_types(state1, state2): # def _canonicalize_dtype(x64_enabled, dtype): # def canonicalize_dtype(dtype): # def _dtype(x): # def default_tolerance(): # def tolerance(dtype, tol=None): # def device_under_test(): # def _assert_numpy_allclose(a, b, atol=None, rtol=None, err_msg=''): # def is_sequence(x): # def assertArraysEqual(self, x, y, *, check_dtypes=True, err_msg=''): # def assertArraysAllClose(self, x, y, *, check_dtypes=True, atol=None, # rtol=None, err_msg=''): # def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True): # def assertAllClose(self, x, y, *, check_dtypes=True, atol=None, rtol=None, # canonicalize_dtypes=True, err_msg=''): # XX = jnp.dot(X.T, X) # I = jnp.eye(X.shape[1]) # class JaxoptTestCase(parameterized.TestCase): . Output only the next line.
grad = jax.grad(loss_fun, argnums=1)(0, logits)
Based on the snippet: <|code_start|> class CacheManager(object): def __init__(self, image, config): self.image = image self.config = config def get_dir(self, size): if size == 'full': return self.image.orig_dir return os.path.join(self.config['CACHE_DIR'], self.image.album, str(size)) def get_path(self, size): return os.path.join(self.get_dir(size), self.image.filename) def get(self, size): if size not in self.config['ALLOWED_SIZES']: raise UnsupportedImageSizeError if size == 'full': return (self.image.orig_dir, self.image.filename) if not os.path.exists(self.get_path(size)): <|code_end|> , predict the immediate next line with the help of imports: from showoff.lib import ExifManager from showoff.lib.exceptions import UnsupportedImageSizeError from PIL import Image import os and context (classes, functions, sometimes code) from other files: # Path: showoff/lib/exif_manager.py # class ExifManager(object): # def __init__(self, image): # self.image = image # self.supported_exiftags = [ # "ImageWidth", # "ImageLength", # "BitsPerSample", # "Compression", # "PhotometricInterpretation", # "ImageDescription", # "Make", # "Model", # "StripOffsets", # "Orientation", # "SamplesPerPixel", # "RowsPerStrip", # "StripByteConunts", # "XResolution", # "YResolution", # "PlanarConfiguration", # "ResolutionUnit", # "TransferFunction", # "Software", # "DateTime", # "Artist", # "WhitePoint", # "PrimaryChromaticities", # "JpegIFOffset", # "JpegIFByteCount", # "YCbCrCoefficients", # "YCbCrSubSampling", # "YCbCrPositioning", # "ReferenceBlackWhite", # "RelatedImageFileFormat", # "RelatedImageLength", # "RelatedImageWidth", # "CFARepeatPatternDim", # "CFAPattern", # "BatteryLevel", # "Copyright", # "ExposureTime", # "FNumber", # "ExifOffset", # "InterColorProfile", # "ExposureProgram", # "SpectralSensitivity", # "GPSInfo", # "ISOSpeedRatings", # "OECF", # "Interlace", # "TimeZoneOffset", # "SelfTimerMode", # "ExifVersion", # "DateTimeOriginal", # "DateTimeDigitized", # "ComponentsConfiguration", # "CompressedBitsPerPixel", # "CompressedBitsPerPixel", # "ShutterSpeedValue", # "ApertureValue", # "BrightnessValue", # "ExposureBiasValue", # "MaxApertureValue", # "SubjectDistance", # "MeteringMode", # "LightSource", # "Flash", # "FocalLength", # "FlashEnergy", # "SpatialFrequencyResponse", # "Noise", # "ImageNumber", # "SecurityClassification", # "ImageHistory", # "SubjectLocation", # "ExposureIndex", # "TIFF/EPStandardID", # "UserComment", # "SubsecTime", # "SubsecTimeOriginal", # "SubsecTimeDigitized", # "FlashPixVersion", # "ColorSpace", # "ExifImageWidth", # "ExifImageHeight", # "RelatedSoundFile", # "ExifInteroperabilityOffset", # "FlashEnergy", # "SpatialFrequencyResponse", # "FocalPlaneXResolution", # "FocalPlaneYResolution", # "FocalPlaneResolutionUnit", # "SubjectLocation", # "ExposureIndex", # "SensingMethod", # "FileSource", # "SceneType", # "CFAPattern" # ] # # def update(self): # if not os.path.exists(self.image.exif_dir): # os.mkdir(self.image.exif_dir) # img = Image.open(self.image.orig_file) # if not hasattr(img, '_getexif'): # return None # exif = img._getexif() # # if exif is None: # return # # ret = {} # if exif: # for tag, value in exif.items(): # decoded = ExifTags.TAGS.get(tag, tag) # try: # ret[decoded] = str(value).encode('utf-8') # except: # pass # # with open(self.image.exif_file, 'w') as f: # for key in self.supported_exiftags: # if key in ret: # f.write("%s|%s\n" % (key, ret[key])) # return ret # # def get_exif(self): # exif = {} # # if os.path.exists(self.image.exif_file): # with open(self.image.exif_file) as f: # for line in f.readlines(): # line_arr = line.split('|') # if len(line_arr) > 1: # exif[line_arr[0]] = line_arr[1] # else: # exif = self.update() # # return exif # # def get_exif_tag_value(self, exif, tag): # for tag, value in exif.items(): # decoded = ExifTags.TAGS.get(tag, tag) # if decoded == tag: # return value # return None # # def get_exif_datetime(self): # img = Image.open(self.image.orig_file) # if not hasattr(img, "_getexif"): # return None # exif = img._getexif() # datetime = self.get_exif_tag_value(exif, 'DateTime') # return datetime # # Path: showoff/lib/exceptions.py # class UnsupportedImageSizeError(Error): # pass . Output only the next line.
self.update(size)
Given the following code snippet before the placeholder: <|code_start|> class CacheManager(object): def __init__(self, image, config): self.image = image self.config = config def get_dir(self, size): if size == 'full': return self.image.orig_dir return os.path.join(self.config['CACHE_DIR'], self.image.album, str(size)) def get_path(self, size): return os.path.join(self.get_dir(size), self.image.filename) <|code_end|> , predict the next line using imports from the current file: from showoff.lib import ExifManager from showoff.lib.exceptions import UnsupportedImageSizeError from PIL import Image import os and context including class names, function names, and sometimes code from other files: # Path: showoff/lib/exif_manager.py # class ExifManager(object): # def __init__(self, image): # self.image = image # self.supported_exiftags = [ # "ImageWidth", # "ImageLength", # "BitsPerSample", # "Compression", # "PhotometricInterpretation", # "ImageDescription", # "Make", # "Model", # "StripOffsets", # "Orientation", # "SamplesPerPixel", # "RowsPerStrip", # "StripByteConunts", # "XResolution", # "YResolution", # "PlanarConfiguration", # "ResolutionUnit", # "TransferFunction", # "Software", # "DateTime", # "Artist", # "WhitePoint", # "PrimaryChromaticities", # "JpegIFOffset", # "JpegIFByteCount", # "YCbCrCoefficients", # "YCbCrSubSampling", # "YCbCrPositioning", # "ReferenceBlackWhite", # "RelatedImageFileFormat", # "RelatedImageLength", # "RelatedImageWidth", # "CFARepeatPatternDim", # "CFAPattern", # "BatteryLevel", # "Copyright", # "ExposureTime", # "FNumber", # "ExifOffset", # "InterColorProfile", # "ExposureProgram", # "SpectralSensitivity", # "GPSInfo", # "ISOSpeedRatings", # "OECF", # "Interlace", # "TimeZoneOffset", # "SelfTimerMode", # "ExifVersion", # "DateTimeOriginal", # "DateTimeDigitized", # "ComponentsConfiguration", # "CompressedBitsPerPixel", # "CompressedBitsPerPixel", # "ShutterSpeedValue", # "ApertureValue", # "BrightnessValue", # "ExposureBiasValue", # "MaxApertureValue", # "SubjectDistance", # "MeteringMode", # "LightSource", # "Flash", # "FocalLength", # "FlashEnergy", # "SpatialFrequencyResponse", # "Noise", # "ImageNumber", # "SecurityClassification", # "ImageHistory", # "SubjectLocation", # "ExposureIndex", # "TIFF/EPStandardID", # "UserComment", # "SubsecTime", # "SubsecTimeOriginal", # "SubsecTimeDigitized", # "FlashPixVersion", # "ColorSpace", # "ExifImageWidth", # "ExifImageHeight", # "RelatedSoundFile", # "ExifInteroperabilityOffset", # "FlashEnergy", # "SpatialFrequencyResponse", # "FocalPlaneXResolution", # "FocalPlaneYResolution", # "FocalPlaneResolutionUnit", # "SubjectLocation", # "ExposureIndex", # "SensingMethod", # "FileSource", # "SceneType", # "CFAPattern" # ] # # def update(self): # if not os.path.exists(self.image.exif_dir): # os.mkdir(self.image.exif_dir) # img = Image.open(self.image.orig_file) # if not hasattr(img, '_getexif'): # return None # exif = img._getexif() # # if exif is None: # return # # ret = {} # if exif: # for tag, value in exif.items(): # decoded = ExifTags.TAGS.get(tag, tag) # try: # ret[decoded] = str(value).encode('utf-8') # except: # pass # # with open(self.image.exif_file, 'w') as f: # for key in self.supported_exiftags: # if key in ret: # f.write("%s|%s\n" % (key, ret[key])) # return ret # # def get_exif(self): # exif = {} # # if os.path.exists(self.image.exif_file): # with open(self.image.exif_file) as f: # for line in f.readlines(): # line_arr = line.split('|') # if len(line_arr) > 1: # exif[line_arr[0]] = line_arr[1] # else: # exif = self.update() # # return exif # # def get_exif_tag_value(self, exif, tag): # for tag, value in exif.items(): # decoded = ExifTags.TAGS.get(tag, tag) # if decoded == tag: # return value # return None # # def get_exif_datetime(self): # img = Image.open(self.image.orig_file) # if not hasattr(img, "_getexif"): # return None # exif = img._getexif() # datetime = self.get_exif_tag_value(exif, 'DateTime') # return datetime # # Path: showoff/lib/exceptions.py # class UnsupportedImageSizeError(Error): # pass . Output only the next line.
def get(self, size):
Given the code snippet: <|code_start|>#!/usr/bin/env python app = Flask(__name__) app.config.from_pyfile('config.py') app.config.from_envvar('SHOWOFF_FRONTEND_CONFIG', silent=True) app.register_blueprint(frontend, url_prefix=app.config['FRONTEND_PREFIX']) if __name__ == '__main__': <|code_end|> , generate the next line using the imports in this file: from flask import Flask from showoff.frontend.controllers import frontend and context (functions, classes, or occasionally code) from other files: # Path: showoff/frontend/controllers.py # def login(album): # def static_files(filename): # def get_image(album, filename, size="full"): # def image_page(album, filename, template='image'): # def list_album(album, page, template='list'): # def show_nonpaginated(album, template='grid_full'): # def show_slideshow(album, page): # def show_album(album): # def show_index(): . Output only the next line.
app.run(host=app.config['FRONTEND_HOST'], port=app.config['FRONTEND_PORT'])
Given snippet: <|code_start|> class ImageModifier(object): def __init__(self, image): self.image = image self.cache = CacheManager(image) def rotate(self, steps=1): if steps < 1: steps = 1 if steps > 3: steps = 3 img = Image.open(self.image.get_fullsize_path()) <|code_end|> , continue by predicting the next line. Consider current file imports: from showoff.lib import CacheManager from PIL import ExifTags, Image import os and context: # Path: showoff/lib/cache_manager.py # class CacheManager(object): # def __init__(self, image, config): # self.image = image # self.config = config # # def get_dir(self, size): # if size == 'full': # return self.image.orig_dir # # return os.path.join(self.config['CACHE_DIR'], # self.image.album, # str(size)) # # def get_path(self, size): # return os.path.join(self.get_dir(size), self.image.filename) # # def get(self, size): # if size not in self.config['ALLOWED_SIZES']: # raise UnsupportedImageSizeError # # if size == 'full': # return (self.image.orig_dir, self.image.filename) # # if not os.path.exists(self.get_path(size)): # self.update(size) # # return (self.get_dir(size), self.image.filename) # # def remove_cached_file(self, size): # fpath = self.get_path(size) # if os.path.exists(fpath): # os.unlink(fpath) # # def clear(self, size=None): # if size is None: # for size in self.config['ALLOWED_SIZES']: # self.remove_cached_file(size) # else: # self.remove_cached_file(size) # # def update(self, size): # fpath = self.get_path(size) # # if not os.path.exists(fpath): # adir = os.path.join(self.config['CACHE_DIR'], # self.image.album) # if not os.path.exists(adir): # os.mkdir(adir) # # tdir = os.path.join(adir, str(int(size))) # if not os.path.exists(tdir): # os.mkdir(tdir) # # if not os.path.exists(self.image.exif_file): # exif = ExifManager(self.image) # exif.update() # # img = Image.open(self.image.get_fullsize_path()) # img.thumbnail((int(size), int(size)), Image.ANTIALIAS) # img.save(self.get_path(size), 'JPEG') which might include code, classes, or functions. Output only the next line.
img = img.rotate(steps * -90)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python app = Flask(__name__) app.config.from_pyfile('config.py') app.config.from_envvar('SHOWOFF_ADMIN_CONFIG', silent=True) app.register_blueprint(admin, url_prefix=app.config['ADMIN_PREFIX']) if __name__ == '__main__': <|code_end|> , predict the next line using imports from the current file: from flask import Flask from showoff.admin.controllers import admin and context including class names, function names, and sometimes code from other files: # Path: showoff/admin/controllers.py # def render_themed(template, **options): # def static_files(filename): # def show_image(album, filename, size=None): # def show_image_full(album, filename): # def image_page(album, filename): # def rotate_url(): # def list_album(album, page, template='grid'): # def show_album(album): # def show_index(): # def image_rotate(album, filename, steps=1): # def exif_rotate_image(album, filename): # def toggle_publish_image(album, filename): # def add_image_to_show(album, filename): # def remove_image_from_show(album, filename): # def sort_show_by_exifdate(album): # def sort_show_by_filename(album): # def show_edit_users(album): # def add_all_images_to_show(album): # def show_change_setting(album, setting, value): # def show_change_password(album): # def show_remove_user(album, username): # def goback(is_ok): . Output only the next line.
app.run(host=app.config['ADMIN_HOST'], port=app.config['ADMIN_PORT'])
Predict the next line for this snippet: <|code_start|> # Set up its initial separation and energy scales (from here on, # the configurational binding entropies of all pairs of tethers # are fixed, so its much quicker to change binding energies) # # It doesn't matter what beta_DeltaG0 is set to at this stage, other # than it's something different from infinity for all the pairs # of strands that may bind during this run # print "Initializing configurational entropy factors..." plates.beta_DeltaG0['alpha', 'alpha_p'] = -10 plates.beta_DeltaG0['alpha', 'beta_p'] = -5 plates.beta_DeltaG0['beta', 'alpha_p'] = -5 plates.separation = L plates.update() print "Done" # For a given difference between strong and weak bond binding strength, # map out bonding probabilities def do_it(beta_DeltaDeltaG): print "Looking at beta_DeltaDeltaG = %g" % beta_DeltaDeltaG with open('competing_deltaDelta%g.txt' % beta_DeltaDeltaG, 'w') as f: for beta_DeltaG0Strong in xrange(0, -51, -1): print " beta_DeltaG0Strong = %g" % beta_DeltaG0Strong beta_DeltaG0Weak = beta_DeltaG0Strong + beta_DeltaDeltaG plates.beta_DeltaG0['alpha', 'alpha_p'] = beta_DeltaG0Strong <|code_end|> with the help of current file imports: import numpy as np import subprocess import scipy.interpolate import dnacc from math import pi, sqrt from dnacc.units import nm and context from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): , which may contain function names, class names, or code. Output only the next line.
plates.beta_DeltaG0['alpha', 'beta_p'] = beta_DeltaG0Weak
Given the code snippet: <|code_start|># Copyright 2012 Patrick Varilly, Stefano Angioletti-Uberti # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. num_tethers = 200 box_L = 200 * nm plates = dnacc.Plates(Lx=box_L, Ly=box_L, periodic=True) <|code_end|> , generate the next line using the imports in this file: import dnacc import numpy as np from dnacc.units import nm and context (functions, classes, or occasionally code) from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): . Output only the next line.
for (x, y) in np.random.random_sample((num_tethers / 2, 2)):
Predict the next line after this snippet: <|code_start|> with open('bad-plates-A_B-T%.1f-G%.1f.txt' % (T, beta_DeltaG0), 'w') as f: f.write('# h (nm)\t' 'F_rep (kT/nm^2)\t' 'F_att (kT/nm^2)\t' 'F_plate (kT/nm^2)\n') for h, betaF, betaFRep in zip(hArr, badBetaFPlate, betaFRepPlate): betaFAtt = betaF - betaFRep f.write('%g\t%g\t%g\t%g\n' % (h / nm, betaFRep / (1 / nm ** 2), betaFAtt / (1 / nm ** 2), betaF / (1 / nm ** 2))) # Now for sphere-sphere potentials betaFSpheres = dnacc.calc_spheres_potential(hArr, betaFPlate, R) betaFRepSpheres = dnacc.calc_spheres_potential(hArr, betaFRepPlate, R) with open('spheres-A_B-T%.1f-G%.1f.txt' % (T, beta_DeltaG0), 'w') as f: f.write('# h (nm)\t' 'F_rep (kT)\t' 'F_att (kT)\t' 'F_spheres (kT)\n') for h, betaF, betaFRep in zip(hArr, betaFSpheres, betaFRepSpheres): betaFAtt = betaF - betaFRep f.write('%g\t%g\t%g\t%g\n' % (h / nm, betaFRep, betaFAtt, betaF)) # Same, but with the Poisson approximation badBetaFSpheres = dnacc.calc_spheres_potential(hArr, badBetaFPlate, R) <|code_end|> using the current file's imports: import numpy as np import subprocess import scipy.interpolate import dnacc from math import pi from dnacc.units import nm and any relevant context from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): . Output only the next line.
with open('bad-spheres-A_B-T%.1f-G%.1f.txt' %
Continue the code snippet: <|code_start|> sigma = platesXXP.tether_types[0]['sigma'] with open('fig2c.txt', 'w') as f: f.write('# h/L (L = 20 nm)\t' 'F/A (kT / L^2)\n') beta_Delta = 5 for beta_DeltaG0strong in xrange(-40, 7): f.write('# betaDeltaG0strong = %g\n' % beta_DeltaG0strong) set_competing_interactions(platesXXP, beta_DeltaG0strong, beta_DeltaG0strong + beta_Delta) platesXXP.at(2.1 * L).set_reference_now() VArr = [platesXXP.at(h).free_energy_density for h in hArr] for h, V in zip(hArr, VArr): f.write('%g\t%g\n' % (h / L, V / (1 / L ** 2))) f.write('\n\n') subprocess.call(['gnuplot', 'plot_fig2c.gp']) # Figure 3a # ========= def figure3a(): with open('fig3a.txt', 'w') as f: f.write('# DeltaG0strong (kT)\t' <|code_end|> . Use current file imports: import numpy as np import subprocess import operator import dnacc from math import sqrt from dnacc.units import nm and context (classes, functions, or code) from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): . Output only the next line.
'F_min_XXp/A (kT / L^2)\t' 'F_min_XX/A (kT / L^2)\n')
Next line prediction: <|code_start|># This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. num_tethers = 200 box_L = 200 * nm plates = dnacc.Plates(Lx=box_L, Ly=box_L, periodic=True) for (x, y) in np.random.random_sample((num_tethers / 2, 2)): plates.add_tether(plate='lower', sticky_end='alpha', L=20 * nm, pos=(x * box_L, y * box_L)) for (x, y) in np.random.random_sample((num_tethers / 2, 2)): plates.add_tether(plate='upper', sticky_end='alphap', L=20 * nm, pos=(x * box_L, y * box_L)) plates.beta_DeltaG0['alpha', 'alphap'] = 0.0 plates.at(20 * nm) print("# Delta G_0 (kT) Bonds Formed / Max possible") <|code_end|> . Use current file imports: (import dnacc import numpy as np from dnacc.units import nm) and context including class names, function names, or small code snippets from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): . Output only the next line.
for dg in np.linspace(-20.0, 0.0, 21):
Predict the next line for this snippet: <|code_start|># but the fixed-point iteration was performed to a looser tolerance (hence # the slight numerical differences) # Basic plate properties L = 20 * nm S = 1.0 sigma = 1 / (S * L) ** 2 num_tethers = 400 boxL = sqrt(num_tethers / sigma) def setup_explicit(): global explicit_plates # Generate plate grafting points #grafting_pts = boxL * np.random.random_sample( (num_tethers,2) ) grafting_pts = np.loadtxt('plate.dat', skiprows=4) # Set up system explicit_plates = dnacc.Plates(boxL, boxL, periodic=True) explicit_plates.set_tether_prototype(L=L) cur_plate, next_plate = 'lower', 'upper' cur_end, next_end = 'alpha', 'alpha_p' for pt in grafting_pts: explicit_plates.add_tether(plate=cur_plate, <|code_end|> with the help of current file imports: import numpy as np import subprocess import scipy.interpolate import dnacc from math import pi, sqrt from dnacc.units import nm and context from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): , which may contain function names, class names, or code. Output only the next line.
sticky_end=cur_end,
Predict the next line for this snippet: <|code_start|> def setup_explicit(sphere_list, patches): # Set up system spheres = dnacc.Spheres() spheres.set_tether_prototype(L=L) for name, props in sphere_list.iteritems(): spheres.add_sphere(name, props['centre'], props['radius']) # Generate grafting points for patches centered at 0.0 ids = list() for patch_props in patches: patch_ids = dnacc.patches.add_circular_patch_to_sphere( spheres, **patch_props) ids.extend(patch_ids) # Record original positions for i in ids: spheres.tethers[i]['orig_pos'] = np.array(spheres.tethers[i]['pos']) return spheres # Main module # =========== <|code_end|> with the help of current file imports: import numpy as np import subprocess import scipy.interpolate import dnacc from math import pi, sqrt from dnacc.units import nm and context from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): , which may contain function names, class names, or code. Output only the next line.
np.random.seed(1) # To make the following plots deterministic
Next line prediction: <|code_start|> for tether in plates.tethers: if tether['plate'] == 'upper': tether['pos'] = tether['orig_pos'] + np.array((d, 0.0)) plates.update() return plates.free_energy def run(L, sigma, beta_DeltaG0, patch_radii, skip=False, plates=None): if plates is None: plates = setup_explicit(L, sigma, patch_radii) max_patch_radii = max(patch_radii.itervalues()) if skip: return plates filename = ("patch_results_L%gnm_S%g_dg%gkT_upperR%gnm_lowerR%gnm.dat" % (L / nm, sqrt(1 / sigma) / L, beta_DeltaG0, patch_radii['upper'] / nm, patch_radii['lower'] / nm)) print "Working on %s" % filename print "Total number of tethers: %d" % len(plates.tethers) with open(filename, 'w') as f: f.write("# d (nm)\t" "h (nm)\t" "F (kT)\n") f.write("# Total number of tethers: %d\n" % len(plates.tethers)) for d in np.linspace(-2 * max_patch_radii - 2 * L, +2 * max_patch_radii + 2 * L, 40): for h in np.linspace(0.05 * L, 2 * L, 20): <|code_end|> . Use current file imports: (import numpy as np import subprocess import scipy.interpolate import dnacc from math import pi, sqrt from dnacc.units import nm) and context including class names, function names, or small code snippets from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): . Output only the next line.
f.write("%g\t%g\t%g\n" %
Here is a snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #!/usr/bin/env python try: os.mkdir('results') except Exception: pass # ======================================================================== # Parameters # ======================================================================== # Everything that Bortolo has calculated uses Kuhn lengths as the unit # of length l_Kuhn = 5 * nm # Calculate a pair potential for Rogers & Crocker-style A and B spheres R = 550 * nm N_A_in_A = 4800.0 N_B_in_B = 4200.0 N_A_in_AB = 2400.0 <|code_end|> . Write the next line using the current file imports: import dnacc import numpy as np import subprocess import os from dnacc import units, physics from dnacc.units import nm from dnacc.utils import pbc_delta from ssDNA_stats import * from math import pi, sqrt, acos, cos, atan2, log, exp from contextlib import contextmanager and context from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): # # Path: dnacc/physics.py # _GSL_CONST_MKSA_SPEED_OF_LIGHT = 2.99792458e8 # m / s # _GSL_CONST_MKSA_VACUUM_PERMITTIVITY = 8.854187817e-12 # A^2 s^4 / kg m^3 # _GSL_CONST_MKSA_VACUUM_PERMEABILITY = 1.25663706144e-6 # kg m / A^2 s^2 # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_BOLTZMANN = 1.3806504e-23 # kg m^2 / K s^2 # _GSL_CONST_MKSA_MOLAR_GAS = 8.314472e0 # kg m^2 / K mol s^2 # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_MKSA_ELECTRON_VOLT = 1.602176487e-19 # kg m^2 / s^2 # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_MASS_ELECTRON = 9.10938188e-31 # kg # _GSL_CONST_MKSA_BOHR_RADIUS = 5.291772083e-11 # m # _GSL_CONST_MKSA_DEBYE = 3.33564095198e-30 # A s^2 / m^2 # N_A = _GSL_CONST_NUM_AVOGADRO # R = _GSL_CONST_MKSA_MOLAR_GAS * units.J / (units.K * units.mol) # D = _GSL_CONST_MKSA_DEBYE * units.C * units.m # # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): # # Path: dnacc/utils.py # def pbc_delta(x1, x2, Lx): # """Find x1 - x2 in a periodic 1D interval of size Lx.""" # dx = (x1 - x2) % Lx # if dx > 0.5 * Lx: # dx -= Lx # return dx , which may include functions, classes, or code. Output only the next line.
N_B_in_AB = 3500.0
Here is a snippet: <|code_start|> # The rolling walker has this radius R = 500.0 * nm # Look at various overall binding energies ts = plates.tether_types def do_it(beta_DeltaG0Mid): print 'Working on beta_DeltaG0Mid = %g' % beta_DeltaG0Mid # and various energy gaps for beta_Delta in xrange(0, 10): plates.beta_DeltaG0['alpha', 'beta1'] = \ beta_DeltaG0Mid - 0.5 * beta_Delta plates.beta_DeltaG0['alpha', 'beta2'] = \ beta_DeltaG0Mid + 0.5 * beta_Delta # and various total strand coverage for S in 0.75, 0.25: sigma = 1 / (S * L) ** 2 ts[ALPHA]['sigma'] = sigma * 0.5 with open('walk-S%0.2f-G0Mid%.1f-delta%.1f.dat' % (S, beta_DeltaG0Mid, beta_Delta), 'w') as f: f.write('c\t' 'F_rep (kT)\n') <|code_end|> . Write the next line using the current file imports: import numpy as np import subprocess import operator import dnacc from dnacc.units import nm and context from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): , which may include functions, classes, or code. Output only the next line.
offset = 0
Next line prediction: <|code_start|> plates.update() f.write('%g\t%g\t%g\n' % (beta_DeltaG0a, plates.sigma_bound[ALPHA, ALPHA_P] / (2 * sigma), (plates.sigma_bound[ALPHA, BETA_P] + plates.sigma_bound[BETA, ALPHA_P]) / (2 * sigma))) f.write('\n\n') subprocess.call(['gnuplot', 'plot_fig5a.gp']) # Figure 5b # ========= def figure5b(): reset_plates(plates) S = 0.75 sigma = 0.5 / (S * L) ** 2 ts = plates.tether_types ts[ALPHA]['L'] = ts[ALPHA_P]['L'] = 0.3 * L ts[BETA]['L'] = ts[BETA_P]['L'] = 1.7 * L for t in plates.tether_types: t['sigma'] = sigma with open('fig5b.txt', 'w') as f: f.write('# h/L (L = 20 nm)\t' 'F (kT / L^2)\n') beta_DeltaDeltaG = 8 for beta_DeltaG0a in (-5.8, -8.7, -11.6, -14.5, -17.4, -20.3): <|code_end|> . Use current file imports: (import numpy as np import subprocess import operator import dnacc from math import sqrt from dnacc.units import nm) and context including class names, function names, or small code snippets from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): . Output only the next line.
f.write("# beta_DeltaG0a = %g\n" % beta_DeltaG0a)
Based on the snippet: <|code_start|># it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ## Unit testing ## ------------ def test_plates(): plates = Plates(200 * nm, 200 * nm) plates.beta_DeltaG0["alpha", "alpha'"] = -10 plates.set_tether_prototype(plate='lower', L=20 * nm, sticky_end="alpha") for x, y in [(10, 20), (15, 20), (15, 15)]: plates.add_tether(pos=(x * nm, y * nm)) plates.set_tether_prototype(plate='upper', L=20 * nm, sticky_end="alpha'") <|code_end|> , predict the immediate next line with the help of imports: import unittest import numpy as np import matplotlib.pyplot as plt from dnacc.plates import * from dnacc.spheres import * from dnacc.patches import * from dnacc.units import nm and context (classes, functions, sometimes code) from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): . Output only the next line.
for x, y in [(12, 21), (17, 21), (14, 16)]:
Predict the next line after this snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. plates = dnacc.PlatesMeanField() plates.add_tether_type(plate='lower', sticky_end='alpha', L=20 * nm, sigma=1 / (20 * nm) ** 2) plates.add_tether_type(plate='upper', sticky_end='alphap', L=20 * nm, sigma=1 / (20 * nm) ** 2) plates.beta_DeltaG0['alpha', 'alphap'] = -8 # in kT plates.at(41 * nm).set_reference_now() h_arr = np.linspace(1 * nm, 40 * nm, 40) V_plate_arr = [plates.at(h).free_energy_density for h in h_arr] R = 500 * nm V_sphere_arr = dnacc.calc_spheres_potential(h_arr, V_plate_arr, R) print("# h (nm) V (kT)") <|code_end|> using the current file's imports: import dnacc import numpy as np from dnacc.units import nm and any relevant context from other files: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): . Output only the next line.
for (h, V) in zip(h_arr, V_sphere_arr):
Given snippet: <|code_start|>plates.set_tether_type_prototype(sigma=0, L=L) ALPHA = plates.add_tether_type(plate='upper', sticky_end='alpha') ALPHA_P = plates.add_tether_type(plate='lower', sticky_end='alphap') # Where will we calculate these potentials hArr = np.linspace(1 * nm, 40 * nm, 40) # Do various grafting densities for S in 0.25, 0.75: sigma = 1 / (S * L) ** 2 plates.tether_types[ALPHA]['sigma'] = sigma plates.tether_types[ALPHA_P]['sigma'] = sigma for betaDeltaG0 in xrange(-7, -2): plates.beta_DeltaG0['alpha', 'alphap'] = betaDeltaG0 betaFPlate = [plates.at(h).free_energy_density for h in hArr] # Make plate potential first with open('plates-S%0.2f-G%.1f.dat' % (S, betaDeltaG0), 'w') as f: f.write('\t'.join(['h / L', "F_rep (kT/L^2)", "F_att (kT/L^2)", "F_plate (kT/L^2)"]) + '\n') for h, V in zip(hArr, betaFPlate): betaFRep = plates.at(h).rep_free_energy_density betaFAtt = V - betaFRep <|code_end|> , continue by predicting the next line. Consider current file imports: import dnacc import numpy as np from dnacc.units import nm and context: # Path: dnacc/units.py # _GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS = 1.660538782e-27 # kg # _GSL_CONST_MKSA_ELECTRON_CHARGE = 1.602176487e-19 # A s # _GSL_CONST_NUM_AVOGADRO = 6.02214199e23 # 1 / mol # _GSL_CONST_MKSA_GAUSS = 1e-4 # kg / A s^2 # _GSL_CONST_MKSA_BAR = 1e5 # kg / m s^2 # _GSL_CONST_MKSA_STD_ATMOSPHERE = 1.01325e5 # kg / m s^2 # _GSL_CONST_MKSA_TORR = 1.33322368421e2 # kg / m s^2 # _GSL_CONST_MKSA_METER_OF_MERCURY = 1.33322368421e5 # kg / m s^2 # K = 1.0 # A = Ampere # N = kg * m / s ** 2 # J = N * m # W = J / s # C = Ampere * s # V = J / C # F = C / V # S = 1 / Ohm # T = Wb / m ** 2 # H = Wb / Ampere # L = dm ** 3 # G = _GSL_CONST_MKSA_GAUSS * T # P = 1 * g / (cm * s) # AA = 1e-10 * m # M = mol / L # def add_amperes_unit(): # def _add_prefixes(name, realname=None): which might include code, classes, or functions. Output only the next line.
f.write('%.7g\t%.7g\t%.7g\t%.7g\n'
Given the code snippet: <|code_start|># A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # Activate the theme. html_theme = 'bootstrap' html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # (Optional) Logo. Should be small enough to fit the navbar (ideally 24x24). # Path should be relative to the ``_static`` files directory. html_logo = "logo_small.png" # Theme options are theme-specific and customize the look and feel of a # theme further. html_theme_options = { # Navigation bar title. (Default: ``project`` value) 'navbar_title': "FABGIS", # Tab name for entire site. (Default: "Site") 'navbar_site_name': "Go", # A list of tuples containing pages or urls to link to. # Valid tuples should be in the following forms: # (name, page) # a link to a page # (name, "/aa/bb", 1) # a link to an arbitrary relative url # (name, "http://example.com", True) # arbitrary absolute url # Note the "1" or "True" value above as the third argument to indicate # an arbitrary url. 'navbar_links': [ <|code_end|> , generate the next line using the imports in this file: import sys import os import sphinx_bootstrap_theme from setup import setup and context (functions, classes, or occasionally code) from other files: # Path: setup.py . Output only the next line.
("GitHub Project", "https://github.com/timlinux/fabgis"),
Based on the snippet: <|code_start|># coding=utf-8 """ GDAL Related Tasks. =================== Module for gdal related tasks""" <|code_end|> , predict the immediate next line with the help of imports: import fabtools from fabric.contrib.files import exists, append from fabric.api import fastprint, run, cd, env, task, sudo, settings from .common import add_ubuntugis_ppa, setup_env from .system import setup_ccache, get_processor_count from .proj4 import build_proj4 and context (classes, functions, sometimes code) from other files: # Path: fabgis/common.py # @task # def add_ubuntugis_ppa(): # """Ensure we have ubuntu-gis repo.""" # fabtools.deb.update_index(quiet=True) # fabtools.require.deb.package('software-properties-common') # fabtools.require.deb.ppa( # #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True) # 'ppa:ubuntugis/ubuntugis-unstable') # # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # Path: fabgis/system.py # @task # def setup_ccache(): # """Setup ccache.""" # fabtools.require.deb.package('ccache') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/gcc') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/g++') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/cc') # # def get_processor_count(): # return run('cat /proc/cpuinfo | grep ^processor | wc -l') # # Path: fabgis/proj4.py # @task # def build_proj4(version='4.8.0'): # """Get proj4 from tarball and build it. # # :param version: Proj version to build. The version should be consistent # with a downloadable tar file from the project web site. Default is # the current stable release. # :type version: str # """ # setup_env() # fabtools.require.deb.package('build-essential') # setup_ccache() # # code_base = '%s/cpp' % env.fg.workspace # filename = 'proj-%s' % version # source_url = 'http://download.osgeo.org/proj/%s.tar.gz' % filename # code_path = '%s/%s' % (code_base, filename) # # if not exists(code_path): # fastprint('Extracted tarball does not exist, creating.') # with cd(code_base): # if exists('%s.tar.gz' % filename): # run('rm %s.tar.gz' % filename) # run('wget %s' % source_url) # run('tar xfz %s.tar.gz' % filename) # # processor_count = get_processor_count() # # with cd(code_path): # # Dont fail if make clean does not work # with settings(warn_only=True): # run('make clean') # run('./configure') # run('make -j %s' % processor_count) # sudo('make install') # # Write to ld path too so libs are loaded nicely # ld_file = '/etc/ld.so.conf.d/usr_local_lib.conf' # with settings(warn_only=True): # sudo('rm %s' % ld_file) # append_if_not_present(ld_file, '/usr/local/lib', use_sudo=True) # sudo('ldconfig') . Output only the next line.
@task
Given snippet: <|code_start|># coding=utf-8 """ GDAL Related Tasks. =================== Module for gdal related tasks""" <|code_end|> , continue by predicting the next line. Consider current file imports: import fabtools from fabric.contrib.files import exists, append from fabric.api import fastprint, run, cd, env, task, sudo, settings from .common import add_ubuntugis_ppa, setup_env from .system import setup_ccache, get_processor_count from .proj4 import build_proj4 and context: # Path: fabgis/common.py # @task # def add_ubuntugis_ppa(): # """Ensure we have ubuntu-gis repo.""" # fabtools.deb.update_index(quiet=True) # fabtools.require.deb.package('software-properties-common') # fabtools.require.deb.ppa( # #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True) # 'ppa:ubuntugis/ubuntugis-unstable') # # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # Path: fabgis/system.py # @task # def setup_ccache(): # """Setup ccache.""" # fabtools.require.deb.package('ccache') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/gcc') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/g++') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/cc') # # def get_processor_count(): # return run('cat /proc/cpuinfo | grep ^processor | wc -l') # # Path: fabgis/proj4.py # @task # def build_proj4(version='4.8.0'): # """Get proj4 from tarball and build it. # # :param version: Proj version to build. The version should be consistent # with a downloadable tar file from the project web site. Default is # the current stable release. # :type version: str # """ # setup_env() # fabtools.require.deb.package('build-essential') # setup_ccache() # # code_base = '%s/cpp' % env.fg.workspace # filename = 'proj-%s' % version # source_url = 'http://download.osgeo.org/proj/%s.tar.gz' % filename # code_path = '%s/%s' % (code_base, filename) # # if not exists(code_path): # fastprint('Extracted tarball does not exist, creating.') # with cd(code_base): # if exists('%s.tar.gz' % filename): # run('rm %s.tar.gz' % filename) # run('wget %s' % source_url) # run('tar xfz %s.tar.gz' % filename) # # processor_count = get_processor_count() # # with cd(code_path): # # Dont fail if make clean does not work # with settings(warn_only=True): # run('make clean') # run('./configure') # run('make -j %s' % processor_count) # sudo('make install') # # Write to ld path too so libs are loaded nicely # ld_file = '/etc/ld.so.conf.d/usr_local_lib.conf' # with settings(warn_only=True): # sudo('rm %s' % ld_file) # append_if_not_present(ld_file, '/usr/local/lib', use_sudo=True) # sudo('ldconfig') which might include code, classes, or functions. Output only the next line.
@task
Given the code snippet: <|code_start|># coding=utf-8 """ GDAL Related Tasks. =================== Module for gdal related tasks""" @task <|code_end|> , generate the next line using the imports in this file: import fabtools from fabric.contrib.files import exists, append from fabric.api import fastprint, run, cd, env, task, sudo, settings from .common import add_ubuntugis_ppa, setup_env from .system import setup_ccache, get_processor_count from .proj4 import build_proj4 and context (functions, classes, or occasionally code) from other files: # Path: fabgis/common.py # @task # def add_ubuntugis_ppa(): # """Ensure we have ubuntu-gis repo.""" # fabtools.deb.update_index(quiet=True) # fabtools.require.deb.package('software-properties-common') # fabtools.require.deb.ppa( # #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True) # 'ppa:ubuntugis/ubuntugis-unstable') # # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # Path: fabgis/system.py # @task # def setup_ccache(): # """Setup ccache.""" # fabtools.require.deb.package('ccache') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/gcc') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/g++') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/cc') # # def get_processor_count(): # return run('cat /proc/cpuinfo | grep ^processor | wc -l') # # Path: fabgis/proj4.py # @task # def build_proj4(version='4.8.0'): # """Get proj4 from tarball and build it. # # :param version: Proj version to build. The version should be consistent # with a downloadable tar file from the project web site. Default is # the current stable release. # :type version: str # """ # setup_env() # fabtools.require.deb.package('build-essential') # setup_ccache() # # code_base = '%s/cpp' % env.fg.workspace # filename = 'proj-%s' % version # source_url = 'http://download.osgeo.org/proj/%s.tar.gz' % filename # code_path = '%s/%s' % (code_base, filename) # # if not exists(code_path): # fastprint('Extracted tarball does not exist, creating.') # with cd(code_base): # if exists('%s.tar.gz' % filename): # run('rm %s.tar.gz' % filename) # run('wget %s' % source_url) # run('tar xfz %s.tar.gz' % filename) # # processor_count = get_processor_count() # # with cd(code_path): # # Dont fail if make clean does not work # with settings(warn_only=True): # run('make clean') # run('./configure') # run('make -j %s' % processor_count) # sudo('make install') # # Write to ld path too so libs are loaded nicely # ld_file = '/etc/ld.so.conf.d/usr_local_lib.conf' # with settings(warn_only=True): # sudo('rm %s' % ld_file) # append_if_not_present(ld_file, '/usr/local/lib', use_sudo=True) # sudo('ldconfig') . Output only the next line.
def build_gdal(with_ecw=False, with_mrsid=False):
Predict the next line after this snippet: <|code_start|># coding=utf-8 """ GDAL Related Tasks. =================== Module for gdal related tasks""" <|code_end|> using the current file's imports: import fabtools from fabric.contrib.files import exists, append from fabric.api import fastprint, run, cd, env, task, sudo, settings from .common import add_ubuntugis_ppa, setup_env from .system import setup_ccache, get_processor_count from .proj4 import build_proj4 and any relevant context from other files: # Path: fabgis/common.py # @task # def add_ubuntugis_ppa(): # """Ensure we have ubuntu-gis repo.""" # fabtools.deb.update_index(quiet=True) # fabtools.require.deb.package('software-properties-common') # fabtools.require.deb.ppa( # #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True) # 'ppa:ubuntugis/ubuntugis-unstable') # # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # Path: fabgis/system.py # @task # def setup_ccache(): # """Setup ccache.""" # fabtools.require.deb.package('ccache') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/gcc') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/g++') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/cc') # # def get_processor_count(): # return run('cat /proc/cpuinfo | grep ^processor | wc -l') # # Path: fabgis/proj4.py # @task # def build_proj4(version='4.8.0'): # """Get proj4 from tarball and build it. # # :param version: Proj version to build. The version should be consistent # with a downloadable tar file from the project web site. Default is # the current stable release. # :type version: str # """ # setup_env() # fabtools.require.deb.package('build-essential') # setup_ccache() # # code_base = '%s/cpp' % env.fg.workspace # filename = 'proj-%s' % version # source_url = 'http://download.osgeo.org/proj/%s.tar.gz' % filename # code_path = '%s/%s' % (code_base, filename) # # if not exists(code_path): # fastprint('Extracted tarball does not exist, creating.') # with cd(code_base): # if exists('%s.tar.gz' % filename): # run('rm %s.tar.gz' % filename) # run('wget %s' % source_url) # run('tar xfz %s.tar.gz' % filename) # # processor_count = get_processor_count() # # with cd(code_path): # # Dont fail if make clean does not work # with settings(warn_only=True): # run('make clean') # run('./configure') # run('make -j %s' % processor_count) # sudo('make install') # # Write to ld path too so libs are loaded nicely # ld_file = '/etc/ld.so.conf.d/usr_local_lib.conf' # with settings(warn_only=True): # sudo('rm %s' % ld_file) # append_if_not_present(ld_file, '/usr/local/lib', use_sudo=True) # sudo('ldconfig') . Output only the next line.
@task
Continue the code snippet: <|code_start|># coding=utf-8 """ GDAL Related Tasks. =================== Module for gdal related tasks""" @task <|code_end|> . Use current file imports: import fabtools from fabric.contrib.files import exists, append from fabric.api import fastprint, run, cd, env, task, sudo, settings from .common import add_ubuntugis_ppa, setup_env from .system import setup_ccache, get_processor_count from .proj4 import build_proj4 and context (classes, functions, or code) from other files: # Path: fabgis/common.py # @task # def add_ubuntugis_ppa(): # """Ensure we have ubuntu-gis repo.""" # fabtools.deb.update_index(quiet=True) # fabtools.require.deb.package('software-properties-common') # fabtools.require.deb.ppa( # #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True) # 'ppa:ubuntugis/ubuntugis-unstable') # # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # Path: fabgis/system.py # @task # def setup_ccache(): # """Setup ccache.""" # fabtools.require.deb.package('ccache') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/gcc') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/g++') # sudo('ln -fs /usr/bin/ccache /usr/local/bin/cc') # # def get_processor_count(): # return run('cat /proc/cpuinfo | grep ^processor | wc -l') # # Path: fabgis/proj4.py # @task # def build_proj4(version='4.8.0'): # """Get proj4 from tarball and build it. # # :param version: Proj version to build. The version should be consistent # with a downloadable tar file from the project web site. Default is # the current stable release. # :type version: str # """ # setup_env() # fabtools.require.deb.package('build-essential') # setup_ccache() # # code_base = '%s/cpp' % env.fg.workspace # filename = 'proj-%s' % version # source_url = 'http://download.osgeo.org/proj/%s.tar.gz' % filename # code_path = '%s/%s' % (code_base, filename) # # if not exists(code_path): # fastprint('Extracted tarball does not exist, creating.') # with cd(code_base): # if exists('%s.tar.gz' % filename): # run('rm %s.tar.gz' % filename) # run('wget %s' % source_url) # run('tar xfz %s.tar.gz' % filename) # # processor_count = get_processor_count() # # with cd(code_path): # # Dont fail if make clean does not work # with settings(warn_only=True): # run('make clean') # run('./configure') # run('make -j %s' % processor_count) # sudo('make install') # # Write to ld path too so libs are loaded nicely # ld_file = '/etc/ld.so.conf.d/usr_local_lib.conf' # with settings(warn_only=True): # sudo('rm %s' % ld_file) # append_if_not_present(ld_file, '/usr/local/lib', use_sudo=True) # sudo('ldconfig') . Output only the next line.
def build_gdal(with_ecw=False, with_mrsid=False):
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8 """ Dropbox related tasks. ====================== Helpers for dropbox so that you can easily move gis data to the server.""" <|code_end|> , predict the next line using imports from the current file: import os from fabric.contrib.files import exists from fabtools import require from fabric.api import run, cd, env, task, sudo, put from .common import setup_env from .utilities import replace_tokens from .utilities import append_if_not_present and context including class names, function names, and sometimes code from other files: # Path: fabgis/common.py # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # Path: fabgis/utilities.py # def replace_tokens(conf_file, tokens): # """Deprecated: prepare a template config file by replacing its tokens. # # :param conf_file: Either a full path to a conf file name or just the # file name. In the latter case, it assumes the file is then in the # current working directory. It the file name ends in '.templ', # a copy will be made and the takens replaced in the copy. Otherwise # the original file will be manipulated. # :type conf_file: str # # :param tokens: A dictionary of key-values that should be replaced # in the conf file. # :type tokens: dic # # :returns: Path to the replaced file. # :rtype: str # # Example tokens:: # # my_tokens = { # 'SERVERNAME': env.doc_site_name, # Web Url e.g. foo.com # 'WEBMASTER': 'werner@linfiniti.com', # email of web master # 'DOCUMENTROOT': webdir, # Content root .e.g. /var/www # 'SITENAME': sitename, # Choosen name of jenkins 'root' # } # # .. deprecated:: You should use fabric.contrib.files.upload_template rather. # """ # # if '.templ' == conf_file[-6:]: # templ_file = conf_file # conf_file = conf_file.replace('.templ', '') # sudo( # 'cp %(templ_file)s %(conf_file)s' % { # 'templ_file': templ_file, # 'conf_file': conf_file}) # # base_path, file_name = os.path.split(conf_file) # if base_path is not '': # # The file is not in the current working dir. # with cd(base_path): # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # else: # # filename only, not full path - assumes the current working dir is # # the same as where the conf file is located # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # return conf_file # # Path: fabgis/utilities.py # def append_if_not_present(filename, text, use_sudo=False): # """Append to a file if an equivalent line is not already there. # :param filename: Name of file to append to. # :type filename: str # # :param text: Text to append. # :type text: str # # :param use_sudo: Run the command as sudo # :type use_sudo: bool # """ # if not contains(filename, text): # append(filename, text, use_sudo=use_sudo) . Output only the next line.
@task
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8 """ Dropbox related tasks. ====================== Helpers for dropbox so that you can easily move gis data to the server.""" <|code_end|> , predict the next line using imports from the current file: import os from fabric.contrib.files import exists from fabtools import require from fabric.api import run, cd, env, task, sudo, put from .common import setup_env from .utilities import replace_tokens from .utilities import append_if_not_present and context including class names, function names, and sometimes code from other files: # Path: fabgis/common.py # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # Path: fabgis/utilities.py # def replace_tokens(conf_file, tokens): # """Deprecated: prepare a template config file by replacing its tokens. # # :param conf_file: Either a full path to a conf file name or just the # file name. In the latter case, it assumes the file is then in the # current working directory. It the file name ends in '.templ', # a copy will be made and the takens replaced in the copy. Otherwise # the original file will be manipulated. # :type conf_file: str # # :param tokens: A dictionary of key-values that should be replaced # in the conf file. # :type tokens: dic # # :returns: Path to the replaced file. # :rtype: str # # Example tokens:: # # my_tokens = { # 'SERVERNAME': env.doc_site_name, # Web Url e.g. foo.com # 'WEBMASTER': 'werner@linfiniti.com', # email of web master # 'DOCUMENTROOT': webdir, # Content root .e.g. /var/www # 'SITENAME': sitename, # Choosen name of jenkins 'root' # } # # .. deprecated:: You should use fabric.contrib.files.upload_template rather. # """ # # if '.templ' == conf_file[-6:]: # templ_file = conf_file # conf_file = conf_file.replace('.templ', '') # sudo( # 'cp %(templ_file)s %(conf_file)s' % { # 'templ_file': templ_file, # 'conf_file': conf_file}) # # base_path, file_name = os.path.split(conf_file) # if base_path is not '': # # The file is not in the current working dir. # with cd(base_path): # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # else: # # filename only, not full path - assumes the current working dir is # # the same as where the conf file is located # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # return conf_file # # Path: fabgis/utilities.py # def append_if_not_present(filename, text, use_sudo=False): # """Append to a file if an equivalent line is not already there. # :param filename: Name of file to append to. # :type filename: str # # :param text: Text to append. # :type text: str # # :param use_sudo: Run the command as sudo # :type use_sudo: bool # """ # if not contains(filename, text): # append(filename, text, use_sudo=use_sudo) . Output only the next line.
@task
Predict the next line after this snippet: <|code_start|># coding=utf-8 """ System related tasks. ===================== Tools for setting up and hardening a system.""" <|code_end|> using the current file's imports: from getpass import getpass from fabric.api import cd, fastprint, prompt from fabric.contrib.files import contains, exists, append, sed from fabric.colors import red from fabric.api import env, task, sudo, local, reboot from fabric.operations import run from .utilities import append_if_not_present import fabtools and any relevant context from other files: # Path: fabgis/utilities.py # def append_if_not_present(filename, text, use_sudo=False): # """Append to a file if an equivalent line is not already there. # :param filename: Name of file to append to. # :type filename: str # # :param text: Text to append. # :type text: str # # :param use_sudo: Run the command as sudo # :type use_sudo: bool # """ # if not contains(filename, text): # append(filename, text, use_sudo=use_sudo) . Output only the next line.
@task
Based on the snippet: <|code_start|> sudo('make install') create_postgis_2_template() @task def setup_postgis_1_5(): """Set up postgis. You can call this multiple times without it actually installing all over again each time since it checks for the presence of pgis first. We build from source because we want 1.5""" setup_env() pg_file = '/usr/share/postgresql/9.1/contrib/postgis-1.5/postgis.sql' if not fabtools.files.is_file(pg_file): add_ubuntugis_ppa() fabtools.require.deb.package('postgresql-server-dev-all') fabtools.require.deb.package('build-essential') # Note - no postgis installation from package as we want to build 1.5 # from source fabtools.require.postgres.server() # Now get and install postgis 1.5 if needed fabtools.require.deb.package('libxml2-dev') fabtools.require.deb.package('libgeos-dev') fabtools.require.deb.package('libgdal1-dev') <|code_end|> , predict the immediate next line with the help of imports: import os import fabtools from fabric.contrib.files import exists from fabtools.postgres import create_user from fabric.colors import red, green, blue from fabric.api import run, cd, env, task, sudo, get, put, fastprint from .common import setup_env, show_environment, add_ubuntugis_ppa from .utilities import replace_tokens and context (classes, functions, sometimes code) from other files: # Path: fabgis/common.py # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # def show_environment(): # """For diagnostics - show any pertinent info about server.""" # setup_env() # fastprint('\n-------------------------------------------------\n') # for key, value in env.fg.iteritems(): # fastprint('Key: %s \t\t Value: %s\n' % (key, value)) # fastprint('-------------------------------------------------\n') # # @task # def add_ubuntugis_ppa(): # """Ensure we have ubuntu-gis repo.""" # fabtools.deb.update_index(quiet=True) # fabtools.require.deb.package('software-properties-common') # fabtools.require.deb.ppa( # #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True) # 'ppa:ubuntugis/ubuntugis-unstable') # # Path: fabgis/utilities.py # def replace_tokens(conf_file, tokens): # """Deprecated: prepare a template config file by replacing its tokens. # # :param conf_file: Either a full path to a conf file name or just the # file name. In the latter case, it assumes the file is then in the # current working directory. It the file name ends in '.templ', # a copy will be made and the takens replaced in the copy. Otherwise # the original file will be manipulated. # :type conf_file: str # # :param tokens: A dictionary of key-values that should be replaced # in the conf file. # :type tokens: dic # # :returns: Path to the replaced file. # :rtype: str # # Example tokens:: # # my_tokens = { # 'SERVERNAME': env.doc_site_name, # Web Url e.g. foo.com # 'WEBMASTER': 'werner@linfiniti.com', # email of web master # 'DOCUMENTROOT': webdir, # Content root .e.g. /var/www # 'SITENAME': sitename, # Choosen name of jenkins 'root' # } # # .. deprecated:: You should use fabric.contrib.files.upload_template rather. # """ # # if '.templ' == conf_file[-6:]: # templ_file = conf_file # conf_file = conf_file.replace('.templ', '') # sudo( # 'cp %(templ_file)s %(conf_file)s' % { # 'templ_file': templ_file, # 'conf_file': conf_file}) # # base_path, file_name = os.path.split(conf_file) # if base_path is not '': # # The file is not in the current working dir. # with cd(base_path): # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # else: # # filename only, not full path - assumes the current working dir is # # the same as where the conf file is located # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # return conf_file . Output only the next line.
fabtools.require.deb.package('libproj-dev')
Given the following code snippet before the placeholder: <|code_start|> sudo('make install') create_postgis_2_template() @task def setup_postgis_1_5(): """Set up postgis. You can call this multiple times without it actually installing all over again each time since it checks for the presence of pgis first. We build from source because we want 1.5""" setup_env() pg_file = '/usr/share/postgresql/9.1/contrib/postgis-1.5/postgis.sql' if not fabtools.files.is_file(pg_file): add_ubuntugis_ppa() fabtools.require.deb.package('postgresql-server-dev-all') fabtools.require.deb.package('build-essential') # Note - no postgis installation from package as we want to build 1.5 # from source fabtools.require.postgres.server() # Now get and install postgis 1.5 if needed fabtools.require.deb.package('libxml2-dev') fabtools.require.deb.package('libgeos-dev') fabtools.require.deb.package('libgdal1-dev') <|code_end|> , predict the next line using imports from the current file: import os import fabtools from fabric.contrib.files import exists from fabtools.postgres import create_user from fabric.colors import red, green, blue from fabric.api import run, cd, env, task, sudo, get, put, fastprint from .common import setup_env, show_environment, add_ubuntugis_ppa from .utilities import replace_tokens and context including class names, function names, and sometimes code from other files: # Path: fabgis/common.py # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # def show_environment(): # """For diagnostics - show any pertinent info about server.""" # setup_env() # fastprint('\n-------------------------------------------------\n') # for key, value in env.fg.iteritems(): # fastprint('Key: %s \t\t Value: %s\n' % (key, value)) # fastprint('-------------------------------------------------\n') # # @task # def add_ubuntugis_ppa(): # """Ensure we have ubuntu-gis repo.""" # fabtools.deb.update_index(quiet=True) # fabtools.require.deb.package('software-properties-common') # fabtools.require.deb.ppa( # #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True) # 'ppa:ubuntugis/ubuntugis-unstable') # # Path: fabgis/utilities.py # def replace_tokens(conf_file, tokens): # """Deprecated: prepare a template config file by replacing its tokens. # # :param conf_file: Either a full path to a conf file name or just the # file name. In the latter case, it assumes the file is then in the # current working directory. It the file name ends in '.templ', # a copy will be made and the takens replaced in the copy. Otherwise # the original file will be manipulated. # :type conf_file: str # # :param tokens: A dictionary of key-values that should be replaced # in the conf file. # :type tokens: dic # # :returns: Path to the replaced file. # :rtype: str # # Example tokens:: # # my_tokens = { # 'SERVERNAME': env.doc_site_name, # Web Url e.g. foo.com # 'WEBMASTER': 'werner@linfiniti.com', # email of web master # 'DOCUMENTROOT': webdir, # Content root .e.g. /var/www # 'SITENAME': sitename, # Choosen name of jenkins 'root' # } # # .. deprecated:: You should use fabric.contrib.files.upload_template rather. # """ # # if '.templ' == conf_file[-6:]: # templ_file = conf_file # conf_file = conf_file.replace('.templ', '') # sudo( # 'cp %(templ_file)s %(conf_file)s' % { # 'templ_file': templ_file, # 'conf_file': conf_file}) # # base_path, file_name = os.path.split(conf_file) # if base_path is not '': # # The file is not in the current working dir. # with cd(base_path): # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # else: # # filename only, not full path - assumes the current working dir is # # the same as where the conf file is located # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # return conf_file . Output only the next line.
fabtools.require.deb.package('libproj-dev')
Given the following code snippet before the placeholder: <|code_start|> @task def setup_postgis_1_5(): """Set up postgis. You can call this multiple times without it actually installing all over again each time since it checks for the presence of pgis first. We build from source because we want 1.5""" setup_env() pg_file = '/usr/share/postgresql/9.1/contrib/postgis-1.5/postgis.sql' if not fabtools.files.is_file(pg_file): add_ubuntugis_ppa() fabtools.require.deb.package('postgresql-server-dev-all') fabtools.require.deb.package('build-essential') # Note - no postgis installation from package as we want to build 1.5 # from source fabtools.require.postgres.server() # Now get and install postgis 1.5 if needed fabtools.require.deb.package('libxml2-dev') fabtools.require.deb.package('libgeos-dev') fabtools.require.deb.package('libgdal1-dev') fabtools.require.deb.package('libproj-dev') source_url = ('http://download.osgeo.org/postgis/source/' 'postgis-1.5.8.tar.gz') <|code_end|> , predict the next line using imports from the current file: import os import fabtools from fabric.contrib.files import exists from fabtools.postgres import create_user from fabric.colors import red, green, blue from fabric.api import run, cd, env, task, sudo, get, put, fastprint from .common import setup_env, show_environment, add_ubuntugis_ppa from .utilities import replace_tokens and context including class names, function names, and sometimes code from other files: # Path: fabgis/common.py # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # def show_environment(): # """For diagnostics - show any pertinent info about server.""" # setup_env() # fastprint('\n-------------------------------------------------\n') # for key, value in env.fg.iteritems(): # fastprint('Key: %s \t\t Value: %s\n' % (key, value)) # fastprint('-------------------------------------------------\n') # # @task # def add_ubuntugis_ppa(): # """Ensure we have ubuntu-gis repo.""" # fabtools.deb.update_index(quiet=True) # fabtools.require.deb.package('software-properties-common') # fabtools.require.deb.ppa( # #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True) # 'ppa:ubuntugis/ubuntugis-unstable') # # Path: fabgis/utilities.py # def replace_tokens(conf_file, tokens): # """Deprecated: prepare a template config file by replacing its tokens. # # :param conf_file: Either a full path to a conf file name or just the # file name. In the latter case, it assumes the file is then in the # current working directory. It the file name ends in '.templ', # a copy will be made and the takens replaced in the copy. Otherwise # the original file will be manipulated. # :type conf_file: str # # :param tokens: A dictionary of key-values that should be replaced # in the conf file. # :type tokens: dic # # :returns: Path to the replaced file. # :rtype: str # # Example tokens:: # # my_tokens = { # 'SERVERNAME': env.doc_site_name, # Web Url e.g. foo.com # 'WEBMASTER': 'werner@linfiniti.com', # email of web master # 'DOCUMENTROOT': webdir, # Content root .e.g. /var/www # 'SITENAME': sitename, # Choosen name of jenkins 'root' # } # # .. deprecated:: You should use fabric.contrib.files.upload_template rather. # """ # # if '.templ' == conf_file[-6:]: # templ_file = conf_file # conf_file = conf_file.replace('.templ', '') # sudo( # 'cp %(templ_file)s %(conf_file)s' % { # 'templ_file': templ_file, # 'conf_file': conf_file}) # # base_path, file_name = os.path.split(conf_file) # if base_path is not '': # # The file is not in the current working dir. # with cd(base_path): # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # else: # # filename only, not full path - assumes the current working dir is # # the same as where the conf file is located # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # return conf_file . Output only the next line.
source = 'postgis-1.5.8'
Here is a snippet: <|code_start|> fabtools.require.deb.package('libgdal1-dev') fabtools.require.deb.package('libproj-dev') source_url = ('http://download.osgeo.org/postgis/source/' 'postgis-2.1.1.tar.gz') source = 'postgis-2.1.1' if not fabtools.files.is_file('%s.tar.gz' % source): run('wget %s' % source_url) run('tar xfz %s.tar.gz' % source) with cd(source): run('./configure') run('make') sudo('make install') create_postgis_2_template() @task def setup_postgis_1_5(): """Set up postgis. You can call this multiple times without it actually installing all over again each time since it checks for the presence of pgis first. We build from source because we want 1.5""" setup_env() pg_file = '/usr/share/postgresql/9.1/contrib/postgis-1.5/postgis.sql' if not fabtools.files.is_file(pg_file): add_ubuntugis_ppa() fabtools.require.deb.package('postgresql-server-dev-all') <|code_end|> . Write the next line using the current file imports: import os import fabtools from fabric.contrib.files import exists from fabtools.postgres import create_user from fabric.colors import red, green, blue from fabric.api import run, cd, env, task, sudo, get, put, fastprint from .common import setup_env, show_environment, add_ubuntugis_ppa from .utilities import replace_tokens and context from other files: # Path: fabgis/common.py # def setup_env(): # """Things to do regardless of whether command is local or remote. # # Todo - many of these env.fg settings should be module specific... # # """ # if env.fg is not None: # fastprint('Environment already set!\n') # return # # fastprint('Setting environment!\n') # env.fg = fdict() # with hide('output'): # env.fg.user = run('whoami') # # Workaround for # env.fg.hostname = run('hostname') # # this which fails in docker - see # # https://github.com/dotcloud/docker/issues/1301 # #env.fg.hostname = fabtools.system.get_hostname() # env.fg.home = os.path.join('/home/', env.fg.user) # env.fg.workspace = os.path.join(env.fg.home, 'dev') # env.fg.inasafe_git_url = 'git://github.com/AIFDR/inasafe.git' # env.fg.qgis_git_url = 'git://github.com/qgis/QGIS.git' # env.fg.kandan_git_url = 'git://github.com/kandanapp/kandan.git' # env.fg.gdal_svn_url = 'https://svn.osgeo.org/gdal/trunk/gdal' # env.fg.inasafe_checkout_alias = 'inasafe-fabric' # env.fg.qgis_checkout_alias = 'qgis-fabric' # env.fg.inasafe_code_path = os.path.join( # env.fg.workspace, env.fg.inasafe_checkout_alias) # env.fg.qgis_code_path = os.path.join( # env.fg.workspace, env.fg.qgis_checkout_alias) # # def show_environment(): # """For diagnostics - show any pertinent info about server.""" # setup_env() # fastprint('\n-------------------------------------------------\n') # for key, value in env.fg.iteritems(): # fastprint('Key: %s \t\t Value: %s\n' % (key, value)) # fastprint('-------------------------------------------------\n') # # @task # def add_ubuntugis_ppa(): # """Ensure we have ubuntu-gis repo.""" # fabtools.deb.update_index(quiet=True) # fabtools.require.deb.package('software-properties-common') # fabtools.require.deb.ppa( # #'ppa:ubuntugis/ubuntugis-unstable', auto_yes=True) # 'ppa:ubuntugis/ubuntugis-unstable') # # Path: fabgis/utilities.py # def replace_tokens(conf_file, tokens): # """Deprecated: prepare a template config file by replacing its tokens. # # :param conf_file: Either a full path to a conf file name or just the # file name. In the latter case, it assumes the file is then in the # current working directory. It the file name ends in '.templ', # a copy will be made and the takens replaced in the copy. Otherwise # the original file will be manipulated. # :type conf_file: str # # :param tokens: A dictionary of key-values that should be replaced # in the conf file. # :type tokens: dic # # :returns: Path to the replaced file. # :rtype: str # # Example tokens:: # # my_tokens = { # 'SERVERNAME': env.doc_site_name, # Web Url e.g. foo.com # 'WEBMASTER': 'werner@linfiniti.com', # email of web master # 'DOCUMENTROOT': webdir, # Content root .e.g. /var/www # 'SITENAME': sitename, # Choosen name of jenkins 'root' # } # # .. deprecated:: You should use fabric.contrib.files.upload_template rather. # """ # # if '.templ' == conf_file[-6:]: # templ_file = conf_file # conf_file = conf_file.replace('.templ', '') # sudo( # 'cp %(templ_file)s %(conf_file)s' % { # 'templ_file': templ_file, # 'conf_file': conf_file}) # # base_path, file_name = os.path.split(conf_file) # if base_path is not '': # # The file is not in the current working dir. # with cd(base_path): # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # else: # # filename only, not full path - assumes the current working dir is # # the same as where the conf file is located # for key, value in tokens.iteritems(): # sudo('sed -i.bak -r -e "s/\[%s\]/%s/g" %s' % ( # key, value, file_name)) # sudo('rm %s.bak' % file_name) # return conf_file , which may include functions, classes, or code. Output only the next line.
fabtools.require.deb.package('build-essential')
Based on the snippet: <|code_start|> def _model_wrapper(dependency=None, message=None, complete=None): def private(self, key, default=None): return getattr(self,'_%s%s'%(self.__class__.__name__,key),default) def private_set(self, key, data): args = tuple() kwargs = {} if data is None: pass elif isinstance(data, tuple): if len(data) == 2 and isinstance(data[0], tuple) and isinstance(data[1],dict): args = data[0] kwargs = data[1] else: args = data elif isinstance(data, dict): kwargs = data else: args = (data,) setattr(self, '_%s%s_args'%(self.__class__.__name__,key), args) <|code_end|> , predict the immediate next line with the help of imports: from abc import ABCMeta, abstractmethod from ..utility.text import colour_text as coloured import sys import traceback and context (classes, functions, sometimes code) from other files: # Path: qubricks/utility/text.py # def colour_text(text, colour_name='WHITE', bold=False): # if colour_name in COLOURS: # return '\033[{0};{1}m{2}\033[0m'.format( # int(bold), COLOURS.index(colour_name) + 30, text) # sys.stderr.write('ERROR: "{0}" is not a valid colour.\n'.format(colour_name)) # sys.stderr.write('VALID COLOURS: {0}.\n'.format(', '.join(COLOURS))) . Output only the next line.
setattr(self, '_%s%s_kwargs'%(self.__class__.__name__,key), kwargs)
Given the following code snippet before the placeholder: <|code_start|> # Access to the data: clusters # ---------------------------- def get_cluster_colors(self, clusters=None, can_override=True, ): if clusters is None: clusters = self.clusters_selected if can_override and self.override_color: group_colors = get_array(self.get_group_colors('all')) groups = get_array(self.get_cluster_groups('all')) colors = pd.Series(group_colors[groups], index=self.get_clusters_unique()) else: colors = pd.Series([self.get_cluster_color(c) for c in clusters], index=clusters) return select(colors, clusters) def get_cluster_color(self, cluster): try: return next_color(cluster) except IndexError: return 0 def get_cluster_groups(self, clusters=None): if clusters is None: clusters = self.clusters_selected return select(self.cluster_groups, clusters) def get_group_colors(self, groups=None): return select(self.group_colors, groups) <|code_end|> , predict the next line using imports from the current file: import os import os.path import re import numpy as np import pandas as pd from collections import Counter from qtools import QtGui, QtCore from tools import (load_text, normalize, load_binary, load_pickle, save_text, get_array, first_row, load_binary_memmap) from selection import (select, select_pairs, get_spikes_in_clusters, get_some_spikes_in_clusters, get_some_spikes, get_indices) from kwiklib.utils.logger import (debug, info, warn, exception, FileLogger, register, unregister) from kwiklib.utils.colors import COLORS_COUNT, generate_colors, next_color and context including class names, function names, and sometimes code from other files: # Path: kwiklib/utils/logger.py # def debug(self, msg): # self._logger.debug(self.get_message(msg)) # # def info(self, msg): # self._logger.info(self.get_message(msg)) # # def warn(self, msg): # self._logger.warn(self.get_message(msg)) # # def exception(self, msg): # self._logger.exception(self.get_message(msg)) # # class FileLogger(Logger): # def __init__(self, filename=None, **kwargs): # kwargs['handler'] = logging.FileHandler(filename) # super(FileLogger, self).__init__(**kwargs) # # def close(self): # self.handler.close() # self._logger.removeHandler(self.handler) # del self.handler # del self._logger # # def register(logger): # name = logger.name # if name not in LOGGERS: # LOGGERS[name] = logger # # def unregister(logger): # name = logger.name # if name in LOGGERS: # LOGGERS[name].close() # del LOGGERS[name] . Output only the next line.
def get_group_names(self, groups=None):
Predict the next line for this snippet: <|code_start|> tree = ET.parse(filename_xml) root = tree.getroot() d = {} ac = root.find('acquisitionSystem') if ac is not None: nc = ac.find('nChannels') if nc is not None: d['total_channels'] = int(nc.text) sr = ac.find('samplingRate') if sr is not None: d['rate'] = float(sr.text) sd = root.find('spikeDetection') if sd is not None: cg = sd.find('channelGroups') if cg is not None: # find the group corresponding to the fileindex g = cg.findall('group')[fileindex - 1] if g is not None: ns = g.find('nSamples') if ns is not None: d['nsamples'] = int(ns.text) nf = g.find('nFeatures') if nf is not None: d['fetdim'] = int(nf.text) c = g.find('channels') if c is not None: <|code_end|> with the help of current file imports: import os import os.path import re import xml.etree.ElementTree as ET import numpy as np import pandas as pd from loader import (Loader, default_group_info, reorder, renumber_clusters, default_cluster_info) from tools import (load_text, normalize, load_binary, load_pickle, save_text, get_array, first_row, load_binary_memmap) from selection import (select, select_pairs, get_spikes_in_clusters, get_some_spikes_in_clusters, get_some_spikes, get_indices) from kwiklib.utils.logger import (register, unregister, FileLogger, debug, info, warn) from kwiklib.utils.colors import COLORS_COUNT, generate_colors and context from other files: # Path: kwiklib/utils/logger.py # def register(logger): # name = logger.name # if name not in LOGGERS: # LOGGERS[name] = logger # # def unregister(logger): # name = logger.name # if name in LOGGERS: # LOGGERS[name].close() # del LOGGERS[name] # # class FileLogger(Logger): # def __init__(self, filename=None, **kwargs): # kwargs['handler'] = logging.FileHandler(filename) # super(FileLogger, self).__init__(**kwargs) # # def close(self): # self.handler.close() # self._logger.removeHandler(self.handler) # del self.handler # del self._logger # # def debug(self, msg): # self._logger.debug(self.get_message(msg)) # # def info(self, msg): # self._logger.info(self.get_message(msg)) # # def warn(self, msg): # self._logger.warn(self.get_message(msg)) , which may contain function names, class names, or code. Output only the next line.
d['nchannels'] = len(c.findall('channel'))
Next line prediction: <|code_start|> return filenames # ----------------------------------------------------------------------------- # File reading functions # ----------------------------------------------------------------------------- def read_xml(filename_xml, fileindex=1): """Read the XML file associated to the current dataset, and return a metadata dictionary.""" tree = ET.parse(filename_xml) root = tree.getroot() d = {} ac = root.find('acquisitionSystem') if ac is not None: nc = ac.find('nChannels') if nc is not None: d['total_channels'] = int(nc.text) sr = ac.find('samplingRate') if sr is not None: d['rate'] = float(sr.text) sd = root.find('spikeDetection') if sd is not None: cg = sd.find('channelGroups') if cg is not None: # find the group corresponding to the fileindex g = cg.findall('group')[fileindex - 1] <|code_end|> . Use current file imports: (import os import os.path import re import xml.etree.ElementTree as ET import numpy as np import pandas as pd from loader import (Loader, default_group_info, reorder, renumber_clusters, default_cluster_info) from tools import (load_text, normalize, load_binary, load_pickle, save_text, get_array, first_row, load_binary_memmap) from selection import (select, select_pairs, get_spikes_in_clusters, get_some_spikes_in_clusters, get_some_spikes, get_indices) from kwiklib.utils.logger import (register, unregister, FileLogger, debug, info, warn) from kwiklib.utils.colors import COLORS_COUNT, generate_colors) and context including class names, function names, or small code snippets from other files: # Path: kwiklib/utils/logger.py # def register(logger): # name = logger.name # if name not in LOGGERS: # LOGGERS[name] = logger # # def unregister(logger): # name = logger.name # if name in LOGGERS: # LOGGERS[name].close() # del LOGGERS[name] # # class FileLogger(Logger): # def __init__(self, filename=None, **kwargs): # kwargs['handler'] = logging.FileHandler(filename) # super(FileLogger, self).__init__(**kwargs) # # def close(self): # self.handler.close() # self._logger.removeHandler(self.handler) # del self.handler # del self._logger # # def debug(self, msg): # self._logger.debug(self.get_message(msg)) # # def info(self, msg): # self._logger.info(self.get_message(msg)) # # def warn(self, msg): # self._logger.warn(self.get_message(msg)) . Output only the next line.
if g is not None:
Predict the next line for this snippet: <|code_start|> return metadata # Features. def process_features(features, fetdim, nchannels, freq, nfet=None): features = np.array(features, dtype=np.float32) nspikes, ncol = features.shape if nfet is not None: nextrafet = nfet - fetdim * nchannels else: nextrafet = ncol - fetdim * nchannels # get the spiketimes spiketimes = features[:,-1].copy() spiketimes *= (1. / freq) # normalize normal features while keeping symmetry features_normal = normalize(features[:,:fetdim * nchannels], symmetric=True) features_time = spiketimes.reshape((-1, 1)) * 1. / spiketimes[-1] * 2 - 1 # features_time = spiketimes.reshape((-1, 1)) * 1. / spiketimes[-1]# * 2 - 1 # normalize extra features without keeping symmetry if nextrafet > 1: features_extra = normalize(features[:,-nextrafet:-1], symmetric=False) features = np.hstack((features_normal, features_extra, features_time)) else: features = np.hstack((features_normal, features_time)) return features, spiketimes <|code_end|> with the help of current file imports: import os import os.path import re import xml.etree.ElementTree as ET import numpy as np import pandas as pd from loader import (Loader, default_group_info, reorder, renumber_clusters, default_cluster_info) from tools import (load_text, normalize, load_binary, load_pickle, save_text, get_array, first_row, load_binary_memmap) from selection import (select, select_pairs, get_spikes_in_clusters, get_some_spikes_in_clusters, get_some_spikes, get_indices) from kwiklib.utils.logger import (register, unregister, FileLogger, debug, info, warn) from kwiklib.utils.colors import COLORS_COUNT, generate_colors and context from other files: # Path: kwiklib/utils/logger.py # def register(logger): # name = logger.name # if name not in LOGGERS: # LOGGERS[name] = logger # # def unregister(logger): # name = logger.name # if name in LOGGERS: # LOGGERS[name].close() # del LOGGERS[name] # # class FileLogger(Logger): # def __init__(self, filename=None, **kwargs): # kwargs['handler'] = logging.FileHandler(filename) # super(FileLogger, self).__init__(**kwargs) # # def close(self): # self.handler.close() # self._logger.removeHandler(self.handler) # del self.handler # del self._logger # # def debug(self, msg): # self._logger.debug(self.get_message(msg)) # # def info(self, msg): # self._logger.info(self.get_message(msg)) # # def warn(self, msg): # self._logger.warn(self.get_message(msg)) , which may contain function names, class names, or code. Output only the next line.
def read_features(filename_fet, nchannels, fetdim, freq, do_process=True):
Predict the next line for this snippet: <|code_start|> return os.path.join(dir, filtered[0]) return None def find_any_filename(filename, extension_requested, dir='', files=[]): # get the full path dir = dir.strip() if not dir: dir = os.path.dirname(os.path.realpath(filename)) # try obtaining the list of all files in the directory if not files: try: files = os.listdir(dir) except (OSError, IOError): raise IOError("Error when accessing '{0:s}'.".format(dir)) filtered = filter(lambda f: f.endswith('.' + extension_requested), files) if filtered: return os.path.join(dir, filtered[0]) def find_filename_or_new(filename, extension_requested, have_file_index=True, dir='', files=[]): """Find an existing filename with a requested extension, or create a new filename based on an existing file.""" # Find the filename with the requested extension. filename_found = find_filename(filename, extension_requested, dir=dir, files=files) # If it does not exist, find a file that exists, and replace the extension # with the requested one. if not filename_found: <|code_end|> with the help of current file imports: import os import os.path import re import xml.etree.ElementTree as ET import numpy as np import pandas as pd from loader import (Loader, default_group_info, reorder, renumber_clusters, default_cluster_info) from tools import (load_text, normalize, load_binary, load_pickle, save_text, get_array, first_row, load_binary_memmap) from selection import (select, select_pairs, get_spikes_in_clusters, get_some_spikes_in_clusters, get_some_spikes, get_indices) from kwiklib.utils.logger import (register, unregister, FileLogger, debug, info, warn) from kwiklib.utils.colors import COLORS_COUNT, generate_colors and context from other files: # Path: kwiklib/utils/logger.py # def register(logger): # name = logger.name # if name not in LOGGERS: # LOGGERS[name] = logger # # def unregister(logger): # name = logger.name # if name in LOGGERS: # LOGGERS[name].close() # del LOGGERS[name] # # class FileLogger(Logger): # def __init__(self, filename=None, **kwargs): # kwargs['handler'] = logging.FileHandler(filename) # super(FileLogger, self).__init__(**kwargs) # # def close(self): # self.handler.close() # self._logger.removeHandler(self.handler) # del self.handler # del self._logger # # def debug(self, msg): # self._logger.debug(self.get_message(msg)) # # def info(self, msg): # self._logger.info(self.get_message(msg)) # # def warn(self, msg): # self._logger.warn(self.get_message(msg)) , which may contain function names, class names, or code. Output only the next line.
if have_file_index:
Given the code snippet: <|code_start|> fetdim=d['fetdim'], freq=d['rate']) return metadata # Features. def process_features(features, fetdim, nchannels, freq, nfet=None): features = np.array(features, dtype=np.float32) nspikes, ncol = features.shape if nfet is not None: nextrafet = nfet - fetdim * nchannels else: nextrafet = ncol - fetdim * nchannels # get the spiketimes spiketimes = features[:,-1].copy() spiketimes *= (1. / freq) # normalize normal features while keeping symmetry features_normal = normalize(features[:,:fetdim * nchannels], symmetric=True) features_time = spiketimes.reshape((-1, 1)) * 1. / spiketimes[-1] * 2 - 1 # features_time = spiketimes.reshape((-1, 1)) * 1. / spiketimes[-1]# * 2 - 1 # normalize extra features without keeping symmetry if nextrafet > 1: features_extra = normalize(features[:,-nextrafet:-1], symmetric=False) features = np.hstack((features_normal, features_extra, features_time)) else: features = np.hstack((features_normal, features_time)) <|code_end|> , generate the next line using the imports in this file: import os import os.path import re import xml.etree.ElementTree as ET import numpy as np import pandas as pd from loader import (Loader, default_group_info, reorder, renumber_clusters, default_cluster_info) from tools import (load_text, normalize, load_binary, load_pickle, save_text, get_array, first_row, load_binary_memmap) from selection import (select, select_pairs, get_spikes_in_clusters, get_some_spikes_in_clusters, get_some_spikes, get_indices) from kwiklib.utils.logger import (register, unregister, FileLogger, debug, info, warn) from kwiklib.utils.colors import COLORS_COUNT, generate_colors and context (functions, classes, or occasionally code) from other files: # Path: kwiklib/utils/logger.py # def register(logger): # name = logger.name # if name not in LOGGERS: # LOGGERS[name] = logger # # def unregister(logger): # name = logger.name # if name in LOGGERS: # LOGGERS[name].close() # del LOGGERS[name] # # class FileLogger(Logger): # def __init__(self, filename=None, **kwargs): # kwargs['handler'] = logging.FileHandler(filename) # super(FileLogger, self).__init__(**kwargs) # # def close(self): # self.handler.close() # self._logger.removeHandler(self.handler) # del self.handler # del self._logger # # def debug(self, msg): # self._logger.debug(self.get_message(msg)) # # def info(self, msg): # self._logger.info(self.get_message(msg)) # # def warn(self, msg): # self._logger.warn(self.get_message(msg)) . Output only the next line.
return features, spiketimes
Continue the code snippet: <|code_start|> sr = ac.find('samplingRate') if sr is not None: d['rate'] = float(sr.text) sd = root.find('spikeDetection') if sd is not None: cg = sd.find('channelGroups') if cg is not None: # find the group corresponding to the fileindex g = cg.findall('group')[fileindex - 1] if g is not None: ns = g.find('nSamples') if ns is not None: d['nsamples'] = int(ns.text) nf = g.find('nFeatures') if nf is not None: d['fetdim'] = int(nf.text) c = g.find('channels') if c is not None: d['nchannels'] = len(c.findall('channel')) if 'nchannels' not in d: d['nchannels'] = d['total_channels'] if 'nsamples' not in d: ne = root.find('neuroscope') if ne is not None: sp = ne.find('spikes') if sp is not None: ns = sp.find('nSamples') <|code_end|> . Use current file imports: import os import os.path import re import xml.etree.ElementTree as ET import numpy as np import pandas as pd from loader import (Loader, default_group_info, reorder, renumber_clusters, default_cluster_info) from tools import (load_text, normalize, load_binary, load_pickle, save_text, get_array, first_row, load_binary_memmap) from selection import (select, select_pairs, get_spikes_in_clusters, get_some_spikes_in_clusters, get_some_spikes, get_indices) from kwiklib.utils.logger import (register, unregister, FileLogger, debug, info, warn) from kwiklib.utils.colors import COLORS_COUNT, generate_colors and context (classes, functions, or code) from other files: # Path: kwiklib/utils/logger.py # def register(logger): # name = logger.name # if name not in LOGGERS: # LOGGERS[name] = logger # # def unregister(logger): # name = logger.name # if name in LOGGERS: # LOGGERS[name].close() # del LOGGERS[name] # # class FileLogger(Logger): # def __init__(self, filename=None, **kwargs): # kwargs['handler'] = logging.FileHandler(filename) # super(FileLogger, self).__init__(**kwargs) # # def close(self): # self.handler.close() # self._logger.removeHandler(self.handler) # del self.handler # del self._logger # # def debug(self, msg): # self._logger.debug(self.get_message(msg)) # # def info(self, msg): # self._logger.info(self.get_message(msg)) # # def warn(self, msg): # self._logger.warn(self.get_message(msg)) . Output only the next line.
if ns is not None:
Here is a snippet: <|code_start|> urlpatterns = [ url(r'^(?P<id>\d+)/(?:(?P<slug>[\w-]+)/)?$', views.view, name='view'), url(r'^rss/(?P<id>\d+)/$', CategoryArticlesFeed(), name='rss'), <|code_end|> . Write the next line using the current file imports: from django.conf.urls import url from twobuntu.categories import views from twobuntu.feeds import CategoryArticlesFeed and context from other files: # Path: twobuntu/categories/views.py # def view(request, category): # # Path: twobuntu/feeds.py # class CategoryArticlesFeed(ArticleFeed): # """ # Feed of articles in a specific category. # """ # # def get_object(self, request, id): # return get_object_or_404(Category, pk=id) # # def title(self, category): # return 'Articles in %s' % category # # def link(self, category): # return category.get_absolute_url() # # def description(self, category): # return "Articles filed under %s." % category # # def items(self, category): # return Article.objects.select_related('author', 'category').filter(status=Article.PUBLISHED, category=category)[:20] , which may include functions, classes, or code. Output only the next line.
]
Using the snippet: <|code_start|> urlpatterns = [ url(r'^(?P<id>\d+)/(?:(?P<slug>[\w-]+)/)?$', views.view, name='view'), url(r'^rss/(?P<id>\d+)/$', CategoryArticlesFeed(), name='rss'), <|code_end|> , determine the next line of code. You have imports: from django.conf.urls import url from twobuntu.categories import views from twobuntu.feeds import CategoryArticlesFeed and context (class names, function names, or code) available: # Path: twobuntu/categories/views.py # def view(request, category): # # Path: twobuntu/feeds.py # class CategoryArticlesFeed(ArticleFeed): # """ # Feed of articles in a specific category. # """ # # def get_object(self, request, id): # return get_object_or_404(Category, pk=id) # # def title(self, category): # return 'Articles in %s' % category # # def link(self, category): # return category.get_absolute_url() # # def description(self, category): # return "Articles filed under %s." % category # # def items(self, category): # return Article.objects.select_related('author', 'category').filter(status=Article.PUBLISHED, category=category)[:20] . Output only the next line.
]
Based on the snippet: <|code_start|> urlpatterns = [ url(r'^view/(?P<id>\d+)/$', views.view, name='view'), url(r'^upload/$', views.upload, name='upload'), <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import url from twobuntu.images import views and context (classes, functions, sometimes code) from other files: # Path: twobuntu/images/views.py # def view(request, id): # def upload(request): . Output only the next line.
]
Continue the code snippet: <|code_start|> sitemaps = { 'home': HomePageSitemap, 'static': StaticViewSitemap, } urlpatterns = [ url(r'^$', views.index, name='home'), url(r'^about/$', views.about, name='about'), url(r'^links/$', views.links, name='links'), url(r'^feedback/$', views.feedback, name='feedback'), url(r'^join/$', views.join, name='join'), url(r'^opensearch\.xml$', views.opensearch, name='opensearch'), url(r'^accounts/', include('twobuntu.accounts.urls', 'accounts')), url(r'^articles/', include('twobuntu.articles.urls', 'articles')), url(r'^api/', include('twobuntu.api.urls', 'api')), url(r'^categories/', include('twobuntu.categories.urls', 'categories')), <|code_end|> . Use current file imports: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from twobuntu import views from twobuntu.feeds import LatestArticlesFeed from twobuntu.sitemaps import HomePageSitemap, StaticViewSitemap and context (classes, functions, or code) from other files: # Path: twobuntu/views.py # def index(request): # def commit(): # def about(request): # def links(request): # def feedback(request): # def join(request): # def opensearch(request): # def old(request, id): # # Path: twobuntu/feeds.py # class LatestArticlesFeed(ArticleFeed): # """ # Feed of most recent articles. # """ # # title = "Latest Articles on 2buntu" # link = reverse_lazy('home') # description = "Recently published articles about Ubuntu on the 2buntu blog." # # def items(self): # return Article.objects.select_related('author', 'category').filter(status=Article.PUBLISHED)[:20] # # Path: twobuntu/sitemaps.py # class HomePageSitemap(sitemaps.Sitemap): # priority = 1.0 # changefreq = 'weekly' # # def items(self): # return ['home'] # # def location(self, item): # return reverse(item) # # class StaticViewSitemap(sitemaps.Sitemap): # priority = 0.8 # changefreq = 'yearly' # # def items(self): # return ['about', 'links', 'feedback', 'join'] # # def location(self, item): # return reverse(item) . Output only the next line.
url(r'^images/', include('twobuntu.images.urls', 'images')),
Next line prediction: <|code_start|> sitemaps = { 'home': HomePageSitemap, 'static': StaticViewSitemap, } urlpatterns = [ url(r'^$', views.index, name='home'), url(r'^about/$', views.about, name='about'), url(r'^links/$', views.links, name='links'), url(r'^feedback/$', views.feedback, name='feedback'), url(r'^join/$', views.join, name='join'), url(r'^opensearch\.xml$', views.opensearch, name='opensearch'), url(r'^accounts/', include('twobuntu.accounts.urls', 'accounts')), url(r'^articles/', include('twobuntu.articles.urls', 'articles')), url(r'^api/', include('twobuntu.api.urls', 'api')), url(r'^categories/', include('twobuntu.categories.urls', 'categories')), url(r'^images/', include('twobuntu.images.urls', 'images')), <|code_end|> . Use current file imports: (from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from twobuntu import views from twobuntu.feeds import LatestArticlesFeed from twobuntu.sitemaps import HomePageSitemap, StaticViewSitemap) and context including class names, function names, or small code snippets from other files: # Path: twobuntu/views.py # def index(request): # def commit(): # def about(request): # def links(request): # def feedback(request): # def join(request): # def opensearch(request): # def old(request, id): # # Path: twobuntu/feeds.py # class LatestArticlesFeed(ArticleFeed): # """ # Feed of most recent articles. # """ # # title = "Latest Articles on 2buntu" # link = reverse_lazy('home') # description = "Recently published articles about Ubuntu on the 2buntu blog." # # def items(self): # return Article.objects.select_related('author', 'category').filter(status=Article.PUBLISHED)[:20] # # Path: twobuntu/sitemaps.py # class HomePageSitemap(sitemaps.Sitemap): # priority = 1.0 # changefreq = 'weekly' # # def items(self): # return ['home'] # # def location(self, item): # return reverse(item) # # class StaticViewSitemap(sitemaps.Sitemap): # priority = 0.8 # changefreq = 'yearly' # # def items(self): # return ['about', 'links', 'feedback', 'join'] # # def location(self, item): # return reverse(item) . Output only the next line.
url(r'^news/', include('twobuntu.news.urls', 'news')),
Here is a snippet: <|code_start|> sitemaps = { 'home': HomePageSitemap, 'static': StaticViewSitemap, } urlpatterns = [ url(r'^$', views.index, name='home'), url(r'^about/$', views.about, name='about'), url(r'^links/$', views.links, name='links'), url(r'^feedback/$', views.feedback, name='feedback'), url(r'^join/$', views.join, name='join'), url(r'^opensearch\.xml$', views.opensearch, name='opensearch'), <|code_end|> . Write the next line using the current file imports: from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from twobuntu import views from twobuntu.feeds import LatestArticlesFeed from twobuntu.sitemaps import HomePageSitemap, StaticViewSitemap and context from other files: # Path: twobuntu/views.py # def index(request): # def commit(): # def about(request): # def links(request): # def feedback(request): # def join(request): # def opensearch(request): # def old(request, id): # # Path: twobuntu/feeds.py # class LatestArticlesFeed(ArticleFeed): # """ # Feed of most recent articles. # """ # # title = "Latest Articles on 2buntu" # link = reverse_lazy('home') # description = "Recently published articles about Ubuntu on the 2buntu blog." # # def items(self): # return Article.objects.select_related('author', 'category').filter(status=Article.PUBLISHED)[:20] # # Path: twobuntu/sitemaps.py # class HomePageSitemap(sitemaps.Sitemap): # priority = 1.0 # changefreq = 'weekly' # # def items(self): # return ['home'] # # def location(self, item): # return reverse(item) # # class StaticViewSitemap(sitemaps.Sitemap): # priority = 0.8 # changefreq = 'yearly' # # def items(self): # return ['about', 'links', 'feedback', 'join'] # # def location(self, item): # return reverse(item) , which may include functions, classes, or code. Output only the next line.
url(r'^accounts/', include('twobuntu.accounts.urls', 'accounts')),
Predict the next line after this snippet: <|code_start|> urlpatterns = [ url(r'^(?P<id>\d+)/(?:(?P<slug>[\w-]+)/)?$', views.view, name='view'), url(r'^editor/(?:(?P<id>\d+)/)?$', views.editor, name='editor'), url(r'^(?P<action>submit|publish|release)/(?P<id>\d+)/$', views.modify, name='modify'), url(r'^schedule/(?P<id>\d+)/$', views.schedule, name='schedule'), url(r'^delete/(?P<id>\d+)/$', views.delete, name='delete'), url(r'^search/$', views.search, name='search'), url(r'^markdown/$', views.markdown, name='markdown'), <|code_end|> using the current file's imports: from django.conf.urls import url from twobuntu.articles import views and any relevant context from other files: # Path: twobuntu/articles/views.py # def view(request, article): # def search(request): # def editor(request, id): # def markdown(request): # def modify(request, action, id): # def schedule(request, id): # def delete(request, id): . Output only the next line.
]
Given snippet: <|code_start|> class IspSerializer(serializers.ModelSerializer): class Meta(object): model = Isp fields = ("name", "asn") class UserSerializer(serializers.ModelSerializer): isp = IspSerializer(read_only=True) <|code_end|> , continue by predicting the next line. Consider current file imports: from rest_framework import serializers from .models import Isp, User and context: # Path: pinder/users/models.py # class Isp(models.Model): # # asn = models.PositiveIntegerField(primary_key=True) # name = models.CharField(max_length=128) # # def __str__(self): # return self.name # # class User(AbstractBaseUser, PermissionsMixin): # # USERNAME_FIELD = "email" # REQUIRED_FIELDS = ["name"] # # name = models.CharField(max_length=128) # email = models.EmailField(unique=True) # isp = models.ForeignKey(Isp) # # is_staff = models.BooleanField( # "Staff status", # default=False, # help_text="Designates whether the user can log into the admin site." # ) # is_active = models.BooleanField( # "Active", # default=True, # help_text="Designates whether this user should be treated as active." # ) # date_joined = models.DateTimeField(auto_now_add=True) # date_modified = models.DateTimeField(auto_now=True) # # objects = UserManager() # # def __str__(self): # return self.name # # def get_absolute_url(self): # return "/users/%s/" % self.asn # # def get_short_name(self): # """ # Django wants this. Not sure why. # """ # return self.asn # # def get_username(self): # """ # Required by Django to use as a key for authentication. # """ # return self.email which might include code, classes, or functions. Output only the next line.
class Meta:
Using the snippet: <|code_start|> class IspSerializer(serializers.ModelSerializer): class Meta(object): model = Isp fields = ("name", "asn") class UserSerializer(serializers.ModelSerializer): isp = IspSerializer(read_only=True) <|code_end|> , determine the next line of code. You have imports: from rest_framework import serializers from .models import Isp, User and context (class names, function names, or code) available: # Path: pinder/users/models.py # class Isp(models.Model): # # asn = models.PositiveIntegerField(primary_key=True) # name = models.CharField(max_length=128) # # def __str__(self): # return self.name # # class User(AbstractBaseUser, PermissionsMixin): # # USERNAME_FIELD = "email" # REQUIRED_FIELDS = ["name"] # # name = models.CharField(max_length=128) # email = models.EmailField(unique=True) # isp = models.ForeignKey(Isp) # # is_staff = models.BooleanField( # "Staff status", # default=False, # help_text="Designates whether the user can log into the admin site." # ) # is_active = models.BooleanField( # "Active", # default=True, # help_text="Designates whether this user should be treated as active." # ) # date_joined = models.DateTimeField(auto_now_add=True) # date_modified = models.DateTimeField(auto_now=True) # # objects = UserManager() # # def __str__(self): # return self.name # # def get_absolute_url(self): # return "/users/%s/" % self.asn # # def get_short_name(self): # """ # Django wants this. Not sure why. # """ # return self.asn # # def get_username(self): # """ # Required by Django to use as a key for authentication. # """ # return self.email . Output only the next line.
class Meta:
Using the snippet: <|code_start|> router = DefaultRouter() router.register(r'requests', RequestViewSet) urlpatterns = [ url( r"^api/auth/", include('rest_framework.urls', namespace="rest_framework") ), url(r"^api/", include(router.urls, namespace="drf")), url(r"^$", IndexView.as_view(), name="index"), url(r"^requests/$", RequestListView.as_view(), name="request-list"), <|code_end|> , determine the next line of code. You have imports: from django.conf.urls import url, include from django.contrib import admin from rest_framework.routers import DefaultRouter from peering_requests.views import ( RequestViewSet, RequestDetailView, RequestAcceptanceView, RequestListView) from users.views import LoginView from .views import IndexView and context (class names, function names, or code) available: # Path: pinder/pinder/views.py # class IndexView(TemplateView): # # template_name = "pinder/index.html" . Output only the next line.
url(
Given the following code snippet before the placeholder: <|code_start|> class IspViewSet(ModelViewSet): model = Isp queryset = Isp.objects.all() serializer_class = IspSerializer <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth import login from django.core.urlresolvers import reverse from django.views.generic import RedirectView from rest_framework.permissions import AllowAny from rest_framework.viewsets import ModelViewSet from .models import Isp, User from .serializers import IspSerializer, UserSerializer and context including class names, function names, and sometimes code from other files: # Path: pinder/users/models.py # class Isp(models.Model): # # asn = models.PositiveIntegerField(primary_key=True) # name = models.CharField(max_length=128) # # def __str__(self): # return self.name # # class User(AbstractBaseUser, PermissionsMixin): # # USERNAME_FIELD = "email" # REQUIRED_FIELDS = ["name"] # # name = models.CharField(max_length=128) # email = models.EmailField(unique=True) # isp = models.ForeignKey(Isp) # # is_staff = models.BooleanField( # "Staff status", # default=False, # help_text="Designates whether the user can log into the admin site." # ) # is_active = models.BooleanField( # "Active", # default=True, # help_text="Designates whether this user should be treated as active." # ) # date_joined = models.DateTimeField(auto_now_add=True) # date_modified = models.DateTimeField(auto_now=True) # # objects = UserManager() # # def __str__(self): # return self.name # # def get_absolute_url(self): # return "/users/%s/" % self.asn # # def get_short_name(self): # """ # Django wants this. Not sure why. # """ # return self.asn # # def get_username(self): # """ # Required by Django to use as a key for authentication. # """ # return self.email # # Path: pinder/users/serializers.py # class IspSerializer(serializers.ModelSerializer): # # class Meta(object): # model = Isp # fields = ("name", "asn") # # class UserSerializer(serializers.ModelSerializer): # # isp = IspSerializer(read_only=True) # # class Meta: # model = User # fields = ("name", "email", "isp") . Output only the next line.
permission_classes = (AllowAny,)
Predict the next line for this snippet: <|code_start|> class IspViewSet(ModelViewSet): model = Isp queryset = Isp.objects.all() serializer_class = IspSerializer permission_classes = (AllowAny,) class UserViewSet(ModelViewSet): model = User queryset = User.objects.all() serializer_class = UserSerializer <|code_end|> with the help of current file imports: from django.contrib.auth import login from django.core.urlresolvers import reverse from django.views.generic import RedirectView from rest_framework.permissions import AllowAny from rest_framework.viewsets import ModelViewSet from .models import Isp, User from .serializers import IspSerializer, UserSerializer and context from other files: # Path: pinder/users/models.py # class Isp(models.Model): # # asn = models.PositiveIntegerField(primary_key=True) # name = models.CharField(max_length=128) # # def __str__(self): # return self.name # # class User(AbstractBaseUser, PermissionsMixin): # # USERNAME_FIELD = "email" # REQUIRED_FIELDS = ["name"] # # name = models.CharField(max_length=128) # email = models.EmailField(unique=True) # isp = models.ForeignKey(Isp) # # is_staff = models.BooleanField( # "Staff status", # default=False, # help_text="Designates whether the user can log into the admin site." # ) # is_active = models.BooleanField( # "Active", # default=True, # help_text="Designates whether this user should be treated as active." # ) # date_joined = models.DateTimeField(auto_now_add=True) # date_modified = models.DateTimeField(auto_now=True) # # objects = UserManager() # # def __str__(self): # return self.name # # def get_absolute_url(self): # return "/users/%s/" % self.asn # # def get_short_name(self): # """ # Django wants this. Not sure why. # """ # return self.asn # # def get_username(self): # """ # Required by Django to use as a key for authentication. # """ # return self.email # # Path: pinder/users/serializers.py # class IspSerializer(serializers.ModelSerializer): # # class Meta(object): # model = Isp # fields = ("name", "asn") # # class UserSerializer(serializers.ModelSerializer): # # isp = IspSerializer(read_only=True) # # class Meta: # model = User # fields = ("name", "email", "isp") , which may contain function names, class names, or code. Output only the next line.
permission_classes = (AllowAny,)
Given snippet: <|code_start|> class IspViewSet(ModelViewSet): model = Isp queryset = Isp.objects.all() serializer_class = IspSerializer permission_classes = (AllowAny,) class UserViewSet(ModelViewSet): model = User queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) class LoginView(RedirectView): def get_redirect_url(self, *args, **kwargs): login(self.request, User.objects.get(pk=2)) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib.auth import login from django.core.urlresolvers import reverse from django.views.generic import RedirectView from rest_framework.permissions import AllowAny from rest_framework.viewsets import ModelViewSet from .models import Isp, User from .serializers import IspSerializer, UserSerializer and context: # Path: pinder/users/models.py # class Isp(models.Model): # # asn = models.PositiveIntegerField(primary_key=True) # name = models.CharField(max_length=128) # # def __str__(self): # return self.name # # class User(AbstractBaseUser, PermissionsMixin): # # USERNAME_FIELD = "email" # REQUIRED_FIELDS = ["name"] # # name = models.CharField(max_length=128) # email = models.EmailField(unique=True) # isp = models.ForeignKey(Isp) # # is_staff = models.BooleanField( # "Staff status", # default=False, # help_text="Designates whether the user can log into the admin site." # ) # is_active = models.BooleanField( # "Active", # default=True, # help_text="Designates whether this user should be treated as active." # ) # date_joined = models.DateTimeField(auto_now_add=True) # date_modified = models.DateTimeField(auto_now=True) # # objects = UserManager() # # def __str__(self): # return self.name # # def get_absolute_url(self): # return "/users/%s/" % self.asn # # def get_short_name(self): # """ # Django wants this. Not sure why. # """ # return self.asn # # def get_username(self): # """ # Required by Django to use as a key for authentication. # """ # return self.email # # Path: pinder/users/serializers.py # class IspSerializer(serializers.ModelSerializer): # # class Meta(object): # model = Isp # fields = ("name", "asn") # # class UserSerializer(serializers.ModelSerializer): # # isp = IspSerializer(read_only=True) # # class Meta: # model = User # fields = ("name", "email", "isp") which might include code, classes, or functions. Output only the next line.
return reverse("index")
Here is a snippet: <|code_start|> class IspViewSet(ModelViewSet): model = Isp queryset = Isp.objects.all() serializer_class = IspSerializer permission_classes = (AllowAny,) class UserViewSet(ModelViewSet): model = User queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) <|code_end|> . Write the next line using the current file imports: from django.contrib.auth import login from django.core.urlresolvers import reverse from django.views.generic import RedirectView from rest_framework.permissions import AllowAny from rest_framework.viewsets import ModelViewSet from .models import Isp, User from .serializers import IspSerializer, UserSerializer and context from other files: # Path: pinder/users/models.py # class Isp(models.Model): # # asn = models.PositiveIntegerField(primary_key=True) # name = models.CharField(max_length=128) # # def __str__(self): # return self.name # # class User(AbstractBaseUser, PermissionsMixin): # # USERNAME_FIELD = "email" # REQUIRED_FIELDS = ["name"] # # name = models.CharField(max_length=128) # email = models.EmailField(unique=True) # isp = models.ForeignKey(Isp) # # is_staff = models.BooleanField( # "Staff status", # default=False, # help_text="Designates whether the user can log into the admin site." # ) # is_active = models.BooleanField( # "Active", # default=True, # help_text="Designates whether this user should be treated as active." # ) # date_joined = models.DateTimeField(auto_now_add=True) # date_modified = models.DateTimeField(auto_now=True) # # objects = UserManager() # # def __str__(self): # return self.name # # def get_absolute_url(self): # return "/users/%s/" % self.asn # # def get_short_name(self): # """ # Django wants this. Not sure why. # """ # return self.asn # # def get_username(self): # """ # Required by Django to use as a key for authentication. # """ # return self.email # # Path: pinder/users/serializers.py # class IspSerializer(serializers.ModelSerializer): # # class Meta(object): # model = Isp # fields = ("name", "asn") # # class UserSerializer(serializers.ModelSerializer): # # isp = IspSerializer(read_only=True) # # class Meta: # model = User # fields = ("name", "email", "isp") , which may include functions, classes, or code. Output only the next line.
class LoginView(RedirectView):
Based on the snippet: <|code_start|> class StandardPagination(PageNumberPagination): page_size = 25 page_size_query_param = "page-size" max_page_size = 100000 class RequestViewSet(ModelViewSet): model = Request queryset = Request.objects.all() serializer_class = RequestSerializer pagination_class = StandardPagination permission_classes = (AllowAny,) filter_backends = (DjangoFilterBackend, filters.OrderingFilter) filter_class = RequestFilterSet ordering_fields = ("sender", "receiver", "created", "modified") renderer_classes = (JSONRenderer, BrowsableAPIRenderer) <|code_end|> , predict the immediate next line with the help of imports: from django.views.generic import DetailView, ListView from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import AllowAny from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer from rest_framework.viewsets import ModelViewSet from .models import Request from .serializers import RequestSerializer, PostRequestSerializer from .filters import RequestFilterSet and context (classes, functions, sometimes code) from other files: # Path: pinder/peering_requests/models.py # class Request(models.Model): # # STATE_WAITING = "waiting" # STATE_IN_PROGRESS = "in-progress" # STATE_HOLD = "hold" # STATE_REJECTED = "rejected" # STATE_FINISHED = "finished" # # STATES = ( # (STATE_WAITING, "Waiting"), # (STATE_IN_PROGRESS, "In Progress"), # (STATE_HOLD, "On Hold"), # (STATE_REJECTED, "Rejected"), # (STATE_FINISHED, "Finished"), # ) # # sender = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name="requests_received") # receiver = models.ForeignKey("users.Isp", related_name="requests_sent") # ixlan_id = models.PositiveIntegerField() # # state = models.CharField( # choices=STATES, default=STATE_WAITING, max_length=8) # # sender_is_ready = models.BooleanField(default=False) # receiver_is_ready = models.BooleanField(default=False) # # created = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # # def __str__(self): # return "Peering request from {} to {}".format( # self.sender, self.receiver) # # Path: pinder/peering_requests/serializers.py # class RequestSerializer(serializers.ModelSerializer): # # sender = UserSerializer(read_only=True) # receiver = IspSerializer(read_only=True) # # class Meta(object): # model = Request # fields = ( # "id", # "sender", # "receiver", # "ixlan_id", # "state", # "sender_is_ready", # "receiver_is_ready", # "created", # "modified" # ) # # class PostRequestSerializer(serializers.ModelSerializer): # # class Meta(object): # model = Request # fields = ( # "id", # "sender", # "receiver", # "ixlan_id", # ) # # Path: pinder/peering_requests/filters.py # class RequestFilterSet(django_filters.FilterSet): # # class Meta: # model = Request # fields = ( # "state", # "sender_is_ready", # "receiver_is_ready", # "ixlan_id" # ) . Output only the next line.
def get_serializer_class(self, *args, **kwargs):
Predict the next line after this snippet: <|code_start|> class StandardPagination(PageNumberPagination): page_size = 25 page_size_query_param = "page-size" max_page_size = 100000 class RequestViewSet(ModelViewSet): model = Request queryset = Request.objects.all() serializer_class = RequestSerializer pagination_class = StandardPagination permission_classes = (AllowAny,) filter_backends = (DjangoFilterBackend, filters.OrderingFilter) filter_class = RequestFilterSet ordering_fields = ("sender", "receiver", "created", "modified") renderer_classes = (JSONRenderer, BrowsableAPIRenderer) def get_serializer_class(self, *args, **kwargs): if self.request.method == "POST": return PostRequestSerializer return RequestSerializer <|code_end|> using the current file's imports: from django.views.generic import DetailView, ListView from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import AllowAny from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer from rest_framework.viewsets import ModelViewSet from .models import Request from .serializers import RequestSerializer, PostRequestSerializer from .filters import RequestFilterSet and any relevant context from other files: # Path: pinder/peering_requests/models.py # class Request(models.Model): # # STATE_WAITING = "waiting" # STATE_IN_PROGRESS = "in-progress" # STATE_HOLD = "hold" # STATE_REJECTED = "rejected" # STATE_FINISHED = "finished" # # STATES = ( # (STATE_WAITING, "Waiting"), # (STATE_IN_PROGRESS, "In Progress"), # (STATE_HOLD, "On Hold"), # (STATE_REJECTED, "Rejected"), # (STATE_FINISHED, "Finished"), # ) # # sender = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name="requests_received") # receiver = models.ForeignKey("users.Isp", related_name="requests_sent") # ixlan_id = models.PositiveIntegerField() # # state = models.CharField( # choices=STATES, default=STATE_WAITING, max_length=8) # # sender_is_ready = models.BooleanField(default=False) # receiver_is_ready = models.BooleanField(default=False) # # created = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # # def __str__(self): # return "Peering request from {} to {}".format( # self.sender, self.receiver) # # Path: pinder/peering_requests/serializers.py # class RequestSerializer(serializers.ModelSerializer): # # sender = UserSerializer(read_only=True) # receiver = IspSerializer(read_only=True) # # class Meta(object): # model = Request # fields = ( # "id", # "sender", # "receiver", # "ixlan_id", # "state", # "sender_is_ready", # "receiver_is_ready", # "created", # "modified" # ) # # class PostRequestSerializer(serializers.ModelSerializer): # # class Meta(object): # model = Request # fields = ( # "id", # "sender", # "receiver", # "ixlan_id", # ) # # Path: pinder/peering_requests/filters.py # class RequestFilterSet(django_filters.FilterSet): # # class Meta: # model = Request # fields = ( # "state", # "sender_is_ready", # "receiver_is_ready", # "ixlan_id" # ) . Output only the next line.
class RequestListView(ListView):
Predict the next line for this snippet: <|code_start|> class RequestSerializer(serializers.ModelSerializer): sender = UserSerializer(read_only=True) receiver = IspSerializer(read_only=True) class Meta(object): model = Request fields = ( "id", "sender", "receiver", "ixlan_id", "state", "sender_is_ready", "receiver_is_ready", <|code_end|> with the help of current file imports: from rest_framework import serializers from users.serializers import IspSerializer, UserSerializer from .models import Request and context from other files: # Path: pinder/peering_requests/models.py # class Request(models.Model): # # STATE_WAITING = "waiting" # STATE_IN_PROGRESS = "in-progress" # STATE_HOLD = "hold" # STATE_REJECTED = "rejected" # STATE_FINISHED = "finished" # # STATES = ( # (STATE_WAITING, "Waiting"), # (STATE_IN_PROGRESS, "In Progress"), # (STATE_HOLD, "On Hold"), # (STATE_REJECTED, "Rejected"), # (STATE_FINISHED, "Finished"), # ) # # sender = models.ForeignKey( # settings.AUTH_USER_MODEL, related_name="requests_received") # receiver = models.ForeignKey("users.Isp", related_name="requests_sent") # ixlan_id = models.PositiveIntegerField() # # state = models.CharField( # choices=STATES, default=STATE_WAITING, max_length=8) # # sender_is_ready = models.BooleanField(default=False) # receiver_is_ready = models.BooleanField(default=False) # # created = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # # def __str__(self): # return "Peering request from {} to {}".format( # self.sender, self.receiver) , which may contain function names, class names, or code. Output only the next line.
"created",
Based on the snippet: <|code_start|> app_name = "users" urlpatterns = [ path("", view=user_list_view, name="list"), path("~redirect/", view=user_redirect_view, name="redirect"), path("~update/", view=user_update_view, name="update"), path("<str:username>/", view=user_detail_view, name="detail"), <|code_end|> , predict the immediate next line with the help of imports: from django.urls import path from pyfreebilling.users.views import ( user_list_view, user_redirect_view, user_update_view, user_detail_view, ) and context (classes, functions, sometimes code) from other files: # Path: pyfreebilling/users/views.py # class UserDetailView(LoginRequiredMixin, DetailView): # class UserListView(LoginRequiredMixin, ListView): # class UserUpdateView(LoginRequiredMixin, UpdateView): # class UserRedirectView(LoginRequiredMixin, RedirectView): # def get_success_url(self): # def get_object(self): # def form_valid(self, form): # def get_redirect_url(self): . Output only the next line.
]
Based on the snippet: <|code_start|> app_name = "users" urlpatterns = [ path("", view=user_list_view, name="list"), path("~redirect/", view=user_redirect_view, name="redirect"), path("~update/", view=user_update_view, name="update"), path("<str:username>/", view=user_detail_view, name="detail"), <|code_end|> , predict the immediate next line with the help of imports: from django.urls import path from pyfreebilling.users.views import ( user_list_view, user_redirect_view, user_update_view, user_detail_view, ) and context (classes, functions, sometimes code) from other files: # Path: pyfreebilling/users/views.py # class UserDetailView(LoginRequiredMixin, DetailView): # class UserListView(LoginRequiredMixin, ListView): # class UserUpdateView(LoginRequiredMixin, UpdateView): # class UserRedirectView(LoginRequiredMixin, RedirectView): # def get_success_url(self): # def get_object(self): # def form_valid(self, form): # def get_redirect_url(self): . Output only the next line.
]
Given the code snippet: <|code_start|> class DestinationForm(forms.ModelForm): class Meta: model = Destination fields = ['name', 'country_iso2', 'carrier', 'type'] class PrefixForm(forms.ModelForm): class Meta: model = Prefix fields = ['prefix', 'destination'] class CarrierForm(forms.ModelForm): class Meta: model = Carrier <|code_end|> , generate the next line using the imports in this file: from django import forms from .models import Destination, Prefix, Carrier, Region, Country, Type and context (functions, classes, or occasionally code) from other files: # Path: pyfreebilling/direction/models.py # class Destination(models.Model): # # # Fields # name = models.CharField(_(u"name of destination"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # country_iso2 = CountryField(_(u"country"), blank=True) # # # Relationship Fields # carrier = models.ForeignKey(Carrier, # verbose_name=_(u"carrier"), on_delete=models.PROTECT # ) # type = models.ForeignKey(Type, # verbose_name=_(u"Type of destination"), on_delete=models.PROTECT # ) # # class Meta: # db_table = 'dest_destination' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_destination_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_destination_update', args=(self.slug,)) # # class Prefix(models.Model): # # # Fields # prefix = models.CharField(_(u"prefix"), unique=True, max_length=15, help_text=_(u"International public telecommunication prefix (maximum 15 digits)")) # slug = extension_fields.AutoSlugField(populate_from='prefix', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # Relationship Fields # destination = models.ForeignKey(Destination, # verbose_name=_(u"destination"), on_delete=models.PROTECT, # ) # # class Meta: # db_table = 'dest_prefix' # app_label = 'direction' # ordering = ('prefix',) # # def __unicode__(self): # return u'%s' % self.prefix # # def get_absolute_url(self): # return reverse('direction_prefix_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_prefix_update', args=(self.slug,)) # # class Carrier(models.Model): # # # Fields # name = models.CharField(_(u"carrier name"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # class Meta: # db_table = 'dest_carrier' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_carrier_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_carrier_update', args=(self.slug,)) # # class Region(models.Model): # # # Fields # name = models.CharField(_(u"region name"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # class Meta: # db_table = 'dest_region' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_region_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_region_update', args=(self.slug,)) # # class Country(models.Model): # # # Fields # country_iso2 = CountryField(_(u"country"), unique=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # Relationship Fields # region = models.ForeignKey(Region, # verbose_name=_(u"region"), on_delete=models.SET_NULL, blank=True, null=True, # ) # # class Meta: # db_table = 'dest_country' # app_label = 'direction' # ordering = ('country_iso2',) # # def __unicode__(self): # return u'%s' % self.pk # # def get_absolute_url(self): # return reverse('direction_country_detail', args=(self.pk,)) # # def get_update_url(self): # return reverse('direction_country_update', args=(self.pk,)) # # class Type(models.Model): # # # Fields # name = models.CharField(_(u"type of destination"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # class Meta: # db_table = 'dest_type' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_type_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_type_update', args=(self.slug,)) . Output only the next line.
fields = ['name']
Here is a snippet: <|code_start|> class DestinationForm(forms.ModelForm): class Meta: model = Destination fields = ['name', 'country_iso2', 'carrier', 'type'] class PrefixForm(forms.ModelForm): class Meta: model = Prefix fields = ['prefix', 'destination'] class CarrierForm(forms.ModelForm): class Meta: model = Carrier fields = ['name'] <|code_end|> . Write the next line using the current file imports: from django import forms from .models import Destination, Prefix, Carrier, Region, Country, Type and context from other files: # Path: pyfreebilling/direction/models.py # class Destination(models.Model): # # # Fields # name = models.CharField(_(u"name of destination"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # country_iso2 = CountryField(_(u"country"), blank=True) # # # Relationship Fields # carrier = models.ForeignKey(Carrier, # verbose_name=_(u"carrier"), on_delete=models.PROTECT # ) # type = models.ForeignKey(Type, # verbose_name=_(u"Type of destination"), on_delete=models.PROTECT # ) # # class Meta: # db_table = 'dest_destination' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_destination_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_destination_update', args=(self.slug,)) # # class Prefix(models.Model): # # # Fields # prefix = models.CharField(_(u"prefix"), unique=True, max_length=15, help_text=_(u"International public telecommunication prefix (maximum 15 digits)")) # slug = extension_fields.AutoSlugField(populate_from='prefix', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # Relationship Fields # destination = models.ForeignKey(Destination, # verbose_name=_(u"destination"), on_delete=models.PROTECT, # ) # # class Meta: # db_table = 'dest_prefix' # app_label = 'direction' # ordering = ('prefix',) # # def __unicode__(self): # return u'%s' % self.prefix # # def get_absolute_url(self): # return reverse('direction_prefix_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_prefix_update', args=(self.slug,)) # # class Carrier(models.Model): # # # Fields # name = models.CharField(_(u"carrier name"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # class Meta: # db_table = 'dest_carrier' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_carrier_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_carrier_update', args=(self.slug,)) # # class Region(models.Model): # # # Fields # name = models.CharField(_(u"region name"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # class Meta: # db_table = 'dest_region' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_region_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_region_update', args=(self.slug,)) # # class Country(models.Model): # # # Fields # country_iso2 = CountryField(_(u"country"), unique=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # Relationship Fields # region = models.ForeignKey(Region, # verbose_name=_(u"region"), on_delete=models.SET_NULL, blank=True, null=True, # ) # # class Meta: # db_table = 'dest_country' # app_label = 'direction' # ordering = ('country_iso2',) # # def __unicode__(self): # return u'%s' % self.pk # # def get_absolute_url(self): # return reverse('direction_country_detail', args=(self.pk,)) # # def get_update_url(self): # return reverse('direction_country_update', args=(self.pk,)) # # class Type(models.Model): # # # Fields # name = models.CharField(_(u"type of destination"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # class Meta: # db_table = 'dest_type' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_type_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_type_update', args=(self.slug,)) , which may include functions, classes, or code. Output only the next line.
class RegionForm(forms.ModelForm):
Continue the code snippet: <|code_start|> class DestinationForm(forms.ModelForm): class Meta: model = Destination fields = ['name', 'country_iso2', 'carrier', 'type'] class PrefixForm(forms.ModelForm): <|code_end|> . Use current file imports: from django import forms from .models import Destination, Prefix, Carrier, Region, Country, Type and context (classes, functions, or code) from other files: # Path: pyfreebilling/direction/models.py # class Destination(models.Model): # # # Fields # name = models.CharField(_(u"name of destination"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # country_iso2 = CountryField(_(u"country"), blank=True) # # # Relationship Fields # carrier = models.ForeignKey(Carrier, # verbose_name=_(u"carrier"), on_delete=models.PROTECT # ) # type = models.ForeignKey(Type, # verbose_name=_(u"Type of destination"), on_delete=models.PROTECT # ) # # class Meta: # db_table = 'dest_destination' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_destination_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_destination_update', args=(self.slug,)) # # class Prefix(models.Model): # # # Fields # prefix = models.CharField(_(u"prefix"), unique=True, max_length=15, help_text=_(u"International public telecommunication prefix (maximum 15 digits)")) # slug = extension_fields.AutoSlugField(populate_from='prefix', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # Relationship Fields # destination = models.ForeignKey(Destination, # verbose_name=_(u"destination"), on_delete=models.PROTECT, # ) # # class Meta: # db_table = 'dest_prefix' # app_label = 'direction' # ordering = ('prefix',) # # def __unicode__(self): # return u'%s' % self.prefix # # def get_absolute_url(self): # return reverse('direction_prefix_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_prefix_update', args=(self.slug,)) # # class Carrier(models.Model): # # # Fields # name = models.CharField(_(u"carrier name"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # class Meta: # db_table = 'dest_carrier' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_carrier_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_carrier_update', args=(self.slug,)) # # class Region(models.Model): # # # Fields # name = models.CharField(_(u"region name"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # class Meta: # db_table = 'dest_region' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_region_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_region_update', args=(self.slug,)) # # class Country(models.Model): # # # Fields # country_iso2 = CountryField(_(u"country"), unique=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # Relationship Fields # region = models.ForeignKey(Region, # verbose_name=_(u"region"), on_delete=models.SET_NULL, blank=True, null=True, # ) # # class Meta: # db_table = 'dest_country' # app_label = 'direction' # ordering = ('country_iso2',) # # def __unicode__(self): # return u'%s' % self.pk # # def get_absolute_url(self): # return reverse('direction_country_detail', args=(self.pk,)) # # def get_update_url(self): # return reverse('direction_country_update', args=(self.pk,)) # # class Type(models.Model): # # # Fields # name = models.CharField(_(u"type of destination"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # class Meta: # db_table = 'dest_type' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_type_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_type_update', args=(self.slug,)) . Output only the next line.
class Meta:
Here is a snippet: <|code_start|> class DestinationForm(forms.ModelForm): class Meta: model = Destination fields = ['name', 'country_iso2', 'carrier', 'type'] class PrefixForm(forms.ModelForm): class Meta: model = Prefix fields = ['prefix', 'destination'] class CarrierForm(forms.ModelForm): <|code_end|> . Write the next line using the current file imports: from django import forms from .models import Destination, Prefix, Carrier, Region, Country, Type and context from other files: # Path: pyfreebilling/direction/models.py # class Destination(models.Model): # # # Fields # name = models.CharField(_(u"name of destination"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # country_iso2 = CountryField(_(u"country"), blank=True) # # # Relationship Fields # carrier = models.ForeignKey(Carrier, # verbose_name=_(u"carrier"), on_delete=models.PROTECT # ) # type = models.ForeignKey(Type, # verbose_name=_(u"Type of destination"), on_delete=models.PROTECT # ) # # class Meta: # db_table = 'dest_destination' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_destination_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_destination_update', args=(self.slug,)) # # class Prefix(models.Model): # # # Fields # prefix = models.CharField(_(u"prefix"), unique=True, max_length=15, help_text=_(u"International public telecommunication prefix (maximum 15 digits)")) # slug = extension_fields.AutoSlugField(populate_from='prefix', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # Relationship Fields # destination = models.ForeignKey(Destination, # verbose_name=_(u"destination"), on_delete=models.PROTECT, # ) # # class Meta: # db_table = 'dest_prefix' # app_label = 'direction' # ordering = ('prefix',) # # def __unicode__(self): # return u'%s' % self.prefix # # def get_absolute_url(self): # return reverse('direction_prefix_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_prefix_update', args=(self.slug,)) # # class Carrier(models.Model): # # # Fields # name = models.CharField(_(u"carrier name"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # class Meta: # db_table = 'dest_carrier' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_carrier_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_carrier_update', args=(self.slug,)) # # class Region(models.Model): # # # Fields # name = models.CharField(_(u"region name"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # class Meta: # db_table = 'dest_region' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_region_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_region_update', args=(self.slug,)) # # class Country(models.Model): # # # Fields # country_iso2 = CountryField(_(u"country"), unique=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # Relationship Fields # region = models.ForeignKey(Region, # verbose_name=_(u"region"), on_delete=models.SET_NULL, blank=True, null=True, # ) # # class Meta: # db_table = 'dest_country' # app_label = 'direction' # ordering = ('country_iso2',) # # def __unicode__(self): # return u'%s' % self.pk # # def get_absolute_url(self): # return reverse('direction_country_detail', args=(self.pk,)) # # def get_update_url(self): # return reverse('direction_country_update', args=(self.pk,)) # # class Type(models.Model): # # # Fields # name = models.CharField(_(u"type of destination"), max_length=255, unique=True) # slug = extension_fields.AutoSlugField(populate_from='name', blank=True) # created = models.DateTimeField(auto_now_add=True, editable=False) # last_updated = models.DateTimeField(auto_now=True, editable=False) # # # class Meta: # db_table = 'dest_type' # app_label = 'direction' # ordering = ('name',) # # def __unicode__(self): # return u'%s' % self.name # # def get_absolute_url(self): # return reverse('direction_type_detail', args=(self.slug,)) # # def get_update_url(self): # return reverse('direction_type_update', args=(self.slug,)) , which may include functions, classes, or code. Output only the next line.
class Meta:
Here is a snippet: <|code_start|># this plugin does a very simple display of download progress. to use it, add # @downloads to your status_format. try: except ImportError: class Downloads(PerInstancePlugin): CONFIG_SECTION = 'downloads' def __init__(self, uzbl): super(Downloads, self).__init__(uzbl) uzbl.connect('DOWNLOAD_STARTED', self.download_started) uzbl.connect('DOWNLOAD_PROGRESS', self.download_progress) uzbl.connect('DOWNLOAD_COMPLETE', self.download_complete) <|code_end|> . Write the next line using the current file imports: import os from html import escape from cgi import escape from uzbl.arguments import splitquoted from .config import Config from uzbl.ext import PerInstancePlugin and context from other files: # Path: uzbl/arguments.py # def match(s): # def lex(s): # def parse(l): # def __new__(cls, s): # def raw(self, frm=0, to=None): # def safe_raw(self, frm=0, to=None): # def is_quoted(s): # def unquote(s): # class Arguments(tuple): # # Path: uzbl/plugins/config.py # class Config(PerInstancePlugin): # """Configuration plugin, has dictionary interface for config access # # This class is currenty not inherited from either UserDict or abc.Mapping # because not sure what version of python we want to support. It's not # hard to implement all needed methods either. # """ # # CONFIG_SECTION = 'config' # # def __init__(self, uzbl): # super(Config, self).__init__(uzbl) # # self.data = {} # uzbl.connect('VARIABLE_SET', self.parse_set_event) # assert not 'a' in self.data # # def __getitem__(self, key): # return self.data[key] # # def __setitem__(self, key, value): # self.set(key, value) # # def __delitem__(self, key): # self.set(key) # # def get(self, key, default=None): # return self.data.get(key, default) # # def __contains__(self, key): # return key in self.data # # def keys(self): # return iter(self.data.keys()) # # def items(self): # return iter(self.data.items()) # # def update(self, other=None, **kwargs): # if other is None: # other = {} # # for (key, value) in list(dict(other).items()) + list(kwargs.items()): # self[key] = value # # # def set(self, key, value='', force=False): # '''Generates a `set <key> <value>` command string to send to the # current uzbl instance. # # Note that the config dict isn't updated by this function. The config # dict is only updated after a successful `VARIABLE_SET ..` event # returns from the uzbl instance.''' # # assert valid_key(key) # # if isinstance(value, bool): # value = int(value) # # else: # value = str(value) # assert '\n' not in value # # if not force and key in self and self[key] == value: # return # # self.uzbl.send('set %s %s' % (key, value)) # # # def parse_set_event(self, args): # '''Parse `VARIABLE_SET <var> <type> <value>` event and load the # (key, value) pair into the `uzbl.config` dict.''' # # args = splitquoted(args) # if len(args) == 2: # key, type, raw_value = args[0], args[1], '' # elif len(args) == 3: # key, type, raw_value = args # else: # raise Exception('Invalid number of arguments') # # assert valid_key(key) # assert type in types # # new_value = types[type](raw_value) # old_value = self.data.get(key, None) # # # Update new value. # self.data[key] = new_value # # if old_value != new_value: # self.uzbl.event('CONFIG_CHANGED', key, new_value) # # # Cleanup null config values. # if type == 'str' and not new_value: # del self.data[key] # # def cleanup(self): # # not sure it's needed, but safer for cyclic links # self.data.clear() # super(Config, self).cleanup() # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] , which may include functions, classes, or code. Output only the next line.
self.active_downloads = {}
Using the snippet: <|code_start|># this plugin does a very simple display of download progress. to use it, add # @downloads to your status_format. try: except ImportError: class Downloads(PerInstancePlugin): CONFIG_SECTION = 'downloads' def __init__(self, uzbl): <|code_end|> , determine the next line of code. You have imports: import os from html import escape from cgi import escape from uzbl.arguments import splitquoted from .config import Config from uzbl.ext import PerInstancePlugin and context (class names, function names, or code) available: # Path: uzbl/arguments.py # def match(s): # def lex(s): # def parse(l): # def __new__(cls, s): # def raw(self, frm=0, to=None): # def safe_raw(self, frm=0, to=None): # def is_quoted(s): # def unquote(s): # class Arguments(tuple): # # Path: uzbl/plugins/config.py # class Config(PerInstancePlugin): # """Configuration plugin, has dictionary interface for config access # # This class is currenty not inherited from either UserDict or abc.Mapping # because not sure what version of python we want to support. It's not # hard to implement all needed methods either. # """ # # CONFIG_SECTION = 'config' # # def __init__(self, uzbl): # super(Config, self).__init__(uzbl) # # self.data = {} # uzbl.connect('VARIABLE_SET', self.parse_set_event) # assert not 'a' in self.data # # def __getitem__(self, key): # return self.data[key] # # def __setitem__(self, key, value): # self.set(key, value) # # def __delitem__(self, key): # self.set(key) # # def get(self, key, default=None): # return self.data.get(key, default) # # def __contains__(self, key): # return key in self.data # # def keys(self): # return iter(self.data.keys()) # # def items(self): # return iter(self.data.items()) # # def update(self, other=None, **kwargs): # if other is None: # other = {} # # for (key, value) in list(dict(other).items()) + list(kwargs.items()): # self[key] = value # # # def set(self, key, value='', force=False): # '''Generates a `set <key> <value>` command string to send to the # current uzbl instance. # # Note that the config dict isn't updated by this function. The config # dict is only updated after a successful `VARIABLE_SET ..` event # returns from the uzbl instance.''' # # assert valid_key(key) # # if isinstance(value, bool): # value = int(value) # # else: # value = str(value) # assert '\n' not in value # # if not force and key in self and self[key] == value: # return # # self.uzbl.send('set %s %s' % (key, value)) # # # def parse_set_event(self, args): # '''Parse `VARIABLE_SET <var> <type> <value>` event and load the # (key, value) pair into the `uzbl.config` dict.''' # # args = splitquoted(args) # if len(args) == 2: # key, type, raw_value = args[0], args[1], '' # elif len(args) == 3: # key, type, raw_value = args # else: # raise Exception('Invalid number of arguments') # # assert valid_key(key) # assert type in types # # new_value = types[type](raw_value) # old_value = self.data.get(key, None) # # # Update new value. # self.data[key] = new_value # # if old_value != new_value: # self.uzbl.event('CONFIG_CHANGED', key, new_value) # # # Cleanup null config values. # if type == 'str' and not new_value: # del self.data[key] # # def cleanup(self): # # not sure it's needed, but safer for cyclic links # self.data.clear() # super(Config, self).cleanup() # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] . Output only the next line.
super(Downloads, self).__init__(uzbl)
Using the snippet: <|code_start|> '''Generates a `set <key> <value>` command string to send to the current uzbl instance. Note that the config dict isn't updated by this function. The config dict is only updated after a successful `VARIABLE_SET ..` event returns from the uzbl instance.''' assert valid_key(key) if isinstance(value, bool): value = int(value) else: value = str(value) assert '\n' not in value if not force and key in self and self[key] == value: return self.uzbl.send('set %s %s' % (key, value)) def parse_set_event(self, args): '''Parse `VARIABLE_SET <var> <type> <value>` event and load the (key, value) pair into the `uzbl.config` dict.''' args = splitquoted(args) if len(args) == 2: key, type, raw_value = args[0], args[1], '' elif len(args) == 3: <|code_end|> , determine the next line of code. You have imports: from re import compile from uzbl.arguments import splitquoted from uzbl.ext import PerInstancePlugin and context (class names, function names, or code) available: # Path: uzbl/arguments.py # def match(s): # def lex(s): # def parse(l): # def __new__(cls, s): # def raw(self, frm=0, to=None): # def safe_raw(self, frm=0, to=None): # def is_quoted(s): # def unquote(s): # class Arguments(tuple): # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] . Output only the next line.
key, type, raw_value = args
Using the snippet: <|code_start|> Note that the config dict isn't updated by this function. The config dict is only updated after a successful `VARIABLE_SET ..` event returns from the uzbl instance.''' assert valid_key(key) if isinstance(value, bool): value = int(value) else: value = str(value) assert '\n' not in value if not force and key in self and self[key] == value: return self.uzbl.send('set %s %s' % (key, value)) def parse_set_event(self, args): '''Parse `VARIABLE_SET <var> <type> <value>` event and load the (key, value) pair into the `uzbl.config` dict.''' args = splitquoted(args) if len(args) == 2: key, type, raw_value = args[0], args[1], '' elif len(args) == 3: key, type, raw_value = args else: <|code_end|> , determine the next line of code. You have imports: from re import compile from uzbl.arguments import splitquoted from uzbl.ext import PerInstancePlugin and context (class names, function names, or code) available: # Path: uzbl/arguments.py # def match(s): # def lex(s): # def parse(l): # def __new__(cls, s): # def raw(self, frm=0, to=None): # def safe_raw(self, frm=0, to=None): # def is_quoted(s): # def unquote(s): # class Arguments(tuple): # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] . Output only the next line.
raise Exception('Invalid number of arguments')
Next line prediction: <|code_start|> def setUp(self): self.event_manager = EventManagerMock( (SharedHistory,), (OnSetPlugin, KeyCmd, Config, History) ) self.uzbl = self.event_manager.add() self.other = self.event_manager.add() s = SharedHistory[self.uzbl] data = ( ('', 'woop'), ('', 'doop'), ('', 'bar'), ('', 'foo'), ('git', 'spam'), ('git', 'egg'), ('foo', 'foo') ) for prompt, input in data: s.addline(prompt, input) def test_step(self): h = History[self.uzbl] self.assertEqual('', next(h)) self.assertEqual('', next(h)) self.assertEqual('foo', h.prev()) self.assertEqual('bar', h.prev()) self.assertEqual('foo', next(h)) self.assertEqual('bar', h.prev()) self.assertEqual('doop', h.prev()) self.assertEqual('woop', h.prev()) <|code_end|> . Use current file imports: (import sys import unittest from emtest import EventManagerMock from six import next from uzbl.plugins.history import History, SharedHistory from uzbl.plugins.keycmd import Keylet, KeyCmd from uzbl.plugins.on_set import OnSetPlugin from uzbl.plugins.config import Config) and context including class names, function names, or small code snippets from other files: # Path: uzbl/plugins/config.py # class Config(PerInstancePlugin): # """Configuration plugin, has dictionary interface for config access # # This class is currenty not inherited from either UserDict or abc.Mapping # because not sure what version of python we want to support. It's not # hard to implement all needed methods either. # """ # # CONFIG_SECTION = 'config' # # def __init__(self, uzbl): # super(Config, self).__init__(uzbl) # # self.data = {} # uzbl.connect('VARIABLE_SET', self.parse_set_event) # assert not 'a' in self.data # # def __getitem__(self, key): # return self.data[key] # # def __setitem__(self, key, value): # self.set(key, value) # # def __delitem__(self, key): # self.set(key) # # def get(self, key, default=None): # return self.data.get(key, default) # # def __contains__(self, key): # return key in self.data # # def keys(self): # return iter(self.data.keys()) # # def items(self): # return iter(self.data.items()) # # def update(self, other=None, **kwargs): # if other is None: # other = {} # # for (key, value) in list(dict(other).items()) + list(kwargs.items()): # self[key] = value # # # def set(self, key, value='', force=False): # '''Generates a `set <key> <value>` command string to send to the # current uzbl instance. # # Note that the config dict isn't updated by this function. The config # dict is only updated after a successful `VARIABLE_SET ..` event # returns from the uzbl instance.''' # # assert valid_key(key) # # if isinstance(value, bool): # value = int(value) # # else: # value = str(value) # assert '\n' not in value # # if not force and key in self and self[key] == value: # return # # self.uzbl.send('set %s %s' % (key, value)) # # # def parse_set_event(self, args): # '''Parse `VARIABLE_SET <var> <type> <value>` event and load the # (key, value) pair into the `uzbl.config` dict.''' # # args = splitquoted(args) # if len(args) == 2: # key, type, raw_value = args[0], args[1], '' # elif len(args) == 3: # key, type, raw_value = args # else: # raise Exception('Invalid number of arguments') # # assert valid_key(key) # assert type in types # # new_value = types[type](raw_value) # old_value = self.data.get(key, None) # # # Update new value. # self.data[key] = new_value # # if old_value != new_value: # self.uzbl.event('CONFIG_CHANGED', key, new_value) # # # Cleanup null config values. # if type == 'str' and not new_value: # del self.data[key] # # def cleanup(self): # # not sure it's needed, but safer for cyclic links # self.data.clear() # super(Config, self).cleanup() . Output only the next line.
self.assertTrue(len(h.prev()) > 0)
Based on the snippet: <|code_start|> def test_escape(): cases = [ ("c'thulu", "'c\\'thulu'"), ("'compli\\'cated'", "'\\'compli\\\\\\'cated\\''"), ] <|code_end|> , predict the immediate next line with the help of imports: from uzbl.plugins.cmd_expand import cmd_expand and context (classes, functions, sometimes code) from other files: # Path: uzbl/plugins/cmd_expand.py # def cmd_expand(cmd, args): # '''Exports a function that provides the following # expansions in any uzbl command string: # # %s = replace('%s', ' '.join(args)) # %r = replace('%r', "'%s'" % escaped(' '.join(args))) # %1 = replace('%1', arg[0]) # %2 = replace('%2', arg[1]) # %n = replace('%n', arg[n-1]) # ''' # # # Ensure (1) all string representable and (2) correct string encoding. # args = list(map(str, args)) # # # Direct string replace. # if '%s' in cmd: # cmd = cmd.replace('%s', ' '.join(args)) # # # Escaped and quoted string replace. # if '%r' in cmd: # cmd = cmd.replace('%r', "'%s'" % escape(' '.join(args))) # # # Arg index string replace. # idx_list = list(enumerate(args)) # idx_list.reverse() # for (index, arg) in idx_list: # index += 1 # if '%%%d' % index in cmd: # cmd = cmd.replace('%%%d' % index, str(arg)) # # return cmd . Output only the next line.
for input, expect in cases:
Based on the snippet: <|code_start|> cmd = (cmd,) cmds = self.events[event] if cmd not in cmds: cmds.append((cmd, pattern)) def parse_on_event(self, args): '''Parse ON_EVENT events and pass them to the on_event function. Syntax: "event ON_EVENT <EVENT_NAME> <[ pattern ]> commands".''' args = splitquoted(args) assert args, 'missing on event arguments' # split into event name, optional argument pattern and command event = args[0] pattern = [] if args[1] == '[': for i, arg in enumerate(args[2:]): if arg == ']': break pattern.append(arg) command = tuple(args[3+i:]) else: command = tuple(args[1:]) assert event and command, 'missing on event command' self.on_event(event, pattern, command) def cleanup(self): <|code_end|> , predict the immediate next line with the help of imports: import fnmatch from functools import partial from uzbl.arguments import splitquoted from .cmd_expand import send_user_command from uzbl.ext import PerInstancePlugin and context (classes, functions, sometimes code) from other files: # Path: uzbl/arguments.py # def match(s): # def lex(s): # def parse(l): # def __new__(cls, s): # def raw(self, frm=0, to=None): # def safe_raw(self, frm=0, to=None): # def is_quoted(s): # def unquote(s): # class Arguments(tuple): # # Path: uzbl/plugins/cmd_expand.py # def send_user_command(uzbl, cmd, args): # if cmd[0] == 'event': # has_var = any('@' in x for x in cmd) # event = cmd[1] # args = ' '.join(format_arg(c, args) for c in cmd[2:]) # if not has_var: # # Bypass the roundtrip to uzbl and dispatch immediately # uzbl.event(event, args) # else: # uzbl.send(' '.join(('event', event, args))) # else: # cmd = ' '.join((cmd_expand(cmd[0], args),) + # tuple(format_arg(c, args) for c in cmd[1:])) # uzbl.send(cmd) # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] . Output only the next line.
self.events.clear()
Here is a snippet: <|code_start|> cmd = (cmd,) cmds = self.events[event] if cmd not in cmds: cmds.append((cmd, pattern)) def parse_on_event(self, args): '''Parse ON_EVENT events and pass them to the on_event function. Syntax: "event ON_EVENT <EVENT_NAME> <[ pattern ]> commands".''' args = splitquoted(args) assert args, 'missing on event arguments' # split into event name, optional argument pattern and command event = args[0] pattern = [] if args[1] == '[': for i, arg in enumerate(args[2:]): if arg == ']': break pattern.append(arg) command = tuple(args[3+i:]) else: command = tuple(args[1:]) assert event and command, 'missing on event command' self.on_event(event, pattern, command) def cleanup(self): <|code_end|> . Write the next line using the current file imports: import fnmatch from functools import partial from uzbl.arguments import splitquoted from .cmd_expand import send_user_command from uzbl.ext import PerInstancePlugin and context from other files: # Path: uzbl/arguments.py # def match(s): # def lex(s): # def parse(l): # def __new__(cls, s): # def raw(self, frm=0, to=None): # def safe_raw(self, frm=0, to=None): # def is_quoted(s): # def unquote(s): # class Arguments(tuple): # # Path: uzbl/plugins/cmd_expand.py # def send_user_command(uzbl, cmd, args): # if cmd[0] == 'event': # has_var = any('@' in x for x in cmd) # event = cmd[1] # args = ' '.join(format_arg(c, args) for c in cmd[2:]) # if not has_var: # # Bypass the roundtrip to uzbl and dispatch immediately # uzbl.event(event, args) # else: # uzbl.send(' '.join(('event', event, args))) # else: # cmd = ' '.join((cmd_expand(cmd[0], args),) + # tuple(format_arg(c, args) for c in cmd[1:])) # uzbl.send(cmd) # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] , which may include functions, classes, or code. Output only the next line.
self.events.clear()
Next line prediction: <|code_start|> def on_event(self, event, pattern, cmd): '''Add a new event to watch and respond to.''' event = event.upper() self.logger.debug('new event handler %r %r %r', event, pattern, cmd) if event not in self.events: self.uzbl.connect(event, partial(self.event_handler, on_event=event)) self.events[event] = [] if isinstance(cmd, str): cmd = (cmd,) cmds = self.events[event] if cmd not in cmds: cmds.append((cmd, pattern)) def parse_on_event(self, args): '''Parse ON_EVENT events and pass them to the on_event function. Syntax: "event ON_EVENT <EVENT_NAME> <[ pattern ]> commands".''' args = splitquoted(args) assert args, 'missing on event arguments' # split into event name, optional argument pattern and command event = args[0] pattern = [] if args[1] == '[': for i, arg in enumerate(args[2:]): <|code_end|> . Use current file imports: (import fnmatch from functools import partial from uzbl.arguments import splitquoted from .cmd_expand import send_user_command from uzbl.ext import PerInstancePlugin) and context including class names, function names, or small code snippets from other files: # Path: uzbl/arguments.py # def match(s): # def lex(s): # def parse(l): # def __new__(cls, s): # def raw(self, frm=0, to=None): # def safe_raw(self, frm=0, to=None): # def is_quoted(s): # def unquote(s): # class Arguments(tuple): # # Path: uzbl/plugins/cmd_expand.py # def send_user_command(uzbl, cmd, args): # if cmd[0] == 'event': # has_var = any('@' in x for x in cmd) # event = cmd[1] # args = ' '.join(format_arg(c, args) for c in cmd[2:]) # if not has_var: # # Bypass the roundtrip to uzbl and dispatch immediately # uzbl.event(event, args) # else: # uzbl.send(' '.join(('event', event, args))) # else: # cmd = ' '.join((cmd_expand(cmd[0], args),) + # tuple(format_arg(c, args) for c in cmd[1:])) # uzbl.send(cmd) # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] . Output only the next line.
if arg == ']':
Here is a snippet: <|code_start|>#!/usr/bin/env python class ArgumentsTest(unittest.TestCase): def test_empty(self): a = Arguments('') self.assertEqual(len(a), 0) self.assertEqual(a.raw(), '') def test_space(self): a = Arguments(' foo bar') <|code_end|> . Write the next line using the current file imports: import unittest from uzbl.arguments import Arguments and context from other files: # Path: uzbl/arguments.py # class Arguments(tuple): # ''' # Given a argument line gives access to the split parts # honoring common quotation and escaping rules # # >>> Arguments(r"simple 'quoted string'") # ('simple', 'quoted string') # ''' # # def __new__(cls, s): # ''' # >>> Arguments(r"one two three") # ('one', 'two', 'three') # >>> Arguments(r"spam 'escaping \\'works\\''") # ('spam', "escaping 'works'") # >>> # For testing purposes we can pass a preparsed tuple # >>> Arguments(('foo', 'bar', 'baz az')) # ('foo', 'bar', 'baz az') # ''' # if isinstance(s, tuple): # self = tuple.__new__(cls, s) # self._raw, self._ref = s, list(range(len(s))) # return self # # args, raw, ref = parse(lex(s)) # self = tuple.__new__(cls, args) # self._raw, self._ref = raw, ref # return self # # def raw(self, frm=0, to=None): # ''' # Returns the portion of the raw input that yielded arguments # from 'frm' to 'to' # # >>> args = Arguments(r"'spam, spam' egg sausage and 'spam'") # >>> args # ('spam, spam', 'egg', 'sausage', 'and', 'spam') # >>> args.raw(1) # "egg sausage and 'spam'" # ''' # if len(self._ref) < 1: # return '' # rfrm = self._ref[frm] # if to is None or len(self._ref) <= to + 1: # rto = len(self._raw) # else: # rto = self._ref[to + 1] - 1 # return ''.join(self._raw[rfrm:rto]) # # def safe_raw(self, frm=0, to=None): # ''' # Returns the portion of the raw input that yielded arguments # from 'frm' to 'to' # # >>> args = Arguments(r"'spam, spam' egg sausage and 'spam'") # >>> args # ('spam, spam', 'egg', 'sausage', 'and', 'spam') # >>> args.raw(1) # "egg sausage and 'spam'" # ''' # return self.raw(frm, to).replace('@', '\\@') , which may include functions, classes, or code. Output only the next line.
self.assertEqual(len(a), 2)
Based on the snippet: <|code_start|> class ProgressBar(PerInstancePlugin): CONFIG_SECTION = 'progress' splitfrmt = re.compile(r'(%[A-Z][^%]|%[^%])').split def __init__(self, uzbl): super(ProgressBar, self).__init__(uzbl) <|code_end|> , predict the immediate next line with the help of imports: import re from .config import Config from uzbl.ext import PerInstancePlugin and context (classes, functions, sometimes code) from other files: # Path: uzbl/plugins/config.py # class Config(PerInstancePlugin): # """Configuration plugin, has dictionary interface for config access # # This class is currenty not inherited from either UserDict or abc.Mapping # because not sure what version of python we want to support. It's not # hard to implement all needed methods either. # """ # # CONFIG_SECTION = 'config' # # def __init__(self, uzbl): # super(Config, self).__init__(uzbl) # # self.data = {} # uzbl.connect('VARIABLE_SET', self.parse_set_event) # assert not 'a' in self.data # # def __getitem__(self, key): # return self.data[key] # # def __setitem__(self, key, value): # self.set(key, value) # # def __delitem__(self, key): # self.set(key) # # def get(self, key, default=None): # return self.data.get(key, default) # # def __contains__(self, key): # return key in self.data # # def keys(self): # return iter(self.data.keys()) # # def items(self): # return iter(self.data.items()) # # def update(self, other=None, **kwargs): # if other is None: # other = {} # # for (key, value) in list(dict(other).items()) + list(kwargs.items()): # self[key] = value # # # def set(self, key, value='', force=False): # '''Generates a `set <key> <value>` command string to send to the # current uzbl instance. # # Note that the config dict isn't updated by this function. The config # dict is only updated after a successful `VARIABLE_SET ..` event # returns from the uzbl instance.''' # # assert valid_key(key) # # if isinstance(value, bool): # value = int(value) # # else: # value = str(value) # assert '\n' not in value # # if not force and key in self and self[key] == value: # return # # self.uzbl.send('set %s %s' % (key, value)) # # # def parse_set_event(self, args): # '''Parse `VARIABLE_SET <var> <type> <value>` event and load the # (key, value) pair into the `uzbl.config` dict.''' # # args = splitquoted(args) # if len(args) == 2: # key, type, raw_value = args[0], args[1], '' # elif len(args) == 3: # key, type, raw_value = args # else: # raise Exception('Invalid number of arguments') # # assert valid_key(key) # assert type in types # # new_value = types[type](raw_value) # old_value = self.data.get(key, None) # # # Update new value. # self.data[key] = new_value # # if old_value != new_value: # self.uzbl.event('CONFIG_CHANGED', key, new_value) # # # Cleanup null config values. # if type == 'str' and not new_value: # del self.data[key] # # def cleanup(self): # # not sure it's needed, but safer for cyclic links # self.data.clear() # super(Config, self).cleanup() # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] . Output only the next line.
uzbl.connect('LOAD_COMMIT', lambda uri: self.update_progress())
Predict the next line after this snippet: <|code_start|> class ProgressBar(PerInstancePlugin): CONFIG_SECTION = 'progress' splitfrmt = re.compile(r'(%[A-Z][^%]|%[^%])').split <|code_end|> using the current file's imports: import re from .config import Config from uzbl.ext import PerInstancePlugin and any relevant context from other files: # Path: uzbl/plugins/config.py # class Config(PerInstancePlugin): # """Configuration plugin, has dictionary interface for config access # # This class is currenty not inherited from either UserDict or abc.Mapping # because not sure what version of python we want to support. It's not # hard to implement all needed methods either. # """ # # CONFIG_SECTION = 'config' # # def __init__(self, uzbl): # super(Config, self).__init__(uzbl) # # self.data = {} # uzbl.connect('VARIABLE_SET', self.parse_set_event) # assert not 'a' in self.data # # def __getitem__(self, key): # return self.data[key] # # def __setitem__(self, key, value): # self.set(key, value) # # def __delitem__(self, key): # self.set(key) # # def get(self, key, default=None): # return self.data.get(key, default) # # def __contains__(self, key): # return key in self.data # # def keys(self): # return iter(self.data.keys()) # # def items(self): # return iter(self.data.items()) # # def update(self, other=None, **kwargs): # if other is None: # other = {} # # for (key, value) in list(dict(other).items()) + list(kwargs.items()): # self[key] = value # # # def set(self, key, value='', force=False): # '''Generates a `set <key> <value>` command string to send to the # current uzbl instance. # # Note that the config dict isn't updated by this function. The config # dict is only updated after a successful `VARIABLE_SET ..` event # returns from the uzbl instance.''' # # assert valid_key(key) # # if isinstance(value, bool): # value = int(value) # # else: # value = str(value) # assert '\n' not in value # # if not force and key in self and self[key] == value: # return # # self.uzbl.send('set %s %s' % (key, value)) # # # def parse_set_event(self, args): # '''Parse `VARIABLE_SET <var> <type> <value>` event and load the # (key, value) pair into the `uzbl.config` dict.''' # # args = splitquoted(args) # if len(args) == 2: # key, type, raw_value = args[0], args[1], '' # elif len(args) == 3: # key, type, raw_value = args # else: # raise Exception('Invalid number of arguments') # # assert valid_key(key) # assert type in types # # new_value = types[type](raw_value) # old_value = self.data.get(key, None) # # # Update new value. # self.data[key] = new_value # # if old_value != new_value: # self.uzbl.event('CONFIG_CHANGED', key, new_value) # # # Cleanup null config values. # if type == 'str' and not new_value: # del self.data[key] # # def cleanup(self): # # not sure it's needed, but safer for cyclic links # self.data.clear() # super(Config, self).cleanup() # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] . Output only the next line.
def __init__(self, uzbl):
Next line prediction: <|code_start|> elif len(hints) == 1: self.completion.lock() self.complete_completion(partial, hints[0]) self.completion.unlock() return elif partial in hints and self.completion.level == COMPLETE: self.completion.lock() self.complete_completion(partial, partial) self.completion.unlock() return smalllen, smallest = sorted([(len(h), h) for h in hints])[0] common = '' for i in range(len(partial), smalllen): char, same = smallest[i], True for hint in hints: if hint[i] != char: same = False break if not same: break common += char if common: self.completion.lock() self.partial_completion(partial, partial + common) <|code_end|> . Use current file imports: (import json import re from uzbl.arguments import splitquoted from uzbl.ext import PerInstancePlugin from .config import Config from .keycmd import KeyCmd) and context including class names, function names, or small code snippets from other files: # Path: uzbl/arguments.py # def match(s): # def lex(s): # def parse(l): # def __new__(cls, s): # def raw(self, frm=0, to=None): # def safe_raw(self, frm=0, to=None): # def is_quoted(s): # def unquote(s): # class Arguments(tuple): # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] # # Path: uzbl/plugins/config.py # class Config(PerInstancePlugin): # """Configuration plugin, has dictionary interface for config access # # This class is currenty not inherited from either UserDict or abc.Mapping # because not sure what version of python we want to support. It's not # hard to implement all needed methods either. # """ # # CONFIG_SECTION = 'config' # # def __init__(self, uzbl): # super(Config, self).__init__(uzbl) # # self.data = {} # uzbl.connect('VARIABLE_SET', self.parse_set_event) # assert not 'a' in self.data # # def __getitem__(self, key): # return self.data[key] # # def __setitem__(self, key, value): # self.set(key, value) # # def __delitem__(self, key): # self.set(key) # # def get(self, key, default=None): # return self.data.get(key, default) # # def __contains__(self, key): # return key in self.data # # def keys(self): # return iter(self.data.keys()) # # def items(self): # return iter(self.data.items()) # # def update(self, other=None, **kwargs): # if other is None: # other = {} # # for (key, value) in list(dict(other).items()) + list(kwargs.items()): # self[key] = value # # # def set(self, key, value='', force=False): # '''Generates a `set <key> <value>` command string to send to the # current uzbl instance. # # Note that the config dict isn't updated by this function. The config # dict is only updated after a successful `VARIABLE_SET ..` event # returns from the uzbl instance.''' # # assert valid_key(key) # # if isinstance(value, bool): # value = int(value) # # else: # value = str(value) # assert '\n' not in value # # if not force and key in self and self[key] == value: # return # # self.uzbl.send('set %s %s' % (key, value)) # # # def parse_set_event(self, args): # '''Parse `VARIABLE_SET <var> <type> <value>` event and load the # (key, value) pair into the `uzbl.config` dict.''' # # args = splitquoted(args) # if len(args) == 2: # key, type, raw_value = args[0], args[1], '' # elif len(args) == 3: # key, type, raw_value = args # else: # raise Exception('Invalid number of arguments') # # assert valid_key(key) # assert type in types # # new_value = types[type](raw_value) # old_value = self.data.get(key, None) # # # Update new value. # self.data[key] = new_value # # if old_value != new_value: # self.uzbl.event('CONFIG_CHANGED', key, new_value) # # # Cleanup null config values. # if type == 'str' and not new_value: # del self.data[key] # # def cleanup(self): # # not sure it's needed, but safer for cyclic links # self.data.clear() # super(Config, self).cleanup() . Output only the next line.
self.completion.unlock()
Here is a snippet: <|code_start|> return config = Config[self.uzbl] hints = [h for h in self.completion if h.startswith(partial)] if not hints: del config['completion_list'] return config['completion_list'] = self.listformatter.format(partial, hints) def start_completion(self, *args): if self.completion.locked: return partial = self.get_incomplete_keyword() if not partial: return self.stop_completion() if self.completion.level < COMPLETE: self.completion.level += 1 hints = [h for h in self.completion if h.startswith(partial)] if not hints: return elif len(hints) == 1: self.completion.lock() self.complete_completion(partial, hints[0]) self.completion.unlock() <|code_end|> . Write the next line using the current file imports: import json import re from uzbl.arguments import splitquoted from uzbl.ext import PerInstancePlugin from .config import Config from .keycmd import KeyCmd and context from other files: # Path: uzbl/arguments.py # def match(s): # def lex(s): # def parse(l): # def __new__(cls, s): # def raw(self, frm=0, to=None): # def safe_raw(self, frm=0, to=None): # def is_quoted(s): # def unquote(s): # class Arguments(tuple): # # Path: uzbl/ext.py # class PerInstancePlugin(BasePlugin): # """Base class for plugins which instantiate once per uzbl instance""" # # def __init__(self, uzbl): # self.uzbl = uzbl # self.plugin_config = uzbl.parent.get_plugin_config(self.CONFIG_SECTION) # self.logger = uzbl.logger # we can also append plugin name to logger # # def cleanup(self): # """Cleanup state after instance is gone # # Default function avoids cyclic refrences, so don't forget to call # super() if overriding # """ # del self.uzbl # # @classmethod # def _get_instance(cls, owner): # """Returns instance of the plugin # # This method should be private to not violate TOOWTDI # """ # if not isinstance(owner, Uzbl): # raise ValueError("Can only get {0} instance for uzbl, not {1}" # .format(cls.__name__, type(owner).__name__)) # # TODO(tailhook) probably subclasses can be returned as well # return owner.plugins[cls] # # Path: uzbl/plugins/config.py # class Config(PerInstancePlugin): # """Configuration plugin, has dictionary interface for config access # # This class is currenty not inherited from either UserDict or abc.Mapping # because not sure what version of python we want to support. It's not # hard to implement all needed methods either. # """ # # CONFIG_SECTION = 'config' # # def __init__(self, uzbl): # super(Config, self).__init__(uzbl) # # self.data = {} # uzbl.connect('VARIABLE_SET', self.parse_set_event) # assert not 'a' in self.data # # def __getitem__(self, key): # return self.data[key] # # def __setitem__(self, key, value): # self.set(key, value) # # def __delitem__(self, key): # self.set(key) # # def get(self, key, default=None): # return self.data.get(key, default) # # def __contains__(self, key): # return key in self.data # # def keys(self): # return iter(self.data.keys()) # # def items(self): # return iter(self.data.items()) # # def update(self, other=None, **kwargs): # if other is None: # other = {} # # for (key, value) in list(dict(other).items()) + list(kwargs.items()): # self[key] = value # # # def set(self, key, value='', force=False): # '''Generates a `set <key> <value>` command string to send to the # current uzbl instance. # # Note that the config dict isn't updated by this function. The config # dict is only updated after a successful `VARIABLE_SET ..` event # returns from the uzbl instance.''' # # assert valid_key(key) # # if isinstance(value, bool): # value = int(value) # # else: # value = str(value) # assert '\n' not in value # # if not force and key in self and self[key] == value: # return # # self.uzbl.send('set %s %s' % (key, value)) # # # def parse_set_event(self, args): # '''Parse `VARIABLE_SET <var> <type> <value>` event and load the # (key, value) pair into the `uzbl.config` dict.''' # # args = splitquoted(args) # if len(args) == 2: # key, type, raw_value = args[0], args[1], '' # elif len(args) == 3: # key, type, raw_value = args # else: # raise Exception('Invalid number of arguments') # # assert valid_key(key) # assert type in types # # new_value = types[type](raw_value) # old_value = self.data.get(key, None) # # # Update new value. # self.data[key] = new_value # # if old_value != new_value: # self.uzbl.event('CONFIG_CHANGED', key, new_value) # # # Cleanup null config values. # if type == 'str' and not new_value: # del self.data[key] # # def cleanup(self): # # not sure it's needed, but safer for cyclic links # self.data.clear() # super(Config, self).cleanup() , which may include functions, classes, or code. Output only the next line.
return
Here is a snippet: <|code_start|> self.uzbl = self.event_manager.add() def test_command(self): oe = OnEventPlugin[self.uzbl] event, command = 'FOO', 'test test' oe.parse_on_event('FOO test test') oe.event_handler('', on_event=event) self.uzbl.send.assert_called_once_with(command) def test_command_with_quotes(self): oe = OnEventPlugin[self.uzbl] event, command = 'FOO', 'test "string with spaces"' oe.parse_on_event('FOO test "string with spaces"') oe.event_handler('', on_event=event) self.uzbl.send.assert_called_once_with(command) def test_matching_pattern(self): oe = OnEventPlugin[self.uzbl] event, command = 'FOO', "test test" oe.parse_on_event('FOO [ BAR ] test test') oe.event_handler('BAR else', on_event=event) self.uzbl.send.assert_called_once_with(command) def test_non_matching_pattern(self): oe = OnEventPlugin[self.uzbl] event, pattern, command = 'FOO', ['BAR'], 'test test' <|code_end|> . Write the next line using the current file imports: import unittest from emtest import EventManagerMock from uzbl.plugins.on_event import OnEventPlugin and context from other files: # Path: uzbl/plugins/on_event.py # class OnEventPlugin(PerInstancePlugin): # CONFIG_SECTION = 'on_event' # # def __init__(self, uzbl): # '''Export functions and connect handlers to events.''' # super(OnEventPlugin, self).__init__(uzbl) # # self.events = {} # # uzbl.connect('ON_EVENT', self.parse_on_event) # # def event_handler(self, *args, **kargs): # '''This function handles all the events being watched by various # on_event definitions and responds accordingly.''' # # # Could be connected to a EM internal event that can use anything as # # arguments # if len(args) == 1 and isinstance(args[0], str): # args = splitquoted(args[0]) # # event = kargs['on_event'] # if event not in self.events: # return # # commands = self.events[event] # for cmd, pattern in commands: # if not pattern or match_args(pattern, args): # send_user_command(self.uzbl, cmd, args) # # def on_event(self, event, pattern, cmd): # '''Add a new event to watch and respond to.''' # # event = event.upper() # self.logger.debug('new event handler %r %r %r', event, pattern, cmd) # if event not in self.events: # self.uzbl.connect(event, # partial(self.event_handler, on_event=event)) # self.events[event] = [] # # if isinstance(cmd, str): # cmd = (cmd,) # # cmds = self.events[event] # if cmd not in cmds: # cmds.append((cmd, pattern)) # # def parse_on_event(self, args): # '''Parse ON_EVENT events and pass them to the on_event function. # # Syntax: "event ON_EVENT <EVENT_NAME> <[ pattern ]> commands".''' # # args = splitquoted(args) # assert args, 'missing on event arguments' # # # split into event name, optional argument pattern and command # event = args[0] # pattern = [] # if args[1] == '[': # for i, arg in enumerate(args[2:]): # if arg == ']': # break # pattern.append(arg) # command = tuple(args[3+i:]) # else: # command = tuple(args[1:]) # # assert event and command, 'missing on event command' # self.on_event(event, pattern, command) # # def cleanup(self): # self.events.clear() # super(OnEventPlugin, self).cleanup() , which may include functions, classes, or code. Output only the next line.
oe.on_event(event, pattern, command)
Given the following code snippet before the placeholder: <|code_start|> argparser.add_argument( '--no-cpu', dest='cpu_change', default=True, action='store_const', const=False) args = argparser.parse_args(sys.argv[1:]) if args.cpu_change: cpu.change('userspace', cpu.min_freq()) cpu.dump() aio.set_event_loop(loop) if not args.endpoint: os.putenv('PYTHONPATH', 'src') server_fut = aio.create_subprocess_exec( 'python', 'benchmarks/japronto/micro.py', *args.server.split()) server = loop.run_until_complete(server_fut) os.unsetenv('PYTHONPATH') if not args.endpoint: process = psutil.Process(server.pid) elif args.pid: process = psutil.Process(args.pid) else: process = None cpu_p = 100 while cpu_p > 5: cpu_p = psutil.cpu_percent(interval=1) print('CPU usage in 1 sec:', cpu_p) <|code_end|> , predict the next line using imports from the current file: import argparse import sys import asyncio as aio import os import statistics import uvloop import psutil from asyncio.subprocess import PIPE, STDOUT from misc import cpu from misc import buggers and context including class names, function names, and sometimes code from other files: # Path: misc/cpu.py # CPU_PREFIX = '/sys/devices/system/cpu/' # def save(): # def change(governor, freq=None): # def available_freq(): # def min_freq(): # def max_freq(): # def dump(): # # Path: misc/buggers.py # def silence(): # def noise(): . Output only the next line.
results = []
Predict the next line after this snippet: <|code_start|> def run_wrk(loop, endpoint=None): endpoint = endpoint or 'http://localhost:8080' wrk_fut = aio.create_subprocess_exec( './wrk', '-t', '1', '-c', '100', '-d', '2', '-s', 'misc/pipeline.lua', endpoint, stdout=PIPE, stderr=STDOUT) wrk = loop.run_until_complete(wrk_fut) lines = [] while 1: line = loop.run_until_complete(wrk.stdout.readline()) if line: line = line.decode('utf-8') lines.append(line) if line.startswith('Requests/sec:'): rps = float(line.split()[-1]) else: <|code_end|> using the current file's imports: import argparse import sys import asyncio as aio import os import statistics import uvloop import psutil from asyncio.subprocess import PIPE, STDOUT from misc import cpu from misc import buggers and any relevant context from other files: # Path: misc/cpu.py # CPU_PREFIX = '/sys/devices/system/cpu/' # def save(): # def change(governor, freq=None): # def available_freq(): # def min_freq(): # def max_freq(): # def dump(): # # Path: misc/buggers.py # def silence(): # def noise(): . Output only the next line.
break
Next line prediction: <|code_start|> connection.putrequest('GET', '/noleak/1/2') if body: connection.putheader('Content-Length', str(len(body))) connection.endheaders(body) response = connection.getresponse() assert response.status == 200 @pytest.mark.arg('keep_alive') def test_keep_alive(request): keep_alives = [True, False, True, True, False, False, True, False] still_open = False for keep_alive in keep_alives: if not still_open: connection_gen = connection(request.getfixturevalue('server')) conn = next(connection_gen) still_open = keep_alive conn.putrequest('GET', '/noleak/1/2') if not keep_alive: conn.putheader('Connection', 'close') conn.endheaders() response = conn.getresponse() assert response.status == 200 @pytest.mark.arg('route') <|code_end|> . Use current file imports: (import pytest import integration_tests.common from misc import client) and context including class names, function names, or small code snippets from other files: # Path: misc/client.py # def readline(sock): # def readexact(sock, size): # def __init__(self, sock): # def read_status_line(self): # def read_headers(self): # def encoding(self): # def read_body(self): # def json(self): # def __init__(self, addr): # def maybe_connect(self): # def putline(self, line=None): # def putclose(self, data): # def putrequest(self, method, path, query_string=None): # def request(self, method, path, query_string=None, headers=None, # body=None): # def putheader(self, name, value): # def endheaders(self, body=None): # def getresponse(self): # def close(self): # def chunked_encoder(data): # class Response: # class Connection: . Output only the next line.
def test_route(connection):
Based on the snippet: <|code_start|> json_body = json.loads(response.body) assert response.status == 200 assert json_body['method'] == method connection.close() st_route_prefix = st.sampled_from(['/dump/', '/dump1/', '/dump2/']) @given(route_prefix=st_route_prefix) @settings(verbosity=Verbosity.verbose) def test_route(prefix, connect, route_prefix): connection = connect() connection.request('GET', prefix + route_prefix + '1/2') response = connection.getresponse() json_body = json.loads(response.body) assert response.status == 200 assert json_body['route'].startswith(prefix + route_prefix) connection.close() @given(param1=st.param, param2=st.param) @settings(verbosity=Verbosity.verbose) def test_match_dict(prefix, connect, param1, param2): connection = connect() connection.request('GET', prefix + '/dump/{}/{}'.format(param1, param2)) <|code_end|> , predict the immediate next line with the help of imports: import pytest import json import base64 import integration_tests.common from functools import partial from hypothesis import given, settings, Verbosity, HealthCheck from integration_tests import strategies as st from misc import client and context (classes, functions, sometimes code) from other files: # Path: integration_tests/strategies.py # # Path: misc/client.py # def readline(sock): # def readexact(sock, size): # def __init__(self, sock): # def read_status_line(self): # def read_headers(self): # def encoding(self): # def read_body(self): # def json(self): # def __init__(self, addr): # def maybe_connect(self): # def putline(self, line=None): # def putclose(self, data): # def putrequest(self, method, path, query_string=None): # def request(self, method, path, query_string=None, headers=None, # body=None): # def putheader(self, name, value): # def endheaders(self, body=None): # def getresponse(self): # def close(self): # def chunked_encoder(data): # class Response: # class Connection: . Output only the next line.
response = connection.getresponse()
Predict the next line for this snippet: <|code_start|> assert json_body['body'] is None if request['error']: assert json_body['exception']['type'] == \ 'RouteNotFoundException' if request['error'] == 'not-found' \ else 'ForcedException' assert json_body['exception']['args'] == \ '' if request['error'] == 'not-found' else request['error'] else: assert 'exception' not in json_body connection.close() def format_sleep_qs(val): return 'sleep=' + str(val / 100) st_sleep = st.builds(format_sleep_qs, st.integers(min_value=0, max_value=10)) st_prefix = st.sampled_from(['/dump', '/async/dump']) st_async_request = st.fixed_dictionaries({ 'query_string': st_sleep, 'prefix': st_prefix, 'error': st_errors }) st_async_requests = st.lists(st_async_request, min_size=2, max_size=5) \ .filter(lambda rs: any(r['prefix'].startswith('/async') for r in rs)) @given(requests=st_async_requests) @settings(verbosity=Verbosity.verbose) <|code_end|> with the help of current file imports: import pytest import json import base64 import integration_tests.common from functools import partial from hypothesis import given, settings, Verbosity, HealthCheck from integration_tests import strategies as st from misc import client and context from other files: # Path: integration_tests/strategies.py # # Path: misc/client.py # def readline(sock): # def readexact(sock, size): # def __init__(self, sock): # def read_status_line(self): # def read_headers(self): # def encoding(self): # def read_body(self): # def json(self): # def __init__(self, addr): # def maybe_connect(self): # def putline(self, line=None): # def putclose(self, data): # def putrequest(self, method, path, query_string=None): # def request(self, method, path, query_string=None, headers=None, # body=None): # def putheader(self, name, value): # def endheaders(self, body=None): # def getresponse(self): # def close(self): # def chunked_encoder(data): # class Response: # class Connection: , which may contain function names, class names, or code. Output only the next line.
def test_async_pipeline(requests):
Using the snippet: <|code_start|> def main(): parser = get_parser() args = parser.parse_args() if not args.script: os.putenv('_JAPR_IGNORE_RUN', '1') if args.reload: os.execv( sys.executable, [sys.executable, '-m', 'japronto.reloader', *sys.argv[1:]]) <|code_end|> , determine the next line of code. You have imports: import sys import os from .runner import get_parser, verify, run and context (class names, function names, or code) available: # Path: src/japronto/runner.py # def get_parser(): # prog = 'python -m japronto' if sys.argv[0].endswith('__main__.py') \ # else 'japronto' # parser = ArgumentParser(prog=prog) # parser.add_argument('--host', dest='host', type=str, default='0.0.0.0') # parser.add_argument('--port', dest='port', type=int, default=8080) # parser.add_argument('--worker-num', dest='worker_num', type=int, default=1) # parser.add_argument( # '--reload', dest='reload', action='store_const', # const=True, default=False) # # parser.add_argument( # '--reloader-pid', dest='reloader_pid', type=int, help=SUPPRESS) # parser.add_argument( # '--script', dest='script', action='store_const', # const=True, default=False, help=SUPPRESS) # # parser.add_argument('application') # # return parser # # def verify(args): # if args.script: # script = args.application # # if not os.path.exists(script): # print("Script '{}' not found.".format(script)) # # return script # else: # try: # module, attribute = args.application.rsplit('.', 1) # except ValueError: # print( # "Application specificer must contain at least one '.'," + # "got '{}'.".format(args.application)) # return False # # try: # module = import_module(module) # except ModuleNotFoundError as e: # print(e.args[0] + ' on Python search path.') # return False # # try: # attribute = getattr(module, attribute) # except AttributeError: # print( # "Module '{}' does not have an attribute '{}'." # .format(module.__name__, attribute)) # return False # # if not isinstance(attribute, Application): # print("{} is not an instance of 'japronto.Application'.") # return False # # return attribute # # def run(attribute, args): # if args.script: # runpy.run_path(attribute) # else: # attribute._run( # host=args.host, port=args.port, # worker_num=args.worker_num, reloader_pid=args.reloader_pid) . Output only the next line.
if not args.script:
Given the following code snippet before the placeholder: <|code_start|> def main(): parser = get_parser() args = parser.parse_args() if not args.script: os.putenv('_JAPR_IGNORE_RUN', '1') if args.reload: os.execv( sys.executable, [sys.executable, '-m', 'japronto.reloader', *sys.argv[1:]]) <|code_end|> , predict the next line using imports from the current file: import sys import os from .runner import get_parser, verify, run and context including class names, function names, and sometimes code from other files: # Path: src/japronto/runner.py # def get_parser(): # prog = 'python -m japronto' if sys.argv[0].endswith('__main__.py') \ # else 'japronto' # parser = ArgumentParser(prog=prog) # parser.add_argument('--host', dest='host', type=str, default='0.0.0.0') # parser.add_argument('--port', dest='port', type=int, default=8080) # parser.add_argument('--worker-num', dest='worker_num', type=int, default=1) # parser.add_argument( # '--reload', dest='reload', action='store_const', # const=True, default=False) # # parser.add_argument( # '--reloader-pid', dest='reloader_pid', type=int, help=SUPPRESS) # parser.add_argument( # '--script', dest='script', action='store_const', # const=True, default=False, help=SUPPRESS) # # parser.add_argument('application') # # return parser # # def verify(args): # if args.script: # script = args.application # # if not os.path.exists(script): # print("Script '{}' not found.".format(script)) # # return script # else: # try: # module, attribute = args.application.rsplit('.', 1) # except ValueError: # print( # "Application specificer must contain at least one '.'," + # "got '{}'.".format(args.application)) # return False # # try: # module = import_module(module) # except ModuleNotFoundError as e: # print(e.args[0] + ' on Python search path.') # return False # # try: # attribute = getattr(module, attribute) # except AttributeError: # print( # "Module '{}' does not have an attribute '{}'." # .format(module.__name__, attribute)) # return False # # if not isinstance(attribute, Application): # print("{} is not an instance of 'japronto.Application'.") # return False # # return attribute # # def run(attribute, args): # if args.script: # runpy.run_path(attribute) # else: # attribute._run( # host=args.host, port=args.port, # worker_num=args.worker_num, reloader_pid=args.reloader_pid) . Output only the next line.
if not args.script:
Using the snippet: <|code_start|> def main(): parser = get_parser() args = parser.parse_args() <|code_end|> , determine the next line of code. You have imports: import sys import os from .runner import get_parser, verify, run and context (class names, function names, or code) available: # Path: src/japronto/runner.py # def get_parser(): # prog = 'python -m japronto' if sys.argv[0].endswith('__main__.py') \ # else 'japronto' # parser = ArgumentParser(prog=prog) # parser.add_argument('--host', dest='host', type=str, default='0.0.0.0') # parser.add_argument('--port', dest='port', type=int, default=8080) # parser.add_argument('--worker-num', dest='worker_num', type=int, default=1) # parser.add_argument( # '--reload', dest='reload', action='store_const', # const=True, default=False) # # parser.add_argument( # '--reloader-pid', dest='reloader_pid', type=int, help=SUPPRESS) # parser.add_argument( # '--script', dest='script', action='store_const', # const=True, default=False, help=SUPPRESS) # # parser.add_argument('application') # # return parser # # def verify(args): # if args.script: # script = args.application # # if not os.path.exists(script): # print("Script '{}' not found.".format(script)) # # return script # else: # try: # module, attribute = args.application.rsplit('.', 1) # except ValueError: # print( # "Application specificer must contain at least one '.'," + # "got '{}'.".format(args.application)) # return False # # try: # module = import_module(module) # except ModuleNotFoundError as e: # print(e.args[0] + ' on Python search path.') # return False # # try: # attribute = getattr(module, attribute) # except AttributeError: # print( # "Module '{}' does not have an attribute '{}'." # .format(module.__name__, attribute)) # return False # # if not isinstance(attribute, Application): # print("{} is not an instance of 'japronto.Application'.") # return False # # return attribute # # def run(attribute, args): # if args.script: # runpy.run_path(attribute) # else: # attribute._run( # host=args.host, port=args.port, # worker_num=args.worker_num, reloader_pid=args.reloader_pid) . Output only the next line.
if not args.script:
Next line prediction: <|code_start|> os.makedirs('.collector', exist_ok=True) os.putenv('COLLECTOR_FILE', '.collector/{}.json'.format(server.pid)) collector = subprocess.Popen([ sys.executable, 'misc/collector.py', str(server.pid)]) os.unsetenv('COLLECTOR_FILE') def cleanup(*args): try: server.terminate() assert server.wait() == 0 finally: atexit.unregister(cleanup) atexit.register(cleanup) signal.signal(signal.SIGINT, cleanup) def run(): time.sleep(2) for reverse in [True, False]: for combination in integration_tests.generators.generate_combinations( reverse=reverse): conn = client.Connection('localhost:8080') time.sleep(2) integration_tests.generators.send_requests( conn, 200, **combination) time.sleep(2) conn.close() <|code_end|> . Use current file imports: (import subprocess import sys import signal import atexit import os import time import integration_tests.common # noqa import integration_tests.generators # noqa from misc import client # noqa) and context including class names, function names, or small code snippets from other files: # Path: misc/client.py # def readline(sock): # def readexact(sock, size): # def __init__(self, sock): # def read_status_line(self): # def read_headers(self): # def encoding(self): # def read_body(self): # def json(self): # def __init__(self, addr): # def maybe_connect(self): # def putline(self, line=None): # def putclose(self, data): # def putrequest(self, method, path, query_string=None): # def request(self, method, path, query_string=None, headers=None, # body=None): # def putheader(self, name, value): # def endheaders(self, body=None): # def getresponse(self): # def close(self): # def chunked_encoder(data): # class Response: # class Connection: . Output only the next line.
time.sleep(2)
Continue the code snippet: <|code_start|> @classmethod def from_str(cls, value): return cls(*value.split()) class TracingRoute(Route): cnt = 0 def __new__(cls, *args, **kw): print('new', args) cls.cnt += 1 return Route.__new__(cls) def __init__(self, pattern, methods): super().__init__(pattern, lambda x: None, methods=methods) def __del__(self): type(self).cnt -= 1 print('del') def route_from_str(value): pattern, *methods = value.split() if methods: methods = methods[0].split(',') return TracingRoute(pattern, methods=methods) def parametrize_make_matcher(): <|code_end|> . Use current file imports: from functools import partial from . import Route from .matcher import Matcher from .cmatcher import Matcher as CMatcher import pytest and context (classes, functions, or code) from other files: # Path: src/japronto/router/route.py # class Route: # def __init__(self, pattern, handler, methods): # self.pattern = pattern # self.handler = handler # self.methods = methods # self.segments = parse(pattern) # self.placeholder_cnt = \ # sum(1 for s in self.segments if s[0] == 'placeholder') # # def __repr__(self): # return '<Route {}, {} {}>'.format( # self.pattern, self.methods, hex(id(self))) # # def describe(self): # return self.pattern + (' ' if self.methods else '') + \ # ' '.join(self.methods) # # def __eq__(self, other): # return self.pattern == other.pattern and self.methods == other.methods # # Path: src/japronto/router/matcher.py # class Matcher: # def __init__(self, routes): # self._routes = routes # # def match_request(self, request): # for route in self._routes: # match_dict = {} # rest = request.path # # value = True # for typ, data in route.segments: # if typ == 'exact': # if not rest.startswith(data): # break # # rest = rest[len(data):] # elif typ == 'placeholder': # value, slash, rest = rest.partition('/') # if not value: # break # match_dict[data] = value # rest = slash + rest # else: # assert 0, 'Unknown type' # # if rest: # continue # # if not value: # continue # # if len(match_dict) != route.placeholder_cnt: # continue # # if route.methods and request.method not in route.methods: # continue # # return route, match_dict . Output only the next line.
def make(cls):
Based on the snippet: <|code_start|> routes = [route_from_str(r) for r in [ '/', '/test GET', '/hi/{there} POST,DELETE', '/{oh}/{dear} PATCH', '/lets PATCH' ]] return cls(routes) make_matcher = partial(make, Matcher) make_cmatcher = partial(make, CMatcher) return pytest.mark.parametrize( 'make_matcher', [make_matcher, make_cmatcher], ids=['py', 'c']) def parametrize_request_route_and_dict(cases): return pytest.mark.parametrize( 'req,route,match_dict', ((FakeRequest.from_str(req), route_from_str(route), match_dict) for req, route, match_dict in cases), ids=[req + '-' + route for req, route, _ in cases]) @parametrize_request_route_and_dict([ ('GET /', '/', {}), ('POST /', '/', {}), ('GET /test', '/test GET', {}), ('DELETE /hi/jane', '/hi/{there} POST,DELETE', {'there': 'jane'}), <|code_end|> , predict the immediate next line with the help of imports: from functools import partial from . import Route from .matcher import Matcher from .cmatcher import Matcher as CMatcher import pytest and context (classes, functions, sometimes code) from other files: # Path: src/japronto/router/route.py # class Route: # def __init__(self, pattern, handler, methods): # self.pattern = pattern # self.handler = handler # self.methods = methods # self.segments = parse(pattern) # self.placeholder_cnt = \ # sum(1 for s in self.segments if s[0] == 'placeholder') # # def __repr__(self): # return '<Route {}, {} {}>'.format( # self.pattern, self.methods, hex(id(self))) # # def describe(self): # return self.pattern + (' ' if self.methods else '') + \ # ' '.join(self.methods) # # def __eq__(self, other): # return self.pattern == other.pattern and self.methods == other.methods # # Path: src/japronto/router/matcher.py # class Matcher: # def __init__(self, routes): # self._routes = routes # # def match_request(self, request): # for route in self._routes: # match_dict = {} # rest = request.path # # value = True # for typ, data in route.segments: # if typ == 'exact': # if not rest.startswith(data): # break # # rest = rest[len(data):] # elif typ == 'placeholder': # value, slash, rest = rest.partition('/') # if not value: # break # match_dict[data] = value # rest = slash + rest # else: # assert 0, 'Unknown type' # # if rest: # continue # # if not value: # continue # # if len(match_dict) != route.placeholder_cnt: # continue # # if route.methods and request.method not in route.methods: # continue # # return route, match_dict . Output only the next line.
('PATCH /lets/go', '/{oh}/{dear} PATCH', {'oh': 'lets', 'dear': 'go'}),
Given snippet: <|code_start|> @pytest.fixture(scope='function', params=[2, 3, 4]) def get_connections_and_wait(request): server, process = integration_tests.common.start_server([ 'integration_tests/reaper.py', '1', str(request.param)], path='.test', return_process=True) def connection_num(): return len( set(c.fd for c in process.connections()) | set(c.fd for p in process.children() for c in p.connections())) yield connection_num, partial(time.sleep, request.param) server.terminate() assert server.wait() == 0 def test_empty(get_connections_and_wait): get_connections, wait = get_connections_and_wait conn = client.Connection('localhost:8080') assert get_connections() == 1 conn.maybe_connect() time.sleep(.1) assert get_connections() == 2 <|code_end|> , continue by predicting the next line. Consider current file imports: from functools import partial from misc import client import time import pytest import integration_tests.common and context: # Path: misc/client.py # def readline(sock): # def readexact(sock, size): # def __init__(self, sock): # def read_status_line(self): # def read_headers(self): # def encoding(self): # def read_body(self): # def json(self): # def __init__(self, addr): # def maybe_connect(self): # def putline(self, line=None): # def putclose(self, data): # def putrequest(self, method, path, query_string=None): # def request(self, method, path, query_string=None, headers=None, # body=None): # def putheader(self, name, value): # def endheaders(self, body=None): # def getresponse(self): # def close(self): # def chunked_encoder(data): # class Response: # class Connection: which might include code, classes, or functions. Output only the next line.
wait()
Based on the snippet: <|code_start|> methods = buffer[offset:offset + methods_len].strip().decode('ascii') \ .split() return DecodedRoute( route_id, handler_id, coro_func, simple, placeholder_cnt, segments, methods) def handler(): pass async def coro(): # needs to have await to prevent being promoted to function await asyncio.sleep(1) @pytest.mark.parametrize('route', [ Route('/', handler, []), Route('/', coro, ['GET']), Route('/test/{hi}', handler, []), Route('/test/{hi}', coro, ['POST']), Route('/tést', coro, ['POST']) ], ids=Route.describe) def test_compile(route): decompiled = decompile(compile(route)) assert decompiled.route_id == id(route) assert decompiled.handler_id == id(route.handler) <|code_end|> , predict the immediate next line with the help of imports: import asyncio import pytest from collections import namedtuple from .route import parse, MatcherEntry, Segment, SegmentType, Route, \ compile, roundto8 and context (classes, functions, sometimes code) from other files: # Path: src/japronto/router/route.py # class RouteNotFoundException(Exception): # class Route: # class SegmentType(IntEnum): # def __init__(self, pattern, handler, methods): # def __repr__(self): # def describe(self): # def __eq__(self, other): # def parse(pattern): # def roundto8(v): # def padto8(data): # def compile(route): # def compile_all(routes): # EXACT = 0 # PLACEHOLDER = 1 . Output only the next line.
assert decompiled.coro_func == asyncio.iscoroutinefunction(route.handler)
Given snippet: <|code_start|> .split() return DecodedRoute( route_id, handler_id, coro_func, simple, placeholder_cnt, segments, methods) def handler(): pass async def coro(): # needs to have await to prevent being promoted to function await asyncio.sleep(1) @pytest.mark.parametrize('route', [ Route('/', handler, []), Route('/', coro, ['GET']), Route('/test/{hi}', handler, []), Route('/test/{hi}', coro, ['POST']), Route('/tést', coro, ['POST']) ], ids=Route.describe) def test_compile(route): decompiled = decompile(compile(route)) assert decompiled.route_id == id(route) assert decompiled.handler_id == id(route.handler) assert decompiled.coro_func == asyncio.iscoroutinefunction(route.handler) assert not decompiled.simple <|code_end|> , continue by predicting the next line. Consider current file imports: import asyncio import pytest from collections import namedtuple from .route import parse, MatcherEntry, Segment, SegmentType, Route, \ compile, roundto8 and context: # Path: src/japronto/router/route.py # class RouteNotFoundException(Exception): # class Route: # class SegmentType(IntEnum): # def __init__(self, pattern, handler, methods): # def __repr__(self): # def describe(self): # def __eq__(self, other): # def parse(pattern): # def roundto8(v): # def padto8(data): # def compile(route): # def compile_all(routes): # EXACT = 0 # PLACEHOLDER = 1 which might include code, classes, or functions. Output only the next line.
assert decompiled.placeholder_cnt == route.placeholder_cnt
Predict the next line after this snippet: <|code_start|> @pytest.mark.parametrize('pattern,result', [ ('/', [('exact', '/')]), ('/{{a}}', [('exact', '/{a}')]), ('{a}', [('placeholder', 'a')]), ('a/{a}', [('exact', 'a/'), ('placeholder', 'a')]), ('{a}/a', [('placeholder', 'a'), ('exact', '/a')]), ('{a}/{{a}}', [('placeholder', 'a'), ('exact', '/{a}')]), ('{a}/{b}', [('placeholder', 'a'), ('exact', '/'), ('placeholder', 'b')]) ]) def test_parse(pattern, result): assert parse(pattern) == result @pytest.mark.parametrize('pattern,error', [ ('{a', 'Unbalanced'), ('{a}/{b', 'Unbalanced'), ('{a}a', 'followed by'), ('{a}/{a}', 'Duplicate') ]) <|code_end|> using the current file's imports: import asyncio import pytest from collections import namedtuple from .route import parse, MatcherEntry, Segment, SegmentType, Route, \ compile, roundto8 and any relevant context from other files: # Path: src/japronto/router/route.py # class RouteNotFoundException(Exception): # class Route: # class SegmentType(IntEnum): # def __init__(self, pattern, handler, methods): # def __repr__(self): # def describe(self): # def __eq__(self, other): # def parse(pattern): # def roundto8(v): # def padto8(data): # def compile(route): # def compile_all(routes): # EXACT = 0 # PLACEHOLDER = 1 . Output only the next line.
def test_parse_error(pattern, error):